@sveltejs/vite-plugin-svelte 2.0.2 → 2.0.3

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
  };
@@ -480,6 +543,7 @@ import ${JSON.stringify(cssId)};
480
543
  compiled.js.code = makeHot({
481
544
  id: filename,
482
545
  compiledCode: compiled.js.code,
546
+ //@ts-expect-error hot isn't a boolean at this point
483
547
  hotOptions: { ...options.hot, injectCss: options.hot?.injectCss === true && hasCss },
484
548
  compiled,
485
549
  originalCode: code,
@@ -492,6 +556,7 @@ import ${JSON.stringify(cssId)};
492
556
  filename,
493
557
  normalizedFilename,
494
558
  lang: code.match(scriptLangRE)?.[1] || "js",
559
+ // @ts-ignore
495
560
  compiled,
496
561
  ssr,
497
562
  dependencies,
@@ -728,7 +793,7 @@ function findConfigToLoad(viteConfig, inlineOptions) {
728
793
 
729
794
  // src/utils/constants.ts
730
795
  var VITE_RESOLVE_MAIN_FIELDS = ["module", "jsnext:main", "jsnext"];
731
- var SVELTE_RESOLVE_MAIN_FIELDS = ["svelte", ...VITE_RESOLVE_MAIN_FIELDS];
796
+ var SVELTE_RESOLVE_MAIN_FIELDS = ["svelte"];
732
797
  var SVELTE_IMPORTS = [
733
798
  "svelte/animate",
734
799
  "svelte/easing",
@@ -752,61 +817,6 @@ import path5 from "path";
752
817
  // src/utils/esbuild.ts
753
818
  import { readFileSync } from "fs";
754
819
  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
820
  var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
811
821
  function esbuildSveltePlugin(options) {
812
822
  return {
@@ -932,6 +942,7 @@ var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
932
942
  "vite",
933
943
  "vitest",
934
944
  "__vite-browser-external"
945
+ // see https://github.com/sveltejs/vite-plugin-svelte/issues/362
935
946
  ];
936
947
  var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
937
948
  "@fontsource/",
@@ -950,6 +961,7 @@ var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
950
961
  function isCommonDepWithoutSvelteField(dependency) {
951
962
  return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
952
963
  (prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
964
+ // check prefix omitting @scope/
953
965
  );
954
966
  }
955
967
 
@@ -960,7 +972,9 @@ import { dirname } from "path";
960
972
  import { performance } from "perf_hooks";
961
973
  import { normalizePath as normalizePath2 } from "vite";
962
974
  var defaultCollectionOptions = {
975
+ // log after 500ms and more than one file processed
963
976
  logInProgress: (c, now) => now - c.collectionStart > 500 && c.stats.length > 1,
977
+ // always log results
964
978
  logResult: () => true
965
979
  };
966
980
  function humanDuration(n) {
@@ -998,7 +1012,7 @@ function formatPackageStats(pkgStats) {
998
1012
  }
999
1013
  async function getClosestNamedPackage(file) {
1000
1014
  let name = "$unknown";
1001
- let path11 = await findClosestPkgJsonPath(file, (pkgPath) => {
1015
+ let path10 = await findClosestPkgJsonPath(file, (pkgPath) => {
1002
1016
  const pkg = JSON.parse(readFileSync2(pkgPath, "utf-8"));
1003
1017
  if (pkg.name != null) {
1004
1018
  name = pkg.name;
@@ -1006,11 +1020,12 @@ async function getClosestNamedPackage(file) {
1006
1020
  }
1007
1021
  return false;
1008
1022
  });
1009
- path11 = normalizePath2(dirname(path11 ?? file)) + "/";
1010
- return { name, path: path11 };
1023
+ path10 = normalizePath2(dirname(path10 ?? file)) + "/";
1024
+ return { name, path: path10 };
1011
1025
  }
1012
1026
  var VitePluginSvelteStats = class {
1013
1027
  constructor() {
1028
+ // package directory -> package name
1014
1029
  this._packages = [];
1015
1030
  this._collections = [];
1016
1031
  }
@@ -1127,6 +1142,7 @@ var knownRootOptions = /* @__PURE__ */ new Set(["extensions", "compilerOptions",
1127
1142
  var allowedInlineOptions = /* @__PURE__ */ new Set([
1128
1143
  "configFile",
1129
1144
  "kit",
1145
+ // only for internal use by sveltekit
1130
1146
  ...allowedPluginOptions,
1131
1147
  ...knownRootOptions
1132
1148
  ]);
@@ -1226,6 +1242,7 @@ function mergeConfigs(...configs) {
1226
1242
  let result = {};
1227
1243
  for (const config of configs.filter((x) => x != null)) {
1228
1244
  result = deepmerge(result, config, {
1245
+ // replace arrays
1229
1246
  arrayMerge: (target, source) => source ?? target
1230
1247
  });
1231
1248
  }
@@ -1356,12 +1373,22 @@ function resolveViteRoot(viteConfig) {
1356
1373
  return normalizePath3(viteConfig.root ? path5.resolve(viteConfig.root) : process.cwd());
1357
1374
  }
1358
1375
  async function buildExtraViteConfig(options, config) {
1376
+ if (!config.resolve) {
1377
+ config.resolve = {};
1378
+ }
1379
+ config.resolve.mainFields = [
1380
+ ...SVELTE_RESOLVE_MAIN_FIELDS,
1381
+ ...config.resolve.mainFields ?? VITE_RESOLVE_MAIN_FIELDS
1382
+ ];
1359
1383
  const extraViteConfig = {
1360
1384
  resolve: {
1361
- mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1362
1385
  dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS],
1363
1386
  conditions: [...SVELTE_EXPORT_CONDITIONS]
1364
1387
  }
1388
+ // this option is still awaiting a PR in vite to be supported
1389
+ // see https://github.com/sveltejs/vite-plugin-svelte/issues/60
1390
+ // @ts-ignore
1391
+ // knownJsSrcExtensions: options.extensions
1365
1392
  };
1366
1393
  const extraSvelteConfig = buildExtraConfigForSvelte(config);
1367
1394
  const extraDepsConfig = await buildExtraConfigForDependencies(options, config);
@@ -1396,14 +1423,20 @@ async function buildExtraViteConfig(options, config) {
1396
1423
  if (options.prebundleSvelteLibraries) {
1397
1424
  extraViteConfig.optimizeDeps = {
1398
1425
  ...extraViteConfig.optimizeDeps,
1426
+ // Experimental Vite API to allow these extensions to be scanned and prebundled
1427
+ // @ts-ignore
1399
1428
  extensions: options.extensions ?? [".svelte"],
1429
+ // Add esbuild plugin to prebundle Svelte files.
1430
+ // Currently a placeholder as more information is needed after Vite config is resolved,
1431
+ // the real Svelte plugin is added in `patchResolvedViteConfig()`
1400
1432
  esbuildOptions: {
1401
1433
  plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1402
1434
  } }]
1403
1435
  }
1404
1436
  };
1405
1437
  }
1406
- if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && config.experimental?.hmrPartialAccept !== false) {
1438
+ if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && // deviate from svelte-hmr, default to true
1439
+ config.experimental?.hmrPartialAccept !== false) {
1407
1440
  log.debug('enabling "experimental.hmrPartialAccept" in vite config');
1408
1441
  extraViteConfig.experimental = { hmrPartialAccept: true };
1409
1442
  }
@@ -1602,7 +1635,9 @@ function setupWatchers(options, cache, requestParser) {
1602
1635
  });
1603
1636
  }
1604
1637
  function ensureWatchedFile(watcher, file, root) {
1605
- if (file && !file.startsWith(root + "/") && !file.includes("\0") && fs4.existsSync(file)) {
1638
+ if (file && // only need to watch if out of root
1639
+ !file.startsWith(root + "/") && // some rollup plugins use null bytes for private resolved Ids
1640
+ !file.includes("\0") && fs4.existsSync(file)) {
1606
1641
  watcher.add(path6.resolve(file));
1607
1642
  }
1608
1643
  }
@@ -1787,6 +1822,7 @@ import 'virtual:svelte-inspector-path:load-inspector.js'` };
1787
1822
  injectTo: "body",
1788
1823
  attrs: {
1789
1824
  type: "module",
1825
+ // /@id/ is needed, otherwise the virtual: is seen as protocol by browser and cors error happens
1790
1826
  src: "/@id/virtual:svelte-inspector-path:load-inspector.js"
1791
1827
  }
1792
1828
  }
@@ -1883,8 +1919,8 @@ var VitePluginSvelteCache = class {
1883
1919
  getError(svelteRequest) {
1884
1920
  return this._errors.get(svelteRequest.normalizedFilename);
1885
1921
  }
1886
- getDependants(path11) {
1887
- const dependants = this._dependants.get(path11);
1922
+ getDependants(path10) {
1923
+ const dependants = this._dependants.get(path10);
1888
1924
  return dependants ? [...dependants] : [];
1889
1925
  }
1890
1926
  getResolvedSvelteField(name, importer) {
@@ -1912,6 +1948,7 @@ async function loadRaw(svelteRequest, compileSvelte2, options) {
1912
1948
  const type = query.type;
1913
1949
  compileData = await compileSvelte2(svelteRequest, source, {
1914
1950
  ...options,
1951
+ // don't use dynamic vite-plugin-svelte defaults here to ensure stable result between ssr,dev and build
1915
1952
  compilerOptions: {
1916
1953
  dev: false,
1917
1954
  css: false,
@@ -1993,7 +2030,6 @@ function toRawExports(object) {
1993
2030
  }
1994
2031
 
1995
2032
  // src/preprocess.ts
1996
- import path10 from "path";
1997
2033
  import { preprocessCSS, resolveConfig, transformWithEsbuild } from "vite";
1998
2034
  var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss", "sss"];
1999
2035
  var supportedScriptLangs = ["ts"];
@@ -2014,19 +2050,21 @@ function viteScript() {
2014
2050
  const lang = attributes.lang;
2015
2051
  if (!supportedScriptLangs.includes(lang))
2016
2052
  return;
2017
- const transformResult = await transformWithEsbuild(content, filename, {
2053
+ const { code, map } = await transformWithEsbuild(content, filename, {
2018
2054
  loader: lang,
2019
2055
  target: "esnext",
2020
2056
  tsconfigRaw: {
2021
2057
  compilerOptions: {
2058
+ // svelte typescript needs this flag to work with type imports
2022
2059
  importsNotUsedAsValues: "preserve",
2023
2060
  preserveValueImports: true
2024
2061
  }
2025
2062
  }
2026
2063
  });
2064
+ mapSourcesToRelative(map, filename);
2027
2065
  return {
2028
- code: transformResult.code,
2029
- map: transformResult.map
2066
+ code,
2067
+ map
2030
2068
  };
2031
2069
  }
2032
2070
  };
@@ -2052,13 +2090,11 @@ function viteStyle(config = {}) {
2052
2090
  transform = getCssTransformFn(resolvedConfig);
2053
2091
  }
2054
2092
  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
- }
2093
+ const { code, map } = await transform(content, moduleId);
2094
+ mapSourcesToRelative(map, moduleId);
2059
2095
  return {
2060
- code: result.code,
2061
- map: result.map ?? void 0
2096
+ code,
2097
+ map: map ?? void 0
2062
2098
  };
2063
2099
  };
2064
2100
  style.__resolvedConfig = null;
@@ -2089,6 +2125,7 @@ function svelte(inlineOptions) {
2089
2125
  const plugins = [
2090
2126
  {
2091
2127
  name: "vite-plugin-svelte",
2128
+ // make sure our resolver runs before vite internal resolver to resolve svelte field correctly
2092
2129
  enforce: "pre",
2093
2130
  api,
2094
2131
  async config(config, configEnv) {
@@ -2227,11 +2264,7 @@ function svelte(inlineOptions) {
2227
2264
  }
2228
2265
  const svelteRequest = requestParser(ctx.file, false, ctx.timestamp);
2229
2266
  if (svelteRequest) {
2230
- try {
2231
- return handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options);
2232
- } catch (e) {
2233
- throw toRollupError(e, options);
2234
- }
2267
+ return handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, options);
2235
2268
  }
2236
2269
  },
2237
2270
  async buildEnd() {