@sveltejs/vite-plugin-svelte 1.0.0-next.32 → 1.0.0-next.36

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.cjs CHANGED
@@ -23,36 +23,42 @@ var __spreadValues = (a, b) => {
23
23
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
24
  var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
25
25
  var __export = (target, all) => {
26
- __markAsModule(target);
27
26
  for (var name in all)
28
27
  __defProp(target, name, { get: all[name], enumerable: true });
29
28
  };
30
- var __reExport = (target, module2, desc) => {
29
+ var __reExport = (target, module2, copyDefault, desc) => {
31
30
  if (module2 && typeof module2 === "object" || typeof module2 === "function") {
32
31
  for (let key of __getOwnPropNames(module2))
33
- if (!__hasOwnProp.call(target, key) && key !== "default")
32
+ if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
34
33
  __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
35
34
  }
36
35
  return target;
37
36
  };
38
- var __toModule = (module2) => {
39
- return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
37
+ var __toESM = (module2, isNodeMode) => {
38
+ return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", !isNodeMode && module2 && module2.__esModule ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
40
39
  };
40
+ var __toCommonJS = /* @__PURE__ */ ((cache) => {
41
+ return (module2, temp) => {
42
+ return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);
43
+ };
44
+ })(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
41
45
 
42
46
  // src/index.ts
43
- __export(exports, {
47
+ var src_exports = {};
48
+ __export(src_exports, {
44
49
  svelte: () => svelte
45
50
  });
46
51
 
47
- // ../../node_modules/.pnpm/tsup@5.10.1_typescript@4.5.2/node_modules/tsup/assets/cjs_shims.js
48
- var importMetaUrlShim = typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
52
+ // ../../node_modules/.pnpm/tsup@5.11.11_typescript@4.5.5/node_modules/tsup/assets/cjs_shims.js
53
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
54
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
49
55
 
50
56
  // src/index.ts
51
- var import_fs6 = __toModule(require("fs"));
57
+ var import_fs6 = __toESM(require("fs"), 1);
52
58
 
53
59
  // src/utils/log.ts
54
- var import_colors = __toModule(require("kleur/colors"));
55
- var import_debug = __toModule(require("debug"));
60
+ var import_colors = require("kleur/colors");
61
+ var import_debug = __toESM(require("debug"), 1);
56
62
  var levels = ["debug", "info", "warn", "error", "silent"];
57
63
  var prefix = "vite-plugin-svelte";
58
64
  var loggers = {
@@ -111,7 +117,7 @@ function _log(logger, message, payload) {
111
117
  function createLogger(level) {
112
118
  const logger = loggers[level];
113
119
  const logFn = _log.bind(null, logger);
114
- const logged = new Set();
120
+ const logged = /* @__PURE__ */ new Set();
115
121
  const once = function(message, payload) {
116
122
  if (logged.has(message)) {
117
123
  return;
@@ -186,7 +192,10 @@ function buildExtendedLogMessage(w) {
186
192
  parts.push(":", w.start.line, ":", w.start.column);
187
193
  }
188
194
  if (w.message) {
189
- parts.push(" ", w.message);
195
+ if (parts.length > 0) {
196
+ parts.push(" ");
197
+ }
198
+ parts.push(w.message);
190
199
  }
191
200
  return parts.join("");
192
201
  }
@@ -203,7 +212,7 @@ async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, option
203
212
  const content = await read();
204
213
  const compileData = await compileSvelte2(svelteRequest, content, options);
205
214
  cache.update(compileData);
206
- const affectedModules = new Set();
215
+ const affectedModules = /* @__PURE__ */ new Set();
207
216
  const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId);
208
217
  const mainModule = server.moduleGraph.getModuleById(svelteRequest.id);
209
218
  const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css);
@@ -263,12 +272,12 @@ function normalizeJsCode(code) {
263
272
  }
264
273
 
265
274
  // src/utils/compile.ts
266
- var import_compiler = __toModule(require("svelte/compiler"));
267
- var import_svelte_hmr = __toModule(require("svelte-hmr"));
275
+ var import_compiler = require("svelte/compiler");
276
+ var import_svelte_hmr = require("svelte-hmr");
268
277
 
269
278
  // src/utils/hash.ts
270
- var crypto = __toModule(require("crypto"));
271
- var hashes = Object.create(null);
279
+ var crypto = __toESM(require("crypto"), 1);
280
+ var hashes = /* @__PURE__ */ Object.create(null);
272
281
  var hash_length = 12;
273
282
  function safeBase64Hash(input) {
274
283
  if (hashes[input]) {
@@ -314,7 +323,12 @@ var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequ
314
323
  }
315
324
  let preprocessed;
316
325
  if (options.preprocess) {
317
- preprocessed = await (0, import_compiler.preprocess)(code, options.preprocess, { filename });
326
+ try {
327
+ preprocessed = await (0, import_compiler.preprocess)(code, options.preprocess, { filename });
328
+ } catch (e) {
329
+ e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
330
+ throw e;
331
+ }
318
332
  if (preprocessed.dependencies)
319
333
  dependencies.push(...preprocessed.dependencies);
320
334
  if (preprocessed.map)
@@ -375,9 +389,9 @@ function createCompileSvelte(options) {
375
389
  }
376
390
 
377
391
  // src/utils/id.ts
378
- var import_pluginutils = __toModule(require("@rollup/pluginutils"));
379
- var import_vite = __toModule(require("vite"));
380
- var fs = __toModule(require("fs"));
392
+ var import_pluginutils = require("@rollup/pluginutils");
393
+ var import_vite = require("vite");
394
+ var fs = __toESM(require("fs"), 1);
381
395
  var VITE_FS_PREFIX = "/@fs/";
382
396
  var IS_WINDOWS = process.platform === "win32";
383
397
  function splitId(id) {
@@ -453,13 +467,13 @@ function buildIdParser(options) {
453
467
  }
454
468
 
455
469
  // src/utils/options.ts
456
- var import_vite2 = __toModule(require("vite"));
470
+ var import_vite3 = require("vite");
457
471
 
458
472
  // src/utils/load-svelte-config.ts
459
- var import_module = __toModule(require("module"));
460
- var import_path = __toModule(require("path"));
461
- var import_fs = __toModule(require("fs"));
462
- var import_url = __toModule(require("url"));
473
+ var import_module = require("module");
474
+ var import_path = __toESM(require("path"), 1);
475
+ var import_fs = __toESM(require("fs"), 1);
476
+ var import_url = require("url");
463
477
  var esmRequire;
464
478
  var knownSvelteConfigNames = [
465
479
  "svelte.config.js",
@@ -488,7 +502,7 @@ async function loadSvelteConfig(viteConfig, inlineOptions) {
488
502
  }
489
503
  if (!configFile.endsWith(".mjs")) {
490
504
  try {
491
- const _require = importMetaUrlShim ? esmRequire ?? (esmRequire = (0, import_module.createRequire)(importMetaUrlShim)) : require;
505
+ const _require = importMetaUrl ? esmRequire ?? (esmRequire = (0, import_module.createRequire)(importMetaUrl)) : require;
492
506
  delete _require.cache[_require.resolve(configFile)];
493
507
  const result = _require(configFile);
494
508
  if (result != null) {
@@ -548,12 +562,12 @@ var SVELTE_HMR_IMPORTS = [
548
562
  ];
549
563
 
550
564
  // src/utils/options.ts
551
- var import_path3 = __toModule(require("path"));
565
+ var import_path3 = __toESM(require("path"), 1);
552
566
 
553
567
  // src/utils/dependencies.ts
554
- var import_path2 = __toModule(require("path"));
555
- var import_fs2 = __toModule(require("fs"));
556
- var import_module2 = __toModule(require("module"));
568
+ var import_path2 = __toESM(require("path"), 1);
569
+ var import_fs2 = __toESM(require("fs"), 1);
570
+ var import_module2 = require("module");
557
571
  function findRootSvelteDependencies(root, cwdFallback = true) {
558
572
  log.debug(`findSvelteDependencies: searching svelte dependencies in ${root}`);
559
573
  const pkgFile = import_path2.default.join(root, "package.json");
@@ -578,7 +592,7 @@ function findRootSvelteDependencies(root, cwdFallback = true) {
578
592
  ].filter((dep) => !is_common_without_svelte_field(dep));
579
593
  return getSvelteDependencies(deps, root);
580
594
  }
581
- function getSvelteDependencies(deps, pkgDir, path6 = []) {
595
+ function getSvelteDependencies(deps, pkgDir, path7 = []) {
582
596
  const result = [];
583
597
  const localRequire = (0, import_module2.createRequire)(`${pkgDir}/package.json`);
584
598
  const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
@@ -586,18 +600,18 @@ function getSvelteDependencies(deps, pkgDir, path6 = []) {
586
600
  const type = getSvelteDependencyType(pkg);
587
601
  if (!type)
588
602
  continue;
589
- result.push({ name: pkg.name, type, pkg, dir, path: path6 });
603
+ result.push({ name: pkg.name, type, pkg, dir, path: path7 });
590
604
  if (type === "component-library" && pkg.dependencies) {
591
605
  let dependencyNames = Object.keys(pkg.dependencies);
592
- const circular = dependencyNames.filter((name) => path6.includes(name));
606
+ const circular = dependencyNames.filter((name) => path7.includes(name));
593
607
  if (circular.length > 0) {
594
- log.warn.enabled && log.warn(`skipping circular svelte dependencies in automated vite optimizeDeps handling`, circular.map((x) => path6.concat(x).join(">")));
595
- dependencyNames = dependencyNames.filter((name) => !path6.includes(name));
608
+ log.warn.enabled && log.warn(`skipping circular svelte dependencies in automated vite optimizeDeps handling`, circular.map((x) => path7.concat(x).join(">")));
609
+ dependencyNames = dependencyNames.filter((name) => !path7.includes(name));
596
610
  }
597
- if (path6.length === 3) {
598
- log.debug.once(`encountered deep svelte dependency tree: ${path6.join(">")}`);
611
+ if (path7.length === 3) {
612
+ log.debug.once(`encountered deep svelte dependency tree: ${path7.join(">")}`);
599
613
  }
600
- result.push(...getSvelteDependencies(dependencyNames, dir, path6.concat(pkg.name)));
614
+ result.push(...getSvelteDependencies(dependencyNames, dir, path7.concat(pkg.name)));
601
615
  }
602
616
  }
603
617
  return result;
@@ -696,26 +710,30 @@ function needsOptimization(dep, localRequire) {
696
710
  if (!depData)
697
711
  return false;
698
712
  const pkg = depData.pkg;
699
- return pkg.main && !pkg.module && !pkg.exports;
713
+ const isCjs = pkg.main && !pkg.module && !pkg.exports;
714
+ if (!isCjs)
715
+ return false;
716
+ const entryExt = import_path2.default.extname(pkg.main);
717
+ return !entryExt || entryExt === ".js" || entryExt === ".cjs";
700
718
  }
701
719
 
702
720
  // src/utils/options.ts
703
- var import_module3 = __toModule(require("module"));
721
+ var import_module3 = require("module");
704
722
 
705
723
  // src/utils/esbuild.ts
706
- var import_fs3 = __toModule(require("fs"));
707
- var import_compiler2 = __toModule(require("svelte/compiler"));
724
+ var import_fs3 = require("fs");
725
+ var import_compiler2 = require("svelte/compiler");
708
726
 
709
727
  // src/utils/error.ts
710
- function toRollupError(error) {
711
- const { filename, frame, start, code, name } = error;
728
+ function toRollupError(error, options) {
729
+ const { filename, frame, start, code, name, stack } = error;
712
730
  const rollupError = {
713
731
  name,
714
732
  id: filename,
715
733
  message: buildExtendedLogMessage(error),
716
734
  frame: formatFrameForVite(frame),
717
735
  code,
718
- stack: ""
736
+ stack: options.isBuild || options.isDebug || !frame ? stack : ""
719
737
  };
720
738
  if (start) {
721
739
  rollupError.loc = {
@@ -726,8 +744,8 @@ function toRollupError(error) {
726
744
  }
727
745
  return rollupError;
728
746
  }
729
- function toESBuildError(error) {
730
- const { filename, frame, start } = error;
747
+ function toESBuildError(error, options) {
748
+ const { filename, frame, start, stack } = error;
731
749
  const partialMessage = {
732
750
  text: buildExtendedLogMessage(error)
733
751
  };
@@ -739,6 +757,9 @@ function toESBuildError(error) {
739
757
  lineText: lineFromFrame(start.line, frame)
740
758
  };
741
759
  }
760
+ if (options.isBuild || options.isDebug || !frame) {
761
+ partialMessage.detail = stack;
762
+ }
742
763
  return partialMessage;
743
764
  }
744
765
  function lineFromFrame(lineNo, frame) {
@@ -757,6 +778,7 @@ function formatFrameForVite(frame) {
757
778
  }
758
779
 
759
780
  // src/utils/esbuild.ts
781
+ var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
760
782
  function esbuildSveltePlugin(options) {
761
783
  return {
762
784
  name: "vite-plugin-svelte:optimize-svelte",
@@ -770,7 +792,7 @@ function esbuildSveltePlugin(options) {
770
792
  const contents = await compileSvelte(options, { filename, code });
771
793
  return { contents };
772
794
  } catch (e) {
773
- return { errors: [toESBuildError(e)] };
795
+ return { errors: [toESBuildError(e, options)] };
774
796
  }
775
797
  });
776
798
  }
@@ -798,11 +820,17 @@ async function compileSvelte(options, { filename, code }) {
798
820
  const compileOptions = __spreadProps(__spreadValues({}, options.compilerOptions), {
799
821
  css: true,
800
822
  filename,
823
+ format: "esm",
801
824
  generate: "dom"
802
825
  });
803
826
  let preprocessed;
804
827
  if (options.preprocess) {
805
- preprocessed = await (0, import_compiler2.preprocess)(code, options.preprocess, { filename });
828
+ try {
829
+ preprocessed = await (0, import_compiler2.preprocess)(code, options.preprocess, { filename });
830
+ } catch (e) {
831
+ e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
832
+ throw e;
833
+ }
806
834
  if (preprocessed.map)
807
835
  compileOptions.sourcemap = preprocessed.map;
808
836
  }
@@ -820,8 +848,235 @@ async function compileSvelte(options, { filename, code }) {
820
848
  return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
821
849
  }
822
850
 
851
+ // src/utils/preprocess.ts
852
+ var import_vite2 = require("vite");
853
+ var import_magic_string2 = __toESM(require("magic-string"), 1);
854
+ var import_compiler3 = require("svelte/compiler");
855
+
856
+ // src/utils/sourcemap.ts
857
+ var import_magic_string = __toESM(require("magic-string"), 1);
858
+ async function buildMagicString(from, to, options) {
859
+ let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
860
+ try {
861
+ const dmpPkg = await import("diff-match-patch");
862
+ diff_match_patch = dmpPkg.diff_match_patch;
863
+ DIFF_INSERT = dmpPkg.DIFF_INSERT;
864
+ DIFF_DELETE = dmpPkg.DIFF_DELETE;
865
+ } catch (e) {
866
+ log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
867
+ return null;
868
+ }
869
+ const dmp = new diff_match_patch();
870
+ const diffs = dmp.diff_main(from, to);
871
+ dmp.diff_cleanupSemantic(diffs);
872
+ const m = new import_magic_string.default(from, options);
873
+ let pos = 0;
874
+ for (let i = 0; i < diffs.length; i++) {
875
+ const diff = diffs[i];
876
+ const nextDiff = diffs[i + 1];
877
+ if (diff[0] === DIFF_DELETE) {
878
+ if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
879
+ m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
880
+ i++;
881
+ } else {
882
+ m.remove(pos, pos + diff[1].length);
883
+ }
884
+ pos += diff[1].length;
885
+ } else if (diff[0] === DIFF_INSERT) {
886
+ if (nextDiff) {
887
+ m.appendRight(pos, diff[1]);
888
+ } else {
889
+ m.append(diff[1]);
890
+ }
891
+ } else {
892
+ pos += diff[1].length;
893
+ }
894
+ }
895
+ return m;
896
+ }
897
+ async function buildSourceMap(from, to, filename) {
898
+ const m = await buildMagicString(from, to, { filename });
899
+ return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
900
+ }
901
+
902
+ // src/utils/preprocess.ts
903
+ var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
904
+ var supportedScriptLangs = ["ts"];
905
+ function createViteScriptPreprocessor() {
906
+ return async ({ attributes, content, filename = "" }) => {
907
+ const lang = attributes.lang;
908
+ if (!supportedScriptLangs.includes(lang))
909
+ return;
910
+ const transformResult = await (0, import_vite2.transformWithEsbuild)(content, filename, {
911
+ loader: lang,
912
+ tsconfigRaw: {
913
+ compilerOptions: {
914
+ importsNotUsedAsValues: "preserve",
915
+ preserveValueImports: true
916
+ }
917
+ }
918
+ });
919
+ return {
920
+ code: transformResult.code,
921
+ map: transformResult.map
922
+ };
923
+ };
924
+ }
925
+ function createViteStylePreprocessor(config) {
926
+ const pluginName = "vite:css";
927
+ const plugin = config.plugins.find((p) => p.name === pluginName);
928
+ if (!plugin) {
929
+ throw new Error(`failed to find plugin ${pluginName}`);
930
+ }
931
+ if (!plugin.transform) {
932
+ throw new Error(`plugin ${pluginName} has no transform`);
933
+ }
934
+ const pluginTransform = plugin.transform.bind(null);
935
+ return async ({ attributes, content, filename = "" }) => {
936
+ var _a, _b;
937
+ const lang = attributes.lang;
938
+ if (!supportedStyleLangs.includes(lang))
939
+ return;
940
+ const moduleId = `${filename}.${lang}`;
941
+ const transformResult = await pluginTransform(content, moduleId);
942
+ if (((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
943
+ transformResult.map.sources[0] = filename;
944
+ }
945
+ return {
946
+ code: transformResult.code,
947
+ map: transformResult.map ?? void 0
948
+ };
949
+ };
950
+ }
951
+ function createVitePreprocessorGroup(config) {
952
+ return {
953
+ markup({ content, filename }) {
954
+ return (0, import_compiler3.preprocess)(content, {
955
+ script: createViteScriptPreprocessor(),
956
+ style: createViteStylePreprocessor(config)
957
+ }, { filename });
958
+ }
959
+ };
960
+ }
961
+ function createInjectScopeEverythingRulePreprocessorGroup() {
962
+ return {
963
+ style({ content, filename }) {
964
+ const s = new import_magic_string2.default(content);
965
+ s.append(" *{}");
966
+ return {
967
+ code: s.toString(),
968
+ map: s.generateDecodedMap({ source: filename, hires: true })
969
+ };
970
+ }
971
+ };
972
+ }
973
+ function buildExtraPreprocessors(options, config) {
974
+ var _a, _b;
975
+ const prependPreprocessors = [];
976
+ const appendPreprocessors = [];
977
+ if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
978
+ log.debug("adding vite preprocessor");
979
+ prependPreprocessors.push(createVitePreprocessorGroup(config));
980
+ }
981
+ const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
982
+ if (pluginsWithPreprocessorsDeprecated.length > 0) {
983
+ log.warn(`The following plugins use the deprecated 'plugin.sveltePreprocess' field. Please contact their maintainers and ask them to move it to 'plugin.api.sveltePreprocess': ${pluginsWithPreprocessorsDeprecated.map((p) => p.name).join(", ")}`);
984
+ pluginsWithPreprocessorsDeprecated.forEach((p) => {
985
+ if (!p.api) {
986
+ p.api = {};
987
+ }
988
+ if (p.api.sveltePreprocess === void 0) {
989
+ p.api.sveltePreprocess = p.sveltePreprocess;
990
+ } else {
991
+ log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
992
+ }
993
+ });
994
+ }
995
+ const pluginsWithPreprocessors = config.plugins.filter((p) => {
996
+ var _a2;
997
+ return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
998
+ });
999
+ const ignored = [], included = [];
1000
+ for (const p of pluginsWithPreprocessors) {
1001
+ if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
1002
+ ignored.push(p);
1003
+ } else {
1004
+ included.push(p);
1005
+ }
1006
+ }
1007
+ if (ignored.length > 0) {
1008
+ log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
1009
+ }
1010
+ if (included.length > 0) {
1011
+ log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
1012
+ appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
1013
+ }
1014
+ if (options.hot && options.emitCss) {
1015
+ appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
1016
+ }
1017
+ return { prependPreprocessors, appendPreprocessors };
1018
+ }
1019
+ function addExtraPreprocessors(options, config) {
1020
+ var _a;
1021
+ const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
1022
+ if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
1023
+ if (!options.preprocess) {
1024
+ options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
1025
+ } else if (Array.isArray(options.preprocess)) {
1026
+ options.preprocess.unshift(...prependPreprocessors);
1027
+ options.preprocess.push(...appendPreprocessors);
1028
+ } else {
1029
+ options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
1030
+ }
1031
+ }
1032
+ const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
1033
+ if (options.preprocess && generateMissingSourceMaps) {
1034
+ options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
1035
+ }
1036
+ }
1037
+ function validateSourceMapOutputWrapper(group, i) {
1038
+ const wrapper = {};
1039
+ for (const [processorType, processorFn] of Object.entries(group)) {
1040
+ wrapper[processorType] = async (options) => {
1041
+ var _a;
1042
+ const result = await processorFn(options);
1043
+ if (result && result.code !== options.content) {
1044
+ let invalidMap = false;
1045
+ if (!result.map) {
1046
+ invalidMap = true;
1047
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
1048
+ filename: options.filename,
1049
+ type: processorType,
1050
+ processor: processorFn.toString()
1051
+ });
1052
+ } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
1053
+ invalidMap = true;
1054
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
1055
+ filename: options.filename,
1056
+ type: processorType,
1057
+ processor: processorFn.toString()
1058
+ });
1059
+ }
1060
+ if (invalidMap) {
1061
+ try {
1062
+ const map = await buildSourceMap(options.content, result.code, options.filename);
1063
+ if (map) {
1064
+ log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
1065
+ result.map = map;
1066
+ }
1067
+ } catch (e) {
1068
+ log.error(`failed to build sourcemap`, e);
1069
+ }
1070
+ }
1071
+ }
1072
+ return result;
1073
+ };
1074
+ }
1075
+ return wrapper;
1076
+ }
1077
+
823
1078
  // src/utils/options.ts
824
- var knownOptions = new Set([
1079
+ var knownOptions = /* @__PURE__ */ new Set([
825
1080
  "configFile",
826
1081
  "include",
827
1082
  "exclude",
@@ -835,28 +1090,54 @@ var knownOptions = new Set([
835
1090
  "disableDependencyReinclusion",
836
1091
  "experimental"
837
1092
  ]);
838
- function buildDefaultOptions(isProduction, emitCss = true) {
839
- const hot = isProduction ? false : {
840
- injectCss: !emitCss
841
- };
1093
+ function validateInlineOptions(inlineOptions) {
1094
+ const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
1095
+ if (invalidKeys.length) {
1096
+ log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in config`, inlineOptions);
1097
+ }
1098
+ }
1099
+ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1100
+ const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteUserConfig), {
1101
+ root: resolveViteRoot(viteUserConfig)
1102
+ });
842
1103
  const defaultOptions = {
843
1104
  extensions: [".svelte"],
844
- hot,
845
- emitCss,
1105
+ emitCss: true,
846
1106
  compilerOptions: {
847
- format: "esm",
848
- css: !emitCss,
849
- dev: !isProduction
1107
+ format: "esm"
850
1108
  }
851
1109
  };
852
- log.debug(`default options for ${isProduction ? "production" : "development"}`, defaultOptions);
853
- return defaultOptions;
854
- }
855
- function validateInlineOptions(inlineOptions) {
856
- const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
857
- if (invalidKeys.length) {
858
- log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in config`, inlineOptions);
1110
+ const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions);
1111
+ const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), {
1112
+ compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.compilerOptions), svelteConfig == null ? void 0 : svelteConfig.compilerOptions), inlineOptions == null ? void 0 : inlineOptions.compilerOptions),
1113
+ experimental: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.experimental), svelteConfig == null ? void 0 : svelteConfig.experimental), inlineOptions == null ? void 0 : inlineOptions.experimental),
1114
+ root: viteConfigWithResolvedRoot.root,
1115
+ isBuild: viteEnv.command === "build",
1116
+ isServe: viteEnv.command === "serve",
1117
+ isDebug: process.env.DEBUG != null
1118
+ });
1119
+ if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
1120
+ merged.configFile = svelteConfig.configFile;
859
1121
  }
1122
+ return merged;
1123
+ }
1124
+ function resolveOptions(preResolveOptions2, viteConfig) {
1125
+ const defaultOptions = {
1126
+ hot: viteConfig.isProduction ? false : { injectCss: !preResolveOptions2.emitCss },
1127
+ compilerOptions: {
1128
+ css: !preResolveOptions2.emitCss,
1129
+ dev: !viteConfig.isProduction
1130
+ }
1131
+ };
1132
+ const merged = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), preResolveOptions2), {
1133
+ compilerOptions: __spreadValues(__spreadValues({}, defaultOptions.compilerOptions), preResolveOptions2.compilerOptions),
1134
+ root: viteConfig.root,
1135
+ isProduction: viteConfig.isProduction
1136
+ });
1137
+ addExtraPreprocessors(merged, viteConfig);
1138
+ enforceOptionsForHmr(merged);
1139
+ enforceOptionsForProduction(merged);
1140
+ return merged;
860
1141
  }
861
1142
  function enforceOptionsForHmr(options) {
862
1143
  if (options.hot) {
@@ -901,34 +1182,8 @@ function enforceOptionsForProduction(options) {
901
1182
  }
902
1183
  }
903
1184
  }
904
- function mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfig, viteEnv) {
905
- const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), {
906
- compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions.compilerOptions), (svelteConfig == null ? void 0 : svelteConfig.compilerOptions) || {}), (inlineOptions == null ? void 0 : inlineOptions.compilerOptions) || {}),
907
- experimental: __spreadValues(__spreadValues({}, (svelteConfig == null ? void 0 : svelteConfig.experimental) || {}), (inlineOptions == null ? void 0 : inlineOptions.experimental) || {}),
908
- root: viteConfig.root,
909
- isProduction: viteEnv.mode === "production",
910
- isBuild: viteEnv.command === "build",
911
- isServe: viteEnv.command === "serve",
912
- isSvelteKit: !!(svelteConfig == null ? void 0 : svelteConfig.kit)
913
- });
914
- if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
915
- merged.configFile = svelteConfig.configFile;
916
- }
917
- return merged;
918
- }
919
- async function resolveOptions(inlineOptions = {}, viteConfig, viteEnv) {
920
- const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteConfig), {
921
- root: resolveViteRoot(viteConfig)
922
- });
923
- const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions) || {};
924
- const defaultOptions = buildDefaultOptions(viteEnv.mode === "production", inlineOptions.emitCss ?? svelteConfig.emitCss);
925
- const resolvedOptions = mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfigWithResolvedRoot, viteEnv);
926
- enforceOptionsForProduction(resolvedOptions);
927
- enforceOptionsForHmr(resolvedOptions);
928
- return resolvedOptions;
929
- }
930
1185
  function resolveViteRoot(viteConfig) {
931
- return (0, import_vite2.normalizePath)(viteConfig.root ? import_path3.default.resolve(viteConfig.root) : process.cwd());
1186
+ return (0, import_vite3.normalizePath)(viteConfig.root ? import_path3.default.resolve(viteConfig.root) : process.cwd());
932
1187
  }
933
1188
  function buildExtraViteConfig(options, config, configEnv) {
934
1189
  const svelteDeps = findRootSvelteDependencies(options.root);
@@ -944,16 +1199,16 @@ function buildExtraViteConfig(options, config, configEnv) {
944
1199
  extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config);
945
1200
  return extraViteConfig;
946
1201
  }
947
- function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
1202
+ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps2) {
948
1203
  const include = [];
949
1204
  const exclude = ["svelte-hmr"];
950
1205
  const isIncluded = (dep) => {
951
1206
  var _a;
952
- return include.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a.includes(dep));
1207
+ return include.includes(dep) || ((_a = optimizeDeps2 == null ? void 0 : optimizeDeps2.include) == null ? void 0 : _a.includes(dep));
953
1208
  };
954
1209
  const isExcluded = (dep) => {
955
1210
  var _a;
956
- return exclude.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
1211
+ return exclude.includes(dep) || ((_a = optimizeDeps2 == null ? void 0 : optimizeDeps2.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
957
1212
  };
958
1213
  if (!isExcluded("svelte")) {
959
1214
  const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
@@ -967,7 +1222,8 @@ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
967
1222
  include,
968
1223
  exclude,
969
1224
  esbuildOptions: {
970
- plugins: [esbuildSveltePlugin(options)]
1225
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1226
+ } }]
971
1227
  }
972
1228
  };
973
1229
  }
@@ -1007,14 +1263,22 @@ function buildSSROptionsForSvelte(svelteDeps, options, config) {
1007
1263
  noExternal
1008
1264
  };
1009
1265
  }
1266
+ function patchResolvedViteConfig(viteConfig, options) {
1267
+ var _a, _b;
1268
+ const facadeEsbuildSveltePlugin = (_b = (_a = viteConfig.optimizeDeps.esbuildOptions) == null ? void 0 : _a.plugins) == null ? void 0 : _b.find((plugin) => plugin.name === facadeEsbuildSveltePluginName);
1269
+ if (facadeEsbuildSveltePlugin) {
1270
+ Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options));
1271
+ }
1272
+ }
1010
1273
 
1011
1274
  // src/utils/vite-plugin-svelte-cache.ts
1012
1275
  var VitePluginSvelteCache = class {
1013
1276
  constructor() {
1014
- this._css = new Map();
1015
- this._js = new Map();
1016
- this._dependencies = new Map();
1017
- this._dependants = new Map();
1277
+ this._css = /* @__PURE__ */ new Map();
1278
+ this._js = /* @__PURE__ */ new Map();
1279
+ this._dependencies = /* @__PURE__ */ new Map();
1280
+ this._dependants = /* @__PURE__ */ new Map();
1281
+ this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1018
1282
  }
1019
1283
  update(compileData) {
1020
1284
  this.updateCSS(compileData);
@@ -1038,7 +1302,7 @@ var VitePluginSvelteCache = class {
1038
1302
  const added = dependencies.filter((d) => !prevDependencies.includes(d));
1039
1303
  added.forEach((d) => {
1040
1304
  if (!this._dependants.has(d)) {
1041
- this._dependants.set(d, new Set());
1305
+ this._dependants.set(d, /* @__PURE__ */ new Set());
1042
1306
  }
1043
1307
  this._dependants.get(d).add(compileData.filename);
1044
1308
  });
@@ -1076,15 +1340,24 @@ var VitePluginSvelteCache = class {
1076
1340
  return this._js.get(svelteRequest.normalizedFilename);
1077
1341
  }
1078
1342
  }
1079
- getDependants(path6) {
1080
- const dependants = this._dependants.get(path6);
1343
+ getDependants(path7) {
1344
+ const dependants = this._dependants.get(path7);
1081
1345
  return dependants ? [...dependants] : [];
1082
1346
  }
1347
+ getResolvedSvelteField(name, importer) {
1348
+ return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
1349
+ }
1350
+ setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
1351
+ this._resolvedSvelteFields.set(this._getResolvedSvelteFieldKey(importee, importer), resolvedSvelte);
1352
+ }
1353
+ _getResolvedSvelteFieldKey(importee, importer) {
1354
+ return importer ? `${importer} > ${importee}` : importee;
1355
+ }
1083
1356
  };
1084
1357
 
1085
1358
  // src/utils/watch.ts
1086
- var import_fs4 = __toModule(require("fs"));
1087
- var import_path4 = __toModule(require("path"));
1359
+ var import_fs4 = __toESM(require("fs"), 1);
1360
+ var import_path4 = __toESM(require("path"), 1);
1088
1361
  function setupWatchers(options, cache, requestParser) {
1089
1362
  const { server, configFile: svelteConfigFile } = options;
1090
1363
  if (!server) {
@@ -1111,8 +1384,7 @@ function setupWatchers(options, cache, requestParser) {
1111
1384
  }
1112
1385
  };
1113
1386
  const triggerViteRestart = (filename) => {
1114
- var _a;
1115
- if (serverConfig.middlewareMode || options.isSvelteKit) {
1387
+ if (serverConfig.middlewareMode) {
1116
1388
  const message = "Svelte config change detected, restart your dev process to apply the changes.";
1117
1389
  log.info(message, filename);
1118
1390
  ws.send({
@@ -1121,7 +1393,7 @@ function setupWatchers(options, cache, requestParser) {
1121
1393
  });
1122
1394
  } else {
1123
1395
  log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1124
- server.restart(!!((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries));
1396
+ server.restart();
1125
1397
  }
1126
1398
  };
1127
1399
  const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => import_path4.default.join(root, cfg));
@@ -1159,15 +1431,25 @@ function ensureWatchedFile(watcher, file, root) {
1159
1431
  }
1160
1432
 
1161
1433
  // src/utils/resolve.ts
1162
- var import_path5 = __toModule(require("path"));
1163
- var import_fs5 = __toModule(require("fs"));
1164
- var import_require_relative = __toModule(require("require-relative"));
1165
- function resolveViaPackageJsonSvelte(importee, importer) {
1166
- if (importer && isBareImport(importee)) {
1167
- const importeePkgFile = import_require_relative.default.resolve(`${importee}/package.json`, import_path5.default.dirname(importer));
1168
- const importeePkg = JSON.parse(import_fs5.default.readFileSync(importeePkgFile, { encoding: "utf-8" }));
1169
- if (importeePkg.svelte) {
1170
- return import_path5.default.resolve(import_path5.default.dirname(importeePkgFile), importeePkg.svelte);
1434
+ var import_path5 = __toESM(require("path"), 1);
1435
+ var import_module4 = require("module");
1436
+ function resolveViaPackageJsonSvelte(importee, importer, cache) {
1437
+ if (importer && isBareImport(importee) && !is_common_without_svelte_field(importee)) {
1438
+ const cached = cache.getResolvedSvelteField(importee, importer);
1439
+ if (cached) {
1440
+ return cached;
1441
+ }
1442
+ const localRequire = (0, import_module4.createRequire)(importer);
1443
+ const pkgData = resolveDependencyData(importee, localRequire);
1444
+ if (pkgData) {
1445
+ const { pkg, dir } = pkgData;
1446
+ if (pkg.svelte) {
1447
+ const result = import_path5.default.resolve(dir, pkg.svelte);
1448
+ cache.setResolvedSvelteField(importee, importer, result);
1449
+ return result;
1450
+ }
1451
+ } else {
1452
+ throw new Error(`failed to resolve package.json of ${importee} imported by ${importer}`);
1171
1453
  }
1172
1454
  }
1173
1455
  }
@@ -1186,231 +1468,42 @@ function isBareImport(importee) {
1186
1468
  }
1187
1469
  }
1188
1470
 
1189
- // src/utils/preprocess.ts
1190
- var import_vite3 = __toModule(require("vite"));
1191
- var import_magic_string2 = __toModule(require("magic-string"));
1192
- var import_compiler3 = __toModule(require("svelte/compiler"));
1193
-
1194
- // src/utils/sourcemap.ts
1195
- var import_magic_string = __toModule(require("magic-string"));
1196
- async function buildMagicString(from, to, options) {
1197
- let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
1198
- try {
1199
- const dmpPkg = await import("diff-match-patch");
1200
- diff_match_patch = dmpPkg.diff_match_patch;
1201
- DIFF_INSERT = dmpPkg.DIFF_INSERT;
1202
- DIFF_DELETE = dmpPkg.DIFF_DELETE;
1203
- } catch (e) {
1204
- log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
1205
- return null;
1206
- }
1207
- const dmp = new diff_match_patch();
1208
- const diffs = dmp.diff_main(from, to);
1209
- dmp.diff_cleanupSemantic(diffs);
1210
- const m = new import_magic_string.default(from, options);
1211
- let pos = 0;
1212
- for (let i = 0; i < diffs.length; i++) {
1213
- const diff = diffs[i];
1214
- const nextDiff = diffs[i + 1];
1215
- if (diff[0] === DIFF_DELETE) {
1216
- if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
1217
- m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
1218
- i++;
1219
- } else {
1220
- m.remove(pos, pos + diff[1].length);
1221
- }
1222
- pos += diff[1].length;
1223
- } else if (diff[0] === DIFF_INSERT) {
1224
- if (nextDiff) {
1225
- m.appendRight(pos, diff[1]);
1226
- } else {
1227
- m.append(diff[1]);
1228
- }
1229
- } else {
1230
- pos += diff[1].length;
1231
- }
1232
- }
1233
- return m;
1234
- }
1235
- async function buildSourceMap(from, to, filename) {
1236
- const m = await buildMagicString(from, to, { filename });
1237
- return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
1238
- }
1239
-
1240
- // src/utils/preprocess.ts
1241
- var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
1242
- var supportedScriptLangs = ["ts"];
1243
- function createViteScriptPreprocessor() {
1244
- return async ({ attributes, content, filename = "" }) => {
1245
- const lang = attributes.lang;
1246
- if (!supportedScriptLangs.includes(lang))
1247
- return;
1248
- const transformResult = await (0, import_vite3.transformWithEsbuild)(content, filename, {
1249
- loader: lang,
1250
- tsconfigRaw: {
1251
- compilerOptions: {
1252
- importsNotUsedAsValues: "preserve"
1253
- }
1254
- }
1255
- });
1256
- return {
1257
- code: transformResult.code,
1258
- map: transformResult.map
1259
- };
1260
- };
1261
- }
1262
- function createViteStylePreprocessor(config) {
1263
- const pluginName = "vite:css";
1264
- const plugin = config.plugins.find((p) => p.name === pluginName);
1265
- if (!plugin) {
1266
- throw new Error(`failed to find plugin ${pluginName}`);
1267
- }
1268
- if (!plugin.transform) {
1269
- throw new Error(`plugin ${pluginName} has no transform`);
1270
- }
1271
- const pluginTransform = plugin.transform.bind(null);
1272
- return async ({ attributes, content, filename = "" }) => {
1273
- var _a, _b;
1274
- const lang = attributes.lang;
1275
- if (!supportedStyleLangs.includes(lang))
1276
- return;
1277
- const moduleId = `${filename}.${lang}`;
1278
- const transformResult = await pluginTransform(content, moduleId);
1279
- const hasMap = transformResult.map && transformResult.map.mappings !== "";
1280
- if (hasMap && ((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
1281
- transformResult.map.sources[0] = filename;
1282
- }
1283
- return {
1284
- code: transformResult.code,
1285
- map: hasMap ? transformResult.map : void 0
1286
- };
1287
- };
1288
- }
1289
- function createVitePreprocessorGroup(config) {
1290
- return {
1291
- markup({ content, filename }) {
1292
- return (0, import_compiler3.preprocess)(content, {
1293
- script: createViteScriptPreprocessor(),
1294
- style: createViteStylePreprocessor(config)
1295
- }, { filename });
1296
- }
1297
- };
1298
- }
1299
- function createInjectScopeEverythingRulePreprocessorGroup() {
1300
- return {
1301
- style({ content, filename }) {
1302
- const s = new import_magic_string2.default(content);
1303
- s.append(" *{}");
1304
- return {
1305
- code: s.toString(),
1306
- map: s.generateDecodedMap({ source: filename, hires: true })
1307
- };
1308
- }
1309
- };
1310
- }
1311
- function buildExtraPreprocessors(options, config) {
1312
- var _a, _b;
1313
- const prependPreprocessors = [];
1314
- const appendPreprocessors = [];
1315
- if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
1316
- log.debug("adding vite preprocessor");
1317
- prependPreprocessors.push(createVitePreprocessorGroup(config));
1318
- }
1319
- const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
1320
- if (pluginsWithPreprocessorsDeprecated.length > 0) {
1321
- log.warn(`The following plugins use the deprecated 'plugin.sveltePreprocess' field. Please contact their maintainers and ask them to move it to 'plugin.api.sveltePreprocess': ${pluginsWithPreprocessorsDeprecated.map((p) => p.name).join(", ")}`);
1322
- pluginsWithPreprocessorsDeprecated.forEach((p) => {
1323
- if (!p.api) {
1324
- p.api = {};
1325
- }
1326
- if (p.api.sveltePreprocess === void 0) {
1327
- p.api.sveltePreprocess = p.sveltePreprocess;
1328
- } else {
1329
- log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
1330
- }
1331
- });
1332
- }
1333
- const pluginsWithPreprocessors = config.plugins.filter((p) => {
1334
- var _a2;
1335
- return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
1471
+ // src/utils/optimizer.ts
1472
+ var import_fs5 = __toESM(require("fs"), 1);
1473
+ var import_path6 = __toESM(require("path"), 1);
1474
+ var import_vite4 = require("vite");
1475
+ var PREBUNDLE_SENSITIVE_OPTIONS = [
1476
+ "compilerOptions",
1477
+ "configFile",
1478
+ "experimental",
1479
+ "extensions",
1480
+ "ignorePluginPreprocessors",
1481
+ "preprocess"
1482
+ ];
1483
+ async function handleOptimizeDeps(options, viteConfig) {
1484
+ if (!options.experimental.prebundleSvelteLibraries || !viteConfig.cacheDir)
1485
+ return;
1486
+ const viteMetadataPath = import_path6.default.resolve(viteConfig.cacheDir, "_metadata.json");
1487
+ if (!import_fs5.default.existsSync(viteMetadataPath))
1488
+ return;
1489
+ const svelteMetadataPath = import_path6.default.resolve(viteConfig.cacheDir, "_svelte_metadata.json");
1490
+ const currentSvelteMetadata = JSON.stringify(generateSvelteMetadata(options), (_, value) => {
1491
+ return typeof value === "function" ? value.toString() : value;
1336
1492
  });
1337
- const ignored = [], included = [];
1338
- for (const p of pluginsWithPreprocessors) {
1339
- if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
1340
- ignored.push(p);
1341
- } else {
1342
- included.push(p);
1343
- }
1344
- }
1345
- if (ignored.length > 0) {
1346
- log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
1347
- }
1348
- if (included.length > 0) {
1349
- log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
1350
- appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
1351
- }
1352
- if (options.hot && options.emitCss) {
1353
- appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
1354
- }
1355
- return { prependPreprocessors, appendPreprocessors };
1356
- }
1357
- function addExtraPreprocessors(options, config) {
1358
- var _a;
1359
- const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
1360
- if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
1361
- if (!options.preprocess) {
1362
- options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
1363
- } else if (Array.isArray(options.preprocess)) {
1364
- options.preprocess.unshift(...prependPreprocessors);
1365
- options.preprocess.push(...appendPreprocessors);
1366
- } else {
1367
- options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
1368
- }
1369
- }
1370
- const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
1371
- if (options.preprocess && generateMissingSourceMaps) {
1372
- options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
1493
+ if (import_fs5.default.existsSync(svelteMetadataPath)) {
1494
+ const existingSvelteMetadata = import_fs5.default.readFileSync(svelteMetadataPath, "utf8");
1495
+ if (existingSvelteMetadata === currentSvelteMetadata)
1496
+ return;
1373
1497
  }
1498
+ await (0, import_vite4.optimizeDeps)(viteConfig, true);
1499
+ import_fs5.default.writeFileSync(svelteMetadataPath, currentSvelteMetadata);
1374
1500
  }
1375
- function validateSourceMapOutputWrapper(group, i) {
1376
- const wrapper = {};
1377
- for (const [processorType, processorFn] of Object.entries(group)) {
1378
- wrapper[processorType] = async (options) => {
1379
- var _a;
1380
- const result = await processorFn(options);
1381
- if (result && result.code !== options.content) {
1382
- let invalidMap = false;
1383
- if (!result.map) {
1384
- invalidMap = true;
1385
- log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
1386
- filename: options.filename,
1387
- type: processorType,
1388
- processor: processorFn.toString()
1389
- });
1390
- } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
1391
- invalidMap = true;
1392
- log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
1393
- filename: options.filename,
1394
- type: processorType,
1395
- processor: processorFn.toString()
1396
- });
1397
- }
1398
- if (invalidMap) {
1399
- try {
1400
- const map = await buildSourceMap(options.content, result.code, options.filename);
1401
- if (map) {
1402
- log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
1403
- result.map = map;
1404
- }
1405
- } catch (e) {
1406
- log.error(`failed to build sourcemap`, e);
1407
- }
1408
- }
1409
- }
1410
- return result;
1411
- };
1501
+ function generateSvelteMetadata(options) {
1502
+ const metadata = {};
1503
+ for (const key of PREBUNDLE_SENSITIVE_OPTIONS) {
1504
+ metadata[key] = options[key];
1412
1505
  }
1413
- return wrapper;
1506
+ return metadata;
1414
1507
  }
1415
1508
 
1416
1509
  // src/index.ts
@@ -1420,7 +1513,7 @@ function svelte(inlineOptions) {
1420
1513
  }
1421
1514
  validateInlineOptions(inlineOptions);
1422
1515
  const cache = new VitePluginSvelteCache();
1423
- const pkg_export_errors = new Set();
1516
+ const pkg_resolve_errors = /* @__PURE__ */ new Set();
1424
1517
  let requestParser;
1425
1518
  let options;
1426
1519
  let viteConfig;
@@ -1435,18 +1528,22 @@ function svelte(inlineOptions) {
1435
1528
  } else if (config.logLevel) {
1436
1529
  log.setLevel(config.logLevel);
1437
1530
  }
1438
- options = await resolveOptions(inlineOptions, config, configEnv);
1531
+ options = await preResolveOptions(inlineOptions, config, configEnv);
1439
1532
  const extraViteConfig = buildExtraViteConfig(options, config, configEnv);
1440
1533
  log.debug("additional vite config", extraViteConfig);
1441
1534
  return extraViteConfig;
1442
1535
  },
1443
1536
  async configResolved(config) {
1444
- addExtraPreprocessors(options, config);
1537
+ options = resolveOptions(options, config);
1538
+ patchResolvedViteConfig(config, options);
1445
1539
  requestParser = buildIdParser(options);
1446
1540
  compileSvelte2 = createCompileSvelte(options);
1447
1541
  viteConfig = config;
1448
1542
  log.debug("resolved options", options);
1449
1543
  },
1544
+ async buildStart() {
1545
+ await handleOptimizeDeps(options, viteConfig);
1546
+ },
1450
1547
  configureServer(server) {
1451
1548
  options.server = server;
1452
1549
  setupWatchers(options, cache, requestParser);
@@ -1493,21 +1590,13 @@ function svelte(inlineOptions) {
1493
1590
  return resolvedSvelteSSR;
1494
1591
  }
1495
1592
  try {
1496
- const resolved = resolveViaPackageJsonSvelte(importee, importer);
1593
+ const resolved = resolveViaPackageJsonSvelte(importee, importer, cache);
1497
1594
  if (resolved) {
1498
1595
  log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`);
1499
1596
  return resolved;
1500
1597
  }
1501
1598
  } catch (err) {
1502
- switch (err.code) {
1503
- case "ERR_PACKAGE_PATH_NOT_EXPORTED":
1504
- pkg_export_errors.add(importee);
1505
- return null;
1506
- case "MODULE_NOT_FOUND":
1507
- return null;
1508
- default:
1509
- throw err;
1510
- }
1599
+ pkg_resolve_errors.add(importee);
1511
1600
  }
1512
1601
  },
1513
1602
  async transform(code, id, opts) {
@@ -1533,7 +1622,7 @@ function svelte(inlineOptions) {
1533
1622
  try {
1534
1623
  compileData = await compileSvelte2(svelteRequest, code, options);
1535
1624
  } catch (e) {
1536
- throw toRollupError(e);
1625
+ throw toRollupError(e, options);
1537
1626
  }
1538
1627
  logCompilerWarnings(compileData.compiled.warnings, options);
1539
1628
  cache.update(compileData);
@@ -1555,14 +1644,17 @@ function svelte(inlineOptions) {
1555
1644
  }
1556
1645
  },
1557
1646
  buildEnd() {
1558
- if (pkg_export_errors.size > 0) {
1559
- 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"));
1647
+ if (pkg_resolve_errors.size > 0) {
1648
+ 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.
1649
+ If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.
1650
+ ${Array.from(pkg_resolve_errors, (s) => `- ${s}`).join("\n")}`.replace(/\t/g, ""));
1560
1651
  }
1561
1652
  }
1562
1653
  };
1563
1654
  }
1655
+ module.exports = __toCommonJS(src_exports);
1564
1656
  // Annotate the CommonJS export names for ESM import in node:
1565
1657
  0 && (module.exports = {
1566
1658
  svelte
1567
1659
  });
1568
- //# sourceMappingURL=index.cjs.map
1660
+ //# sourceMappingURL=index.cjs.map