From 62afd80c3a7bd6430be3c552acdb8baa75aac995 Mon Sep 17 00:00:00 2001 From: Dominik G Date: Thu, 26 Oct 2023 19:27:18 +0200 Subject: [PATCH] refactor(types): use dts-buddy to generate types with map (#751) * refactor(types): use dts-buddy to generate types with map, cleanup type definitions and tsconfig * chore: update generated types * fix: use .d.ts for type imports * fix: ignore .changesets/pre.json to prevent format check fails on main after release merge * fix: move types inside import condition to avoid masquerading as cjs warning * fix: types * bump dts-buddy * fix: regenerate types * fix: use correct type Options for plugin function arg * fix(types): reexport index.js from public.d.ts to ensure types and functions are properly exported through module declaration generated by dts-buddy; move dynamicCompileOptions to PluginOptions, rename SvelteOptions to SvelteConfig * fix: update lockfile * Update .changeset/metal-olives-wait.md Co-authored-by: Bjorn Lu * fix: update types --------- Co-authored-by: Rich Harris Co-authored-by: Bjorn Lu --- .changeset/gorgeous-hats-bathe.md | 5 + .changeset/many-cows-rescue.md | 5 + .changeset/metal-olives-wait.md | 6 + .changeset/small-pears-accept.md | 5 + .github/workflows/ci.yml | 3 + .github/workflows/release.yml | 5 +- .prettierrc.js | 6 +- package.json | 4 +- .../vite-plugin-svelte-inspector/package.json | 14 +- .../vite-plugin-svelte-inspector/src/index.js | 7 +- .../src/options.js | 4 +- .../src/{index.d.ts => public.d.ts} | 5 +- .../tsconfig.json | 10 +- .../types/index.d.ts | 74 +++++++ .../types/index.d.ts.map | 17 ++ packages/vite-plugin-svelte/package.json | 17 +- packages/vite-plugin-svelte/src/index.js | 5 +- packages/vite-plugin-svelte/src/preprocess.js | 13 +- .../src/{index.d.ts => public.d.ts} | 99 ++++----- .../vite-plugin-svelte/src/types/compile.d.ts | 27 +-- .../vite-plugin-svelte/src/types/log.d.ts | 2 +- .../vite-plugin-svelte/src/types/options.d.ts | 2 +- .../vite-plugin-svelte/src/utils/compile.js | 2 +- .../vite-plugin-svelte/src/utils/error.js | 2 +- .../vite-plugin-svelte/src/utils/esbuild.js | 2 +- packages/vite-plugin-svelte/src/utils/id.js | 4 +- .../src/utils/load-svelte-config.js | 8 +- .../vite-plugin-svelte/src/utils/options.js | 12 +- .../src/utils/preprocess.js | 10 +- packages/vite-plugin-svelte/tsconfig.json | 9 +- packages/vite-plugin-svelte/types/index.d.ts | 189 ++++++++++++++++++ .../vite-plugin-svelte/types/index.d.ts.map | 25 +++ pnpm-lock.yaml | 28 +++ 33 files changed, 475 insertions(+), 151 deletions(-) create mode 100644 .changeset/gorgeous-hats-bathe.md create mode 100644 .changeset/many-cows-rescue.md create mode 100644 .changeset/metal-olives-wait.md create mode 100644 .changeset/small-pears-accept.md rename packages/vite-plugin-svelte-inspector/src/{index.d.ts => public.d.ts} (95%) create mode 100644 packages/vite-plugin-svelte-inspector/types/index.d.ts create mode 100644 packages/vite-plugin-svelte-inspector/types/index.d.ts.map rename packages/vite-plugin-svelte/src/{index.d.ts => public.d.ts} (81%) create mode 100644 packages/vite-plugin-svelte/types/index.d.ts create mode 100644 packages/vite-plugin-svelte/types/index.d.ts.map diff --git a/.changeset/gorgeous-hats-bathe.md b/.changeset/gorgeous-hats-bathe.md new file mode 100644 index 000000000..49d304a90 --- /dev/null +++ b/.changeset/gorgeous-hats-bathe.md @@ -0,0 +1,5 @@ +--- +'@sveltejs/vite-plugin-svelte': patch +--- + +fix(types): use correct type Options for svelte function arg diff --git a/.changeset/many-cows-rescue.md b/.changeset/many-cows-rescue.md new file mode 100644 index 000000000..f85c85f80 --- /dev/null +++ b/.changeset/many-cows-rescue.md @@ -0,0 +1,5 @@ +--- +'@sveltejs/vite-plugin-svelte': major +--- + +breaking: remove package.json export diff --git a/.changeset/metal-olives-wait.md b/.changeset/metal-olives-wait.md new file mode 100644 index 000000000..bc9a88544 --- /dev/null +++ b/.changeset/metal-olives-wait.md @@ -0,0 +1,6 @@ +--- +'@sveltejs/vite-plugin-svelte-inspector': major +'@sveltejs/vite-plugin-svelte': major +--- + +breaking(types): emit types with dts-buddy to include type map diff --git a/.changeset/small-pears-accept.md b/.changeset/small-pears-accept.md new file mode 100644 index 000000000..2738bcbd7 --- /dev/null +++ b/.changeset/small-pears-accept.md @@ -0,0 +1,5 @@ +--- +'@sveltejs/vite-plugin-svelte': major +--- + +breaking(types): rename SvelteOptions to SvelteConfig diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 72c978aa0..700188239 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,6 +66,9 @@ jobs: - name: publint if: (${{ success() }} || ${{ failure() }}) run: pnpm check:publint + - name: generated types are up to date + if: (${{ success() }} || ${{ failure() }}) + run: pnpm generate:types && [ "`git status --porcelain=v1`" == "" ] test: timeout-minutes: 10 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ed3c78c5b..f17751cf8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -43,7 +43,10 @@ jobs: cache-dependency-path: '**/pnpm-lock.yaml' - name: install run: pnpm install --frozen-lockfile --prefer-offline --ignore-scripts - + - name: generated types are up to date + run: pnpm generate:types && [ "`git status --porcelain=v1`" == "" ] + - name: publint + run: pnpm check:publint - name: Creating .npmrc run: | cat << EOF > "$HOME/.npmrc" diff --git a/.prettierrc.js b/.prettierrc.js index 125787a48..38ab8c80f 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -16,9 +16,13 @@ export default { }, { files: [ - '**/vite.config.js.timestamp-*.mjs', '**/CHANGELOG.md', '.github/renovate.json5', + '**/types/index.d.ts', + '**/types/index.d.ts.map', + '**/pnpm-lock.yaml', + '.changeset/pre.json', + '**/vite.config.js.timestamp-*.mjs', 'packages/e2e-tests/dynamic-compile-options/src/components/A.svelte' ], options: { diff --git a/package.json b/package.json index 5958e1a6f..c34c8f964 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,8 @@ "fixup": "run-s lint format", "release": "pnpm changeset publish", "prepare": "husky install", - "playwright": "playwright-core" + "playwright": "playwright-core", + "generate:types": "pnpm --filter \"./packages/*\" --parallel generate:types" }, "devDependencies": { "@changesets/cli": "^2.26.2", @@ -28,6 +29,7 @@ "@typescript-eslint/eslint-plugin": "^6.8.0", "@typescript-eslint/parser": "^6.8.0", "cross-env": "^7.0.3", + "dts-buddy": "^0.3.0", "eslint": "^8.51.0", "eslint-config-prettier": "^9.0.0", "eslint-plugin-html": "^7.1.0", diff --git a/packages/vite-plugin-svelte-inspector/package.json b/packages/vite-plugin-svelte-inspector/package.json index a3365a8ab..2a5dcd806 100644 --- a/packages/vite-plugin-svelte-inspector/package.json +++ b/packages/vite-plugin-svelte-inspector/package.json @@ -4,19 +4,23 @@ "license": "MIT", "author": "dominikg", "files": [ - "src" + "src", + "types" ], "type": "module", - "types": "src/index.d.ts", + "types": "types/index.d.ts", "exports": { ".": { - "types": "./src/index.d.ts", - "import": "./src/index.js" + "import": { + "types": "./types/index.d.ts", + "default": "./src/index.js" + } } }, "scripts": { "check:publint": "publint --strict", - "check:types": "tsc --noEmit" + "check:types": "tsc --noEmit", + "generate:types": "dts-buddy -m \"@sveltejs/vite-plugin-svelte-inspector:src/public.d.ts\"" }, "engines": { "node": "^18.0.0 || >=20" diff --git a/packages/vite-plugin-svelte-inspector/src/index.js b/packages/vite-plugin-svelte-inspector/src/index.js index 0ed33e514..1f2e6ca4c 100644 --- a/packages/vite-plugin-svelte-inspector/src/index.js +++ b/packages/vite-plugin-svelte-inspector/src/index.js @@ -14,14 +14,17 @@ function getInspectorPath() { ); } -/** @type {import('.').svelteInspector} */ +/** + * @param {Partial} [options] + * @returns {import('vite').Plugin} + */ export function svelteInspector(options) { const inspectorPath = getInspectorPath(); debug(`svelte inspector path: ${inspectorPath}`); /** @type {import('vite').ResolvedConfig} */ let viteConfig; - /** @type {import('.').Options} */ + /** @type {import('./public.d.ts').Options} */ let inspectorOptions; let disabled = false; diff --git a/packages/vite-plugin-svelte-inspector/src/options.js b/packages/vite-plugin-svelte-inspector/src/options.js index 9283df9b0..d53561520 100644 --- a/packages/vite-plugin-svelte-inspector/src/options.js +++ b/packages/vite-plugin-svelte-inspector/src/options.js @@ -1,7 +1,7 @@ import { loadEnv } from 'vite'; import { debug } from './debug.js'; -/** @type {import('.').Options} */ +/** @type {import('./public.d.ts').Options} */ export const defaultInspectorOptions = { toggleKeyCombo: process.platform === 'darwin' ? 'meta-shift' : 'control-shift', navKeys: { parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' }, @@ -14,7 +14,7 @@ export const defaultInspectorOptions = { /** * @param {import('vite').ResolvedConfig} config - * @returns {Partial | boolean | void} + * @returns {Partial | boolean | void} */ export function parseEnvironmentOptions(config) { const env = loadEnv(config.mode, config.envDir ?? process.cwd(), 'SVELTE_INSPECTOR'); diff --git a/packages/vite-plugin-svelte-inspector/src/index.d.ts b/packages/vite-plugin-svelte-inspector/src/public.d.ts similarity index 95% rename from packages/vite-plugin-svelte-inspector/src/index.d.ts rename to packages/vite-plugin-svelte-inspector/src/public.d.ts index b5c2ce28b..538d7cb42 100644 --- a/packages/vite-plugin-svelte-inspector/src/index.d.ts +++ b/packages/vite-plugin-svelte-inspector/src/public.d.ts @@ -1,5 +1,3 @@ -import type { Plugin } from 'vite'; - export interface Options { /** * define a key combo to toggle inspector, @@ -63,6 +61,7 @@ export interface Options { /** * internal options that are automatically set, not to be set or used by users + * @internal */ __internal?: { // vite base url @@ -70,4 +69,4 @@ export interface Options { }; } -export declare function svelteInspector(options?: Options): Plugin; +export * from './index.js'; diff --git a/packages/vite-plugin-svelte-inspector/tsconfig.json b/packages/vite-plugin-svelte-inspector/tsconfig.json index 53b8c64ae..90b557e70 100644 --- a/packages/vite-plugin-svelte-inspector/tsconfig.json +++ b/packages/vite-plugin-svelte-inspector/tsconfig.json @@ -1,21 +1,17 @@ { "include": ["src"], - "exclude": ["**/*.spec.ts"], "compilerOptions": { "noEmit": true, "target": "ES2020", - "module": "ES2020", + "module": "ES2022", "moduleResolution": "node", "strict": true, - "declaration": true, - "sourceMap": true, "noUnusedLocals": true, - "esModuleInterop": true, "baseUrl": ".", - "resolveJsonModule": true, // see https://devblogs.microsoft.com/typescript/announcing-typescript-4-4-beta/#use-unknown-catch-variables "useUnknownInCatchVariables": false, "allowJs": true, - "checkJs": true + "checkJs": true, + "allowSyntheticDefaultImports": true } } diff --git a/packages/vite-plugin-svelte-inspector/types/index.d.ts b/packages/vite-plugin-svelte-inspector/types/index.d.ts new file mode 100644 index 000000000..fbba16c60 --- /dev/null +++ b/packages/vite-plugin-svelte-inspector/types/index.d.ts @@ -0,0 +1,74 @@ +declare module '@sveltejs/vite-plugin-svelte-inspector' { + export interface Options { + /** + * define a key combo to toggle inspector, + * @default 'meta-shift' on mac, 'control-shift' on other os + * + * any number of modifiers `control` `shift` `alt` `meta` followed by zero or one regular key, separated by - + * examples: control-shift, control-o, control-alt-s meta-x control-meta + * Some keys have native behavior (e.g. alt-s opens history menu on firefox). + * To avoid conflicts or accidentally typing into inputs, modifier only combinations are recommended. + */ + toggleKeyCombo?: string; + + /** + * define keys to select elements with via keyboard + * @default {parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' } + * + * improves accessibility and also helps when you want to select elements that do not have a hoverable surface area + * due to tight wrapping + * + * A note for users of screen-readers: + * If you are using arrow keys to navigate the page itself, change the navKeys to avoid conflicts. + * e.g. navKeys: {parent: 'w', prev: 'a', child: 's', next: 'd'} + * + * + * parent: select closest parent + * child: select first child (or grandchild) + * next: next sibling (or parent if no next sibling exists) + * prev: previous sibling (or parent if no prev sibling exists) + */ + navKeys?: { parent: string; child: string; next: string; prev: string }; + + /** + * define key to open the editor for the currently selected dom node + * + * @default 'Enter' + */ + openKey?: string; + + /** + * inspector is automatically disabled when releasing toggleKeyCombo after holding it for a longpress + * @default true + */ + holdMode?: boolean; + + /** + * when to show the toggle button + * @default 'active' + */ + showToggleButton?: 'always' | 'active' | 'never'; + + /** + * where to display the toggle button + * @default top-right + */ + toggleButtonPos?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'; + + /** + * inject custom styles when inspector is active + */ + customStyles?: boolean; + + /** + * internal options that are automatically set, not to be set or used by users + * */ + __internal?: { + // vite base url + base: string; + }; + } + export function svelteInspector(options?: Partial | undefined): import('vite').Plugin; +} + +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/vite-plugin-svelte-inspector/types/index.d.ts.map b/packages/vite-plugin-svelte-inspector/types/index.d.ts.map new file mode 100644 index 000000000..15d752e59 --- /dev/null +++ b/packages/vite-plugin-svelte-inspector/types/index.d.ts.map @@ -0,0 +1,17 @@ +{ + "version": 3, + "file": "index.d.ts", + "names": [ + "Options", + "svelteInspector" + ], + "sources": [ + "../src/public.d.ts", + "../src/index.js" + ], + "sourcesContent": [ + null, + null + ], + "mappings": ";kBAAiBA,OAAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBCoBRC,eAAeA" +} \ No newline at end of file diff --git a/packages/vite-plugin-svelte/package.json b/packages/vite-plugin-svelte/package.json index 89494b618..e93ec9994 100644 --- a/packages/vite-plugin-svelte/package.json +++ b/packages/vite-plugin-svelte/package.json @@ -4,20 +4,23 @@ "license": "MIT", "author": "dominikg", "files": [ - "src" + "src", + "types" ], "type": "module", - "types": "src/index.d.ts", + "types": "types/index.d.ts", "exports": { ".": { - "types": "./src/index.d.ts", - "import": "./src/index.js" - }, - "./package.json": "./package.json" + "import": { + "types": "./types/index.d.ts", + "default": "./src/index.js" + } + } }, "scripts": { "check:publint": "publint --strict", - "check:types": "tsc --noEmit" + "check:types": "tsc --noEmit", + "generate:types": "dts-buddy -m \"@sveltejs/vite-plugin-svelte:src/public.d.ts\"" }, "engines": { "node": "^18.0.0 || >=20" diff --git a/packages/vite-plugin-svelte/src/index.js b/packages/vite-plugin-svelte/src/index.js index 8a6cd80e5..7b23ad7bf 100644 --- a/packages/vite-plugin-svelte/src/index.js +++ b/packages/vite-plugin-svelte/src/index.js @@ -20,7 +20,10 @@ import { saveSvelteMetadata } from './utils/optimizer.js'; import { VitePluginSvelteCache } from './utils/vite-plugin-svelte-cache.js'; import { loadRaw } from './utils/load-raw.js'; -/** @type {import('./index.d.ts').svelte} */ +/** + * @param {Partial} [inlineOptions] + * @returns {import('vite').Plugin[]} + */ export function svelte(inlineOptions) { if (process.env.DEBUG != null) { log.setLevel('debug'); diff --git a/packages/vite-plugin-svelte/src/preprocess.js b/packages/vite-plugin-svelte/src/preprocess.js index b7b32cd49..863ccd530 100644 --- a/packages/vite-plugin-svelte/src/preprocess.js +++ b/packages/vite-plugin-svelte/src/preprocess.js @@ -9,9 +9,12 @@ const supportedScriptLangs = ['ts']; export const lang_sep = '.vite-preprocess'; -/** @type {import('./index.d.ts').vitePreprocess} */ +/** + * @param {import('./public.d.ts').VitePreprocessOptions} opts + * @returns {import('svelte/compiler').PreprocessorGroup} + */ export function vitePreprocess(opts) { - /** @type {import('svelte/types/compiler/preprocess').PreprocessorGroup} */ + /** @type {import('svelte/compiler').PreprocessorGroup} */ const preprocessor = { name: 'vite-preprocess' }; if (opts?.script !== false) { preprocessor.script = viteScript().script; @@ -24,7 +27,7 @@ export function vitePreprocess(opts) { } /** - * @returns {{ script: import('svelte/types/compiler/preprocess').Preprocessor }} + * @returns {{ script: import('svelte/compiler').Preprocessor }} */ function viteScript() { return { @@ -55,12 +58,12 @@ function viteScript() { /** * @param {import('vite').ResolvedConfig | import('vite').InlineConfig} config - * @returns {{ style: import('svelte/types/compiler/preprocess').Preprocessor }} + * @returns {{ style: import('svelte/compiler').Preprocessor }} */ function viteStyle(config = {}) { /** @type {CssTransform} */ let transform; - /** @type {import('svelte/types/compiler/preprocess').Preprocessor} */ + /** @type {import('svelte/compiler').Preprocessor} */ const style = async ({ attributes, content, filename = '' }) => { const ext = attributes.lang ? `.${attributes.lang}` : '.css'; if (attributes.lang && !isCSSRequest(ext)) return; diff --git a/packages/vite-plugin-svelte/src/index.d.ts b/packages/vite-plugin-svelte/src/public.d.ts similarity index 81% rename from packages/vite-plugin-svelte/src/index.d.ts rename to packages/vite-plugin-svelte/src/public.d.ts index 75d6bf369..672c697a2 100644 --- a/packages/vite-plugin-svelte/src/index.d.ts +++ b/packages/vite-plugin-svelte/src/public.d.ts @@ -1,9 +1,10 @@ -import type { InlineConfig, ResolvedConfig, UserConfig, Plugin } from 'vite'; -import type { CompileOptions, Warning } from 'svelte/types/compiler/interfaces'; -import type { PreprocessorGroup } from 'svelte/types/compiler/preprocess'; +import type { InlineConfig, ResolvedConfig } from 'vite'; +import type { CompileOptions } from 'svelte/compiler'; +import type { Warning } from 'svelte/types/compiler/interfaces'; +import type { PreprocessorGroup } from 'svelte/compiler'; import type { Options as InspectorOptions } from '@sveltejs/vite-plugin-svelte-inspector'; -type Options = Omit & PluginOptionsInline; +export type Options = Omit & PluginOptionsInline; interface PluginOptionsInline extends PluginOptions { /** @@ -94,13 +95,39 @@ interface PluginOptions { * @default unset for dev, always false for build */ inspector?: InspectorOptions | boolean; + + /** + * A function to update `compilerOptions` before compilation + * + * `data.filename` - The file to be compiled + * `data.code` - The preprocessed Svelte code + * `data.compileOptions` - The current compiler options + * + * To change part of the compiler options, return an object with the changes you need. + * + * @example + * ``` + * ({ filename, compileOptions }) => { + * // Dynamically set hydration per Svelte file + * if (compileWithHydratable(filename) && !compileOptions.hydratable) { + * return { hydratable: true }; + * } + * } + * ``` + */ + dynamicCompileOptions?: (data: { + filename: string; + code: string; + compileOptions: Partial; + }) => Promise | void> | Partial | void; + /** * These options are considered experimental and breaking changes to them can occur in any release */ experimental?: ExperimentalOptions; } -interface SvelteOptions { +export interface SvelteConfig { /** * A list of file extensions to be compiled by Svelte * @@ -122,31 +149,6 @@ interface SvelteOptions { */ compilerOptions?: Omit; - /** - * A function to update `compilerOptions` before compilation - * - * `data.filename` - The file to be compiled - * `data.code` - The preprocessed Svelte code - * `data.compileOptions` - The current compiler options - * - * To change part of the compiler options, return an object with the changes you need. - * - * @example - * ``` - * ({ filename, compileOptions }) => { - * // Dynamically set hydration per Svelte file - * if (compileWithHydratable(filename) && !compileOptions.hydratable) { - * return { hydratable: true }; - * } - * } - * ``` - */ - dynamicCompileOptions?: (data: { - filename: string; - code: string; - compileOptions: Partial; - }) => Promise | void> | Partial | void; - /** * Handles warning emitted from the Svelte compiler */ @@ -174,44 +176,11 @@ interface ExperimentalOptions { disableSvelteResolveWarnings?: boolean; } -type ModuleFormat = NonNullable<'esm'>; -type CssHashGetter = NonNullable; type Arrayable = T | T[]; -interface VitePreprocessOptions { +export interface VitePreprocessOptions { script?: boolean; style?: boolean | InlineConfig | ResolvedConfig; } -declare function vitePreprocess(opts?: VitePreprocessOptions): PreprocessorGroup; - -declare function loadSvelteConfig( - viteConfig?: UserConfig, - inlineOptions?: Partial -): Promise | undefined>; - -declare function svelte(inlineOptions?: Partial): Plugin[]; - -export { - Arrayable, - CssHashGetter, - ModuleFormat, - Options, - PluginOptions, - SvelteOptions, - loadSvelteConfig, - svelte, - VitePreprocessOptions, - vitePreprocess -}; - -// reexported types - -export { CompileOptions, Warning } from 'svelte/types/compiler/interfaces'; - -export { - MarkupPreprocessor, - Preprocessor, - PreprocessorGroup, - Processed -} from 'svelte/types/compiler/preprocess'; +export * from './index.js'; diff --git a/packages/vite-plugin-svelte/src/types/compile.d.ts b/packages/vite-plugin-svelte/src/types/compile.d.ts index 64d3e04e8..d6ba48e0f 100644 --- a/packages/vite-plugin-svelte/src/types/compile.d.ts +++ b/packages/vite-plugin-svelte/src/types/compile.d.ts @@ -1,4 +1,4 @@ -import type { Processed } from 'svelte/types/compiler/preprocess'; +import type { Processed, CompileResult } from 'svelte/compiler'; import type { SvelteRequest } from './id.d.ts'; import type { ResolvedOptions } from './options.d.ts'; @@ -14,34 +14,11 @@ export interface Code { dependencies?: any[]; } -export interface Compiled { - js: Code; - css: Code; - ast: any; // TODO type - warnings: any[]; // TODO type - vars: Array<{ - name: string; - export_name: string; - injected: boolean; - module: boolean; - mutated: boolean; - reassigned: boolean; - referenced: boolean; - writable: boolean; - referenced_from_script: boolean; - }>; - stats: { - timings: { - total: number; - }; - }; -} - export interface CompileData { filename: string; normalizedFilename: string; lang: string; - compiled: Compiled; + compiled: CompileResult; ssr: boolean | undefined; dependencies: string[]; preprocessed: Processed; diff --git a/packages/vite-plugin-svelte/src/types/log.d.ts b/packages/vite-plugin-svelte/src/types/log.d.ts index 9c1153c0b..ee712fb69 100644 --- a/packages/vite-plugin-svelte/src/types/log.d.ts +++ b/packages/vite-plugin-svelte/src/types/log.d.ts @@ -1,4 +1,4 @@ -import type { Warning } from '../index.d.ts'; +import type { Warning } from 'svelte/types/compiler/interfaces'; export interface LogFn extends SimpleLogFn { (message: string, payload?: any, namespace?: string): void; diff --git a/packages/vite-plugin-svelte/src/types/options.d.ts b/packages/vite-plugin-svelte/src/types/options.d.ts index 3b52dae5d..ec32b9eb6 100644 --- a/packages/vite-plugin-svelte/src/types/options.d.ts +++ b/packages/vite-plugin-svelte/src/types/options.d.ts @@ -1,7 +1,7 @@ import type { CompileOptions } from 'svelte/types/compiler/interfaces'; import type { ViteDevServer } from 'vite'; import { VitePluginSvelteStats } from '../utils/vite-plugin-svelte-stats.js'; -import type { Options } from '../index.d.ts'; +import type { Options } from '../public.d.ts'; export interface PreResolvedOptions extends Options { // these options are non-nullable after resolve diff --git a/packages/vite-plugin-svelte/src/utils/compile.js b/packages/vite-plugin-svelte/src/utils/compile.js index 8d30b4268..d43bc90e3 100644 --- a/packages/vite-plugin-svelte/src/utils/compile.js +++ b/packages/vite-plugin-svelte/src/utils/compile.js @@ -54,7 +54,7 @@ export const _createCompileSvelte = (makeHot) => { // also they for hmr updates too } } - /** @type {import('../index.d.ts').CompileOptions} */ + /** @type {import('svelte/compiler').CompileOptions} */ const compileOptions = { ...options.compilerOptions, filename, diff --git a/packages/vite-plugin-svelte/src/utils/error.js b/packages/vite-plugin-svelte/src/utils/error.js index c7f33a6e9..b7ca277fb 100644 --- a/packages/vite-plugin-svelte/src/utils/error.js +++ b/packages/vite-plugin-svelte/src/utils/error.js @@ -104,7 +104,7 @@ function formatFrameForVite(frame) { /** * @param {import('svelte/types/compiler/interfaces').Warning & Error} err a svelte compiler error, which is a mix of Warning and an error * @param {string} originalCode - * @param {import('../index.js').Arrayable} [preprocessors] + * @param {import('../public.d.ts').Options['preprocess']} [preprocessors] */ export function enhanceCompileError(err, originalCode, preprocessors) { preprocessors = arraify(preprocessors ?? []); diff --git a/packages/vite-plugin-svelte/src/utils/esbuild.js b/packages/vite-plugin-svelte/src/utils/esbuild.js index cb8c353a5..0b3a19af5 100644 --- a/packages/vite-plugin-svelte/src/utils/esbuild.js +++ b/packages/vite-plugin-svelte/src/utils/esbuild.js @@ -59,7 +59,7 @@ async function compileSvelte(options, { filename, code }, statsCollection) { // TODO ideally we'd be able to externalize prebundled styles too, but for now always put them in the js css = 'injected'; } - /** @type {import('../index.d.ts').CompileOptions} */ + /** @type {import('svelte/compiler').CompileOptions} */ const compileOptions = { ...options.compilerOptions, css, diff --git a/packages/vite-plugin-svelte/src/utils/id.js b/packages/vite-plugin-svelte/src/utils/id.js index ee7a719d3..8c688db1f 100644 --- a/packages/vite-plugin-svelte/src/utils/id.js +++ b/packages/vite-plugin-svelte/src/utils/id.js @@ -159,8 +159,8 @@ function stripRoot(normalizedFilename, normalizedRoot) { } /** - * @param {import('../index.d.ts').Arrayable | undefined} include - * @param {import('../index.d.ts').Arrayable | undefined} exclude + * @param {import('../public.d.ts').Options['include'] | undefined} include + * @param {import('../public.d.ts').Options['exclude'] | undefined} exclude * @param {string[]} extensions * @returns {(filename: string) => boolean} */ diff --git a/packages/vite-plugin-svelte/src/utils/load-svelte-config.js b/packages/vite-plugin-svelte/src/utils/load-svelte-config.js index 0e153fb0e..cb8a41b23 100644 --- a/packages/vite-plugin-svelte/src/utils/load-svelte-config.js +++ b/packages/vite-plugin-svelte/src/utils/load-svelte-config.js @@ -24,7 +24,11 @@ async function dynamicImportDefault(filePath, timestamp) { return await import(filePath + '?t=' + timestamp).then((m) => m.default); } -/** @type {import('../index.d.ts').loadSvelteConfig} */ +/** + * @param {import('vite').UserConfig} viteConfig + * @param {Partial} inlineOptions + * @returns {Promise | undefined>} + */ export async function loadSvelteConfig(viteConfig, inlineOptions) { if (inlineOptions?.configFile === false) { return; @@ -86,7 +90,7 @@ export async function loadSvelteConfig(viteConfig, inlineOptions) { /** * @param {import('vite').UserConfig | undefined} viteConfig - * @param {Partial | undefined} inlineOptions + * @param {Partial | undefined} inlineOptions * @returns {string | undefined} */ function findConfigToLoad(viteConfig, inlineOptions) { diff --git a/packages/vite-plugin-svelte/src/utils/options.js b/packages/vite-plugin-svelte/src/utils/options.js index 844cfaac7..396ecfe64 100644 --- a/packages/vite-plugin-svelte/src/utils/options.js +++ b/packages/vite-plugin-svelte/src/utils/options.js @@ -45,7 +45,7 @@ const knownRootOptions = new Set(['extensions', 'compilerOptions', 'preprocess', const allowedInlineOptions = new Set(['configFile', ...allowedPluginOptions, ...knownRootOptions]); /** - * @param {Partial} [inlineOptions] + * @param {Partial} [inlineOptions] */ export function validateInlineOptions(inlineOptions) { const invalidKeys = Object.keys(inlineOptions || {}).filter( @@ -57,8 +57,8 @@ export function validateInlineOptions(inlineOptions) { } /** - * @param {Partial} [config] - * @returns {Partial | undefined} + * @param {Partial} [config] + * @returns {Partial | undefined} */ function convertPluginOptions(config) { if (!config) { @@ -108,7 +108,7 @@ function convertPluginOptions(config) { delete pluginOptions[unkownOption]; }); } - /** @type {import('../index.d.ts').Options} */ + /** @type {import('../public.d.ts').Options} */ const result = { ...config, ...pluginOptions @@ -121,7 +121,7 @@ function convertPluginOptions(config) { /** * used in config phase, merges the default options, svelte config, and inline options - * @param {Partial | undefined} inlineOptions + * @param {Partial | undefined} inlineOptions * @param {import('vite').UserConfig} viteUserConfig * @param {import('vite').ConfigEnv} viteEnv * @returns {Promise} @@ -191,7 +191,7 @@ function mergeConfigs(...configs) { */ export function resolveOptions(preResolveOptions, viteConfig, cache) { const css = preResolveOptions.emitCss ? 'external' : 'injected'; - /** @type {Partial} */ + /** @type {Partial} */ const defaultOptions = { hot: viteConfig.isProduction ? false diff --git a/packages/vite-plugin-svelte/src/utils/preprocess.js b/packages/vite-plugin-svelte/src/utils/preprocess.js index 675607460..169bedcdc 100644 --- a/packages/vite-plugin-svelte/src/utils/preprocess.js +++ b/packages/vite-plugin-svelte/src/utils/preprocess.js @@ -9,7 +9,7 @@ import { normalizePath } from 'vite'; * * only used during dev with enabled css hmr * - * @returns {import('svelte/types/compiler/preprocess').PreprocessorGroup} + * @returns {import('svelte/compiler').PreprocessorGroup} */ export function createInjectScopeEverythingRulePreprocessorGroup() { return { @@ -32,14 +32,14 @@ export function createInjectScopeEverythingRulePreprocessorGroup() { * @param {import('../types/options.d.ts').ResolvedOptions} options * @param {import('vite').ResolvedConfig} config * @returns {{ - * prependPreprocessors: import('svelte/types/compiler/preprocess').PreprocessorGroup[], - * appendPreprocessors: import('svelte/types/compiler/preprocess').PreprocessorGroup[] + * prependPreprocessors: import('svelte/compiler').PreprocessorGroup[], + * appendPreprocessors: import('svelte/compiler').PreprocessorGroup[] * }} */ function buildExtraPreprocessors(options, config) { - /** @type {import('svelte/types/compiler/preprocess').PreprocessorGroup[]} */ + /** @type {import('svelte/compiler').PreprocessorGroup[]} */ const prependPreprocessors = []; - /** @type {import('svelte/types/compiler/preprocess').PreprocessorGroup[]} */ + /** @type {import('svelte/compiler').PreprocessorGroup[]} */ const appendPreprocessors = []; // @ts-ignore diff --git a/packages/vite-plugin-svelte/tsconfig.json b/packages/vite-plugin-svelte/tsconfig.json index 53b8c64ae..753c44ebb 100644 --- a/packages/vite-plugin-svelte/tsconfig.json +++ b/packages/vite-plugin-svelte/tsconfig.json @@ -1,21 +1,18 @@ { "include": ["src"], - "exclude": ["**/*.spec.ts"], "compilerOptions": { "noEmit": true, "target": "ES2020", - "module": "ES2020", + "module": "ES2022", "moduleResolution": "node", "strict": true, - "declaration": true, - "sourceMap": true, "noUnusedLocals": true, - "esModuleInterop": true, "baseUrl": ".", "resolveJsonModule": true, // see https://devblogs.microsoft.com/typescript/announcing-typescript-4-4-beta/#use-unknown-catch-variables "useUnknownInCatchVariables": false, "allowJs": true, - "checkJs": true + "checkJs": true, + "allowSyntheticDefaultImports": true } } diff --git a/packages/vite-plugin-svelte/types/index.d.ts b/packages/vite-plugin-svelte/types/index.d.ts new file mode 100644 index 000000000..69ee7bf51 --- /dev/null +++ b/packages/vite-plugin-svelte/types/index.d.ts @@ -0,0 +1,189 @@ +declare module '@sveltejs/vite-plugin-svelte' { + import type { InlineConfig, ResolvedConfig } from 'vite'; + import type { CompileOptions, PreprocessorGroup } from 'svelte/compiler'; + import type { Warning } from 'svelte/types/compiler/interfaces'; + import type { Options as InspectorOptions } from '@sveltejs/vite-plugin-svelte-inspector'; + export type Options = Omit & PluginOptionsInline; + + interface PluginOptionsInline extends PluginOptions { + /** + * Path to a svelte config file, either absolute or relative to Vite root + * + * set to `false` to ignore the svelte config file + * + * @see https://vitejs.dev/config/#root + */ + configFile?: string | false; + } + + interface PluginOptions { + /** + * A `picomatch` pattern, or array of patterns, which specifies the files the plugin should + * operate on. By default, all svelte files are included. + * + * @see https://github.com/micromatch/picomatch + */ + include?: Arrayable; + /** + * A `picomatch` pattern, or array of patterns, which specifies the files to be ignored by the + * plugin. By default, no files are ignored. + * + * @see https://github.com/micromatch/picomatch + */ + exclude?: Arrayable; + /** + * Emit Svelte styles as virtual CSS files for Vite and other plugins to process + * + * @default true + */ + emitCss?: boolean; + /** + * Enable or disable Hot Module Replacement. + * + * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + * + * DO NOT CUSTOMIZE SVELTE-HMR OPTIONS UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING + * + * YOU HAVE BEEN WARNED + * + * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + * + * Set an object to pass custom options to svelte-hmr + * + * @see https://github.com/rixo/svelte-hmr#options + * @default true for development, always false for production + */ + hot?: + | boolean + | { + injectCss?: boolean; + partialAccept?: boolean; + [key: string]: any; + }; + /** + * Some Vite plugins can contribute additional preprocessors by defining `api.sveltePreprocess`. + * If you don't want to use them, set this to true to ignore them all or use an array of strings + * with plugin names to specify which. + * + * @default false + */ + ignorePluginPreprocessors?: boolean | string[]; + /** + * vite-plugin-svelte automatically handles excluding svelte libraries and reinclusion of their dependencies + * in vite.optimizeDeps. + * + * `disableDependencyReinclusion: true` disables all reinclusions + * `disableDependencyReinclusion: ['foo','bar']` disables reinclusions for dependencies of foo and bar + * + * This should be used for hybrid packages that contain both node and browser dependencies, eg Routify + * + * @default false + */ + disableDependencyReinclusion?: boolean | string[]; + /** + * Enable support for Vite's dependency optimization to prebundle Svelte libraries. + * + * To disable prebundling for a specific library, add it to `optimizeDeps.exclude`. + * + * @default true for dev, false for build + */ + prebundleSvelteLibraries?: boolean; + /** + * toggle/configure Svelte Inspector + * + * @default unset for dev, always false for build + */ + inspector?: InspectorOptions | boolean; + + /** + * A function to update `compilerOptions` before compilation + * + * `data.filename` - The file to be compiled + * `data.code` - The preprocessed Svelte code + * `data.compileOptions` - The current compiler options + * + * To change part of the compiler options, return an object with the changes you need. + * + * @example + * ``` + * ({ filename, compileOptions }) => { + * // Dynamically set hydration per Svelte file + * if (compileWithHydratable(filename) && !compileOptions.hydratable) { + * return { hydratable: true }; + * } + * } + * ``` + */ + dynamicCompileOptions?: (data: { + filename: string; + code: string; + compileOptions: Partial; + }) => Promise | void> | Partial | void; + + /** + * These options are considered experimental and breaking changes to them can occur in any release + */ + experimental?: ExperimentalOptions; + } + + export interface SvelteConfig { + /** + * A list of file extensions to be compiled by Svelte + * + * @default ['.svelte'] + */ + extensions?: string[]; + /** + * An array of preprocessors to transform the Svelte source code before compilation + * + * @see https://svelte.dev/docs#svelte_preprocess + */ + preprocess?: Arrayable; + /** + * The options to be passed to the Svelte compiler. A few options are set by default, + * including `dev` and `css`. However, some options are non-configurable, like + * `filename`, `format`, `generate`, and `cssHash` (in dev). + * + * @see https://svelte.dev/docs#svelte_compile + */ + compilerOptions?: Omit; + + /** + * Handles warning emitted from the Svelte compiler + */ + onwarn?: (warning: Warning, defaultHandler?: (warning: Warning) => void) => void; + /** + * Options for vite-plugin-svelte + */ + vitePlugin?: PluginOptions; + } + + /** + * These options are considered experimental and breaking changes to them can occur in any release + */ + interface ExperimentalOptions { + /** + * send a websocket message with svelte compiler warnings during dev + * + */ + sendWarningsToBrowser?: boolean; + /** + * disable svelte field resolve warnings + * + * @default false + */ + disableSvelteResolveWarnings?: boolean; + } + + type Arrayable = T | T[]; + + export interface VitePreprocessOptions { + script?: boolean; + style?: boolean | InlineConfig | ResolvedConfig; + } + export function svelte(inlineOptions?: Partial | undefined): import('vite').Plugin[]; + export function vitePreprocess(opts: VitePreprocessOptions): import('svelte/compiler').PreprocessorGroup; + export function loadSvelteConfig(viteConfig: import('vite').UserConfig, inlineOptions: Partial): Promise | undefined>; +} + +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/vite-plugin-svelte/types/index.d.ts.map b/packages/vite-plugin-svelte/types/index.d.ts.map new file mode 100644 index 000000000..8355d0629 --- /dev/null +++ b/packages/vite-plugin-svelte/types/index.d.ts.map @@ -0,0 +1,25 @@ +{ + "version": 3, + "file": "index.d.ts", + "names": [ + "Options", + "SvelteConfig", + "VitePreprocessOptions", + "svelte", + "vitePreprocess", + "loadSvelteConfig" + ], + "sources": [ + "../src/public.d.ts", + "../src/index.js", + "../src/preprocess.js", + "../src/utils/load-svelte-config.js" + ], + "sourcesContent": [ + null, + null, + null, + null + ], + "mappings": ";;;;;aAMYA,OAAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBA2HFC,YAAYA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAmDZC,qBAAqBA;;;;iBC1JtBC,MAAMA;iBCXNC,cAAcA;iBCgBRC,gBAAgBA" +} \ No newline at end of file diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3bbeb0377..a78c51b25 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -36,6 +36,9 @@ importers: cross-env: specifier: ^7.0.3 version: 7.0.3 + dts-buddy: + specifier: ^0.3.0 + version: 0.3.0(typescript@5.2.2) eslint: specifier: ^8.51.0 version: 8.51.0 @@ -1334,6 +1337,13 @@ packages: resolution: {integrity: sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==} engines: {node: '>=6.0.0'} + /@jridgewell/source-map@0.3.5: + resolution: {integrity: sha512-UTYAUj/wviwdsMfzoSJspJxbkH5o1snzwX0//0ENX1u/55kkZZkcTZP6u9bwKGkv+dkk9at4m1Cpt0uY80kcpQ==} + dependencies: + '@jridgewell/gen-mapping': 0.3.3 + '@jridgewell/trace-mapping': 0.3.20 + dev: true + /@jridgewell/sourcemap-codec@1.4.15: resolution: {integrity: sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==} @@ -2724,6 +2734,24 @@ packages: engines: {node: '>=12'} dev: true + /dts-buddy@0.3.0(typescript@5.2.2): + resolution: {integrity: sha512-O/l2Sw//bCpqJVWOQ+8xh54QLRGg4dh+42mONTRyxbIPEpXzN9pOJXYNDOWndPGlgJWMNhlQIUGYxnEcZ83c+g==} + hasBin: true + peerDependencies: + typescript: '>=5.0.4 <5.3' + dependencies: + '@jridgewell/source-map': 0.3.5 + '@jridgewell/sourcemap-codec': 1.4.15 + globrex: 0.1.2 + kleur: 4.1.5 + locate-character: 3.0.0 + magic-string: 0.30.5 + sade: 1.8.1 + tiny-glob: 0.2.9 + ts-api-utils: 1.0.3(typescript@5.2.2) + typescript: 5.2.2 + dev: true + /eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} dev: true