@sveltejs/vite-plugin-svelte 2.0.4 → 2.1.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.
package/dist/index.d.ts CHANGED
@@ -158,11 +158,11 @@ interface ExperimentalOptions {
158
158
  */
159
159
  sendWarningsToBrowser?: boolean;
160
160
  /**
161
- * disable svelte compile statistics
161
+ * disable svelte field resolve warnings
162
162
  *
163
163
  * @default false
164
164
  */
165
- disableCompileStats?: 'dev' | 'build' | boolean;
165
+ disableSvelteResolveWarnings?: boolean;
166
166
  }
167
167
  interface InspectorOptions {
168
168
  /**
package/dist/index.js CHANGED
@@ -8,6 +8,10 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
8
8
 
9
9
  // src/index.ts
10
10
  import fs8 from "fs";
11
+ import { VERSION as svelteVersion } from "svelte/compiler";
12
+ import {
13
+ version as viteVersion
14
+ } from "vite";
11
15
  import { isDepExcluded as isDepExcluded2 } from "vitefu";
12
16
 
13
17
  // src/utils/log.ts
@@ -55,14 +59,19 @@ function setLevel(level) {
55
59
  _log(loggers.error, `invalid log level: ${level} `);
56
60
  }
57
61
  }
58
- function _log(logger, message, payload) {
62
+ function _log(logger, message, payload, namespace) {
59
63
  if (!logger.enabled) {
60
64
  return;
61
65
  }
62
66
  if (logger.isDebug) {
63
- payload !== void 0 ? logger.log(message, payload) : logger.log(message);
67
+ const log2 = namespace ? logger.log.extend(namespace) : logger.log;
68
+ payload !== void 0 ? log2(message, payload) : log2(message);
64
69
  } else {
65
- logger.log(logger.color(`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} [${prefix}] ${message}`));
70
+ logger.log(
71
+ logger.color(
72
+ `${(/* @__PURE__ */ new Date()).toLocaleTimeString()} [${prefix}${namespace ? `:${namespace}` : ""}] ${message}`
73
+ )
74
+ );
66
75
  if (payload) {
67
76
  logger.log(payload);
68
77
  }
@@ -72,12 +81,12 @@ function createLogger(level) {
72
81
  const logger = loggers[level];
73
82
  const logFn = _log.bind(null, logger);
74
83
  const logged = /* @__PURE__ */ new Set();
75
- const once = function(message, payload) {
76
- if (logged.has(message)) {
84
+ const once = function(message, payload, namespace) {
85
+ if (!logger.enabled || logged.has(message)) {
77
86
  return;
78
87
  }
79
88
  logged.add(message);
80
- logFn.apply(null, [message, payload]);
89
+ logFn.apply(null, [message, payload, namespace]);
81
90
  };
82
91
  Object.defineProperty(logFn, "enabled", {
83
92
  get() {
@@ -181,6 +190,9 @@ function buildExtendedLogMessage(w) {
181
190
  }
182
191
  return parts.join("");
183
192
  }
193
+ function isDebugNamespaceEnabled(namespace) {
194
+ return debug.enabled(`vite:${prefix}:${namespace}`);
195
+ }
184
196
 
185
197
  // src/utils/error.ts
186
198
  function toRollupError(error, options) {
@@ -425,16 +437,48 @@ function addExtraPreprocessors(options, config) {
425
437
 
426
438
  // src/utils/sourcemaps.ts
427
439
  import path2 from "path";
428
- function mapSourcesToRelative(map, filename) {
429
- if (map?.sources) {
430
- map.sources = map.sources.map((s) => {
431
- if (path2.isAbsolute(s)) {
432
- const relative = path2.relative(filename, s);
433
- return relative === "" ? path2.basename(filename) : relative;
434
- } else {
435
- return s;
436
- }
437
- });
440
+ var IS_WINDOWS = process.platform === "win32";
441
+ function mapToRelative(map, filename) {
442
+ if (!map) {
443
+ return;
444
+ }
445
+ const sourceRoot = map.sourceRoot;
446
+ const dirname2 = path2.dirname(filename);
447
+ const toRelative = (s) => {
448
+ if (!s) {
449
+ return s;
450
+ }
451
+ let sourcePath;
452
+ if (s.startsWith("file:///")) {
453
+ sourcePath = s.slice(IS_WINDOWS ? 8 : 7);
454
+ } else if (sourceRoot) {
455
+ const sep = sourceRoot[sourceRoot.length - 1] === "/" || s[0] === "/" ? "" : "/";
456
+ sourcePath = `${sourceRoot}${sep}${s}`;
457
+ } else {
458
+ sourcePath = s;
459
+ }
460
+ return path2.isAbsolute(sourcePath) ? path2.relative(dirname2, sourcePath) : sourcePath;
461
+ };
462
+ if (map.file) {
463
+ map.file = path2.basename(filename);
464
+ }
465
+ if (map.sources) {
466
+ map.sources = map.sources.map(toRelative);
467
+ }
468
+ if (map.sourceRoot) {
469
+ delete map.sourceRoot;
470
+ }
471
+ }
472
+ function removeLangSuffix(map, suffix) {
473
+ if (!map) {
474
+ return;
475
+ }
476
+ const removeSuffix = (s) => s?.endsWith(suffix) ? s.slice(0, -1 * suffix.length) : s;
477
+ if (map.file) {
478
+ map.file = removeSuffix(map.file);
479
+ }
480
+ if (map.sources) {
481
+ map.sources = map.sources.map(removeSuffix);
438
482
  }
439
483
  }
440
484
 
@@ -505,7 +549,7 @@ var _createCompileSvelte = (makeHot) => {
505
549
  compileOptions.sourcemap = preprocessed.map;
506
550
  }
507
551
  if (typeof preprocessed?.map === "object") {
508
- mapSourcesToRelative(preprocessed?.map, filename);
552
+ mapToRelative(preprocessed?.map, filename);
509
553
  }
510
554
  if (raw && svelteRequest.query.type === "preprocessed") {
511
555
  return { preprocessed: preprocessed ?? { code } };
@@ -534,8 +578,8 @@ var _createCompileSvelte = (makeHot) => {
534
578
  if (endStat) {
535
579
  endStat();
536
580
  }
537
- mapSourcesToRelative(compiled.js?.map, filename);
538
- mapSourcesToRelative(compiled.css?.map, filename);
581
+ mapToRelative(compiled.js?.map, filename);
582
+ mapToRelative(compiled.css?.map, filename);
539
583
  if (!raw) {
540
584
  const hasCss = compiled.css?.code?.trim().length > 0;
541
585
  if (emitCss && hasCss) {
@@ -591,7 +635,7 @@ import { createFilter } from "vite";
591
635
  import { normalizePath } from "vite";
592
636
  import * as fs from "fs";
593
637
  var VITE_FS_PREFIX = "/@fs/";
594
- var IS_WINDOWS = process.platform === "win32";
638
+ var IS_WINDOWS2 = process.platform === "win32";
595
639
  var SUPPORTED_COMPILER_OPTIONS = [
596
640
  "generate",
597
641
  "dev",
@@ -636,7 +680,7 @@ function createVirtualImportId(filename, root, type) {
636
680
  if (existsInRoot(filename, root)) {
637
681
  filename = root + filename;
638
682
  } else if (filename.startsWith(VITE_FS_PREFIX)) {
639
- filename = IS_WINDOWS ? filename.slice(VITE_FS_PREFIX.length) : filename.slice(VITE_FS_PREFIX.length - 1);
683
+ filename = IS_WINDOWS2 ? filename.slice(VITE_FS_PREFIX.length) : filename.slice(VITE_FS_PREFIX.length - 1);
640
684
  }
641
685
  return `${filename}?${parts.join("&")}`;
642
686
  }
@@ -814,6 +858,7 @@ var SVELTE_HMR_IMPORTS = [
814
858
  "svelte-hmr"
815
859
  ];
816
860
  var SVELTE_EXPORT_CONDITIONS = ["svelte"];
861
+ var FAQ_LINK_CONFLICTS_IN_SVELTE_RESOLVE = "https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md#conflicts-in-svelte-resolve";
817
862
 
818
863
  // src/utils/options.ts
819
864
  import path5 from "path";
@@ -970,9 +1015,6 @@ function isCommonDepWithoutSvelteField(dependency) {
970
1015
  }
971
1016
 
972
1017
  // src/utils/vite-plugin-svelte-stats.ts
973
- import { findClosestPkgJsonPath } from "vitefu";
974
- import { readFileSync as readFileSync2 } from "fs";
975
- import { dirname } from "path";
976
1018
  import { performance } from "perf_hooks";
977
1019
  import { normalizePath as normalizePath2 } from "vite";
978
1020
  var defaultCollectionOptions = {
@@ -1014,24 +1056,10 @@ function formatPackageStats(pkgStats) {
1014
1056
  ).join("\n");
1015
1057
  return table;
1016
1058
  }
1017
- async function getClosestNamedPackage(file) {
1018
- let name = "$unknown";
1019
- let path10 = await findClosestPkgJsonPath(file, (pkgPath) => {
1020
- const pkg = JSON.parse(readFileSync2(pkgPath, "utf-8"));
1021
- if (pkg.name != null) {
1022
- name = pkg.name;
1023
- return true;
1024
- }
1025
- return false;
1026
- });
1027
- path10 = normalizePath2(dirname(path10 ?? file)) + "/";
1028
- return { name, path: path10 };
1029
- }
1030
1059
  var VitePluginSvelteStats = class {
1031
- constructor() {
1032
- // package directory -> package name
1033
- this._packages = [];
1060
+ constructor(cache) {
1034
1061
  this._collections = [];
1062
+ this._cache = cache;
1035
1063
  }
1036
1064
  startCollection(name, opts) {
1037
1065
  const options = {
@@ -1061,7 +1089,7 @@ var VitePluginSvelteStats = class {
1061
1089
  stats.push(stat);
1062
1090
  if (!hasLoggedProgress && options.logInProgress(collection, now)) {
1063
1091
  hasLoggedProgress = true;
1064
- log.info(`${name} in progress ...`);
1092
+ log.debug(`${name} in progress ...`, void 0, "stats");
1065
1093
  }
1066
1094
  };
1067
1095
  },
@@ -1083,7 +1111,12 @@ var VitePluginSvelteStats = class {
1083
1111
  const logResult = collection.options.logResult(collection);
1084
1112
  if (logResult) {
1085
1113
  await this._aggregateStatsResult(collection);
1086
- log.info(`${collection.name} done.`, formatPackageStats(collection.packageStats));
1114
+ log.debug(
1115
+ `${collection.name} done.
1116
+ ${formatPackageStats(collection.packageStats)}`,
1117
+ void 0,
1118
+ "stats"
1119
+ );
1087
1120
  }
1088
1121
  const index = this._collections.indexOf(collection);
1089
1122
  this._collections.splice(index, 1);
@@ -1098,18 +1131,14 @@ var VitePluginSvelteStats = class {
1098
1131
  collection.finish = () => {
1099
1132
  };
1100
1133
  } catch (e) {
1101
- log.debug.once(`failed to finish stats for ${collection.name}`, e);
1134
+ log.debug.once(`failed to finish stats for ${collection.name}
1135
+ `, e, "stats");
1102
1136
  }
1103
1137
  }
1104
1138
  async _aggregateStatsResult(collection) {
1105
1139
  const stats = collection.stats;
1106
1140
  for (const stat of stats) {
1107
- let pkg = this._packages.find((p) => stat.file.startsWith(p.path));
1108
- if (!pkg) {
1109
- pkg = await getClosestNamedPackage(stat.file);
1110
- this._packages.push(pkg);
1111
- }
1112
- stat.pkg = pkg.name;
1141
+ stat.pkg = (await this._cache.getPackageInfo(stat.file)).name;
1113
1142
  }
1114
1143
  const grouped = {};
1115
1144
  stats.forEach((stat) => {
@@ -1252,7 +1281,7 @@ function mergeConfigs(...configs) {
1252
1281
  }
1253
1282
  return result;
1254
1283
  }
1255
- function resolveOptions(preResolveOptions2, viteConfig) {
1284
+ function resolveOptions(preResolveOptions2, viteConfig, cache) {
1256
1285
  const css = preResolveOptions2.emitCss ? "external" : "injected";
1257
1286
  const defaultOptions = {
1258
1287
  hot: viteConfig.isProduction ? false : {
@@ -1275,11 +1304,8 @@ function resolveOptions(preResolveOptions2, viteConfig) {
1275
1304
  addExtraPreprocessors(merged, viteConfig);
1276
1305
  enforceOptionsForHmr(merged);
1277
1306
  enforceOptionsForProduction(merged);
1278
- const isLogLevelInfo = [void 0, "info"].includes(viteConfig.logLevel);
1279
- const disableCompileStats = merged.experimental?.disableCompileStats;
1280
- const statsEnabled = disableCompileStats !== true && disableCompileStats !== (merged.isBuild ? "build" : "dev");
1281
- if (statsEnabled && isLogLevelInfo) {
1282
- merged.stats = new VitePluginSvelteStats();
1307
+ if (log.debug.enabled && isDebugNamespaceEnabled("stats")) {
1308
+ merged.stats = new VitePluginSvelteStats(cache);
1283
1309
  }
1284
1310
  return merged;
1285
1311
  }
@@ -1726,12 +1752,12 @@ import fs6 from "fs";
1726
1752
 
1727
1753
  // src/ui/inspector/utils.ts
1728
1754
  var FS_PREFIX = `/@fs/`;
1729
- var IS_WINDOWS2 = process.platform === "win32";
1755
+ var IS_WINDOWS3 = process.platform === "win32";
1730
1756
  var queryRE = /\?.*$/s;
1731
1757
  var hashRE = /#.*$/s;
1732
1758
  function idToFile(id) {
1733
1759
  if (id.startsWith(FS_PREFIX)) {
1734
- id = id = id.slice(IS_WINDOWS2 ? FS_PREFIX.length : FS_PREFIX.length - 1);
1760
+ id = id = id.slice(IS_WINDOWS3 ? FS_PREFIX.length : FS_PREFIX.length - 1);
1735
1761
  }
1736
1762
  return id.replace(hashRE, "").replace(queryRE, "");
1737
1763
  }
@@ -1837,6 +1863,10 @@ import 'virtual:svelte-inspector-path:load-inspector.js'` };
1837
1863
  }
1838
1864
 
1839
1865
  // src/utils/vite-plugin-svelte-cache.ts
1866
+ import { readFileSync as readFileSync2 } from "fs";
1867
+ import { dirname } from "path";
1868
+ import { findClosestPkgJsonPath } from "vitefu";
1869
+ import { normalizePath as normalizePath5 } from "vite";
1840
1870
  var VitePluginSvelteCache = class {
1841
1871
  constructor() {
1842
1872
  this._css = /* @__PURE__ */ new Map();
@@ -1845,6 +1875,7 @@ var VitePluginSvelteCache = class {
1845
1875
  this._dependants = /* @__PURE__ */ new Map();
1846
1876
  this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1847
1877
  this._errors = /* @__PURE__ */ new Map();
1878
+ this._packageInfos = [];
1848
1879
  }
1849
1880
  update(compileData) {
1850
1881
  this._errors.delete(compileData.normalizedFilename);
@@ -1930,6 +1961,9 @@ var VitePluginSvelteCache = class {
1930
1961
  getResolvedSvelteField(name, importer) {
1931
1962
  return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
1932
1963
  }
1964
+ hasResolvedSvelteField(name, importer) {
1965
+ return this._resolvedSvelteFields.has(this._getResolvedSvelteFieldKey(name, importer));
1966
+ }
1933
1967
  setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
1934
1968
  this._resolvedSvelteFields.set(
1935
1969
  this._getResolvedSvelteFieldKey(importee, importer),
@@ -1939,7 +1973,37 @@ var VitePluginSvelteCache = class {
1939
1973
  _getResolvedSvelteFieldKey(importee, importer) {
1940
1974
  return importer ? `${importer} > ${importee}` : importee;
1941
1975
  }
1976
+ async getPackageInfo(file) {
1977
+ let info = this._packageInfos.find((pi) => file.startsWith(pi.path));
1978
+ if (!info) {
1979
+ info = await findPackageInfo(file);
1980
+ this._packageInfos.push(info);
1981
+ }
1982
+ return info;
1983
+ }
1942
1984
  };
1985
+ async function findPackageInfo(file) {
1986
+ const info = {
1987
+ name: "$unknown",
1988
+ version: "0.0.0-unknown",
1989
+ path: "$unknown"
1990
+ };
1991
+ let path10 = await findClosestPkgJsonPath(file, (pkgPath) => {
1992
+ const pkg = JSON.parse(readFileSync2(pkgPath, "utf-8"));
1993
+ if (pkg.name != null) {
1994
+ info.name = pkg.name;
1995
+ if (pkg.version != null) {
1996
+ info.version = pkg.version;
1997
+ }
1998
+ info.svelte = pkg.svelte;
1999
+ return true;
2000
+ }
2001
+ return false;
2002
+ });
2003
+ path10 = normalizePath5(dirname(path10 ?? file)) + "/";
2004
+ info.path = path10;
2005
+ return info;
2006
+ }
1943
2007
 
1944
2008
  // src/utils/load-raw.ts
1945
2009
  import fs7 from "fs";
@@ -2037,6 +2101,7 @@ function toRawExports(object) {
2037
2101
  import { preprocessCSS, resolveConfig, transformWithEsbuild } from "vite";
2038
2102
  var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss", "sss"];
2039
2103
  var supportedScriptLangs = ["ts"];
2104
+ var lang_sep = ".vite-preprocess.";
2040
2105
  function vitePreprocess(opts) {
2041
2106
  const preprocessor = {};
2042
2107
  if (opts?.script !== false) {
@@ -2065,7 +2130,7 @@ function viteScript() {
2065
2130
  }
2066
2131
  }
2067
2132
  });
2068
- mapSourcesToRelative(map, filename);
2133
+ mapToRelative(map, filename);
2069
2134
  return {
2070
2135
  code,
2071
2136
  map
@@ -2093,12 +2158,16 @@ function viteStyle(config = {}) {
2093
2158
  }
2094
2159
  transform = getCssTransformFn(resolvedConfig);
2095
2160
  }
2096
- const moduleId = `${filename}.${lang}`;
2097
- const { code, map } = await transform(content, moduleId);
2098
- mapSourcesToRelative(map, moduleId);
2161
+ const suffix = `${lang_sep}${lang}`;
2162
+ const moduleId = `${filename}${suffix}`;
2163
+ const { code, map, deps } = await transform(content, moduleId);
2164
+ removeLangSuffix(map, suffix);
2165
+ mapToRelative(map, filename);
2166
+ const dependencies = deps ? Array.from(deps).filter((d) => !d.endsWith(suffix)) : void 0;
2099
2167
  return {
2100
2168
  code,
2101
- map: map ?? void 0
2169
+ map: map ?? void 0,
2170
+ dependencies
2102
2171
  };
2103
2172
  };
2104
2173
  style.__resolvedConfig = null;
@@ -2114,6 +2183,8 @@ function isResolvedConfig(config) {
2114
2183
  }
2115
2184
 
2116
2185
  // src/index.ts
2186
+ var isVite4_0 = viteVersion.startsWith("4.0");
2187
+ var isSvelte3 = svelteVersion.startsWith("3");
2117
2188
  function svelte(inlineOptions) {
2118
2189
  if (process.env.DEBUG != null) {
2119
2190
  log.setLevel("debug");
@@ -2125,6 +2196,7 @@ function svelte(inlineOptions) {
2125
2196
  let viteConfig;
2126
2197
  let compileSvelte2;
2127
2198
  let resolvedSvelteSSR;
2199
+ let packagesWithResolveWarnings;
2128
2200
  const api = {};
2129
2201
  const plugins = [
2130
2202
  {
@@ -2144,7 +2216,7 @@ function svelte(inlineOptions) {
2144
2216
  return extraViteConfig;
2145
2217
  },
2146
2218
  async configResolved(config) {
2147
- options = resolveOptions(options, config);
2219
+ options = resolveOptions(options, config, cache);
2148
2220
  patchResolvedViteConfig(config, options);
2149
2221
  requestParser = buildIdParser(options);
2150
2222
  compileSvelte2 = createCompileSvelte(options);
@@ -2153,6 +2225,7 @@ function svelte(inlineOptions) {
2153
2225
  log.debug("resolved options", options);
2154
2226
  },
2155
2227
  async buildStart() {
2228
+ packagesWithResolveWarnings = /* @__PURE__ */ new Set();
2156
2229
  if (!options.prebundleSvelteLibraries)
2157
2230
  return;
2158
2231
  const isSvelteMetadataChanged = await saveSvelteMetadata(viteConfig.cacheDir, options);
@@ -2195,7 +2268,7 @@ function svelte(inlineOptions) {
2195
2268
  return svelteRequest.cssId;
2196
2269
  }
2197
2270
  }
2198
- if (ssr && importee === "svelte") {
2271
+ if (isVite4_0 && isSvelte3 && ssr && importee === "svelte") {
2199
2272
  if (!resolvedSvelteSSR) {
2200
2273
  resolvedSvelteSSR = this.resolve("svelte/ssr", void 0, { skipSelf: true }).then(
2201
2274
  (svelteSSR) => {
@@ -2217,13 +2290,31 @@ function svelte(inlineOptions) {
2217
2290
  const isPrebundled = options.prebundleSvelteLibraries && viteConfig.optimizeDeps?.disabled !== true && viteConfig.optimizeDeps?.disabled !== (options.isBuild ? "build" : "dev") && !isDepExcluded2(importee, viteConfig.optimizeDeps?.exclude ?? []);
2218
2291
  if (ssr || scan || !isPrebundled) {
2219
2292
  try {
2293
+ const isFirstResolve = !cache.hasResolvedSvelteField(importee, importer);
2220
2294
  const resolved = await resolveViaPackageJsonSvelte(importee, importer, cache);
2221
- if (resolved) {
2222
- log.debug(
2223
- `resolveId resolved ${resolved} via package.json svelte field of ${importee}`
2295
+ if (isFirstResolve && resolved) {
2296
+ const packageInfo = await cache.getPackageInfo(resolved);
2297
+ const packageVersion = `${packageInfo.name}@${packageInfo.version}`;
2298
+ log.debug.once(
2299
+ `resolveId resolved ${importee} to ${resolved} via package.json svelte field of ${packageVersion}`
2224
2300
  );
2225
- return resolved;
2301
+ try {
2302
+ const viteResolved = (await this.resolve(importee, importer, { ...opts, skipSelf: true }))?.id;
2303
+ if (resolved !== viteResolved) {
2304
+ packagesWithResolveWarnings.add(packageVersion);
2305
+ log.debug.enabled && log.debug.once(
2306
+ `resolve difference for ${packageVersion} ${importee} - svelte: "${resolved}", vite: "${viteResolved}"`
2307
+ );
2308
+ }
2309
+ } catch (e) {
2310
+ packagesWithResolveWarnings.add(packageVersion);
2311
+ log.debug.enabled && log.debug.once(
2312
+ `resolve error for ${packageVersion} ${importee} - svelte: "${resolved}", vite: ERROR`,
2313
+ e
2314
+ );
2315
+ }
2226
2316
  }
2317
+ return resolved;
2227
2318
  } catch (e) {
2228
2319
  log.debug.once(
2229
2320
  `error trying to resolve ${importee} from ${importer} via package.json svelte field `,
@@ -2273,6 +2364,17 @@ function svelte(inlineOptions) {
2273
2364
  },
2274
2365
  async buildEnd() {
2275
2366
  await options.stats?.finishAll();
2367
+ if (!options.experimental?.disableSvelteResolveWarnings && packagesWithResolveWarnings?.size > 0) {
2368
+ log.warn(
2369
+ `WARNING: The following packages use a svelte resolve configuration in package.json that has conflicting results and is going to cause problems future.
2370
+
2371
+ ${[
2372
+ ...packagesWithResolveWarnings
2373
+ ].join("\n")}
2374
+
2375
+ Please see ${FAQ_LINK_CONFLICTS_IN_SVELTE_RESOLVE} for details.`
2376
+ );
2377
+ }
2276
2378
  }
2277
2379
  }
2278
2380
  ];