update type generation script (#8712)

* chore: playground (#8648)

* initialize playground

* pnpm up

* tidy up git ignore

* remove fluff

* format

* rm readme

* fix jsconfig error

* add skip-worktree instructions

* reload hack

* simplify

* use rollup

* ughh

* add flag for SSR

* ...

* simplify further

* configure launch.json

* add debugger info to readme

* remove vm modules flag

* use replaceAll instead of replace

* tidy up

* fix: make it run

* add watch to launch config

* Generate type declarations with `dts-buddy` (#8702)

* use dts-buddy

* remove debug output

* remove existing type generation script

* fix package.json

* update gitignore

* bump dts-buddy

* remove unused action entry point

* add svelte/compiler and svelte/types/compiler/preprocess modules

* bump dts-buddy

* annoying

* changeset

* bump dts-buddy

* get rid of .d.ts files

* another one

* Update packages/svelte/package.json

Co-authored-by: gtmnayan <50981692+gtm-nayan@users.noreply.github.com>

---------

Co-authored-by: Rich Harris <git@rich-harris.dev>
Co-authored-by: gtmnayan <50981692+gtm-nayan@users.noreply.github.com>

* fix: export ComponentType (#8694)

* fix: export ComponentType

* ughh

* changeset

* fix: derived types (#8700)

* fix: derived store types

* changeset

* Version Packages (next) (#8709)

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>

* update type generation script

* remove unused stuff

* fix: changeset publish script isn't called release anymore (#8711)

* chore: remove prepare script (#8713)

* chore: fix release workflow (#8716)

* More readable, Fix $$_attributes

* Fix types (#8727)

* put comment in right place

* bump dts-buddy

---------

Co-authored-by: Rich Harris <git@rich-harris.dev>

* build types

* add svelte/compiler types

* remove prepare script

* fix

* typo

* squelch errors

* Add svelte and kit to twoslash's types field

* squelch more stuff

* Add errors to account for new types

* Remove deps

* formatting tweak

* fix linting, maybe

* the hell

* gah

* Fix types a bit

* bump dts-buddy

* pnpm generate in dev mode

* Cache again

* reduce index

* bump dts-buddy

* remove comment

---------

Co-authored-by: gtmnayan <50981692+gtm-nayan@users.noreply.github.com>
Co-authored-by: Rich Harris <git@rich-harris.dev>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Dominik G <dominik.goepel@gmx.de>
Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>
Co-authored-by: Puru Vijay <devpuruvj@gmail.com>
pull/8731/head
Rich Harris 1 year ago committed by GitHub
parent 744c596c89
commit b1cafc4573
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -124,7 +124,7 @@ declare global {
export {};
// @filename: index.ts
// @errors: 18046
// @errors: 18046 2769 7006
// ---cut---
import { derived } from 'svelte/store';

@ -58,7 +58,8 @@ Sometimes actions emit custom events and apply custom attributes to the element
<!--- file: App.svelte --->
<script>
/**
* @type {import('svelte/action').Action<HTMLDivElement, { prop: any }, { 'on:emit': (e: CustomEvent<string>) => void }>} */
* @type {import('svelte/action').Action<HTMLDivElement, { prop: any }, { 'on:emit': (e: CustomEvent<string>) => void }>}
*/
function foo(node, { prop }) {
// the node has been mounted in the DOM

@ -310,6 +310,7 @@ Multiple preprocessors can be used together. The output of the first becomes the
> In Svelte 3, all `markup` functions ran first, then all `script` and then all `style` preprocessors. This order was changed in Svelte 4.
```js
// @errors: 2322
// @filename: ambient.d.ts
declare global {
var source: string;
@ -398,3 +399,7 @@ The current version, as set in package.json.
import { VERSION } from 'svelte/compiler';
console.log(`running svelte version ${VERSION}`);
```
## Types
> TYPES: svelte/compiler

@ -5,7 +5,8 @@ title: 'Client-side component API'
## Creating a component
```ts
// @filename: ambiend.d.ts
// @errors: 2554
// @filename: ambient.d.ts
import { SvelteComponent, ComponentConstructorOptions } from 'svelte';
declare global {
@ -14,6 +15,7 @@ declare global {
}
// @filename: index.ts
// @errors: 2554
// ---cut---
const component = new Component(options);
```
@ -21,7 +23,8 @@ const component = new Component(options);
A client-side component — that is, a component compiled with `generate: 'dom'` (or the `generate` option left unspecified) is a JavaScript class.
```ts
// @filename: ambiend.d.ts
// @errors: 2554
// @filename: ambient.d.ts
import { SvelteComponent, ComponentConstructorOptions } from 'svelte';
declare module './App.svelte' {
@ -30,6 +33,7 @@ declare module './App.svelte' {
}
// @filename: index.ts
// @errors: 2554
// ---cut---
import App from './App.svelte';
@ -63,7 +67,7 @@ Whereas children of `target` are normally left alone, `hydrate: true` will cause
The existing DOM doesn't need to match the component — Svelte will 'repair' the DOM as it goes.
```ts
// @filename: ambiend.d.ts
// @filename: ambient.d.ts
import { SvelteComponent, ComponentConstructorOptions } from 'svelte';
declare module './App.svelte' {
@ -72,7 +76,7 @@ declare module './App.svelte' {
}
// @filename: index.ts
// @errors: 2322
// @errors: 2322 2554
// ---cut---
import App from './App.svelte';
@ -85,7 +89,7 @@ const app = new App({
## `$set`
```ts
// @filename: ambiend.d.ts
// @filename: ambient.d.ts
import { SvelteComponent, ComponentConstructorOptions } from 'svelte';
declare global {
@ -106,7 +110,7 @@ Programmatically sets props on an instance. `component.$set({ x: 1 })` is equiva
Calling this method schedules an update for the next microtask — the DOM is _not_ updated synchronously.
```ts
// @filename: ambiend.d.ts
// @filename: ambient.d.ts
import { SvelteComponent, ComponentConstructorOptions } from 'svelte';
declare global {
@ -124,7 +128,7 @@ component.$set({ answer: 42 });
## `$on`
```ts
// @filename: ambiend.d.ts
// @filename: ambient.d.ts
import { SvelteComponent, ComponentConstructorOptions } from 'svelte';
declare global {
@ -146,7 +150,7 @@ Causes the `callback` function to be called whenever the component dispatches an
A function is returned that will remove the event listener when called.
```ts
// @filename: ambiend.d.ts
// @filename: ambient.d.ts
import { SvelteComponent, ComponentConstructorOptions } from 'svelte';
declare global {
@ -168,7 +172,7 @@ off();
## `$destroy`
```js
// @filename: ambiend.d.ts
// @filename: ambient.d.ts
import { SvelteComponent, ComponentConstructorOptions } from 'svelte';
declare global {
@ -188,7 +192,7 @@ Removes a component from the DOM and triggers any `onDestroy` handlers.
## Component props
```js
// @filename: ambiend.d.ts
// @filename: ambient.d.ts
import { SvelteComponent, ComponentConstructorOptions } from 'svelte';
declare global {
@ -199,12 +203,13 @@ declare global {
export {}
// @filename: index.ts
// @errors: 2339
// ---cut---
component.prop;
```
```js
// @filename: ambiend.d.ts
// @filename: ambient.d.ts
import { SvelteComponent, ComponentConstructorOptions } from 'svelte';
declare global {
@ -216,6 +221,7 @@ declare global {
export {}
// @filename: index.ts
// @errors: 2339
// ---cut---
component.prop = value;
```
@ -225,7 +231,7 @@ If a component is compiled with `accessors: true`, each instance will have gette
By default, `accessors` is `false`, unless you're compiling as a custom element.
```js
// @filename: ambiend.d.ts
// @filename: ambient.d.ts
import { SvelteComponent, ComponentConstructorOptions } from 'svelte';
declare global {
@ -237,6 +243,7 @@ declare global {
export {}
// @filename: index.ts
// @errors: 2339
// ---cut---
console.log(component.count);
component.count += 1;

@ -7,7 +7,7 @@
"scripts": {
"test": "pnpm test -r --filter=./packages/*",
"build": "pnpm -r build",
"check": "pnpm -r check",
"check": "cd packages/svelte && pnpm build && cd ../../ && pnpm -r check",
"lint": "pnpm -r lint",
"format": "pnpm -r format",
"changeset:version": "changeset version && pnpm -r generate:version && git add --all",
@ -30,4 +30,4 @@
"prettier-plugin-svelte": "^2.10.0"
},
"packageManager": "pnpm@8.6.0"
}
}

@ -125,7 +125,7 @@
"@types/node": "^14.14.31",
"@typescript-eslint/eslint-plugin": "^5.58.0",
"agadoo": "^3.0.0",
"dts-buddy": "^0.1.2",
"dts-buddy": "^0.1.6",
"esbuild": "^0.17.19",
"happy-dom": "^9.18.3",
"jsdom": "^21.1.1",
@ -137,4 +137,4 @@
"util": "^0.12.5",
"vitest": "^0.31.1"
}
}
}

@ -12,15 +12,15 @@
* ```ts
* interface Attributes {
* newprop?: string;
* 'on:event': (e: CustomEvent<boolean>) => void;
* 'on:event': (e: CustomEvent<boolean>) => void;
* }
*
* export function myAction(node: HTMLElement, parameter: Parameter): ActionReturn<Parameter, Attributes> {
* // ...
* return {
* update: (updatedParameter) => {...},
* destroy: () => {...}
* };
* // ...
* return {
* update: (updatedParameter) => {...},
* destroy: () => {...}
* };
* }
* ```
*

@ -274,7 +274,7 @@ export function construct_svelte_component_dev(component, props) {
*
* Can be used to create strongly typed Svelte components.
*
* ### Example:
* #### Example:
*
* You have component library on npm called `component-library`, from which
* you export a component called `MyComponent`. For Svelte+TypeScript users,

@ -106,6 +106,7 @@ export function subscribe(store, ...callbacks) {
}
/**
* Get the current value from a store by subscribing and immediately unsubscribing.
* @template T
* @param {import('../store/public.js').Readable<T>} store
* @returns {T}

@ -189,10 +189,4 @@ export function readonly(store) {
};
}
/**
* Get the current value from a store by subscribing and immediately unsubscribing.
* @template T
* @param {import('./public.js').Readable<T>} store readable
* @returns {T}
*/
export { get_store_value as get };

@ -121,8 +121,8 @@ importers:
specifier: ^3.0.0
version: 3.0.0
dts-buddy:
specifier: ^0.1.2
version: 0.1.2
specifier: ^0.1.6
version: 0.1.6
esbuild:
specifier: ^0.17.19
version: 0.17.19
@ -229,12 +229,6 @@ importers:
prettier-plugin-svelte:
specifier: ^2.10.1
version: 2.10.1(prettier@2.8.8)(svelte@packages+svelte)
rollup:
specifier: ^3.23.0
version: 3.23.0
rollup-plugin-dts:
specifier: ^5.3.0
version: 5.3.0(rollup@3.23.0)(typescript@5.0.4)
sass:
specifier: ^1.62.1
version: 1.62.1
@ -265,9 +259,6 @@ importers:
tiny-glob:
specifier: ^0.2.9
version: 0.2.9
ts-morph:
specifier: ^18.0.0
version: 18.0.0
typescript:
specifier: ^5.0.4
version: 5.0.4
@ -276,7 +267,7 @@ importers:
version: 4.3.9(@types/node@20.2.5)(sass@1.62.1)
vite-imagetools:
specifier: ^5.0.4
version: 5.0.4(rollup@3.23.0)
version: 5.0.4
packages:
@ -1919,15 +1910,6 @@ packages:
engines: {node: '>= 10'}
dev: true
/@ts-morph/common@0.19.0:
resolution: {integrity: sha512-Unz/WHmd4pGax91rdIKWi51wnVUW11QttMEPpBiBgIewnc9UQIX7UDLxr5vRlqeByXCwhkF6VabSsI0raWcyAQ==}
dependencies:
fast-glob: 3.2.12
minimatch: 7.4.6
mkdirp: 2.1.6
path-browserify: 1.0.1
dev: true
/@types/aria-query@5.0.1:
resolution: {integrity: sha512-XTIieEY+gvJ39ChLcB4If5zHtPxt3Syj5rgZR+e1ctpmK8NjPf0zFqsz4JpLJT0xla9GFDKjy8Cpu331nrmE1Q==}
dev: true
@ -2714,10 +2696,6 @@ packages:
engines: {node: '>=0.8'}
dev: true
/code-block-writer@12.0.0:
resolution: {integrity: sha512-q4dMFMlXtKR3XNBHyMHt/3pwYNA69EDk00lloMOaaUMKPUXBw6lpXtbu3MMVG6/uOihGnRDOlkyqsONEUj60+w==}
dev: true
/code-red@1.0.0:
resolution: {integrity: sha512-x5fNWOBu7Ii38br3iVPuwQcDQM0f2h8ipvqw4qTLlOzYlrFQRz954qR0hPZ8asV5KG/igXNY8CRG6xtDUoKOJQ==}
dependencies:
@ -3128,8 +3106,8 @@ packages:
engines: {node: '>=12'}
dev: true
/dts-buddy@0.1.2:
resolution: {integrity: sha512-CLDbDXtcrNjuWLYljJuCL4l//mvDZzjtFkmr4yGyCAk58szuzmjzoWKG+7NBFWeeajOiISu/IG96QNMb0CPtdw==}
/dts-buddy@0.1.6:
resolution: {integrity: sha512-CjZGxch9dL1XjvsOsgW2IMXHoREcl+q/AXNe05QCYvq6nnC8SVZT5w6ll5Kafe4lQJif8eLag4j9xPZ44h5Vhw==}
hasBin: true
dependencies:
'@jridgewell/source-map': 0.3.3
@ -3140,6 +3118,7 @@ packages:
magic-string: 0.30.0
sade: 1.8.1
tiny-glob: 0.2.9
ts-api-utils: 0.0.46(typescript@5.0.4)
typescript: 5.0.4
dev: true
@ -4958,13 +4937,6 @@ packages:
brace-expansion: 2.0.1
dev: true
/minimatch@7.4.6:
resolution: {integrity: sha512-sBz8G/YjVniEz6lKPNpKxXwazJe4c19fEfV2GDMX6AjFz+MX9uDWIZW8XreVhkFW3fkIdTv/gxWr/Kks5FFAVw==}
engines: {node: '>=10'}
dependencies:
brace-expansion: 2.0.1
dev: true
/minimist-options@4.1.0:
resolution: {integrity: sha512-Q4r8ghd80yhO/0j1O3B2BjweX3fiHg9cdOwjJd2J76Q135c+NDxGCqdYKQ1SKBuFfgWbAUzBfvYjPUEeNgqN1A==}
engines: {node: '>= 6'}
@ -5361,10 +5333,6 @@ packages:
entities: 4.5.0
dev: true
/path-browserify@1.0.1:
resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
dev: true
/path-exists@4.0.0:
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
engines: {node: '>=8'}
@ -5828,20 +5796,6 @@ packages:
glob: 7.2.3
dev: true
/rollup-plugin-dts@5.3.0(rollup@3.23.0)(typescript@5.0.4):
resolution: {integrity: sha512-8FXp0ZkyZj1iU5klkIJYLjIq/YZSwBoERu33QBDxm/1yw5UU4txrEtcmMkrq+ZiKu3Q4qvPCNqc3ovX6rjqzbQ==}
engines: {node: '>=v14'}
peerDependencies:
rollup: ^3.0.0
typescript: ^4.1 || ^5.0
dependencies:
magic-string: 0.30.0
rollup: 3.23.0
typescript: 5.0.4
optionalDependencies:
'@babel/code-frame': 7.21.4
dev: true
/rollup-plugin-serve@2.0.2:
resolution: {integrity: sha512-ALqyTbPhlf7FZ5RzlbDvMYvbKuCHWginJkTo6dMsbgji/a78IbsXox+pC83HENdkTRz8OXrTj+aShp3+3ratpg==}
dependencies:
@ -6565,11 +6519,13 @@ packages:
engines: {node: '>=8'}
dev: true
/ts-morph@18.0.0:
resolution: {integrity: sha512-Kg5u0mk19PIIe4islUI/HWRvm9bC1lHejK4S0oh1zaZ77TMZAEmQC0sHQYiu2RgCQFZKXz1fMVi/7nOOeirznA==}
/ts-api-utils@0.0.46(typescript@5.0.4):
resolution: {integrity: sha512-YKJeSx39n0mMk+hrpyHKyTgxA3s7Pz/j1cXYR+t8HcwwZupzOR5xDGKnOEw3gmLaUeFUQt3FJD39AH9Ajn/mdA==}
engines: {node: '>=16.13.0'}
peerDependencies:
typescript: '>=4.2.0'
dependencies:
'@ts-morph/common': 0.19.0
code-block-writer: 12.0.0
typescript: 5.0.4
dev: true
/tsconfig-paths@3.14.2:
@ -6770,7 +6726,7 @@ packages:
spdx-expression-parse: 3.0.1
dev: true
/vite-imagetools@5.0.4(rollup@3.23.0):
/vite-imagetools@5.0.4:
resolution: {integrity: sha512-EIRstqWlmoQipsucFCioqCYpfp+rG5v8gpKDFvFJBxEKEAEBPnxW+swmE5dfoRQkwMKkYwmBWeXYsnMaDohUtg==}
engines: {node: '>=12.0.0'}
dependencies:

@ -4,14 +4,13 @@
"description": "Docs and examples for Svelte",
"type": "module",
"scripts": {
"prepare": "pnpm generate",
"dev": "node scripts/update.js && vite dev",
"dev": "node scripts/update.js && pnpm run generate && vite dev",
"build": "node scripts/update.js && pnpm run generate && vite build",
"generate": "node scripts/type-gen/index.js && node scripts/generate_examples.js",
"update": "node scripts/update.js --force=true",
"preview": "vite preview",
"start": "node build",
"check": "node scripts/update.js && svelte-kit sync && svelte-check",
"check": "node scripts/update.js && pnpm generate && svelte-kit sync && svelte-check",
"check:watch": "svelte-kit sync && svelte-check --watch",
"format": "pnpm run check:format -- --write",
"check:format": "prettier --check . --ignore-path .gitignore --plugin-search-dir=."
@ -43,8 +42,6 @@
"node-fetch": "^3.3.1",
"prettier": "^2.8.8",
"prettier-plugin-svelte": "^2.10.1",
"rollup": "^3.23.0",
"rollup-plugin-dts": "^5.3.0",
"sass": "^1.62.1",
"satori": "^0.9.1",
"satori-html": "^0.3.2",
@ -55,7 +52,6 @@
"svelte-check": "^3.4.3",
"svelte-preprocess": "^5.0.4",
"tiny-glob": "^0.2.9",
"ts-morph": "^18.0.0",
"typescript": "^5.0.4",
"vite": "^4.3.9",
"vite-imagetools": "^5.0.4"

@ -1,127 +0,0 @@
// @ts-check
import MagicString from 'magic-string';
import fs from 'node:fs';
import { rollup } from 'rollup';
import dts from 'rollup-plugin-dts';
import { VERSION } from 'svelte/compiler';
import { Project, SyntaxKind } from 'ts-morph';
import ts from 'typescript';
export async function get_bundled_types() {
const dtsSources = fs.readdirSync(new URL('./dts-sources', import.meta.url));
/** @type {Map<string, {code: string, ts_source_file: ts.SourceFile}>} */
const codes = new Map();
for (const file of dtsSources) {
const bundle = await rollup({
input: new URL(`./dts-sources/${file}`, import.meta.url).pathname,
plugins: [dts({ respectExternal: true })]
});
const moduleName = (file === 'index.d.ts' ? 'svelte' : `svelte/${file}`).replace('.d.ts', '');
const code = await bundle.generate({ format: 'esm' }).then(({ output }) => output[0].code);
const inlined_export_declaration_code = inlineExportDeclarations(code);
codes.set(moduleName, {
code: inlined_export_declaration_code,
ts_source_file: ts.createSourceFile(
'index.d.ts',
inlined_export_declaration_code,
ts.ScriptTarget.ESNext,
true,
ts.ScriptKind.TS
)
});
// !IMPORTANT: This is for debugging purposes only.
// !Do not remove until Svelte d.ts files are stable during v4/v5
write_to_node_modules('before', file, code);
write_to_node_modules('after', file, inlined_export_declaration_code);
}
return codes;
}
/**
* @param {string} str
*/
function inlineExportDeclarations(str) {
const project = new Project();
const source_file = project.createSourceFile('index.d.ts', str, { overwrite: true });
// There's only gonna be one because of the output of dts-plugin
const exportDeclaration = source_file.getExportDeclarations()[0];
const exportedSymbols = exportDeclaration
.getNamedExports()
.map((e) => e.getAliasNode()?.getText() ?? e.getNameNode().getText());
// console.log(exportedSymbols);
if (exportedSymbols.length === 0) return str;
const aliasedExportedSymbols = new Map();
const namedExports = exportDeclaration.getNamedExports();
namedExports.forEach((namedExport) => {
if (namedExport.getAliasNode()) {
const alias = namedExport.getAliasNode()?.getText();
const originalName = namedExport.getNameNode().getText();
aliasedExportedSymbols.set(alias, originalName);
}
});
for (const [exported, og] of aliasedExportedSymbols) {
source_file.forEachDescendant((node) => {
if (node.getKind() === ts.SyntaxKind.Identifier && node.getText() === og) {
node.replaceWithText(exported);
}
});
}
{
// Get the symbols and their declarations
const exportedSymbols = exportDeclaration
.getNamedExports()
.map((exp) => exp.getSymbolOrThrow());
/** @type {import('ts-morph').ExportSpecifier[]} */
// @ts-ignore
const exportedDeclarations = exportedSymbols.flatMap((symbol) => symbol.getDeclarations());
// Add 'export' keyword to the declarations
exportedDeclarations.forEach((declaration) => {
if (!declaration.getFirstDescendantByKind(SyntaxKind.ExportKeyword)) {
for (const target of declaration.getLocalTargetDeclarations()) {
if (target.isKind(SyntaxKind.VariableDeclaration)) {
target.getVariableStatement()?.setIsExported(true);
} else {
// @ts-ignore
target.setIsExported(true);
}
}
}
});
}
exportDeclaration.remove();
// In case it is export declare VERSION = '__VERSION__', replace it with svelte's real version
const stringified = source_file.getFullText().replace('__VERSION__', VERSION);
return stringified;
}
/**
* @param {'before' | 'after'} label
* @param {string} filename
* @param {string} code
*/
function write_to_node_modules(label, filename, code) {
const folder = new URL(`../../node_modules/.type-gen/${label}`, import.meta.url).pathname;
try {
fs.mkdirSync(folder, { recursive: true });
} catch {}
fs.writeFileSync(`${folder}/${filename}`, code);
}

@ -1 +0,0 @@
export type * from 'svelte/action';

@ -1 +0,0 @@
export type * from 'svelte/animate';

@ -1 +0,0 @@
export type * from 'svelte/compiler';

@ -1 +0,0 @@
export type * from 'svelte/easing';

@ -1 +0,0 @@
export type * from 'svelte';

@ -1 +0,0 @@
export type * from 'svelte/internal';

@ -1 +0,0 @@
export type * from 'svelte/motion';

@ -1 +0,0 @@
export type * from 'svelte/store';

@ -1 +0,0 @@
export type * from 'svelte/transition';

@ -1,8 +1,8 @@
// @ts-check
import fs from 'fs';
import fs from 'node:fs';
import path from 'node:path';
import prettier from 'prettier';
import ts from 'typescript';
import { get_bundled_types } from './compile-types.js';
/** @typedef {{
* name: string;
@ -106,7 +106,7 @@ function get_types(code, statements) {
const snippet = prettier
.format(snippet_unformatted, {
parser: 'typescript',
printWidth: 80,
printWidth: 60,
useTabs: true,
singleQuote: true,
trailingComma: 'none'
@ -143,7 +143,7 @@ function munge_type_element(member, depth = 1) {
// @ts-ignore
const doc = member.jsDoc?.[0];
if (/do not use!/i.test(doc?.comment)) return;
if (/private api/i.test(doc?.comment)) return;
/** @type {string[]} */
const children = [];
@ -151,7 +151,7 @@ function munge_type_element(member, depth = 1) {
const name = member.name?.escapedText;
let snippet = member.getText();
for (let i = 0; i < depth; i += 1) {
for (let i = -1; i < depth; i += 1) {
snippet = snippet.replace(/^\t/gm, '');
}
@ -219,137 +219,60 @@ function munge_type_element(member, depth = 1) {
};
}
const bundled_types = await get_bundled_types();
{
const module = bundled_types.get('svelte');
if (!module) throw new Error('Could not find svelte');
modules.push({
name: 'svelte',
comment: '',
...get_types(module.code, module.ts_source_file.statements)
});
}
{
const module = bundled_types.get('svelte/compiler');
if (!module) throw new Error('Could not find svelte/compiler');
modules.push({
name: 'svelte/compiler',
comment: '',
...get_types(module.code, module.ts_source_file.statements)
});
}
{
const module = bundled_types.get('svelte/action');
if (!module) throw new Error('Could not find svelte/action');
modules.push({
name: 'svelte/action',
comment: '',
...get_types(module.code, module.ts_source_file.statements)
});
}
{
const module = bundled_types.get('svelte/animate');
if (!module) throw new Error('Could not find svelte/animate');
modules.push({
name: 'svelte/animate',
comment: '',
...get_types(module.code, module.ts_source_file.statements)
});
}
{
const module = bundled_types.get('svelte/easing');
if (!module) throw new Error('Could not find svelte/easing');
modules.push({
name: 'svelte/easing',
comment: '',
...get_types(module.code, module.ts_source_file.statements)
});
/**
* Type declarations include fully qualified URLs so that they become links when
* you hover over names in an editor with TypeScript enabled. We need to remove
* the origin so that they become root-relative, so that they work in preview
* deployments and when developing locally
* @param {string} str
*/
function strip_origin(str) {
return str.replace(/https:\/\/svelte\.dev/g, '');
}
{
const module = bundled_types.get('svelte/motion');
/**
* @param {string} file
*/
function read_d_ts_file(file) {
const resolved = path.resolve('../../packages/svelte', file);
if (!module) throw new Error('Could not find svelte/motion');
// We can't use JSDoc comments inside JSDoc, so we would get ts(7031) errors if
// we didn't ignore this error specifically for `/// file:` code examples
const str = fs.readFileSync(resolved, 'utf-8');
modules.push({
name: 'svelte/motion',
comment: '',
...get_types(module.code, module.ts_source_file.statements)
return str.replace(/(\s*\*\s*)```js([\s\S]+?)```/g, (match, prefix, code) => {
return `${prefix}\`\`\`js${prefix}// @errors: 7031${code}\`\`\``;
});
}
{
const module = bundled_types.get('svelte/store');
if (!module) throw new Error('Could not find svelte/store');
const code = read_d_ts_file('types/index.d.ts');
const node = ts.createSourceFile('index.d.ts', code, ts.ScriptTarget.Latest, true);
modules.push({
name: 'svelte/store',
comment: '',
...get_types(module.code, module.ts_source_file.statements)
});
}
for (const statement of node.statements) {
if (ts.isModuleDeclaration(statement)) {
// @ts-ignore
const name = statement.name.text || statement.name.escapedText;
{
const module = bundled_types.get('svelte/transition');
if (name === '*.svelte' || name === 'svelte/types/compiler/preprocess') {
continue;
}
if (!module) throw new Error('Could not find svelte/transition');
// @ts-ignore
const comment = strip_origin(statement.jsDoc?.[0].comment ?? '');
modules.push({
name: 'svelte/transition',
comment: '',
...get_types(module.code, module.ts_source_file.statements)
});
modules.push({
name,
comment,
// @ts-ignore
...get_types(code, statement.body?.statements)
});
}
}
}
modules.sort((a, b) => (a.name < b.name ? -1 : 1));
// Fix the duplicate/messed up types
// !NOTE: This relies on mutation of `modules`
$: {
const module_with_SvelteComponent = modules.find((m) =>
m.types.filter((t) => t.name === 'SvelteComponent')
);
if (!module_with_SvelteComponent) break $;
const svelte_comp_part = module_with_SvelteComponent?.types.find(
(t) => t.name === 'SvelteComponent'
);
if (!svelte_comp_part) break $;
const internal_module = bundled_types.get('svelte/internal');
if (!internal_module) break $;
const internal_types = get_types(internal_module.code, internal_module.ts_source_file.statements);
const svelte_comp_dev_internal = internal_types.types.find(
(t) => t.name === 'SvelteComponentDev'
);
if (!svelte_comp_dev_internal) break $;
svelte_comp_part.children = svelte_comp_dev_internal.children;
svelte_comp_part.comment = svelte_comp_dev_internal.comment;
svelte_comp_part.snippet = svelte_comp_dev_internal.snippet;
}
// Remove $$_attributes from ActionReturn
$: {
const module_with_ActionReturn = modules.find((m) =>

@ -234,6 +234,8 @@ function generate_ts_from_js(markdown) {
return match.replace('js', 'original-js') + '\n```generated-ts\n' + ts + '\n```';
})
.replaceAll(/```svelte\n([\s\S]+?)\n```/g, (match, code) => {
METADATA_REGEX.lastIndex = 0;
if (!METADATA_REGEX.test(code)) {
// No named file -> assume that the code is not meant to be shown in two versions
return match;
@ -873,7 +875,8 @@ function syntax_highlight({ source, filename, language, highlighter, twoslashBan
defaultCompilerOptions: {
allowJs: true,
checkJs: true,
target: ts.ScriptTarget.ES2022
target: ts.ScriptTarget.ES2022,
types: ['svelte', '@sveltejs/kit']
}
});

@ -2,5 +2,6 @@
"$schema": "http://openapi.vercel.sh/vercel.json",
"github": {
"silent": true
}
}
},
"buildCommand": "cd ../../packages/svelte && pnpm prepublishOnly && cd ../../sites/svelte.dev && pnpm build"
}
Loading…
Cancel
Save