@sveltejs/vite-plugin-svelte 1.0.0-next.30 → 1.0.0-next.34

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.4.1_typescript@4.4.4/node_modules/tsup/assets/cjs_shims.js
48
- var importMetaUrlShim = typeof document === "undefined" ? new (require("url")).URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
52
+ // ../../node_modules/.pnpm/tsup@5.11.10_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_fs7 = __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 != null ? 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,27 +702,87 @@ 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");
714
+
715
+ // src/utils/esbuild.ts
716
+ var import_fs3 = require("fs");
717
+ var import_compiler2 = require("svelte/compiler");
718
+
719
+ // src/utils/error.ts
720
+ function toRollupError(error) {
721
+ const { filename, frame, start, code, name } = error;
722
+ const rollupError = {
723
+ name,
724
+ id: filename,
725
+ message: buildExtendedLogMessage(error),
726
+ frame: formatFrameForVite(frame),
727
+ code,
728
+ stack: ""
729
+ };
730
+ if (start) {
731
+ rollupError.loc = {
732
+ line: start.line,
733
+ column: start.column,
734
+ file: filename
735
+ };
736
+ }
737
+ return rollupError;
738
+ }
739
+ function toESBuildError(error) {
740
+ const { filename, frame, start } = error;
741
+ const partialMessage = {
742
+ text: buildExtendedLogMessage(error)
743
+ };
744
+ if (start) {
745
+ partialMessage.location = {
746
+ line: start.line,
747
+ column: start.column,
748
+ file: filename,
749
+ lineText: lineFromFrame(start.line, frame)
750
+ };
751
+ }
752
+ return partialMessage;
753
+ }
754
+ function lineFromFrame(lineNo, frame) {
755
+ if (!frame) {
756
+ return "";
757
+ }
758
+ const lines = frame.split("\n");
759
+ const errorLine = lines.find((line) => line.trimStart().startsWith(`${lineNo}: `));
760
+ return errorLine ? errorLine.substring(errorLine.indexOf(": ") + 3) : "";
761
+ }
762
+ function formatFrameForVite(frame) {
763
+ if (!frame) {
764
+ return "";
765
+ }
766
+ return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
767
+ }
704
768
 
705
769
  // src/utils/esbuild.ts
706
- var import_fs3 = __toModule(require("fs"));
707
- var import_compiler2 = __toModule(require("svelte/compiler"));
770
+ var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
708
771
  function esbuildSveltePlugin(options) {
709
772
  return {
710
773
  name: "vite-plugin-svelte:optimize-svelte",
711
774
  setup(build) {
712
- var _a;
713
775
  disableVitePrebundleSvelte(build);
714
- const svelteExtensions = ((_a = options.extensions) != null ? _a : [".svelte"]).map((ext) => ext.slice(1));
776
+ const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
715
777
  const svelteFilter = new RegExp(`\\.(` + svelteExtensions.join("|") + `)(\\?.*)?$`);
716
778
  build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
717
779
  const code = await import_fs3.promises.readFile(filename, "utf8");
718
- const contents = await compileSvelte(options, { filename, code });
719
- return { contents };
780
+ try {
781
+ const contents = await compileSvelte(options, { filename, code });
782
+ return { contents };
783
+ } catch (e) {
784
+ return { errors: [toESBuildError(e)] };
785
+ }
720
786
  });
721
787
  }
722
788
  };
@@ -743,6 +809,7 @@ async function compileSvelte(options, { filename, code }) {
743
809
  const compileOptions = __spreadProps(__spreadValues({}, options.compilerOptions), {
744
810
  css: true,
745
811
  filename,
812
+ format: "esm",
746
813
  generate: "dom"
747
814
  });
748
815
  let preprocessed;
@@ -765,8 +832,235 @@ async function compileSvelte(options, { filename, code }) {
765
832
  return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
766
833
  }
767
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
+
768
1062
  // src/utils/options.ts
769
- var knownOptions = new Set([
1063
+ var knownOptions = /* @__PURE__ */ new Set([
770
1064
  "configFile",
771
1065
  "include",
772
1066
  "exclude",
@@ -780,28 +1074,53 @@ var knownOptions = new Set([
780
1074
  "disableDependencyReinclusion",
781
1075
  "experimental"
782
1076
  ]);
783
- function buildDefaultOptions(isProduction, emitCss = true) {
784
- const hot = isProduction ? false : {
785
- injectCss: !emitCss
786
- };
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
+ });
787
1087
  const defaultOptions = {
788
1088
  extensions: [".svelte"],
789
- hot,
790
- emitCss,
1089
+ emitCss: true,
791
1090
  compilerOptions: {
792
- format: "esm",
793
- css: !emitCss,
794
- dev: !isProduction
1091
+ format: "esm"
795
1092
  }
796
1093
  };
797
- log.debug(`default options for ${isProduction ? "production" : "development"}`, defaultOptions);
798
- return defaultOptions;
799
- }
800
- function validateInlineOptions(inlineOptions) {
801
- const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
802
- if (invalidKeys.length) {
803
- 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;
804
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;
805
1124
  }
806
1125
  function enforceOptionsForHmr(options) {
807
1126
  if (options.hot) {
@@ -846,34 +1165,8 @@ function enforceOptionsForProduction(options) {
846
1165
  }
847
1166
  }
848
1167
  }
849
- function mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfig, viteEnv) {
850
- const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), {
851
- compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions.compilerOptions), (svelteConfig == null ? void 0 : svelteConfig.compilerOptions) || {}), (inlineOptions == null ? void 0 : inlineOptions.compilerOptions) || {}),
852
- experimental: __spreadValues(__spreadValues({}, (svelteConfig == null ? void 0 : svelteConfig.experimental) || {}), (inlineOptions == null ? void 0 : inlineOptions.experimental) || {}),
853
- root: viteConfig.root,
854
- isProduction: viteEnv.mode === "production",
855
- isBuild: viteEnv.command === "build",
856
- isServe: viteEnv.command === "serve"
857
- });
858
- if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
859
- merged.configFile = svelteConfig.configFile;
860
- }
861
- return merged;
862
- }
863
- async function resolveOptions(inlineOptions = {}, viteConfig, viteEnv) {
864
- var _a;
865
- const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteConfig), {
866
- root: resolveViteRoot(viteConfig)
867
- });
868
- const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions) || {};
869
- const defaultOptions = buildDefaultOptions(viteEnv.mode === "production", (_a = inlineOptions.emitCss) != null ? _a : svelteConfig.emitCss);
870
- const resolvedOptions = mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfigWithResolvedRoot, viteEnv);
871
- enforceOptionsForProduction(resolvedOptions);
872
- enforceOptionsForHmr(resolvedOptions);
873
- return resolvedOptions;
874
- }
875
1168
  function resolveViteRoot(viteConfig) {
876
- 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());
877
1170
  }
878
1171
  function buildExtraViteConfig(options, config, configEnv) {
879
1172
  const svelteDeps = findRootSvelteDependencies(options.root);
@@ -889,16 +1182,16 @@ function buildExtraViteConfig(options, config, configEnv) {
889
1182
  extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config);
890
1183
  return extraViteConfig;
891
1184
  }
892
- function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
1185
+ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps2) {
893
1186
  const include = [];
894
1187
  const exclude = ["svelte-hmr"];
895
1188
  const isIncluded = (dep) => {
896
1189
  var _a;
897
- 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));
898
1191
  };
899
1192
  const isExcluded = (dep) => {
900
1193
  var _a;
901
- 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}/`)));
902
1195
  };
903
1196
  if (!isExcluded("svelte")) {
904
1197
  const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
@@ -912,7 +1205,8 @@ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
912
1205
  include,
913
1206
  exclude,
914
1207
  esbuildOptions: {
915
- plugins: [esbuildSveltePlugin(options)]
1208
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1209
+ } }]
916
1210
  }
917
1211
  };
918
1212
  }
@@ -952,14 +1246,21 @@ function buildSSROptionsForSvelte(svelteDeps, options, config) {
952
1246
  noExternal
953
1247
  };
954
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
+ }
955
1256
 
956
1257
  // src/utils/vite-plugin-svelte-cache.ts
957
1258
  var VitePluginSvelteCache = class {
958
1259
  constructor() {
959
- this._css = new Map();
960
- this._js = new Map();
961
- this._dependencies = new Map();
962
- 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();
963
1264
  }
964
1265
  update(compileData) {
965
1266
  this.updateCSS(compileData);
@@ -983,7 +1284,7 @@ var VitePluginSvelteCache = class {
983
1284
  const added = dependencies.filter((d) => !prevDependencies.includes(d));
984
1285
  added.forEach((d) => {
985
1286
  if (!this._dependants.has(d)) {
986
- this._dependants.set(d, new Set());
1287
+ this._dependants.set(d, /* @__PURE__ */ new Set());
987
1288
  }
988
1289
  this._dependants.get(d).add(compileData.filename);
989
1290
  });
@@ -1021,22 +1322,22 @@ var VitePluginSvelteCache = class {
1021
1322
  return this._js.get(svelteRequest.normalizedFilename);
1022
1323
  }
1023
1324
  }
1024
- getDependants(path6) {
1025
- const dependants = this._dependants.get(path6);
1325
+ getDependants(path7) {
1326
+ const dependants = this._dependants.get(path7);
1026
1327
  return dependants ? [...dependants] : [];
1027
1328
  }
1028
1329
  };
1029
1330
 
1030
1331
  // src/utils/watch.ts
1031
- var import_fs4 = __toModule(require("fs"));
1032
- var import_path4 = __toModule(require("path"));
1332
+ var import_fs4 = __toESM(require("fs"), 1);
1333
+ var import_path4 = __toESM(require("path"), 1);
1033
1334
  function setupWatchers(options, cache, requestParser) {
1034
1335
  const { server, configFile: svelteConfigFile } = options;
1035
1336
  if (!server) {
1036
1337
  return;
1037
1338
  }
1038
1339
  const { watcher, ws } = server;
1039
- const { configFile: viteConfigFile, root, server: serverConfig } = server.config;
1340
+ const { root, server: serverConfig } = server.config;
1040
1341
  const emitChangeEventOnDependants = (filename) => {
1041
1342
  const dependants = cache.getDependants(filename);
1042
1343
  dependants.forEach((dependant) => {
@@ -1056,16 +1357,16 @@ function setupWatchers(options, cache, requestParser) {
1056
1357
  }
1057
1358
  };
1058
1359
  const triggerViteRestart = (filename) => {
1059
- if (!!viteConfigFile && !serverConfig.middlewareMode) {
1060
- log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1061
- watcher.emit("change", viteConfigFile);
1062
- } else {
1360
+ if (serverConfig.middlewareMode) {
1063
1361
  const message = "Svelte config change detected, restart your dev process to apply the changes.";
1064
1362
  log.info(message, filename);
1065
1363
  ws.send({
1066
1364
  type: "error",
1067
1365
  err: { message, stack: "", plugin: "vite-plugin-svelte", id: filename }
1068
1366
  });
1367
+ } else {
1368
+ log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1369
+ server.restart();
1069
1370
  }
1070
1371
  };
1071
1372
  const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => import_path4.default.join(root, cfg));
@@ -1103,9 +1404,9 @@ function ensureWatchedFile(watcher, file, root) {
1103
1404
  }
1104
1405
 
1105
1406
  // src/utils/resolve.ts
1106
- var import_path5 = __toModule(require("path"));
1107
- var import_fs5 = __toModule(require("fs"));
1108
- var import_require_relative = __toModule(require("require-relative"));
1407
+ var import_path5 = __toESM(require("path"), 1);
1408
+ var import_fs5 = __toESM(require("fs"), 1);
1409
+ var import_require_relative = __toESM(require("require-relative"), 1);
1109
1410
  function resolveViaPackageJsonSvelte(importee, importer) {
1110
1411
  if (importer && isBareImport(importee)) {
1111
1412
  const importeePkgFile = import_require_relative.default.resolve(`${importee}/package.json`, import_path5.default.dirname(importer));
@@ -1116,7 +1417,7 @@ function resolveViaPackageJsonSvelte(importee, importer) {
1116
1417
  }
1117
1418
  }
1118
1419
  function isBareImport(importee) {
1119
- if (!importee || importee[0] === "." || importee[0] === "\0" || import_path5.default.isAbsolute(importee)) {
1420
+ if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || import_path5.default.isAbsolute(importee)) {
1120
1421
  return false;
1121
1422
  }
1122
1423
  const parts = importee.split("/");
@@ -1130,231 +1431,42 @@ function isBareImport(importee) {
1130
1431
  }
1131
1432
  }
1132
1433
 
1133
- // src/utils/preprocess.ts
1134
- var import_vite3 = __toModule(require("vite"));
1135
- var import_magic_string2 = __toModule(require("magic-string"));
1136
- var import_compiler3 = __toModule(require("svelte/compiler"));
1137
-
1138
- // src/utils/sourcemap.ts
1139
- var import_magic_string = __toModule(require("magic-string"));
1140
- async function buildMagicString(from, to, options) {
1141
- let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
1142
- try {
1143
- const dmpPkg = await import("diff-match-patch");
1144
- diff_match_patch = dmpPkg.diff_match_patch;
1145
- DIFF_INSERT = dmpPkg.DIFF_INSERT;
1146
- DIFF_DELETE = dmpPkg.DIFF_DELETE;
1147
- } catch (e) {
1148
- log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
1149
- return null;
1150
- }
1151
- const dmp = new diff_match_patch();
1152
- const diffs = dmp.diff_main(from, to);
1153
- dmp.diff_cleanupSemantic(diffs);
1154
- const m = new import_magic_string.default(from, options);
1155
- let pos = 0;
1156
- for (let i = 0; i < diffs.length; i++) {
1157
- const diff = diffs[i];
1158
- const nextDiff = diffs[i + 1];
1159
- if (diff[0] === DIFF_DELETE) {
1160
- if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
1161
- m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
1162
- i++;
1163
- } else {
1164
- m.remove(pos, pos + diff[1].length);
1165
- }
1166
- pos += diff[1].length;
1167
- } else if (diff[0] === DIFF_INSERT) {
1168
- if (nextDiff) {
1169
- m.appendRight(pos, diff[1]);
1170
- } else {
1171
- m.append(diff[1]);
1172
- }
1173
- } else {
1174
- pos += diff[1].length;
1175
- }
1176
- }
1177
- return m;
1178
- }
1179
- async function buildSourceMap(from, to, filename) {
1180
- const m = await buildMagicString(from, to, { filename });
1181
- return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
1182
- }
1183
-
1184
- // src/utils/preprocess.ts
1185
- var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
1186
- var supportedScriptLangs = ["ts"];
1187
- function createViteScriptPreprocessor() {
1188
- return async ({ attributes, content, filename = "" }) => {
1189
- const lang = attributes.lang;
1190
- if (!supportedScriptLangs.includes(lang))
1191
- return;
1192
- const transformResult = await (0, import_vite3.transformWithEsbuild)(content, filename, {
1193
- loader: lang,
1194
- tsconfigRaw: {
1195
- compilerOptions: {
1196
- importsNotUsedAsValues: "preserve"
1197
- }
1198
- }
1199
- });
1200
- return {
1201
- code: transformResult.code,
1202
- map: transformResult.map
1203
- };
1204
- };
1205
- }
1206
- function createViteStylePreprocessor(config) {
1207
- const pluginName = "vite:css";
1208
- const plugin = config.plugins.find((p) => p.name === pluginName);
1209
- if (!plugin) {
1210
- throw new Error(`failed to find plugin ${pluginName}`);
1211
- }
1212
- if (!plugin.transform) {
1213
- throw new Error(`plugin ${pluginName} has no transform`);
1214
- }
1215
- const pluginTransform = plugin.transform.bind(null);
1216
- return async ({ attributes, content, filename = "" }) => {
1217
- var _a, _b;
1218
- const lang = attributes.lang;
1219
- if (!supportedStyleLangs.includes(lang))
1220
- return;
1221
- const moduleId = `${filename}.${lang}`;
1222
- const transformResult = await pluginTransform(content, moduleId);
1223
- const hasMap = transformResult.map && transformResult.map.mappings !== "";
1224
- if (hasMap && ((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
1225
- transformResult.map.sources[0] = filename;
1226
- }
1227
- return {
1228
- code: transformResult.code,
1229
- map: hasMap ? transformResult.map : void 0
1230
- };
1231
- };
1232
- }
1233
- function createVitePreprocessorGroup(config) {
1234
- return {
1235
- markup({ content, filename }) {
1236
- return (0, import_compiler3.preprocess)(content, {
1237
- script: createViteScriptPreprocessor(),
1238
- style: createViteStylePreprocessor(config)
1239
- }, { filename });
1240
- }
1241
- };
1242
- }
1243
- function createInjectScopeEverythingRulePreprocessorGroup() {
1244
- return {
1245
- style({ content, filename }) {
1246
- const s = new import_magic_string2.default(content);
1247
- s.append(" *{}");
1248
- return {
1249
- code: s.toString(),
1250
- map: s.generateDecodedMap({ source: filename, hires: true })
1251
- };
1252
- }
1253
- };
1254
- }
1255
- function buildExtraPreprocessors(options, config) {
1256
- var _a, _b;
1257
- const prependPreprocessors = [];
1258
- const appendPreprocessors = [];
1259
- if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
1260
- log.debug("adding vite preprocessor");
1261
- prependPreprocessors.push(createVitePreprocessorGroup(config));
1262
- }
1263
- const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
1264
- if (pluginsWithPreprocessorsDeprecated.length > 0) {
1265
- 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(", ")}`);
1266
- pluginsWithPreprocessorsDeprecated.forEach((p) => {
1267
- if (!p.api) {
1268
- p.api = {};
1269
- }
1270
- if (p.api.sveltePreprocess === void 0) {
1271
- p.api.sveltePreprocess = p.sveltePreprocess;
1272
- } else {
1273
- log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
1274
- }
1275
- });
1276
- }
1277
- const pluginsWithPreprocessors = config.plugins.filter((p) => {
1278
- var _a2;
1279
- return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
1434
+ // src/utils/optimizer.ts
1435
+ var import_fs6 = __toESM(require("fs"), 1);
1436
+ var import_path6 = __toESM(require("path"), 1);
1437
+ var import_vite4 = require("vite");
1438
+ var PREBUNDLE_SENSITIVE_OPTIONS = [
1439
+ "compilerOptions",
1440
+ "configFile",
1441
+ "experimental",
1442
+ "extensions",
1443
+ "ignorePluginPreprocessors",
1444
+ "preprocess"
1445
+ ];
1446
+ async function handleOptimizeDeps(options, viteConfig) {
1447
+ if (!options.experimental.prebundleSvelteLibraries || !viteConfig.cacheDir)
1448
+ return;
1449
+ const viteMetadataPath = import_path6.default.resolve(viteConfig.cacheDir, "_metadata.json");
1450
+ if (!import_fs6.default.existsSync(viteMetadataPath))
1451
+ return;
1452
+ const svelteMetadataPath = import_path6.default.resolve(viteConfig.cacheDir, "_svelte_metadata.json");
1453
+ const currentSvelteMetadata = JSON.stringify(generateSvelteMetadata(options), (_, value) => {
1454
+ return typeof value === "function" ? value.toString() : value;
1280
1455
  });
1281
- const ignored = [], included = [];
1282
- for (const p of pluginsWithPreprocessors) {
1283
- if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
1284
- ignored.push(p);
1285
- } else {
1286
- included.push(p);
1287
- }
1288
- }
1289
- if (ignored.length > 0) {
1290
- log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
1291
- }
1292
- if (included.length > 0) {
1293
- log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
1294
- appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
1295
- }
1296
- if (options.hot && options.emitCss) {
1297
- appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
1298
- }
1299
- return { prependPreprocessors, appendPreprocessors };
1300
- }
1301
- function addExtraPreprocessors(options, config) {
1302
- var _a;
1303
- const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
1304
- if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
1305
- if (!options.preprocess) {
1306
- options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
1307
- } else if (Array.isArray(options.preprocess)) {
1308
- options.preprocess.unshift(...prependPreprocessors);
1309
- options.preprocess.push(...appendPreprocessors);
1310
- } else {
1311
- options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
1312
- }
1313
- }
1314
- const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
1315
- if (options.preprocess && generateMissingSourceMaps) {
1316
- options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
1456
+ if (import_fs6.default.existsSync(svelteMetadataPath)) {
1457
+ const existingSvelteMetadata = import_fs6.default.readFileSync(svelteMetadataPath, "utf8");
1458
+ if (existingSvelteMetadata === currentSvelteMetadata)
1459
+ return;
1317
1460
  }
1461
+ await (0, import_vite4.optimizeDeps)(viteConfig, true);
1462
+ import_fs6.default.writeFileSync(svelteMetadataPath, currentSvelteMetadata);
1318
1463
  }
1319
- function validateSourceMapOutputWrapper(group, i) {
1320
- const wrapper = {};
1321
- for (const [processorType, processorFn] of Object.entries(group)) {
1322
- wrapper[processorType] = async (options) => {
1323
- var _a;
1324
- const result = await processorFn(options);
1325
- if (result && result.code !== options.content) {
1326
- let invalidMap = false;
1327
- if (!result.map) {
1328
- invalidMap = true;
1329
- log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
1330
- filename: options.filename,
1331
- type: processorType,
1332
- processor: processorFn.toString()
1333
- });
1334
- } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
1335
- invalidMap = true;
1336
- log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
1337
- filename: options.filename,
1338
- type: processorType,
1339
- processor: processorFn.toString()
1340
- });
1341
- }
1342
- if (invalidMap) {
1343
- try {
1344
- const map = await buildSourceMap(options.content, result.code, options.filename);
1345
- if (map) {
1346
- log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
1347
- result.map = map;
1348
- }
1349
- } catch (e) {
1350
- log.error(`failed to build sourcemap`, e);
1351
- }
1352
- }
1353
- }
1354
- return result;
1355
- };
1464
+ function generateSvelteMetadata(options) {
1465
+ const metadata = {};
1466
+ for (const key of PREBUNDLE_SENSITIVE_OPTIONS) {
1467
+ metadata[key] = options[key];
1356
1468
  }
1357
- return wrapper;
1469
+ return metadata;
1358
1470
  }
1359
1471
 
1360
1472
  // src/index.ts
@@ -1364,7 +1476,7 @@ function svelte(inlineOptions) {
1364
1476
  }
1365
1477
  validateInlineOptions(inlineOptions);
1366
1478
  const cache = new VitePluginSvelteCache();
1367
- const pkg_export_errors = new Set();
1479
+ const pkg_export_errors = /* @__PURE__ */ new Set();
1368
1480
  let requestParser;
1369
1481
  let options;
1370
1482
  let viteConfig;
@@ -1379,18 +1491,22 @@ function svelte(inlineOptions) {
1379
1491
  } else if (config.logLevel) {
1380
1492
  log.setLevel(config.logLevel);
1381
1493
  }
1382
- options = await resolveOptions(inlineOptions, config, configEnv);
1494
+ options = await preResolveOptions(inlineOptions, config, configEnv);
1383
1495
  const extraViteConfig = buildExtraViteConfig(options, config, configEnv);
1384
1496
  log.debug("additional vite config", extraViteConfig);
1385
1497
  return extraViteConfig;
1386
1498
  },
1387
1499
  async configResolved(config) {
1388
- addExtraPreprocessors(options, config);
1500
+ options = resolveOptions(options, config);
1501
+ patchResolvedViteConfig(config, options);
1389
1502
  requestParser = buildIdParser(options);
1390
1503
  compileSvelte2 = createCompileSvelte(options);
1391
1504
  viteConfig = config;
1392
1505
  log.debug("resolved options", options);
1393
1506
  },
1507
+ async buildStart() {
1508
+ await handleOptimizeDeps(options, viteConfig);
1509
+ },
1394
1510
  configureServer(server) {
1395
1511
  options.server = server;
1396
1512
  setupWatchers(options, cache, requestParser);
@@ -1409,13 +1525,13 @@ function svelte(inlineOptions) {
1409
1525
  }
1410
1526
  if (viteConfig.assetsInclude(filename)) {
1411
1527
  log.debug(`load returns raw content for ${filename}`);
1412
- return import_fs6.default.readFileSync(filename, "utf-8");
1528
+ return import_fs7.default.readFileSync(filename, "utf-8");
1413
1529
  }
1414
1530
  }
1415
1531
  },
1416
- async resolveId(importee, importer, opts, _ssr) {
1417
- const ssr = _ssr === true || opts.ssr;
1418
- const svelteRequest = requestParser(importee, !!ssr);
1532
+ async resolveId(importee, importer, opts) {
1533
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1534
+ const svelteRequest = requestParser(importee, ssr);
1419
1535
  if (svelteRequest == null ? void 0 : svelteRequest.query.svelte) {
1420
1536
  if (svelteRequest.query.type === "style") {
1421
1537
  log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
@@ -1456,8 +1572,8 @@ function svelte(inlineOptions) {
1456
1572
  },
1457
1573
  async transform(code, id, opts) {
1458
1574
  var _a;
1459
- const ssr = opts === true || (opts == null ? void 0 : opts.ssr);
1460
- const svelteRequest = requestParser(id, !!ssr);
1575
+ const ssr = !!(opts == null ? void 0 : opts.ssr);
1576
+ const svelteRequest = requestParser(id, ssr);
1461
1577
  if (!svelteRequest) {
1462
1578
  return;
1463
1579
  }
@@ -1473,7 +1589,12 @@ function svelte(inlineOptions) {
1473
1589
  log.error("failed to transform tagged svelte request", svelteRequest);
1474
1590
  throw new Error(`failed to transform tagged svelte request for id ${id}`);
1475
1591
  }
1476
- const compileData = await compileSvelte2(svelteRequest, code, options);
1592
+ let compileData;
1593
+ try {
1594
+ compileData = await compileSvelte2(svelteRequest, code, options);
1595
+ } catch (e) {
1596
+ throw toRollupError(e);
1597
+ }
1477
1598
  logCompilerWarnings(compileData.compiled.warnings, options);
1478
1599
  cache.update(compileData);
1479
1600
  if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) {
@@ -1500,8 +1621,9 @@ function svelte(inlineOptions) {
1500
1621
  }
1501
1622
  };
1502
1623
  }
1624
+ module.exports = __toCommonJS(src_exports);
1503
1625
  // Annotate the CommonJS export names for ESM import in node:
1504
1626
  0 && (module.exports = {
1505
1627
  svelte
1506
1628
  });
1507
- //# sourceMappingURL=index.cjs.map
1629
+ //# sourceMappingURL=index.cjs.map