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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -89,7 +89,7 @@ function _log(logger, message, payload) {
89
89
  function createLogger(level) {
90
90
  const logger = loggers[level];
91
91
  const logFn = _log.bind(null, logger);
92
- const logged = new Set();
92
+ const logged = /* @__PURE__ */ new Set();
93
93
  const once = function(message, payload) {
94
94
  if (logged.has(message)) {
95
95
  return;
@@ -164,7 +164,10 @@ function buildExtendedLogMessage(w) {
164
164
  parts.push(":", w.start.line, ":", w.start.column);
165
165
  }
166
166
  if (w.message) {
167
- parts.push(" ", w.message);
167
+ if (parts.length > 0) {
168
+ parts.push(" ");
169
+ }
170
+ parts.push(w.message);
168
171
  }
169
172
  return parts.join("");
170
173
  }
@@ -181,7 +184,7 @@ async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, option
181
184
  const content = await read();
182
185
  const compileData = await compileSvelte2(svelteRequest, content, options);
183
186
  cache.update(compileData);
184
- const affectedModules = new Set();
187
+ const affectedModules = /* @__PURE__ */ new Set();
185
188
  const cssModule = server.moduleGraph.getModuleById(svelteRequest.cssId);
186
189
  const mainModule = server.moduleGraph.getModuleById(svelteRequest.id);
187
190
  const cssUpdated = cssModule && cssChanged(cachedCss, compileData.compiled.css);
@@ -245,16 +248,14 @@ import { compile, preprocess, walk } from "svelte/compiler";
245
248
  import { createMakeHot } from "svelte-hmr";
246
249
 
247
250
  // src/utils/hash.ts
248
- import {
249
- createHash
250
- } from "crypto";
251
- var hashes = Object.create(null);
251
+ import * as crypto from "crypto";
252
+ var hashes = /* @__PURE__ */ Object.create(null);
252
253
  var hash_length = 12;
253
254
  function safeBase64Hash(input) {
254
255
  if (hashes[input]) {
255
256
  return hashes[input];
256
257
  }
257
- const md5 = createHash("md5");
258
+ const md5 = crypto.createHash("md5");
258
259
  md5.update(input);
259
260
  const hash = toSafe(md5.digest("base64")).substr(0, hash_length);
260
261
  hashes[input] = hash;
@@ -294,7 +295,12 @@ var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequ
294
295
  }
295
296
  let preprocessed;
296
297
  if (options.preprocess) {
297
- preprocessed = await preprocess(code, options.preprocess, { filename });
298
+ try {
299
+ preprocessed = await preprocess(code, options.preprocess, { filename });
300
+ } catch (e) {
301
+ e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
302
+ throw e;
303
+ }
298
304
  if (preprocessed.dependencies)
299
305
  dependencies.push(...preprocessed.dependencies);
300
306
  if (preprocessed.map)
@@ -357,9 +363,7 @@ function createCompileSvelte(options) {
357
363
  // src/utils/id.ts
358
364
  import { createFilter } from "@rollup/pluginutils";
359
365
  import { normalizePath } from "vite";
360
- import {
361
- existsSync
362
- } from "fs";
366
+ import * as fs from "fs";
363
367
  var VITE_FS_PREFIX = "/@fs/";
364
368
  var IS_WINDOWS = process.platform === "win32";
365
369
  function splitId(id) {
@@ -413,7 +417,7 @@ function existsInRoot(filename, root) {
413
417
  if (filename.startsWith(VITE_FS_PREFIX)) {
414
418
  return false;
415
419
  }
416
- return existsSync(root + filename);
420
+ return fs.existsSync(root + filename);
417
421
  }
418
422
  function stripRoot(normalizedFilename, normalizedRoot) {
419
423
  return normalizedFilename.startsWith(normalizedRoot + "/") ? normalizedFilename.slice(normalizedRoot.length) : normalizedFilename;
@@ -435,7 +439,9 @@ function buildIdParser(options) {
435
439
  }
436
440
 
437
441
  // src/utils/options.ts
438
- import { normalizePath as normalizePath2 } from "vite";
442
+ import {
443
+ normalizePath as normalizePath2
444
+ } from "vite";
439
445
 
440
446
  // src/utils/load-svelte-config.ts
441
447
  import { createRequire } from "module";
@@ -560,7 +566,7 @@ function findRootSvelteDependencies(root, cwdFallback = true) {
560
566
  ].filter((dep) => !is_common_without_svelte_field(dep));
561
567
  return getSvelteDependencies(deps, root);
562
568
  }
563
- function getSvelteDependencies(deps, pkgDir, path6 = []) {
569
+ function getSvelteDependencies(deps, pkgDir, path7 = []) {
564
570
  const result = [];
565
571
  const localRequire = createRequire2(`${pkgDir}/package.json`);
566
572
  const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
@@ -568,18 +574,18 @@ function getSvelteDependencies(deps, pkgDir, path6 = []) {
568
574
  const type = getSvelteDependencyType(pkg);
569
575
  if (!type)
570
576
  continue;
571
- result.push({ name: pkg.name, type, pkg, dir, path: path6 });
577
+ result.push({ name: pkg.name, type, pkg, dir, path: path7 });
572
578
  if (type === "component-library" && pkg.dependencies) {
573
579
  let dependencyNames = Object.keys(pkg.dependencies);
574
- const circular = dependencyNames.filter((name) => path6.includes(name));
580
+ const circular = dependencyNames.filter((name) => path7.includes(name));
575
581
  if (circular.length > 0) {
576
- log.warn.enabled && log.warn(`skipping circular svelte dependencies in automated vite optimizeDeps handling`, circular.map((x) => path6.concat(x).join(">")));
577
- dependencyNames = dependencyNames.filter((name) => !path6.includes(name));
582
+ log.warn.enabled && log.warn(`skipping circular svelte dependencies in automated vite optimizeDeps handling`, circular.map((x) => path7.concat(x).join(">")));
583
+ dependencyNames = dependencyNames.filter((name) => !path7.includes(name));
578
584
  }
579
- if (path6.length === 3) {
580
- log.debug.once(`encountered deep svelte dependency tree: ${path6.join(">")}`);
585
+ if (path7.length === 3) {
586
+ log.debug.once(`encountered deep svelte dependency tree: ${path7.join(">")}`);
581
587
  }
582
- result.push(...getSvelteDependencies(dependencyNames, dir, path6.concat(pkg.name)));
588
+ result.push(...getSvelteDependencies(dependencyNames, dir, path7.concat(pkg.name)));
583
589
  }
584
590
  }
585
591
  return result;
@@ -678,7 +684,11 @@ function needsOptimization(dep, localRequire) {
678
684
  if (!depData)
679
685
  return false;
680
686
  const pkg = depData.pkg;
681
- return pkg.main && !pkg.module && !pkg.exports;
687
+ const isCjs = pkg.main && !pkg.module && !pkg.exports;
688
+ if (!isCjs)
689
+ return false;
690
+ const entryExt = path2.extname(pkg.main);
691
+ return !entryExt || entryExt === ".js" || entryExt === ".cjs";
682
692
  }
683
693
 
684
694
  // src/utils/options.ts
@@ -689,15 +699,15 @@ import { promises as fs4 } from "fs";
689
699
  import { compile as compile2, preprocess as preprocess2 } from "svelte/compiler";
690
700
 
691
701
  // src/utils/error.ts
692
- function toRollupError(error) {
693
- const { filename, frame, start, code, name } = error;
702
+ function toRollupError(error, options) {
703
+ const { filename, frame, start, code, name, stack } = error;
694
704
  const rollupError = {
695
705
  name,
696
706
  id: filename,
697
707
  message: buildExtendedLogMessage(error),
698
708
  frame: formatFrameForVite(frame),
699
709
  code,
700
- stack: ""
710
+ stack: options.isBuild || options.isDebug || !frame ? stack : ""
701
711
  };
702
712
  if (start) {
703
713
  rollupError.loc = {
@@ -708,8 +718,8 @@ function toRollupError(error) {
708
718
  }
709
719
  return rollupError;
710
720
  }
711
- function toESBuildError(error) {
712
- const { filename, frame, start } = error;
721
+ function toESBuildError(error, options) {
722
+ const { filename, frame, start, stack } = error;
713
723
  const partialMessage = {
714
724
  text: buildExtendedLogMessage(error)
715
725
  };
@@ -721,6 +731,9 @@ function toESBuildError(error) {
721
731
  lineText: lineFromFrame(start.line, frame)
722
732
  };
723
733
  }
734
+ if (options.isBuild || options.isDebug || !frame) {
735
+ partialMessage.detail = stack;
736
+ }
724
737
  return partialMessage;
725
738
  }
726
739
  function lineFromFrame(lineNo, frame) {
@@ -739,6 +752,7 @@ function formatFrameForVite(frame) {
739
752
  }
740
753
 
741
754
  // src/utils/esbuild.ts
755
+ var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
742
756
  function esbuildSveltePlugin(options) {
743
757
  return {
744
758
  name: "vite-plugin-svelte:optimize-svelte",
@@ -752,7 +766,7 @@ function esbuildSveltePlugin(options) {
752
766
  const contents = await compileSvelte(options, { filename, code });
753
767
  return { contents };
754
768
  } catch (e) {
755
- return { errors: [toESBuildError(e)] };
769
+ return { errors: [toESBuildError(e, options)] };
756
770
  }
757
771
  });
758
772
  }
@@ -780,11 +794,17 @@ async function compileSvelte(options, { filename, code }) {
780
794
  const compileOptions = __spreadProps(__spreadValues({}, options.compilerOptions), {
781
795
  css: true,
782
796
  filename,
797
+ format: "esm",
783
798
  generate: "dom"
784
799
  });
785
800
  let preprocessed;
786
801
  if (options.preprocess) {
787
- preprocessed = await preprocess2(code, options.preprocess, { filename });
802
+ try {
803
+ preprocessed = await preprocess2(code, options.preprocess, { filename });
804
+ } catch (e) {
805
+ e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
806
+ throw e;
807
+ }
788
808
  if (preprocessed.map)
789
809
  compileOptions.sourcemap = preprocessed.map;
790
810
  }
@@ -802,8 +822,237 @@ async function compileSvelte(options, { filename, code }) {
802
822
  return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
803
823
  }
804
824
 
825
+ // src/utils/preprocess.ts
826
+ import {
827
+ transformWithEsbuild
828
+ } from "vite";
829
+ import MagicString2 from "magic-string";
830
+ import { preprocess as preprocess3 } from "svelte/compiler";
831
+
832
+ // src/utils/sourcemap.ts
833
+ import MagicString from "magic-string";
834
+ async function buildMagicString(from, to, options) {
835
+ let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
836
+ try {
837
+ const dmpPkg = await import("diff-match-patch");
838
+ diff_match_patch = dmpPkg.diff_match_patch;
839
+ DIFF_INSERT = dmpPkg.DIFF_INSERT;
840
+ DIFF_DELETE = dmpPkg.DIFF_DELETE;
841
+ } catch (e) {
842
+ log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
843
+ return null;
844
+ }
845
+ const dmp = new diff_match_patch();
846
+ const diffs = dmp.diff_main(from, to);
847
+ dmp.diff_cleanupSemantic(diffs);
848
+ const m = new MagicString(from, options);
849
+ let pos = 0;
850
+ for (let i = 0; i < diffs.length; i++) {
851
+ const diff = diffs[i];
852
+ const nextDiff = diffs[i + 1];
853
+ if (diff[0] === DIFF_DELETE) {
854
+ if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
855
+ m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
856
+ i++;
857
+ } else {
858
+ m.remove(pos, pos + diff[1].length);
859
+ }
860
+ pos += diff[1].length;
861
+ } else if (diff[0] === DIFF_INSERT) {
862
+ if (nextDiff) {
863
+ m.appendRight(pos, diff[1]);
864
+ } else {
865
+ m.append(diff[1]);
866
+ }
867
+ } else {
868
+ pos += diff[1].length;
869
+ }
870
+ }
871
+ return m;
872
+ }
873
+ async function buildSourceMap(from, to, filename) {
874
+ const m = await buildMagicString(from, to, { filename });
875
+ return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
876
+ }
877
+
878
+ // src/utils/preprocess.ts
879
+ var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
880
+ var supportedScriptLangs = ["ts"];
881
+ function createViteScriptPreprocessor() {
882
+ return async ({ attributes, content, filename = "" }) => {
883
+ const lang = attributes.lang;
884
+ if (!supportedScriptLangs.includes(lang))
885
+ return;
886
+ const transformResult = await transformWithEsbuild(content, filename, {
887
+ loader: lang,
888
+ tsconfigRaw: {
889
+ compilerOptions: {
890
+ importsNotUsedAsValues: "preserve",
891
+ preserveValueImports: true
892
+ }
893
+ }
894
+ });
895
+ return {
896
+ code: transformResult.code,
897
+ map: transformResult.map
898
+ };
899
+ };
900
+ }
901
+ function createViteStylePreprocessor(config) {
902
+ const pluginName = "vite:css";
903
+ const plugin = config.plugins.find((p) => p.name === pluginName);
904
+ if (!plugin) {
905
+ throw new Error(`failed to find plugin ${pluginName}`);
906
+ }
907
+ if (!plugin.transform) {
908
+ throw new Error(`plugin ${pluginName} has no transform`);
909
+ }
910
+ const pluginTransform = plugin.transform.bind(null);
911
+ return async ({ attributes, content, filename = "" }) => {
912
+ var _a, _b;
913
+ const lang = attributes.lang;
914
+ if (!supportedStyleLangs.includes(lang))
915
+ return;
916
+ const moduleId = `${filename}.${lang}`;
917
+ const transformResult = await pluginTransform(content, moduleId);
918
+ if (((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
919
+ transformResult.map.sources[0] = filename;
920
+ }
921
+ return {
922
+ code: transformResult.code,
923
+ map: transformResult.map ?? void 0
924
+ };
925
+ };
926
+ }
927
+ function createVitePreprocessorGroup(config) {
928
+ return {
929
+ markup({ content, filename }) {
930
+ return preprocess3(content, {
931
+ script: createViteScriptPreprocessor(),
932
+ style: createViteStylePreprocessor(config)
933
+ }, { filename });
934
+ }
935
+ };
936
+ }
937
+ function createInjectScopeEverythingRulePreprocessorGroup() {
938
+ return {
939
+ style({ content, filename }) {
940
+ const s = new MagicString2(content);
941
+ s.append(" *{}");
942
+ return {
943
+ code: s.toString(),
944
+ map: s.generateDecodedMap({ source: filename, hires: true })
945
+ };
946
+ }
947
+ };
948
+ }
949
+ function buildExtraPreprocessors(options, config) {
950
+ var _a, _b;
951
+ const prependPreprocessors = [];
952
+ const appendPreprocessors = [];
953
+ if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
954
+ log.debug("adding vite preprocessor");
955
+ prependPreprocessors.push(createVitePreprocessorGroup(config));
956
+ }
957
+ const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
958
+ if (pluginsWithPreprocessorsDeprecated.length > 0) {
959
+ 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(", ")}`);
960
+ pluginsWithPreprocessorsDeprecated.forEach((p) => {
961
+ if (!p.api) {
962
+ p.api = {};
963
+ }
964
+ if (p.api.sveltePreprocess === void 0) {
965
+ p.api.sveltePreprocess = p.sveltePreprocess;
966
+ } else {
967
+ log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
968
+ }
969
+ });
970
+ }
971
+ const pluginsWithPreprocessors = config.plugins.filter((p) => {
972
+ var _a2;
973
+ return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
974
+ });
975
+ const ignored = [], included = [];
976
+ for (const p of pluginsWithPreprocessors) {
977
+ if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
978
+ ignored.push(p);
979
+ } else {
980
+ included.push(p);
981
+ }
982
+ }
983
+ if (ignored.length > 0) {
984
+ log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
985
+ }
986
+ if (included.length > 0) {
987
+ log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
988
+ appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
989
+ }
990
+ if (options.hot && options.emitCss) {
991
+ appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
992
+ }
993
+ return { prependPreprocessors, appendPreprocessors };
994
+ }
995
+ function addExtraPreprocessors(options, config) {
996
+ var _a;
997
+ const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
998
+ if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
999
+ if (!options.preprocess) {
1000
+ options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
1001
+ } else if (Array.isArray(options.preprocess)) {
1002
+ options.preprocess.unshift(...prependPreprocessors);
1003
+ options.preprocess.push(...appendPreprocessors);
1004
+ } else {
1005
+ options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
1006
+ }
1007
+ }
1008
+ const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
1009
+ if (options.preprocess && generateMissingSourceMaps) {
1010
+ options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
1011
+ }
1012
+ }
1013
+ function validateSourceMapOutputWrapper(group, i) {
1014
+ const wrapper = {};
1015
+ for (const [processorType, processorFn] of Object.entries(group)) {
1016
+ wrapper[processorType] = async (options) => {
1017
+ var _a;
1018
+ const result = await processorFn(options);
1019
+ if (result && result.code !== options.content) {
1020
+ let invalidMap = false;
1021
+ if (!result.map) {
1022
+ invalidMap = true;
1023
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
1024
+ filename: options.filename,
1025
+ type: processorType,
1026
+ processor: processorFn.toString()
1027
+ });
1028
+ } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
1029
+ invalidMap = true;
1030
+ log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
1031
+ filename: options.filename,
1032
+ type: processorType,
1033
+ processor: processorFn.toString()
1034
+ });
1035
+ }
1036
+ if (invalidMap) {
1037
+ try {
1038
+ const map = await buildSourceMap(options.content, result.code, options.filename);
1039
+ if (map) {
1040
+ log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
1041
+ result.map = map;
1042
+ }
1043
+ } catch (e) {
1044
+ log.error(`failed to build sourcemap`, e);
1045
+ }
1046
+ }
1047
+ }
1048
+ return result;
1049
+ };
1050
+ }
1051
+ return wrapper;
1052
+ }
1053
+
805
1054
  // src/utils/options.ts
806
- var knownOptions = new Set([
1055
+ var knownOptions = /* @__PURE__ */ new Set([
807
1056
  "configFile",
808
1057
  "include",
809
1058
  "exclude",
@@ -817,39 +1066,65 @@ var knownOptions = new Set([
817
1066
  "disableDependencyReinclusion",
818
1067
  "experimental"
819
1068
  ]);
820
- function buildDefaultOptions(isProduction, emitCss = true) {
821
- const hot = isProduction ? false : {
822
- injectCss: !emitCss
823
- };
824
- const defaultOptions = {
825
- extensions: [".svelte"],
826
- hot,
827
- emitCss,
828
- compilerOptions: {
829
- format: "esm",
830
- css: !emitCss,
831
- dev: !isProduction
832
- }
833
- };
834
- log.debug(`default options for ${isProduction ? "production" : "development"}`, defaultOptions);
835
- return defaultOptions;
836
- }
837
1069
  function validateInlineOptions(inlineOptions) {
838
1070
  const invalidKeys = Object.keys(inlineOptions || {}).filter((key) => !knownOptions.has(key));
839
1071
  if (invalidKeys.length) {
840
1072
  log.warn(`invalid plugin options "${invalidKeys.join(", ")}" in config`, inlineOptions);
841
1073
  }
842
1074
  }
843
- function enforceOptionsForHmr(options) {
844
- if (options.hot) {
845
- if (!options.compilerOptions.dev) {
846
- log.warn("hmr is enabled but compilerOptions.dev is false, forcing it to true");
847
- options.compilerOptions.dev = true;
1075
+ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1076
+ const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteUserConfig), {
1077
+ root: resolveViteRoot(viteUserConfig)
1078
+ });
1079
+ const defaultOptions = {
1080
+ extensions: [".svelte"],
1081
+ emitCss: true,
1082
+ compilerOptions: {
1083
+ format: "esm"
848
1084
  }
849
- if (options.emitCss) {
850
- if (options.hot !== true && options.hot.injectCss) {
851
- log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
852
- options.hot.injectCss = false;
1085
+ };
1086
+ const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions);
1087
+ const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), {
1088
+ compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.compilerOptions), svelteConfig == null ? void 0 : svelteConfig.compilerOptions), inlineOptions == null ? void 0 : inlineOptions.compilerOptions),
1089
+ experimental: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions == null ? void 0 : defaultOptions.experimental), svelteConfig == null ? void 0 : svelteConfig.experimental), inlineOptions == null ? void 0 : inlineOptions.experimental),
1090
+ root: viteConfigWithResolvedRoot.root,
1091
+ isBuild: viteEnv.command === "build",
1092
+ isServe: viteEnv.command === "serve",
1093
+ isDebug: process.env.DEBUG != null
1094
+ });
1095
+ if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
1096
+ merged.configFile = svelteConfig.configFile;
1097
+ }
1098
+ return merged;
1099
+ }
1100
+ function resolveOptions(preResolveOptions2, viteConfig) {
1101
+ const defaultOptions = {
1102
+ hot: viteConfig.isProduction ? false : { injectCss: !preResolveOptions2.emitCss },
1103
+ compilerOptions: {
1104
+ css: !preResolveOptions2.emitCss,
1105
+ dev: !viteConfig.isProduction
1106
+ }
1107
+ };
1108
+ const merged = __spreadProps(__spreadValues(__spreadValues({}, defaultOptions), preResolveOptions2), {
1109
+ compilerOptions: __spreadValues(__spreadValues({}, defaultOptions.compilerOptions), preResolveOptions2.compilerOptions),
1110
+ root: viteConfig.root,
1111
+ isProduction: viteConfig.isProduction
1112
+ });
1113
+ addExtraPreprocessors(merged, viteConfig);
1114
+ enforceOptionsForHmr(merged);
1115
+ enforceOptionsForProduction(merged);
1116
+ return merged;
1117
+ }
1118
+ function enforceOptionsForHmr(options) {
1119
+ if (options.hot) {
1120
+ if (!options.compilerOptions.dev) {
1121
+ log.warn("hmr is enabled but compilerOptions.dev is false, forcing it to true");
1122
+ options.compilerOptions.dev = true;
1123
+ }
1124
+ if (options.emitCss) {
1125
+ if (options.hot !== true && options.hot.injectCss) {
1126
+ log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
1127
+ options.hot.injectCss = false;
853
1128
  }
854
1129
  if (options.compilerOptions.css) {
855
1130
  log.warn("hmr and emitCss are enabled but compilerOptions.css is true, forcing it to false");
@@ -883,32 +1158,6 @@ function enforceOptionsForProduction(options) {
883
1158
  }
884
1159
  }
885
1160
  }
886
- function mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfig, viteEnv) {
887
- const merged = __spreadProps(__spreadValues(__spreadValues(__spreadValues({}, defaultOptions), svelteConfig), inlineOptions), {
888
- compilerOptions: __spreadValues(__spreadValues(__spreadValues({}, defaultOptions.compilerOptions), (svelteConfig == null ? void 0 : svelteConfig.compilerOptions) || {}), (inlineOptions == null ? void 0 : inlineOptions.compilerOptions) || {}),
889
- experimental: __spreadValues(__spreadValues({}, (svelteConfig == null ? void 0 : svelteConfig.experimental) || {}), (inlineOptions == null ? void 0 : inlineOptions.experimental) || {}),
890
- root: viteConfig.root,
891
- isProduction: viteEnv.mode === "production",
892
- isBuild: viteEnv.command === "build",
893
- isServe: viteEnv.command === "serve",
894
- isSvelteKit: !!(svelteConfig == null ? void 0 : svelteConfig.kit)
895
- });
896
- if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
897
- merged.configFile = svelteConfig.configFile;
898
- }
899
- return merged;
900
- }
901
- async function resolveOptions(inlineOptions = {}, viteConfig, viteEnv) {
902
- const viteConfigWithResolvedRoot = __spreadProps(__spreadValues({}, viteConfig), {
903
- root: resolveViteRoot(viteConfig)
904
- });
905
- const svelteConfig = await loadSvelteConfig(viteConfigWithResolvedRoot, inlineOptions) || {};
906
- const defaultOptions = buildDefaultOptions(viteEnv.mode === "production", inlineOptions.emitCss ?? svelteConfig.emitCss);
907
- const resolvedOptions = mergeOptions(defaultOptions, svelteConfig, inlineOptions, viteConfigWithResolvedRoot, viteEnv);
908
- enforceOptionsForProduction(resolvedOptions);
909
- enforceOptionsForHmr(resolvedOptions);
910
- return resolvedOptions;
911
- }
912
1161
  function resolveViteRoot(viteConfig) {
913
1162
  return normalizePath2(viteConfig.root ? path3.resolve(viteConfig.root) : process.cwd());
914
1163
  }
@@ -926,16 +1175,16 @@ function buildExtraViteConfig(options, config, configEnv) {
926
1175
  extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config);
927
1176
  return extraViteConfig;
928
1177
  }
929
- function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
1178
+ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps2) {
930
1179
  const include = [];
931
1180
  const exclude = ["svelte-hmr"];
932
1181
  const isIncluded = (dep) => {
933
1182
  var _a;
934
- return include.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a.includes(dep));
1183
+ return include.includes(dep) || ((_a = optimizeDeps2 == null ? void 0 : optimizeDeps2.include) == null ? void 0 : _a.includes(dep));
935
1184
  };
936
1185
  const isExcluded = (dep) => {
937
1186
  var _a;
938
- return exclude.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
1187
+ return exclude.includes(dep) || ((_a = optimizeDeps2 == null ? void 0 : optimizeDeps2.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
939
1188
  };
940
1189
  if (!isExcluded("svelte")) {
941
1190
  const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
@@ -949,7 +1198,8 @@ function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
949
1198
  include,
950
1199
  exclude,
951
1200
  esbuildOptions: {
952
- plugins: [esbuildSveltePlugin(options)]
1201
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1202
+ } }]
953
1203
  }
954
1204
  };
955
1205
  }
@@ -989,14 +1239,22 @@ function buildSSROptionsForSvelte(svelteDeps, options, config) {
989
1239
  noExternal
990
1240
  };
991
1241
  }
1242
+ function patchResolvedViteConfig(viteConfig, options) {
1243
+ var _a, _b;
1244
+ const facadeEsbuildSveltePlugin = (_b = (_a = viteConfig.optimizeDeps.esbuildOptions) == null ? void 0 : _a.plugins) == null ? void 0 : _b.find((plugin) => plugin.name === facadeEsbuildSveltePluginName);
1245
+ if (facadeEsbuildSveltePlugin) {
1246
+ Object.assign(facadeEsbuildSveltePlugin, esbuildSveltePlugin(options));
1247
+ }
1248
+ }
992
1249
 
993
1250
  // src/utils/vite-plugin-svelte-cache.ts
994
1251
  var VitePluginSvelteCache = class {
995
1252
  constructor() {
996
- this._css = new Map();
997
- this._js = new Map();
998
- this._dependencies = new Map();
999
- this._dependants = new Map();
1253
+ this._css = /* @__PURE__ */ new Map();
1254
+ this._js = /* @__PURE__ */ new Map();
1255
+ this._dependencies = /* @__PURE__ */ new Map();
1256
+ this._dependants = /* @__PURE__ */ new Map();
1257
+ this._resolvedSvelteFields = /* @__PURE__ */ new Map();
1000
1258
  }
1001
1259
  update(compileData) {
1002
1260
  this.updateCSS(compileData);
@@ -1020,7 +1278,7 @@ var VitePluginSvelteCache = class {
1020
1278
  const added = dependencies.filter((d) => !prevDependencies.includes(d));
1021
1279
  added.forEach((d) => {
1022
1280
  if (!this._dependants.has(d)) {
1023
- this._dependants.set(d, new Set());
1281
+ this._dependants.set(d, /* @__PURE__ */ new Set());
1024
1282
  }
1025
1283
  this._dependants.get(d).add(compileData.filename);
1026
1284
  });
@@ -1058,10 +1316,19 @@ var VitePluginSvelteCache = class {
1058
1316
  return this._js.get(svelteRequest.normalizedFilename);
1059
1317
  }
1060
1318
  }
1061
- getDependants(path6) {
1062
- const dependants = this._dependants.get(path6);
1319
+ getDependants(path7) {
1320
+ const dependants = this._dependants.get(path7);
1063
1321
  return dependants ? [...dependants] : [];
1064
1322
  }
1323
+ getResolvedSvelteField(name, importer) {
1324
+ return this._resolvedSvelteFields.get(this._getResolvedSvelteFieldKey(name, importer));
1325
+ }
1326
+ setResolvedSvelteField(importee, importer = void 0, resolvedSvelte) {
1327
+ this._resolvedSvelteFields.set(this._getResolvedSvelteFieldKey(importee, importer), resolvedSvelte);
1328
+ }
1329
+ _getResolvedSvelteFieldKey(importee, importer) {
1330
+ return importer ? `${importer} > ${importee}` : importee;
1331
+ }
1065
1332
  };
1066
1333
 
1067
1334
  // src/utils/watch.ts
@@ -1093,8 +1360,7 @@ function setupWatchers(options, cache, requestParser) {
1093
1360
  }
1094
1361
  };
1095
1362
  const triggerViteRestart = (filename) => {
1096
- var _a;
1097
- if (serverConfig.middlewareMode || options.isSvelteKit) {
1363
+ if (serverConfig.middlewareMode) {
1098
1364
  const message = "Svelte config change detected, restart your dev process to apply the changes.";
1099
1365
  log.info(message, filename);
1100
1366
  ws.send({
@@ -1103,7 +1369,7 @@ function setupWatchers(options, cache, requestParser) {
1103
1369
  });
1104
1370
  } else {
1105
1371
  log.info(`svelte config changed: restarting vite server. - file: ${filename}`);
1106
- server.restart(!!((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries));
1372
+ server.restart();
1107
1373
  }
1108
1374
  };
1109
1375
  const possibleSvelteConfigs = knownSvelteConfigNames.map((cfg) => path4.join(root, cfg));
@@ -1142,14 +1408,24 @@ function ensureWatchedFile(watcher, file, root) {
1142
1408
 
1143
1409
  // src/utils/resolve.ts
1144
1410
  import path5 from "path";
1145
- import fs6 from "fs";
1146
- import relative from "require-relative";
1147
- function resolveViaPackageJsonSvelte(importee, importer) {
1148
- if (importer && isBareImport(importee)) {
1149
- const importeePkgFile = relative.resolve(`${importee}/package.json`, path5.dirname(importer));
1150
- const importeePkg = JSON.parse(fs6.readFileSync(importeePkgFile, { encoding: "utf-8" }));
1151
- if (importeePkg.svelte) {
1152
- return path5.resolve(path5.dirname(importeePkgFile), importeePkg.svelte);
1411
+ import { createRequire as createRequire4 } from "module";
1412
+ function resolveViaPackageJsonSvelte(importee, importer, cache) {
1413
+ if (importer && isBareImport(importee) && !is_common_without_svelte_field(importee)) {
1414
+ const cached = cache.getResolvedSvelteField(importee, importer);
1415
+ if (cached) {
1416
+ return cached;
1417
+ }
1418
+ const localRequire = createRequire4(importer);
1419
+ const pkgData = resolveDependencyData(importee, localRequire);
1420
+ if (pkgData) {
1421
+ const { pkg, dir } = pkgData;
1422
+ if (pkg.svelte) {
1423
+ const result = path5.resolve(dir, pkg.svelte);
1424
+ cache.setResolvedSvelteField(importee, importer, result);
1425
+ return result;
1426
+ }
1427
+ } else {
1428
+ throw new Error(`failed to resolve package.json of ${importee} imported by ${importer}`);
1153
1429
  }
1154
1430
  }
1155
1431
  }
@@ -1168,233 +1444,42 @@ function isBareImport(importee) {
1168
1444
  }
1169
1445
  }
1170
1446
 
1171
- // src/utils/preprocess.ts
1172
- import {
1173
- transformWithEsbuild
1174
- } from "vite";
1175
- import MagicString2 from "magic-string";
1176
- import { preprocess as preprocess3 } from "svelte/compiler";
1177
-
1178
- // src/utils/sourcemap.ts
1179
- import MagicString from "magic-string";
1180
- async function buildMagicString(from, to, options) {
1181
- let diff_match_patch, DIFF_DELETE, DIFF_INSERT;
1182
- try {
1183
- const dmpPkg = await import("diff-match-patch");
1184
- diff_match_patch = dmpPkg.diff_match_patch;
1185
- DIFF_INSERT = dmpPkg.DIFF_INSERT;
1186
- DIFF_DELETE = dmpPkg.DIFF_DELETE;
1187
- } catch (e) {
1188
- log.error.once('Failed to import optional dependency "diff-match-patch". Please install it to enable generated sourcemaps.');
1189
- return null;
1190
- }
1191
- const dmp = new diff_match_patch();
1192
- const diffs = dmp.diff_main(from, to);
1193
- dmp.diff_cleanupSemantic(diffs);
1194
- const m = new MagicString(from, options);
1195
- let pos = 0;
1196
- for (let i = 0; i < diffs.length; i++) {
1197
- const diff = diffs[i];
1198
- const nextDiff = diffs[i + 1];
1199
- if (diff[0] === DIFF_DELETE) {
1200
- if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
1201
- m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
1202
- i++;
1203
- } else {
1204
- m.remove(pos, pos + diff[1].length);
1205
- }
1206
- pos += diff[1].length;
1207
- } else if (diff[0] === DIFF_INSERT) {
1208
- if (nextDiff) {
1209
- m.appendRight(pos, diff[1]);
1210
- } else {
1211
- m.append(diff[1]);
1212
- }
1213
- } else {
1214
- pos += diff[1].length;
1215
- }
1216
- }
1217
- return m;
1218
- }
1219
- async function buildSourceMap(from, to, filename) {
1220
- const m = await buildMagicString(from, to, { filename });
1221
- return m ? m.generateDecodedMap({ source: filename, hires: true, includeContent: false }) : null;
1222
- }
1223
-
1224
- // src/utils/preprocess.ts
1225
- var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
1226
- var supportedScriptLangs = ["ts"];
1227
- function createViteScriptPreprocessor() {
1228
- return async ({ attributes, content, filename = "" }) => {
1229
- const lang = attributes.lang;
1230
- if (!supportedScriptLangs.includes(lang))
1231
- return;
1232
- const transformResult = await transformWithEsbuild(content, filename, {
1233
- loader: lang,
1234
- tsconfigRaw: {
1235
- compilerOptions: {
1236
- importsNotUsedAsValues: "preserve"
1237
- }
1238
- }
1239
- });
1240
- return {
1241
- code: transformResult.code,
1242
- map: transformResult.map
1243
- };
1244
- };
1245
- }
1246
- function createViteStylePreprocessor(config) {
1247
- const pluginName = "vite:css";
1248
- const plugin = config.plugins.find((p) => p.name === pluginName);
1249
- if (!plugin) {
1250
- throw new Error(`failed to find plugin ${pluginName}`);
1251
- }
1252
- if (!plugin.transform) {
1253
- throw new Error(`plugin ${pluginName} has no transform`);
1254
- }
1255
- const pluginTransform = plugin.transform.bind(null);
1256
- return async ({ attributes, content, filename = "" }) => {
1257
- var _a, _b;
1258
- const lang = attributes.lang;
1259
- if (!supportedStyleLangs.includes(lang))
1260
- return;
1261
- const moduleId = `${filename}.${lang}`;
1262
- const transformResult = await pluginTransform(content, moduleId);
1263
- const hasMap = transformResult.map && transformResult.map.mappings !== "";
1264
- if (hasMap && ((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
1265
- transformResult.map.sources[0] = filename;
1266
- }
1267
- return {
1268
- code: transformResult.code,
1269
- map: hasMap ? transformResult.map : void 0
1270
- };
1271
- };
1272
- }
1273
- function createVitePreprocessorGroup(config) {
1274
- return {
1275
- markup({ content, filename }) {
1276
- return preprocess3(content, {
1277
- script: createViteScriptPreprocessor(),
1278
- style: createViteStylePreprocessor(config)
1279
- }, { filename });
1280
- }
1281
- };
1282
- }
1283
- function createInjectScopeEverythingRulePreprocessorGroup() {
1284
- return {
1285
- style({ content, filename }) {
1286
- const s = new MagicString2(content);
1287
- s.append(" *{}");
1288
- return {
1289
- code: s.toString(),
1290
- map: s.generateDecodedMap({ source: filename, hires: true })
1291
- };
1292
- }
1293
- };
1294
- }
1295
- function buildExtraPreprocessors(options, config) {
1296
- var _a, _b;
1297
- const prependPreprocessors = [];
1298
- const appendPreprocessors = [];
1299
- if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
1300
- log.debug("adding vite preprocessor");
1301
- prependPreprocessors.push(createVitePreprocessorGroup(config));
1302
- }
1303
- const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
1304
- if (pluginsWithPreprocessorsDeprecated.length > 0) {
1305
- 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(", ")}`);
1306
- pluginsWithPreprocessorsDeprecated.forEach((p) => {
1307
- if (!p.api) {
1308
- p.api = {};
1309
- }
1310
- if (p.api.sveltePreprocess === void 0) {
1311
- p.api.sveltePreprocess = p.sveltePreprocess;
1312
- } else {
1313
- log.error(`ignoring plugin.sveltePreprocess of ${p.name} because it already defined plugin.api.sveltePreprocess.`);
1314
- }
1315
- });
1316
- }
1317
- const pluginsWithPreprocessors = config.plugins.filter((p) => {
1318
- var _a2;
1319
- return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
1447
+ // src/utils/optimizer.ts
1448
+ import fs6 from "fs";
1449
+ import path6 from "path";
1450
+ import { optimizeDeps } from "vite";
1451
+ var PREBUNDLE_SENSITIVE_OPTIONS = [
1452
+ "compilerOptions",
1453
+ "configFile",
1454
+ "experimental",
1455
+ "extensions",
1456
+ "ignorePluginPreprocessors",
1457
+ "preprocess"
1458
+ ];
1459
+ async function handleOptimizeDeps(options, viteConfig) {
1460
+ if (!options.experimental.prebundleSvelteLibraries || !viteConfig.cacheDir)
1461
+ return;
1462
+ const viteMetadataPath = path6.resolve(viteConfig.cacheDir, "_metadata.json");
1463
+ if (!fs6.existsSync(viteMetadataPath))
1464
+ return;
1465
+ const svelteMetadataPath = path6.resolve(viteConfig.cacheDir, "_svelte_metadata.json");
1466
+ const currentSvelteMetadata = JSON.stringify(generateSvelteMetadata(options), (_, value) => {
1467
+ return typeof value === "function" ? value.toString() : value;
1320
1468
  });
1321
- const ignored = [], included = [];
1322
- for (const p of pluginsWithPreprocessors) {
1323
- if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
1324
- ignored.push(p);
1325
- } else {
1326
- included.push(p);
1327
- }
1328
- }
1329
- if (ignored.length > 0) {
1330
- log.debug(`Ignoring svelte preprocessors defined by these vite plugins: ${ignored.map((p) => p.name).join(", ")}`);
1331
- }
1332
- if (included.length > 0) {
1333
- log.debug(`Adding svelte preprocessors defined by these vite plugins: ${included.map((p) => p.name).join(", ")}`);
1334
- appendPreprocessors.push(...pluginsWithPreprocessors.map((p) => p.api.sveltePreprocess));
1335
- }
1336
- if (options.hot && options.emitCss) {
1337
- appendPreprocessors.push(createInjectScopeEverythingRulePreprocessorGroup());
1338
- }
1339
- return { prependPreprocessors, appendPreprocessors };
1340
- }
1341
- function addExtraPreprocessors(options, config) {
1342
- var _a;
1343
- const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
1344
- if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
1345
- if (!options.preprocess) {
1346
- options.preprocess = [...prependPreprocessors, ...appendPreprocessors];
1347
- } else if (Array.isArray(options.preprocess)) {
1348
- options.preprocess.unshift(...prependPreprocessors);
1349
- options.preprocess.push(...appendPreprocessors);
1350
- } else {
1351
- options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
1352
- }
1353
- }
1354
- const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
1355
- if (options.preprocess && generateMissingSourceMaps) {
1356
- options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
1469
+ if (fs6.existsSync(svelteMetadataPath)) {
1470
+ const existingSvelteMetadata = fs6.readFileSync(svelteMetadataPath, "utf8");
1471
+ if (existingSvelteMetadata === currentSvelteMetadata)
1472
+ return;
1357
1473
  }
1474
+ await optimizeDeps(viteConfig, true);
1475
+ fs6.writeFileSync(svelteMetadataPath, currentSvelteMetadata);
1358
1476
  }
1359
- function validateSourceMapOutputWrapper(group, i) {
1360
- const wrapper = {};
1361
- for (const [processorType, processorFn] of Object.entries(group)) {
1362
- wrapper[processorType] = async (options) => {
1363
- var _a;
1364
- const result = await processorFn(options);
1365
- if (result && result.code !== options.content) {
1366
- let invalidMap = false;
1367
- if (!result.map) {
1368
- invalidMap = true;
1369
- log.warn.enabled && log.warn.once(`preprocessor at index ${i} did not return a sourcemap for ${processorType} transform`, {
1370
- filename: options.filename,
1371
- type: processorType,
1372
- processor: processorFn.toString()
1373
- });
1374
- } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
1375
- invalidMap = true;
1376
- log.warn.enabled && log.warn.once(`preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`, {
1377
- filename: options.filename,
1378
- type: processorType,
1379
- processor: processorFn.toString()
1380
- });
1381
- }
1382
- if (invalidMap) {
1383
- try {
1384
- const map = await buildSourceMap(options.content, result.code, options.filename);
1385
- if (map) {
1386
- log.debug.enabled && log.debug(`adding generated sourcemap to preprocesor result for ${options.filename}`);
1387
- result.map = map;
1388
- }
1389
- } catch (e) {
1390
- log.error(`failed to build sourcemap`, e);
1391
- }
1392
- }
1393
- }
1394
- return result;
1395
- };
1477
+ function generateSvelteMetadata(options) {
1478
+ const metadata = {};
1479
+ for (const key of PREBUNDLE_SENSITIVE_OPTIONS) {
1480
+ metadata[key] = options[key];
1396
1481
  }
1397
- return wrapper;
1482
+ return metadata;
1398
1483
  }
1399
1484
 
1400
1485
  // src/index.ts
@@ -1404,7 +1489,7 @@ function svelte(inlineOptions) {
1404
1489
  }
1405
1490
  validateInlineOptions(inlineOptions);
1406
1491
  const cache = new VitePluginSvelteCache();
1407
- const pkg_export_errors = new Set();
1492
+ const pkg_resolve_errors = /* @__PURE__ */ new Set();
1408
1493
  let requestParser;
1409
1494
  let options;
1410
1495
  let viteConfig;
@@ -1419,18 +1504,22 @@ function svelte(inlineOptions) {
1419
1504
  } else if (config.logLevel) {
1420
1505
  log.setLevel(config.logLevel);
1421
1506
  }
1422
- options = await resolveOptions(inlineOptions, config, configEnv);
1507
+ options = await preResolveOptions(inlineOptions, config, configEnv);
1423
1508
  const extraViteConfig = buildExtraViteConfig(options, config, configEnv);
1424
1509
  log.debug("additional vite config", extraViteConfig);
1425
1510
  return extraViteConfig;
1426
1511
  },
1427
1512
  async configResolved(config) {
1428
- addExtraPreprocessors(options, config);
1513
+ options = resolveOptions(options, config);
1514
+ patchResolvedViteConfig(config, options);
1429
1515
  requestParser = buildIdParser(options);
1430
1516
  compileSvelte2 = createCompileSvelte(options);
1431
1517
  viteConfig = config;
1432
1518
  log.debug("resolved options", options);
1433
1519
  },
1520
+ async buildStart() {
1521
+ await handleOptimizeDeps(options, viteConfig);
1522
+ },
1434
1523
  configureServer(server) {
1435
1524
  options.server = server;
1436
1525
  setupWatchers(options, cache, requestParser);
@@ -1477,21 +1566,13 @@ function svelte(inlineOptions) {
1477
1566
  return resolvedSvelteSSR;
1478
1567
  }
1479
1568
  try {
1480
- const resolved = resolveViaPackageJsonSvelte(importee, importer);
1569
+ const resolved = resolveViaPackageJsonSvelte(importee, importer, cache);
1481
1570
  if (resolved) {
1482
1571
  log.debug(`resolveId resolved ${resolved} via package.json svelte field of ${importee}`);
1483
1572
  return resolved;
1484
1573
  }
1485
1574
  } catch (err) {
1486
- switch (err.code) {
1487
- case "ERR_PACKAGE_PATH_NOT_EXPORTED":
1488
- pkg_export_errors.add(importee);
1489
- return null;
1490
- case "MODULE_NOT_FOUND":
1491
- return null;
1492
- default:
1493
- throw err;
1494
- }
1575
+ pkg_resolve_errors.add(importee);
1495
1576
  }
1496
1577
  },
1497
1578
  async transform(code, id, opts) {
@@ -1517,7 +1598,7 @@ function svelte(inlineOptions) {
1517
1598
  try {
1518
1599
  compileData = await compileSvelte2(svelteRequest, code, options);
1519
1600
  } catch (e) {
1520
- throw toRollupError(e);
1601
+ throw toRollupError(e, options);
1521
1602
  }
1522
1603
  logCompilerWarnings(compileData.compiled.warnings, options);
1523
1604
  cache.update(compileData);
@@ -1539,8 +1620,10 @@ function svelte(inlineOptions) {
1539
1620
  }
1540
1621
  },
1541
1622
  buildEnd() {
1542
- if (pkg_export_errors.size > 0) {
1543
- 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"));
1623
+ if (pkg_resolve_errors.size > 0) {
1624
+ 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.
1625
+ If you had difficulties importing svelte components from a package, then please contact the author and ask them to export the package.json file.
1626
+ ${Array.from(pkg_resolve_errors, (s) => `- ${s}`).join("\n")}`.replace(/\t/g, ""));
1544
1627
  }
1545
1628
  }
1546
1629
  };
@@ -1548,4 +1631,4 @@ function svelte(inlineOptions) {
1548
1631
  export {
1549
1632
  svelte
1550
1633
  };
1551
- //# sourceMappingURL=index.js.map
1634
+ //# sourceMappingURL=index.js.map