@sveltejs/vite-plugin-svelte 1.1.1 → 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.4.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");
@@ -368,7 +369,8 @@ var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequ
368
369
  ...dynamicCompileOptions
369
370
  } : compileOptions;
370
371
  const compiled = (0, import_compiler.compile)(finalCode, finalCompileOptions);
371
- if (emitCss && compiled.css.code) {
372
+ const hasCss = compiled.css?.code?.trim().length > 0;
373
+ if (emitCss && hasCss) {
372
374
  compiled.js.code += `
373
375
  import ${JSON.stringify(cssId)};
374
376
  `;
@@ -377,7 +379,7 @@ import ${JSON.stringify(cssId)};
377
379
  compiled.js.code = makeHot({
378
380
  id: filename,
379
381
  compiledCode: compiled.js.code,
380
- hotOptions: options.hot,
382
+ hotOptions: { ...options.hot, injectCss: options.hot?.injectCss === true && hasCss },
381
383
  compiled,
382
384
  originalCode: code,
383
385
  compileOptions: finalCompileOptions
@@ -602,182 +604,9 @@ var SVELTE_HMR_IMPORTS = [
602
604
  // src/utils/options.ts
603
605
  var import_path4 = __toESM(require("path"), 1);
604
606
 
605
- // src/utils/dependencies.ts
606
- var import_path2 = __toESM(require("path"), 1);
607
- var import_fs2 = __toESM(require("fs"), 1);
608
- var import_module2 = require("module");
609
- function findRootSvelteDependencies(root, cwdFallback = true) {
610
- log.debug(`findSvelteDependencies: searching svelte dependencies in ${root}`);
611
- const pkgFile = import_path2.default.join(root, "package.json");
612
- if (!import_fs2.default.existsSync(pkgFile)) {
613
- if (cwdFallback) {
614
- const cwd = process.cwd();
615
- if (root !== cwd) {
616
- log.debug(`no package.json found in vite root ${root}`);
617
- return findRootSvelteDependencies(cwd, false);
618
- }
619
- }
620
- log.warn(`no package.json found, findRootSvelteDependencies failed`);
621
- return [];
622
- }
623
- const pkg = parsePkg(root);
624
- if (!pkg) {
625
- return [];
626
- }
627
- const deps = [
628
- ...Object.keys(pkg.dependencies || {}),
629
- ...Object.keys(pkg.devDependencies || {})
630
- ].filter((dep) => !is_common_without_svelte_field(dep));
631
- return getSvelteDependencies(deps, root);
632
- }
633
- function getSvelteDependencies(deps, pkgDir, path9 = []) {
634
- const result = [];
635
- const localRequire = (0, import_module2.createRequire)(`${pkgDir}/package.json`);
636
- const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
637
- for (const { pkg, dir } of resolvedDeps) {
638
- const type = getSvelteDependencyType(pkg);
639
- if (!type)
640
- continue;
641
- result.push({ name: pkg.name, type, pkg, dir, path: path9 });
642
- if (type === "component-library" && pkg.dependencies) {
643
- let dependencyNames = Object.keys(pkg.dependencies);
644
- const circular = dependencyNames.filter((name) => path9.includes(name));
645
- if (circular.length > 0) {
646
- log.warn.enabled && log.warn(
647
- `skipping circular svelte dependencies in automated vite optimizeDeps handling`,
648
- circular.map((x) => path9.concat(x).join(">"))
649
- );
650
- dependencyNames = dependencyNames.filter((name) => !path9.includes(name));
651
- }
652
- if (path9.length === 3) {
653
- log.debug.once(`encountered deep svelte dependency tree: ${path9.join(">")}`);
654
- }
655
- result.push(...getSvelteDependencies(dependencyNames, dir, path9.concat(pkg.name)));
656
- }
657
- }
658
- return result;
659
- }
660
- function resolveDependencyData(dep, localRequire) {
661
- try {
662
- const pkgJson = `${dep}/package.json`;
663
- const pkg = localRequire(pkgJson);
664
- const dir = import_path2.default.dirname(localRequire.resolve(pkgJson));
665
- return { dir, pkg };
666
- } catch (e) {
667
- log.debug.once(`dependency ${dep} does not export package.json`, e);
668
- try {
669
- let dir = import_path2.default.dirname(localRequire.resolve(dep));
670
- while (dir) {
671
- const pkg = parsePkg(dir, true);
672
- if (pkg && pkg.name === dep) {
673
- return { dir, pkg };
674
- }
675
- const parent = import_path2.default.dirname(dir);
676
- if (parent === dir) {
677
- break;
678
- }
679
- dir = parent;
680
- }
681
- } catch (e2) {
682
- log.debug.once(`error while trying to find package.json of ${dep}`, e2);
683
- }
684
- }
685
- log.debug.once(`failed to resolve ${dep}`);
686
- }
687
- function parsePkg(dir, silent = false) {
688
- const pkgFile = import_path2.default.join(dir, "package.json");
689
- try {
690
- return JSON.parse(import_fs2.default.readFileSync(pkgFile, "utf-8"));
691
- } catch (e) {
692
- !silent && log.warn.enabled && log.warn(`failed to parse ${pkgFile}`, e);
693
- }
694
- }
695
- function getSvelteDependencyType(pkg) {
696
- if (isSvelteComponentLib(pkg)) {
697
- return "component-library";
698
- } else if (isSvelteLib(pkg)) {
699
- return "js-library";
700
- } else {
701
- return void 0;
702
- }
703
- }
704
- function isSvelteComponentLib(pkg) {
705
- return !!pkg.svelte;
706
- }
707
- function isSvelteLib(pkg) {
708
- return !!pkg.dependencies?.svelte || !!pkg.peerDependencies?.svelte;
709
- }
710
- var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
711
- "@lukeed/uuid",
712
- "@playwright/test",
713
- "@sveltejs/vite-plugin-svelte",
714
- "@sveltejs/kit",
715
- "autoprefixer",
716
- "cookie",
717
- "dotenv",
718
- "esbuild",
719
- "eslint",
720
- "jest",
721
- "mdsvex",
722
- "playwright",
723
- "postcss",
724
- "prettier",
725
- "svelte",
726
- "svelte-check",
727
- "svelte-hmr",
728
- "svelte-preprocess",
729
- "tslib",
730
- "typescript",
731
- "vite",
732
- "vitest",
733
- "__vite-browser-external"
734
- ];
735
- var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
736
- "@fontsource/",
737
- "@postcss-plugins/",
738
- "@rollup/",
739
- "@sveltejs/adapter-",
740
- "@types/",
741
- "@typescript-eslint/",
742
- "eslint-",
743
- "jest-",
744
- "postcss-plugin-",
745
- "prettier-plugin-",
746
- "rollup-plugin-",
747
- "vite-plugin-"
748
- ];
749
- function is_common_without_svelte_field(dependency) {
750
- return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
751
- (prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
752
- );
753
- }
754
- function needsOptimization(dep, localRequire) {
755
- const depData = resolveDependencyData(dep, localRequire);
756
- if (!depData)
757
- return false;
758
- const pkg = depData.pkg;
759
- const hasEsmFields = pkg.module || pkg.exports;
760
- if (hasEsmFields)
761
- return false;
762
- if (pkg.main) {
763
- const entryExt = import_path2.default.extname(pkg.main);
764
- return !entryExt || entryExt === ".js" || entryExt === ".cjs";
765
- } else {
766
- try {
767
- localRequire.resolve(`${dep}/index.js`);
768
- return true;
769
- } catch {
770
- return false;
771
- }
772
- }
773
- }
774
-
775
- // src/utils/options.ts
776
- var import_module3 = require("module");
777
-
778
607
  // src/utils/esbuild.ts
779
- var import_fs3 = require("fs");
780
- var import_compiler2 = require("svelte/compiler");
608
+ var import_fs2 = require("fs");
609
+ var import_compiler3 = require("svelte/compiler");
781
610
 
782
611
  // src/utils/error.ts
783
612
  function toRollupError(error, options) {
@@ -832,7 +661,38 @@ function formatFrameForVite(frame) {
832
661
  return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
833
662
  }
834
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
+
835
694
  // src/utils/esbuild.ts
695
+ var isCssString = atLeastSvelte("3.53.0");
836
696
  var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
837
697
  function esbuildSveltePlugin(options) {
838
698
  return {
@@ -843,7 +703,7 @@ function esbuildSveltePlugin(options) {
843
703
  const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
844
704
  const svelteFilter = new RegExp(`\\.(` + svelteExtensions.join("|") + `)(\\?.*)?$`);
845
705
  build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
846
- const code = await import_fs3.promises.readFile(filename, "utf8");
706
+ const code = await import_fs2.promises.readFile(filename, "utf8");
847
707
  try {
848
708
  const contents = await compileSvelte(options, { filename, code });
849
709
  return { contents };
@@ -855,9 +715,13 @@ function esbuildSveltePlugin(options) {
855
715
  };
856
716
  }
857
717
  async function compileSvelte(options, { filename, code }) {
718
+ let css = options.compilerOptions.css;
719
+ if (css !== "none") {
720
+ css = isCssString ? "injected" : true;
721
+ }
858
722
  const compileOptions = {
859
723
  ...options.compilerOptions,
860
- css: true,
724
+ css,
861
725
  filename,
862
726
  format: "esm",
863
727
  generate: "dom"
@@ -865,7 +729,7 @@ async function compileSvelte(options, { filename, code }) {
865
729
  let preprocessed;
866
730
  if (options.preprocess) {
867
731
  try {
868
- preprocessed = await (0, import_compiler2.preprocess)(code, options.preprocess, { filename });
732
+ preprocessed = await (0, import_compiler3.preprocess)(code, options.preprocess, { filename });
869
733
  } catch (e) {
870
734
  e.message = `Error while preprocessing ${filename}${e.message ? ` - ${e.message}` : ""}`;
871
735
  throw e;
@@ -886,14 +750,14 @@ async function compileSvelte(options, { filename, code }) {
886
750
  ...compileOptions,
887
751
  ...dynamicCompileOptions
888
752
  } : compileOptions;
889
- const compiled = (0, import_compiler2.compile)(finalCode, finalCompileOptions);
753
+ const compiled = (0, import_compiler3.compile)(finalCode, finalCompileOptions);
890
754
  return compiled.js.code + "//# sourceMappingURL=" + compiled.js.map.toUrl();
891
755
  }
892
756
 
893
757
  // src/utils/preprocess.ts
894
758
  var vite = __toESM(require("vite"), 1);
895
759
  var import_magic_string2 = __toESM(require("magic-string"), 1);
896
- var import_compiler3 = require("svelte/compiler");
760
+ var import_compiler4 = require("svelte/compiler");
897
761
 
898
762
  // src/utils/sourcemap.ts
899
763
  var import_magic_string = __toESM(require("magic-string"), 1);
@@ -944,7 +808,7 @@ async function buildSourceMap(from, to, filename) {
944
808
  }
945
809
 
946
810
  // src/utils/preprocess.ts
947
- var import_path3 = __toESM(require("path"), 1);
811
+ var import_path2 = __toESM(require("path"), 1);
948
812
  var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
949
813
  var supportedScriptLangs = ["ts"];
950
814
  function createViteScriptPreprocessor() {
@@ -977,7 +841,7 @@ function createViteStylePreprocessor(config) {
977
841
  const moduleId = `${filename}.${lang}`;
978
842
  const result = await transform(content, moduleId);
979
843
  if (result.map?.sources?.[0] === moduleId) {
980
- result.map.sources[0] = import_path3.default.basename(filename);
844
+ result.map.sources[0] = import_path2.default.basename(filename);
981
845
  }
982
846
  return {
983
847
  code: result.code,
@@ -1005,7 +869,7 @@ function getCssTransformFn(config) {
1005
869
  function createVitePreprocessorGroup(config) {
1006
870
  return {
1007
871
  markup({ content, filename }) {
1008
- return (0, import_compiler3.preprocess)(
872
+ return (0, import_compiler4.preprocess)(
1009
873
  content,
1010
874
  {
1011
875
  script: createViteScriptPreprocessor(),
@@ -1024,7 +888,7 @@ function createInjectScopeEverythingRulePreprocessorGroup() {
1024
888
  return {
1025
889
  code: s.toString(),
1026
890
  map: s.generateDecodedMap({
1027
- source: filename ? import_path3.default.basename(filename) : void 0,
891
+ source: filename ? import_path2.default.basename(filename) : void 0,
1028
892
  hires: true
1029
893
  })
1030
894
  };
@@ -1148,6 +1012,72 @@ function validateSourceMapOutputWrapper(group, i) {
1148
1012
 
1149
1013
  // src/utils/options.ts
1150
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");
1151
1081
  var allowedPluginOptions = /* @__PURE__ */ new Set([
1152
1082
  "include",
1153
1083
  "exclude",
@@ -1265,13 +1195,14 @@ function mergeConfigs(...configs) {
1265
1195
  return result;
1266
1196
  }
1267
1197
  function resolveOptions(preResolveOptions2, viteConfig) {
1198
+ const css = cssAsString ? preResolveOptions2.emitCss ? "external" : "injected" : !preResolveOptions2.emitCss;
1268
1199
  const defaultOptions = {
1269
1200
  hot: viteConfig.isProduction ? false : {
1270
- injectCss: !preResolveOptions2.emitCss,
1201
+ injectCss: css === true || css === "injected",
1271
1202
  partialAccept: !!viteConfig.experimental?.hmrPartialAccept
1272
1203
  },
1273
1204
  compilerOptions: {
1274
- css: !preResolveOptions2.emitCss,
1205
+ css,
1275
1206
  dev: !viteConfig.isProduction
1276
1207
  }
1277
1208
  };
@@ -1299,11 +1230,13 @@ function enforceOptionsForHmr(options) {
1299
1230
  log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
1300
1231
  options.hot.injectCss = false;
1301
1232
  }
1302
- if (options.compilerOptions.css) {
1233
+ const css = options.compilerOptions.css;
1234
+ if (css === true || css === "injected") {
1235
+ const forcedCss = cssAsString ? "external" : false;
1303
1236
  log.warn(
1304
- "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}`
1305
1238
  );
1306
- options.compilerOptions.css = false;
1239
+ options.compilerOptions.css = forcedCss;
1307
1240
  }
1308
1241
  } else {
1309
1242
  if (options.hot === true || !options.hot.injectCss) {
@@ -1316,11 +1249,13 @@ function enforceOptionsForHmr(options) {
1316
1249
  options.hot.injectCss = true;
1317
1250
  }
1318
1251
  }
1319
- if (!options.compilerOptions.css) {
1252
+ const css = options.compilerOptions.css;
1253
+ if (!(css === true || css === "injected")) {
1254
+ const forcedCss = cssAsString ? "injected" : true;
1320
1255
  log.warn(
1321
- "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}`
1322
1257
  );
1323
- options.compilerOptions.css = true;
1258
+ options.compilerOptions.css = forcedCss;
1324
1259
  }
1325
1260
  }
1326
1261
  }
@@ -1358,16 +1293,9 @@ function removeIgnoredOptions(options) {
1358
1293
  }
1359
1294
  }
1360
1295
  function addSvelteKitOptions(options) {
1361
- if (options?.kit != null) {
1362
- const kit_browser_hydrate = options.kit.browser?.hydrate;
1363
- const hydratable = kit_browser_hydrate !== false;
1364
- if (options.compilerOptions.hydratable != null && options.compilerOptions.hydratable !== hydratable) {
1365
- log.warn(
1366
- `Conflicting values "compilerOptions.hydratable: ${options.compilerOptions.hydratable}" and "kit.browser.hydrate: ${kit_browser_hydrate}" in your svelte config. You should remove "compilerOptions.hydratable".`
1367
- );
1368
- }
1369
- log.debug(`Setting compilerOptions.hydratable: ${hydratable} for SvelteKit`);
1370
- 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;
1371
1299
  }
1372
1300
  }
1373
1301
  function handleDeprecatedOptions(options) {
@@ -1381,100 +1309,118 @@ function handleDeprecatedOptions(options) {
1381
1309
  function resolveViteRoot(viteConfig) {
1382
1310
  return (0, import_vite3.normalizePath)(viteConfig.root ? import_path4.default.resolve(viteConfig.root) : process.cwd());
1383
1311
  }
1384
- function buildExtraViteConfig(options, config) {
1385
- const svelteDeps = findRootSvelteDependencies(options.root);
1312
+ async function buildExtraViteConfig(options, config) {
1386
1313
  const extraViteConfig = {
1387
1314
  resolve: {
1388
1315
  mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1389
1316
  dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS]
1390
1317
  }
1391
1318
  };
1392
- extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(
1393
- svelteDeps,
1394
- options,
1395
- config.optimizeDeps
1396
- );
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
+ };
1397
1349
  if (options.prebundleSvelteLibraries) {
1398
- extraViteConfig.optimizeDeps = {
1399
- ...extraViteConfig.optimizeDeps,
1400
- extensions: options.extensions ?? [".svelte"],
1401
- esbuildOptions: {
1402
- plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1403
- } }]
1404
- }
1350
+ extraViteConfig.optimizeDeps.extensions = options.extensions ?? [".svelte"];
1351
+ extraViteConfig.optimizeDeps.esbuildOptions = {
1352
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1353
+ } }]
1405
1354
  };
1406
1355
  }
1407
- extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config, extraViteConfig);
1408
1356
  if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && config.experimental?.hmrPartialAccept !== false) {
1409
1357
  log.debug('enabling "experimental.hmrPartialAccept" in vite config');
1410
1358
  extraViteConfig.experimental = { hmrPartialAccept: true };
1411
1359
  }
1412
1360
  return extraViteConfig;
1413
1361
  }
1414
- 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) {
1415
1407
  const include = [];
1416
1408
  const exclude = ["svelte-hmr"];
1417
- const isIncluded = (dep) => include.includes(dep) || optimizeDeps?.include?.includes(dep);
1418
- const isExcluded = (dep) => {
1419
- return exclude.includes(dep) || optimizeDeps?.exclude?.some((id) => dep === id || id.startsWith(`${dep}/`));
1420
- };
1421
- if (!isExcluded("svelte")) {
1409
+ if (!(0, import_vitefu2.isDepExcluded)("svelte", config.optimizeDeps?.exclude ?? [])) {
1422
1410
  const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
1423
1411
  log.debug(
1424
1412
  `adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(", ")} `
1425
1413
  );
1426
- include.push(...svelteImportsToInclude.filter((x) => !isIncluded(x)));
1414
+ include.push(...svelteImportsToInclude);
1427
1415
  } else {
1428
1416
  log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
1429
1417
  }
1430
- if (options.prebundleSvelteLibraries) {
1431
- return { include, exclude };
1432
- }
1433
- svelteDeps = svelteDeps.filter((dep) => dep.type === "component-library");
1434
- const svelteDepsToExclude = Array.from(new Set(svelteDeps.map((dep) => dep.name))).filter(
1435
- (dep) => !isIncluded(dep)
1436
- );
1437
- log.debug(`automatically excluding found svelte dependencies: ${svelteDepsToExclude.join(", ")}`);
1438
- exclude.push(...svelteDepsToExclude.filter((x) => !isExcluded(x)));
1439
- if (options.disableDependencyReinclusion !== true) {
1440
- const disabledReinclusions = options.disableDependencyReinclusion || [];
1441
- if (disabledReinclusions.length > 0) {
1442
- log.debug(`not reincluding transitive dependencies of`, disabledReinclusions);
1443
- }
1444
- const transitiveDepsToInclude = svelteDeps.filter((dep) => !disabledReinclusions.includes(dep.name) && isExcluded(dep.name)).flatMap((dep) => {
1445
- const localRequire = (0, import_module3.createRequire)(`${dep.dir}/package.json`);
1446
- return Object.keys(dep.pkg.dependencies || {}).filter((depOfDep) => !isExcluded(depOfDep) && needsOptimization(depOfDep, localRequire)).map((depOfDep) => dep.path.concat(dep.name, depOfDep).join(" > "));
1447
- });
1448
- log.debug(
1449
- `reincluding transitive dependencies of excluded svelte dependencies`,
1450
- transitiveDepsToInclude
1451
- );
1452
- include.push(...transitiveDepsToInclude);
1453
- }
1454
- return { include, exclude };
1455
- }
1456
- function buildSSROptionsForSvelte(svelteDeps, options, config) {
1457
1418
  const noExternal = [];
1458
- if (!config.ssr?.external?.includes("svelte")) {
1419
+ const external = [];
1420
+ if (!(0, import_vitefu2.isDepExternaled)("svelte", config.ssr?.external ?? [])) {
1459
1421
  noExternal.push("svelte", /^svelte\//);
1460
1422
  }
1461
- noExternal.push(
1462
- ...Array.from(new Set(svelteDeps.map((s) => s.name))).filter(
1463
- (x) => !config.ssr?.external?.includes(x)
1464
- )
1465
- );
1466
- const ssr = {
1467
- noExternal,
1468
- external: []
1469
- };
1470
- if (options.isServe) {
1471
- ssr.external = Array.from(
1472
- new Set(svelteDeps.flatMap((dep) => Object.keys(dep.pkg.dependencies || {})))
1473
- ).filter(
1474
- (dep) => !ssr.noExternal.includes(dep) && !config.ssr?.external?.includes(dep)
1475
- );
1476
- }
1477
- return ssr;
1423
+ return { optimizeDeps: { include, exclude }, ssr: { noExternal, external } };
1478
1424
  }
1479
1425
  function patchResolvedViteConfig(viteConfig, options) {
1480
1426
  const facadeEsbuildSveltePlugin = viteConfig.optimizeDeps.esbuildOptions?.plugins?.find(
@@ -1591,7 +1537,7 @@ var VitePluginSvelteCache = class {
1591
1537
  };
1592
1538
 
1593
1539
  // src/utils/watch.ts
1594
- var import_fs4 = __toESM(require("fs"), 1);
1540
+ var import_fs3 = __toESM(require("fs"), 1);
1595
1541
  var import_path5 = __toESM(require("path"), 1);
1596
1542
  function setupWatchers(options, cache, requestParser) {
1597
1543
  const { server, configFile: svelteConfigFile } = options;
@@ -1603,7 +1549,7 @@ function setupWatchers(options, cache, requestParser) {
1603
1549
  const emitChangeEventOnDependants = (filename) => {
1604
1550
  const dependants = cache.getDependants(filename);
1605
1551
  dependants.forEach((dependant) => {
1606
- if (import_fs4.default.existsSync(dependant)) {
1552
+ if (import_fs3.default.existsSync(dependant)) {
1607
1553
  log.debug(
1608
1554
  `emitting virtual change event for "${dependant}" because depdendency "${filename}" changed`
1609
1555
  );
@@ -1664,22 +1610,21 @@ function setupWatchers(options, cache, requestParser) {
1664
1610
  });
1665
1611
  }
1666
1612
  function ensureWatchedFile(watcher, file, root) {
1667
- 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)) {
1668
1614
  watcher.add(import_path5.default.resolve(file));
1669
1615
  }
1670
1616
  }
1671
1617
 
1672
1618
  // src/utils/resolve.ts
1673
1619
  var import_path6 = __toESM(require("path"), 1);
1674
- var import_module4 = require("module");
1675
- function resolveViaPackageJsonSvelte(importee, importer, cache) {
1676
- 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)) {
1677
1623
  const cached = cache.getResolvedSvelteField(importee, importer);
1678
1624
  if (cached) {
1679
1625
  return cached;
1680
1626
  }
1681
- const localRequire = (0, import_module4.createRequire)(importer);
1682
- const pkgData = resolveDependencyData(importee, localRequire);
1627
+ const pkgData = await resolveDependencyData(importee, importer);
1683
1628
  if (pkgData) {
1684
1629
  const { pkg, dir } = pkgData;
1685
1630
  if (pkg.svelte) {
@@ -1691,7 +1636,7 @@ function resolveViaPackageJsonSvelte(importee, importer, cache) {
1691
1636
  }
1692
1637
  }
1693
1638
  function isNodeInternal(importee) {
1694
- return importee.startsWith("node:") || import_module4.builtinModules.includes(importee);
1639
+ return importee.startsWith("node:") || import_module2.builtinModules.includes(importee);
1695
1640
  }
1696
1641
  function isBareImport(importee) {
1697
1642
  if (!importee || importee[0] === "." || importee[0] === "\0" || importee.includes(":") || import_path6.default.isAbsolute(importee)) {
@@ -1709,7 +1654,7 @@ function isBareImport(importee) {
1709
1654
  }
1710
1655
 
1711
1656
  // src/utils/optimizer.ts
1712
- var import_fs5 = require("fs");
1657
+ var import_fs4 = require("fs");
1713
1658
  var import_path7 = __toESM(require("path"), 1);
1714
1659
  var PREBUNDLE_SENSITIVE_OPTIONS = [
1715
1660
  "compilerOptions",
@@ -1727,11 +1672,11 @@ async function saveSvelteMetadata(cacheDir, options) {
1727
1672
  });
1728
1673
  let existingSvelteMetadata;
1729
1674
  try {
1730
- existingSvelteMetadata = await import_fs5.promises.readFile(svelteMetadataPath, "utf8");
1675
+ existingSvelteMetadata = await import_fs4.promises.readFile(svelteMetadataPath, "utf8");
1731
1676
  } catch {
1732
1677
  }
1733
- await import_fs5.promises.mkdir(cacheDir, { recursive: true });
1734
- await import_fs5.promises.writeFile(svelteMetadataPath, currentSvelteMetadata);
1678
+ await import_fs4.promises.mkdir(cacheDir, { recursive: true });
1679
+ await import_fs4.promises.writeFile(svelteMetadataPath, currentSvelteMetadata);
1735
1680
  return currentSvelteMetadata !== existingSvelteMetadata;
1736
1681
  }
1737
1682
  function generateSvelteMetadata(options) {
@@ -1746,7 +1691,7 @@ function generateSvelteMetadata(options) {
1746
1691
  var import_vite4 = require("vite");
1747
1692
  var import_path8 = __toESM(require("path"), 1);
1748
1693
  var import_url2 = require("url");
1749
- var import_fs6 = __toESM(require("fs"), 1);
1694
+ var import_fs5 = __toESM(require("fs"), 1);
1750
1695
 
1751
1696
  // src/ui/inspector/utils.ts
1752
1697
  var FS_PREFIX = `/@fs/`;
@@ -1823,8 +1768,8 @@ function svelteInspector() {
1823
1768
  return `export default ${JSON.stringify(inspectorOptions ?? {})}`;
1824
1769
  } else if (id.startsWith(inspectorPath)) {
1825
1770
  const file = idToFile(id);
1826
- if (import_fs6.default.existsSync(file)) {
1827
- 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");
1828
1773
  } else {
1829
1774
  log.error(`failed to find file for svelte-inspector: ${file}, referenced by id ${id}.`);
1830
1775
  }
@@ -1885,7 +1830,7 @@ function svelte(inlineOptions) {
1885
1830
  log.setLevel(config.logLevel);
1886
1831
  }
1887
1832
  options = await preResolveOptions(inlineOptions, config, configEnv);
1888
- const extraViteConfig = buildExtraViteConfig(options, config);
1833
+ const extraViteConfig = await buildExtraViteConfig(options, config);
1889
1834
  log.debug("additional vite config", extraViteConfig);
1890
1835
  return extraViteConfig;
1891
1836
  },
@@ -1924,7 +1869,7 @@ function svelte(inlineOptions) {
1924
1869
  }
1925
1870
  if (viteConfig.assetsInclude(filename)) {
1926
1871
  log.debug(`load returns raw content for ${filename}`);
1927
- return import_fs7.default.readFileSync(filename, "utf-8");
1872
+ return import_fs6.default.readFileSync(filename, "utf-8");
1928
1873
  }
1929
1874
  }
1930
1875
  },
@@ -1957,19 +1902,23 @@ function svelte(inlineOptions) {
1957
1902
  }
1958
1903
  return resolvedSvelteSSR;
1959
1904
  }
1960
- try {
1961
- const resolved = resolveViaPackageJsonSvelte(importee, importer, cache);
1962
- if (resolved) {
1963
- log.debug(
1964
- `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
1965
1920
  );
1966
- return resolved;
1967
1921
  }
1968
- } catch (e) {
1969
- log.debug.once(
1970
- `error trying to resolve ${importee} from ${importer} via package.json svelte field `,
1971
- e
1972
- );
1973
1922
  }
1974
1923
  },
1975
1924
  async transform(code, id, opts) {