@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.js CHANGED
@@ -8,6 +8,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
8
8
 
9
9
  // src/index.ts
10
10
  import fs8 from "fs";
11
+ import { isDepExcluded as isDepExcluded2 } from "vitefu";
11
12
 
12
13
  // src/utils/log.ts
13
14
  import { cyan, yellow, red } from "kleur/colors";
@@ -339,7 +340,8 @@ var _createCompileSvelte = (makeHot) => async function compileSvelte2(svelteRequ
339
340
  ...dynamicCompileOptions
340
341
  } : compileOptions;
341
342
  const compiled = compile(finalCode, finalCompileOptions);
342
- if (emitCss && compiled.css.code) {
343
+ const hasCss = compiled.css?.code?.trim().length > 0;
344
+ if (emitCss && hasCss) {
343
345
  compiled.js.code += `
344
346
  import ${JSON.stringify(cssId)};
345
347
  `;
@@ -348,7 +350,7 @@ import ${JSON.stringify(cssId)};
348
350
  compiled.js.code = makeHot({
349
351
  id: filename,
350
352
  compiledCode: compiled.js.code,
351
- hotOptions: options.hot,
353
+ hotOptions: { ...options.hot, injectCss: options.hot?.injectCss === true && hasCss },
352
354
  compiled,
353
355
  originalCode: code,
354
356
  compileOptions: finalCompileOptions
@@ -461,9 +463,7 @@ function buildIdParser(options) {
461
463
  }
462
464
 
463
465
  // src/utils/options.ts
464
- import {
465
- normalizePath as normalizePath2
466
- } from "vite";
466
+ import { normalizePath as normalizePath2 } from "vite";
467
467
 
468
468
  // src/utils/load-svelte-config.ts
469
469
  import { createRequire } from "module";
@@ -575,181 +575,8 @@ var SVELTE_HMR_IMPORTS = [
575
575
  // src/utils/options.ts
576
576
  import path4 from "path";
577
577
 
578
- // src/utils/dependencies.ts
579
- import path2 from "path";
580
- import fs3 from "fs";
581
- import { createRequire as createRequire2 } from "module";
582
- function findRootSvelteDependencies(root, cwdFallback = true) {
583
- log.debug(`findSvelteDependencies: searching svelte dependencies in ${root}`);
584
- const pkgFile = path2.join(root, "package.json");
585
- if (!fs3.existsSync(pkgFile)) {
586
- if (cwdFallback) {
587
- const cwd = process.cwd();
588
- if (root !== cwd) {
589
- log.debug(`no package.json found in vite root ${root}`);
590
- return findRootSvelteDependencies(cwd, false);
591
- }
592
- }
593
- log.warn(`no package.json found, findRootSvelteDependencies failed`);
594
- return [];
595
- }
596
- const pkg = parsePkg(root);
597
- if (!pkg) {
598
- return [];
599
- }
600
- const deps = [
601
- ...Object.keys(pkg.dependencies || {}),
602
- ...Object.keys(pkg.devDependencies || {})
603
- ].filter((dep) => !is_common_without_svelte_field(dep));
604
- return getSvelteDependencies(deps, root);
605
- }
606
- function getSvelteDependencies(deps, pkgDir, path9 = []) {
607
- const result = [];
608
- const localRequire = createRequire2(`${pkgDir}/package.json`);
609
- const resolvedDeps = deps.map((dep) => resolveDependencyData(dep, localRequire)).filter(Boolean);
610
- for (const { pkg, dir } of resolvedDeps) {
611
- const type = getSvelteDependencyType(pkg);
612
- if (!type)
613
- continue;
614
- result.push({ name: pkg.name, type, pkg, dir, path: path9 });
615
- if (type === "component-library" && pkg.dependencies) {
616
- let dependencyNames = Object.keys(pkg.dependencies);
617
- const circular = dependencyNames.filter((name) => path9.includes(name));
618
- if (circular.length > 0) {
619
- log.warn.enabled && log.warn(
620
- `skipping circular svelte dependencies in automated vite optimizeDeps handling`,
621
- circular.map((x) => path9.concat(x).join(">"))
622
- );
623
- dependencyNames = dependencyNames.filter((name) => !path9.includes(name));
624
- }
625
- if (path9.length === 3) {
626
- log.debug.once(`encountered deep svelte dependency tree: ${path9.join(">")}`);
627
- }
628
- result.push(...getSvelteDependencies(dependencyNames, dir, path9.concat(pkg.name)));
629
- }
630
- }
631
- return result;
632
- }
633
- function resolveDependencyData(dep, localRequire) {
634
- try {
635
- const pkgJson = `${dep}/package.json`;
636
- const pkg = localRequire(pkgJson);
637
- const dir = path2.dirname(localRequire.resolve(pkgJson));
638
- return { dir, pkg };
639
- } catch (e) {
640
- log.debug.once(`dependency ${dep} does not export package.json`, e);
641
- try {
642
- let dir = path2.dirname(localRequire.resolve(dep));
643
- while (dir) {
644
- const pkg = parsePkg(dir, true);
645
- if (pkg && pkg.name === dep) {
646
- return { dir, pkg };
647
- }
648
- const parent = path2.dirname(dir);
649
- if (parent === dir) {
650
- break;
651
- }
652
- dir = parent;
653
- }
654
- } catch (e2) {
655
- log.debug.once(`error while trying to find package.json of ${dep}`, e2);
656
- }
657
- }
658
- log.debug.once(`failed to resolve ${dep}`);
659
- }
660
- function parsePkg(dir, silent = false) {
661
- const pkgFile = path2.join(dir, "package.json");
662
- try {
663
- return JSON.parse(fs3.readFileSync(pkgFile, "utf-8"));
664
- } catch (e) {
665
- !silent && log.warn.enabled && log.warn(`failed to parse ${pkgFile}`, e);
666
- }
667
- }
668
- function getSvelteDependencyType(pkg) {
669
- if (isSvelteComponentLib(pkg)) {
670
- return "component-library";
671
- } else if (isSvelteLib(pkg)) {
672
- return "js-library";
673
- } else {
674
- return void 0;
675
- }
676
- }
677
- function isSvelteComponentLib(pkg) {
678
- return !!pkg.svelte;
679
- }
680
- function isSvelteLib(pkg) {
681
- return !!pkg.dependencies?.svelte || !!pkg.peerDependencies?.svelte;
682
- }
683
- var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
684
- "@lukeed/uuid",
685
- "@playwright/test",
686
- "@sveltejs/vite-plugin-svelte",
687
- "@sveltejs/kit",
688
- "autoprefixer",
689
- "cookie",
690
- "dotenv",
691
- "esbuild",
692
- "eslint",
693
- "jest",
694
- "mdsvex",
695
- "playwright",
696
- "postcss",
697
- "prettier",
698
- "svelte",
699
- "svelte-check",
700
- "svelte-hmr",
701
- "svelte-preprocess",
702
- "tslib",
703
- "typescript",
704
- "vite",
705
- "vitest",
706
- "__vite-browser-external"
707
- ];
708
- var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
709
- "@fontsource/",
710
- "@postcss-plugins/",
711
- "@rollup/",
712
- "@sveltejs/adapter-",
713
- "@types/",
714
- "@typescript-eslint/",
715
- "eslint-",
716
- "jest-",
717
- "postcss-plugin-",
718
- "prettier-plugin-",
719
- "rollup-plugin-",
720
- "vite-plugin-"
721
- ];
722
- function is_common_without_svelte_field(dependency) {
723
- return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
724
- (prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
725
- );
726
- }
727
- function needsOptimization(dep, localRequire) {
728
- const depData = resolveDependencyData(dep, localRequire);
729
- if (!depData)
730
- return false;
731
- const pkg = depData.pkg;
732
- const hasEsmFields = pkg.module || pkg.exports;
733
- if (hasEsmFields)
734
- return false;
735
- if (pkg.main) {
736
- const entryExt = path2.extname(pkg.main);
737
- return !entryExt || entryExt === ".js" || entryExt === ".cjs";
738
- } else {
739
- try {
740
- localRequire.resolve(`${dep}/index.js`);
741
- return true;
742
- } catch {
743
- return false;
744
- }
745
- }
746
- }
747
-
748
- // src/utils/options.ts
749
- import { createRequire as createRequire3 } from "module";
750
-
751
578
  // src/utils/esbuild.ts
752
- import { promises as fs4 } from "fs";
579
+ import { promises as fs3 } from "fs";
753
580
  import { compile as compile2, preprocess as preprocess2 } from "svelte/compiler";
754
581
 
755
582
  // src/utils/error.ts
@@ -805,7 +632,38 @@ function formatFrameForVite(frame) {
805
632
  return frame.split("\n").map((line) => line.match(/^\s+\^/) ? " " + line : " " + line.replace(":", " | ")).join("\n");
806
633
  }
807
634
 
635
+ // src/utils/svelte-version.ts
636
+ import { VERSION } from "svelte/compiler";
637
+ var svelteVersion = parseVersion(VERSION);
638
+ function parseVersion(version) {
639
+ const segments = version.split(".", 3).map((s) => parseInt(s, 10));
640
+ while (segments.length < 3) {
641
+ segments.push(0);
642
+ }
643
+ return segments;
644
+ }
645
+ function compareToSvelte(version) {
646
+ const parsedVersion = parseVersion(version);
647
+ for (let i = 0; i < svelteVersion.length; i++) {
648
+ const a = parsedVersion[i];
649
+ const b = svelteVersion[i];
650
+ if (a === b) {
651
+ continue;
652
+ } else if (a > b) {
653
+ return 1;
654
+ } else {
655
+ return -1;
656
+ }
657
+ }
658
+ return 0;
659
+ }
660
+ function atLeastSvelte(version) {
661
+ const result = compareToSvelte(version) <= 0;
662
+ return result;
663
+ }
664
+
808
665
  // src/utils/esbuild.ts
666
+ var isCssString = atLeastSvelte("3.53.0");
809
667
  var facadeEsbuildSveltePluginName = "vite-plugin-svelte:facade";
810
668
  function esbuildSveltePlugin(options) {
811
669
  return {
@@ -816,7 +674,7 @@ function esbuildSveltePlugin(options) {
816
674
  const svelteExtensions = (options.extensions ?? [".svelte"]).map((ext) => ext.slice(1));
817
675
  const svelteFilter = new RegExp(`\\.(` + svelteExtensions.join("|") + `)(\\?.*)?$`);
818
676
  build.onLoad({ filter: svelteFilter }, async ({ path: filename }) => {
819
- const code = await fs4.readFile(filename, "utf8");
677
+ const code = await fs3.readFile(filename, "utf8");
820
678
  try {
821
679
  const contents = await compileSvelte(options, { filename, code });
822
680
  return { contents };
@@ -828,9 +686,13 @@ function esbuildSveltePlugin(options) {
828
686
  };
829
687
  }
830
688
  async function compileSvelte(options, { filename, code }) {
689
+ let css = options.compilerOptions.css;
690
+ if (css !== "none") {
691
+ css = isCssString ? "injected" : true;
692
+ }
831
693
  const compileOptions = {
832
694
  ...options.compilerOptions,
833
- css: true,
695
+ css,
834
696
  filename,
835
697
  format: "esm",
836
698
  generate: "dom"
@@ -917,7 +779,7 @@ async function buildSourceMap(from, to, filename) {
917
779
  }
918
780
 
919
781
  // src/utils/preprocess.ts
920
- import path3 from "path";
782
+ import path2 from "path";
921
783
  var supportedStyleLangs = ["css", "less", "sass", "scss", "styl", "stylus", "postcss"];
922
784
  var supportedScriptLangs = ["ts"];
923
785
  function createViteScriptPreprocessor() {
@@ -950,7 +812,7 @@ function createViteStylePreprocessor(config) {
950
812
  const moduleId = `${filename}.${lang}`;
951
813
  const result = await transform(content, moduleId);
952
814
  if (result.map?.sources?.[0] === moduleId) {
953
- result.map.sources[0] = path3.basename(filename);
815
+ result.map.sources[0] = path2.basename(filename);
954
816
  }
955
817
  return {
956
818
  code: result.code,
@@ -997,7 +859,7 @@ function createInjectScopeEverythingRulePreprocessorGroup() {
997
859
  return {
998
860
  code: s.toString(),
999
861
  map: s.generateDecodedMap({
1000
- source: filename ? path3.basename(filename) : void 0,
862
+ source: filename ? path2.basename(filename) : void 0,
1001
863
  hires: true
1002
864
  })
1003
865
  };
@@ -1121,6 +983,78 @@ function validateSourceMapOutputWrapper(group, i) {
1121
983
 
1122
984
  // src/utils/options.ts
1123
985
  import deepmerge from "deepmerge";
986
+ import {
987
+ crawlFrameworkPkgs,
988
+ isDepExcluded,
989
+ isDepExternaled,
990
+ isDepIncluded,
991
+ isDepNoExternaled
992
+ } from "vitefu";
993
+
994
+ // src/utils/dependencies.ts
995
+ import path3 from "path";
996
+ import fs4 from "fs/promises";
997
+ import { findDepPkgJsonPath } from "vitefu";
998
+ async function resolveDependencyData(dep, parent) {
999
+ const depDataPath = await findDepPkgJsonPath(dep, parent);
1000
+ if (!depDataPath)
1001
+ return void 0;
1002
+ try {
1003
+ return {
1004
+ dir: path3.dirname(depDataPath),
1005
+ pkg: JSON.parse(await fs4.readFile(depDataPath, "utf-8"))
1006
+ };
1007
+ } catch {
1008
+ return void 0;
1009
+ }
1010
+ }
1011
+ var COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD = [
1012
+ "@lukeed/uuid",
1013
+ "@playwright/test",
1014
+ "@sveltejs/vite-plugin-svelte",
1015
+ "@sveltejs/kit",
1016
+ "autoprefixer",
1017
+ "cookie",
1018
+ "dotenv",
1019
+ "esbuild",
1020
+ "eslint",
1021
+ "jest",
1022
+ "mdsvex",
1023
+ "playwright",
1024
+ "postcss",
1025
+ "prettier",
1026
+ "svelte",
1027
+ "svelte-check",
1028
+ "svelte-hmr",
1029
+ "svelte-preprocess",
1030
+ "tslib",
1031
+ "typescript",
1032
+ "vite",
1033
+ "vitest",
1034
+ "__vite-browser-external"
1035
+ ];
1036
+ var COMMON_PREFIXES_WITHOUT_SVELTE_FIELD = [
1037
+ "@fontsource/",
1038
+ "@postcss-plugins/",
1039
+ "@rollup/",
1040
+ "@sveltejs/adapter-",
1041
+ "@types/",
1042
+ "@typescript-eslint/",
1043
+ "eslint-",
1044
+ "jest-",
1045
+ "postcss-plugin-",
1046
+ "prettier-plugin-",
1047
+ "rollup-plugin-",
1048
+ "vite-plugin-"
1049
+ ];
1050
+ function isCommonDepWithoutSvelteField(dependency) {
1051
+ return COMMON_DEPENDENCIES_WITHOUT_SVELTE_FIELD.includes(dependency) || COMMON_PREFIXES_WITHOUT_SVELTE_FIELD.some(
1052
+ (prefix2) => prefix2.startsWith("@") ? dependency.startsWith(prefix2) : dependency.substring(dependency.lastIndexOf("/") + 1).startsWith(prefix2)
1053
+ );
1054
+ }
1055
+
1056
+ // src/utils/options.ts
1057
+ var cssAsString = atLeastSvelte("3.53.0");
1124
1058
  var allowedPluginOptions = /* @__PURE__ */ new Set([
1125
1059
  "include",
1126
1060
  "exclude",
@@ -1238,13 +1172,14 @@ function mergeConfigs(...configs) {
1238
1172
  return result;
1239
1173
  }
1240
1174
  function resolveOptions(preResolveOptions2, viteConfig) {
1175
+ const css = cssAsString ? preResolveOptions2.emitCss ? "external" : "injected" : !preResolveOptions2.emitCss;
1241
1176
  const defaultOptions = {
1242
1177
  hot: viteConfig.isProduction ? false : {
1243
- injectCss: !preResolveOptions2.emitCss,
1178
+ injectCss: css === true || css === "injected",
1244
1179
  partialAccept: !!viteConfig.experimental?.hmrPartialAccept
1245
1180
  },
1246
1181
  compilerOptions: {
1247
- css: !preResolveOptions2.emitCss,
1182
+ css,
1248
1183
  dev: !viteConfig.isProduction
1249
1184
  }
1250
1185
  };
@@ -1272,11 +1207,13 @@ function enforceOptionsForHmr(options) {
1272
1207
  log.warn("hmr and emitCss are enabled but hot.injectCss is true, forcing it to false");
1273
1208
  options.hot.injectCss = false;
1274
1209
  }
1275
- if (options.compilerOptions.css) {
1210
+ const css = options.compilerOptions.css;
1211
+ if (css === true || css === "injected") {
1212
+ const forcedCss = cssAsString ? "external" : false;
1276
1213
  log.warn(
1277
- "hmr and emitCss are enabled but compilerOptions.css is true, forcing it to false"
1214
+ `hmr and emitCss are enabled but compilerOptions.css is ${css}, forcing it to ${forcedCss}`
1278
1215
  );
1279
- options.compilerOptions.css = false;
1216
+ options.compilerOptions.css = forcedCss;
1280
1217
  }
1281
1218
  } else {
1282
1219
  if (options.hot === true || !options.hot.injectCss) {
@@ -1289,11 +1226,13 @@ function enforceOptionsForHmr(options) {
1289
1226
  options.hot.injectCss = true;
1290
1227
  }
1291
1228
  }
1292
- if (!options.compilerOptions.css) {
1229
+ const css = options.compilerOptions.css;
1230
+ if (!(css === true || css === "injected")) {
1231
+ const forcedCss = cssAsString ? "injected" : true;
1293
1232
  log.warn(
1294
- "hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to true"
1233
+ `hmr with emitCss disabled requires compilerOptions.css to be enabled, forcing it to ${forcedCss}`
1295
1234
  );
1296
- options.compilerOptions.css = true;
1235
+ options.compilerOptions.css = forcedCss;
1297
1236
  }
1298
1237
  }
1299
1238
  }
@@ -1331,16 +1270,9 @@ function removeIgnoredOptions(options) {
1331
1270
  }
1332
1271
  }
1333
1272
  function addSvelteKitOptions(options) {
1334
- if (options?.kit != null) {
1335
- const kit_browser_hydrate = options.kit.browser?.hydrate;
1336
- const hydratable = kit_browser_hydrate !== false;
1337
- if (options.compilerOptions.hydratable != null && options.compilerOptions.hydratable !== hydratable) {
1338
- log.warn(
1339
- `Conflicting values "compilerOptions.hydratable: ${options.compilerOptions.hydratable}" and "kit.browser.hydrate: ${kit_browser_hydrate}" in your svelte config. You should remove "compilerOptions.hydratable".`
1340
- );
1341
- }
1342
- log.debug(`Setting compilerOptions.hydratable: ${hydratable} for SvelteKit`);
1343
- options.compilerOptions.hydratable = hydratable;
1273
+ if (options?.kit != null && options.compilerOptions.hydratable == null) {
1274
+ log.debug(`Setting compilerOptions.hydratable = true for SvelteKit`);
1275
+ options.compilerOptions.hydratable = true;
1344
1276
  }
1345
1277
  }
1346
1278
  function handleDeprecatedOptions(options) {
@@ -1354,100 +1286,118 @@ function handleDeprecatedOptions(options) {
1354
1286
  function resolveViteRoot(viteConfig) {
1355
1287
  return normalizePath2(viteConfig.root ? path4.resolve(viteConfig.root) : process.cwd());
1356
1288
  }
1357
- function buildExtraViteConfig(options, config) {
1358
- const svelteDeps = findRootSvelteDependencies(options.root);
1289
+ async function buildExtraViteConfig(options, config) {
1359
1290
  const extraViteConfig = {
1360
1291
  resolve: {
1361
1292
  mainFields: [...SVELTE_RESOLVE_MAIN_FIELDS],
1362
1293
  dedupe: [...SVELTE_IMPORTS, ...SVELTE_HMR_IMPORTS]
1363
1294
  }
1364
1295
  };
1365
- extraViteConfig.optimizeDeps = buildOptimizeDepsForSvelte(
1366
- svelteDeps,
1367
- options,
1368
- config.optimizeDeps
1369
- );
1296
+ const extraSvelteConfig = buildExtraConfigForSvelte(config);
1297
+ const extraDepsConfig = await buildExtraConfigForDependencies(options, config);
1298
+ extraViteConfig.optimizeDeps = {
1299
+ include: [
1300
+ ...extraSvelteConfig.optimizeDeps.include,
1301
+ ...extraDepsConfig.optimizeDeps.include.filter(
1302
+ (dep) => !isDepExcluded(dep, extraSvelteConfig.optimizeDeps.exclude)
1303
+ )
1304
+ ],
1305
+ exclude: [
1306
+ ...extraSvelteConfig.optimizeDeps.exclude,
1307
+ ...extraDepsConfig.optimizeDeps.exclude.filter(
1308
+ (dep) => !isDepIncluded(dep, extraSvelteConfig.optimizeDeps.include)
1309
+ )
1310
+ ]
1311
+ };
1312
+ extraViteConfig.ssr = {
1313
+ external: [
1314
+ ...extraSvelteConfig.ssr.external,
1315
+ ...extraDepsConfig.ssr.external.filter(
1316
+ (dep) => !isDepNoExternaled(dep, extraSvelteConfig.ssr.noExternal)
1317
+ )
1318
+ ],
1319
+ noExternal: [
1320
+ ...extraSvelteConfig.ssr.noExternal,
1321
+ ...extraDepsConfig.ssr.noExternal.filter(
1322
+ (dep) => !isDepExternaled(dep, extraSvelteConfig.ssr.external)
1323
+ )
1324
+ ]
1325
+ };
1370
1326
  if (options.prebundleSvelteLibraries) {
1371
- extraViteConfig.optimizeDeps = {
1372
- ...extraViteConfig.optimizeDeps,
1373
- extensions: options.extensions ?? [".svelte"],
1374
- esbuildOptions: {
1375
- plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1376
- } }]
1377
- }
1327
+ extraViteConfig.optimizeDeps.extensions = options.extensions ?? [".svelte"];
1328
+ extraViteConfig.optimizeDeps.esbuildOptions = {
1329
+ plugins: [{ name: facadeEsbuildSveltePluginName, setup: () => {
1330
+ } }]
1378
1331
  };
1379
1332
  }
1380
- extraViteConfig.ssr = buildSSROptionsForSvelte(svelteDeps, options, config, extraViteConfig);
1381
1333
  if ((options.hot == null || options.hot === true || options.hot && options.hot.partialAccept !== false) && config.experimental?.hmrPartialAccept !== false) {
1382
1334
  log.debug('enabling "experimental.hmrPartialAccept" in vite config');
1383
1335
  extraViteConfig.experimental = { hmrPartialAccept: true };
1384
1336
  }
1385
1337
  return extraViteConfig;
1386
1338
  }
1387
- function buildOptimizeDepsForSvelte(svelteDeps, options, optimizeDeps) {
1339
+ async function buildExtraConfigForDependencies(options, config) {
1340
+ const depsConfig = await crawlFrameworkPkgs({
1341
+ root: options.root,
1342
+ isBuild: options.isBuild,
1343
+ viteUserConfig: config,
1344
+ isFrameworkPkgByJson(pkgJson) {
1345
+ return !!pkgJson.svelte;
1346
+ },
1347
+ isSemiFrameworkPkgByJson(pkgJson) {
1348
+ return !!pkgJson.dependencies?.svelte || !!pkgJson.peerDependencies?.svelte;
1349
+ },
1350
+ isFrameworkPkgByName(pkgName) {
1351
+ const isNotSveltePackage = isCommonDepWithoutSvelteField(pkgName);
1352
+ if (isNotSveltePackage) {
1353
+ return false;
1354
+ } else {
1355
+ return void 0;
1356
+ }
1357
+ }
1358
+ });
1359
+ log.debug("extra config for dependencies generated by vitefu", depsConfig);
1360
+ if (options.prebundleSvelteLibraries) {
1361
+ depsConfig.optimizeDeps.exclude = [];
1362
+ const userExclude = config.optimizeDeps?.exclude;
1363
+ depsConfig.optimizeDeps.include = !userExclude ? [] : depsConfig.optimizeDeps.include.filter((dep) => {
1364
+ return dep.includes(">") && dep.split(">").slice(0, -1).some((d) => isDepExcluded(d.trim(), userExclude));
1365
+ });
1366
+ }
1367
+ if (options.disableDependencyReinclusion === true) {
1368
+ depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter(
1369
+ (dep) => !dep.includes(">")
1370
+ );
1371
+ } else if (Array.isArray(options.disableDependencyReinclusion)) {
1372
+ const disabledDeps = options.disableDependencyReinclusion;
1373
+ depsConfig.optimizeDeps.include = depsConfig.optimizeDeps.include.filter((dep) => {
1374
+ if (!dep.includes(">"))
1375
+ return true;
1376
+ const trimDep = dep.replace(/\s+/g, "");
1377
+ return disabledDeps.some((disabled) => trimDep.includes(`${disabled}>`));
1378
+ });
1379
+ }
1380
+ log.debug("post-processed extra config for dependencies", depsConfig);
1381
+ return depsConfig;
1382
+ }
1383
+ function buildExtraConfigForSvelte(config) {
1388
1384
  const include = [];
1389
1385
  const exclude = ["svelte-hmr"];
1390
- const isIncluded = (dep) => include.includes(dep) || optimizeDeps?.include?.includes(dep);
1391
- const isExcluded = (dep) => {
1392
- return exclude.includes(dep) || optimizeDeps?.exclude?.some((id) => dep === id || id.startsWith(`${dep}/`));
1393
- };
1394
- if (!isExcluded("svelte")) {
1386
+ if (!isDepExcluded("svelte", config.optimizeDeps?.exclude ?? [])) {
1395
1387
  const svelteImportsToInclude = SVELTE_IMPORTS.filter((x) => x !== "svelte/ssr");
1396
1388
  log.debug(
1397
1389
  `adding bare svelte packages to optimizeDeps.include: ${svelteImportsToInclude.join(", ")} `
1398
1390
  );
1399
- include.push(...svelteImportsToInclude.filter((x) => !isIncluded(x)));
1391
+ include.push(...svelteImportsToInclude);
1400
1392
  } else {
1401
1393
  log.debug('"svelte" is excluded in optimizeDeps.exclude, skipped adding it to include.');
1402
1394
  }
1403
- if (options.prebundleSvelteLibraries) {
1404
- return { include, exclude };
1405
- }
1406
- svelteDeps = svelteDeps.filter((dep) => dep.type === "component-library");
1407
- const svelteDepsToExclude = Array.from(new Set(svelteDeps.map((dep) => dep.name))).filter(
1408
- (dep) => !isIncluded(dep)
1409
- );
1410
- log.debug(`automatically excluding found svelte dependencies: ${svelteDepsToExclude.join(", ")}`);
1411
- exclude.push(...svelteDepsToExclude.filter((x) => !isExcluded(x)));
1412
- if (options.disableDependencyReinclusion !== true) {
1413
- const disabledReinclusions = options.disableDependencyReinclusion || [];
1414
- if (disabledReinclusions.length > 0) {
1415
- log.debug(`not reincluding transitive dependencies of`, disabledReinclusions);
1416
- }
1417
- const transitiveDepsToInclude = svelteDeps.filter((dep) => !disabledReinclusions.includes(dep.name) && isExcluded(dep.name)).flatMap((dep) => {
1418
- const localRequire = createRequire3(`${dep.dir}/package.json`);
1419
- return Object.keys(dep.pkg.dependencies || {}).filter((depOfDep) => !isExcluded(depOfDep) && needsOptimization(depOfDep, localRequire)).map((depOfDep) => dep.path.concat(dep.name, depOfDep).join(" > "));
1420
- });
1421
- log.debug(
1422
- `reincluding transitive dependencies of excluded svelte dependencies`,
1423
- transitiveDepsToInclude
1424
- );
1425
- include.push(...transitiveDepsToInclude);
1426
- }
1427
- return { include, exclude };
1428
- }
1429
- function buildSSROptionsForSvelte(svelteDeps, options, config) {
1430
1395
  const noExternal = [];
1431
- if (!config.ssr?.external?.includes("svelte")) {
1396
+ const external = [];
1397
+ if (!isDepExternaled("svelte", config.ssr?.external ?? [])) {
1432
1398
  noExternal.push("svelte", /^svelte\//);
1433
1399
  }
1434
- noExternal.push(
1435
- ...Array.from(new Set(svelteDeps.map((s) => s.name))).filter(
1436
- (x) => !config.ssr?.external?.includes(x)
1437
- )
1438
- );
1439
- const ssr = {
1440
- noExternal,
1441
- external: []
1442
- };
1443
- if (options.isServe) {
1444
- ssr.external = Array.from(
1445
- new Set(svelteDeps.flatMap((dep) => Object.keys(dep.pkg.dependencies || {})))
1446
- ).filter(
1447
- (dep) => !ssr.noExternal.includes(dep) && !config.ssr?.external?.includes(dep)
1448
- );
1449
- }
1450
- return ssr;
1400
+ return { optimizeDeps: { include, exclude }, ssr: { noExternal, external } };
1451
1401
  }
1452
1402
  function patchResolvedViteConfig(viteConfig, options) {
1453
1403
  const facadeEsbuildSveltePlugin = viteConfig.optimizeDeps.esbuildOptions?.plugins?.find(
@@ -1644,15 +1594,14 @@ function ensureWatchedFile(watcher, file, root) {
1644
1594
 
1645
1595
  // src/utils/resolve.ts
1646
1596
  import path6 from "path";
1647
- import { builtinModules, createRequire as createRequire4 } from "module";
1648
- function resolveViaPackageJsonSvelte(importee, importer, cache) {
1649
- if (importer && isBareImport(importee) && !isNodeInternal(importee) && !is_common_without_svelte_field(importee)) {
1597
+ import { builtinModules } from "module";
1598
+ async function resolveViaPackageJsonSvelte(importee, importer, cache) {
1599
+ if (importer && isBareImport(importee) && !isNodeInternal(importee) && !isCommonDepWithoutSvelteField(importee)) {
1650
1600
  const cached = cache.getResolvedSvelteField(importee, importer);
1651
1601
  if (cached) {
1652
1602
  return cached;
1653
1603
  }
1654
- const localRequire = createRequire4(importer);
1655
- const pkgData = resolveDependencyData(importee, localRequire);
1604
+ const pkgData = await resolveDependencyData(importee, importer);
1656
1605
  if (pkgData) {
1657
1606
  const { pkg, dir } = pkgData;
1658
1607
  if (pkg.svelte) {
@@ -1858,7 +1807,7 @@ function svelte(inlineOptions) {
1858
1807
  log.setLevel(config.logLevel);
1859
1808
  }
1860
1809
  options = await preResolveOptions(inlineOptions, config, configEnv);
1861
- const extraViteConfig = buildExtraViteConfig(options, config);
1810
+ const extraViteConfig = await buildExtraViteConfig(options, config);
1862
1811
  log.debug("additional vite config", extraViteConfig);
1863
1812
  return extraViteConfig;
1864
1813
  },
@@ -1930,19 +1879,23 @@ function svelte(inlineOptions) {
1930
1879
  }
1931
1880
  return resolvedSvelteSSR;
1932
1881
  }
1933
- try {
1934
- const resolved = resolveViaPackageJsonSvelte(importee, importer, cache);
1935
- if (resolved) {
1936
- log.debug(
1937
- `resolveId resolved ${resolved} via package.json svelte field of ${importee}`
1882
+ const scan = !!opts?.scan;
1883
+ const isPrebundled = options.prebundleSvelteLibraries && viteConfig.optimizeDeps?.disabled !== true && viteConfig.optimizeDeps?.disabled !== (options.isBuild ? "build" : "dev") && !isDepExcluded2(importee, viteConfig.optimizeDeps?.exclude ?? []);
1884
+ if (ssr || scan || !isPrebundled) {
1885
+ try {
1886
+ const resolved = await resolveViaPackageJsonSvelte(importee, importer, cache);
1887
+ if (resolved) {
1888
+ log.debug(
1889
+ `resolveId resolved ${resolved} via package.json svelte field of ${importee}`
1890
+ );
1891
+ return resolved;
1892
+ }
1893
+ } catch (e) {
1894
+ log.debug.once(
1895
+ `error trying to resolve ${importee} from ${importer} via package.json svelte field `,
1896
+ e
1938
1897
  );
1939
- return resolved;
1940
1898
  }
1941
- } catch (e) {
1942
- log.debug.once(
1943
- `error trying to resolve ${importee} from ${importer} via package.json svelte field `,
1944
- e
1945
- );
1946
1899
  }
1947
1900
  },
1948
1901
  async transform(code, id, opts) {