@sveltejs/vite-plugin-svelte 1.1.0 → 1.2.0

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
@@ -31,12 +31,13 @@ __export(src_exports, {
31
31
  });
32
32
  module.exports = __toCommonJS(src_exports);
33
33
 
34
- // ../../node_modules/.pnpm/tsup@6.3.0/node_modules/tsup/assets/cjs_shims.js
34
+ // ../../node_modules/.pnpm/tsup@6.5.0/node_modules/tsup/assets/cjs_shims.js
35
35
  var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
36
36
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
37
37
 
38
38
  // src/index.ts
39
- var import_fs7 = __toESM(require("fs"), 1);
39
+ var import_fs6 = __toESM(require("fs"), 1);
40
+ var import_vitefu3 = require("vitefu");
40
41
 
41
42
  // src/utils/log.ts
42
43
  var import_colors = require("kleur/colors");
@@ -127,12 +128,11 @@ var log = {
127
128
  setLevel
128
129
  };
129
130
  function logCompilerWarnings(svelteRequest, warnings, options) {
130
- var _a, _b, _c;
131
131
  const { emitCss, onwarn, isBuild } = options;
132
- const sendViaWS = !isBuild && ((_a = options.experimental) == null ? void 0 : _a.sendWarningsToBrowser);
132
+ const sendViaWS = !isBuild && options.experimental?.sendWarningsToBrowser;
133
133
  let warn = isBuild ? warnBuild : warnDev;
134
134
  const handledByDefaultWarn = [];
135
- const notIgnored = warnings == null ? void 0 : warnings.filter((w) => !ignoreCompilerWarning(w, isBuild, emitCss));
135
+ const notIgnored = warnings?.filter((w) => !ignoreCompilerWarning(w, isBuild, emitCss));
136
136
  const extra = buildExtraWarnings(warnings, isBuild);
137
137
  const allWarnings = [...notIgnored, ...extra];
138
138
  if (sendViaWS) {
@@ -160,7 +160,7 @@ function logCompilerWarnings(svelteRequest, warnings, options) {
160
160
  rawWarnings: warnings
161
161
  };
162
162
  log.debug(`sending svelte:warnings message for ${svelteRequest.normalizedFilename}`);
163
- (_c = (_b = options.server) == null ? void 0 : _b.ws) == null ? void 0 : _c.send("svelte:warnings", message);
163
+ options.server?.ws?.send("svelte:warnings", message);
164
164
  }
165
165
  }
166
166
  function ignoreCompilerWarning(warning, isBuild, emitCss) {
@@ -255,11 +255,11 @@ async function handleHotUpdate(compileSvelte2, ctx, svelteRequest, cache, option
255
255
  return result;
256
256
  }
257
257
  function cssChanged(prev, next) {
258
- return !isCodeEqual(prev == null ? void 0 : prev.code, next == null ? void 0 : next.code);
258
+ return !isCodeEqual(prev?.code, next?.code);
259
259
  }
260
260
  function jsChanged(prev, next, filename) {
261
- const prevJs = prev == null ? void 0 : prev.code;
262
- const nextJs = next == null ? void 0 : next.code;
261
+ const prevJs = prev?.code;
262
+ const nextJs = next?.code;
263
263
  const isStrictEqual = isCodeEqual(prevJs, nextJs);
264
264
  if (isStrictEqual) {
265
265
  return false;
@@ -319,7 +319,6 @@ function toSafe(base64) {
319
319
  // src/utils/compile.ts
320
320
  var scriptLangRE = /<script [^>]*lang=["']?([^"' >]+)["']?[^>]*>/;
321
321
  var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequest, code, options) {
322
- var _a, _b, _c;
323
322
  const { filename, normalizedFilename, cssId, ssr } = svelteRequest;
324
323
  const { emitCss = true } = options;
325
324
  const dependencies = [];
@@ -355,11 +354,11 @@ var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequ
355
354
  compileOptions.sourcemap = preprocessed.map;
356
355
  }
357
356
  const finalCode = preprocessed ? preprocessed.code : code;
358
- const dynamicCompileOptions = await ((_b = (_a = options.experimental) == null ? void 0 : _a.dynamicCompileOptions) == null ? void 0 : _b.call(_a, {
357
+ const dynamicCompileOptions = await options.experimental?.dynamicCompileOptions?.({
359
358
  filename,
360
359
  code: finalCode,
361
360
  compileOptions
362
- }));
361
+ });
363
362
  if (dynamicCompileOptions && log.debug.enabled) {
364
363
  log.debug(
365
364
  `dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`
@@ -370,7 +369,8 @@ var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequ
370
369
  ...dynamicCompileOptions
371
370
  } : compileOptions;
372
371
  const compiled = (0, import_compiler.compile)(finalCode, finalCompileOptions);
373
- if (emitCss && compiled.css.code) {
372
+ const hasCss = compiled.css?.code?.trim().length > 0;
373
+ if (emitCss && hasCss) {
374
374
  compiled.js.code += `
375
375
  import ${JSON.stringify(cssId)};
376
376
  `;
@@ -379,7 +379,7 @@ import ${JSON.stringify(cssId)};
379
379
  compiled.js.code = makeHot({
380
380
  id: filename,
381
381
  compiledCode: compiled.js.code,
382
- hotOptions: options.hot,
382
+ hotOptions: { ...options.hot, injectCss: options.hot?.injectCss === true && hasCss },
383
383
  compiled,
384
384
  originalCode: code,
385
385
  compileOptions: finalCompileOptions
@@ -389,18 +389,17 @@ import ${JSON.stringify(cssId)};
389
389
  return {
390
390
  filename,
391
391
  normalizedFilename,
392
- lang: ((_c = code.match(scriptLangRE)) == null ? void 0 : _c[1]) || "js",
392
+ lang: code.match(scriptLangRE)?.[1] || "js",
393
393
  compiled,
394
394
  ssr,
395
395
  dependencies
396
396
  };
397
397
  };
398
398
  function buildMakeHot(options) {
399
- var _a, _b;
400
399
  const needsMakeHot = options.hot !== false && options.isServe && !options.isProduction;
401
400
  if (needsMakeHot) {
402
- const hotApi = (_a = options == null ? void 0 : options.hot) == null ? void 0 : _a.hotApi;
403
- const adapter = (_b = options == null ? void 0 : options.hot) == null ? void 0 : _b.adapter;
401
+ const hotApi = options?.hot?.hotApi;
402
+ const adapter = options?.hot?.adapter;
404
403
  return (0, import_svelte_hmr.createMakeHot)({
405
404
  walk: import_compiler.walk,
406
405
  hotApi,
@@ -493,7 +492,7 @@ function buildIdParser(options) {
493
492
  }
494
493
 
495
494
  // src/utils/options.ts
496
- var import_vite4 = require("vite");
495
+ var import_vite3 = require("vite");
497
496
 
498
497
  // src/utils/load-svelte-config.ts
499
498
  var import_module = require("module");
@@ -512,7 +511,7 @@ var dynamicImportDefault = new Function(
512
511
  'return import(path + "?t=" + timestamp).then(m => m.default)'
513
512
  );
514
513
  async function loadSvelteConfig(viteConfig, inlineOptions) {
515
- if ((inlineOptions == null ? void 0 : inlineOptions.configFile) === false) {
514
+ if (inlineOptions?.configFile === false) {
516
515
  return;
517
516
  }
518
517
  const configFile = findConfigToLoad(viteConfig, inlineOptions);
@@ -561,8 +560,8 @@ async function loadSvelteConfig(viteConfig, inlineOptions) {
561
560
  }
562
561
  }
563
562
  function findConfigToLoad(viteConfig, inlineOptions) {
564
- const root = (viteConfig == null ? void 0 : viteConfig.root) || process.cwd();
565
- if (inlineOptions == null ? void 0 : inlineOptions.configFile) {
563
+ const root = viteConfig?.root || process.cwd();
564
+ if (inlineOptions?.configFile) {
566
565
  const abolutePath = import_path.default.isAbsolute(inlineOptions.configFile) ? inlineOptions.configFile : import_path.default.resolve(root, inlineOptions.configFile);
567
566
  if (!import_fs.default.existsSync(abolutePath)) {
568
567
  throw new Error(`failed to find svelte config file ${abolutePath}.`);
@@ -605,183 +604,9 @@ var SVELTE_HMR_IMPORTS = [
605
604
  // src/utils/options.ts
606
605
  var import_path4 = __toESM(require("path"), 1);
607
606
 
608
- // src/utils/dependencies.ts
609
- var import_path2 = __toESM(require("path"), 1);
610
- var import_fs2 = __toESM(require("fs"), 1);
611
- var import_module2 = require("module");
612
- function findRootSvelteDependencies(root, cwdFallback = true) {
613
- log.debug(`findSvelteDependencies: searching svelte dependencies in ${root}`);
614
- const pkgFile = import_path2.default.join(root, "package.json");
615
- if (!import_fs2.default.existsSync(pkgFile)) {
616
- if (cwdFallback) {
617
- const cwd = process.cwd();
618
- if (root !== cwd) {
619
- log.debug(`no package.json found in vite root ${root}`);
620
- return findRootSvelteDependencies(cwd, false);
621
- }
622
- }
623
- log.warn(`no package.json found, findRootSvelteDependencies failed`);
624
- return [];
625
- }
626
- const pkg = parsePkg(root);
627
- if (!pkg) {
628
- return [];
629
- }
630
- const deps = [
631
- ...Object.keys(pkg.dependencies || {}),
632
- ...Object.keys(pkg.devDependencies || {})
633
- ].filter((dep) => !is_common_without_svelte_field(dep));
634
- return getSvelteDependencies(deps, root);
635
- }
636
- function getSvelteDependencies(deps, pkgDir, path9 = []) {
637
- const result = [];
638
- const localRequire = (0, import_module2.createRequire)(`${pkgDir}/package.json`);
639
- const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
640
- for (const { pkg, dir } of resolvedDeps) {
641
- const type = getSvelteDependencyType(pkg);
642
- if (!type)
643
- continue;
644
- result.push({ name: pkg.name, type, pkg, dir, path: path9 });
645
- if (type === "component-library" && pkg.dependencies) {
646
- let dependencyNames = Object.keys(pkg.dependencies);
647
- const circular = dependencyNames.filter((name) => path9.includes(name));
648
- if (circular.length > 0) {
649
- log.warn.enabled && log.warn(
650
- `skipping circular svelte dependencies in automated vite optimizeDeps handling`,
651
- circular.map((x) => path9.concat(x).join(">"))
652
- );
653
- dependencyNames = dependencyNames.filter((name) => !path9.includes(name));
654
- }
655
- if (path9.length === 3) {
656
- log.debug.once(`encountered deep svelte dependency tree: ${path9.join(">")}`);
657
- }
658
- result.push(...getSvelteDependencies(dependencyNames, dir, path9.concat(pkg.name)));
659
- }
660
- }
661
- return result;
662
- }
663
- function resolveDependencyData(dep, localRequire) {
664
- try {
665
- const pkgJson = `${dep}/package.json`;
666
- const pkg = localRequire(pkgJson);
667
- const dir = import_path2.default.dirname(localRequire.resolve(pkgJson));
668
- return { dir, pkg };
669
- } catch (e) {
670
- log.debug.once(`dependency ${dep} does not export package.json`, e);
671
- try {
672
- let dir = import_path2.default.dirname(localRequire.resolve(dep));
673
- while (dir) {
674
- const pkg = parsePkg(dir, true);
675
- if (pkg && pkg.name === dep) {
676
- return { dir, pkg };
677
- }
678
- const parent = import_path2.default.dirname(dir);
679
- if (parent === dir) {
680
- break;
681
- }
682
- dir = parent;
683
- }
684
- } catch (e2) {
685
- log.debug.once(`error while trying to find package.json of ${dep}`, e2);
686
- }
687
- }
688
- log.debug.once(`failed to resolve ${dep}`);
689
- }
690
- function parsePkg(dir, silent = false) {
691
- const pkgFile = import_path2.default.join(dir, "package.json");
692
- try {
693
- return JSON.parse(import_fs2.default.readFileSync(pkgFile, "utf-8"));
694
- } catch (e) {
695
- !silent && log.warn.enabled && log.warn(`failed to parse ${pkgFile}`, e);
696
- }
697
- }
698
- function getSvelteDependencyType(pkg) {
699
- if (isSvelteComponentLib(pkg)) {
700
- return "component-library";
701
- } else if (isSvelteLib(pkg)) {
702
- return "js-library";
703
- } else {
704
- return void 0;
705
- }
706
- }
707
- function isSvelteComponentLib(pkg) {
708
- return !!pkg.svelte;
709
- }
710
- function isSvelteLib(pkg) {
711
- var _a, _b;
712
- return !!((_a = pkg.dependencies) == null ? void 0 : _a.svelte) || !!((_b = pkg.peerDependencies) == null ? void 0 : _b.svelte);
713
- }
714
- var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
715
- "@lukeed/uuid",
716
- "@playwright/test",
717
- "@sveltejs/vite-plugin-svelte",
718
- "@sveltejs/kit",
719
- "autoprefixer",
720
- "cookie",
721
- "dotenv",
722
- "esbuild",
723
- "eslint",
724
- "jest",
725
- "mdsvex",
726
- "playwright",
727
- "postcss",
728
- "prettier",
729
- "svelte",
730
- "svelte-check",
731
- "svelte-hmr",
732
- "svelte-preprocess",
733
- "tslib",
734
- "typescript",
735
- "vite",
736
- "vitest",
737
- "__vite-browser-external"
738
- ];
739
- var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
740
- "@fontsource/",
741
- "@postcss-plugins/",
742
- "@rollup/",
743
- "@sveltejs/adapter-",
744
- "@types/",
745
- "@typescript-eslint/",
746
- "eslint-",
747
- "jest-",
748
- "postcss-plugin-",
749
- "prettier-plugin-",
750
- "rollup-plugin-",
751
- "vite-plugin-"
752
- ];
753
- function is_common_without_svelte_field(dependency) {
754
- return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
755
- (prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
756
- );
757
- }
758
- function needsOptimization(dep, localRequire) {
759
- const depData = resolveDependencyData(dep, localRequire);
760
- if (!depData)
761
- return false;
762
- const pkg = depData.pkg;
763
- const hasEsmFields = pkg.module || pkg.exports;
764
- if (hasEsmFields)
765
- return false;
766
- if (pkg.main) {
767
- const entryExt = import_path2.default.extname(pkg.main);
768
- return !entryExt || entryExt === ".js" || entryExt === ".cjs";
769
- } else {
770
- try {
771
- localRequire.resolve(`${dep}/index.js`);
772
- return true;
773
- } catch {
774
- return false;
775
- }
776
- }
777
- }
778
-
779
- // src/utils/options.ts
780
- var import_module3 = require("module");
781
-
782
607
  // src/utils/esbuild.ts
783
- var import_fs3 = require("fs");
784
- var import_compiler2 = require("svelte/compiler");
608
+ var import_fs2 = require("fs");
609
+ var import_compiler3 = require("svelte/compiler");
785
610
 
786
611
  // src/utils/error.ts
787
612
  function toRollupError(error, options) {
@@ -836,19 +661,49 @@ function formatFrameForVite(frame) {
836
661
  return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
837
662
  }
838
663
 
664
+ // src/utils/svelte-version.ts
665
+ var import_compiler2 = require("svelte/compiler");
666
+ var svelteVersion = parseVersion(import_compiler2.VERSION);
667
+ function parseVersion(version) {
668
+ const segments = version.split(".", 3).map((s) => parseInt(s, 10));
669
+ while (segments.length < 3) {
670
+ segments.push(0);
671
+ }
672
+ return segments;
673
+ }
674
+ function compareToSvelte(version) {
675
+ const parsedVersion = parseVersion(version);
676
+ for (let i = 0; i < svelteVersion.length; i++) {
677
+ const a = parsedVersion[i];
678
+ const b = svelteVersion[i];
679
+ if (a === b) {
680
+ continue;
681
+ } else if (a > b) {
682
+ return 1;
683
+ } else {
684
+ return -1;
685
+ }
686
+ }
687
+ return 0;
688
+ }
689
+ function atLeastSvelte(version) {
690
+ const result = compareToSvelte(version) <= 0;
691
+ return result;
692
+ }
693
+
839
694
  // src/utils/esbuild.ts
695
+ var isCssString = atLeastSvelte("3.53.0");
840
696
  var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
841
697
  function esbuildSveltePlugin(options) {
842
698
  return {
843
699
  name: "vite-plugin-svelte:optimize-svelte",
844
700
  setup(build) {
845
- var _a;
846
- if ((_a = build.initialOptions.plugins) == null ? void 0 : _a.some((v) => v.name === "vite:dep-scan"))
701
+ if (build.initialOptions.plugins?.some((v) => v.name === "vite:dep-scan"))
847
702
  return;
848
703
  const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
849
704
  const svelteFilter = new RegExp(`\\.(` + svelteExtensions.join("|") + `)(\\?.*)?$`);
850
705
  build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
851
- const code = await import_fs3.promises.readFile(filename, "utf8");
706
+ const code = await import_fs2.promises.readFile(filename, "utf8");
852
707
  try {
853
708
  const contents = await compileSvelte(options, { filename, code });
854
709
  return { contents };
@@ -860,10 +715,13 @@ function esbuildSveltePlugin(options) {
860
715
  };
861
716
  }
862
717
  async function compileSvelte(options, { filename, code }) {
863
- var _a, _b;
718
+ let css = options.compilerOptions.css;
719
+ if (css !== "none") {
720
+ css = isCssString ? "injected" : true;
721
+ }
864
722
  const compileOptions = {
865
723
  ...options.compilerOptions,
866
- css: true,
724
+ css,
867
725
  filename,
868
726
  format: "esm",
869
727
  generate: "dom"
@@ -871,7 +729,7 @@ async function compileSvelte(options, { filename, code }) {
871
729
  let preprocessed;
872
730
  if (options.preprocess) {
873
731
  try {
874
- preprocessed = await (0, import_compiler2.preprocess)(code, options.preprocess, { filename });
732
+ preprocessed = await (0, import_compiler3.preprocess)(code, options.preprocess, { filename });
875
733
  } catch (e) {
876
734
  e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
877
735
  throw e;
@@ -880,11 +738,11 @@ async function compileSvelte(options, { filename, code }) {
880
738
  compileOptions.sourcemap = preprocessed.map;
881
739
  }
882
740
  const finalCode = preprocessed ? preprocessed.code : code;
883
- const dynamicCompileOptions = await ((_b = (_a = options.experimental) == null ? void 0 : _a.dynamicCompileOptions) == null ? void 0 : _b.call(_a, {
741
+ const dynamicCompileOptions = await options.experimental?.dynamicCompileOptions?.({
884
742
  filename,
885
743
  code: finalCode,
886
744
  compileOptions
887
- }));
745
+ });
888
746
  if (dynamicCompileOptions && log.debug.enabled) {
889
747
  log.debug(`dynamic compile options for ${filename}: ${JSON.stringify(dynamicCompileOptions)}`);
890
748
  }
@@ -892,14 +750,14 @@ async function compileSvelte(options, { filename, code }) {
892
750
  ...compileOptions,
893
751
  ...dynamicCompileOptions
894
752
  } : compileOptions;
895
- const compiled = (0, import_compiler2.compile)(finalCode, finalCompileOptions);
753
+ const compiled = (0, import_compiler3.compile)(finalCode, finalCompileOptions);
896
754
  return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
897
755
  }
898
756
 
899
757
  // src/utils/preprocess.ts
900
- var import_vite3 = require("vite");
758
+ var vite = __toESM(require("vite"), 1);
901
759
  var import_magic_string2 = __toESM(require("magic-string"), 1);
902
- var import_compiler3 = require("svelte/compiler");
760
+ var import_compiler4 = require("svelte/compiler");
903
761
 
904
762
  // src/utils/sourcemap.ts
905
763
  var import_magic_string = __toESM(require("magic-string"), 1);
@@ -925,7 +783,7 @@ async function buildMagicString(from, to, options) {
925
783
  const diff = diffs[i];
926
784
  const nextDiff = diffs[i + 1];
927
785
  if (diff[0] === DIFF_DELETE) {
928
- if ((nextDiff == null ? void 0 : nextDiff[0]) === DIFF_INSERT) {
786
+ if (nextDiff?.[0] === DIFF_INSERT) {
929
787
  m.overwrite(pos, pos + diff[1].length, nextDiff[1]);
930
788
  i++;
931
789
  } else {
@@ -950,7 +808,7 @@ async function buildSourceMap(from, to, filename) {
950
808
  }
951
809
 
952
810
  // src/utils/preprocess.ts
953
- var import_path3 = __toESM(require("path"), 1);
811
+ var import_path2 = __toESM(require("path"), 1);
954
812
  var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
955
813
  var supportedScriptLangs = ["ts"];
956
814
  function createViteScriptPreprocessor() {
@@ -958,7 +816,7 @@ function createViteScriptPreprocessor() {
958
816
  const lang = attributes.lang;
959
817
  if (!supportedScriptLangs.includes(lang))
960
818
  return;
961
- const transformResult = await (0, import_vite3.transformWithEsbuild)(content, filename, {
819
+ const transformResult = await vite.transformWithEsbuild(content, filename, {
962
820
  loader: lang,
963
821
  target: "esnext",
964
822
  tsconfigRaw: {
@@ -975,38 +833,43 @@ function createViteScriptPreprocessor() {
975
833
  };
976
834
  }
977
835
  function createViteStylePreprocessor(config) {
978
- const pluginName = "vite:css";
979
- const plugin = config.plugins.find((p) => p.name === pluginName);
980
- if (!plugin) {
981
- throw new Error(`failed to find plugin ${pluginName}`);
982
- }
983
- if (!plugin.transform) {
984
- throw new Error(`plugin ${pluginName} has no transform`);
985
- }
986
- const pluginTransform = plugin.transform.bind(null);
836
+ const transform = getCssTransformFn(config);
987
837
  return async ({ attributes, content, filename = "" }) => {
988
- var _a, _b;
989
838
  const lang = attributes.lang;
990
839
  if (!supportedStyleLangs.includes(lang))
991
840
  return;
992
841
  const moduleId = `${filename}.${lang}`;
993
- const transformResult = await pluginTransform(
994
- content,
995
- moduleId
996
- );
997
- if (((_b = (_a = transformResult.map) == null ? void 0 : _a.sources) == null ? void 0 : _b[0]) === moduleId) {
998
- transformResult.map.sources[0] = import_path3.default.basename(filename);
842
+ const result = await transform(content, moduleId);
843
+ if (result.map?.sources?.[0] === moduleId) {
844
+ result.map.sources[0] = import_path2.default.basename(filename);
999
845
  }
1000
846
  return {
1001
- code: transformResult.code,
1002
- map: transformResult.map ?? void 0
847
+ code: result.code,
848
+ map: result.map ?? void 0
1003
849
  };
1004
850
  };
1005
851
  }
852
+ function getCssTransformFn(config) {
853
+ if (vite.preprocessCSS) {
854
+ return async (code, filename) => {
855
+ return vite.preprocessCSS(code, filename, config);
856
+ };
857
+ } else {
858
+ const pluginName = "vite:css";
859
+ const plugin = config.plugins.find((p) => p.name === pluginName);
860
+ if (!plugin) {
861
+ throw new Error(`failed to find plugin ${pluginName}`);
862
+ }
863
+ if (!plugin.transform) {
864
+ throw new Error(`plugin ${pluginName} has no transform`);
865
+ }
866
+ return plugin.transform.bind(null);
867
+ }
868
+ }
1006
869
  function createVitePreprocessorGroup(config) {
1007
870
  return {
1008
871
  markup({ content, filename }) {
1009
- return (0, import_compiler3.preprocess)(
872
+ return (0, import_compiler4.preprocess)(
1010
873
  content,
1011
874
  {
1012
875
  script: createViteScriptPreprocessor(),
@@ -1025,7 +888,7 @@ function createInjectScopeEverythingRulePreprocessorGroup() {
1025
888
  return {
1026
889
  code: s.toString(),
1027
890
  map: s.generateDecodedMap({
1028
- source: filename ? import_path3.default.basename(filename) : void 0,
891
+ source: filename ? import_path2.default.basename(filename) : void 0,
1029
892
  hires: true
1030
893
  })
1031
894
  };
@@ -1033,14 +896,13 @@ function createInjectScopeEverythingRulePreprocessorGroup() {
1033
896
  };
1034
897
  }
1035
898
  function buildExtraPreprocessors(options, config) {
1036
- var _a, _b;
1037
899
  const prependPreprocessors = [];
1038
900
  const appendPreprocessors = [];
1039
- if ((_a = options.experimental) == null ? void 0 : _a.useVitePreprocess) {
901
+ if (options.experimental?.useVitePreprocess) {
1040
902
  log.debug("adding vite preprocessor");
1041
903
  prependPreprocessors.push(createVitePreprocessorGroup(config));
1042
904
  }
1043
- const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p == null ? void 0 : p.sveltePreprocess);
905
+ const pluginsWithPreprocessorsDeprecated = config.plugins.filter((p) => p?.sveltePreprocess);
1044
906
  if (pluginsWithPreprocessorsDeprecated.length > 0) {
1045
907
  log.warn(
1046
908
  `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(", ")}`
@@ -1058,13 +920,10 @@ function buildExtraPreprocessors(options, config) {
1058
920
  }
1059
921
  });
1060
922
  }
1061
- const pluginsWithPreprocessors = config.plugins.filter((p) => {
1062
- var _a2;
1063
- return (_a2 = p == null ? void 0 : p.api) == null ? void 0 : _a2.sveltePreprocess;
1064
- });
923
+ const pluginsWithPreprocessors = config.plugins.filter((p) => p?.api?.sveltePreprocess);
1065
924
  const ignored = [], included = [];
1066
925
  for (const p of pluginsWithPreprocessors) {
1067
- if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && ((_b = options.ignorePluginPreprocessors) == null ? void 0 : _b.includes(p.name))) {
926
+ if (options.ignorePluginPreprocessors === true || Array.isArray(options.ignorePluginPreprocessors) && options.ignorePluginPreprocessors?.includes(p.name)) {
1068
927
  ignored.push(p);
1069
928
  } else {
1070
929
  included.push(p);
@@ -1087,7 +946,6 @@ function buildExtraPreprocessors(options, config) {
1087
946
  return { prependPreprocessors, appendPreprocessors };
1088
947
  }
1089
948
  function addExtraPreprocessors(options, config) {
1090
- var _a;
1091
949
  const { prependPreprocessors, appendPreprocessors } = buildExtraPreprocessors(options, config);
1092
950
  if (prependPreprocessors.length > 0 || appendPreprocessors.length > 0) {
1093
951
  if (!options.preprocess) {
@@ -1099,7 +957,7 @@ function addExtraPreprocessors(options, config) {
1099
957
  options.preprocess = [...prependPreprocessors, options.preprocess, ...appendPreprocessors];
1100
958
  }
1101
959
  }
1102
- const generateMissingSourceMaps = !!((_a = options.experimental) == null ? void 0 : _a.generateMissingPreprocessorSourcemaps);
960
+ const generateMissingSourceMaps = !!options.experimental?.generateMissingPreprocessorSourcemaps;
1103
961
  if (options.preprocess && generateMissingSourceMaps) {
1104
962
  options.preprocess = Array.isArray(options.preprocess) ? options.preprocess.map((p, i) => validateSourceMapOutputWrapper(p, i)) : validateSourceMapOutputWrapper(options.preprocess, 0);
1105
963
  }
@@ -1108,7 +966,6 @@ function validateSourceMapOutputWrapper(group, i) {
1108
966
  const wrapper = {};
1109
967
  for (const [processorType, processorFn] of Object.entries(group)) {
1110
968
  wrapper[processorType] = async (options) => {
1111
- var _a;
1112
969
  const result = await processorFn(options);
1113
970
  if (result && result.code !== options.content) {
1114
971
  let invalidMap = false;
@@ -1122,7 +979,7 @@ function validateSourceMapOutputWrapper(group, i) {
1122
979
  processor: processorFn.toString()
1123
980
  }
1124
981
  );
1125
- } else if (((_a = result.map) == null ? void 0 : _a.mappings) === "") {
982
+ } else if (result.map?.mappings === "") {
1126
983
  invalidMap = true;
1127
984
  log.warn.enabled && log.warn.once(
1128
985
  `preprocessor at index ${i} returned an invalid empty sourcemap for ${processorType} transform`,
@@ -1155,6 +1012,72 @@ function validateSourceMapOutputWrapper(group, i) {
1155
1012
 
1156
1013
  // src/utils/options.ts
1157
1014
  var import_deepmerge = __toESM(require("deepmerge"), 1);
1015
+ var import_vitefu2 = require("vitefu");
1016
+
1017
+ // src/utils/dependencies.ts
1018
+ var import_path3 = __toESM(require("path"), 1);
1019
+ var import_promises = __toESM(require("fs/promises"), 1);
1020
+ var import_vitefu = require("vitefu");
1021
+ async function resolveDependencyData(dep, parent) {
1022
+ const depDataPath = await (0, import_vitefu.findDepPkgJsonPath)(dep, parent);
1023
+ if (!depDataPath)
1024
+ return void 0;
1025
+ try {
1026
+ return {
1027
+ dir: import_path3.default.dirname(depDataPath),
1028
+ pkg: JSON.parse(await import_promises.default.readFile(depDataPath, "utf-8"))
1029
+ };
1030
+ } catch {
1031
+ return void 0;
1032
+ }
1033
+ }
1034
+ var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
1035
+ "@lukeed/uuid",
1036
+ "@playwright/test",
1037
+ "@sveltejs/vite-plugin-svelte",
1038
+ "@sveltejs/kit",
1039
+ "autoprefixer",
1040
+ "cookie",
1041
+ "dotenv",
1042
+ "esbuild",
1043
+ "eslint",
1044
+ "jest",
1045
+ "mdsvex",
1046
+ "playwright",
1047
+ "postcss",
1048
+ "prettier",
1049
+ "svelte",
1050
+ "svelte-check",
1051
+ "svelte-hmr",
1052
+ "svelte-preprocess",
1053
+ "tslib",
1054
+ "typescript",
1055
+ "vite",
1056
+ "vitest",
1057
+ "__vite-browser-external"
1058
+ ];
1059
+ var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
1060
+ "@fontsource/",
1061
+ "@postcss-plugins/",
1062
+ "@rollup/",
1063
+ "@sveltejs/adapter-",
1064
+ "@types/",
1065
+ "@typescript-eslint/",
1066
+ "eslint-",
1067
+ "jest-",
1068
+ "postcss-plugin-",
1069
+ "prettier-plugin-",
1070
+ "rollup-plugin-",
1071
+ "vite-plugin-"
1072
+ ];
1073
+ function isCommonDepWithoutSvelteField(dependency) {
1074
+ return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
1075
+ (prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
1076
+ );
1077
+ }
1078
+
1079
+ // src/utils/options.ts
1080
+ var cssAsString = atLeastSvelte("3.53.0");
1158
1081
  var allowedPluginOptions = /* @__PURE__ */ new Set([
1159
1082
  "include",
1160
1083
  "exclude",
@@ -1257,7 +1180,7 @@ async function preResolveOptions(inlineOptions = {}, viteUserConfig, viteEnv) {
1257
1180
  inlineOptions,
1258
1181
  extraOptions
1259
1182
  );
1260
- if (svelteConfig == null ? void 0 : svelteConfig.configFile) {
1183
+ if (svelteConfig?.configFile) {
1261
1184
  merged.configFile = svelteConfig.configFile;
1262
1185
  }
1263
1186
  return merged;
@@ -1272,14 +1195,14 @@ function mergeConfigs(...configs) {
1272
1195
  return result;
1273
1196
  }
1274
1197
  function resolveOptions(preResolveOptions2, viteConfig) {
1275
- var _a;
1198
+ const css = cssAsString ? preResolveOptions2.emitCss ? "external" : "injected" : !preResolveOptions2.emitCss;
1276
1199
  const defaultOptions = {
1277
1200
  hot: viteConfig.isProduction ? false : {
1278
- injectCss: !preResolveOptions2.emitCss,
1279
- partialAccept: !!((_a = viteConfig.experimental) == null ? void 0 : _a.hmrPartialAccept)
1201
+ injectCss: css === true || css === "injected",
1202
+ partialAccept: !!viteConfig.experimental?.hmrPartialAccept
1280
1203
  },
1281
1204
  compilerOptions: {
1282
- css: !preResolveOptions2.emitCss,
1205
+ css,
1283
1206
  dev: !viteConfig.isProduction
1284
1207
  }
1285
1208
  };
@@ -1307,11 +1230,13 @@ function enforceOptionsForHmr(options) {
1307
1230
  log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
1308
1231
  options.hot.injectCss = false;
1309
1232
  }
1310
- if (options.compilerOptions.css) {
1233
+ const css = options.compilerOptions.css;
1234
+ if (css === true || css === "injected") {
1235
+ const forcedCss = cssAsString ? "external" : false;
1311
1236
  log.warn(
1312
- "hmr and emitCss are enabled but compilerOptions.css is true, forcing it to false"
1237
+ `hmr and emitCss are enabled but compilerOptions.css is ${css}, forcing it to ${forcedCss}`
1313
1238
  );
1314
- options.compilerOptions.css = false;
1239
+ options.compilerOptions.css = forcedCss;
1315
1240
  }
1316
1241
  } else {
1317
1242
  if (options.hot === true || !options.hot.injectCss) {
@@ -1324,11 +1249,13 @@ function enforceOptionsForHmr(options) {
1324
1249
  options.hot.injectCss = true;
1325
1250
  }
1326
1251
  }
1327
- if (!options.compilerOptions.css) {
1252
+ const css = options.compilerOptions.css;
1253
+ if (!(css === true || css === "injected")) {
1254
+ const forcedCss = cssAsString ? "injected" : true;
1328
1255
  log.warn(
1329
- "hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to true"
1256
+ `hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to ${forcedCss}`
1330
1257
  );
1331
- options.compilerOptions.css = true;
1258
+ options.compilerOptions.css = forcedCss;
1332
1259
  }
1333
1260
  }
1334
1261
  }
@@ -1366,141 +1293,137 @@ function removeIgnoredOptions(options) {
1366
1293
  }
1367
1294
  }
1368
1295
  function addSvelteKitOptions(options) {
1369
- var _a;
1370
- if ((options == null ? void 0 : options.kit) != null) {
1371
- const kit_browser_hydrate = (_a = options.kit.browser) == null ? void 0 : _a.hydrate;
1372
- const hydratable = kit_browser_hydrate !== false;
1373
- if (options.compilerOptions.hydratable != null && options.compilerOptions.hydratable !== hydratable) {
1374
- log.warn(
1375
- `Conflicting values "compilerOptions.hydratable: ${options.compilerOptions.hydratable}" and "kit.browser.hydrate: ${kit_browser_hydrate}" in your svelte config. You should remove "compilerOptions.hydratable".`
1376
- );
1377
- }
1378
- log.debug(`Setting compilerOptions.hydratable: ${hydratable} for SvelteKit`);
1379
- options.compilerOptions.hydratable = hydratable;
1296
+ if (options?.kit != null && options.compilerOptions.hydratable == null) {
1297
+ log.debug(`Setting compilerOptions.hydratable = true for SvelteKit`);
1298
+ options.compilerOptions.hydratable = true;
1380
1299
  }
1381
1300
  }
1382
1301
  function handleDeprecatedOptions(options) {
1383
- var _a, _b;
1384
- if ((_a = options.experimental) == null ? void 0 : _a.prebundleSvelteLibraries) {
1385
- options.prebundleSvelteLibraries = (_b = options.experimental) == null ? void 0 : _b.prebundleSvelteLibraries;
1302
+ if (options.experimental?.prebundleSvelteLibraries) {
1303
+ options.prebundleSvelteLibraries = options.experimental?.prebundleSvelteLibraries;
1386
1304
  log.warn(
1387
1305
  "experimental.prebundleSvelteLibraries is no longer experimental and has moved to prebundleSvelteLibraries"
1388
1306
  );
1389
1307
  }
1390
1308
  }
1391
1309
  function resolveViteRoot(viteConfig) {
1392
- return (0, import_vite4.normalizePath)(viteConfig.root ? import_path4.default.resolve(viteConfig.root) : process.cwd());
1310
+ return (0, import_vite3.normalizePath)(viteConfig.root ? import_path4.default.resolve(viteConfig.root) : process.cwd());
1393
1311
  }
1394
- function buildExtraViteConfig(options, config) {
1395
- var _a;
1396
- const svelteDeps = findRootSvelteDependencies(options.root);
1312
+ async function buildExtraViteConfig(options, config) {
1397
1313
  const extraViteConfig = {
1398
1314
  resolve: {
1399
1315
  mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1400
1316
  dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS]
1401
1317
  }
1402
1318
  };
1403
- extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(
1404
- svelteDeps,
1405
- options,
1406
- config.optimizeDeps
1407
- );
1319
+ const extraSvelteConfig = buildExtraConfigForSvelte(config);
1320
+ const extraDepsConfig = await buildExtraConfigForDependencies(options, config);
1321
+ extraViteConfig.optimizeDeps = {
1322
+ include: [
1323
+ ...extraSvelteConfig.optimizeDeps.include,
1324
+ ...extraDepsConfig.optimizeDeps.include.filter(
1325
+ (dep) => !(0, import_vitefu2.isDepExcluded)(dep, extraSvelteConfig.optimizeDeps.exclude)
1326
+ )
1327
+ ],
1328
+ exclude: [
1329
+ ...extraSvelteConfig.optimizeDeps.exclude,
1330
+ ...extraDepsConfig.optimizeDeps.exclude.filter(
1331
+ (dep) => !(0, import_vitefu2.isDepIncluded)(dep, extraSvelteConfig.optimizeDeps.include)
1332
+ )
1333
+ ]
1334
+ };
1335
+ extraViteConfig.ssr = {
1336
+ external: [
1337
+ ...extraSvelteConfig.ssr.external,
1338
+ ...extraDepsConfig.ssr.external.filter(
1339
+ (dep) => !(0, import_vitefu2.isDepNoExternaled)(dep, extraSvelteConfig.ssr.noExternal)
1340
+ )
1341
+ ],
1342
+ noExternal: [
1343
+ ...extraSvelteConfig.ssr.noExternal,
1344
+ ...extraDepsConfig.ssr.noExternal.filter(
1345
+ (dep) => !(0, import_vitefu2.isDepExternaled)(dep, extraSvelteConfig.ssr.external)
1346
+ )
1347
+ ]
1348
+ };
1408
1349
  if (options.prebundleSvelteLibraries) {
1409
- extraViteConfig.optimizeDeps = {
1410
- ...extraViteConfig.optimizeDeps,
1411
- extensions: options.extensions ?? [".svelte"],
1412
- esbuildOptions: {
1413
- plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1414
- } }]
1415
- }
1350
+ extraViteConfig.optimizeDeps.extensions = options.extensions ?? [".svelte"];
1351
+ extraViteConfig.optimizeDeps.esbuildOptions = {
1352
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1353
+ } }]
1416
1354
  };
1417
1355
  }
1418
- extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config, extraViteConfig);
1419
- if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && ((_a = config.experimental) == null ? void 0 : _a.hmrPartialAccept) !== false) {
1356
+ if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && config.experimental?.hmrPartialAccept !== false) {
1420
1357
  log.debug('enabling "experimental.hmrPartialAccept" in vite config');
1421
1358
  extraViteConfig.experimental = { hmrPartialAccept: true };
1422
1359
  }
1423
1360
  return extraViteConfig;
1424
1361
  }
1425
- function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
1362
+ async function buildExtraConfigForDependencies(options, config) {
1363
+ const depsConfig = await (0, import_vitefu2.crawlFrameworkPkgs)({
1364
+ root: options.root,
1365
+ isBuild: options.isBuild,
1366
+ viteUserConfig: config,
1367
+ isFrameworkPkgByJson(pkgJson) {
1368
+ return !!pkgJson.svelte;
1369
+ },
1370
+ isSemiFrameworkPkgByJson(pkgJson) {
1371
+ return !!pkgJson.dependencies?.svelte || !!pkgJson.peerDependencies?.svelte;
1372
+ },
1373
+ isFrameworkPkgByName(pkgName) {
1374
+ const isNotSveltePackage = isCommonDepWithoutSvelteField(pkgName);
1375
+ if (isNotSveltePackage) {
1376
+ return false;
1377
+ } else {
1378
+ return void 0;
1379
+ }
1380
+ }
1381
+ });
1382
+ log.debug("extra config for dependencies generated by vitefu", depsConfig);
1383
+ if (options.prebundleSvelteLibraries) {
1384
+ depsConfig.optimizeDeps.exclude = [];
1385
+ const userExclude = config.optimizeDeps?.exclude;
1386
+ depsConfig.optimizeDeps.include = !userExclude ? [] : depsConfig.optimizeDeps.include.filter((dep) => {
1387
+ return dep.includes(">") && dep.split(">").slice(0, -1).some((d) => (0, import_vitefu2.isDepExcluded)(d.trim(), userExclude));
1388
+ });
1389
+ }
1390
+ if (options.disableDependencyReinclusion === true) {
1391
+ depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter(
1392
+ (dep) => !dep.includes(">")
1393
+ );
1394
+ } else if (Array.isArray(options.disableDependencyReinclusion)) {
1395
+ const disabledDeps = options.disableDependencyReinclusion;
1396
+ depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter((dep) => {
1397
+ if (!dep.includes(">"))
1398
+ return true;
1399
+ const trimDep = dep.replace(/\s+/g, "");
1400
+ return disabledDeps.some((disabled) => trimDep.includes(`${disabled}>`));
1401
+ });
1402
+ }
1403
+ log.debug("post-processed extra config for dependencies", depsConfig);
1404
+ return depsConfig;
1405
+ }
1406
+ function buildExtraConfigForSvelte(config) {
1426
1407
  const include = [];
1427
1408
  const exclude = ["svelte-hmr"];
1428
- const isIncluded = (dep) => {
1429
- var _a;
1430
- return include.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.include) == null ? void 0 : _a.includes(dep));
1431
- };
1432
- const isExcluded = (dep) => {
1433
- var _a;
1434
- return exclude.includes(dep) || ((_a = optimizeDeps == null ? void 0 : optimizeDeps.exclude) == null ? void 0 : _a.some((id) => dep === id || id.startsWith(`${dep}/`)));
1435
- };
1436
- if (!isExcluded("svelte")) {
1409
+ if (!(0, import_vitefu2.isDepExcluded)("svelte", config.optimizeDeps?.exclude ?? [])) {
1437
1410
  const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
1438
1411
  log.debug(
1439
1412
  `adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(", ")} `
1440
1413
  );
1441
- include.push(...svelteImportsToInclude.filter((x) => !isIncluded(x)));
1414
+ include.push(...svelteImportsToInclude);
1442
1415
  } else {
1443
1416
  log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
1444
1417
  }
1445
- if (options.prebundleSvelteLibraries) {
1446
- return { include, exclude };
1447
- }
1448
- svelteDeps = svelteDeps.filter((dep) => dep.type === "component-library");
1449
- const svelteDepsToExclude = Array.from(new Set(svelteDeps.map((dep) => dep.name))).filter(
1450
- (dep) => !isIncluded(dep)
1451
- );
1452
- log.debug(`automatically excluding found svelte dependencies: ${svelteDepsToExclude.join(", ")}`);
1453
- exclude.push(...svelteDepsToExclude.filter((x) => !isExcluded(x)));
1454
- if (options.disableDependencyReinclusion !== true) {
1455
- const disabledReinclusions = options.disableDependencyReinclusion || [];
1456
- if (disabledReinclusions.length > 0) {
1457
- log.debug(`not reincluding transitive dependencies of`, disabledReinclusions);
1458
- }
1459
- const transitiveDepsToInclude = svelteDeps.filter((dep) => !disabledReinclusions.includes(dep.name) && isExcluded(dep.name)).flatMap((dep) => {
1460
- const localRequire = (0, import_module3.createRequire)(`${dep.dir}/package.json`);
1461
- return Object.keys(dep.pkg.dependencies || {}).filter((depOfDep) => !isExcluded(depOfDep) && needsOptimization(depOfDep, localRequire)).map((depOfDep) => dep.path.concat(dep.name, depOfDep).join(" > "));
1462
- });
1463
- log.debug(
1464
- `reincluding transitive dependencies of excluded svelte dependencies`,
1465
- transitiveDepsToInclude
1466
- );
1467
- include.push(...transitiveDepsToInclude);
1468
- }
1469
- return { include, exclude };
1470
- }
1471
- function buildSSROptionsForSvelte(svelteDeps, options, config) {
1472
- var _a, _b;
1473
1418
  const noExternal = [];
1474
- if (!((_b = (_a = config.ssr) == null ? void 0 : _a.external) == null ? void 0 : _b.includes("svelte"))) {
1419
+ const external = [];
1420
+ if (!(0, import_vitefu2.isDepExternaled)("svelte", config.ssr?.external ?? [])) {
1475
1421
  noExternal.push("svelte", /^svelte\//);
1476
1422
  }
1477
- noExternal.push(
1478
- ...Array.from(new Set(svelteDeps.map((s) => s.name))).filter(
1479
- (x) => {
1480
- var _a2, _b2;
1481
- return !((_b2 = (_a2 = config.ssr) == null ? void 0 : _a2.external) == null ? void 0 : _b2.includes(x));
1482
- }
1483
- )
1484
- );
1485
- const ssr = {
1486
- noExternal,
1487
- external: []
1488
- };
1489
- if (options.isServe) {
1490
- ssr.external = Array.from(
1491
- new Set(svelteDeps.flatMap((dep) => Object.keys(dep.pkg.dependencies || {})))
1492
- ).filter(
1493
- (dep) => {
1494
- var _a2, _b2;
1495
- return !ssr.noExternal.includes(dep) && !((_b2 = (_a2 = config.ssr) == null ? void 0 : _a2.external) == null ? void 0 : _b2.includes(dep));
1496
- }
1497
- );
1498
- }
1499
- return ssr;
1423
+ return { optimizeDeps: { include, exclude }, ssr: { noExternal, external } };
1500
1424
  }
1501
1425
  function patchResolvedViteConfig(viteConfig, options) {
1502
- var _a, _b;
1503
- const facadeEsbuildSveltePlugin = (_b = (_a = viteConfig.optimizeDeps.esbuildOptions) == null ? void 0 : _a.plugins) == null ? void 0 : _b.find(
1426
+ const facadeEsbuildSveltePlugin = viteConfig.optimizeDeps.esbuildOptions?.plugins?.find(
1504
1427
  (plugin) => plugin.name === facadeEsbuildSveltePluginName
1505
1428
  );
1506
1429
  if (facadeEsbuildSveltePlugin) {
@@ -1614,7 +1537,7 @@ var VitePluginSvelteCache = class {
1614
1537
  };
1615
1538
 
1616
1539
  // src/utils/watch.ts
1617
- var import_fs4 = __toESM(require("fs"), 1);
1540
+ var import_fs3 = __toESM(require("fs"), 1);
1618
1541
  var import_path5 = __toESM(require("path"), 1);
1619
1542
  function setupWatchers(options, cache, requestParser) {
1620
1543
  const { server, configFile: svelteConfigFile } = options;
@@ -1626,7 +1549,7 @@ function setupWatchers(options, cache, requestParser) {
1626
1549
  const emitChangeEventOnDependants = (filename) => {
1627
1550
  const dependants = cache.getDependants(filename);
1628
1551
  dependants.forEach((dependant) => {
1629
- if (import_fs4.default.existsSync(dependant)) {
1552
+ if (import_fs3.default.existsSync(dependant)) {
1630
1553
  log.debug(
1631
1554
  `emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`
1632
1555
  );
@@ -1687,22 +1610,21 @@ function setupWatchers(options, cache, requestParser) {
1687
1610
  });
1688
1611
  }
1689
1612
  function ensureWatchedFile(watcher, file, root) {
1690
- if (file && !file.startsWith(root + "/") && !file.includes("\0") && import_fs4.default.existsSync(file)) {
1613
+ if (file && !file.startsWith(root + "/") && !file.includes("\0") && import_fs3.default.existsSync(file)) {
1691
1614
  watcher.add(import_path5.default.resolve(file));
1692
1615
  }
1693
1616
  }
1694
1617
 
1695
1618
  // src/utils/resolve.ts
1696
1619
  var import_path6 = __toESM(require("path"), 1);
1697
- var import_module4 = require("module");
1698
- function resolveViaPackageJsonSvelte(importee, importer, cache) {
1699
- if (importer && isBareImport(importee) && !isNodeInternal(importee) && !is_common_without_svelte_field(importee)) {
1620
+ var import_module2 = require("module");
1621
+ async function resolveViaPackageJsonSvelte(importee, importer, cache) {
1622
+ if (importer && isBareImport(importee) && !isNodeInternal(importee) && !isCommonDepWithoutSvelteField(importee)) {
1700
1623
  const cached = cache.getResolvedSvelteField(importee, importer);
1701
1624
  if (cached) {
1702
1625
  return cached;
1703
1626
  }
1704
- const localRequire = (0, import_module4.createRequire)(importer);
1705
- const pkgData = resolveDependencyData(importee, localRequire);
1627
+ const pkgData = await resolveDependencyData(importee, importer);
1706
1628
  if (pkgData) {
1707
1629
  const { pkg, dir } = pkgData;
1708
1630
  if (pkg.svelte) {
@@ -1714,7 +1636,7 @@ function resolveViaPackageJsonSvelte(importee, importer, cache) {
1714
1636
  }
1715
1637
  }
1716
1638
  function isNodeInternal(importee) {
1717
- return importee.startsWith("node:") || import_module4.builtinModules.includes(importee);
1639
+ return importee.startsWith("node:") || import_module2.builtinModules.includes(importee);
1718
1640
  }
1719
1641
  function isBareImport(importee) {
1720
1642
  if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || import_path6.default.isAbsolute(importee)) {
@@ -1732,7 +1654,7 @@ function isBareImport(importee) {
1732
1654
  }
1733
1655
 
1734
1656
  // src/utils/optimizer.ts
1735
- var import_fs5 = require("fs");
1657
+ var import_fs4 = require("fs");
1736
1658
  var import_path7 = __toESM(require("path"), 1);
1737
1659
  var PREBUNDLE_SENSITIVE_OPTIONS = [
1738
1660
  "compilerOptions",
@@ -1750,11 +1672,11 @@ async function saveSvelteMetadata(cacheDir, options) {
1750
1672
  });
1751
1673
  let existingSvelteMetadata;
1752
1674
  try {
1753
- existingSvelteMetadata = await import_fs5.promises.readFile(svelteMetadataPath, "utf8");
1675
+ existingSvelteMetadata = await import_fs4.promises.readFile(svelteMetadataPath, "utf8");
1754
1676
  } catch {
1755
1677
  }
1756
- await import_fs5.promises.mkdir(cacheDir, { recursive: true });
1757
- await import_fs5.promises.writeFile(svelteMetadataPath, currentSvelteMetadata);
1678
+ await import_fs4.promises.mkdir(cacheDir, { recursive: true });
1679
+ await import_fs4.promises.writeFile(svelteMetadataPath, currentSvelteMetadata);
1758
1680
  return currentSvelteMetadata !== existingSvelteMetadata;
1759
1681
  }
1760
1682
  function generateSvelteMetadata(options) {
@@ -1766,10 +1688,10 @@ function generateSvelteMetadata(options) {
1766
1688
  }
1767
1689
 
1768
1690
  // src/ui/inspector/plugin.ts
1769
- var import_vite5 = require("vite");
1691
+ var import_vite4 = require("vite");
1770
1692
  var import_path8 = __toESM(require("path"), 1);
1771
1693
  var import_url2 = require("url");
1772
- var import_fs6 = __toESM(require("fs"), 1);
1694
+ var import_fs5 = __toESM(require("fs"), 1);
1773
1695
 
1774
1696
  // src/ui/inspector/utils.ts
1775
1697
  var FS_PREFIX = `/@fs/`;
@@ -1794,7 +1716,7 @@ var defaultInspectorOptions = {
1794
1716
  customStyles: true
1795
1717
  };
1796
1718
  function getInspectorPath() {
1797
- const pluginPath = (0, import_vite5.normalizePath)(import_path8.default.dirname((0, import_url2.fileURLToPath)(importMetaUrl)));
1719
+ const pluginPath = (0, import_vite4.normalizePath)(import_path8.default.dirname((0, import_url2.fileURLToPath)(importMetaUrl)));
1798
1720
  return pluginPath.replace(/\/vite-plugin-svelte\/dist$/, "/vite-plugin-svelte/src/ui/inspector/");
1799
1721
  }
1800
1722
  function svelteInspector() {
@@ -1808,9 +1730,8 @@ function svelteInspector() {
1808
1730
  apply: "serve",
1809
1731
  enforce: "pre",
1810
1732
  configResolved(config) {
1811
- var _a, _b, _c;
1812
1733
  const vps = config.plugins.find((p) => p.name === "vite-plugin-svelte");
1813
- if ((_c = (_b = (_a = vps == null ? void 0 : vps.api) == null ? void 0 : _a.options) == null ? void 0 : _b.experimental) == null ? void 0 : _c.inspector) {
1734
+ if (vps?.api?.options?.experimental?.inspector) {
1814
1735
  inspectorOptions = {
1815
1736
  ...defaultInspectorOptions,
1816
1737
  ...vps.api.options.experimental.inspector
@@ -1828,7 +1749,7 @@ function svelteInspector() {
1828
1749
  }
1829
1750
  },
1830
1751
  async resolveId(importee, importer, options) {
1831
- if ((options == null ? void 0 : options.ssr) || disabled) {
1752
+ if (options?.ssr || disabled) {
1832
1753
  return;
1833
1754
  }
1834
1755
  if (importee.startsWith("virtual:svelte-inspector-options")) {
@@ -1840,22 +1761,22 @@ function svelteInspector() {
1840
1761
  }
1841
1762
  },
1842
1763
  async load(id, options) {
1843
- if ((options == null ? void 0 : options.ssr) || disabled) {
1764
+ if (options?.ssr || disabled) {
1844
1765
  return;
1845
1766
  }
1846
1767
  if (id === "virtual:svelte-inspector-options") {
1847
1768
  return `export default ${JSON.stringify(inspectorOptions ?? {})}`;
1848
1769
  } else if (id.startsWith(inspectorPath)) {
1849
1770
  const file = idToFile(id);
1850
- if (import_fs6.default.existsSync(file)) {
1851
- return await import_fs6.default.promises.readFile(file, "utf-8");
1771
+ if (import_fs5.default.existsSync(file)) {
1772
+ return await import_fs5.default.promises.readFile(file, "utf-8");
1852
1773
  } else {
1853
1774
  log.error(`failed to find file for svelte-inspector: ${file}, referenced by id ${id}.`);
1854
1775
  }
1855
1776
  }
1856
1777
  },
1857
1778
  transform(code, id, options) {
1858
- if ((options == null ? void 0 : options.ssr) || disabled || !appendTo) {
1779
+ if (options?.ssr || disabled || !appendTo) {
1859
1780
  return;
1860
1781
  }
1861
1782
  if (id.endsWith(appendTo)) {
@@ -1909,7 +1830,7 @@ function svelte(inlineOptions) {
1909
1830
  log.setLevel(config.logLevel);
1910
1831
  }
1911
1832
  options = await preResolveOptions(inlineOptions, config, configEnv);
1912
- const extraViteConfig = buildExtraViteConfig(options, config);
1833
+ const extraViteConfig = await buildExtraViteConfig(options, config);
1913
1834
  log.debug("additional vite config", extraViteConfig);
1914
1835
  return extraViteConfig;
1915
1836
  },
@@ -1935,7 +1856,7 @@ function svelte(inlineOptions) {
1935
1856
  setupWatchers(options, cache, requestParser);
1936
1857
  },
1937
1858
  load(id, opts) {
1938
- const ssr = !!(opts == null ? void 0 : opts.ssr);
1859
+ const ssr = !!opts?.ssr;
1939
1860
  const svelteRequest = requestParser(id, !!ssr);
1940
1861
  if (svelteRequest) {
1941
1862
  const { filename, query } = svelteRequest;
@@ -1948,14 +1869,14 @@ function svelte(inlineOptions) {
1948
1869
  }
1949
1870
  if (viteConfig.assetsInclude(filename)) {
1950
1871
  log.debug(`load returns raw content for ${filename}`);
1951
- return import_fs7.default.readFileSync(filename, "utf-8");
1872
+ return import_fs6.default.readFileSync(filename, "utf-8");
1952
1873
  }
1953
1874
  }
1954
1875
  },
1955
1876
  async resolveId(importee, importer, opts) {
1956
- const ssr = !!(opts == null ? void 0 : opts.ssr);
1877
+ const ssr = !!opts?.ssr;
1957
1878
  const svelteRequest = requestParser(importee, ssr);
1958
- if (svelteRequest == null ? void 0 : svelteRequest.query.svelte) {
1879
+ if (svelteRequest?.query.svelte) {
1959
1880
  if (svelteRequest.query.type === "style") {
1960
1881
  log.debug(`resolveId resolved virtual css module ${svelteRequest.cssId}`);
1961
1882
  return svelteRequest.cssId;
@@ -1981,24 +1902,27 @@ function svelte(inlineOptions) {
1981
1902
  }
1982
1903
  return resolvedSvelteSSR;
1983
1904
  }
1984
- try {
1985
- const resolved = resolveViaPackageJsonSvelte(importee, importer, cache);
1986
- if (resolved) {
1987
- log.debug(
1988
- `resolveId resolved ${resolved} via package.json svelte field of ${importee}`
1905
+ const scan = !!opts?.scan;
1906
+ const isPrebundled = options.prebundleSvelteLibraries && viteConfig.optimizeDeps?.disabled !== true && viteConfig.optimizeDeps?.disabled !== (options.isBuild ? "build" : "dev") && !(0, import_vitefu3.isDepExcluded)(importee, viteConfig.optimizeDeps?.exclude ?? []);
1907
+ if (ssr || scan || !isPrebundled) {
1908
+ try {
1909
+ const resolved = await resolveViaPackageJsonSvelte(importee, importer, cache);
1910
+ if (resolved) {
1911
+ log.debug(
1912
+ `resolveId resolved ${resolved} via package.json svelte field of ${importee}`
1913
+ );
1914
+ return resolved;
1915
+ }
1916
+ } catch (e) {
1917
+ log.debug.once(
1918
+ `error trying to resolve ${importee} from ${importer} via package.json svelte field `,
1919
+ e
1989
1920
  );
1990
- return resolved;
1991
1921
  }
1992
- } catch (e) {
1993
- log.debug.once(
1994
- `error trying to resolve ${importee} from ${importer} via package.json svelte field `,
1995
- e
1996
- );
1997
1922
  }
1998
1923
  },
1999
1924
  async transform(code, id, opts) {
2000
- var _a;
2001
- const ssr = !!(opts == null ? void 0 : opts.ssr);
1925
+ const ssr = !!opts?.ssr;
2002
1926
  const svelteRequest = requestParser(id, ssr);
2003
1927
  if (!svelteRequest || svelteRequest.query.svelte) {
2004
1928
  return;
@@ -2012,7 +1936,7 @@ function svelte(inlineOptions) {
2012
1936
  }
2013
1937
  logCompilerWarnings(svelteRequest, compileData.compiled.warnings, options);
2014
1938
  cache.update(compileData);
2015
- if (((_a = compileData.dependencies) == null ? void 0 : _a.length) && options.server) {
1939
+ if (compileData.dependencies?.length && options.server) {
2016
1940
  compileData.dependencies.forEach((d) => {
2017
1941
  ensureWatchedFile(options.server.watcher, d, options.root);
2018
1942
  });