weapp-vite 5.6.3 → 5.7.1

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.
@@ -649,11 +649,6 @@ var require_eventemitter3 = __commonJS({
649
649
  }
650
650
  });
651
651
 
652
- // src/logger.ts
653
- init_esm_shims();
654
- import logger from "@weapp-core/logger";
655
- var logger_default = logger;
656
-
657
652
  // src/constants.ts
658
653
  init_esm_shims();
659
654
  var VERSION = "__VERSION__";
@@ -672,6 +667,13 @@ var templateExtensions = ["wxml", "html"];
672
667
  init_esm_shims();
673
668
  var import_gte = __toESM(require_gte(), 1);
674
669
  import process2 from "process";
670
+
671
+ // src/logger.ts
672
+ init_esm_shims();
673
+ import logger from "@weapp-core/logger";
674
+ var logger_default = logger;
675
+
676
+ // src/utils/version.ts
675
677
  function getRuntime() {
676
678
  if (typeof process2 !== "undefined" && process2.versions?.node) {
677
679
  return {
@@ -706,55 +708,13 @@ function checkRuntime(minVersions) {
706
708
  }
707
709
  }
708
710
 
709
- // src/utils/weappConfig.ts
710
- init_esm_shims();
711
- import fs from "fs-extra";
712
- import path from "pathe";
713
- var WEAPP_VITE_CONFIG_CANDIDATES = [
714
- "weapp-vite.config.ts",
715
- "weapp-vite.config.mts",
716
- "weapp-vite.config.cts",
717
- "weapp-vite.config.js",
718
- "weapp-vite.config.mjs",
719
- "weapp-vite.config.cjs",
720
- "weapp-vite.config.json"
721
- ];
722
- var WEAPP_VITE_CONFIG_SET = new Set(WEAPP_VITE_CONFIG_CANDIDATES);
723
- async function findWeappConfigInDirectory(directory) {
724
- for (const filename of WEAPP_VITE_CONFIG_CANDIDATES) {
725
- const candidatePath = path.resolve(directory, filename);
726
- if (await fs.pathExists(candidatePath)) {
727
- return candidatePath;
728
- }
729
- }
730
- return void 0;
731
- }
732
- async function resolveWeappConfigFile(options) {
733
- const { root, specified } = options;
734
- if (specified) {
735
- const resolvedSpecified = path.isAbsolute(specified) ? specified : path.resolve(root, specified);
736
- const specifiedBaseName = path.basename(resolvedSpecified);
737
- if (WEAPP_VITE_CONFIG_SET.has(specifiedBaseName)) {
738
- if (await fs.pathExists(resolvedSpecified)) {
739
- return resolvedSpecified;
740
- }
741
- return void 0;
742
- }
743
- const fromSpecifiedDirectory = await findWeappConfigInDirectory(path.dirname(resolvedSpecified));
744
- if (fromSpecifiedDirectory) {
745
- return fromSpecifiedDirectory;
746
- }
747
- }
748
- return findWeappConfigInDirectory(root);
749
- }
750
-
751
711
  // src/utils/index.ts
752
712
  init_esm_shims();
753
713
 
754
714
  // src/utils/file.ts
755
715
  init_esm_shims();
756
- import fs2 from "fs-extra";
757
- import path2 from "pathe";
716
+ import fs from "fs-extra";
717
+ import path from "pathe";
758
718
  function isJsOrTs(name) {
759
719
  if (typeof name === "string") {
760
720
  return /\.[jt]s$/.test(name);
@@ -775,13 +735,13 @@ function changeFileExtension(filePath, extension) {
775
735
  return "";
776
736
  }
777
737
  extension = extension ? extension.startsWith(".") ? extension : `.${extension}` : "";
778
- const basename4 = path2.basename(filePath, path2.extname(filePath));
779
- return path2.join(path2.dirname(filePath), basename4 + extension);
738
+ const basename4 = path.basename(filePath, path.extname(filePath));
739
+ return path.join(path.dirname(filePath), basename4 + extension);
780
740
  }
781
741
  async function findVueEntry(filepath) {
782
742
  for (const ext2 of vueExtensions) {
783
743
  const p = changeFileExtension(filepath, ext2);
784
- if (await fs2.exists(p)) {
744
+ if (await fs.exists(p)) {
785
745
  return p;
786
746
  }
787
747
  }
@@ -791,7 +751,7 @@ async function findJsEntry(filepath) {
791
751
  return changeFileExtension(filepath, ext2);
792
752
  });
793
753
  for (const p of predictions) {
794
- if (await fs2.exists(p)) {
754
+ if (await fs.exists(p)) {
795
755
  return {
796
756
  path: p,
797
757
  predictions
@@ -807,7 +767,7 @@ async function findJsonEntry(filepath) {
807
767
  return changeFileExtension(filepath, ext2);
808
768
  });
809
769
  for (const p of predictions) {
810
- if (await fs2.exists(p)) {
770
+ if (await fs.exists(p)) {
811
771
  return {
812
772
  predictions,
813
773
  path: p
@@ -823,7 +783,7 @@ async function findCssEntry(filepath) {
823
783
  return changeFileExtension(filepath, ext2);
824
784
  });
825
785
  for (const p of predictions) {
826
- if (await fs2.exists(p)) {
786
+ if (await fs.exists(p)) {
827
787
  return {
828
788
  predictions,
829
789
  path: p
@@ -839,7 +799,7 @@ async function findTemplateEntry(filepath) {
839
799
  return changeFileExtension(filepath, ext2);
840
800
  });
841
801
  for (const p of predictions) {
842
- if (await fs2.exists(p)) {
802
+ if (await fs.exists(p)) {
843
803
  return {
844
804
  predictions,
845
805
  path: p
@@ -856,9 +816,9 @@ function isTemplate(filepath) {
856
816
  async function touch(filename) {
857
817
  const time = /* @__PURE__ */ new Date();
858
818
  try {
859
- await fs2.utimes(filename, time, time);
819
+ await fs.utimes(filename, time, time);
860
820
  } catch {
861
- await fs2.close(await fs2.open(filename, "w"));
821
+ await fs.close(await fs.open(filename, "w"));
862
822
  }
863
823
  }
864
824
 
@@ -866,7 +826,7 @@ async function touch(filename) {
866
826
  init_esm_shims();
867
827
  import { get, isObject, set } from "@weapp-core/shared";
868
828
  import { parse as parseJson, stringify } from "comment-json";
869
- import path3 from "pathe";
829
+ import path2 from "pathe";
870
830
  function jsonFileRemoveJsExtension(fileName) {
871
831
  return fileName.replace(/\.[jt]s$/, "");
872
832
  }
@@ -911,7 +871,7 @@ function resolveImportee(importee, jsonPath, aliasEntries) {
911
871
  return importee;
912
872
  }
913
873
  const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
914
- return path3.relative(path3.dirname(jsonPath), updatedId);
874
+ return path2.relative(path2.dirname(jsonPath), updatedId);
915
875
  }
916
876
  return importee;
917
877
  }
@@ -954,16 +914,16 @@ import crypto from "crypto";
954
914
 
955
915
  // src/utils/projectConfig.ts
956
916
  init_esm_shims();
957
- import fs3 from "fs-extra";
958
- import path4 from "pathe";
917
+ import fs2 from "fs-extra";
918
+ import path3 from "pathe";
959
919
  async function getProjectConfig(root, options) {
960
- const baseJsonPath = path4.resolve(root, "project.config.json");
961
- const privateJsonPath = path4.resolve(root, "project.private.config.json");
920
+ const baseJsonPath = path3.resolve(root, "project.config.json");
921
+ const privateJsonPath = path3.resolve(root, "project.private.config.json");
962
922
  let baseJson = {};
963
923
  let privateJson = {};
964
- if (await fs3.exists(baseJsonPath)) {
924
+ if (await fs2.exists(baseJsonPath)) {
965
925
  try {
966
- baseJson = await fs3.readJson(baseJsonPath) || {};
926
+ baseJson = await fs2.readJson(baseJsonPath) || {};
967
927
  } catch {
968
928
  throw new Error(`\u89E3\u6790 json \u683C\u5F0F\u5931\u8D25, project.config.json \u4E3A\u975E\u6CD5\u7684 json \u683C\u5F0F`);
969
929
  }
@@ -971,9 +931,9 @@ async function getProjectConfig(root, options) {
971
931
  throw new Error(`\u5728 ${root} \u76EE\u5F55\u4E0B\u627E\u4E0D\u5230 project.config.json`);
972
932
  }
973
933
  if (!options?.ignorePrivate) {
974
- if (await fs3.exists(privateJsonPath)) {
934
+ if (await fs2.exists(privateJsonPath)) {
975
935
  try {
976
- privateJson = await fs3.readJson(privateJsonPath) || {};
936
+ privateJson = await fs2.readJson(privateJsonPath) || {};
977
937
  } catch {
978
938
  throw new Error(`\u89E3\u6790 json \u683C\u5F0F\u5931\u8D25, project.private.config.json \u4E3A\u975E\u6CD5\u7684 json \u683C\u5F0F`);
979
939
  }
@@ -1014,121 +974,46 @@ function regExpTest(arr, str, options) {
1014
974
  return false;
1015
975
  }
1016
976
 
1017
- // src/platform.ts
1018
- init_esm_shims();
1019
-
1020
- // src/platforms/adapters.ts
977
+ // src/utils/weappConfig.ts
1021
978
  init_esm_shims();
1022
- var MINI_PROGRAM_PLATFORM_ADAPTERS = [
1023
- {
1024
- id: "weapp",
1025
- displayName: "WeChat Mini Program",
1026
- aliases: ["weapp", "wechat", "weixin", "wx"],
1027
- outputExtensions: {
1028
- js: "js",
1029
- json: "json",
1030
- wxml: "wxml",
1031
- wxss: "wxss",
1032
- wxs: "wxs"
1033
- }
1034
- },
1035
- {
1036
- id: "alipay",
1037
- displayName: "Alipay Mini Program",
1038
- aliases: ["alipay", "ali", "my"],
1039
- outputExtensions: {
1040
- js: "js",
1041
- json: "json",
1042
- wxml: "axml",
1043
- wxss: "acss",
1044
- wxs: "sjs"
1045
- }
1046
- },
1047
- {
1048
- id: "swan",
1049
- displayName: "Baidu Smart Program",
1050
- aliases: ["swan", "baidu", "bd"],
1051
- outputExtensions: {
1052
- js: "js",
1053
- json: "json",
1054
- wxml: "swan",
1055
- wxss: "css",
1056
- wxs: "sjs"
1057
- }
1058
- },
1059
- {
1060
- id: "tt",
1061
- displayName: "ByteDance / Douyin Mini Program",
1062
- aliases: ["tt", "toutiao", "bytedance", "douyin"],
1063
- outputExtensions: {
1064
- js: "js",
1065
- json: "json",
1066
- wxml: "ttml",
1067
- wxss: "ttss"
1068
- }
1069
- },
1070
- {
1071
- id: "jd",
1072
- displayName: "JD Mini Program",
1073
- aliases: ["jd", "jingdong"],
1074
- outputExtensions: {
1075
- js: "js",
1076
- json: "json",
1077
- wxml: "jxml",
1078
- wxss: "jxss",
1079
- wxs: "wxs"
1080
- }
1081
- },
1082
- {
1083
- id: "xhs",
1084
- displayName: "Xiaohongshu Mini Program",
1085
- aliases: ["xhs", "xiaohongshu", "little-red-book", "red"],
1086
- outputExtensions: {
1087
- js: "js",
1088
- json: "json",
1089
- wxml: "xhsml",
1090
- wxss: "css",
1091
- wxs: "wxs"
1092
- }
1093
- }
979
+ import fs3 from "fs-extra";
980
+ import path4 from "pathe";
981
+ var WEAPP_VITE_CONFIG_CANDIDATES = [
982
+ "weapp-vite.config.ts",
983
+ "weapp-vite.config.mts",
984
+ "weapp-vite.config.cts",
985
+ "weapp-vite.config.js",
986
+ "weapp-vite.config.mjs",
987
+ "weapp-vite.config.cjs",
988
+ "weapp-vite.config.json"
1094
989
  ];
1095
-
1096
- // src/platform.ts
1097
- var DEFAULT_MP_PLATFORM = "weapp";
1098
- var PLATFORM_ADAPTER_BY_ID = /* @__PURE__ */ new Map();
1099
- var PLATFORM_ALIAS_TO_ID = /* @__PURE__ */ new Map();
1100
- for (const adapter of MINI_PROGRAM_PLATFORM_ADAPTERS) {
1101
- PLATFORM_ADAPTER_BY_ID.set(adapter.id, adapter);
1102
- for (const alias of adapter.aliases) {
1103
- const normalized = alias.trim().toLowerCase();
1104
- if (!normalized) {
1105
- continue;
990
+ var WEAPP_VITE_CONFIG_SET = new Set(WEAPP_VITE_CONFIG_CANDIDATES);
991
+ async function findWeappConfigInDirectory(directory) {
992
+ for (const filename of WEAPP_VITE_CONFIG_CANDIDATES) {
993
+ const candidatePath = path4.resolve(directory, filename);
994
+ if (await fs3.pathExists(candidatePath)) {
995
+ return candidatePath;
1106
996
  }
1107
- PLATFORM_ALIAS_TO_ID.set(normalized, adapter.id);
1108
- }
1109
- if (!PLATFORM_ALIAS_TO_ID.has(adapter.id)) {
1110
- PLATFORM_ALIAS_TO_ID.set(adapter.id, adapter.id);
1111
- }
1112
- }
1113
- var MINI_PLATFORM_ALIASES = Object.freeze(
1114
- Object.fromEntries(PLATFORM_ALIAS_TO_ID.entries())
1115
- );
1116
- function normalizeMiniPlatform(input) {
1117
- return input ? input.trim().toLowerCase() : void 0;
1118
- }
1119
- function resolveMiniPlatform(input) {
1120
- const normalized = normalizeMiniPlatform(input);
1121
- if (!normalized) {
1122
- return void 0;
1123
997
  }
1124
- return PLATFORM_ALIAS_TO_ID.get(normalized);
998
+ return void 0;
1125
999
  }
1126
- function getMiniProgramPlatformAdapter(platform) {
1127
- const adapter = PLATFORM_ADAPTER_BY_ID.get(platform);
1128
- if (!adapter) {
1129
- throw new Error(`Unsupported mini program platform "${platform}".`);
1000
+ async function resolveWeappConfigFile(options) {
1001
+ const { root, specified } = options;
1002
+ if (specified) {
1003
+ const resolvedSpecified = path4.isAbsolute(specified) ? specified : path4.resolve(root, specified);
1004
+ const specifiedBaseName = path4.basename(resolvedSpecified);
1005
+ if (WEAPP_VITE_CONFIG_SET.has(specifiedBaseName)) {
1006
+ if (await fs3.pathExists(resolvedSpecified)) {
1007
+ return resolvedSpecified;
1008
+ }
1009
+ return void 0;
1010
+ }
1011
+ const fromSpecifiedDirectory = await findWeappConfigInDirectory(path4.dirname(resolvedSpecified));
1012
+ if (fromSpecifiedDirectory) {
1013
+ return fromSpecifiedDirectory;
1014
+ }
1130
1015
  }
1131
- return adapter;
1016
+ return findWeappConfigInDirectory(root);
1132
1017
  }
1133
1018
 
1134
1019
  // src/context/getInstance.ts
@@ -11894,31 +11779,170 @@ rimraf.rimraf = rimraf;
11894
11779
  // src/runtime/buildPlugin.ts
11895
11780
  import { build } from "vite";
11896
11781
 
11782
+ // src/runtime/independentError.ts
11783
+ init_esm_shims();
11784
+ var ANSI_ESCAPE_PATTERN = /\u001B\[[0-9;]*m/g;
11785
+ function stripAnsi(value) {
11786
+ return value.replace(ANSI_ESCAPE_PATTERN, "");
11787
+ }
11788
+ function isErrorInstance(value) {
11789
+ return value instanceof Error;
11790
+ }
11791
+ function formatSummary(payload) {
11792
+ const parts = [];
11793
+ const code = payload.code;
11794
+ if (typeof code === "string" && code.trim()) {
11795
+ parts.push(`code: ${code.trim()}`);
11796
+ }
11797
+ const plugin = payload.plugin;
11798
+ if (typeof plugin === "string" && plugin.trim()) {
11799
+ parts.push(`plugin: ${plugin.trim()}`);
11800
+ }
11801
+ const id = payload.id;
11802
+ if (typeof id === "string" && id.trim()) {
11803
+ parts.push(`id: ${id.trim()}`);
11804
+ }
11805
+ if (!parts.length) {
11806
+ return "";
11807
+ }
11808
+ return ` (${parts.join(", ")})`;
11809
+ }
11810
+ function collectDetails(payload) {
11811
+ const details = [];
11812
+ const frame = payload.frame;
11813
+ if (typeof frame === "string" && frame.trim()) {
11814
+ details.push(frame.trim());
11815
+ }
11816
+ const stack = payload.stack;
11817
+ if (typeof stack === "string" && stack.trim()) {
11818
+ details.push(stack.trim());
11819
+ }
11820
+ return details;
11821
+ }
11822
+ function extractMessage(value, seen) {
11823
+ if (!value || seen.has(value)) {
11824
+ return void 0;
11825
+ }
11826
+ if (typeof value === "string") {
11827
+ const trimmed = stripAnsi(value).trim();
11828
+ return trimmed || void 0;
11829
+ }
11830
+ if (isErrorInstance(value)) {
11831
+ const trimmed = stripAnsi(value.message ?? "").trim();
11832
+ if (trimmed) {
11833
+ return trimmed;
11834
+ }
11835
+ if (value.cause) {
11836
+ return extractMessage(value.cause, seen);
11837
+ }
11838
+ return void 0;
11839
+ }
11840
+ if (typeof value === "object") {
11841
+ const record = value;
11842
+ seen.add(record);
11843
+ const directMessage = extractMessage(record.message, seen);
11844
+ if (directMessage) {
11845
+ return directMessage;
11846
+ }
11847
+ const nestedKeys = ["reason", "detail", "details", "error", "field0", "field1", "cause"];
11848
+ for (const key of nestedKeys) {
11849
+ if (key in record) {
11850
+ const nestedMessage = extractMessage(record[key], seen);
11851
+ if (nestedMessage) {
11852
+ return nestedMessage;
11853
+ }
11854
+ }
11855
+ }
11856
+ }
11857
+ return void 0;
11858
+ }
11859
+ function createIndependentBuildError(root, cause) {
11860
+ const fallback = `Independent bundle for ${root} failed`;
11861
+ if (isErrorInstance(cause)) {
11862
+ if (!cause.message || cause.message.trim() === "") {
11863
+ return new Error(fallback, { cause });
11864
+ }
11865
+ return cause;
11866
+ }
11867
+ if (!cause) {
11868
+ return new Error(fallback);
11869
+ }
11870
+ if (typeof cause === "string") {
11871
+ const trimmed = stripAnsi(cause).trim();
11872
+ if (!trimmed) {
11873
+ return new Error(fallback, { cause });
11874
+ }
11875
+ return new Error(trimmed, { cause });
11876
+ }
11877
+ if (typeof cause === "object") {
11878
+ const payload = cause;
11879
+ const seen = /* @__PURE__ */ new Set();
11880
+ const extracted = extractMessage(payload, seen);
11881
+ const summary = formatSummary(payload);
11882
+ const detailLines = collectDetails(payload);
11883
+ if (extracted) {
11884
+ let composedMessage = extracted;
11885
+ if (summary) {
11886
+ composedMessage += summary;
11887
+ }
11888
+ if (detailLines.length) {
11889
+ composedMessage += `
11890
+ ${detailLines.join("\n")}`;
11891
+ }
11892
+ return new Error(composedMessage, { cause });
11893
+ }
11894
+ if (summary || detailLines.length) {
11895
+ const composed = detailLines.length ? `${fallback}${summary}
11896
+ ${detailLines.join("\n")}` : `${fallback}${summary}`;
11897
+ if (composed.trim()) {
11898
+ return new Error(composed, { cause });
11899
+ }
11900
+ }
11901
+ }
11902
+ try {
11903
+ const serialized = JSON.stringify(cause);
11904
+ if (serialized && serialized !== "{}") {
11905
+ return new Error(`${fallback}: ${serialized}`, { cause });
11906
+ }
11907
+ } catch {
11908
+ }
11909
+ return new Error(fallback, { cause });
11910
+ }
11911
+
11912
+ // src/runtime/sharedBuildConfig.ts
11913
+ init_esm_shims();
11914
+ import picomatch from "picomatch";
11915
+
11897
11916
  // src/runtime/advancedChunks.ts
11898
11917
  init_esm_shims();
11899
11918
 
11900
11919
  // src/runtime/chunkStrategy.ts
11901
11920
  init_esm_shims();
11921
+ import { Buffer as Buffer2 } from "buffer";
11902
11922
  import { posix as path10 } from "pathe";
11903
11923
  var SHARED_CHUNK_VIRTUAL_PREFIX = "weapp_shared_virtual";
11904
11924
  var SUB_PACKAGE_SHARED_DIR = "weapp-shared";
11905
11925
  var DEFAULT_SHARED_CHUNK_STRATEGY = "duplicate";
11926
+ var sharedChunkDiagnostics = /* @__PURE__ */ new Map();
11906
11927
  function resolveSharedChunkName(options) {
11907
11928
  const {
11908
11929
  id,
11909
11930
  ctx,
11910
11931
  relativeAbsoluteSrcRoot,
11911
11932
  subPackageRoots,
11912
- strategy
11933
+ strategy,
11934
+ forceDuplicateTester
11913
11935
  } = options;
11914
11936
  const moduleInfo = ctx.getModuleInfo(id);
11915
11937
  if (!moduleInfo?.importers || moduleInfo.importers.length <= 1) {
11916
11938
  return void 0;
11917
11939
  }
11918
- const summary = summarizeImportPrefixes({
11940
+ const { summary, ignoredMainImporters } = summarizeImportPrefixes({
11941
+ ctx,
11919
11942
  importers: moduleInfo.importers,
11920
11943
  relativeAbsoluteSrcRoot,
11921
- subPackageRoots: Array.from(subPackageRoots)
11944
+ subPackageRoots: Array.from(subPackageRoots),
11945
+ forceDuplicateTester
11922
11946
  });
11923
11947
  const keys = Object.keys(summary);
11924
11948
  if (keys.length === 0) {
@@ -11932,19 +11956,145 @@ function resolveSharedChunkName(options) {
11932
11956
  if (strategy === "duplicate" && !hasMainImporter) {
11933
11957
  const combination = keys.filter(Boolean).sort().join("+");
11934
11958
  const combinationSegment = combination ? `${combination}/` : "";
11935
- return `${SHARED_CHUNK_VIRTUAL_PREFIX}/${combinationSegment}common`;
11959
+ const sharedName = `${SHARED_CHUNK_VIRTUAL_PREFIX}/${combinationSegment}common`;
11960
+ if (ignoredMainImporters.length) {
11961
+ sharedChunkDiagnostics.set(sharedName, {
11962
+ ignoredMainImporters: Array.from(new Set(ignoredMainImporters))
11963
+ });
11964
+ sharedChunkDiagnostics.set(`${sharedName}.js`, {
11965
+ ignoredMainImporters: Array.from(new Set(ignoredMainImporters))
11966
+ });
11967
+ }
11968
+ return sharedName;
11936
11969
  }
11937
11970
  return "common";
11938
11971
  }
11939
11972
  function summarizeImportPrefixes(options) {
11940
- const { importers, relativeAbsoluteSrcRoot, subPackageRoots } = options;
11973
+ const {
11974
+ ctx,
11975
+ importers,
11976
+ relativeAbsoluteSrcRoot,
11977
+ subPackageRoots,
11978
+ forceDuplicateTester
11979
+ } = options;
11941
11980
  const summary = {};
11981
+ const ignoredImporters = /* @__PURE__ */ new Set();
11982
+ const state = {
11983
+ cache: /* @__PURE__ */ new Map(),
11984
+ stack: /* @__PURE__ */ new Set()
11985
+ };
11942
11986
  for (const importer of importers) {
11943
- const relPath = relativeAbsoluteSrcRoot(importer);
11944
- const prefix = resolveSubPackagePrefix(relPath, subPackageRoots);
11945
- summary[prefix] = (summary[prefix] || 0) + 1;
11987
+ const { prefixes, ignored } = collectEffectivePrefixes(importer, {
11988
+ ctx,
11989
+ relativeAbsoluteSrcRoot,
11990
+ subPackageRoots,
11991
+ forceDuplicateTester
11992
+ }, state);
11993
+ for (const prefix of prefixes) {
11994
+ summary[prefix] = (summary[prefix] || 0) + 1;
11995
+ }
11996
+ for (const entry of ignored) {
11997
+ ignoredImporters.add(entry);
11998
+ }
11999
+ }
12000
+ return {
12001
+ summary,
12002
+ ignoredMainImporters: Array.from(ignoredImporters)
12003
+ };
12004
+ }
12005
+ function collectEffectivePrefixes(importer, options, state) {
12006
+ const cached = state.cache.get(importer);
12007
+ if (cached) {
12008
+ return {
12009
+ prefixes: [...cached.prefixes],
12010
+ hasRealMain: cached.hasRealMain,
12011
+ ignored: [...cached.ignored]
12012
+ };
12013
+ }
12014
+ if (state.stack.has(importer)) {
12015
+ return {
12016
+ prefixes: [""],
12017
+ hasRealMain: true,
12018
+ ignored: []
12019
+ };
12020
+ }
12021
+ state.stack.add(importer);
12022
+ const {
12023
+ ctx,
12024
+ relativeAbsoluteSrcRoot,
12025
+ subPackageRoots,
12026
+ forceDuplicateTester
12027
+ } = options;
12028
+ const relativeId = relativeAbsoluteSrcRoot(importer);
12029
+ const subPackagePrefix = resolveSubPackagePrefix(relativeId, subPackageRoots);
12030
+ if (subPackagePrefix) {
12031
+ const result2 = {
12032
+ prefixes: [subPackagePrefix],
12033
+ hasRealMain: false,
12034
+ ignored: []
12035
+ };
12036
+ state.cache.set(importer, result2);
12037
+ state.stack.delete(importer);
12038
+ return {
12039
+ prefixes: [...result2.prefixes],
12040
+ hasRealMain: result2.hasRealMain,
12041
+ ignored: []
12042
+ };
12043
+ }
12044
+ const moduleInfo = ctx.getModuleInfo(importer);
12045
+ const importerParents = moduleInfo?.importers ?? [];
12046
+ const forcedDuplicate = forceDuplicateTester?.(relativeId, importer) ?? false;
12047
+ if (!importerParents.length) {
12048
+ const result2 = forcedDuplicate ? {
12049
+ prefixes: [],
12050
+ hasRealMain: false,
12051
+ ignored: [relativeId]
12052
+ } : {
12053
+ prefixes: [""],
12054
+ hasRealMain: true,
12055
+ ignored: []
12056
+ };
12057
+ state.cache.set(importer, result2);
12058
+ state.stack.delete(importer);
12059
+ return {
12060
+ prefixes: [...result2.prefixes],
12061
+ hasRealMain: result2.hasRealMain,
12062
+ ignored: [...result2.ignored]
12063
+ };
12064
+ }
12065
+ const aggregatedPrefixes = /* @__PURE__ */ new Set();
12066
+ let hasRealMain = false;
12067
+ const aggregatedIgnored = [];
12068
+ for (const parent of importerParents) {
12069
+ const collectorResult = collectEffectivePrefixes(parent, options, state);
12070
+ for (const prefix of collectorResult.prefixes) {
12071
+ aggregatedPrefixes.add(prefix);
12072
+ }
12073
+ if (collectorResult.hasRealMain) {
12074
+ hasRealMain = true;
12075
+ }
12076
+ if (collectorResult.ignored.length) {
12077
+ aggregatedIgnored.push(...collectorResult.ignored);
12078
+ }
12079
+ }
12080
+ if (!aggregatedPrefixes.size) {
12081
+ aggregatedPrefixes.add("");
12082
+ hasRealMain = true;
11946
12083
  }
11947
- return summary;
12084
+ const shouldIgnoreAsMain = !aggregatedPrefixes.has("") && importerParents.length > 0;
12085
+ const ignored = shouldIgnoreAsMain || forcedDuplicate && !aggregatedPrefixes.has("") ? [relativeId] : [];
12086
+ const result = {
12087
+ prefixes: Array.from(aggregatedPrefixes),
12088
+ hasRealMain,
12089
+ ignored: Array.from(/* @__PURE__ */ new Set([...aggregatedIgnored, ...ignored]))
12090
+ };
12091
+ state.cache.set(importer, result);
12092
+ state.stack.delete(importer);
12093
+ return {
12094
+ prefixes: [...result.prefixes],
12095
+ hasRealMain: result.hasRealMain,
12096
+ ignored: [...result.ignored]
12097
+ };
11948
12098
  }
11949
12099
  function resolveSubPackagePrefix(fileName, subPackageRoots) {
11950
12100
  for (const root of subPackageRoots) {
@@ -12000,6 +12150,7 @@ function applySharedChunkStrategy(bundle, options) {
12000
12150
  }
12001
12151
  }
12002
12152
  if (hasMainImporter || importerMap.size === 0) {
12153
+ consumeSharedChunkDiagnostics(originalSharedFileName);
12003
12154
  let finalFileName = chunk.fileName;
12004
12155
  if (fileName.startsWith(`${SHARED_CHUNK_VIRTUAL_PREFIX}/`)) {
12005
12156
  const newFileName = fileName.slice(SHARED_CHUNK_VIRTUAL_PREFIX.length + 1);
@@ -12016,6 +12167,7 @@ function applySharedChunkStrategy(bundle, options) {
12016
12167
  }
12017
12168
  const importerToChunk = /* @__PURE__ */ new Map();
12018
12169
  const duplicates = [];
12170
+ const diagnostics = consumeSharedChunkDiagnostics(originalSharedFileName);
12019
12171
  for (const { newFileName, importers: importerFiles } of importerMap.values()) {
12020
12172
  this.emitFile({
12021
12173
  type: "asset",
@@ -12038,20 +12190,42 @@ function applySharedChunkStrategy(bundle, options) {
12038
12190
  });
12039
12191
  }
12040
12192
  updateImporters(bundle, importerToChunk, fileName);
12041
- chunk.code = "// duplicated into sub-packages via weapp-vite chunk strategy\n";
12042
- chunk.map = null;
12043
- chunk.sourcemapFileName = null;
12044
- chunk.imports = [];
12045
- chunk.dynamicImports = [];
12046
- chunk.exports = [];
12047
- chunk.moduleIds = [];
12048
- chunk.modules = {};
12193
+ delete bundle[fileName];
12194
+ const candidateMapKeys = /* @__PURE__ */ new Set();
12195
+ candidateMapKeys.add(`${fileName}.map`);
12196
+ if (typeof chunk.sourcemapFileName === "string" && chunk.sourcemapFileName) {
12197
+ candidateMapKeys.add(chunk.sourcemapFileName);
12198
+ }
12199
+ for (const mapKey of candidateMapKeys) {
12200
+ if (mapKey && bundle[mapKey]) {
12201
+ delete bundle[mapKey];
12202
+ }
12203
+ }
12204
+ const chunkBytes = typeof originalCode === "string" ? Buffer2.byteLength(originalCode, "utf8") : void 0;
12205
+ const redundantBytes = typeof chunkBytes === "number" ? chunkBytes * Math.max(duplicates.length - 1, 0) : void 0;
12049
12206
  options.onDuplicate?.({
12050
12207
  sharedFileName: originalSharedFileName,
12051
- duplicates
12208
+ duplicates,
12209
+ ignoredMainImporters: diagnostics?.ignoredMainImporters,
12210
+ chunkBytes,
12211
+ redundantBytes
12052
12212
  });
12053
12213
  }
12054
12214
  }
12215
+ function consumeSharedChunkDiagnostics(fileName) {
12216
+ const direct = sharedChunkDiagnostics.get(fileName);
12217
+ if (direct) {
12218
+ sharedChunkDiagnostics.delete(fileName);
12219
+ return direct;
12220
+ }
12221
+ const withoutExt = fileName.replace(/\.[^./\\]+$/, "");
12222
+ const fallback = sharedChunkDiagnostics.get(withoutExt);
12223
+ if (fallback) {
12224
+ sharedChunkDiagnostics.delete(withoutExt);
12225
+ return fallback;
12226
+ }
12227
+ return void 0;
12228
+ }
12055
12229
  function isSharedVirtualChunk(fileName, output) {
12056
12230
  return output?.type === "chunk" && fileName.startsWith(`${SHARED_CHUNK_VIRTUAL_PREFIX}/`);
12057
12231
  }
@@ -12064,6 +12238,24 @@ function findChunkImporters(bundle, target) {
12064
12238
  const chunk = output;
12065
12239
  if (chunk.imports.includes(target) || chunk.dynamicImports.includes(target)) {
12066
12240
  importers.add(fileName);
12241
+ continue;
12242
+ }
12243
+ const metadata = chunk.viteMetadata;
12244
+ if (metadata) {
12245
+ const importedChunks = metadata.importedChunks;
12246
+ if (hasInCollection(importedChunks, target)) {
12247
+ importers.add(fileName);
12248
+ continue;
12249
+ }
12250
+ const importedScripts = metadata.importedScripts ?? metadata.importedScriptsByUrl;
12251
+ if (hasInCollection(importedScripts, target)) {
12252
+ importers.add(fileName);
12253
+ continue;
12254
+ }
12255
+ }
12256
+ const potentialImport = createRelativeImport(fileName, target);
12257
+ if (potentialImport && containsImportSpecifier(chunk.code ?? "", potentialImport)) {
12258
+ importers.add(fileName);
12067
12259
  }
12068
12260
  }
12069
12261
  return Array.from(importers);
@@ -12091,11 +12283,35 @@ function updateImporters(bundle, importerToChunk, originalFileName) {
12091
12283
  const importerChunk = importer;
12092
12284
  const originalImportPath = createRelativeImport(importerFile, originalFileName);
12093
12285
  const newImportPath = createRelativeImport(importerFile, newChunkFile);
12286
+ let codeUpdated = false;
12094
12287
  if (originalImportPath !== newImportPath) {
12095
- importerChunk.code = replaceAll(importerChunk.code, originalImportPath, newImportPath);
12288
+ const updated = replaceAll(importerChunk.code, originalImportPath, newImportPath);
12289
+ if (updated !== importerChunk.code) {
12290
+ importerChunk.code = updated;
12291
+ codeUpdated = true;
12292
+ }
12293
+ }
12294
+ importerChunk.imports = replaceInArray(importerChunk.imports, originalFileName, newChunkFile, codeUpdated);
12295
+ importerChunk.dynamicImports = replaceInArray(importerChunk.dynamicImports, originalFileName, newChunkFile, codeUpdated);
12296
+ const implicitlyLoadedBefore = importerChunk.implicitlyLoadedBefore;
12297
+ if (Array.isArray(implicitlyLoadedBefore)) {
12298
+ importerChunk.implicitlyLoadedBefore = replaceInArray(
12299
+ implicitlyLoadedBefore,
12300
+ originalFileName,
12301
+ newChunkFile,
12302
+ codeUpdated
12303
+ );
12304
+ }
12305
+ const referencedFiles = importerChunk.referencedFiles;
12306
+ if (Array.isArray(referencedFiles)) {
12307
+ importerChunk.referencedFiles = replaceInArray(
12308
+ referencedFiles,
12309
+ originalFileName,
12310
+ newChunkFile,
12311
+ codeUpdated
12312
+ );
12096
12313
  }
12097
- importerChunk.imports = replaceInArray(importerChunk.imports, originalFileName, newChunkFile);
12098
- importerChunk.dynamicImports = replaceInArray(importerChunk.dynamicImports, originalFileName, newChunkFile);
12314
+ updateViteMetadata(importerChunk, originalFileName, newChunkFile, codeUpdated);
12099
12315
  }
12100
12316
  }
12101
12317
  function replaceAll(source, searchValue, replaceValue) {
@@ -12114,185 +12330,183 @@ function replaceAll(source, searchValue, replaceValue) {
12114
12330
  }
12115
12331
  return source;
12116
12332
  }
12117
- function replaceInArray(list, searchValue, replaceValue) {
12118
- return list.map((value) => {
12119
- return value === searchValue ? replaceValue : value;
12120
- });
12121
- }
12122
- function createRelativeImport(fromFile, toFile) {
12123
- const relative3 = path10.relative(path10.dirname(fromFile), toFile);
12124
- if (!relative3 || relative3.startsWith(".")) {
12125
- return relative3 || "./";
12126
- }
12127
- return `./${relative3}`;
12128
- }
12129
-
12130
- // src/runtime/advancedChunks.ts
12131
- function testByReg2DExpList(reg2DExpList) {
12132
- return (id) => reg2DExpList.some((regExpList) => regExpList.some((regExp) => {
12133
- regExp.lastIndex = 0;
12134
- return regExp.test(id);
12135
- }));
12136
- }
12137
- function createAdvancedChunkNameResolver(options) {
12138
- const {
12139
- relativeAbsoluteSrcRoot,
12140
- getSubPackageRoots,
12141
- strategy,
12142
- vendorsMatchers
12143
- } = options;
12144
- const isVendor = testByReg2DExpList(vendorsMatchers);
12145
- return (id, ctx) => {
12146
- const subPackageRoots = Array.from(getSubPackageRoots());
12147
- const sharedName = resolveSharedChunkName({
12148
- id,
12149
- ctx,
12150
- relativeAbsoluteSrcRoot,
12151
- subPackageRoots,
12152
- strategy
12153
- });
12154
- if (!isVendor(id)) {
12155
- return sharedName;
12156
- }
12157
- if (strategy === "hoist") {
12158
- return "vendors";
12159
- }
12160
- return sharedName;
12161
- };
12162
- }
12163
-
12164
- // src/runtime/independentError.ts
12165
- init_esm_shims();
12166
- var ANSI_ESCAPE_PATTERN = /\u001B\[[0-9;]*m/g;
12167
- function stripAnsi(value) {
12168
- return value.replace(ANSI_ESCAPE_PATTERN, "");
12169
- }
12170
- function isErrorInstance(value) {
12171
- return value instanceof Error;
12172
- }
12173
- function formatSummary(payload) {
12174
- const parts = [];
12175
- const code = payload.code;
12176
- if (typeof code === "string" && code.trim()) {
12177
- parts.push(`code: ${code.trim()}`);
12178
- }
12179
- const plugin = payload.plugin;
12180
- if (typeof plugin === "string" && plugin.trim()) {
12181
- parts.push(`plugin: ${plugin.trim()}`);
12182
- }
12183
- const id = payload.id;
12184
- if (typeof id === "string" && id.trim()) {
12185
- parts.push(`id: ${id.trim()}`);
12186
- }
12187
- if (!parts.length) {
12188
- return "";
12333
+ function containsImportSpecifier(source, specifier) {
12334
+ if (!specifier) {
12335
+ return false;
12189
12336
  }
12190
- return ` (${parts.join(", ")})`;
12191
- }
12192
- function collectDetails(payload) {
12193
- const details = [];
12194
- const frame = payload.frame;
12195
- if (typeof frame === "string" && frame.trim()) {
12196
- details.push(frame.trim());
12337
+ if (source.includes(specifier)) {
12338
+ return true;
12197
12339
  }
12198
- const stack = payload.stack;
12199
- if (typeof stack === "string" && stack.trim()) {
12200
- details.push(stack.trim());
12340
+ if (specifier.startsWith("./")) {
12341
+ const trimmed = specifier.slice(2);
12342
+ if (trimmed && source.includes(trimmed)) {
12343
+ return true;
12344
+ }
12201
12345
  }
12202
- return details;
12346
+ return false;
12203
12347
  }
12204
- function extractMessage(value, seen) {
12205
- if (!value || seen.has(value)) {
12206
- return void 0;
12348
+ function hasInCollection(collection, value) {
12349
+ if (!collection || !value) {
12350
+ return false;
12207
12351
  }
12208
- if (typeof value === "string") {
12209
- const trimmed = stripAnsi(value).trim();
12210
- return trimmed || void 0;
12352
+ if (collection instanceof Set) {
12353
+ return collection.has(value);
12211
12354
  }
12212
- if (isErrorInstance(value)) {
12213
- const trimmed = stripAnsi(value.message ?? "").trim();
12214
- if (trimmed) {
12215
- return trimmed;
12216
- }
12217
- if (value.cause) {
12218
- return extractMessage(value.cause, seen);
12219
- }
12220
- return void 0;
12355
+ if (Array.isArray(collection)) {
12356
+ return collection.includes(value);
12221
12357
  }
12222
- if (typeof value === "object") {
12223
- const record = value;
12224
- seen.add(record);
12225
- const directMessage = extractMessage(record.message, seen);
12226
- if (directMessage) {
12227
- return directMessage;
12228
- }
12229
- const nestedKeys = ["reason", "detail", "details", "error", "field0", "field1", "cause"];
12230
- for (const key of nestedKeys) {
12231
- if (key in record) {
12232
- const nestedMessage = extractMessage(record[key], seen);
12233
- if (nestedMessage) {
12234
- return nestedMessage;
12235
- }
12236
- }
12237
- }
12358
+ if (collection instanceof Map) {
12359
+ return collection.has(value);
12238
12360
  }
12239
- return void 0;
12361
+ return false;
12240
12362
  }
12241
- function createIndependentBuildError(root, cause) {
12242
- const fallback = `Independent bundle for ${root} failed`;
12243
- if (isErrorInstance(cause)) {
12244
- if (!cause.message || cause.message.trim() === "") {
12245
- return new Error(fallback, { cause });
12363
+ function replaceInArray(list, searchValue, replaceValue, shouldInsert) {
12364
+ const values = Array.isArray(list) ? [...list] : [];
12365
+ let replaced = false;
12366
+ for (let index = 0; index < values.length; index++) {
12367
+ const current2 = values[index];
12368
+ if (current2 === searchValue) {
12369
+ values[index] = replaceValue;
12370
+ replaced = true;
12246
12371
  }
12247
- return cause;
12248
12372
  }
12249
- if (!cause) {
12250
- return new Error(fallback);
12373
+ if ((replaced || shouldInsert) && replaceValue && !values.includes(replaceValue)) {
12374
+ values.push(replaceValue);
12251
12375
  }
12252
- if (typeof cause === "string") {
12253
- const trimmed = stripAnsi(cause).trim();
12254
- if (!trimmed) {
12255
- return new Error(fallback, { cause });
12256
- }
12257
- return new Error(trimmed, { cause });
12376
+ return values;
12377
+ }
12378
+ function updateViteMetadata(importerChunk, originalFileName, newChunkFile, shouldInsert) {
12379
+ const metadata = importerChunk.viteMetadata;
12380
+ if (!metadata || typeof metadata !== "object") {
12381
+ return;
12258
12382
  }
12259
- if (typeof cause === "object") {
12260
- const payload = cause;
12261
- const seen = /* @__PURE__ */ new Set();
12262
- const extracted = extractMessage(payload, seen);
12263
- const summary = formatSummary(payload);
12264
- const detailLines = collectDetails(payload);
12265
- if (extracted) {
12266
- let composedMessage = extracted;
12267
- if (summary) {
12268
- composedMessage += summary;
12383
+ const candidateKeys = ["importedChunks", "importedScripts"];
12384
+ for (const key of candidateKeys) {
12385
+ const collection = metadata[key];
12386
+ if (collection instanceof Set) {
12387
+ const hadOriginal = collection.delete(originalFileName);
12388
+ if (hadOriginal || shouldInsert) {
12389
+ collection.add(newChunkFile);
12269
12390
  }
12270
- if (detailLines.length) {
12271
- composedMessage += `
12272
- ${detailLines.join("\n")}`;
12391
+ } else if (Array.isArray(collection)) {
12392
+ metadata[key] = replaceInArray(collection, originalFileName, newChunkFile, shouldInsert);
12393
+ } else if (collection instanceof Map) {
12394
+ if (collection.has(originalFileName)) {
12395
+ const originalValue = collection.get(originalFileName);
12396
+ collection.delete(originalFileName);
12397
+ collection.set(newChunkFile, originalValue);
12273
12398
  }
12274
- return new Error(composedMessage, { cause });
12275
12399
  }
12276
- if (summary || detailLines.length) {
12277
- const composed = detailLines.length ? `${fallback}${summary}
12278
- ${detailLines.join("\n")}` : `${fallback}${summary}`;
12279
- if (composed.trim()) {
12280
- return new Error(composed, { cause });
12281
- }
12400
+ }
12401
+ }
12402
+ function createRelativeImport(fromFile, toFile) {
12403
+ const relative3 = path10.relative(path10.dirname(fromFile), toFile);
12404
+ if (!relative3 || relative3.startsWith(".")) {
12405
+ return relative3 || "./";
12406
+ }
12407
+ return `./${relative3}`;
12408
+ }
12409
+
12410
+ // src/runtime/advancedChunks.ts
12411
+ function testByReg2DExpList(reg2DExpList) {
12412
+ return (id) => reg2DExpList.some((regExpList) => regExpList.some((regExp) => {
12413
+ regExp.lastIndex = 0;
12414
+ return regExp.test(id);
12415
+ }));
12416
+ }
12417
+ function createAdvancedChunkNameResolver(options) {
12418
+ const {
12419
+ relativeAbsoluteSrcRoot,
12420
+ getSubPackageRoots,
12421
+ strategy,
12422
+ vendorsMatchers,
12423
+ forceDuplicateTester
12424
+ } = options;
12425
+ const isVendor = testByReg2DExpList(vendorsMatchers);
12426
+ return (id, ctx) => {
12427
+ const subPackageRoots = Array.from(getSubPackageRoots());
12428
+ const sharedName = resolveSharedChunkName({
12429
+ id,
12430
+ ctx,
12431
+ relativeAbsoluteSrcRoot,
12432
+ subPackageRoots,
12433
+ strategy,
12434
+ forceDuplicateTester
12435
+ });
12436
+ if (!isVendor(id)) {
12437
+ return sharedName;
12282
12438
  }
12439
+ if (strategy === "hoist") {
12440
+ return "vendors";
12441
+ }
12442
+ return sharedName;
12443
+ };
12444
+ }
12445
+
12446
+ // src/runtime/sharedBuildConfig.ts
12447
+ var REG_NODE_MODULES_DIR = /[\\/]node_modules[\\/]/gi;
12448
+ var REG_COMMONJS_HELPERS = /commonjsHelpers\.js$/;
12449
+ function createForceDuplicateTester(patterns) {
12450
+ if (!patterns || patterns.length === 0) {
12451
+ return void 0;
12283
12452
  }
12284
- try {
12285
- const serialized = JSON.stringify(cause);
12286
- if (serialized && serialized !== "{}") {
12287
- return new Error(`${fallback}: ${serialized}`, { cause });
12453
+ const matchers = patterns.map((pattern) => {
12454
+ if (typeof pattern === "string") {
12455
+ const matcher = picomatch(pattern, { dot: true });
12456
+ return (value) => matcher(value);
12288
12457
  }
12289
- } catch {
12458
+ if (isRegexp(pattern)) {
12459
+ return (value) => {
12460
+ pattern.lastIndex = 0;
12461
+ return pattern.test(value);
12462
+ };
12463
+ }
12464
+ return void 0;
12465
+ }).filter((matcher) => typeof matcher === "function");
12466
+ if (!matchers.length) {
12467
+ return void 0;
12290
12468
  }
12291
- return new Error(fallback, { cause });
12469
+ return (relativeId, absoluteId) => {
12470
+ for (const matcher of matchers) {
12471
+ if (matcher(relativeId) || matcher(absoluteId)) {
12472
+ return true;
12473
+ }
12474
+ }
12475
+ return false;
12476
+ };
12477
+ }
12478
+ function createSharedBuildConfig(configService, scanService) {
12479
+ const nodeModulesDeps = [REG_NODE_MODULES_DIR];
12480
+ const commonjsHelpersDeps = [REG_COMMONJS_HELPERS];
12481
+ const sharedStrategy = configService.weappViteConfig?.chunks?.sharedStrategy ?? DEFAULT_SHARED_CHUNK_STRATEGY;
12482
+ const forceDuplicatePatterns = configService.weappViteConfig?.chunks?.forceDuplicatePatterns;
12483
+ const forceDuplicateTester = createForceDuplicateTester(forceDuplicatePatterns);
12484
+ const resolveAdvancedChunkName = createAdvancedChunkNameResolver({
12485
+ vendorsMatchers: [nodeModulesDeps, commonjsHelpersDeps],
12486
+ relativeAbsoluteSrcRoot: configService.relativeAbsoluteSrcRoot,
12487
+ getSubPackageRoots: () => scanService.subPackageMap.keys(),
12488
+ strategy: sharedStrategy,
12489
+ forceDuplicateTester
12490
+ });
12491
+ return {
12492
+ build: {
12493
+ rolldownOptions: {
12494
+ output: {
12495
+ advancedChunks: {
12496
+ groups: [
12497
+ {
12498
+ name: (id, ctx) => resolveAdvancedChunkName(id, ctx)
12499
+ }
12500
+ ]
12501
+ },
12502
+ chunkFileNames: "[name].js"
12503
+ }
12504
+ }
12505
+ }
12506
+ };
12292
12507
  }
12293
12508
 
12294
12509
  // src/runtime/buildPlugin.ts
12295
- var REG_NODE_MODULES_DIR = /[\\/]node_modules[\\/]/gi;
12296
12510
  function createBuildService(ctx) {
12297
12511
  function assertRuntimeServices(target) {
12298
12512
  if (!target.configService || !target.watcherService || !target.npmService || !target.scanService) {
@@ -12380,40 +12594,16 @@ function createBuildService(ctx) {
12380
12594
  configService.mergeWorkers()
12381
12595
  );
12382
12596
  }
12383
- function sharedBuildConfig() {
12384
- const nodeModulesDeps = [REG_NODE_MODULES_DIR];
12385
- const commonjsHelpersDeps = [/commonjsHelpers\.js$/];
12386
- const sharedStrategy = configService.weappViteConfig?.chunks?.sharedStrategy ?? DEFAULT_SHARED_CHUNK_STRATEGY;
12387
- const resolveAdvancedChunkName = createAdvancedChunkNameResolver({
12388
- vendorsMatchers: [nodeModulesDeps, commonjsHelpersDeps],
12389
- relativeAbsoluteSrcRoot: configService.relativeAbsoluteSrcRoot,
12390
- getSubPackageRoots: () => scanService.subPackageMap.keys(),
12391
- strategy: sharedStrategy
12392
- });
12393
- return {
12394
- build: {
12395
- rolldownOptions: {
12396
- output: {
12397
- advancedChunks: {
12398
- groups: [
12399
- {
12400
- name: (id, ctxPlugin) => resolveAdvancedChunkName(id, ctxPlugin)
12401
- }
12402
- ]
12403
- },
12404
- chunkFileNames: "[name].js"
12405
- }
12406
- }
12407
- }
12408
- };
12409
- }
12410
12597
  async function runDev() {
12411
12598
  if (process3.env.NODE_ENV === void 0) {
12412
12599
  process3.env.NODE_ENV = "development";
12413
12600
  }
12414
12601
  debug?.("dev build watcher start");
12415
12602
  const { hasWorkersDir, workersDir } = checkWorkersOptions();
12416
- const buildOptions = configService.merge(void 0, sharedBuildConfig());
12603
+ const buildOptions = configService.merge(
12604
+ void 0,
12605
+ createSharedBuildConfig(configService, scanService)
12606
+ );
12417
12607
  const watcherPromise = build(
12418
12608
  buildOptions
12419
12609
  );
@@ -12502,7 +12692,10 @@ function createBuildService(ctx) {
12502
12692
  debug?.("prod build start");
12503
12693
  const { hasWorkersDir } = checkWorkersOptions();
12504
12694
  const bundlerPromise = build(
12505
- configService.merge(void 0, sharedBuildConfig())
12695
+ configService.merge(
12696
+ void 0,
12697
+ createSharedBuildConfig(configService, scanService)
12698
+ )
12506
12699
  );
12507
12700
  const workerPromise = hasWorkersDir ? buildWorkers() : Promise.resolve();
12508
12701
  const [output] = await Promise.all([bundlerPromise, workerPromise]);
@@ -20021,6 +20214,123 @@ function isMetadataYarnClassic(metadataPath) {
20021
20214
  // src/runtime/config/createConfigService.ts
20022
20215
  import path32 from "pathe";
20023
20216
 
20217
+ // src/platform.ts
20218
+ init_esm_shims();
20219
+
20220
+ // src/platforms/adapters.ts
20221
+ init_esm_shims();
20222
+ var MINI_PROGRAM_PLATFORM_ADAPTERS = [
20223
+ {
20224
+ id: "weapp",
20225
+ displayName: "WeChat Mini Program",
20226
+ aliases: ["weapp", "wechat", "weixin", "wx"],
20227
+ outputExtensions: {
20228
+ js: "js",
20229
+ json: "json",
20230
+ wxml: "wxml",
20231
+ wxss: "wxss",
20232
+ wxs: "wxs"
20233
+ }
20234
+ },
20235
+ {
20236
+ id: "alipay",
20237
+ displayName: "Alipay Mini Program",
20238
+ aliases: ["alipay", "ali", "my"],
20239
+ outputExtensions: {
20240
+ js: "js",
20241
+ json: "json",
20242
+ wxml: "axml",
20243
+ wxss: "acss",
20244
+ wxs: "sjs"
20245
+ }
20246
+ },
20247
+ {
20248
+ id: "swan",
20249
+ displayName: "Baidu Smart Program",
20250
+ aliases: ["swan", "baidu", "bd"],
20251
+ outputExtensions: {
20252
+ js: "js",
20253
+ json: "json",
20254
+ wxml: "swan",
20255
+ wxss: "css",
20256
+ wxs: "sjs"
20257
+ }
20258
+ },
20259
+ {
20260
+ id: "tt",
20261
+ displayName: "ByteDance / Douyin Mini Program",
20262
+ aliases: ["tt", "toutiao", "bytedance", "douyin"],
20263
+ outputExtensions: {
20264
+ js: "js",
20265
+ json: "json",
20266
+ wxml: "ttml",
20267
+ wxss: "ttss"
20268
+ }
20269
+ },
20270
+ {
20271
+ id: "jd",
20272
+ displayName: "JD Mini Program",
20273
+ aliases: ["jd", "jingdong"],
20274
+ outputExtensions: {
20275
+ js: "js",
20276
+ json: "json",
20277
+ wxml: "jxml",
20278
+ wxss: "jxss",
20279
+ wxs: "wxs"
20280
+ }
20281
+ },
20282
+ {
20283
+ id: "xhs",
20284
+ displayName: "Xiaohongshu Mini Program",
20285
+ aliases: ["xhs", "xiaohongshu", "little-red-book", "red"],
20286
+ outputExtensions: {
20287
+ js: "js",
20288
+ json: "json",
20289
+ wxml: "xhsml",
20290
+ wxss: "css",
20291
+ wxs: "wxs"
20292
+ }
20293
+ }
20294
+ ];
20295
+
20296
+ // src/platform.ts
20297
+ var DEFAULT_MP_PLATFORM = "weapp";
20298
+ var PLATFORM_ADAPTER_BY_ID = /* @__PURE__ */ new Map();
20299
+ var PLATFORM_ALIAS_TO_ID = /* @__PURE__ */ new Map();
20300
+ for (const adapter of MINI_PROGRAM_PLATFORM_ADAPTERS) {
20301
+ PLATFORM_ADAPTER_BY_ID.set(adapter.id, adapter);
20302
+ for (const alias of adapter.aliases) {
20303
+ const normalized = alias.trim().toLowerCase();
20304
+ if (!normalized) {
20305
+ continue;
20306
+ }
20307
+ PLATFORM_ALIAS_TO_ID.set(normalized, adapter.id);
20308
+ }
20309
+ if (!PLATFORM_ALIAS_TO_ID.has(adapter.id)) {
20310
+ PLATFORM_ALIAS_TO_ID.set(adapter.id, adapter.id);
20311
+ }
20312
+ }
20313
+ var MINI_PLATFORM_ALIASES = Object.freeze(
20314
+ Object.fromEntries(PLATFORM_ALIAS_TO_ID.entries())
20315
+ );
20316
+ function normalizeMiniPlatform(input) {
20317
+ return input ? input.trim().toLowerCase() : void 0;
20318
+ }
20319
+ function resolveMiniPlatform(input) {
20320
+ const normalized = normalizeMiniPlatform(input);
20321
+ if (!normalized) {
20322
+ return void 0;
20323
+ }
20324
+ return PLATFORM_ALIAS_TO_ID.get(normalized);
20325
+ }
20326
+ function getMiniProgramPlatformAdapter(platform) {
20327
+ const adapter = PLATFORM_ADAPTER_BY_ID.get(platform);
20328
+ if (!adapter) {
20329
+ throw new Error(`Unsupported mini program platform "${platform}".`);
20330
+ }
20331
+ return adapter;
20332
+ }
20333
+
20024
20334
  // src/runtime/oxcRuntime.ts
20025
20335
  init_esm_shims();
20026
20336
  import fs10 from "fs-extra";
@@ -20303,7 +20613,9 @@ function getWeappViteConfig() {
20303
20613
  },
20304
20614
  chunks: {
20305
20615
  sharedStrategy: "duplicate",
20306
- logOptimization: true
20616
+ logOptimization: true,
20617
+ forceDuplicatePatterns: [],
20618
+ duplicateWarningBytes: 512 * 1024
20307
20619
  }
20308
20620
  };
20309
20621
  }
@@ -23730,10 +24042,16 @@ function createCoreLifecyclePlugin(state) {
23730
24042
  const sharedStrategy = configService.weappViteConfig?.chunks?.sharedStrategy ?? DEFAULT_SHARED_CHUNK_STRATEGY;
23731
24043
  const shouldLogChunks = configService.weappViteConfig?.chunks?.logOptimization ?? true;
23732
24044
  const subPackageRoots = Array.from(scanService.subPackageMap.keys()).filter(Boolean);
23733
- applySharedChunkStrategy.call(this, bundle, {
23734
- strategy: sharedStrategy,
23735
- subPackageRoots,
23736
- onDuplicate: shouldLogChunks ? ({ duplicates }) => {
24045
+ const duplicateWarningBytes = Number(configService.weappViteConfig?.chunks?.duplicateWarningBytes ?? 0);
24046
+ const shouldWarnOnDuplicate = Number.isFinite(duplicateWarningBytes) && duplicateWarningBytes > 0;
24047
+ let redundantBytesTotal = 0;
24048
+ const handleDuplicate = shouldLogChunks || shouldWarnOnDuplicate ? ({ duplicates, ignoredMainImporters, chunkBytes, redundantBytes }) => {
24049
+ if (shouldWarnOnDuplicate) {
24050
+ const duplicateCount = duplicates.length;
24051
+ const computedRedundant = typeof redundantBytes === "number" ? redundantBytes : typeof chunkBytes === "number" ? chunkBytes * Math.max(duplicateCount - 1, 0) : 0;
24052
+ redundantBytesTotal += computedRedundant;
24053
+ }
24054
+ if (shouldLogChunks) {
23737
24055
  const subPackageSet = /* @__PURE__ */ new Set();
23738
24056
  let totalReferences = 0;
23739
24057
  for (const { fileName, importers } of duplicates) {
@@ -23744,8 +24062,14 @@ function createCoreLifecyclePlugin(state) {
23744
24062
  }
23745
24063
  }
23746
24064
  const subPackageList = Array.from(subPackageSet).join("\u3001") || "\u76F8\u5173\u5206\u5305";
23747
- logger_default.info(`[subpackages] \u5206\u5305 ${subPackageList} \u5171\u4EAB\u6A21\u5757\u5DF2\u590D\u5236\u5230\u5404\u81EA weapp-shared/common.js\uFF08${totalReferences} \u5904\u5F15\u7528\uFF09`);
23748
- } : void 0,
24065
+ const ignoredHint = ignoredMainImporters?.length ? `\uFF0C\u5FFD\u7565\u4E3B\u5305\u5F15\u7528\uFF1A${ignoredMainImporters.join("\u3001")}` : "";
24066
+ logger_default.info(`[subpackages] \u5206\u5305 ${subPackageList} \u5171\u4EAB\u6A21\u5757\u5DF2\u590D\u5236\u5230\u5404\u81EA weapp-shared/common.js\uFF08${totalReferences} \u5904\u5F15\u7528${ignoredHint}\uFF09`);
24067
+ }
24068
+ } : void 0;
24069
+ applySharedChunkStrategy.call(this, bundle, {
24070
+ strategy: sharedStrategy,
24071
+ subPackageRoots,
24072
+ onDuplicate: handleDuplicate,
23749
24073
  onFallback: shouldLogChunks ? ({ reason, importers }) => {
23750
24074
  const involvedSubs = /* @__PURE__ */ new Set();
23751
24075
  let hasMainReference = false;
@@ -23772,6 +24096,9 @@ function createCoreLifecyclePlugin(state) {
23772
24096
  }
23773
24097
  } : void 0
23774
24098
  });
24099
+ if (shouldWarnOnDuplicate && redundantBytesTotal > duplicateWarningBytes) {
24100
+ logger_default.warn(`[subpackages] \u5206\u5305\u590D\u5236\u5171\u4EAB\u6A21\u5757\u4EA7\u751F\u5197\u4F59\u4F53\u79EF ${formatBytes(redundantBytesTotal)}\uFF0C\u5DF2\u8D85\u8FC7\u9608\u503C ${formatBytes(duplicateWarningBytes)}\uFF0C\u5EFA\u8BAE\u8C03\u6574\u5206\u5305\u5212\u5206\u6216\u8FD0\u884C weapp-vite analyze \u5B9A\u4F4D\u95EE\u9898\u3002`);
24101
+ }
23775
24102
  }
23776
24103
  if (configService.weappViteConfig?.debug?.watchFiles) {
23777
24104
  const watcherService = ctx.watcherService;
@@ -23847,6 +24174,21 @@ function createRequireAnalysisPlugin(state) {
23847
24174
  }
23848
24175
  };
23849
24176
  }
24177
+ function formatBytes(bytes) {
24178
+ if (!Number.isFinite(bytes) || bytes <= 0) {
24179
+ return "0 B";
24180
+ }
24181
+ const units = ["B", "KB", "MB", "GB"];
24182
+ let value = bytes;
24183
+ let index = 0;
24184
+ while (value >= 1024 && index < units.length - 1) {
24185
+ value /= 1024;
24186
+ index++;
24187
+ }
24188
+ const precision = value >= 100 ? 0 : value >= 10 ? 1 : 2;
24189
+ const formatted = value.toFixed(precision).replace(/\.0+$/, "");
24190
+ return `${formatted} ${units[index]}`;
24191
+ }
23850
24192
  function emitJsonAssets(state) {
23851
24193
  const { ctx } = state;
23852
24194
  const { jsonService } = ctx;
@@ -23903,7 +24245,7 @@ import path28 from "pathe";
23903
24245
  // src/plugins/css/shared/sharedStyles.ts
23904
24246
  init_esm_shims();
23905
24247
  import path27 from "pathe";
23906
- import picomatch from "picomatch";
24248
+ import picomatch2 from "picomatch";
23907
24249
  var SLASH_RE = /\\/g;
23908
24250
  function toPosixPath(value) {
23909
24251
  return value.replace(SLASH_RE, "/");
@@ -23965,10 +24307,10 @@ function getStyleMatcher(entry) {
23965
24307
  const includePatterns = entry.include?.length ? entry.include : ["**/*"];
23966
24308
  const excludePatterns = entry.exclude?.length ? entry.exclude : void 0;
23967
24309
  const matcher = {
23968
- include: picomatch(includePatterns, { dot: true })
24310
+ include: picomatch2(includePatterns, { dot: true })
23969
24311
  };
23970
24312
  if (excludePatterns?.length) {
23971
- matcher.exclude = picomatch(excludePatterns, { dot: true });
24313
+ matcher.exclude = picomatch2(excludePatterns, { dot: true });
23972
24314
  }
23973
24315
  styleMatcherCache.set(entry, matcher);
23974
24316
  return matcher;
@@ -24482,6 +24824,16 @@ function wxs(ctx) {
24482
24824
 
24483
24825
  // src/plugins/index.ts
24484
24826
  var RUNTIME_PLUGINS_SYMBOL = Symbol.for("weapp-runtime:plugins");
24827
+ var WEAPP_VITE_CONTEXT_PLUGIN_NAME = "weapp-vite:context";
24828
+ function createContextPlugin(ctx) {
24829
+ return {
24830
+ name: WEAPP_VITE_CONTEXT_PLUGIN_NAME,
24831
+ enforce: "pre",
24832
+ api: {
24833
+ ctx
24834
+ }
24835
+ };
24836
+ }
24485
24837
  function attachRuntimePlugins(ctx, plugins) {
24486
24838
  const runtimePlugins = ctx[RUNTIME_PLUGINS_SYMBOL];
24487
24839
  if (!runtimePlugins?.length) {
@@ -24503,7 +24855,7 @@ function flatten(groups) {
24503
24855
  }, []);
24504
24856
  }
24505
24857
  function vitePluginWeapp(ctx, subPackageMeta) {
24506
- const groups = [preflight(ctx)];
24858
+ const groups = [[createContextPlugin(ctx)], preflight(ctx)];
24507
24859
  if (!subPackageMeta) {
24508
24860
  groups.push(asset(ctx), autoRoutes(ctx), autoImport(ctx));
24509
24861
  }
@@ -24515,7 +24867,7 @@ function vitePluginWeapp(ctx, subPackageMeta) {
24515
24867
  return applyInspect(ctx, assembled);
24516
24868
  }
24517
24869
  function vitePluginWeappWorkers(ctx) {
24518
- const groups = [preflight(ctx), workers(ctx)];
24870
+ const groups = [[createContextPlugin(ctx)], preflight(ctx), workers(ctx)];
24519
24871
  const assembled = attachRuntimePlugins(ctx, flatten(groups));
24520
24872
  return applyInspect(ctx, assembled);
24521
24873
  }
@@ -29718,6 +30070,8 @@ export {
29718
30070
  VERSION,
29719
30071
  checkRuntime,
29720
30072
  resolveWeappConfigFile,
30073
+ SHARED_CHUNK_VIRTUAL_PREFIX,
30074
+ createSharedBuildConfig,
29721
30075
  DEFAULT_MP_PLATFORM,
29722
30076
  normalizeMiniPlatform,
29723
30077
  resolveMiniPlatform,