@sveltejs/vite-plugin-svelte 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/package.json +7 -12
  2. package/src/{handle-hot-update.ts → handle-hot-update.js} +35 -20
  3. package/src/index.d.ts +215 -0
  4. package/src/{index.ts → index.js} +39 -67
  5. package/src/{preprocess.ts → preprocess.js} +37 -28
  6. package/src/types/compile.d.ts +48 -0
  7. package/src/types/id.d.ts +31 -0
  8. package/src/types/log.d.ts +24 -0
  9. package/src/types/options.d.ts +20 -0
  10. package/src/types/plugin-api.d.ts +11 -0
  11. package/src/types/vite-plugin-svelte-stats.d.ts +30 -0
  12. package/src/utils/{compile.ts → compile.js} +32 -63
  13. package/src/utils/{dependencies.ts → dependencies.js} +14 -11
  14. package/src/utils/{error.ts → error.js} +21 -14
  15. package/src/utils/{esbuild.ts → esbuild.js} +23 -17
  16. package/src/utils/{hash.ts → hash.js} +14 -3
  17. package/src/utils/{id.ts → id.js} +59 -60
  18. package/src/utils/{load-raw.ts → load-raw.js} +16 -16
  19. package/src/utils/{load-svelte-config.ts → load-svelte-config.js} +12 -10
  20. package/src/utils/{log.ts → log.js} +81 -48
  21. package/src/utils/{optimizer.ts → optimizer.js} +15 -7
  22. package/src/utils/{options.ts → options.js} +146 -296
  23. package/src/utils/{preprocess.ts → preprocess.js} +28 -12
  24. package/src/utils/{resolve.ts → resolve.js} +18 -9
  25. package/src/utils/{sourcemaps.ts → sourcemaps.js} +22 -14
  26. package/src/utils/{svelte-version.ts → svelte-version.js} +15 -7
  27. package/src/utils/vite-plugin-svelte-cache.js +253 -0
  28. package/src/utils/{vite-plugin-svelte-stats.ts → vite-plugin-svelte-stats.js} +66 -62
  29. package/src/utils/{watch.ts → watch.js} +30 -22
  30. package/dist/index.d.ts +0 -193
  31. package/dist/index.js +0 -2272
  32. package/dist/index.js.map +0 -1
  33. package/src/__tests__/fixtures/preprocess/foo.scss +0 -3
  34. package/src/__tests__/preprocess.spec.ts +0 -51
  35. package/src/utils/__tests__/compile.spec.ts +0 -49
  36. package/src/utils/__tests__/sourcemaps.spec.ts +0 -79
  37. package/src/utils/__tests__/svelte-version.spec.ts +0 -102
  38. package/src/utils/vite-plugin-svelte-cache.ts +0 -182
  39. /package/src/utils/{constants.ts → constants.js} +0 -0
@@ -1,54 +1,29 @@
1
- import { log } from './log';
1
+ import { log } from './log.js';
2
2
  import { performance } from 'perf_hooks';
3
3
  import { normalizePath } from 'vite';
4
- import { VitePluginSvelteCache } from './vite-plugin-svelte-cache';
5
4
 
6
- interface Stat {
7
- file: string;
8
- pkg?: string;
9
- start: number;
10
- end: number;
11
- }
12
-
13
- export interface StatCollection {
14
- name: string;
15
- options: CollectionOptions;
16
- //eslint-disable-next-line no-unused-vars
17
- start: (file: string) => () => void;
18
- stats: Stat[];
19
- packageStats?: PackageStats[];
20
- collectionStart: number;
21
- duration?: number;
22
- finish: () => Promise<void> | void;
23
- finished: boolean;
24
- }
25
-
26
- interface PackageStats {
27
- pkg: string;
28
- files: number;
29
- duration: number;
30
- }
31
-
32
- export interface CollectionOptions {
33
- //eslint-disable-next-line no-unused-vars
34
- logInProgress: (collection: StatCollection, now: number) => boolean;
35
- //eslint-disable-next-line no-unused-vars
36
- logResult: (collection: StatCollection) => boolean;
37
- }
38
-
39
- const defaultCollectionOptions: CollectionOptions = {
5
+ /** @type {import('../types/vite-plugin-svelte-stats.d.ts').CollectionOptions} */
6
+ const defaultCollectionOptions = {
40
7
  // log after 500ms and more than one file processed
41
8
  logInProgress: (c, now) => now - c.collectionStart > 500 && c.stats.length > 1,
42
9
  // always log results
43
10
  logResult: () => true
44
11
  };
45
12
 
46
- function humanDuration(n: number) {
13
+ /**
14
+ * @param {number} n
15
+ * @returns
16
+ */
17
+ function humanDuration(n) {
47
18
  // 99.9ms 0.10s
48
19
  return n < 100 ? `${n.toFixed(1)}ms` : `${(n / 1000).toFixed(2)}s`;
49
20
  }
50
21
 
51
- function formatPackageStats(pkgStats: PackageStats[]) {
22
+ /**
23
+ * @param {import('../types/vite-plugin-svelte-stats.d.ts').PackageStats[]} pkgStats
24
+ * @returns {string}
25
+ */
26
+ function formatPackageStats(pkgStats) {
52
27
  const statLines = pkgStats.map((pkgStat) => {
53
28
  const duration = pkgStat.duration;
54
29
  const avg = duration / pkgStat.files;
@@ -56,7 +31,7 @@ function formatPackageStats(pkgStats: PackageStats[]) {
56
31
  });
57
32
  statLines.unshift(['package', 'files', 'time', 'avg']);
58
33
  const columnWidths = statLines.reduce(
59
- (widths: number[], row) => {
34
+ (widths, row) => {
60
35
  for (let i = 0; i < row.length; i++) {
61
36
  const cell = row[i];
62
37
  if (widths[i] < cell.length) {
@@ -69,9 +44,9 @@ function formatPackageStats(pkgStats: PackageStats[]) {
69
44
  );
70
45
 
71
46
  const table = statLines
72
- .map((row: string[]) =>
47
+ .map((row) =>
73
48
  row
74
- .map((cell: string, i: number) => {
49
+ .map((cell, i) => {
75
50
  if (i === 0) {
76
51
  return cell.padEnd(columnWidths[i], ' ');
77
52
  } else {
@@ -84,23 +59,40 @@ function formatPackageStats(pkgStats: PackageStats[]) {
84
59
  return table;
85
60
  }
86
61
 
62
+ /**
63
+ * @class
64
+ */
87
65
  export class VitePluginSvelteStats {
88
66
  // package directory -> package name
89
- private _cache: VitePluginSvelteCache;
90
- private _collections: StatCollection[] = [];
91
- constructor(cache: VitePluginSvelteCache) {
92
- this._cache = cache;
67
+ /** @type {import('./vite-plugin-svelte-cache.js').VitePluginSvelteCache} */
68
+ #cache;
69
+ /** @type {import('../types/vite-plugin-svelte-stats.d.ts').StatCollection[]} */
70
+ #collections = [];
71
+
72
+ /**
73
+ * @param {import('./vite-plugin-svelte-cache.js').VitePluginSvelteCache} cache
74
+ */
75
+ constructor(cache) {
76
+ this.#cache = cache;
93
77
  }
94
- startCollection(name: string, opts?: Partial<CollectionOptions>) {
78
+
79
+ /**
80
+ * @param {string} name
81
+ * @param {Partial<import('../types/vite-plugin-svelte-stats.d.ts').CollectionOptions>} [opts]
82
+ * @returns {import('../types/vite-plugin-svelte-stats.d.ts').StatCollection}
83
+ */
84
+ startCollection(name, opts) {
95
85
  const options = {
96
86
  ...defaultCollectionOptions,
97
87
  ...opts
98
88
  };
99
- const stats: Stat[] = [];
89
+ /** @type {import('../types/vite-plugin-svelte-stats.d.ts').Stat[]} */
90
+ const stats = [];
100
91
  const collectionStart = performance.now();
101
92
  const _this = this;
102
93
  let hasLoggedProgress = false;
103
- const collection: StatCollection = {
94
+ /** @type {import('../types/vite-plugin-svelte-stats.d.ts').StatCollection} */
95
+ const collection = {
104
96
  name,
105
97
  options,
106
98
  stats,
@@ -112,7 +104,8 @@ export class VitePluginSvelteStats {
112
104
  }
113
105
  file = normalizePath(file);
114
106
  const start = performance.now();
115
- const stat: Stat = { file, start, end: start };
107
+ /** @type {import('../types/vite-plugin-svelte-stats.d.ts').Stat} */
108
+ const stat = { file, start, end: start };
116
109
  return () => {
117
110
  const now = performance.now();
118
111
  stat.end = now;
@@ -124,34 +117,41 @@ export class VitePluginSvelteStats {
124
117
  };
125
118
  },
126
119
  async finish() {
127
- await _this._finish(collection);
120
+ await _this.#finish(collection);
128
121
  }
129
122
  };
130
- _this._collections.push(collection);
123
+ _this.#collections.push(collection);
131
124
  return collection;
132
125
  }
133
126
 
134
- public async finishAll() {
135
- await Promise.all(this._collections.map((c) => c.finish()));
127
+ async finishAll() {
128
+ await Promise.all(this.#collections.map((c) => c.finish()));
136
129
  }
137
130
 
138
- private async _finish(collection: StatCollection) {
131
+ /**
132
+ * @param {import('../types/vite-plugin-svelte-stats.d.ts').StatCollection} collection
133
+ */
134
+ async #finish(collection) {
139
135
  try {
140
136
  collection.finished = true;
141
137
  const now = performance.now();
142
138
  collection.duration = now - collection.collectionStart;
143
139
  const logResult = collection.options.logResult(collection);
144
140
  if (logResult) {
145
- await this._aggregateStatsResult(collection);
141
+ await this.#aggregateStatsResult(collection);
146
142
  log.debug(
147
- `${collection.name} done.\n${formatPackageStats(collection.packageStats!)}`,
143
+ `${collection.name} done.\n${formatPackageStats(
144
+ /** @type {import('../types/vite-plugin-svelte-stats.d.ts').PackageStats[]}*/ (
145
+ collection.packageStats
146
+ )
147
+ )}`,
148
148
  undefined,
149
149
  'stats'
150
150
  );
151
151
  }
152
152
  // cut some ties to free it for garbage collection
153
- const index = this._collections.indexOf(collection);
154
- this._collections.splice(index, 1);
153
+ const index = this.#collections.indexOf(collection);
154
+ this.#collections.splice(index, 1);
155
155
  collection.stats.length = 0;
156
156
  collection.stats = [];
157
157
  if (collection.packageStats) {
@@ -166,16 +166,20 @@ export class VitePluginSvelteStats {
166
166
  }
167
167
  }
168
168
 
169
- private async _aggregateStatsResult(collection: StatCollection) {
169
+ /**
170
+ * @param {import('../types/vite-plugin-svelte-stats.d.ts').StatCollection} collection
171
+ */
172
+ async #aggregateStatsResult(collection) {
170
173
  const stats = collection.stats;
171
174
  for (const stat of stats) {
172
- stat.pkg = (await this._cache.getPackageInfo(stat.file)).name;
175
+ stat.pkg = (await this.#cache.getPackageInfo(stat.file)).name;
173
176
  }
174
177
 
175
178
  // group stats
176
- const grouped: { [key: string]: PackageStats } = {};
179
+ /** @type {Record<string, import('../types/vite-plugin-svelte-stats.d.ts').PackageStats>} */
180
+ const grouped = {};
177
181
  stats.forEach((stat) => {
178
- const pkg = stat.pkg!;
182
+ const pkg = /** @type {string} */ (stat.pkg);
179
183
  let group = grouped[pkg];
180
184
  if (!group) {
181
185
  group = grouped[pkg] = {
@@ -1,25 +1,23 @@
1
- import { VitePluginSvelteCache } from './vite-plugin-svelte-cache';
2
1
  import fs from 'fs';
3
- import { log } from './log';
4
- import { IdParser } from './id';
5
- import { ResolvedOptions } from './options';
6
- import { knownSvelteConfigNames } from './load-svelte-config';
2
+ import { log } from './log.js';
3
+ import { knownSvelteConfigNames } from './load-svelte-config.js';
7
4
  import path from 'path';
8
- import { FSWatcher } from 'vite';
9
5
 
10
- export function setupWatchers(
11
- options: ResolvedOptions,
12
- cache: VitePluginSvelteCache,
13
- requestParser: IdParser
14
- ) {
6
+ /**
7
+ * @param {import('../types/options.d.ts').ResolvedOptions} options
8
+ * @param {import('./vite-plugin-svelte-cache').VitePluginSvelteCache} cache
9
+ * @param {import('../types/id.d.ts').IdParser} requestParser
10
+ * @returns {void}
11
+ */
12
+ export function setupWatchers(options, cache, requestParser) {
15
13
  const { server, configFile: svelteConfigFile } = options;
16
14
  if (!server) {
17
15
  return;
18
16
  }
19
17
  const { watcher, ws } = server;
20
18
  const { root, server: serverConfig } = server.config;
21
-
22
- const emitChangeEventOnDependants = (filename: string) => {
19
+ /** @type {(filename: string) => void} */
20
+ const emitChangeEventOnDependants = (filename) => {
23
21
  const dependants = cache.getDependants(filename);
24
22
  dependants.forEach((dependant) => {
25
23
  if (fs.existsSync(dependant)) {
@@ -30,8 +28,8 @@ export function setupWatchers(
30
28
  }
31
29
  });
32
30
  };
33
-
34
- const removeUnlinkedFromCache = (filename: string) => {
31
+ /** @type {(filename: string) => void} */
32
+ const removeUnlinkedFromCache = (filename) => {
35
33
  const svelteRequest = requestParser(filename, false);
36
34
  if (svelteRequest) {
37
35
  const removedFromCache = cache.remove(svelteRequest);
@@ -40,8 +38,8 @@ export function setupWatchers(
40
38
  }
41
39
  }
42
40
  };
43
-
44
- const triggerViteRestart = (filename: string) => {
41
+ /** @type {(filename: string) => void} */
42
+ const triggerViteRestart = (filename) => {
45
43
  if (serverConfig.middlewareMode) {
46
44
  // in middlewareMode we can't restart the server automatically
47
45
  // show the user an overlay instead
@@ -59,8 +57,9 @@ export function setupWatchers(
59
57
  };
60
58
 
61
59
  // collection of watcher listeners by event
60
+ /** @type {Record<string, Function[]>} */
62
61
  const listenerCollection = {
63
- add: [] as Array<Function>,
62
+ add: [],
64
63
  change: [emitChangeEventOnDependants],
65
64
  unlink: [removeUnlinkedFromCache, emitChangeEventOnDependants]
66
65
  };
@@ -68,13 +67,15 @@ export function setupWatchers(
68
67
  if (svelteConfigFile !== false) {
69
68
  // configFile false means we ignore the file and external process is responsible
70
69
  const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => path.join(root, cfg));
71
- const restartOnConfigAdd = (filename: string) => {
70
+ /** @type {(filename: string) => void} */
71
+ const restartOnConfigAdd = (filename) => {
72
72
  if (possibleSvelteConfigs.includes(filename)) {
73
73
  triggerViteRestart(filename);
74
74
  }
75
75
  };
76
76
 
77
- const restartOnConfigChange = (filename: string) => {
77
+ /** @type {(filename: string) => void} */
78
+ const restartOnConfigChange = (filename) => {
78
79
  if (filename === svelteConfigFile) {
79
80
  triggerViteRestart(filename);
80
81
  }
@@ -94,8 +95,15 @@ export function setupWatchers(
94
95
  }
95
96
  });
96
97
  }
97
- // taken from vite utils
98
- export function ensureWatchedFile(watcher: FSWatcher, file: string | null, root: string): void {
98
+
99
+ /**
100
+ * taken from vite utils
101
+ * @param {import('vite').FSWatcher} watcher
102
+ * @param {string | null} file
103
+ * @param {string} root
104
+ * @returns {void}
105
+ */
106
+ export function ensureWatchedFile(watcher, file, root) {
99
107
  if (
100
108
  file &&
101
109
  // only need to watch if out of root
package/dist/index.d.ts DELETED
@@ -1,193 +0,0 @@
1
- import { InlineConfig, ResolvedConfig, UserConfig, Plugin } from 'vite';
2
- import { CompileOptions, Warning } from 'svelte/types/compiler/interfaces';
3
- export { CompileOptions, Warning } from 'svelte/types/compiler/interfaces';
4
- import { PreprocessorGroup } from 'svelte/types/compiler/preprocess';
5
- export { MarkupPreprocessor, Preprocessor, PreprocessorGroup, Processed } from 'svelte/types/compiler/preprocess';
6
- import { Options as Options$1 } from '@sveltejs/vite-plugin-svelte-inspector';
7
-
8
- type Options = Omit<SvelteOptions, 'vitePlugin'> & PluginOptionsInline;
9
- interface PluginOptionsInline extends PluginOptions {
10
- /**
11
- * Path to a svelte config file, either absolute or relative to Vite root
12
- *
13
- * set to `false` to ignore the svelte config file
14
- *
15
- * @see https://vitejs.dev/config/#root
16
- */
17
- configFile?: string | false;
18
- }
19
- interface PluginOptions {
20
- /**
21
- * A `picomatch` pattern, or array of patterns, which specifies the files the plugin should
22
- * operate on. By default, all svelte files are included.
23
- *
24
- * @see https://github.com/micromatch/picomatch
25
- */
26
- include?: Arrayable<string>;
27
- /**
28
- * A `picomatch` pattern, or array of patterns, which specifies the files to be ignored by the
29
- * plugin. By default, no files are ignored.
30
- *
31
- * @see https://github.com/micromatch/picomatch
32
- */
33
- exclude?: Arrayable<string>;
34
- /**
35
- * Emit Svelte styles as virtual CSS files for Vite and other plugins to process
36
- *
37
- * @default true
38
- */
39
- emitCss?: boolean;
40
- /**
41
- * Enable or disable Hot Module Replacement.
42
- *
43
- * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
44
- *
45
- * DO NOT CUSTOMIZE SVELTE-HMR OPTIONS UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING
46
- *
47
- * YOU HAVE BEEN WARNED
48
- *
49
- * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
50
- *
51
- * Set an object to pass custom options to svelte-hmr
52
- *
53
- * @see https://github.com/rixo/svelte-hmr#options
54
- * @default true for development, always false for production
55
- */
56
- hot?: boolean | {
57
- injectCss?: boolean;
58
- partialAccept?: boolean;
59
- [key: string]: any;
60
- };
61
- /**
62
- * Some Vite plugins can contribute additional preprocessors by defining `api.sveltePreprocess`.
63
- * If you don't want to use them, set this to true to ignore them all or use an array of strings
64
- * with plugin names to specify which.
65
- *
66
- * @default false
67
- */
68
- ignorePluginPreprocessors?: boolean | string[];
69
- /**
70
- * vite-plugin-svelte automatically handles excluding svelte libraries and reinclusion of their dependencies
71
- * in vite.optimizeDeps.
72
- *
73
- * `disableDependencyReinclusion: true` disables all reinclusions
74
- * `disableDependencyReinclusion: ['foo','bar']` disables reinclusions for dependencies of foo and bar
75
- *
76
- * This should be used for hybrid packages that contain both node and browser dependencies, eg Routify
77
- *
78
- * @default false
79
- */
80
- disableDependencyReinclusion?: boolean | string[];
81
- /**
82
- * Enable support for Vite's dependency optimization to prebundle Svelte libraries.
83
- *
84
- * To disable prebundling for a specific library, add it to `optimizeDeps.exclude`.
85
- *
86
- * @default true for dev, false for build
87
- */
88
- prebundleSvelteLibraries?: boolean;
89
- /**
90
- * toggle/configure Svelte Inspector
91
- *
92
- * @default true
93
- */
94
- inspector?: Options$1 | boolean;
95
- /**
96
- * These options are considered experimental and breaking changes to them can occur in any release
97
- */
98
- experimental?: ExperimentalOptions;
99
- }
100
- interface SvelteOptions {
101
- /**
102
- * A list of file extensions to be compiled by Svelte
103
- *
104
- * @default ['.svelte']
105
- */
106
- extensions?: string[];
107
- /**
108
- * An array of preprocessors to transform the Svelte source code before compilation
109
- *
110
- * @see https://svelte.dev/docs#svelte_preprocess
111
- */
112
- preprocess?: Arrayable<PreprocessorGroup>;
113
- /**
114
- * The options to be passed to the Svelte compiler. A few options are set by default,
115
- * including `dev` and `css`. However, some options are non-configurable, like
116
- * `filename`, `format`, `generate`, and `cssHash` (in dev).
117
- *
118
- * @see https://svelte.dev/docs#svelte_compile
119
- */
120
- compilerOptions?: Omit<CompileOptions, 'filename' | 'format' | 'generate'>;
121
- /**
122
- * Handles warning emitted from the Svelte compiler
123
- */
124
- onwarn?: (warning: Warning, defaultHandler?: (warning: Warning) => void) => void;
125
- /**
126
- * Options for vite-plugin-svelte
127
- */
128
- vitePlugin?: PluginOptions;
129
- }
130
- /**
131
- * These options are considered experimental and breaking changes to them can occur in any release
132
- */
133
- interface ExperimentalOptions {
134
- /**
135
- * A function to update `compilerOptions` before compilation
136
- *
137
- * `data.filename` - The file to be compiled
138
- * `data.code` - The preprocessed Svelte code
139
- * `data.compileOptions` - The current compiler options
140
- *
141
- * To change part of the compiler options, return an object with the changes you need.
142
- *
143
- * @example
144
- * ```
145
- * ({ filename, compileOptions }) => {
146
- * // Dynamically set hydration per Svelte file
147
- * if (compileWithHydratable(filename) && !compileOptions.hydratable) {
148
- * return { hydratable: true };
149
- * }
150
- * }
151
- * ```
152
- */
153
- dynamicCompileOptions?: (data: {
154
- filename: string;
155
- code: string;
156
- compileOptions: Partial<CompileOptions>;
157
- }) => Promise<Partial<CompileOptions> | void> | Partial<CompileOptions> | void;
158
- /**
159
- * send a websocket message with svelte compiler warnings during dev
160
- *
161
- */
162
- sendWarningsToBrowser?: boolean;
163
- /**
164
- * disable svelte field resolve warnings
165
- *
166
- * @default false
167
- */
168
- disableSvelteResolveWarnings?: boolean;
169
- }
170
- type ModuleFormat = NonNullable<CompileOptions['format']>;
171
- type CssHashGetter = NonNullable<CompileOptions['cssHash']>;
172
- type Arrayable<T> = T | T[];
173
-
174
- declare function vitePreprocess(opts?: {
175
- script?: boolean;
176
- style?: boolean | InlineConfig | ResolvedConfig;
177
- }): PreprocessorGroup;
178
-
179
- declare function loadSvelteConfig(viteConfig?: UserConfig, inlineOptions?: Partial<Options>): Promise<Partial<SvelteOptions> | undefined>;
180
-
181
- type SvelteWarningsMessage = {
182
- id: string;
183
- filename: string;
184
- normalizedFilename: string;
185
- timestamp: number;
186
- warnings: Warning[];
187
- allWarnings: Warning[];
188
- rawWarnings: Warning[];
189
- };
190
-
191
- declare function svelte(inlineOptions?: Partial<Options>): Plugin[];
192
-
193
- export { Arrayable, CssHashGetter, ModuleFormat, Options, PluginOptions, SvelteOptions, SvelteWarningsMessage, loadSvelteConfig, svelte, vitePreprocess };