@sveltejs/vite-plugin-svelte 2.0.2 → 2.0.4

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.
package/dist/index.js CHANGED
@@ -62,7 +62,7 @@ function _log(logger, message, payload) {
62
62
  if (logger.isDebug) {
63
63
  payload !== void 0 ? logger.log(message, payload) : logger.log(message);
64
64
  } else {
65
- logger.log(logger.color(`${new Date().toLocaleTimeString()} [${prefix}] ${message}`));
65
+ logger.log(logger.color(`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} [${prefix}] ${message}`));
66
66
  if (payload) {
67
67
  logger.log(payload);
68
68
  }
@@ -127,15 +127,19 @@ function logCompilerWarnings(svelteRequest, warnings, options) {
127
127
  normalizedFilename: svelteRequest.normalizedFilename,
128
128
  timestamp: svelteRequest.timestamp,
129
129
  warnings: handledByDefaultWarn,
130
+ // allWarnings filtered by warnings where onwarn did not call the default handler
130
131
  allWarnings,
132
+ // includes warnings filtered by onwarn and our extra vite plugin svelte warnings
131
133
  rawWarnings: warnings
134
+ // raw compiler output
132
135
  };
133
136
  log.debug(`sending svelte:warnings message for ${svelteRequest.normalizedFilename}`);
134
137
  options.server?.ws?.send("svelte:warnings", message);
135
138
  }
136
139
  }
137
140
  function ignoreCompilerWarning(warning, isBuild, emitCss) {
138
- return !emitCss && warning.code === "css-unused-selector" || !isBuild && isNoScopableElementWarning(warning);
141
+ return !emitCss && warning.code === "css-unused-selector" || // same as rollup-plugin-svelte
142
+ !isBuild && isNoScopableElementWarning(warning);
139
143
  }
140
144
  function isNoScopableElementWarning(warning) {
141
145
  return warning.code === "css-unused-selector" && warning.message.includes('"*"');
@@ -178,6 +182,62 @@ function buildExtendedLogMessage(w) {
178
182
  return parts.join("");
179
183
  }
180
184
 
185
+ // src/utils/error.ts
186
+ function toRollupError(error, options) {
187
+ const { filename, frame, start, code, name, stack } = error;
188
+ const rollupError = {
189
+ name,
190
+ // needed otherwise sveltekit coalesce_to_error turns it into a string
191
+ id: filename,
192
+ message: buildExtendedLogMessage(error),
193
+ // include filename:line:column so that it's clickable
194
+ frame: formatFrameForVite(frame),
195
+ code,
196
+ stack: options.isBuild || options.isDebug || !frame ? stack : ""
197
+ };
198
+ if (start) {
199
+ rollupError.loc = {
200
+ line: start.line,
201
+ column: start.column,
202
+ file: filename
203
+ };
204
+ }
205
+ return rollupError;
206
+ }
207
+ function toESBuildError(error, options) {
208
+ const { filename, frame, start, stack } = error;
209
+ const partialMessage = {
210
+ text: buildExtendedLogMessage(error)
211
+ };
212
+ if (start) {
213
+ partialMessage.location = {
214
+ line: start.line,
215
+ column: start.column,
216
+ file: filename,
217
+ lineText: lineFromFrame(start.line, frame)
218
+ // needed to get a meaningful error message on cli
219
+ };
220
+ }
221
+ if (options.isBuild || options.isDebug || !frame) {
222
+ partialMessage.detail = stack;
223
+ }
224
+ return partialMessage;
225
+ }
226
+ function lineFromFrame(lineNo, frame) {
227
+ if (!frame) {
228
+ return "";
229
+ }
230
+ const lines = frame.split("\n");
231
+ const errorLine = lines.find((line) => line.trimStart().startsWith(`${lineNo}: `));
232
+ return errorLine ? errorLine.substring(errorLine.indexOf(": ") + 3) : "";
233
+ }
234
+ function formatFrameForVite(frame) {
235
+ if (!frame) {
236
+ return "";
237
+ }
238
+ return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
239
+ }
240
+
181
241
  // src/handle-hot-update.ts
182
242
  async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options) {
183
243
  if (!cache.has(svelteRequest)) {
@@ -194,7 +254,7 @@ async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, option
194
254
  cache.update(compileData);
195
255
  } catch (e) {
196
256
  cache.setError(svelteRequest, e);
197
- throw e;
257
+ throw toRollupError(e, options);
198
258
  }
199
259
  const affectedModules = [...modules];
200
260
  const cssIdx = modules.findIndex((m) => m.id === svelteRequest.cssId);
@@ -363,9 +423,8 @@ function addExtraPreprocessors(options, config) {
363
423
  }
364
424
  }
365
425
 
366
- // src/utils/compile.ts
426
+ // src/utils/sourcemaps.ts
367
427
  import path2 from "path";
368
- var scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/;
369
428
  function mapSourcesToRelative(map, filename) {
370
429
  if (map?.sources) {
371
430
  map.sources = map.sources.map((s) => {
@@ -378,6 +437,9 @@ function mapSourcesToRelative(map, filename) {
378
437
  });
379
438
  }
380
439
  }
440
+
441
+ // src/utils/compile.ts
442
+ var scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/;
381
443
  var _createCompileSvelte = (makeHot) => {
382
444
  let stats;
383
445
  const devStylePreprocessor = createInjectScopeEverythingRulePreprocessorGroup();
@@ -405,6 +467,7 @@ var _createCompileSvelte = (makeHot) => {
405
467
  const compileOptions = {
406
468
  ...options.compilerOptions,
407
469
  filename: normalizedFilename,
470
+ // use normalized here to avoid bleeding absolute fs path
408
471
  generate: ssr ? "ssr" : "dom",
409
472
  format: "esm"
410
473
  };
@@ -464,6 +527,10 @@ var _createCompileSvelte = (makeHot) => {
464
527
  } : compileOptions;
465
528
  const endStat = stats?.start(filename);
466
529
  const compiled = compile(finalCode, finalCompileOptions);
530
+ compiled.js.code = compiled.js.code.replace(
531
+ /\/\* [@#]__PURE__ \*\/(\s*)$/gm,
532
+ " $1"
533
+ );
467
534
  if (endStat) {
468
535
  endStat();
469
536
  }
@@ -480,6 +547,7 @@ import ${JSON.stringify(cssId)};
480
547
  compiled.js.code = makeHot({
481
548
  id: filename,
482
549
  compiledCode: compiled.js.code,
550
+ //@ts-expect-error hot isn't a boolean at this point
483
551
  hotOptions: { ...options.hot, injectCss: options.hot?.injectCss === true && hasCss },
484
552
  compiled,
485
553
  originalCode: code,
@@ -492,6 +560,7 @@ import ${JSON.stringify(cssId)};
492
560
  filename,
493
561
  normalizedFilename,
494
562
  lang: code.match(scriptLangRE)?.[1] || "js",
563
+ // @ts-ignore
495
564
  compiled,
496
565
  ssr,
497
566
  dependencies,
@@ -728,7 +797,7 @@ function findConfigToLoad(viteConfig, inlineOptions) {
728
797
 
729
798
  // src/utils/constants.ts
730
799
  var VITE_RESOLVE_MAIN_FIELDS = ["module", "jsnext:main", "jsnext"];
731
- var SVELTE_RESOLVE_MAIN_FIELDS = ["svelte", ...VITE_RESOLVE_MAIN_FIELDS];
800
+ var SVELTE_RESOLVE_MAIN_FIELDS = ["svelte"];
732
801
  var SVELTE_IMPORTS = [
733
802
  "svelte/animate",
734
803
  "svelte/easing",
@@ -752,61 +821,6 @@ import path5 from "path";
752
821
  // src/utils/esbuild.ts
753
822
  import { readFileSync } from "fs";
754
823
  import { compile as compile2, preprocess as preprocess2 } from "svelte/compiler";
755
-
756
- // src/utils/error.ts
757
- function toRollupError(error, options) {
758
- const { filename, frame, start, code, name, stack } = error;
759
- const rollupError = {
760
- name,
761
- id: filename,
762
- message: buildExtendedLogMessage(error),
763
- frame: formatFrameForVite(frame),
764
- code,
765
- stack: options.isBuild || options.isDebug || !frame ? stack : ""
766
- };
767
- if (start) {
768
- rollupError.loc = {
769
- line: start.line,
770
- column: start.column,
771
- file: filename
772
- };
773
- }
774
- return rollupError;
775
- }
776
- function toESBuildError(error, options) {
777
- const { filename, frame, start, stack } = error;
778
- const partialMessage = {
779
- text: buildExtendedLogMessage(error)
780
- };
781
- if (start) {
782
- partialMessage.location = {
783
- line: start.line,
784
- column: start.column,
785
- file: filename,
786
- lineText: lineFromFrame(start.line, frame)
787
- };
788
- }
789
- if (options.isBuild || options.isDebug || !frame) {
790
- partialMessage.detail = stack;
791
- }
792
- return partialMessage;
793
- }
794
- function lineFromFrame(lineNo, frame) {
795
- if (!frame) {
796
- return "";
797
- }
798
- const lines = frame.split("\n");
799
- const errorLine = lines.find((line) => line.trimStart().startsWith(`${lineNo}: `));
800
- return errorLine ? errorLine.substring(errorLine.indexOf(": ") + 3) : "";
801
- }
802
- function formatFrameForVite(frame) {
803
- if (!frame) {
804
- return "";
805
- }
806
- return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
807
- }
808
-
809
- // src/utils/esbuild.ts
810
824
  var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
811
825
  function esbuildSveltePlugin(options) {
812
826
  return {
@@ -932,6 +946,7 @@ var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
932
946
  "vite",
933
947
  "vitest",
934
948
  "__vite-browser-external"
949
+ // see https://github.com/sveltejs/vite-plugin-svelte/issues/362
935
950
  ];
936
951
  var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
937
952
  "@fontsource/",
@@ -950,6 +965,7 @@ var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
950
965
  function isCommonDepWithoutSvelteField(dependency) {
951
966
  return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
952
967
  (prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
968
+ // check prefix omitting @scope/
953
969
  );
954
970
  }
955
971
 
@@ -960,7 +976,9 @@ import { dirname } from "path";
960
976
  import { performance } from "perf_hooks";
961
977
  import { normalizePath as normalizePath2 } from "vite";
962
978
  var defaultCollectionOptions = {
979
+ // log after 500ms and more than one file processed
963
980
  logInProgress: (c, now) => now - c.collectionStart > 500 && c.stats.length > 1,
981
+ // always log results
964
982
  logResult: () => true
965
983
  };
966
984
  function humanDuration(n) {
@@ -998,7 +1016,7 @@ function formatPackageStats(pkgStats) {
998
1016
  }
999
1017
  async function getClosestNamedPackage(file) {
1000
1018
  let name = "$unknown";
1001
- let path11 = await findClosestPkgJsonPath(file, (pkgPath) => {
1019
+ let path10 = await findClosestPkgJsonPath(file, (pkgPath) => {
1002
1020
  const pkg = JSON.parse(readFileSync2(pkgPath, "utf-8"));
1003
1021
  if (pkg.name != null) {
1004
1022
  name = pkg.name;
@@ -1006,11 +1024,12 @@ async function getClosestNamedPackage(file) {
1006
1024
  }
1007
1025
  return false;
1008
1026
  });
1009
- path11 = normalizePath2(dirname(path11 ?? file)) + "/";
1010
- return { name, path: path11 };
1027
+ path10 = normalizePath2(dirname(path10 ?? file)) + "/";
1028
+ return { name, path: path10 };
1011
1029
  }
1012
1030
  var VitePluginSvelteStats = class {
1013
1031
  constructor() {
1032
+ // package directory -> package name
1014
1033
  this._packages = [];
1015
1034
  this._collections = [];
1016
1035
  }
@@ -1127,6 +1146,7 @@ var knownRootOptions = /* @__PURE__ */ new Set(["extensions", "compilerOptions",
1127
1146
  var allowedInlineOptions = /* @__PURE__ */ new Set([
1128
1147
  "configFile",
1129
1148
  "kit",
1149
+ // only for internal use by sveltekit
1130
1150
  ...allowedPluginOptions,
1131
1151
  ...knownRootOptions
1132
1152
  ]);
@@ -1226,6 +1246,7 @@ function mergeConfigs(...configs) {
1226
1246
  let result = {};
1227
1247
  for (const config of configs.filter((x) => x != null)) {
1228
1248
  result = deepmerge(result, config, {
1249
+ // replace arrays
1229
1250
  arrayMerge: (target, source) => source ?? target
1230
1251
  });
1231
1252
  }
@@ -1356,12 +1377,22 @@ function resolveViteRoot(viteConfig) {
1356
1377
  return normalizePath3(viteConfig.root ? path5.resolve(viteConfig.root) : process.cwd());
1357
1378
  }
1358
1379
  async function buildExtraViteConfig(options, config) {
1380
+ if (!config.resolve) {
1381
+ config.resolve = {};
1382
+ }
1383
+ config.resolve.mainFields = [
1384
+ ...SVELTE_RESOLVE_MAIN_FIELDS,
1385
+ ...config.resolve.mainFields ?? VITE_RESOLVE_MAIN_FIELDS
1386
+ ];
1359
1387
  const extraViteConfig = {
1360
1388
  resolve: {
1361
- mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1362
1389
  dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS],
1363
1390
  conditions: [...SVELTE_EXPORT_CONDITIONS]
1364
1391
  }
1392
+ // this option is still awaiting a PR in vite to be supported
1393
+ // see https://github.com/sveltejs/vite-plugin-svelte/issues/60
1394
+ // @ts-ignore
1395
+ // knownJsSrcExtensions: options.extensions
1365
1396
  };
1366
1397
  const extraSvelteConfig = buildExtraConfigForSvelte(config);
1367
1398
  const extraDepsConfig = await buildExtraConfigForDependencies(options, config);
@@ -1396,14 +1427,20 @@ async function buildExtraViteConfig(options, config) {
1396
1427
  if (options.prebundleSvelteLibraries) {
1397
1428
  extraViteConfig.optimizeDeps = {
1398
1429
  ...extraViteConfig.optimizeDeps,
1430
+ // Experimental Vite API to allow these extensions to be scanned and prebundled
1431
+ // @ts-ignore
1399
1432
  extensions: options.extensions ?? [".svelte"],
1433
+ // Add esbuild plugin to prebundle Svelte files.
1434
+ // Currently a placeholder as more information is needed after Vite config is resolved,
1435
+ // the real Svelte plugin is added in `patchResolvedViteConfig()`
1400
1436
  esbuildOptions: {
1401
1437
  plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1402
1438
  } }]
1403
1439
  }
1404
1440
  };
1405
1441
  }
1406
- if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && config.experimental?.hmrPartialAccept !== false) {
1442
+ if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && // deviate from svelte-hmr, default to true
1443
+ config.experimental?.hmrPartialAccept !== false) {
1407
1444
  log.debug('enabling "experimental.hmrPartialAccept" in vite config');
1408
1445
  extraViteConfig.experimental = { hmrPartialAccept: true };
1409
1446
  }
@@ -1602,7 +1639,9 @@ function setupWatchers(options, cache, requestParser) {
1602
1639
  });
1603
1640
  }
1604
1641
  function ensureWatchedFile(watcher, file, root) {
1605
- if (file && !file.startsWith(root + "/") && !file.includes("\0") && fs4.existsSync(file)) {
1642
+ if (file && // only need to watch if out of root
1643
+ !file.startsWith(root + "/") && // some rollup plugins use null bytes for private resolved Ids
1644
+ !file.includes("\0") && fs4.existsSync(file)) {
1606
1645
  watcher.add(path6.resolve(file));
1607
1646
  }
1608
1647
  }
@@ -1787,6 +1826,7 @@ import 'virtual:svelte-inspector-path:load-inspector.js'` };
1787
1826
  injectTo: "body",
1788
1827
  attrs: {
1789
1828
  type: "module",
1829
+ // /@id/ is needed, otherwise the virtual: is seen as protocol by browser and cors error happens
1790
1830
  src: "/@id/virtual:svelte-inspector-path:load-inspector.js"
1791
1831
  }
1792
1832
  }
@@ -1883,8 +1923,8 @@ var VitePluginSvelteCache = class {
1883
1923
  getError(svelteRequest) {
1884
1924
  return this._errors.get(svelteRequest.normalizedFilename);
1885
1925
  }
1886
- getDependants(path11) {
1887
- const dependants = this._dependants.get(path11);
1926
+ getDependants(path10) {
1927
+ const dependants = this._dependants.get(path10);
1888
1928
  return dependants ? [...dependants] : [];
1889
1929
  }
1890
1930
  getResolvedSvelteField(name, importer) {
@@ -1912,6 +1952,7 @@ async function loadRaw(svelteRequest, compileSvelte2, options) {
1912
1952
  const type = query.type;
1913
1953
  compileData = await compileSvelte2(svelteRequest, source, {
1914
1954
  ...options,
1955
+ // don't use dynamic vite-plugin-svelte defaults here to ensure stable result between ssr,dev and build
1915
1956
  compilerOptions: {
1916
1957
  dev: false,
1917
1958
  css: false,
@@ -1993,7 +2034,6 @@ function toRawExports(object) {
1993
2034
  }
1994
2035
 
1995
2036
  // src/preprocess.ts
1996
- import path10 from "path";
1997
2037
  import { preprocessCSS, resolveConfig, transformWithEsbuild } from "vite";
1998
2038
  var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss", "sss"];
1999
2039
  var supportedScriptLangs = ["ts"];
@@ -2014,19 +2054,21 @@ function viteScript() {
2014
2054
  const lang = attributes.lang;
2015
2055
  if (!supportedScriptLangs.includes(lang))
2016
2056
  return;
2017
- const transformResult = await transformWithEsbuild(content, filename, {
2057
+ const { code, map } = await transformWithEsbuild(content, filename, {
2018
2058
  loader: lang,
2019
2059
  target: "esnext",
2020
2060
  tsconfigRaw: {
2021
2061
  compilerOptions: {
2062
+ // svelte typescript needs this flag to work with type imports
2022
2063
  importsNotUsedAsValues: "preserve",
2023
2064
  preserveValueImports: true
2024
2065
  }
2025
2066
  }
2026
2067
  });
2068
+ mapSourcesToRelative(map, filename);
2027
2069
  return {
2028
- code: transformResult.code,
2029
- map: transformResult.map
2070
+ code,
2071
+ map
2030
2072
  };
2031
2073
  }
2032
2074
  };
@@ -2052,13 +2094,11 @@ function viteStyle(config = {}) {
2052
2094
  transform = getCssTransformFn(resolvedConfig);
2053
2095
  }
2054
2096
  const moduleId = `${filename}.${lang}`;
2055
- const result = await transform(content, moduleId);
2056
- if (result.map?.sources?.[0] === moduleId) {
2057
- result.map.sources[0] = path10.basename(filename);
2058
- }
2097
+ const { code, map } = await transform(content, moduleId);
2098
+ mapSourcesToRelative(map, moduleId);
2059
2099
  return {
2060
- code: result.code,
2061
- map: result.map ?? void 0
2100
+ code,
2101
+ map: map ?? void 0
2062
2102
  };
2063
2103
  };
2064
2104
  style.__resolvedConfig = null;
@@ -2089,6 +2129,7 @@ function svelte(inlineOptions) {
2089
2129
  const plugins = [
2090
2130
  {
2091
2131
  name: "vite-plugin-svelte",
2132
+ // make sure our resolver runs before vite internal resolver to resolve svelte field correctly
2092
2133
  enforce: "pre",
2093
2134
  api,
2094
2135
  async config(config, configEnv) {
@@ -2227,11 +2268,7 @@ function svelte(inlineOptions) {
2227
2268
  }
2228
2269
  const svelteRequest = requestParser(ctx.file, false, ctx.timestamp);
2229
2270
  if (svelteRequest) {
2230
- try {
2231
- return handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options);
2232
- } catch (e) {
2233
- throw toRollupError(e, options);
2234
- }
2271
+ return handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options);
2235
2272
  }
2236
2273
  },
2237
2274
  async buildEnd() {