@sveltejs/vite-plugin-svelte 1.0.0-next.31 → 1.0.0-next.35

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.4/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;
@@ -203,7 +209,7 @@ async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, option
203
209
  const content = await read();
204
210
  const compileData = await compileSvelte2(svelteRequest, content, options);
205
211
  cache.update(compileData);
206
- const affectedModules = new Set();
212
+ const affectedModules = /* @__PURE__ */ new Set();
207
213
  const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId);
208
214
  const mainModule = server.moduleGraph.getModuleById(svelteRequest.id);
209
215
  const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css);
@@ -263,12 +269,12 @@ function normalizeJsCode(code) {
263
269
  }
264
270
 
265
271
  // src/utils/compile.ts
266
- var import_compiler = __toModule(require("svelte/compiler"));
267
- var import_svelte_hmr = __toModule(require("svelte-hmr"));
272
+ var import_compiler = require("svelte/compiler");
273
+ var import_svelte_hmr = require("svelte-hmr");
268
274
 
269
275
  // src/utils/hash.ts
270
- var crypto = __toModule(require("crypto"));
271
- var hashes = Object.create(null);
276
+ var crypto = __toESM(require("crypto"), 1);
277
+ var hashes = /* @__PURE__ */ Object.create(null);
272
278
  var hash_length = 12;
273
279
  function safeBase64Hash(input) {
274
280
  if (hashes[input]) {
@@ -375,9 +381,9 @@ function createCompileSvelte(options) {
375
381
  }
376
382
 
377
383
  // 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"));
384
+ var import_pluginutils = require("@rollup/pluginutils");
385
+ var import_vite = require("vite");
386
+ var fs = __toESM(require("fs"), 1);
381
387
  var VITE_FS_PREFIX = "/@fs/";
382
388
  var IS_WINDOWS = process.platform === "win32";
383
389
  function splitId(id) {
@@ -453,13 +459,13 @@ function buildIdParser(options) {
453
459
  }
454
460
 
455
461
  // src/utils/options.ts
456
- var import_vite2 = __toModule(require("vite"));
462
+ var import_vite3 = require("vite");
457
463
 
458
464
  // 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"));
465
+ var import_module = require("module");
466
+ var import_path = __toESM(require("path"), 1);
467
+ var import_fs = __toESM(require("fs"), 1);
468
+ var import_url = require("url");
463
469
  var esmRequire;
464
470
  var knownSvelteConfigNames = [
465
471
  "svelte.config.js",
@@ -488,7 +494,7 @@ async function loadSvelteConfig(viteConfig, inlineOptions) {
488
494
  }
489
495
  if (!configFile.endsWith(".mjs")) {
490
496
  try {
491
- const _require = importMetaUrlShim ? esmRequire ?? (esmRequire = (0, import_module.createRequire)(importMetaUrlShim)) : require;
497
+ const _require = importMetaUrl ? esmRequire ?? (esmRequire = (0, import_module.createRequire)(importMetaUrl)) : require;
492
498
  delete _require.cache[_require.resolve(configFile)];
493
499
  const result = _require(configFile);
494
500
  if (result != null) {
@@ -548,12 +554,12 @@ var SVELTE_HMR_IMPORTS = [
548
554
  ];
549
555
 
550
556
  // src/utils/options.ts
551
- var import_path3 = __toModule(require("path"));
557
+ var import_path3 = __toESM(require("path"), 1);
552
558
 
553
559
  // 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"));
560
+ var import_path2 = __toESM(require("path"), 1);
561
+ var import_fs2 = __toESM(require("fs"), 1);
562
+ var import_module2 = require("module");
557
563
  function findRootSvelteDependencies(root, cwdFallback = true) {
558
564
  log.debug(`findSvelteDependencies: searching svelte dependencies in ${root}`);
559
565
  const pkgFile = import_path2.default.join(root, "package.json");
@@ -578,7 +584,7 @@ function findRootSvelteDependencies(root, cwdFallback = true) {
578
584
  ].filter((dep) => !is_common_without_svelte_field(dep));
579
585
  return getSvelteDependencies(deps, root);
580
586
  }
581
- function getSvelteDependencies(deps, pkgDir, path6 = []) {
587
+ function getSvelteDependencies(deps, pkgDir, path7 = []) {
582
588
  const result = [];
583
589
  const localRequire = (0, import_module2.createRequire)(`${pkgDir}/package.json`);
584
590
  const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
@@ -586,18 +592,18 @@ function getSvelteDependencies(deps, pkgDir, path6 = []) {
586
592
  const type = getSvelteDependencyType(pkg);
587
593
  if (!type)
588
594
  continue;
589
- result.push({ name: pkg.name, type, pkg, dir, path: path6 });
595
+ result.push({ name: pkg.name, type, pkg, dir, path: path7 });
590
596
  if (type === "component-library" && pkg.dependencies) {
591
597
  let dependencyNames = Object.keys(pkg.dependencies);
592
- const circular = dependencyNames.filter((name) => path6.includes(name));
598
+ const circular = dependencyNames.filter((name) => path7.includes(name));
593
599
  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));
600
+ log.warn.enabled && log.warn(`skipping circular svelte dependencies in automated vite optimizeDeps handling`, circular.map((x) => path7.concat(x).join(">")));
601
+ dependencyNames = dependencyNames.filter((name) => !path7.includes(name));
596
602
  }
597
- if (path6.length === 3) {
598
- log.debug.once(`encountered deep svelte dependency tree: ${path6.join(">")}`);
603
+ if (path7.length === 3) {
604
+ log.debug.once(`encountered deep svelte dependency tree: ${path7.join(">")}`);
599
605
  }
600
- result.push(...getSvelteDependencies(dependencyNames, dir, path6.concat(pkg.name)));
606
+ result.push(...getSvelteDependencies(dependencyNames, dir, path7.concat(pkg.name)));
601
607
  }
602
608
  }
603
609
  return result;
@@ -696,15 +702,19 @@ function needsOptimization(dep, localRequire) {
696
702
  if (!depData)
697
703
  return false;
698
704
  const pkg = depData.pkg;
699
- return pkg.main && !pkg.module && !pkg.exports;
705
+ const isCjs = pkg.main && !pkg.module && !pkg.exports;
706
+ if (!isCjs)
707
+ return false;
708
+ const entryExt = import_path2.default.extname(pkg.main);
709
+ return !entryExt || entryExt === ".js" || entryExt === ".cjs";
700
710
  }
701
711
 
702
712
  // src/utils/options.ts
703
- var import_module3 = __toModule(require("module"));
713
+ var import_module3 = require("module");
704
714
 
705
715
  // src/utils/esbuild.ts
706
- var import_fs3 = __toModule(require("fs"));
707
- var import_compiler2 = __toModule(require("svelte/compiler"));
716
+ var import_fs3 = require("fs");
717
+ var import_compiler2 = require("svelte/compiler");
708
718
 
709
719
  // src/utils/error.ts
710
720
  function toRollupError(error) {
@@ -757,6 +767,7 @@ function formatFrameForVite(frame) {
757
767
  }
758
768
 
759
769
  // src/utils/esbuild.ts
770
+ var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
760
771
  function esbuildSveltePlugin(options) {
761
772
  return {
762
773
  name: "vite-plugin-svelte:optimize-svelte",
@@ -798,6 +809,7 @@ async function compileSvelte(options, { filename, code }) {
798
809
  const compileOptions = __spreadProps(__spreadValues({}, options.compilerOptions), {
799
810
  css: true,
800
811
  filename,
812
+ format: "esm",
801
813
  generate: "dom"
802
814
  });
803
815
  let preprocessed;
@@ -820,8 +832,235 @@ async function compileSvelte(options, { filename, code }) {
820
832
  return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
821
833
  }
822
834
 
835
+ // src/utils/preprocess.ts
836
+ var import_vite2 = require("vite");
837
+ var import_magic_string2 = __toESM(require("magic-string"), 1);
838
+ var import_compiler3 = require("svelte/compiler");
839
+
840
+ // src/utils/sourcemap.ts
841
+ var import_magic_string = __toESM(require("magic-string"), 1);
842
+ async function buildMagicString(from, to, options) {
843
+ let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
844
+ try {
845
+ const dmpPkg = await import("diff-match-patch");
846
+ diff_match_patch = dmpPkg.diff_match_patch;
847
+ DIFF_INSERT = dmpPkg.DIFF_INSERT;
848
+ DIFF_DELETE = dmpPkg.DIFF_DELETE;
849
+ } catch (e) {
850
+ log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
851
+ return null;
852
+ }
853
+ const dmp = new diff_match_patch();
854
+ const diffs = dmp.diff_main(from, to);
855
+ dmp.diff_cleanupSemantic(diffs);
856
+ const m = new import_magic_string.default(from, options);
857
+ let pos = 0;
858
+ for (let i = 0; i < diffs.length; i++) {
859
+ const diff = diffs[i];
860
+ const nextDiff = diffs[i + 1];
861
+ if (diff[0] === DIFF_DELETE) {
862
+ if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
863
+ m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
864
+ i++;
865
+ } else {
866
+ m.remove(pos, pos + diff[1].length);
867
+ }
868
+ pos += diff[1].length;
869
+ } else if (diff[0] === DIFF_INSERT) {
870
+ if (nextDiff) {
871
+ m.appendRight(pos, diff[1]);
872
+ } else {
873
+ m.append(diff[1]);
874
+ }
875
+ } else {
876
+ pos += diff[1].length;
877
+ }
878
+ }
879
+ return m;
880
+ }
881
+ async function buildSourceMap(from, to, filename) {
882
+ const m = await buildMagicString(from, to, { filename });
883
+ return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
884
+ }
885
+
886
+ // src/utils/preprocess.ts
887
+ var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
888
+ var supportedScriptLangs = ["ts"];
889
+ function createViteScriptPreprocessor() {
890
+ return async ({ attributes, content, filename = "" }) => {
891
+ const lang = attributes.lang;
892
+ if (!supportedScriptLangs.includes(lang))
893
+ return;
894
+ const transformResult = await (0, import_vite2.transformWithEsbuild)(content, filename, {
895
+ loader: lang,
896
+ tsconfigRaw: {
897
+ compilerOptions: {
898
+ importsNotUsedAsValues: "preserve",
899
+ preserveValueImports: true
900
+ }
901
+ }
902
+ });
903
+ return {
904
+ code: transformResult.code,
905
+ map: transformResult.map
906
+ };
907
+ };
908
+ }
909
+ function createViteStylePreprocessor(config) {
910
+ const pluginName = "vite:css";
911
+ const plugin = config.plugins.find((p) => p.name === pluginName);
912
+ if (!plugin) {
913
+ throw new Error(`failed to find plugin ${pluginName}`);
914
+ }
915
+ if (!plugin.transform) {
916
+ throw new Error(`plugin ${pluginName} has no transform`);
917
+ }
918
+ const pluginTransform = plugin.transform.bind(null);
919
+ return async ({ attributes, content, filename = "" }) => {
920
+ var _a, _b;
921
+ const lang = attributes.lang;
922
+ if (!supportedStyleLangs.includes(lang))
923
+ return;
924
+ const moduleId = `${filename}.${lang}`;
925
+ const transformResult = await pluginTransform(content, moduleId);
926
+ if (((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
927
+ transformResult.map.sources[0] = filename;
928
+ }
929
+ return {
930
+ code: transformResult.code,
931
+ map: transformResult.map ?? void 0
932
+ };
933
+ };
934
+ }
935
+ function createVitePreprocessorGroup(config) {
936
+ return {
937
+ markup({ content, filename }) {
938
+ return (0, import_compiler3.preprocess)(content, {
939
+ script: createViteScriptPreprocessor(),
940
+ style: createViteStylePreprocessor(config)
941
+ }, { filename });
942
+ }
943
+ };
944
+ }
945
+ function createInjectScopeEverythingRulePreprocessorGroup() {
946
+ return {
947
+ style({ content, filename }) {
948
+ const s = new import_magic_string2.default(content);
949
+ s.append(" *{}");
950
+ return {
951
+ code: s.toString(),
952
+ map: s.generateDecodedMap({ source: filename, hires: true })
953
+ };
954
+ }
955
+ };
956
+ }
957
+ function buildExtraPreprocessors(options, config) {
958
+ var _a, _b;
959
+ const prependPreprocessors = [];
960
+ const appendPreprocessors = [];
961
+ if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
962
+ log.debug("adding vite preprocessor");
963
+ prependPreprocessors.push(createVitePreprocessorGroup(config));
964
+ }
965
+ const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
966
+ if (pluginsWithPreprocessorsDeprecated.length > 0) {
967
+ 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(", ")}`);
968
+ pluginsWithPreprocessorsDeprecated.forEach((p) => {
969
+ if (!p.api) {
970
+ p.api = {};
971
+ }
972
+ if (p.api.sveltePreprocess === void 0) {
973
+ p.api.sveltePreprocess = p.sveltePreprocess;
974
+ } else {
975
+ log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
976
+ }
977
+ });
978
+ }
979
+ const pluginsWithPreprocessors = config.plugins.filter((p) => {
980
+ var _a2;
981
+ return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
982
+ });
983
+ const ignored = [], included = [];
984
+ for (const p of pluginsWithPreprocessors) {
985
+ if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
986
+ ignored.push(p);
987
+ } else {
988
+ included.push(p);
989
+ }
990
+ }
991
+ if (ignored.length > 0) {
992
+ log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
993
+ }
994
+ if (included.length > 0) {
995
+ log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
996
+ appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
997
+ }
998
+ if (options.hot && options.emitCss) {
999
+ appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
1000
+ }
1001
+ return { prependPreprocessors, appendPreprocessors };
1002
+ }
1003
+ function addExtraPreprocessors(options, config) {
1004
+ var _a;
1005
+ const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
1006
+ if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
1007
+ if (!options.preprocess) {
1008
+ options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
1009
+ } else if (Array.isArray(options.preprocess)) {
1010
+ options.preprocess.unshift(...prependPreprocessors);
1011
+ options.preprocess.push(...appendPreprocessors);
1012
+ } else {
1013
+ options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
1014
+ }
1015
+ }
1016
+ const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
1017
+ if (options.preprocess && generateMissingSourceMaps) {
1018
+ options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
1019
+ }
1020
+ }
1021
+ function validateSourceMapOutputWrapper(group, i) {
1022
+ const wrapper = {};
1023
+ for (const [processorType, processorFn] of Object.entries(group)) {
1024
+ wrapper[processorType] = async (options) => {
1025
+ var _a;
1026
+ const result = await processorFn(options);
1027
+ if (result && result.code !== options.content) {
1028
+ let invalidMap = false;
1029
+ if (!result.map) {
1030
+ invalidMap = true;
1031
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
1032
+ filename: options.filename,
1033
+ type: processorType,
1034
+ processor: processorFn.toString()
1035
+ });
1036
+ } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
1037
+ invalidMap = true;
1038
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
1039
+ filename: options.filename,
1040
+ type: processorType,
1041
+ processor: processorFn.toString()
1042
+ });
1043
+ }
1044
+ if (invalidMap) {
1045
+ try {
1046
+ const map = await buildSourceMap(options.content, result.code, options.filename);
1047
+ if (map) {
1048
+ log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
1049
+ result.map = map;
1050
+ }
1051
+ } catch (e) {
1052
+ log.error(`failed to build sourcemap`, e);
1053
+ }
1054
+ }
1055
+ }
1056
+ return result;
1057
+ };
1058
+ }
1059
+ return wrapper;
1060
+ }
1061
+
823
1062
  // src/utils/options.ts
824
- var knownOptions = new Set([
1063
+ var knownOptions = /* @__PURE__ */ new Set([
825
1064
  "configFile",
826
1065
  "include",
827
1066
  "exclude",
@@ -835,28 +1074,53 @@ var knownOptions = new Set([
835
1074
  "disableDependencyReinclusion",
836
1075
  "experimental"
837
1076
  ]);
838
- function buildDefaultOptions(isProduction, emitCss = true) {
839
- const hot = isProduction ? false : {
840
- injectCss: !emitCss
841
- };
1077
+ function validateInlineOptions(inlineOptions) {
1078
+ const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
1079
+ if (invalidKeys.length) {
1080
+ log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in config`, inlineOptions);
1081
+ }
1082
+ }
1083
+ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1084
+ const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteUserConfig), {
1085
+ root: resolveViteRoot(viteUserConfig)
1086
+ });
842
1087
  const defaultOptions = {
843
1088
  extensions: [".svelte"],
844
- hot,
845
- emitCss,
1089
+ emitCss: true,
846
1090
  compilerOptions: {
847
- format: "esm",
848
- css: !emitCss,
849
- dev: !isProduction
1091
+ format: "esm"
850
1092
  }
851
1093
  };
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);
1094
+ const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions);
1095
+ const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), {
1096
+ compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.compilerOptions), svelteConfig == null ? void 0 : svelteConfig.compilerOptions), inlineOptions == null ? void 0 : inlineOptions.compilerOptions),
1097
+ experimental: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.experimental), svelteConfig == null ? void 0 : svelteConfig.experimental), inlineOptions == null ? void 0 : inlineOptions.experimental),
1098
+ root: viteConfigWithResolvedRoot.root,
1099
+ isBuild: viteEnv.command === "build",
1100
+ isServe: viteEnv.command === "serve"
1101
+ });
1102
+ if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
1103
+ merged.configFile = svelteConfig.configFile;
859
1104
  }
1105
+ return merged;
1106
+ }
1107
+ function resolveOptions(preResolveOptions2, viteConfig) {
1108
+ const defaultOptions = {
1109
+ hot: viteConfig.isProduction ? false : { injectCss: !preResolveOptions2.emitCss },
1110
+ compilerOptions: {
1111
+ css: !preResolveOptions2.emitCss,
1112
+ dev: !viteConfig.isProduction
1113
+ }
1114
+ };
1115
+ const merged = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), preResolveOptions2), {
1116
+ compilerOptions: __spreadValues(__spreadValues({}, defaultOptions.compilerOptions), preResolveOptions2.compilerOptions),
1117
+ root: viteConfig.root,
1118
+ isProduction: viteConfig.isProduction
1119
+ });
1120
+ addExtraPreprocessors(merged, viteConfig);
1121
+ enforceOptionsForHmr(merged);
1122
+ enforceOptionsForProduction(merged);
1123
+ return merged;
860
1124
  }
861
1125
  function enforceOptionsForHmr(options) {
862
1126
  if (options.hot) {
@@ -901,33 +1165,8 @@ function enforceOptionsForProduction(options) {
901
1165
  }
902
1166
  }
903
1167
  }
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
- });
913
- if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
914
- merged.configFile = svelteConfig.configFile;
915
- }
916
- return merged;
917
- }
918
- async function resolveOptions(inlineOptions = {}, viteConfig, viteEnv) {
919
- const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteConfig), {
920
- root: resolveViteRoot(viteConfig)
921
- });
922
- const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions) || {};
923
- const defaultOptions = buildDefaultOptions(viteEnv.mode === "production", inlineOptions.emitCss ?? svelteConfig.emitCss);
924
- const resolvedOptions = mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfigWithResolvedRoot, viteEnv);
925
- enforceOptionsForProduction(resolvedOptions);
926
- enforceOptionsForHmr(resolvedOptions);
927
- return resolvedOptions;
928
- }
929
1168
  function resolveViteRoot(viteConfig) {
930
- return (0, import_vite2.normalizePath)(viteConfig.root ? import_path3.default.resolve(viteConfig.root) : process.cwd());
1169
+ return (0, import_vite3.normalizePath)(viteConfig.root ? import_path3.default.resolve(viteConfig.root) : process.cwd());
931
1170
  }
932
1171
  function buildExtraViteConfig(options, config, configEnv) {
933
1172
  const svelteDeps = findRootSvelteDependencies(options.root);
@@ -943,16 +1182,16 @@ function buildExtraViteConfig(options, config, configEnv) {
943
1182
  extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config);
944
1183
  return extraViteConfig;
945
1184
  }
946
- function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
1185
+ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps2) {
947
1186
  const include = [];
948
1187
  const exclude = ["svelte-hmr"];
949
1188
  const isIncluded = (dep) => {
950
1189
  var _a;
951
- return include.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a.includes(dep));
1190
+ return include.includes(dep) || ((_a = optimizeDeps2 == null ? void 0 : optimizeDeps2.include) == null ? void 0 : _a.includes(dep));
952
1191
  };
953
1192
  const isExcluded = (dep) => {
954
1193
  var _a;
955
- return exclude.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
1194
+ return exclude.includes(dep) || ((_a = optimizeDeps2 == null ? void 0 : optimizeDeps2.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
956
1195
  };
957
1196
  if (!isExcluded("svelte")) {
958
1197
  const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
@@ -966,7 +1205,8 @@ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
966
1205
  include,
967
1206
  exclude,
968
1207
  esbuildOptions: {
969
- plugins: [esbuildSveltePlugin(options)]
1208
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1209
+ } }]
970
1210
  }
971
1211
  };
972
1212
  }
@@ -1006,14 +1246,22 @@ function buildSSROptionsForSvelte(svelteDeps, options, config) {
1006
1246
  noExternal
1007
1247
  };
1008
1248
  }
1249
+ function patchResolvedViteConfig(viteConfig, options) {
1250
+ var _a, _b;
1251
+ const facadeEsbuildSveltePlugin = (_b = (_a = viteConfig.optimizeDeps.esbuildOptions) == null ? void 0 : _a.plugins) == null ? void 0 : _b.find((plugin) => plugin.name === facadeEsbuildSveltePluginName);
1252
+ if (facadeEsbuildSveltePlugin) {
1253
+ Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options));
1254
+ }
1255
+ }
1009
1256
 
1010
1257
  // src/utils/vite-plugin-svelte-cache.ts
1011
1258
  var VitePluginSvelteCache = class {
1012
1259
  constructor() {
1013
- this._css = new Map();
1014
- this._js = new Map();
1015
- this._dependencies = new Map();
1016
- this._dependants = new Map();
1260
+ this._css = /* @__PURE__ */ new Map();
1261
+ this._js = /* @__PURE__ */ new Map();
1262
+ this._dependencies = /* @__PURE__ */ new Map();
1263
+ this._dependants = /* @__PURE__ */ new Map();
1264
+ this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1017
1265
  }
1018
1266
  update(compileData) {
1019
1267
  this.updateCSS(compileData);
@@ -1037,7 +1285,7 @@ var VitePluginSvelteCache = class {
1037
1285
  const added = dependencies.filter((d) => !prevDependencies.includes(d));
1038
1286
  added.forEach((d) => {
1039
1287
  if (!this._dependants.has(d)) {
1040
- this._dependants.set(d, new Set());
1288
+ this._dependants.set(d, /* @__PURE__ */ new Set());
1041
1289
  }
1042
1290
  this._dependants.get(d).add(compileData.filename);
1043
1291
  });
@@ -1075,22 +1323,31 @@ var VitePluginSvelteCache = class {
1075
1323
  return this._js.get(svelteRequest.normalizedFilename);
1076
1324
  }
1077
1325
  }
1078
- getDependants(path6) {
1079
- const dependants = this._dependants.get(path6);
1326
+ getDependants(path7) {
1327
+ const dependants = this._dependants.get(path7);
1080
1328
  return dependants ? [...dependants] : [];
1081
1329
  }
1330
+ getResolvedSvelteField(name, importer) {
1331
+ return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
1332
+ }
1333
+ setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
1334
+ this._resolvedSvelteFields.set(this._getResolvedSvelteFieldKey(importee, importer), resolvedSvelte);
1335
+ }
1336
+ _getResolvedSvelteFieldKey(importee, importer) {
1337
+ return importer ? `${importer} > ${importee}` : importee;
1338
+ }
1082
1339
  };
1083
1340
 
1084
1341
  // src/utils/watch.ts
1085
- var import_fs4 = __toModule(require("fs"));
1086
- var import_path4 = __toModule(require("path"));
1342
+ var import_fs4 = __toESM(require("fs"), 1);
1343
+ var import_path4 = __toESM(require("path"), 1);
1087
1344
  function setupWatchers(options, cache, requestParser) {
1088
1345
  const { server, configFile: svelteConfigFile } = options;
1089
1346
  if (!server) {
1090
1347
  return;
1091
1348
  }
1092
1349
  const { watcher, ws } = server;
1093
- const { configFile: viteConfigFile, root, server: serverConfig } = server.config;
1350
+ const { root, server: serverConfig } = server.config;
1094
1351
  const emitChangeEventOnDependants = (filename) => {
1095
1352
  const dependants = cache.getDependants(filename);
1096
1353
  dependants.forEach((dependant) => {
@@ -1110,16 +1367,16 @@ function setupWatchers(options, cache, requestParser) {
1110
1367
  }
1111
1368
  };
1112
1369
  const triggerViteRestart = (filename) => {
1113
- if (!!viteConfigFile && !serverConfig.middlewareMode) {
1114
- log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1115
- watcher.emit("change", viteConfigFile);
1116
- } else {
1370
+ if (serverConfig.middlewareMode) {
1117
1371
  const message = "Svelte config change detected, restart your dev process to apply the changes.";
1118
1372
  log.info(message, filename);
1119
1373
  ws.send({
1120
1374
  type: "error",
1121
1375
  err: { message, stack: "", plugin: "vite-plugin-svelte", id: filename }
1122
1376
  });
1377
+ } else {
1378
+ log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1379
+ server.restart();
1123
1380
  }
1124
1381
  };
1125
1382
  const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => import_path4.default.join(root, cfg));
@@ -1157,20 +1414,30 @@ function ensureWatchedFile(watcher, file, root) {
1157
1414
  }
1158
1415
 
1159
1416
  // src/utils/resolve.ts
1160
- var import_path5 = __toModule(require("path"));
1161
- var import_fs5 = __toModule(require("fs"));
1162
- var import_require_relative = __toModule(require("require-relative"));
1163
- function resolveViaPackageJsonSvelte(importee, importer) {
1164
- if (importer && isBareImport(importee)) {
1165
- const importeePkgFile = import_require_relative.default.resolve(`${importee}/package.json`, import_path5.default.dirname(importer));
1166
- const importeePkg = JSON.parse(import_fs5.default.readFileSync(importeePkgFile, { encoding: "utf-8" }));
1167
- if (importeePkg.svelte) {
1168
- return import_path5.default.resolve(import_path5.default.dirname(importeePkgFile), importeePkg.svelte);
1417
+ var import_path5 = __toESM(require("path"), 1);
1418
+ var import_module4 = require("module");
1419
+ function resolveViaPackageJsonSvelte(importee, importer, cache) {
1420
+ if (importer && isBareImport(importee) && !is_common_without_svelte_field(importee)) {
1421
+ const cached = cache.getResolvedSvelteField(importee, importer);
1422
+ if (cached) {
1423
+ return cached;
1424
+ }
1425
+ const localRequire = (0, import_module4.createRequire)(importer);
1426
+ const pkgData = resolveDependencyData(importee, localRequire);
1427
+ if (pkgData) {
1428
+ const { pkg, dir } = pkgData;
1429
+ if (pkg.svelte) {
1430
+ const result = import_path5.default.resolve(dir, pkg.svelte);
1431
+ cache.setResolvedSvelteField(importee, importer, result);
1432
+ return result;
1433
+ }
1434
+ } else {
1435
+ throw new Error(`failed to resolve package.json of ${importee} imported by ${importer}`);
1169
1436
  }
1170
1437
  }
1171
1438
  }
1172
1439
  function isBareImport(importee) {
1173
- if (!importee || importee[0] === "." || importee[0] === "\0" || import_path5.default.isAbsolute(importee)) {
1440
+ if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || import_path5.default.isAbsolute(importee)) {
1174
1441
  return false;
1175
1442
  }
1176
1443
  const parts = importee.split("/");
@@ -1184,231 +1451,42 @@ function isBareImport(importee) {
1184
1451
  }
1185
1452
  }
1186
1453
 
1187
- // src/utils/preprocess.ts
1188
- var import_vite3 = __toModule(require("vite"));
1189
- var import_magic_string2 = __toModule(require("magic-string"));
1190
- var import_compiler3 = __toModule(require("svelte/compiler"));
1191
-
1192
- // src/utils/sourcemap.ts
1193
- var import_magic_string = __toModule(require("magic-string"));
1194
- async function buildMagicString(from, to, options) {
1195
- let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
1196
- try {
1197
- const dmpPkg = await import("diff-match-patch");
1198
- diff_match_patch = dmpPkg.diff_match_patch;
1199
- DIFF_INSERT = dmpPkg.DIFF_INSERT;
1200
- DIFF_DELETE = dmpPkg.DIFF_DELETE;
1201
- } catch (e) {
1202
- log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
1203
- return null;
1204
- }
1205
- const dmp = new diff_match_patch();
1206
- const diffs = dmp.diff_main(from, to);
1207
- dmp.diff_cleanupSemantic(diffs);
1208
- const m = new import_magic_string.default(from, options);
1209
- let pos = 0;
1210
- for (let i = 0; i < diffs.length; i++) {
1211
- const diff = diffs[i];
1212
- const nextDiff = diffs[i + 1];
1213
- if (diff[0] === DIFF_DELETE) {
1214
- if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
1215
- m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
1216
- i++;
1217
- } else {
1218
- m.remove(pos, pos + diff[1].length);
1219
- }
1220
- pos += diff[1].length;
1221
- } else if (diff[0] === DIFF_INSERT) {
1222
- if (nextDiff) {
1223
- m.appendRight(pos, diff[1]);
1224
- } else {
1225
- m.append(diff[1]);
1226
- }
1227
- } else {
1228
- pos += diff[1].length;
1229
- }
1230
- }
1231
- return m;
1232
- }
1233
- async function buildSourceMap(from, to, filename) {
1234
- const m = await buildMagicString(from, to, { filename });
1235
- return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
1236
- }
1237
-
1238
- // src/utils/preprocess.ts
1239
- var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
1240
- var supportedScriptLangs = ["ts"];
1241
- function createViteScriptPreprocessor() {
1242
- return async ({ attributes, content, filename = "" }) => {
1243
- const lang = attributes.lang;
1244
- if (!supportedScriptLangs.includes(lang))
1245
- return;
1246
- const transformResult = await (0, import_vite3.transformWithEsbuild)(content, filename, {
1247
- loader: lang,
1248
- tsconfigRaw: {
1249
- compilerOptions: {
1250
- importsNotUsedAsValues: "preserve"
1251
- }
1252
- }
1253
- });
1254
- return {
1255
- code: transformResult.code,
1256
- map: transformResult.map
1257
- };
1258
- };
1259
- }
1260
- function createViteStylePreprocessor(config) {
1261
- const pluginName = "vite:css";
1262
- const plugin = config.plugins.find((p) => p.name === pluginName);
1263
- if (!plugin) {
1264
- throw new Error(`failed to find plugin ${pluginName}`);
1265
- }
1266
- if (!plugin.transform) {
1267
- throw new Error(`plugin ${pluginName} has no transform`);
1268
- }
1269
- const pluginTransform = plugin.transform.bind(null);
1270
- return async ({ attributes, content, filename = "" }) => {
1271
- var _a, _b;
1272
- const lang = attributes.lang;
1273
- if (!supportedStyleLangs.includes(lang))
1274
- return;
1275
- const moduleId = `${filename}.${lang}`;
1276
- const transformResult = await pluginTransform(content, moduleId);
1277
- const hasMap = transformResult.map && transformResult.map.mappings !== "";
1278
- if (hasMap && ((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
1279
- transformResult.map.sources[0] = filename;
1280
- }
1281
- return {
1282
- code: transformResult.code,
1283
- map: hasMap ? transformResult.map : void 0
1284
- };
1285
- };
1286
- }
1287
- function createVitePreprocessorGroup(config) {
1288
- return {
1289
- markup({ content, filename }) {
1290
- return (0, import_compiler3.preprocess)(content, {
1291
- script: createViteScriptPreprocessor(),
1292
- style: createViteStylePreprocessor(config)
1293
- }, { filename });
1294
- }
1295
- };
1296
- }
1297
- function createInjectScopeEverythingRulePreprocessorGroup() {
1298
- return {
1299
- style({ content, filename }) {
1300
- const s = new import_magic_string2.default(content);
1301
- s.append(" *{}");
1302
- return {
1303
- code: s.toString(),
1304
- map: s.generateDecodedMap({ source: filename, hires: true })
1305
- };
1306
- }
1307
- };
1308
- }
1309
- function buildExtraPreprocessors(options, config) {
1310
- var _a, _b;
1311
- const prependPreprocessors = [];
1312
- const appendPreprocessors = [];
1313
- if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
1314
- log.debug("adding vite preprocessor");
1315
- prependPreprocessors.push(createVitePreprocessorGroup(config));
1316
- }
1317
- const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
1318
- if (pluginsWithPreprocessorsDeprecated.length > 0) {
1319
- 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(", ")}`);
1320
- pluginsWithPreprocessorsDeprecated.forEach((p) => {
1321
- if (!p.api) {
1322
- p.api = {};
1323
- }
1324
- if (p.api.sveltePreprocess === void 0) {
1325
- p.api.sveltePreprocess = p.sveltePreprocess;
1326
- } else {
1327
- log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
1328
- }
1329
- });
1330
- }
1331
- const pluginsWithPreprocessors = config.plugins.filter((p) => {
1332
- var _a2;
1333
- return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
1454
+ // src/utils/optimizer.ts
1455
+ var import_fs5 = __toESM(require("fs"), 1);
1456
+ var import_path6 = __toESM(require("path"), 1);
1457
+ var import_vite4 = require("vite");
1458
+ var PREBUNDLE_SENSITIVE_OPTIONS = [
1459
+ "compilerOptions",
1460
+ "configFile",
1461
+ "experimental",
1462
+ "extensions",
1463
+ "ignorePluginPreprocessors",
1464
+ "preprocess"
1465
+ ];
1466
+ async function handleOptimizeDeps(options, viteConfig) {
1467
+ if (!options.experimental.prebundleSvelteLibraries || !viteConfig.cacheDir)
1468
+ return;
1469
+ const viteMetadataPath = import_path6.default.resolve(viteConfig.cacheDir, "_metadata.json");
1470
+ if (!import_fs5.default.existsSync(viteMetadataPath))
1471
+ return;
1472
+ const svelteMetadataPath = import_path6.default.resolve(viteConfig.cacheDir, "_svelte_metadata.json");
1473
+ const currentSvelteMetadata = JSON.stringify(generateSvelteMetadata(options), (_, value) => {
1474
+ return typeof value === "function" ? value.toString() : value;
1334
1475
  });
1335
- const ignored = [], included = [];
1336
- for (const p of pluginsWithPreprocessors) {
1337
- if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
1338
- ignored.push(p);
1339
- } else {
1340
- included.push(p);
1341
- }
1342
- }
1343
- if (ignored.length > 0) {
1344
- log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
1345
- }
1346
- if (included.length > 0) {
1347
- log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
1348
- appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
1349
- }
1350
- if (options.hot && options.emitCss) {
1351
- appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
1352
- }
1353
- return { prependPreprocessors, appendPreprocessors };
1354
- }
1355
- function addExtraPreprocessors(options, config) {
1356
- var _a;
1357
- const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
1358
- if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
1359
- if (!options.preprocess) {
1360
- options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
1361
- } else if (Array.isArray(options.preprocess)) {
1362
- options.preprocess.unshift(...prependPreprocessors);
1363
- options.preprocess.push(...appendPreprocessors);
1364
- } else {
1365
- options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
1366
- }
1367
- }
1368
- const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
1369
- if (options.preprocess && generateMissingSourceMaps) {
1370
- options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
1476
+ if (import_fs5.default.existsSync(svelteMetadataPath)) {
1477
+ const existingSvelteMetadata = import_fs5.default.readFileSync(svelteMetadataPath, "utf8");
1478
+ if (existingSvelteMetadata === currentSvelteMetadata)
1479
+ return;
1371
1480
  }
1481
+ await (0, import_vite4.optimizeDeps)(viteConfig, true);
1482
+ import_fs5.default.writeFileSync(svelteMetadataPath, currentSvelteMetadata);
1372
1483
  }
1373
- function validateSourceMapOutputWrapper(group, i) {
1374
- const wrapper = {};
1375
- for (const [processorType, processorFn] of Object.entries(group)) {
1376
- wrapper[processorType] = async (options) => {
1377
- var _a;
1378
- const result = await processorFn(options);
1379
- if (result && result.code !== options.content) {
1380
- let invalidMap = false;
1381
- if (!result.map) {
1382
- invalidMap = true;
1383
- log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
1384
- filename: options.filename,
1385
- type: processorType,
1386
- processor: processorFn.toString()
1387
- });
1388
- } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
1389
- invalidMap = true;
1390
- log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
1391
- filename: options.filename,
1392
- type: processorType,
1393
- processor: processorFn.toString()
1394
- });
1395
- }
1396
- if (invalidMap) {
1397
- try {
1398
- const map = await buildSourceMap(options.content, result.code, options.filename);
1399
- if (map) {
1400
- log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
1401
- result.map = map;
1402
- }
1403
- } catch (e) {
1404
- log.error(`failed to build sourcemap`, e);
1405
- }
1406
- }
1407
- }
1408
- return result;
1409
- };
1484
+ function generateSvelteMetadata(options) {
1485
+ const metadata = {};
1486
+ for (const key of PREBUNDLE_SENSITIVE_OPTIONS) {
1487
+ metadata[key] = options[key];
1410
1488
  }
1411
- return wrapper;
1489
+ return metadata;
1412
1490
  }
1413
1491
 
1414
1492
  // src/index.ts
@@ -1418,7 +1496,7 @@ function svelte(inlineOptions) {
1418
1496
  }
1419
1497
  validateInlineOptions(inlineOptions);
1420
1498
  const cache = new VitePluginSvelteCache();
1421
- const pkg_export_errors = new Set();
1499
+ const pkg_resolve_errors = /* @__PURE__ */ new Set();
1422
1500
  let requestParser;
1423
1501
  let options;
1424
1502
  let viteConfig;
@@ -1433,18 +1511,22 @@ function svelte(inlineOptions) {
1433
1511
  } else if (config.logLevel) {
1434
1512
  log.setLevel(config.logLevel);
1435
1513
  }
1436
- options = await resolveOptions(inlineOptions, config, configEnv);
1514
+ options = await preResolveOptions(inlineOptions, config, configEnv);
1437
1515
  const extraViteConfig = buildExtraViteConfig(options, config, configEnv);
1438
1516
  log.debug("additional vite config", extraViteConfig);
1439
1517
  return extraViteConfig;
1440
1518
  },
1441
1519
  async configResolved(config) {
1442
- addExtraPreprocessors(options, config);
1520
+ options = resolveOptions(options, config);
1521
+ patchResolvedViteConfig(config, options);
1443
1522
  requestParser = buildIdParser(options);
1444
1523
  compileSvelte2 = createCompileSvelte(options);
1445
1524
  viteConfig = config;
1446
1525
  log.debug("resolved options", options);
1447
1526
  },
1527
+ async buildStart() {
1528
+ await handleOptimizeDeps(options, viteConfig);
1529
+ },
1448
1530
  configureServer(server) {
1449
1531
  options.server = server;
1450
1532
  setupWatchers(options, cache, requestParser);
@@ -1467,9 +1549,9 @@ function svelte(inlineOptions) {
1467
1549
  }
1468
1550
  }
1469
1551
  },
1470
- async resolveId(importee, importer, opts, _ssr) {
1471
- const ssr = _ssr === true || opts.ssr;
1472
- const svelteRequest = requestParser(importee, !!ssr);
1552
+ async resolveId(importee, importer, opts) {
1553
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1554
+ const svelteRequest = requestParser(importee, ssr);
1473
1555
  if (svelteRequest == null ? void 0 : svelteRequest.query.svelte) {
1474
1556
  if (svelteRequest.query.type === "style") {
1475
1557
  log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
@@ -1491,27 +1573,19 @@ function svelte(inlineOptions) {
1491
1573
  return resolvedSvelteSSR;
1492
1574
  }
1493
1575
  try {
1494
- const resolved = resolveViaPackageJsonSvelte(importee, importer);
1576
+ const resolved = resolveViaPackageJsonSvelte(importee, importer, cache);
1495
1577
  if (resolved) {
1496
1578
  log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`);
1497
1579
  return resolved;
1498
1580
  }
1499
1581
  } 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
- }
1582
+ pkg_resolve_errors.add(importee);
1509
1583
  }
1510
1584
  },
1511
1585
  async transform(code, id, opts) {
1512
1586
  var _a;
1513
- const ssr = opts === true || (opts == null ? void 0 : opts.ssr);
1514
- const svelteRequest = requestParser(id, !!ssr);
1587
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1588
+ const svelteRequest = requestParser(id, ssr);
1515
1589
  if (!svelteRequest) {
1516
1590
  return;
1517
1591
  }
@@ -1553,14 +1627,17 @@ function svelte(inlineOptions) {
1553
1627
  }
1554
1628
  },
1555
1629
  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"));
1630
+ if (pkg_resolve_errors.size > 0) {
1631
+ 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.
1632
+ If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.
1633
+ ${Array.from(pkg_resolve_errors, (s) => `- ${s}`).join("\n")}`.replace(/\t/g, ""));
1558
1634
  }
1559
1635
  }
1560
1636
  };
1561
1637
  }
1638
+ module.exports = __toCommonJS(src_exports);
1562
1639
  // Annotate the CommonJS export names for ESM import in node:
1563
1640
  0 && (module.exports = {
1564
1641
  svelte
1565
1642
  });
1566
- //# sourceMappingURL=index.cjs.map
1643
+ //# sourceMappingURL=index.cjs.map