@sveltejs/vite-plugin-svelte 1.0.0-next.33 → 1.0.0-next.37

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
@@ -89,7 +89,7 @@ function _log(logger, message, payload) {
89
89
  function createLogger(level) {
90
90
  const logger = loggers[level];
91
91
  const logFn = _log.bind(null, logger);
92
- const logged = new Set();
92
+ const logged = /* @__PURE__ */ new Set();
93
93
  const once = function(message, payload) {
94
94
  if (logged.has(message)) {
95
95
  return;
@@ -164,7 +164,10 @@ function buildExtendedLogMessage(w) {
164
164
  parts.push(":", w.start.line, ":", w.start.column);
165
165
  }
166
166
  if (w.message) {
167
- parts.push(" ", w.message);
167
+ if (parts.length > 0) {
168
+ parts.push(" ");
169
+ }
170
+ parts.push(w.message);
168
171
  }
169
172
  return parts.join("");
170
173
  }
@@ -181,7 +184,7 @@ async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, option
181
184
  const content = await read();
182
185
  const compileData = await compileSvelte2(svelteRequest, content, options);
183
186
  cache.update(compileData);
184
- const affectedModules = new Set();
187
+ const affectedModules = /* @__PURE__ */ new Set();
185
188
  const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId);
186
189
  const mainModule = server.moduleGraph.getModuleById(svelteRequest.id);
187
190
  const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css);
@@ -245,16 +248,14 @@ import { compile, preprocess, walk } from "svelte/compiler";
245
248
  import { createMakeHot } from "svelte-hmr";
246
249
 
247
250
  // src/utils/hash.ts
248
- import {
249
- createHash
250
- } from "crypto";
251
- var hashes = Object.create(null);
251
+ import * as crypto from "crypto";
252
+ var hashes = /* @__PURE__ */ Object.create(null);
252
253
  var hash_length = 12;
253
254
  function safeBase64Hash(input) {
254
255
  if (hashes[input]) {
255
256
  return hashes[input];
256
257
  }
257
- const md5 = createHash("md5");
258
+ const md5 = crypto.createHash("md5");
258
259
  md5.update(input);
259
260
  const hash = toSafe(md5.digest("base64")).substr(0, hash_length);
260
261
  hashes[input] = hash;
@@ -294,7 +295,12 @@ var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequ
294
295
  }
295
296
  let preprocessed;
296
297
  if (options.preprocess) {
297
- preprocessed = await preprocess(code, options.preprocess, { filename });
298
+ try {
299
+ preprocessed = await preprocess(code, options.preprocess, { filename });
300
+ } catch (e) {
301
+ e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
302
+ throw e;
303
+ }
298
304
  if (preprocessed.dependencies)
299
305
  dependencies.push(...preprocessed.dependencies);
300
306
  if (preprocessed.map)
@@ -357,9 +363,7 @@ function createCompileSvelte(options) {
357
363
  // src/utils/id.ts
358
364
  import { createFilter } from "@rollup/pluginutils";
359
365
  import { normalizePath } from "vite";
360
- import {
361
- existsSync
362
- } from "fs";
366
+ import * as fs from "fs";
363
367
  var VITE_FS_PREFIX = "/@fs/";
364
368
  var IS_WINDOWS = process.platform === "win32";
365
369
  function splitId(id) {
@@ -413,7 +417,7 @@ function existsInRoot(filename, root) {
413
417
  if (filename.startsWith(VITE_FS_PREFIX)) {
414
418
  return false;
415
419
  }
416
- return existsSync(root + filename);
420
+ return fs.existsSync(root + filename);
417
421
  }
418
422
  function stripRoot(normalizedFilename, normalizedRoot) {
419
423
  return normalizedFilename.startsWith(normalizedRoot + "/") ? normalizedFilename.slice(normalizedRoot.length) : normalizedFilename;
@@ -562,7 +566,7 @@ function findRootSvelteDependencies(root, cwdFallback = true) {
562
566
  ].filter((dep) => !is_common_without_svelte_field(dep));
563
567
  return getSvelteDependencies(deps, root);
564
568
  }
565
- function getSvelteDependencies(deps, pkgDir, path6 = []) {
569
+ function getSvelteDependencies(deps, pkgDir, path7 = []) {
566
570
  const result = [];
567
571
  const localRequire = createRequire2(`${pkgDir}/package.json`);
568
572
  const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
@@ -570,18 +574,18 @@ function getSvelteDependencies(deps, pkgDir, path6 = []) {
570
574
  const type = getSvelteDependencyType(pkg);
571
575
  if (!type)
572
576
  continue;
573
- result.push({ name: pkg.name, type, pkg, dir, path: path6 });
577
+ result.push({ name: pkg.name, type, pkg, dir, path: path7 });
574
578
  if (type === "component-library" && pkg.dependencies) {
575
579
  let dependencyNames = Object.keys(pkg.dependencies);
576
- const circular = dependencyNames.filter((name) => path6.includes(name));
580
+ const circular = dependencyNames.filter((name) => path7.includes(name));
577
581
  if (circular.length > 0) {
578
- log.warn.enabled && log.warn(`skipping circular svelte dependencies in automated vite optimizeDeps handling`, circular.map((x) => path6.concat(x).join(">")));
579
- dependencyNames = dependencyNames.filter((name) => !path6.includes(name));
582
+ log.warn.enabled && log.warn(`skipping circular svelte dependencies in automated vite optimizeDeps handling`, circular.map((x) => path7.concat(x).join(">")));
583
+ dependencyNames = dependencyNames.filter((name) => !path7.includes(name));
580
584
  }
581
- if (path6.length === 3) {
582
- log.debug.once(`encountered deep svelte dependency tree: ${path6.join(">")}`);
585
+ if (path7.length === 3) {
586
+ log.debug.once(`encountered deep svelte dependency tree: ${path7.join(">")}`);
583
587
  }
584
- result.push(...getSvelteDependencies(dependencyNames, dir, path6.concat(pkg.name)));
588
+ result.push(...getSvelteDependencies(dependencyNames, dir, path7.concat(pkg.name)));
585
589
  }
586
590
  }
587
591
  return result;
@@ -695,15 +699,15 @@ import { promises as fs4 } from "fs";
695
699
  import { compile as compile2, preprocess as preprocess2 } from "svelte/compiler";
696
700
 
697
701
  // src/utils/error.ts
698
- function toRollupError(error) {
699
- const { filename, frame, start, code, name } = error;
702
+ function toRollupError(error, options) {
703
+ const { filename, frame, start, code, name, stack } = error;
700
704
  const rollupError = {
701
705
  name,
702
706
  id: filename,
703
707
  message: buildExtendedLogMessage(error),
704
708
  frame: formatFrameForVite(frame),
705
709
  code,
706
- stack: ""
710
+ stack: options.isBuild || options.isDebug || !frame ? stack : ""
707
711
  };
708
712
  if (start) {
709
713
  rollupError.loc = {
@@ -714,8 +718,8 @@ function toRollupError(error) {
714
718
  }
715
719
  return rollupError;
716
720
  }
717
- function toESBuildError(error) {
718
- const { filename, frame, start } = error;
721
+ function toESBuildError(error, options) {
722
+ const { filename, frame, start, stack } = error;
719
723
  const partialMessage = {
720
724
  text: buildExtendedLogMessage(error)
721
725
  };
@@ -727,6 +731,9 @@ function toESBuildError(error) {
727
731
  lineText: lineFromFrame(start.line, frame)
728
732
  };
729
733
  }
734
+ if (options.isBuild || options.isDebug || !frame) {
735
+ partialMessage.detail = stack;
736
+ }
730
737
  return partialMessage;
731
738
  }
732
739
  function lineFromFrame(lineNo, frame) {
@@ -759,7 +766,7 @@ function esbuildSveltePlugin(options) {
759
766
  const contents = await compileSvelte(options, { filename, code });
760
767
  return { contents };
761
768
  } catch (e) {
762
- return { errors: [toESBuildError(e)] };
769
+ return { errors: [toESBuildError(e, options)] };
763
770
  }
764
771
  });
765
772
  }
@@ -792,7 +799,12 @@ async function compileSvelte(options, { filename, code }) {
792
799
  });
793
800
  let preprocessed;
794
801
  if (options.preprocess) {
795
- preprocessed = await preprocess2(code, options.preprocess, { filename });
802
+ try {
803
+ preprocessed = await preprocess2(code, options.preprocess, { filename });
804
+ } catch (e) {
805
+ e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
806
+ throw e;
807
+ }
796
808
  if (preprocessed.map)
797
809
  compileOptions.sourcemap = preprocessed.map;
798
810
  }
@@ -875,7 +887,8 @@ function createViteScriptPreprocessor() {
875
887
  loader: lang,
876
888
  tsconfigRaw: {
877
889
  compilerOptions: {
878
- importsNotUsedAsValues: "preserve"
890
+ importsNotUsedAsValues: "preserve",
891
+ preserveValueImports: true
879
892
  }
880
893
  }
881
894
  });
@@ -1039,7 +1052,7 @@ function validateSourceMapOutputWrapper(group, i) {
1039
1052
  }
1040
1053
 
1041
1054
  // src/utils/options.ts
1042
- var knownOptions = new Set([
1055
+ var knownOptions = /* @__PURE__ */ new Set([
1043
1056
  "configFile",
1044
1057
  "include",
1045
1058
  "exclude",
@@ -1076,7 +1089,8 @@ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1076
1089
  experimental: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.experimental), svelteConfig == null ? void 0 : svelteConfig.experimental), inlineOptions == null ? void 0 : inlineOptions.experimental),
1077
1090
  root: viteConfigWithResolvedRoot.root,
1078
1091
  isBuild: viteEnv.command === "build",
1079
- isServe: viteEnv.command === "serve"
1092
+ isServe: viteEnv.command === "serve",
1093
+ isDebug: process.env.DEBUG != null
1080
1094
  });
1081
1095
  if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
1082
1096
  merged.configFile = svelteConfig.configFile;
@@ -1093,6 +1107,7 @@ function resolveOptions(preResolveOptions2, viteConfig) {
1093
1107
  };
1094
1108
  const merged = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), preResolveOptions2), {
1095
1109
  compilerOptions: __spreadValues(__spreadValues({}, defaultOptions.compilerOptions), preResolveOptions2.compilerOptions),
1110
+ root: viteConfig.root,
1096
1111
  isProduction: viteConfig.isProduction
1097
1112
  });
1098
1113
  addExtraPreprocessors(merged, viteConfig);
@@ -1160,16 +1175,16 @@ function buildExtraViteConfig(options, config, configEnv) {
1160
1175
  extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config);
1161
1176
  return extraViteConfig;
1162
1177
  }
1163
- function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
1178
+ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps2) {
1164
1179
  const include = [];
1165
1180
  const exclude = ["svelte-hmr"];
1166
1181
  const isIncluded = (dep) => {
1167
1182
  var _a;
1168
- return include.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a.includes(dep));
1183
+ return include.includes(dep) || ((_a = optimizeDeps2 == null ? void 0 : optimizeDeps2.include) == null ? void 0 : _a.includes(dep));
1169
1184
  };
1170
1185
  const isExcluded = (dep) => {
1171
1186
  var _a;
1172
- return exclude.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
1187
+ return exclude.includes(dep) || ((_a = optimizeDeps2 == null ? void 0 : optimizeDeps2.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
1173
1188
  };
1174
1189
  if (!isExcluded("svelte")) {
1175
1190
  const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
@@ -1235,10 +1250,11 @@ function patchResolvedViteConfig(viteConfig, options) {
1235
1250
  // src/utils/vite-plugin-svelte-cache.ts
1236
1251
  var VitePluginSvelteCache = class {
1237
1252
  constructor() {
1238
- this._css = new Map();
1239
- this._js = new Map();
1240
- this._dependencies = new Map();
1241
- this._dependants = new Map();
1253
+ this._css = /* @__PURE__ */ new Map();
1254
+ this._js = /* @__PURE__ */ new Map();
1255
+ this._dependencies = /* @__PURE__ */ new Map();
1256
+ this._dependants = /* @__PURE__ */ new Map();
1257
+ this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1242
1258
  }
1243
1259
  update(compileData) {
1244
1260
  this.updateCSS(compileData);
@@ -1262,7 +1278,7 @@ var VitePluginSvelteCache = class {
1262
1278
  const added = dependencies.filter((d) => !prevDependencies.includes(d));
1263
1279
  added.forEach((d) => {
1264
1280
  if (!this._dependants.has(d)) {
1265
- this._dependants.set(d, new Set());
1281
+ this._dependants.set(d, /* @__PURE__ */ new Set());
1266
1282
  }
1267
1283
  this._dependants.get(d).add(compileData.filename);
1268
1284
  });
@@ -1300,10 +1316,19 @@ var VitePluginSvelteCache = class {
1300
1316
  return this._js.get(svelteRequest.normalizedFilename);
1301
1317
  }
1302
1318
  }
1303
- getDependants(path6) {
1304
- const dependants = this._dependants.get(path6);
1319
+ getDependants(path7) {
1320
+ const dependants = this._dependants.get(path7);
1305
1321
  return dependants ? [...dependants] : [];
1306
1322
  }
1323
+ getResolvedSvelteField(name, importer) {
1324
+ return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
1325
+ }
1326
+ setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
1327
+ this._resolvedSvelteFields.set(this._getResolvedSvelteFieldKey(importee, importer), resolvedSvelte);
1328
+ }
1329
+ _getResolvedSvelteFieldKey(importee, importer) {
1330
+ return importer ? `${importer} > ${importee}` : importee;
1331
+ }
1307
1332
  };
1308
1333
 
1309
1334
  // src/utils/watch.ts
@@ -1335,7 +1360,6 @@ function setupWatchers(options, cache, requestParser) {
1335
1360
  }
1336
1361
  };
1337
1362
  const triggerViteRestart = (filename) => {
1338
- var _a;
1339
1363
  if (serverConfig.middlewareMode) {
1340
1364
  const message = "Svelte config change detected, restart your dev process to apply the changes.";
1341
1365
  log.info(message, filename);
@@ -1345,7 +1369,7 @@ function setupWatchers(options, cache, requestParser) {
1345
1369
  });
1346
1370
  } else {
1347
1371
  log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1348
- server.restart(!!((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries));
1372
+ server.restart();
1349
1373
  }
1350
1374
  };
1351
1375
  const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => path4.join(root, cfg));
@@ -1384,17 +1408,30 @@ function ensureWatchedFile(watcher, file, root) {
1384
1408
 
1385
1409
  // src/utils/resolve.ts
1386
1410
  import path5 from "path";
1387
- import fs6 from "fs";
1388
- import relative from "require-relative";
1389
- function resolveViaPackageJsonSvelte(importee, importer) {
1390
- if (importer && isBareImport(importee)) {
1391
- const importeePkgFile = relative.resolve(`${importee}/package.json`, path5.dirname(importer));
1392
- const importeePkg = JSON.parse(fs6.readFileSync(importeePkgFile, { encoding: "utf-8" }));
1393
- if (importeePkg.svelte) {
1394
- return path5.resolve(path5.dirname(importeePkgFile), importeePkg.svelte);
1411
+ import { builtinModules, createRequire as createRequire4 } from "module";
1412
+ function resolveViaPackageJsonSvelte(importee, importer, cache) {
1413
+ if (importer && isBareImport(importee) && !isNodeInternal(importee) && !is_common_without_svelte_field(importee)) {
1414
+ const cached = cache.getResolvedSvelteField(importee, importer);
1415
+ if (cached) {
1416
+ return cached;
1417
+ }
1418
+ const localRequire = createRequire4(importer);
1419
+ const pkgData = resolveDependencyData(importee, localRequire);
1420
+ if (pkgData) {
1421
+ const { pkg, dir } = pkgData;
1422
+ if (pkg.svelte) {
1423
+ const result = path5.resolve(dir, pkg.svelte);
1424
+ cache.setResolvedSvelteField(importee, importer, result);
1425
+ return result;
1426
+ }
1427
+ } else {
1428
+ throw new Error(`failed to resolve package.json of ${importee} imported by ${importer}`);
1395
1429
  }
1396
1430
  }
1397
1431
  }
1432
+ function isNodeInternal(importee) {
1433
+ return importee.startsWith("node:") || builtinModules.includes(importee);
1434
+ }
1398
1435
  function isBareImport(importee) {
1399
1436
  if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || path5.isAbsolute(importee)) {
1400
1437
  return false;
@@ -1410,6 +1447,44 @@ function isBareImport(importee) {
1410
1447
  }
1411
1448
  }
1412
1449
 
1450
+ // src/utils/optimizer.ts
1451
+ import fs6 from "fs";
1452
+ import path6 from "path";
1453
+ import { optimizeDeps } from "vite";
1454
+ var PREBUNDLE_SENSITIVE_OPTIONS = [
1455
+ "compilerOptions",
1456
+ "configFile",
1457
+ "experimental",
1458
+ "extensions",
1459
+ "ignorePluginPreprocessors",
1460
+ "preprocess"
1461
+ ];
1462
+ async function handleOptimizeDeps(options, viteConfig) {
1463
+ if (!options.experimental.prebundleSvelteLibraries || !viteConfig.cacheDir)
1464
+ return;
1465
+ const viteMetadataPath = path6.resolve(viteConfig.cacheDir, "_metadata.json");
1466
+ if (!fs6.existsSync(viteMetadataPath))
1467
+ return;
1468
+ const svelteMetadataPath = path6.resolve(viteConfig.cacheDir, "_svelte_metadata.json");
1469
+ const currentSvelteMetadata = JSON.stringify(generateSvelteMetadata(options), (_, value) => {
1470
+ return typeof value === "function" ? value.toString() : value;
1471
+ });
1472
+ if (fs6.existsSync(svelteMetadataPath)) {
1473
+ const existingSvelteMetadata = fs6.readFileSync(svelteMetadataPath, "utf8");
1474
+ if (existingSvelteMetadata === currentSvelteMetadata)
1475
+ return;
1476
+ }
1477
+ await optimizeDeps(viteConfig, true);
1478
+ fs6.writeFileSync(svelteMetadataPath, currentSvelteMetadata);
1479
+ }
1480
+ function generateSvelteMetadata(options) {
1481
+ const metadata = {};
1482
+ for (const key of PREBUNDLE_SENSITIVE_OPTIONS) {
1483
+ metadata[key] = options[key];
1484
+ }
1485
+ return metadata;
1486
+ }
1487
+
1413
1488
  // src/index.ts
1414
1489
  function svelte(inlineOptions) {
1415
1490
  if (process.env.DEBUG != null) {
@@ -1417,7 +1492,7 @@ function svelte(inlineOptions) {
1417
1492
  }
1418
1493
  validateInlineOptions(inlineOptions);
1419
1494
  const cache = new VitePluginSvelteCache();
1420
- const pkg_export_errors = new Set();
1495
+ const pkg_resolve_errors = /* @__PURE__ */ new Set();
1421
1496
  let requestParser;
1422
1497
  let options;
1423
1498
  let viteConfig;
@@ -1445,6 +1520,9 @@ function svelte(inlineOptions) {
1445
1520
  viteConfig = config;
1446
1521
  log.debug("resolved options", options);
1447
1522
  },
1523
+ async buildStart() {
1524
+ await handleOptimizeDeps(options, viteConfig);
1525
+ },
1448
1526
  configureServer(server) {
1449
1527
  options.server = server;
1450
1528
  setupWatchers(options, cache, requestParser);
@@ -1491,21 +1569,13 @@ function svelte(inlineOptions) {
1491
1569
  return resolvedSvelteSSR;
1492
1570
  }
1493
1571
  try {
1494
- const resolved = resolveViaPackageJsonSvelte(importee, importer);
1572
+ const resolved = resolveViaPackageJsonSvelte(importee, importer, cache);
1495
1573
  if (resolved) {
1496
1574
  log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`);
1497
1575
  return resolved;
1498
1576
  }
1499
1577
  } catch (err) {
1500
- switch (err.code) {
1501
- case "ERR_PACKAGE_PATH_NOT_EXPORTED":
1502
- pkg_export_errors.add(importee);
1503
- return null;
1504
- case "MODULE_NOT_FOUND":
1505
- return null;
1506
- default:
1507
- throw err;
1508
- }
1578
+ pkg_resolve_errors.add(importee);
1509
1579
  }
1510
1580
  },
1511
1581
  async transform(code, id, opts) {
@@ -1531,7 +1601,7 @@ function svelte(inlineOptions) {
1531
1601
  try {
1532
1602
  compileData = await compileSvelte2(svelteRequest, code, options);
1533
1603
  } catch (e) {
1534
- throw toRollupError(e);
1604
+ throw toRollupError(e, options);
1535
1605
  }
1536
1606
  logCompilerWarnings(compileData.compiled.warnings, options);
1537
1607
  cache.update(compileData);
@@ -1553,8 +1623,10 @@ function svelte(inlineOptions) {
1553
1623
  }
1554
1624
  },
1555
1625
  buildEnd() {
1556
- if (pkg_export_errors.size > 0) {
1557
- log.warn(`The following packages did not export their \`package.json\` file so we could not check the "svelte" field. If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.`, Array.from(pkg_export_errors, (s) => `- ${s}`).join("\n"));
1626
+ if (pkg_resolve_errors.size > 0) {
1627
+ log.warn(`vite-plugin-svelte was unable to find package.json of the following packages and wasn't able to resolve via their "svelte" field.
1628
+ If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.
1629
+ ${Array.from(pkg_resolve_errors, (s) => `- ${s}`).join("\n")}`.replace(/\t/g, ""));
1558
1630
  }
1559
1631
  }
1560
1632
  };