Merge branch 'version-4' into custom-elements-rework

pull/8457/head
Simon Holthausen 3 years ago
commit 9eb73e0370

@ -3,9 +3,11 @@
## Unreleased (4.0) ## Unreleased (4.0)
* **breaking** Minimum supported Node version is now Node 14 * **breaking** Minimum supported Node version is now Node 14
* **breaking** Minimum supported TypeScript version is now 5 (it will likely work with lower versions, but we make no guarantess about that) * **breaking** Minimum supported webpack version is now webpack 5
* **breaking** Minimum supported TypeScript version is now TypeScript 5 (it will likely work with lower versions, but we make no guarantees about that)
* **breaking** Stricter types for `createEventDispatcher` (see PR for migration instructions) ([#7224](https://github.com/sveltejs/svelte/pull/7224)) * **breaking** Stricter types for `createEventDispatcher` (see PR for migration instructions) ([#7224](https://github.com/sveltejs/svelte/pull/7224))
* **breaking** Stricter types for `Action` and `ActionReturn` (see PR for migration instructions) ([#7224](https://github.com/sveltejs/svelte/pull/7224)) * **breaking** Stricter types for `Action` and `ActionReturn` (see PR for migration instructions) ([#7224](https://github.com/sveltejs/svelte/pull/7224))
* **breaking** Stricter types for `onMount` - now throws a type error when returning a function asynchronously to catch potential mistakes around callback functions (see PR for migration instructions) ([#8136](https://github.com/sveltejs/svelte/pull/8136))
* **breaking** Overhaul and drastically improve creating custom elements with Svelte (see PR for list of changes and migration instructions) ([#8457](https://github.com/sveltejs/svelte/pull/8457)) * **breaking** Overhaul and drastically improve creating custom elements with Svelte (see PR for list of changes and migration instructions) ([#8457](https://github.com/sveltejs/svelte/pull/8457))
* Add `a11y no-noninteractive-element-interactions` rule ([#8391](https://github.com/sveltejs/svelte/pull/8391)) * Add `a11y no-noninteractive-element-interactions` rule ([#8391](https://github.com/sveltejs/svelte/pull/8391))
* Add `a11y-no-static-element-interactions`rule ([#8251](https://github.com/sveltejs/svelte/pull/8251)) * Add `a11y-no-static-element-interactions`rule ([#8251](https://github.com/sveltejs/svelte/pull/8251))

@ -14,136 +14,100 @@ const is_publish = !!process.env.PUBLISH;
const ts_plugin = is_publish const ts_plugin = is_publish
? typescript({ ? typescript({
typescript: require('typescript') typescript: require('typescript'),
}) })
: sucrase({ : sucrase({
transforms: ['typescript'] transforms: ['typescript'],
}); });
// The following external and path logic is necessary so that the bundled runtime pieces and the index file fs.writeFileSync(
// reference each other correctly instead of bundling their references to each other `./compiler.d.ts`,
`export { compile, parse, preprocess, walk, VERSION } from './types/compiler/index.js';`
);
/** const runtime_entrypoints = Object.fromEntries(
* Ensures that relative imports inside `src/runtime` like `./internal` and `../store` are externalized correctly fs
*/ .readdirSync('src/runtime', { withFileTypes: true })
const external = (id, parent_id) => { .filter((dirent) => dirent.isDirectory())
const parent_segments = parent_id.replace(/\\/g, '/').split('/'); .map((dirent) => [dirent.name, `src/runtime/${dirent.name}/index.ts`])
// TODO needs to be adjusted when we move to JS modules );
if (parent_segments[parent_segments.length - 3] === 'runtime') {
return /\.\.\/\w+$/.test(id);
} else {
return id === './internal' && parent_segments[parent_segments.length - 2] === 'runtime';
}
}
/**
* Transforms externalized import paths like `../store` into correct relative imports with correct index file extension import
*/
const replace_relative_svelte_imports = (id, ending) => {
id = id.replace(/\\/g, '/');
// TODO needs to be adjusted when we move to JS modules
return /src\/runtime\/\w+$/.test(id) && `../${id.split('/').pop()}/${ending}`;
}
/** /**
* Transforms externalized `./internal` import path into correct relative import with correct index file extension import * @type {import("rollup").RollupOptions[]}
*/ */
const replace_relative_internal_import = (id, ending) => {
id = id.replace(/\\/g, '/');
// TODO needs to be adjusted when we move to JS modules
return id.endsWith('src/runtime/internal') && `./internal/${ending}`;
}
fs.writeFileSync(`./compiler.d.ts`, `export { compile, parse, preprocess, walk, VERSION } from './types/compiler/index';`);
export default [ export default [
/* runtime */
{ {
input: `src/runtime/index.ts`, input: {
output: [ ...runtime_entrypoints,
{ index: 'src/runtime/index.ts',
file: `index.mjs`, ssr: 'src/runtime/ssr.ts'
format: 'esm', },
paths: id => replace_relative_internal_import(id, 'index.mjs') output: ['es', 'cjs'].map(
}, /** @returns {import('rollup').OutputOptions} */
{ (format) => {
file: `index.js`, const ext = format === 'es' ? 'mjs' : 'js';
format: 'cjs', return {
paths: id => replace_relative_internal_import(id, 'index.js') entryFileNames: (entry) => {
} if (entry.isEntry) {
], if (entry.name === 'index') return `index.${ext}`;
external, else if (entry.name === 'ssr') return `ssr.${ext}`;
plugins: [ts_plugin]
},
{ return `${entry.name}/index.${ext}`;
input: `src/runtime/ssr.ts`, }
output: [ },
{ chunkFileNames: `internal/[name]-[hash].${ext}`,
file: `ssr.mjs`, format,
format: 'esm', minifyInternalExports: false,
paths: id => replace_relative_internal_import(id, 'index.mjs') dir: '.',
}, };
{
file: `ssr.js`,
format: 'cjs',
paths: id => replace_relative_internal_import(id, 'index.js')
} }
], ),
external, plugins: [
plugins: [ts_plugin] replace({
}, preventAssignment: true,
values: {
...fs.readdirSync('src/runtime') __VERSION__: pkg.version,
.filter(dir => fs.statSync(`src/runtime/${dir}`).isDirectory())
.map(dir => ({
input: `src/runtime/${dir}/index.ts`,
output: [
{
file: `${dir}/index.mjs`,
format: 'esm',
paths: id => replace_relative_svelte_imports(id, 'index.mjs')
}, },
{ }),
file: `${dir}/index.js`, ts_plugin,
format: 'cjs', {
paths: id => replace_relative_svelte_imports(id, 'index.js') writeBundle(options, bundle) {
} if (options.format !== 'es') return;
],
external, for (const entry of Object.values(bundle)) {
plugins: [ const dir = entry.name;
replace({ if (!entry.isEntry || !runtime_entrypoints[dir]) continue;
__VERSION__: pkg.version
}),
ts_plugin,
{
writeBundle(_options, bundle) {
if (dir === 'internal') { if (dir === 'internal') {
const mod = bundle['index.mjs']; const mod = bundle[`internal/index.mjs`];
if (mod) { if (mod) {
fs.writeFileSync('src/compiler/compile/internal_exports.ts', `// This file is automatically generated\nexport default new Set(${JSON.stringify(mod.exports)});`); fs.writeFileSync(
'src/compiler/compile/internal_exports.ts',
`// This file is automatically generated\n` +
`export default new Set(${JSON.stringify(mod.exports)});`
);
} }
} }
fs.writeFileSync(`${dir}/package.json`, JSON.stringify({ fs.writeFileSync(
main: './index', `${dir}/index.d.ts`,
module: './index.mjs', `export * from '../types/runtime/${dir}/index.js';`
types: './index.d.ts' );
}, null, ' '));
fs.writeFileSync(`${dir}/index.d.ts`, `export * from '../types/runtime/${dir}/index';`);
} }
} }
] }
})), ]
},
/* compiler.js */ /* compiler.js */
{ {
input: 'src/compiler/index.ts', input: 'src/compiler/index.ts',
plugins: [ plugins: [
replace({ replace({
__VERSION__: pkg.version, preventAssignment: true,
'process.env.NODE_DEBUG': false // appears inside the util package values: {
__VERSION__: pkg.version,
'process.env.NODE_DEBUG': false // appears inside the util package
},
}), }),
{ {
resolveId(id) { resolveId(id) {
@ -152,7 +116,7 @@ export default [
if (id === 'util') { if (id === 'util') {
return require.resolve('./node_modules/util'); // just 'utils' would resolve this to the built-in module return require.resolve('./node_modules/util'); // just 'utils' would resolve this to the built-in module
} }
} },
}, },
resolve(), resolve(),
commonjs({ commonjs({
@ -177,6 +141,7 @@ export default [
], ],
external: is_publish external: is_publish
? [] ? []
: id => id === 'acorn' || id === 'magic-string' || id.startsWith('css-tree') : (id) =>
id === 'acorn' || id === 'magic-string' || id.startsWith('css-tree')
} }
]; ];

@ -4,4 +4,4 @@ export { default as preprocess } from './preprocess/index';
export { walk } from 'estree-walker'; export { walk } from 'estree-walker';
export type { CompileOptions, ModuleFormat, EnableSourcemap, CssHashGetter } from './interfaces'; export type { CompileOptions, ModuleFormat, EnableSourcemap, CssHashGetter } from './interfaces';
export const VERSION = '__VERSION__'; export const VERSION: string = '__VERSION__';

@ -108,12 +108,18 @@ export function update_keyed_each(old_blocks, dirty, get_key, dynamic, ctx, list
} }
export function validate_each_keys(ctx, list, get_context, get_key) { export function validate_each_keys(ctx, list, get_context, get_key) {
const keys = new Set(); const keys = new Map();
for (let i = 0; i < list.length; i++) { for (let i = 0; i < list.length; i++) {
const key = get_key(get_context(ctx, list, i)); const key = get_key(get_context(ctx, list, i));
if (keys.has(key)) { if (keys.has(key)) {
throw new Error('Cannot have duplicate keys in a keyed each'); let value = '';
try {
value = `with value '${String(key)}' `;
} catch (e) {
// can't stringify
}
throw new Error(`Cannot have duplicate keys in a keyed each: Keys at index ${keys.get(key)} and ${i} ${value}are duplicates`);
} }
keys.add(key); keys.set(key, i);
} }
} }

@ -27,11 +27,13 @@ export function beforeUpdate(fn: () => any) {
* It must be called during the component's initialisation (but doesn't need to live *inside* the component; * It must be called during the component's initialisation (but doesn't need to live *inside* the component;
* it can be called from an external module). * it can be called from an external module).
* *
* If a function is returned _synchronously_ from `onMount`, it will be called when the component is unmounted.
*
* `onMount` does not run inside a [server-side component](/docs#run-time-server-side-component-api). * `onMount` does not run inside a [server-side component](/docs#run-time-server-side-component-api).
* *
* https://svelte.dev/docs#run-time-svelte-onmount * https://svelte.dev/docs#run-time-svelte-onmount
*/ */
export function onMount(fn: () => any) { export function onMount<T>(fn: () => T extends Promise<() => any> ? "Returning a function asynchronously from onMount won't call that function on destroy" : T): void {
get_current_component().$$.on_mount.push(fn); get_current_component().$$.on_mount.push(fn);
} }

@ -12,8 +12,15 @@ export type Updater<T> = (value: T) => T;
/** Cleanup logic callback. */ /** Cleanup logic callback. */
type Invalidator<T> = (value?: T) => void; type Invalidator<T> = (value?: T) => void;
/** Start and stop notification callbacks. */ /**
export type StartStopNotifier<T> = (set: Subscriber<T>) => Unsubscriber | void; * Start and stop notification callbacks.
* This function is called when the first subscriber subscribes.
*
* @param {(value: T) => void} set Function that sets the value of the store.
* @returns {void | (() => void)} Optionally, a cleanup function that is called when the last remaining
* subscriber unsubscribes.
*/
export type StartStopNotifier<T> = (set: (value: T) => void) => void | (() => void);
/** Readable interface for subscribing. */ /** Readable interface for subscribing. */
export interface Readable<T> { export interface Readable<T> {
@ -48,7 +55,7 @@ const subscriber_queue = [];
/** /**
* Creates a `Readable` store that allows reading by subscription. * Creates a `Readable` store that allows reading by subscription.
* @param value initial value * @param value initial value
* @param {StartStopNotifier}start start and stop notifications for subscriptions * @param {StartStopNotifier} [start]
*/ */
export function readable<T>(value?: T, start?: StartStopNotifier<T>): Readable<T> { export function readable<T>(value?: T, start?: StartStopNotifier<T>): Readable<T> {
return { return {
@ -59,7 +66,7 @@ export function readable<T>(value?: T, start?: StartStopNotifier<T>): Readable<T
/** /**
* Create a `Writable` store that allows both updating and reading by subscription. * Create a `Writable` store that allows both updating and reading by subscription.
* @param {*=}value initial value * @param {*=}value initial value
* @param {StartStopNotifier=}start start and stop notifications for subscriptions * @param {StartStopNotifier=} start
*/ */
export function writable<T>(value?: T, start: StartStopNotifier<T> = noop): Writable<T> { export function writable<T>(value?: T, start: StartStopNotifier<T> = noop): Writable<T> {
let stop: Unsubscriber; let stop: Unsubscriber;

@ -75,9 +75,6 @@ describe('runtime (puppeteer)', () => {
function runTest(dir, hydrate, is_first_run) { function runTest(dir, hydrate, is_first_run) {
if (dir[0] === '.') return; if (dir[0] === '.') return;
// MEMO: puppeteer can not execute Chromium properly with Node8,10 on Linux at GitHub actions.
const { version } = process;
if ((version.startsWith('v8.') || version.startsWith('v10.')) && process.platform === 'linux') return;
const config = loadConfig(`${__dirname}/samples/${dir}/_config.js`); const config = loadConfig(`${__dirname}/samples/${dir}/_config.js`);
const solo = config.solo || /\.solo/.test(dir); const solo = config.solo || /\.solo/.test(dir);

@ -3,5 +3,5 @@ export default {
dev: true dev: true
}, },
error: 'Cannot have duplicate keys in a keyed each' error: 'Cannot have duplicate keys in a keyed each: Keys at index 0 and 3 with value \'1\' are duplicates'
}; };

@ -3,15 +3,15 @@ import type { Action, ActionReturn } from '$runtime/action';
// ---------------- Action // ---------------- Action
const href: Action<HTMLAnchorElement> = (node) => { const href: Action<HTMLAnchorElement> = (node) => {
node.href = ''; node.href = '';
// @ts-expect-error // @ts-expect-error
node.href = 1; node.href = 1;
}; };
href; href;
const required: Action<HTMLElement, boolean> = (node, param) => { const required: Action<HTMLElement, boolean> = (node, param) => {
node; node;
param; param;
}; };
required(null as any, true); required(null as any, true);
// @ts-expect-error (only in strict mode) boolean missing // @ts-expect-error (only in strict mode) boolean missing
@ -20,34 +20,34 @@ required(null as any);
required(null as any, 'string'); required(null as any, 'string');
const required1: Action<HTMLElement, boolean> = (node, param) => { const required1: Action<HTMLElement, boolean> = (node, param) => {
node; node;
param; param;
return { return {
update: (p) => p === true, update: (p) => p === true,
destroy: () => {} destroy: () => {}
}; };
}; };
required1; required1;
const required2: Action<HTMLElement, boolean> = (node) => { const required2: Action<HTMLElement, boolean> = (node) => {
node; node;
}; };
required2; required2;
const required3: Action<HTMLElement, boolean> = (node, param) => { const required3: Action<HTMLElement, boolean> = (node, param) => {
node; node;
param; param;
return { return {
// @ts-expect-error comparison always resolves to false // @ts-expect-error comparison always resolves to false
update: (p) => p === 'd', update: (p) => p === 'd',
destroy: () => {} destroy: () => {}
}; };
}; };
required3; required3;
const optional: Action<HTMLElement, boolean | undefined> = (node, param?) => { const optional: Action<HTMLElement, boolean | undefined> = (node, param?) => {
node; node;
param; param;
}; };
optional(null as any, true); optional(null as any, true);
optional(null as any); optional(null as any);
@ -55,39 +55,39 @@ optional(null as any);
optional(null as any, 'string'); optional(null as any, 'string');
const optional1: Action<HTMLElement, boolean | undefined> = (node, param?) => { const optional1: Action<HTMLElement, boolean | undefined> = (node, param?) => {
node; node;
param; param;
return { return {
update: (p) => p === true, update: (p) => p === true,
destroy: () => {} destroy: () => {}
}; };
}; };
optional1; optional1;
const optional2: Action<HTMLElement, boolean | undefined> = (node) => { const optional2: Action<HTMLElement, boolean | undefined> = (node) => {
node; node;
}; };
optional2; optional2;
const optional3: Action<HTMLElement, boolean | undefined> = (node, param) => { const optional3: Action<HTMLElement, boolean | undefined> = (node, param) => {
node; node;
param; param;
}; };
optional3; optional3;
const optional4: Action<HTMLElement, boolean | undefined> = (node, param?) => { const optional4: Action<HTMLElement, boolean | undefined> = (node, param?) => {
node; node;
param; param;
return { return {
// @ts-expect-error comparison always resolves to false // @ts-expect-error comparison always resolves to false
update: (p) => p === 'd', update: (p) => p === 'd',
destroy: () => {} destroy: () => {}
}; };
}; };
optional4; optional4;
const no: Action<HTMLElement, never> = (node) => { const no: Action<HTMLElement, never> = (node) => {
node; node;
}; };
// @ts-expect-error second param // @ts-expect-error second param
no(null as any, true); no(null as any, true);
@ -96,10 +96,10 @@ no(null as any);
no(null as any, 'string'); no(null as any, 'string');
const no1: Action<HTMLElement, never> = (node) => { const no1: Action<HTMLElement, never> = (node) => {
node; node;
return { return {
destroy: () => {} destroy: () => {}
}; };
}; };
no1; no1;
@ -113,32 +113,32 @@ no3;
// @ts-expect-error update method given // @ts-expect-error update method given
const no4: Action<HTMLElement, never> = (node) => { const no4: Action<HTMLElement, never> = (node) => {
return { return {
update: () => {}, update: () => {},
destroy: () => {} destroy: () => {}
}; };
}; };
no4; no4;
// ---------------- ActionReturn // ---------------- ActionReturn
const requiredReturn: ActionReturn<string> = { const requiredReturn: ActionReturn<string> = {
update: (p) => p.toString() update: (p) => p.toString()
}; };
requiredReturn; requiredReturn;
const optionalReturn: ActionReturn<boolean | undefined> = { const optionalReturn: ActionReturn<boolean | undefined> = {
update: (p) => { update: (p) => {
p === true; p === true;
// @ts-expect-error could be undefined // @ts-expect-error could be undefined
p.toString(); p.toString();
} }
}; };
optionalReturn; optionalReturn;
const invalidProperty: ActionReturn = { const invalidProperty: ActionReturn = {
// @ts-expect-error invalid property // @ts-expect-error invalid property
invalid: () => {} invalid: () => {}
}; };
invalidProperty; invalidProperty;

@ -1,10 +1,10 @@
import { createEventDispatcher } from '$runtime/internal/lifecycle'; import { createEventDispatcher } from '$runtime/internal/lifecycle';
const dispatch = createEventDispatcher<{ const dispatch = createEventDispatcher<{
loaded: never loaded: never
change: string change: string
valid: boolean valid: boolean
optional: number | null optional: number | null
}>(); }>();
// @ts-expect-error: dispatch invalid event // @ts-expect-error: dispatch invalid event

@ -0,0 +1,58 @@
import { onMount } from '$runtime/index';
// sync and no return
onMount(() => {
console.log('mounted');
});
// sync and return value
onMount(() => {
return 'done';
});
// sync and return sync
onMount(() => {
return () => {
return 'done';
};
});
// sync and return async
onMount(() => {
return async () => {
const res = await fetch('');
return res;
};
});
// async and no return
onMount(async () => {
await fetch('');
});
// async and return value
onMount(async () => {
const res = await fetch('');
return res;
});
// @ts-expect-error async and return sync
onMount(async () => {
return () => {
return 'done';
};
});
// @ts-expect-error async and return async
onMount(async () => {
return async () => {
const res = await fetch('');
return res;
};
});
// @ts-expect-error async and return any
onMount(async () => {
const a: any = null as any;
return a;
});
Loading…
Cancel
Save