weapp-vite 6.20.2 → 6.20.3

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.
@@ -1,4 +1,4 @@
1
- import { n as getCompilerContext, v as getRouteRuntimeGlobalKeys } from "./createContext-DiBG4uOB.mjs";
1
+ import { n as getCompilerContext, v as getRouteRuntimeGlobalKeys } from "./createContext-DavT7XIA.mjs";
2
2
  //#region src/auto-routes.ts
3
3
  const ROUTE_RUNTIME_OVERRIDE_KEY = Symbol.for("weapp-vite.route-runtime");
4
4
  function createGetter(resolver) {
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { C as parseCommentJson, D as isPathInside, E as shouldPassPlatformArgToIdeOpen, S as loadViteConfigFile, T as getDefaultIdeProjectRoot, _ as resolveHmrProfileJsonPath, a as formatBytes, b as checkRuntime, d as getBackendForCapability, f as resolveBackendExecution, g as SHARED_CHUNK_VIRTUAL_PREFIX, h as createSharedBuildConfig, m as syncManagedTsconfigBootstrapFiles, p as syncProjectSupportFiles, t as createCompilerContext, w as createCjsConfigLoadError, x as getProjectConfigFileName, y as resolveWeappConfigFile } from "./createContext-DiBG4uOB.mjs";
1
+ import { C as parseCommentJson, D as isPathInside, E as shouldPassPlatformArgToIdeOpen, S as loadViteConfigFile, T as getDefaultIdeProjectRoot, _ as resolveHmrProfileJsonPath, a as formatBytes, b as checkRuntime, d as getBackendForCapability, f as resolveBackendExecution, g as SHARED_CHUNK_VIRTUAL_PREFIX, h as createSharedBuildConfig, m as syncManagedTsconfigBootstrapFiles, p as syncProjectSupportFiles, t as createCompilerContext, w as createCjsConfigLoadError, x as getProjectConfigFileName, y as resolveWeappConfigFile } from "./createContext-DavT7XIA.mjs";
2
2
  import { r as logger_default, t as colors } from "./logger-mt4mSTqV.mjs";
3
- import { h as VERSION } from "./file-DQ5FlYd5.mjs";
3
+ import { h as VERSION } from "./file-AiMZtyLe.mjs";
4
4
  import { c as startWeappViteMcpServer, l as detectAiDevelopmentEnvironment, s as resolveWeappMcpConfig } from "./mcp-BG6TliEg.mjs";
5
5
  import { createRequire } from "node:module";
6
6
  import fs from "node:fs";
@@ -4727,7 +4727,7 @@ function resolveRunnableHotkeyDefinition(input) {
4727
4727
  }
4728
4728
  //#endregion
4729
4729
  //#region package.json
4730
- var version = "6.20.2";
4730
+ var version = "6.20.3";
4731
4731
  //#endregion
4732
4732
  //#region src/cli/devHotkeys/format.ts
4733
4733
  const FULLWIDTH_ASCII_START = 65281;
@@ -1,6 +1,6 @@
1
1
  import { n as applyWeappViteHostMeta } from "./pluginHost--CaeyWpA.mjs";
2
2
  import { n as configureLogger, r as logger_default } from "./logger-mt4mSTqV.mjs";
3
- import { C as isNativeTemplateSource, S as ALL_NATIVE_STYLE_RESOLVER_EXTENSIONS, T as MINI_PROGRAM_PLATFORM_ADAPTERS, _ as jsExtensions, a as findJsonEntry, b as templateExtensions, c as isJsOrTs, d as touch, g as configExtensions, i as findJsEntry, l as isTemplate, n as changeFileExtension, o as findTemplateEntry, p as inlineAutoRoutesImports, r as findCssEntry, s as findVueEntry, t as extractConfigFromVue, v as scriptExtensions, w as isSourceStyleExtension, x as vueExtensions, y as supportedCssLangs } from "./file-DQ5FlYd5.mjs";
3
+ import { C as isNativeTemplateSource, S as ALL_NATIVE_STYLE_RESOLVER_EXTENSIONS, T as MINI_PROGRAM_PLATFORM_ADAPTERS, _ as jsExtensions, a as findJsonEntry, b as templateExtensions, c as isJsOrTs, d as touch, g as configExtensions, i as findJsEntry, l as isTemplate, n as changeFileExtension, o as findTemplateEntry, p as inlineAutoRoutesImports, r as findCssEntry, s as findVueEntry, t as extractConfigFromVue, v as scriptExtensions, w as isSourceStyleExtension, x as vueExtensions, y as supportedCssLangs } from "./file-AiMZtyLe.mjs";
4
4
  import { createRequire, isBuiltin } from "node:module";
5
5
  import { createDebug } from "obug";
6
6
  import fs, { existsSync, readFileSync, realpathSync } from "node:fs";
@@ -36,6 +36,7 @@ import { spawn } from "node:child_process";
36
36
  import PQueue from "p-queue";
37
37
  import { Buffer } from "node:buffer";
38
38
  import MagicString from "magic-string";
39
+ import remapping from "@jridgewell/remapping";
39
40
  import * as t from "@weapp-vite/ast/babelTypes";
40
41
  import babelPresetEnv from "@babel/preset-env";
41
42
  import babelPresetTypescript from "@babel/preset-typescript";
@@ -47,7 +48,6 @@ import { objectHash } from "@weapp-core/shared/node";
47
48
  import { wrapPlugin } from "vite-plugin-performance";
48
49
  import { performance as performance$1 } from "node:perf_hooks";
49
50
  import postcss from "postcss";
50
- import remapping from "@jridgewell/remapping";
51
51
  import { weappWebPlugin } from "@weapp-vite/web";
52
52
  import { bundleRequire } from "rolldown-require";
53
53
  //#region src/debugger.ts
@@ -9067,17 +9067,174 @@ function setCachedSharedChunkName(moduleId, value) {
9067
9067
  sharedChunkNameCache.set(moduleId, value ?? null);
9068
9068
  }
9069
9069
  //#endregion
9070
- //#region src/runtime/chunkStrategy/utils.ts
9071
- function replaceAll(source, searchValue, replaceValue) {
9072
- if (!searchValue) return source;
9073
- if (source.includes(searchValue)) return source.split(searchValue).join(replaceValue);
9074
- if (searchValue.startsWith("./") && replaceValue.startsWith("./")) {
9075
- const trimmedSearch = searchValue.slice(2);
9076
- const trimmedReplace = replaceValue.slice(2);
9077
- if (trimmedSearch && source.includes(trimmedSearch)) return source.split(trimmedSearch).join(trimmedReplace);
9070
+ //#region src/utils/sourcemap.ts
9071
+ function isEncodedSourceMapLike(value) {
9072
+ return Boolean(value && typeof value === "object" && "version" in value && typeof value.version === "number" && "mappings" in value && "names" in value && "sources" in value);
9073
+ }
9074
+ function normalizeEncodedSourceMapLike(value) {
9075
+ if (!value || typeof value !== "object") return null;
9076
+ const sourceMap = value;
9077
+ const numericVersion = typeof sourceMap.version === "number" ? sourceMap.version : typeof sourceMap.version === "string" ? Number(sourceMap.version) : NaN;
9078
+ if (!Number.isFinite(numericVersion)) return null;
9079
+ const normalized = {
9080
+ ...sourceMap,
9081
+ version: numericVersion
9082
+ };
9083
+ return isEncodedSourceMapLike(normalized) ? normalized : null;
9084
+ }
9085
+ function composeSourceMaps(transformedMap, originalMap) {
9086
+ if (isEncodedSourceMapLike(transformedMap) && isEncodedSourceMapLike(originalMap)) return remapping([transformedMap, originalMap], () => null);
9087
+ if (isEncodedSourceMapLike(transformedMap)) return transformedMap;
9088
+ if (isEncodedSourceMapLike(originalMap)) return originalMap;
9089
+ return null;
9090
+ }
9091
+ //#endregion
9092
+ //#region src/utils/outputChunk.ts
9093
+ const INLINE_SOURCE_MAP_RE = /\n?\/\/[#@]\s*sourceMappingURL=(data:application\/json\S*)\s*$/u;
9094
+ function resolveInlineSourceMap(code) {
9095
+ const match = INLINE_SOURCE_MAP_RE.exec(code);
9096
+ if (typeof match?.index !== "number") return null;
9097
+ const dataUrl = match[1];
9098
+ const commaIndex = dataUrl.indexOf(",");
9099
+ if (commaIndex < 0) return null;
9100
+ try {
9101
+ const metadata = dataUrl.slice(0, commaIndex);
9102
+ const payload = dataUrl.slice(commaIndex + 1);
9103
+ const json = metadata.includes(";base64") ? Buffer.from(payload, "base64").toString("utf8") : decodeURIComponent(payload);
9104
+ const map = normalizeEncodedSourceMapLike(JSON.parse(json));
9105
+ return map ? {
9106
+ code: code.slice(0, match.index),
9107
+ map,
9108
+ start: match.index
9109
+ } : null;
9110
+ } catch {
9111
+ return null;
9078
9112
  }
9079
- return source;
9080
9113
  }
9114
+ function appendInlineSourceMap(code, map) {
9115
+ return `${code}${code.endsWith("\n") ? "" : "\n"}//# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(JSON.stringify(map)).toString("base64")}`;
9116
+ }
9117
+ /**
9118
+ * 返回不含 inline sourcemap 数据 URI 的实际脚本,供 AST 转换使用。
9119
+ */
9120
+ function resolveOutputChunkTransformCode(chunk) {
9121
+ return resolveInlineSourceMap(chunk.code)?.code ?? chunk.code;
9122
+ }
9123
+ /**
9124
+ * 应用 MagicString 改写,并把本轮映射与 chunk 既有映射组合。
9125
+ */
9126
+ function applyMagicStringChunkRewrite(chunk, magicString, options) {
9127
+ const previousCode = chunk.code;
9128
+ const inlineSourceMap = resolveInlineSourceMap(previousCode);
9129
+ if (inlineSourceMap) magicString.remove(inlineSourceMap.start, previousCode.length);
9130
+ const nextCode = magicString.toString();
9131
+ if (nextCode === (inlineSourceMap?.code ?? previousCode)) return false;
9132
+ const previousMap = normalizeEncodedSourceMapLike(chunk.map) ?? inlineSourceMap?.map;
9133
+ if (previousMap) {
9134
+ const composedMap = composeSourceMaps(magicString.generateMap({
9135
+ hires: options?.hires ?? "boundary",
9136
+ includeContent: true,
9137
+ source: chunk.fileName
9138
+ }), previousMap);
9139
+ chunk.map = composedMap;
9140
+ chunk.code = inlineSourceMap && composedMap ? appendInlineSourceMap(nextCode, composedMap) : nextCode;
9141
+ } else chunk.code = nextCode;
9142
+ return true;
9143
+ }
9144
+ /**
9145
+ * 在 chunk 当前代码上执行一次可追踪编辑。
9146
+ */
9147
+ function editOutputChunkCode(chunk, edit, options) {
9148
+ const code = chunk.code;
9149
+ const magicString = new MagicString(code);
9150
+ edit(magicString, code);
9151
+ return applyMagicStringChunkRewrite(chunk, magicString, options);
9152
+ }
9153
+ /**
9154
+ * 在 chunk 前方插入无源代码,同时保留原代码映射。
9155
+ */
9156
+ function prependOutputChunkCode(chunk, code) {
9157
+ if (!code) return false;
9158
+ return editOutputChunkCode(chunk, (magicString) => magicString.prepend(code));
9159
+ }
9160
+ /**
9161
+ * 在 chunk 后方插入无源代码,同时保留原代码映射。
9162
+ */
9163
+ function appendOutputChunkCode(chunk, code) {
9164
+ if (!code) return false;
9165
+ return editOutputChunkCode(chunk, (magicString) => magicString.append(code));
9166
+ }
9167
+ /**
9168
+ * 按原始代码坐标批量替换互不重叠的区间。
9169
+ */
9170
+ function replaceOutputChunkCodeRanges(chunk, replacements) {
9171
+ if (replacements.length === 0) return false;
9172
+ const sorted = [...replacements].sort((left, right) => left.start - right.start);
9173
+ let previousEnd = -1;
9174
+ for (const replacement of sorted) {
9175
+ if (replacement.start < 0 || replacement.end < replacement.start || replacement.end > chunk.code.length || replacement.start < previousEnd) throw new RangeError(`Invalid or overlapping output chunk replacement: ${replacement.start}-${replacement.end}`);
9176
+ previousEnd = replacement.end;
9177
+ }
9178
+ return editOutputChunkCode(chunk, (magicString) => {
9179
+ for (const replacement of sorted) magicString.overwrite(replacement.start, replacement.end, replacement.content);
9180
+ });
9181
+ }
9182
+ /**
9183
+ * 使用正则匹配的原始坐标改写 chunk,避免整段字符串替换破坏映射。
9184
+ */
9185
+ function replaceOutputChunkCode(chunk, pattern, replace) {
9186
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
9187
+ const matcher = new RegExp(pattern.source, flags);
9188
+ const replacements = [];
9189
+ for (const match of chunk.code.matchAll(matcher)) {
9190
+ if (typeof match.index !== "number") continue;
9191
+ const content = replace(match);
9192
+ if (content == null || content === match[0]) continue;
9193
+ replacements.push({
9194
+ content,
9195
+ end: match.index + match[0].length,
9196
+ start: match.index
9197
+ });
9198
+ }
9199
+ return replaceOutputChunkCodeRanges(chunk, replacements);
9200
+ }
9201
+ /**
9202
+ * 应用自带映射的完整代码转换,并组合 chunk 既有映射。
9203
+ */
9204
+ function applyOutputChunkTransform(chunk, code, map) {
9205
+ const previousInlineSourceMap = resolveInlineSourceMap(chunk.code);
9206
+ const transformedInlineSourceMap = resolveInlineSourceMap(code);
9207
+ const previousCode = previousInlineSourceMap?.code ?? chunk.code;
9208
+ const transformedCode = transformedInlineSourceMap?.code ?? code;
9209
+ if (transformedCode === previousCode) return false;
9210
+ const previousMap = normalizeEncodedSourceMapLike(chunk.map) ?? previousInlineSourceMap?.map;
9211
+ const transformedMap = normalizeEncodedSourceMapLike(map);
9212
+ if (previousMap && !transformedMap) throw new Error(`Output chunk transform for ${chunk.fileName} must provide a source map`);
9213
+ if (previousMap && transformedMap) {
9214
+ const composedMap = composeSourceMaps(transformedMap, previousMap);
9215
+ chunk.map = composedMap;
9216
+ chunk.code = previousInlineSourceMap && composedMap ? appendInlineSourceMap(transformedCode, composedMap) : transformedCode;
9217
+ } else chunk.code = transformedCode;
9218
+ return true;
9219
+ }
9220
+ /**
9221
+ * 将 generateBundle 阶段组合后的 chunk map 提交到 Rolldown 管理的 map asset。
9222
+ */
9223
+ function syncOutputChunkSourceMapAssets(bundle) {
9224
+ let synced = 0;
9225
+ for (const output of Object.values(bundle)) {
9226
+ if (output?.type !== "chunk") continue;
9227
+ const map = normalizeEncodedSourceMapLike(output.map);
9228
+ if (!map) continue;
9229
+ const mapAsset = bundle[output.sourcemapFileName ?? `${output.fileName}.map`];
9230
+ if (!mapAsset || mapAsset.type !== "asset") continue;
9231
+ mapAsset.source = JSON.stringify(map);
9232
+ synced += 1;
9233
+ }
9234
+ return synced;
9235
+ }
9236
+ //#endregion
9237
+ //#region src/runtime/chunkStrategy/utils.ts
9081
9238
  function createRelativeImport(fromFile, toFile) {
9082
9239
  const relative = posix.relative(posix.dirname(fromFile), toFile);
9083
9240
  if (!relative || relative.startsWith(".")) return relative || "./";
@@ -9085,6 +9242,20 @@ function createRelativeImport(fromFile, toFile) {
9085
9242
  }
9086
9243
  //#endregion
9087
9244
  //#region src/runtime/chunkStrategy/bundle.ts
9245
+ function escapeRegExp$2(value) {
9246
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9247
+ }
9248
+ function replaceChunkCodeAll(chunk, searchValue, replaceValue) {
9249
+ if (!searchValue) return false;
9250
+ const replaceExact = () => replaceOutputChunkCode(chunk, new RegExp(escapeRegExp$2(searchValue), "g"), () => replaceValue);
9251
+ if (chunk.code.includes(searchValue)) return replaceExact();
9252
+ if (searchValue.startsWith("./") && replaceValue.startsWith("./")) {
9253
+ const trimmedSearch = searchValue.slice(2);
9254
+ const trimmedReplace = replaceValue.slice(2);
9255
+ if (trimmedSearch && chunk.code.includes(trimmedSearch)) return replaceOutputChunkCode(chunk, new RegExp(escapeRegExp$2(trimmedSearch), "g"), () => trimmedReplace);
9256
+ }
9257
+ return false;
9258
+ }
9088
9259
  function addDirectImporter(directImporters, imported, importer) {
9089
9260
  if (typeof imported !== "string" || !imported || imported === importer) return;
9090
9261
  let importers = directImporters.get(imported);
@@ -9346,11 +9517,7 @@ function updateImporters(bundle, importerToChunk, originalFileName, index) {
9346
9517
  for (const originalFileName of originalFileNames) {
9347
9518
  const originalImportPath = createRelativeImport(importerFile, originalFileName);
9348
9519
  if (originalImportPath === newImportPath) continue;
9349
- const updated = replaceAll(importerChunk.code, originalImportPath, newImportPath);
9350
- if (updated !== importerChunk.code) {
9351
- importerChunk.code = updated;
9352
- codeUpdated = true;
9353
- }
9520
+ codeUpdated = replaceChunkCodeAll(importerChunk, originalImportPath, newImportPath) || codeUpdated;
9354
9521
  }
9355
9522
  importerChunk.imports = replaceInArray(importerChunk.imports, originalFileNames, newChunkFile, codeUpdated);
9356
9523
  importerChunk.dynamicImports = replaceInArray(importerChunk.dynamicImports, originalFileNames, newChunkFile, codeUpdated);
@@ -9526,6 +9693,17 @@ function resolveSourceMapSource(originalMap, assetSource) {
9526
9693
  }
9527
9694
  if (isSourceLike(assetSource)) return cloneSourceLike(assetSource);
9528
9695
  }
9696
+ function resolveEncodedSourceMap(originalMap, assetSource) {
9697
+ const chunkMap = normalizeEncodedSourceMapLike(originalMap);
9698
+ if (chunkMap) return chunkMap;
9699
+ if (!isSourceLike(assetSource)) return null;
9700
+ try {
9701
+ const source = typeof assetSource === "string" ? assetSource : Buffer.from(assetSource).toString("utf8");
9702
+ return normalizeEncodedSourceMapLike(JSON.parse(source));
9703
+ } catch {
9704
+ return null;
9705
+ }
9706
+ }
9529
9707
  function emitSourceMapAsset(ctx, targetFileName, sourceMapAssetInfo, fallbackSource) {
9530
9708
  if (!targetFileName) return;
9531
9709
  if (sourceMapAssetInfo?.asset && isSourceLike(sourceMapAssetInfo.asset.source)) {
@@ -9683,29 +9861,39 @@ function reserveUniqueFileName(reservedFileNames, fileName) {
9683
9861
  reservedFileNames.add(candidate);
9684
9862
  return candidate;
9685
9863
  }
9686
- function rewriteChunkImportSpecifiersInCode(sourceCode, options) {
9864
+ function createChunkImportSpecifiersRewrite(sourceCode, options) {
9687
9865
  const { sourceFileName, sourceFileNames, targetFileName, imports, dynamicImports, runtimeFileName, resolveImportTarget } = options;
9688
9866
  const sourceFileNameCandidates = (sourceFileNames ?? [sourceFileName ?? ""]).filter(Boolean);
9689
9867
  const specifiers = new Set([...imports, ...dynamicImports].filter(Boolean));
9690
- let rewrittenCode = sourceCode;
9868
+ const magicString = new MagicString(sourceCode);
9869
+ const rewrittenRanges = /* @__PURE__ */ new Set();
9691
9870
  for (const specifier of specifiers) {
9692
9871
  const targetImportPath = createRelativeImportPath(targetFileName, posix.basename(specifier) === ROLLDOWN_RUNTIME_FILE_NAME$1 ? runtimeFileName : resolveImportTarget?.(specifier) ?? specifier);
9693
9872
  if (!targetImportPath) continue;
9694
9873
  for (const sourceCandidate of sourceFileNameCandidates) {
9695
9874
  const sourceImportPath = createRelativeImportPath(sourceCandidate, specifier);
9696
9875
  if (!sourceImportPath || sourceImportPath === targetImportPath) continue;
9697
- rewrittenCode = replaceQuotedImportLiteralValue(rewrittenCode, sourceImportPath, targetImportPath);
9876
+ replaceQuotedImportLiteralValue(magicString, sourceCode, sourceImportPath, targetImportPath, rewrittenRanges);
9698
9877
  }
9699
9878
  }
9700
- return rewrittenCode;
9879
+ return magicString;
9701
9880
  }
9702
9881
  function resolveChunkSourceFileNameForRewrite(fileName) {
9703
9882
  if (!fileName.startsWith(`weapp_shared_virtual/`)) return fileName;
9704
9883
  return fileName.slice(21);
9705
9884
  }
9706
- function replaceQuotedImportLiteralValue(sourceCode, sourcePath, targetPath) {
9885
+ function replaceQuotedImportLiteralValue(magicString, sourceCode, sourcePath, targetPath, rewrittenRanges) {
9707
9886
  const escapedSourcePath = escapeRegExpForPattern(sourcePath);
9708
- return sourceCode.replace(new RegExp(`(['"\`])${escapedSourcePath}\\1`, "g"), (_match, quote) => `${quote}${targetPath}${quote}`);
9887
+ const pattern = new RegExp(`(['"\`])${escapedSourcePath}\\1`, "g");
9888
+ for (const match of sourceCode.matchAll(pattern)) {
9889
+ if (typeof match.index !== "number") continue;
9890
+ const end = match.index + match[0].length;
9891
+ const rangeKey = `${match.index}:${end}`;
9892
+ if (rewrittenRanges.has(rangeKey)) continue;
9893
+ const quote = match[1];
9894
+ magicString.overwrite(match.index, end, `${quote}${targetPath}${quote}`);
9895
+ rewrittenRanges.add(rangeKey);
9896
+ }
9709
9897
  }
9710
9898
  function escapeRegExpForPattern(value) {
9711
9899
  return value.replace(REGEXP_ESCAPE_PATTERN, "\\$&");
@@ -9744,7 +9932,13 @@ function ensureLocalizedDuplicate(args) {
9744
9932
  }
9745
9933
  function rewriteDuplicatedChunkSource(args) {
9746
9934
  const runtimeFileName = posix.join(args.root, ROLLDOWN_RUNTIME_FILE_NAME);
9747
- let rewrittenSource = rewriteChunkImportSpecifiersInCode(args.chunk.code ?? "", {
9935
+ const sourceMapKeys = collectSourceMapKeys(args.sourceFileName, args.chunk);
9936
+ const sourceMapAssetInfo = findSourceMapAsset(args.runtimeContext.bundle, sourceMapKeys);
9937
+ const rewrittenChunk = {
9938
+ ...args.chunk,
9939
+ map: resolveEncodedSourceMap(args.chunk.map, sourceMapAssetInfo?.asset.source)
9940
+ };
9941
+ applyMagicStringChunkRewrite(rewrittenChunk, createChunkImportSpecifiersRewrite(rewrittenChunk.code ?? "", {
9748
9942
  sourceFileNames: createChunkSourceFileNameCandidates(args.sourceFileName),
9749
9943
  targetFileName: args.targetFileName,
9750
9944
  imports: args.chunk.imports,
@@ -9758,7 +9952,7 @@ function rewriteDuplicatedChunkSource(args) {
9758
9952
  sourceFileName: specifier
9759
9953
  });
9760
9954
  }
9761
- });
9955
+ }));
9762
9956
  for (const specifier of [...args.chunk.imports, ...args.chunk.dynamicImports]) {
9763
9957
  const localizedSpecifier = ensureLocalizedDuplicate({
9764
9958
  runtimeContext: args.runtimeContext,
@@ -9767,20 +9961,20 @@ function rewriteDuplicatedChunkSource(args) {
9767
9961
  sourceFileName: specifier
9768
9962
  });
9769
9963
  if (!localizedSpecifier || localizedSpecifier === specifier) continue;
9770
- rewrittenSource = rewriteChunkImportSpecifiersInCode(rewrittenSource, {
9964
+ applyMagicStringChunkRewrite(rewrittenChunk, createChunkImportSpecifiersRewrite(rewrittenChunk.code, {
9771
9965
  sourceFileName: args.targetFileName,
9772
9966
  targetFileName: args.targetFileName,
9773
9967
  imports: [specifier],
9774
9968
  dynamicImports: [],
9775
9969
  runtimeFileName,
9776
9970
  resolveImportTarget: () => localizedSpecifier
9777
- });
9971
+ }));
9778
9972
  }
9779
- return rewrittenSource;
9973
+ return rewrittenChunk;
9780
9974
  }
9781
9975
  function emitDuplicatedChunkAsset(args) {
9782
9976
  if (args.emittedLocalizedDuplicateFiles.has(args.targetFileName)) return;
9783
- const duplicatedSource = rewriteDuplicatedChunkSource({
9977
+ const duplicatedChunk = rewriteDuplicatedChunkSource({
9784
9978
  runtimeContext: args.runtimeContext,
9785
9979
  pendingLocalizedDuplicates: args.pendingLocalizedDuplicates,
9786
9980
  root: args.root,
@@ -9791,17 +9985,24 @@ function emitDuplicatedChunkAsset(args) {
9791
9985
  args.runtimeContext.pluginContext.emitFile({
9792
9986
  type: "asset",
9793
9987
  fileName: args.targetFileName,
9794
- source: duplicatedSource
9988
+ source: duplicatedChunk.code
9795
9989
  });
9796
9990
  const sourceMapKeys = collectSourceMapKeys(args.sourceFileName, args.chunk);
9797
9991
  const sourceMapAssetInfo = findSourceMapAsset(args.runtimeContext.bundle, sourceMapKeys);
9798
- const resolvedSourceMap = resolveSourceMapSource(args.chunk.map, sourceMapAssetInfo?.asset.source);
9799
- if (resolvedSourceMap) {
9992
+ const unchangedSourceMap = duplicatedChunk.code === args.chunk.code ? resolveSourceMapSource(args.chunk.map, sourceMapAssetInfo?.asset.source) : void 0;
9993
+ if (duplicatedChunk.map) {
9994
+ const sourceMapFileName = reserveUniqueFileName(args.runtimeContext.reservedFileNames, `${args.targetFileName}.map`);
9995
+ args.runtimeContext.pluginContext.emitFile({
9996
+ type: "asset",
9997
+ fileName: sourceMapFileName,
9998
+ source: JSON.stringify(duplicatedChunk.map)
9999
+ });
10000
+ } else if (unchangedSourceMap) {
9800
10001
  const sourceMapFileName = reserveUniqueFileName(args.runtimeContext.reservedFileNames, `${args.targetFileName}.map`);
9801
10002
  args.runtimeContext.pluginContext.emitFile({
9802
10003
  type: "asset",
9803
10004
  fileName: sourceMapFileName,
9804
- source: cloneSourceLike(resolvedSourceMap)
10005
+ source: cloneSourceLike(unchangedSourceMap)
9805
10006
  });
9806
10007
  }
9807
10008
  args.emittedLocalizedDuplicateFiles.add(args.targetFileName);
@@ -9840,7 +10041,7 @@ function localizeCrossSubPackageChunkLeaks(bundle, options) {
9840
10041
  if (crossRootImporters.size === 0) continue;
9841
10042
  const chunk = output;
9842
10043
  const sourceMapAssetInfo = findSourceMapAsset(bundle, collectSourceMapKeys(fileName, chunk));
9843
- const resolvedSourceMap = resolveSourceMapSource(chunk.map, sourceMapAssetInfo?.asset.source);
10044
+ const resolvedSourceMap = resolveEncodedSourceMap(chunk.map, sourceMapAssetInfo?.asset.source);
9844
10045
  const importerToChunk = /* @__PURE__ */ new Map();
9845
10046
  const duplicates = [];
9846
10047
  for (const [targetRoot, importerFiles] of crossRootImporters.entries()) {
@@ -9855,25 +10056,39 @@ function localizeCrossSubPackageChunkLeaks(bundle, options) {
9855
10056
  })();
9856
10057
  const runtimeFileName = posix.join(targetRoot, ROLLDOWN_RUNTIME_FILE_NAME);
9857
10058
  if (!existingDuplicateFileName) {
9858
- const duplicatedSource = rewriteChunkImportSpecifiersInCode(chunk.code ?? "", {
10059
+ const duplicatedChunk = {
10060
+ ...chunk,
10061
+ map: resolvedSourceMap
10062
+ };
10063
+ applyMagicStringChunkRewrite(duplicatedChunk, createChunkImportSpecifiersRewrite(duplicatedChunk.code ?? "", {
9859
10064
  sourceFileName: fileName,
9860
10065
  targetFileName: uniqueFileName,
9861
10066
  imports: chunk.imports,
9862
10067
  dynamicImports: chunk.dynamicImports,
9863
10068
  runtimeFileName
9864
- });
10069
+ }));
9865
10070
  this.emitFile({
9866
10071
  type: "asset",
9867
10072
  fileName: uniqueFileName,
9868
- source: duplicatedSource
10073
+ source: duplicatedChunk.code
9869
10074
  });
9870
- if (resolvedSourceMap) {
10075
+ if (duplicatedChunk.map) {
9871
10076
  const sourceMapFileName = reserveUniqueFileName(reservedFileNames, `${uniqueFileName}.map`);
9872
10077
  this.emitFile({
9873
10078
  type: "asset",
9874
10079
  fileName: sourceMapFileName,
9875
- source: cloneSourceLike(resolvedSourceMap)
10080
+ source: JSON.stringify(duplicatedChunk.map)
9876
10081
  });
10082
+ } else if (duplicatedChunk.code === chunk.code) {
10083
+ const unchangedSourceMap = resolveSourceMapSource(chunk.map, sourceMapAssetInfo?.asset.source);
10084
+ if (unchangedSourceMap) {
10085
+ const sourceMapFileName = reserveUniqueFileName(reservedFileNames, `${uniqueFileName}.map`);
10086
+ this.emitFile({
10087
+ type: "asset",
10088
+ fileName: sourceMapFileName,
10089
+ source: cloneSourceLike(unchangedSourceMap)
10090
+ });
10091
+ }
9877
10092
  }
9878
10093
  }
9879
10094
  for (const importerFile of importerFiles) importerToChunk.set(importerFile, uniqueFileName);
@@ -9923,12 +10138,12 @@ function applySharedChunkStrategy(bundle, options) {
9923
10138
  if (!isSharedVirtualChunk(fileName, output)) continue;
9924
10139
  const originalSharedFileName = fileName;
9925
10140
  const chunk = output;
9926
- const originalMap = chunk.map;
9927
10141
  const importers = findChunkImporters(bundle, fileName, importerIndex);
9928
10142
  if (importers.length === 0) continue;
9929
10143
  const sourceMapKeys = collectSourceMapKeys(fileName, chunk);
9930
10144
  const sourceMapAssetInfo = findSourceMapAsset(bundle, sourceMapKeys);
9931
- const resolvedSourceMap = resolveSourceMapSource(originalMap, sourceMapAssetInfo?.asset.source);
10145
+ const resolvedSourceMap = resolveEncodedSourceMap(chunk.map, sourceMapAssetInfo?.asset.source);
10146
+ if (resolvedSourceMap) chunk.map = resolvedSourceMap;
9932
10147
  const importerMap = /* @__PURE__ */ new Map();
9933
10148
  const mainImporters = [];
9934
10149
  let hasMainImporter = false;
@@ -9957,17 +10172,17 @@ function applySharedChunkStrategy(bundle, options) {
9957
10172
  let finalFileName = chunk.fileName;
9958
10173
  if (fileName.startsWith(`weapp_shared_virtual/`)) {
9959
10174
  const newFileName = fileName.slice(21);
9960
- chunk.code = rewriteChunkImportSpecifiersInCode(chunk.code ?? "", {
10175
+ const codeRewritten = applyMagicStringChunkRewrite(chunk, createChunkImportSpecifiersRewrite(chunk.code ?? "", {
9961
10176
  sourceFileNames: createChunkSourceFileNameCandidates(fileName),
9962
10177
  targetFileName: newFileName,
9963
10178
  imports: chunk.imports,
9964
10179
  dynamicImports: chunk.dynamicImports,
9965
10180
  runtimeFileName: ROLLDOWN_RUNTIME_FILE_NAME
9966
- });
10181
+ }));
9967
10182
  chunk.fileName = newFileName;
9968
10183
  if (typeof chunk.sourcemapFileName === "string" && chunk.sourcemapFileName) chunk.sourcemapFileName = `${newFileName}.map`;
9969
10184
  const targetKey = `${newFileName}.map`;
9970
- emitSourceMapAsset(this, targetKey, sourceMapAssetInfo, resolvedSourceMap);
10185
+ emitSourceMapAsset(this, targetKey, codeRewritten ? void 0 : sourceMapAssetInfo, resolveSourceMapSource(chunk.map, void 0));
9971
10186
  for (const mapKey of sourceMapKeys) {
9972
10187
  if (!mapKey || mapKey === targetKey) continue;
9973
10188
  if (bundle[mapKey]) delete bundle[mapKey];
@@ -9989,17 +10204,17 @@ function applySharedChunkStrategy(bundle, options) {
9989
10204
  }
9990
10205
  if (shouldRetainOriginalChunk && fileName.startsWith(`weapp_shared_virtual/`)) {
9991
10206
  const newFileName = fileName.slice(21);
9992
- chunk.code = rewriteChunkImportSpecifiersInCode(chunk.code ?? "", {
10207
+ const codeRewritten = applyMagicStringChunkRewrite(chunk, createChunkImportSpecifiersRewrite(chunk.code ?? "", {
9993
10208
  sourceFileNames: createChunkSourceFileNameCandidates(fileName),
9994
10209
  targetFileName: newFileName,
9995
10210
  imports: chunk.imports,
9996
10211
  dynamicImports: chunk.dynamicImports,
9997
10212
  runtimeFileName: ROLLDOWN_RUNTIME_FILE_NAME
9998
- });
10213
+ }));
9999
10214
  chunk.fileName = newFileName;
10000
10215
  if (typeof chunk.sourcemapFileName === "string" && chunk.sourcemapFileName) chunk.sourcemapFileName = `${newFileName}.map`;
10001
10216
  const targetKey = `${newFileName}.map`;
10002
- emitSourceMapAsset(this, targetKey, sourceMapAssetInfo, resolvedSourceMap);
10217
+ emitSourceMapAsset(this, targetKey, codeRewritten ? void 0 : sourceMapAssetInfo, resolveSourceMapSource(chunk.map, void 0));
10003
10218
  for (const mapKey of sourceMapKeys) {
10004
10219
  if (!mapKey || mapKey === targetKey) continue;
10005
10220
  if (bundle[mapKey]) delete bundle[mapKey];
@@ -19593,10 +19808,12 @@ function patchScopedSlotHostAssetForBundle(ctx, fileName, output) {
19593
19808
  if (output.type === "chunk") {
19594
19809
  const current = output.code;
19595
19810
  if (typeof current !== "string") return false;
19596
- const next = withScopedSlotHostProperties(ctx, fileName, current);
19597
- if (next === current) return false;
19598
- output.code = next;
19599
- return true;
19811
+ if (!getScopedSlotGenericKeys(ctx, fileName)?.size || ctx.configService.platform !== "weapp" || current.includes(WEVU_SLOT_OWNER_ID_PROP)) return false;
19812
+ const transformCode = resolveOutputChunkTransformCode(output);
19813
+ const injected = injectScopedSlotHostPropertiesInJs(transformCode, { sourceMap: Boolean(normalizeEncodedSourceMapLike(output.map)) || transformCode !== current });
19814
+ if (injected.transformed) return applyOutputChunkTransform(output, injected.code, injected.map);
19815
+ const propertySource = createScopedSlotHostPropertiesSource();
19816
+ return replaceOutputChunkCode(output, /Component\(\s*\{/, (match) => `${match[0]} properties: { ${propertySource} },`);
19600
19817
  }
19601
19818
  const current = output.source;
19602
19819
  if (typeof current !== "string" && !Buffer.isBuffer(current) && !(current instanceof Uint8Array)) return false;
@@ -22219,7 +22436,13 @@ async function emitEntryOutput(options) {
22219
22436
  if (styleImports.length === 0) return { code };
22220
22437
  const ms = new MagicString(code);
22221
22438
  for (const styleImport of styleImports) ms.prepend(`import '${styleImport}';\n`);
22222
- return { code: ms.toString() };
22439
+ const result = { code: ms.toString() };
22440
+ if (configService.inlineConfig?.build?.sourcemap) result.map = ms.generateMap({
22441
+ hires: true,
22442
+ includeContent: true,
22443
+ source: id
22444
+ });
22445
+ return result;
22223
22446
  }
22224
22447
  //#endregion
22225
22448
  //#region src/plugins/hooks/useLoadEntry/loadEntry/resolve.ts
@@ -23580,9 +23803,9 @@ function removeImplicitPagePreloads(bundle, options, snapshot = createBundleChun
23580
23803
  const targets = targetSet;
23581
23804
  const ranges = findImplicitRequireRemovalRanges(chunk, targets);
23582
23805
  if (!ranges.length) continue;
23583
- const ms = new MagicString(chunk.code);
23584
- for (const { start, end } of ranges) ms.remove(start, end);
23585
- chunk.code = ms.toString();
23806
+ editOutputChunkCode(chunk, (magicString) => {
23807
+ for (const { start, end } of ranges) magicString.remove(start, end);
23808
+ });
23586
23809
  if (Array.isArray(chunk.imports) && chunk.imports.length) chunk.imports = chunk.imports.filter((name) => !targets.has(name));
23587
23810
  if (implicitlyLoaded && implicitlyLoaded.length) chunk.implicitlyLoadedBefore = implicitlyLoaded.filter((name) => !targets.has(name));
23588
23811
  }
@@ -23708,12 +23931,23 @@ function resolveOutputCode(output) {
23708
23931
  if (output.source == null) return;
23709
23932
  return Buffer.from(output.source).toString();
23710
23933
  }
23711
- function updateOutputCode(output, code) {
23712
- if (output.type === "chunk") {
23713
- output.code = code;
23714
- return;
23934
+ function replaceOutputCode(output, pattern, replace) {
23935
+ if (output.type === "chunk") return replaceOutputChunkCode(output, pattern, replace);
23936
+ const code = resolveOutputCode(output);
23937
+ if (typeof code !== "string") return false;
23938
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
23939
+ const matcher = new RegExp(pattern.source, flags);
23940
+ const magicString = new MagicString(code);
23941
+ let changed = false;
23942
+ for (const match of code.matchAll(matcher)) {
23943
+ if (typeof match.index !== "number") continue;
23944
+ const content = replace(match);
23945
+ if (content == null || content === match[0]) continue;
23946
+ magicString.overwrite(match.index, match.index + match[0].length, content);
23947
+ changed = true;
23715
23948
  }
23716
- output.source = code;
23949
+ if (changed) output.source = magicString.toString();
23950
+ return changed;
23717
23951
  }
23718
23952
  function formatNamedRequireBindings(bindings) {
23719
23953
  return bindings.map(({ importedName, localName }) => {
@@ -23797,45 +24031,41 @@ function rewriteWevuInternalRuntimeImports(bundle, options = {}, snapshot = crea
23797
24031
  const fileName = output.fileName;
23798
24032
  if (!fileName.endsWith(".js")) continue;
23799
24033
  if (!mayContainWevuRuntimeImport(code)) continue;
23800
- let rewritten = code;
23801
- let changed = false;
23802
24034
  const requiredRuntimeFileNames = /* @__PURE__ */ new Set();
23803
24035
  let containsRootWevuRuntimeExport;
23804
- rewritten = rewritten.replace(WEVU_RUNTIME_NAMED_IMPORT_RE, (full, importClause, source) => {
24036
+ const changedNamedImports = replaceOutputCode(output, WEVU_RUNTIME_NAMED_IMPORT_RE, (match) => {
24037
+ const [full, importClause, source] = match;
23805
24038
  const bindings = parseNamedImportBindings(importClause);
23806
24039
  const importedNames = bindings.map((binding) => binding.importedName);
23807
24040
  if (source === "wevu") {
23808
24041
  const result = rewriteRootWevuImport(runtimeChunkIndex, fileName, full, bindings, options, requiredRuntimeFileNames);
23809
- changed ||= result.changed;
23810
- return result.code;
24042
+ return result.changed ? result.code : void 0;
23811
24043
  }
23812
24044
  const resolvedInternalModuleId = normalizeWevuRuntimeModuleId(source);
23813
- if (!resolvedInternalModuleId) return full;
24045
+ if (!resolvedInternalModuleId) return;
23814
24046
  const runtimeChunk = resolveWevuRuntimeChunkForModuleId(runtimeChunkIndex, resolvedInternalModuleId, importedNames);
23815
24047
  const rememberedRuntimeFileName = resolveRememberedWevuRuntimeFileName(resolvedInternalModuleId, importedNames, options);
23816
24048
  const runtimeFileName = runtimeChunk?.fileName ?? rememberedRuntimeFileName;
23817
- if (!runtimeFileName) return full;
24049
+ if (!runtimeFileName) return;
23818
24050
  rememberWevuRuntimeChunk(resolvedInternalModuleId, runtimeChunk, options);
23819
- changed = true;
23820
24051
  requiredRuntimeFileNames.add(runtimeFileName);
23821
24052
  const specifier = normalizeRelativeRequireSpecifier(fileName, runtimeFileName);
23822
24053
  return `const { ${formatNamedRequireBindings(bindings)} } = require(${JSON.stringify(specifier)});`;
23823
24054
  });
23824
- rewritten = rewritten.replace(WEVU_RUNTIME_REQUIRE_RE, (full, rawSpecifier) => {
24055
+ const changedRequires = replaceOutputCode(output, WEVU_RUNTIME_REQUIRE_RE, (match) => {
24056
+ const rawSpecifier = match[1];
23825
24057
  const specifierValue = stripQuotes(rawSpecifier);
23826
24058
  if (specifierValue === "wevu" && containsRootWevuRuntimeExport === void 0) containsRootWevuRuntimeExport = containsWevuInternalRuntimeExportReference(code);
23827
24059
  const normalizedModuleId = normalizeWevuRuntimeModuleId(specifierValue);
23828
24060
  const canUseRememberedRuntime = normalizedModuleId === "wevu/internal-runtime" || specifierValue === "wevu" && containsRootWevuRuntimeExport === true;
23829
24061
  const rememberedRuntimeFileName = normalizedModuleId ? options.runtimeFileNames?.get(normalizedModuleId) : void 0;
23830
24062
  const runtimeFileName = canUseRememberedRuntime ? currentRuntimeChunk?.fileName ?? rememberedRuntimeFileName ?? options.runtimeFileName : rememberedRuntimeFileName;
23831
- if (!runtimeFileName) return full;
23832
- changed = true;
24063
+ if (!runtimeFileName) return;
23833
24064
  requiredRuntimeFileNames.add(runtimeFileName);
23834
24065
  const specifier = normalizeRelativeRequireSpecifier(fileName, runtimeFileName);
23835
24066
  return `require(${JSON.stringify(specifier)})`;
23836
24067
  });
23837
- if (!changed) continue;
23838
- updateOutputCode(output, rewritten);
24068
+ if (!changedNamedImports && !changedRequires) continue;
23839
24069
  if (output.type !== "chunk") continue;
23840
24070
  const chunk = output;
23841
24071
  const nextImports = new Set(Array.isArray(chunk.imports) ? chunk.imports : []);
@@ -23970,7 +24200,7 @@ function appendWevuRuntimeExports(chunk, aliases, importedMembers) {
23970
24200
  lines.push(`Object.defineProperty(exports, ${JSON.stringify(member)}, { enumerable: true, get: function() { return ${member}; } });`);
23971
24201
  existingExports.add(member);
23972
24202
  }
23973
- if (lines.length) chunk.code = `${chunk.code}\n${lines.join("\n")}`;
24203
+ if (lines.length) appendOutputChunkCode(chunk, `\n${lines.join("\n")}`);
23974
24204
  }
23975
24205
  function formatSyntheticSinglePageHookExport(exportName) {
23976
24206
  return [
@@ -23990,7 +24220,7 @@ function appendSyntheticWevuHookExports(chunk, importedMembers) {
23990
24220
  lines.push(formatSyntheticSinglePageHookExport(exportName));
23991
24221
  existingExports.add(exportName);
23992
24222
  }
23993
- if (lines.length) chunk.code = `${chunk.code}\n${lines.join("\n")}`;
24223
+ if (lines.length) appendOutputChunkCode(chunk, `\n${lines.join("\n")}`);
23994
24224
  }
23995
24225
  function resolveWevuBaseChunk(bundleOrSnapshot) {
23996
24226
  return resolveWevuInternalChunk(bundleOrSnapshot, ["assertInSetup", "pushHook"]);
@@ -24005,44 +24235,37 @@ function rewriteSyntheticWevuHookAccess(chunk, wevuChunkFileName, baseChunkFileN
24005
24235
  });
24006
24236
  if (!hookNames.length) return;
24007
24237
  const baseRequireSpecifier = normalizeRelativeRequireSpecifier(chunk.fileName, baseChunkFileName);
24008
- let nextCode = chunk.code;
24009
24238
  for (const hookName of hookNames) {
24010
- for (const ref of usage.runtimeRefs) {
24011
- const memberRe = new RegExp(`\\b${escapeRegExp(ref)}\\.${hookName}\\s*\\(`, "g");
24012
- nextCode = nextCode.replace(memberRe, () => {
24013
- return formatSyntheticSinglePageHookFallback(hookName, `${ref}.${hookName}`, baseRequireSpecifier);
24014
- });
24015
- }
24239
+ for (const ref of usage.runtimeRefs) replaceOutputChunkCode(chunk, new RegExp(`\\b${escapeRegExp(ref)}\\.${hookName}\\s*\\(`, "g"), () => {
24240
+ return formatSyntheticSinglePageHookFallback(hookName, `${ref}.${hookName}`, baseRequireSpecifier);
24241
+ });
24016
24242
  if (!usage.inlineMembers.has(hookName)) continue;
24017
- nextCode = nextCode.replace(/require\((`[^`]+`|'[^']+'|"[^"]+")\)\.([A-Za-z_$][\w$]*)\s*\(/g, (full, rawSpecifier, property) => {
24018
- if (property !== hookName) return full;
24019
- if (resolveRequireTarget(chunk.fileName, stripQuotes(rawSpecifier)) !== wevuChunkFileName) return full;
24243
+ replaceOutputChunkCode(chunk, /require\((`[^`]+`|'[^']+'|"[^"]+")\)\.([A-Za-z_$][\w$]*)\s*\(/g, (match) => {
24244
+ const rawSpecifier = match[1];
24245
+ if (match[2] !== hookName) return;
24246
+ if (resolveRequireTarget(chunk.fileName, stripQuotes(rawSpecifier)) !== wevuChunkFileName) return;
24020
24247
  return formatSyntheticSinglePageHookFallback(hookName, `require(${rawSpecifier}).${hookName}`, baseRequireSpecifier);
24021
24248
  });
24022
24249
  }
24023
- chunk.code = nextCode;
24024
24250
  }
24025
24251
  function rewriteStableWevuRuntimeAccess(chunk, wevuChunkFileName, aliases, usage) {
24026
24252
  if (!aliases.size) return;
24027
- let nextCode = chunk.code;
24028
24253
  for (const [exportName, stableName] of WEVU_EXPORT_ALIASES) {
24029
24254
  const localName = aliases.get(exportName);
24030
24255
  if (!localName) continue;
24031
- if (usage.inlineMembers.has(localName) || usage.inlineMembers.has(stableName)) nextCode = nextCode.replace(/require\((`[^`]+`|'[^']+'|"[^"]+")\)\.([A-Za-z_$][\w$]*)\s*\(/g, (full, rawSpecifier, property) => {
24032
- if (property !== localName && property !== stableName) return full;
24033
- if (resolveRequireTarget(chunk.fileName, stripQuotes(rawSpecifier)) !== wevuChunkFileName) return full;
24256
+ if (usage.inlineMembers.has(localName) || usage.inlineMembers.has(stableName)) replaceOutputChunkCode(chunk, /require\((`[^`]+`|'[^']+'|"[^"]+")\)\.([A-Za-z_$][\w$]*)\s*\(/g, (match) => {
24257
+ const rawSpecifier = match[1];
24258
+ const property = match[2];
24259
+ if (property !== localName && property !== stableName) return;
24260
+ if (resolveRequireTarget(chunk.fileName, stripQuotes(rawSpecifier)) !== wevuChunkFileName) return;
24034
24261
  return `(require(${rawSpecifier}).${stableName} || require(${rawSpecifier}).${property})(`;
24035
24262
  });
24036
24263
  if (!usage.members.has(localName) && !usage.members.has(stableName)) continue;
24037
- for (const ref of usage.runtimeRefs) {
24038
- const memberRe = new RegExp(`\\b${escapeRegExp(ref)}\\.(?:${stableName}|${localName})\\s*\\(`, "g");
24039
- nextCode = nextCode.replace(memberRe, (full) => {
24040
- const property = full.includes(`.${stableName}`) ? stableName : localName;
24041
- return `(${ref}.${stableName} || ${ref}.${property})(`;
24042
- });
24043
- }
24264
+ for (const ref of usage.runtimeRefs) replaceOutputChunkCode(chunk, new RegExp(`\\b${escapeRegExp(ref)}\\.(?:${stableName}|${localName})\\s*\\(`, "g"), (match) => {
24265
+ const property = match[0].includes(`.${stableName}`) ? stableName : localName;
24266
+ return `(${ref}.${stableName} || ${ref}.${property})(`;
24267
+ });
24044
24268
  }
24045
- chunk.code = nextCode;
24046
24269
  }
24047
24270
  function stabilizeWevuRuntimeChunkAccess(bundle, snapshot = createBundleChunkSnapshot(bundle)) {
24048
24271
  const wevuChunks = snapshot.wevuChunks;
@@ -24772,14 +24995,8 @@ function createInjectRequestGlobalsCode(targets, options) {
24772
24995
  function createInjectRequestGlobalsSfcCode(targets, options) {
24773
24996
  return `<script${options?.setup ? " setup lang=\"ts\"" : " lang=\"ts\""}>\n${createInjectRequestGlobalsCode(targets, options)}<\/script>\n`;
24774
24997
  }
24775
- function injectCodeIntoSfcBlock(source, startOffset, injection) {
24776
- return `${source.slice(0, startOffset)}${injection}${source.slice(startOffset)}`;
24777
- }
24778
- /**
24779
- * @description 将请求全局对象注入到现有 SFC 脚本块,避免生成额外的重复 `<script>`。
24780
- */
24781
- function injectRequestGlobalsIntoSfc(source, targets, options) {
24782
- if (targets.length === 0) return source;
24998
+ function resolveRequestGlobalsSfcInjection(source, targets, options) {
24999
+ if (targets.length === 0) return null;
24783
25000
  const { descriptor, errors } = parse$1(source, {
24784
25001
  filename: "request-globals.vue",
24785
25002
  ignoreEmpty: false
@@ -24789,19 +25006,42 @@ function injectRequestGlobalsIntoSfc(source, targets, options) {
24789
25006
  localBindings: false
24790
25007
  } : options;
24791
25008
  const injection = createInjectRequestGlobalsCode(targets, injectionOptions);
24792
- if (errors.length > 0) return `${createInjectRequestGlobalsSfcCode(targets, source.includes("<script setup") ? {
24793
- ...options,
24794
- localBindings: false
24795
- } : options)}${source}`;
25009
+ if (errors.length > 0) return {
25010
+ code: createInjectRequestGlobalsSfcCode(targets, source.includes("<script setup") ? {
25011
+ ...options,
25012
+ localBindings: false
25013
+ } : options),
25014
+ index: 0
25015
+ };
24796
25016
  const inlineScript = descriptor.script && !descriptor.script.src ? descriptor.script : void 0;
24797
- if (inlineScript) return injectCodeIntoSfcBlock(source, inlineScript.loc.start.offset, injection);
24798
- if (descriptor.scriptSetup && !descriptor.scriptSetup.src ? descriptor.scriptSetup : void 0) return `${createInjectRequestGlobalsSfcCode(targets, injectionOptions)}${source}`;
24799
- if (!descriptor.script) return `${createInjectRequestGlobalsSfcCode(targets, injectionOptions)}${source}`;
24800
- if (!descriptor.scriptSetup) return `${createInjectRequestGlobalsSfcCode(targets, {
24801
- ...options,
24802
- setup: true
24803
- })}${source}`;
24804
- return source;
25017
+ if (inlineScript) return {
25018
+ code: injection,
25019
+ index: inlineScript.loc.start.offset
25020
+ };
25021
+ if (descriptor.scriptSetup && !descriptor.scriptSetup.src ? descriptor.scriptSetup : void 0) return {
25022
+ code: createInjectRequestGlobalsSfcCode(targets, injectionOptions),
25023
+ index: 0
25024
+ };
25025
+ if (!descriptor.script) return {
25026
+ code: createInjectRequestGlobalsSfcCode(targets, injectionOptions),
25027
+ index: 0
25028
+ };
25029
+ if (!descriptor.scriptSetup) return {
25030
+ code: createInjectRequestGlobalsSfcCode(targets, {
25031
+ ...options,
25032
+ setup: true
25033
+ }),
25034
+ index: 0
25035
+ };
25036
+ return null;
25037
+ }
25038
+ /**
25039
+ * @description 将请求全局对象注入到现有 SFC 脚本块,避免生成额外的重复 `<script>`。
25040
+ */
25041
+ function injectRequestGlobalsIntoSfc(source, targets, options) {
25042
+ const injection = resolveRequestGlobalsSfcInjection(source, targets, options);
25043
+ if (!injection) return source;
25044
+ return `${source.slice(0, injection.index)}${injection.code}${source.slice(injection.index)}`;
24805
25045
  }
24806
25046
  //#endregion
24807
25047
  //#region src/postcss/constants.ts
@@ -25780,6 +26020,7 @@ function createOutputFinalizerPlugin(ctx) {
25780
26020
  normalizePreprocessorStyleAssetEntries(outputBundle, assetEntries.preprocessorStyleAssets, ctx.configService.outputExtensions?.wxss, (asset) => this.emitFile(asset));
25781
26021
  normalizeTemplateAssetEntries(ctx, assetEntries.templateAssets);
25782
26022
  pruneUnchangedDevHmrOutputs(ctx, outputBundle, wevuRuntimeRewriteOptions, { runtimeRewriteDone: true });
26023
+ syncOutputChunkSourceMapAssets(outputBundle);
25783
26024
  }
25784
26025
  }
25785
26026
  };
@@ -26045,43 +26286,6 @@ function rewriteMiniProgramPlatformApiAccess(code, globalName, options) {
26045
26286
  return createMiniProgramPlatformApiRewrite(code, globalName, options)?.toString() ?? code;
26046
26287
  }
26047
26288
  //#endregion
26048
- //#region src/utils/sourcemap.ts
26049
- function isEncodedSourceMapLike(value) {
26050
- return Boolean(value && typeof value === "object" && "version" in value && typeof value.version === "number" && "mappings" in value && "names" in value && "sources" in value);
26051
- }
26052
- function normalizeEncodedSourceMapLike(value) {
26053
- if (!value || typeof value !== "object") return null;
26054
- const sourceMap = value;
26055
- const numericVersion = typeof sourceMap.version === "number" ? sourceMap.version : typeof sourceMap.version === "string" ? Number(sourceMap.version) : NaN;
26056
- if (!Number.isFinite(numericVersion)) return null;
26057
- const normalized = {
26058
- ...sourceMap,
26059
- version: numericVersion
26060
- };
26061
- return isEncodedSourceMapLike(normalized) ? normalized : null;
26062
- }
26063
- function composeSourceMaps(transformedMap, originalMap) {
26064
- if (isEncodedSourceMapLike(transformedMap) && isEncodedSourceMapLike(originalMap)) return remapping([transformedMap, originalMap], () => null);
26065
- if (isEncodedSourceMapLike(transformedMap)) return transformedMap;
26066
- if (isEncodedSourceMapLike(originalMap)) return originalMap;
26067
- return null;
26068
- }
26069
- //#endregion
26070
- //#region src/plugins/core/lifecycle/emit/rewrite/sourcemap.ts
26071
- function applyMagicStringChunkRewrite(chunk, magicString, options) {
26072
- const previousCode = chunk.code;
26073
- const nextCode = magicString.toString();
26074
- if (nextCode === previousCode) return false;
26075
- const previousMap = normalizeEncodedSourceMapLike(chunk.map);
26076
- chunk.code = nextCode;
26077
- if (previousMap) chunk.map = composeSourceMaps(magicString.generateMap({
26078
- hires: options?.hires ?? "boundary",
26079
- includeContent: true,
26080
- source: chunk.fileName
26081
- }), previousMap);
26082
- return true;
26083
- }
26084
- //#endregion
26085
26289
  //#region src/plugins/core/lifecycle/emit/rewrite/platform.ts
26086
26290
  function mayNeedChunkScriptAnalysis(code) {
26087
26291
  if (code.includes("require")) return true;
@@ -26526,7 +26730,11 @@ function injectRequestGlobalsBundleRuntime(bundle, targets, mode, networkDefault
26526
26730
  ...bindingTargets.map((target) => `${REQUEST_GLOBAL_ACTUALS_KEY}[${JSON.stringify(target)}] = ${REQUEST_GLOBAL_BUNDLE_HOST_REF}.${target}`),
26527
26731
  ...bindingTargets.map((target) => `try{globalThis[${JSON.stringify(target)}]=${REQUEST_GLOBAL_BUNDLE_HOST_REF}.${target}}catch{}`)
26528
26732
  ].join(";");
26529
- chunk.code = `${`/* ${REQUEST_GLOBAL_BUNDLE_MARKER} */ ${passiveBindingsCode ? `${passiveBindingsCode}\n` : ""}`}${syntheticExportCode}${chunk.code}\n;${runtimeBindingCode};\n`;
26733
+ const bundlePrelude = `/* ${REQUEST_GLOBAL_BUNDLE_MARKER} */ ${passiveBindingsCode ? `${passiveBindingsCode}\n` : ""}`;
26734
+ editOutputChunkCode(chunk, (magicString) => {
26735
+ magicString.prepend(`${bundlePrelude}${syntheticExportCode}`);
26736
+ magicString.append(`\n;${runtimeBindingCode};\n`);
26737
+ });
26530
26738
  }
26531
26739
  return installerChunks;
26532
26740
  }
@@ -26544,7 +26752,7 @@ function injectRequestGlobalsPassiveBindings(bundle, installerChunks, targets, m
26544
26752
  if (chunkTargets.length === 0) continue;
26545
26753
  const passiveBindingsCode = createRequestGlobalsPassiveBindingsCode(chunkTargets, resolveRequestGlobalsBindingTargets(chunkTargets));
26546
26754
  if (!passiveBindingsCode) continue;
26547
- chunk.code = `/* ${REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER} */ ${passiveBindingsCode}\n${chunk.code}`;
26755
+ prependOutputChunkCode(chunk, `/* ${REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER} */ ${passiveBindingsCode}\n`);
26548
26756
  }
26549
26757
  }
26550
26758
  function injectRequestGlobalsLocalBindings(bundle, installerChunks, targets, mode, entriesMap, networkDefaults) {
@@ -26561,7 +26769,7 @@ function injectRequestGlobalsLocalBindings(bundle, installerChunks, targets, mod
26561
26769
  const bindingTargets = resolveRequestGlobalsBindingTargets(chunkTargets);
26562
26770
  if (bindingTargets.length === 0) continue;
26563
26771
  const inlineInstallerName = resolveRequestGlobalsInstallerName(chunk.code);
26564
- const firstRequireMatch = chunk.code.match(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE);
26772
+ const firstRequireMatch = chunk.code.matchAll(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE).next().value;
26565
26773
  let requireImportLiteral = null;
26566
26774
  let exportName;
26567
26775
  for (const requireMatch of chunk.code.matchAll(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE)) {
@@ -26578,7 +26786,7 @@ function injectRequestGlobalsLocalBindings(bundle, installerChunks, targets, mod
26578
26786
  if (!installerHostExpression) {
26579
26787
  const passiveBindingsCode = createRequestGlobalsPassiveBindingsCode(chunkTargets);
26580
26788
  if (!passiveBindingsCode) continue;
26581
- chunk.code = `/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ ${passiveBindingsCode}\n${chunk.code}`;
26789
+ prependOutputChunkCode(chunk, `/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ ${passiveBindingsCode}\n`);
26582
26790
  continue;
26583
26791
  }
26584
26792
  const injectionCode = [
@@ -26589,11 +26797,16 @@ function injectRequestGlobalsLocalBindings(bundle, installerChunks, targets, mod
26589
26797
  ...bindingTargets.map((target) => `try{globalThis[${JSON.stringify(target)}]=${REQUEST_GLOBAL_CHUNK_HOST_REF}.${target}}catch{}`),
26590
26798
  ...bindingTargets.map((target) => `var ${target} = ${REQUEST_GLOBAL_CHUNK_HOST_REF}.${target}`)
26591
26799
  ].join(";");
26592
- if (inlineInstallerName && firstRequireMatch?.[0]) {
26593
- chunk.code = `/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ ${chunk.code.replace(firstRequireMatch[0], (match) => `${match};${injectionCode}`)}\n`;
26800
+ if (inlineInstallerName && firstRequireMatch?.[0] && typeof firstRequireMatch.index === "number") {
26801
+ const firstRequireIndex = firstRequireMatch.index;
26802
+ editOutputChunkCode(chunk, (magicString) => {
26803
+ magicString.prepend(`/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ `);
26804
+ magicString.overwrite(firstRequireIndex, firstRequireIndex + firstRequireMatch[0].length, `${firstRequireMatch[0]};${injectionCode}`);
26805
+ magicString.append("\n");
26806
+ });
26594
26807
  continue;
26595
26808
  }
26596
- chunk.code = `/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ ${injectionCode};\n${chunk.code}`;
26809
+ prependOutputChunkCode(chunk, `/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ ${injectionCode};\n`);
26597
26810
  }
26598
26811
  }
26599
26812
  function resolveRequestGlobalsInstallerImport(chunk, installerChunks) {
@@ -26636,17 +26849,13 @@ function isRequestGlobalsSupportChunkFileName(fileName) {
26636
26849
  return baseName.startsWith("request-globals-") || baseName === "web-apis-shared.js";
26637
26850
  }
26638
26851
  function rewriteChunkRequireLiteral(chunk, fromFileName, toFileName) {
26639
- let didRewrite = false;
26640
- const nextCode = chunk.code.replaceAll(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE, (...args) => {
26641
- const match = args[0];
26642
- const requireLiteral = args[2];
26643
- const importee = args[3] ?? args[4] ?? args[5];
26644
- if (!requireLiteral || !importee) return match;
26645
- if (normalizeRelativeChunkImport(chunk.fileName, importee) !== fromFileName) return match;
26646
- didRewrite = true;
26647
- return match.replace(requireLiteral, JSON.stringify(toRequireRequestPath(chunk.fileName, toFileName)));
26852
+ replaceOutputChunkCode(chunk, REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE, (match) => {
26853
+ const requireLiteral = match[2];
26854
+ const importee = match[3] ?? match[4] ?? match[5];
26855
+ if (!requireLiteral || !importee) return;
26856
+ if (normalizeRelativeChunkImport(chunk.fileName, importee) !== fromFileName) return;
26857
+ return match[0].replace(requireLiteral, JSON.stringify(toRequireRequestPath(chunk.fileName, toFileName)));
26648
26858
  });
26649
- if (didRewrite) chunk.code = nextCode;
26650
26859
  }
26651
26860
  function hasBareRequireRegistration(code, requirePath) {
26652
26861
  const escapedRequireLiteral = JSON.stringify(requirePath).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -26671,14 +26880,12 @@ function rewriteEmbeddedRequirePaths(code, fromFileName, toFileName) {
26671
26880
  });
26672
26881
  }
26673
26882
  function rewriteChunkRequireCallsToExpression(chunk, targetFileName, expression) {
26674
- let didRewrite = false;
26675
- const nextCode = rewriteRequireCallLiterals(chunk.code, (_requireLiteral, importee) => {
26883
+ return replaceOutputChunkCode(chunk, REQUEST_GLOBAL_REQUIRE_CALL_RE, (match) => {
26884
+ const importee = match[2] ?? match[3] ?? match[4];
26885
+ if (!importee) return;
26676
26886
  if (normalizeRelativeChunkImport(chunk.fileName, importee) !== targetFileName) return;
26677
- didRewrite = true;
26678
26887
  return expression;
26679
26888
  });
26680
- if (didRewrite) chunk.code = nextCode;
26681
- return didRewrite;
26682
26889
  }
26683
26890
  function createRequestGlobalsStaticImportReplacement(node, expression) {
26684
26891
  const declarations = [];
@@ -26717,10 +26924,11 @@ function rewriteChunkStaticImportsToExpression(chunk, targetFileName, expression
26717
26924
  });
26718
26925
  } });
26719
26926
  if (replacements.length === 0) return false;
26720
- let nextCode = chunk.code;
26721
- for (const replacement of replacements.sort((left, right) => right.start - left.start)) nextCode = `${nextCode.slice(0, replacement.start)}${replacement.value}${nextCode.slice(replacement.end)}`;
26722
- chunk.code = nextCode;
26723
- return true;
26927
+ return replaceOutputChunkCodeRanges(chunk, replacements.map((replacement) => ({
26928
+ content: replacement.value,
26929
+ end: replacement.end,
26930
+ start: replacement.start
26931
+ })));
26724
26932
  } catch {
26725
26933
  return false;
26726
26934
  }
@@ -26766,22 +26974,29 @@ function collapseRequestGlobalsRuntimeSupportChunk(bundle) {
26766
26974
  if (!supportChunk || supportChunk.type !== "chunk") return;
26767
26975
  const supportModuleRef = "__wvRGS__";
26768
26976
  const supportRequireIdentifier = runtimeRequireMatch[1];
26769
- runtimeOutput.code = runtimeOutput.code.replace(runtimeRequireMatch[0], `${supportRequireIdentifier} = ${supportModuleRef}`);
26770
- runtimeOutput.code = [
26771
- `const ${supportModuleRef} = (() => {`,
26772
- " const module = { exports: {} }",
26773
- " const exports = module.exports",
26774
- String(supportChunk.code),
26775
- " return module.exports",
26776
- "})();",
26777
- runtimeOutput.code,
26778
- `for (const __wvRGK__ in ${supportModuleRef}) {`,
26779
- " if (__wvRGK__ in exports) {",
26780
- " continue",
26781
- " }",
26782
- ` Object.defineProperty(exports, __wvRGK__, { enumerable: true, get: () => ${supportModuleRef}[__wvRGK__] })`,
26783
- "}"
26784
- ].join("\n");
26977
+ editOutputChunkCode(runtimeOutput, (magicString) => {
26978
+ const runtimeRequireIndex = runtimeRequireMatch.index;
26979
+ if (typeof runtimeRequireIndex !== "number") return;
26980
+ magicString.overwrite(runtimeRequireIndex, runtimeRequireIndex + runtimeRequireMatch[0].length, `${supportRequireIdentifier} = ${supportModuleRef}`);
26981
+ magicString.prepend([
26982
+ `const ${supportModuleRef} = (() => {`,
26983
+ " const module = { exports: {} }",
26984
+ " const exports = module.exports",
26985
+ String(supportChunk.code),
26986
+ " return module.exports",
26987
+ "})();",
26988
+ ""
26989
+ ].join("\n"));
26990
+ magicString.append([
26991
+ "",
26992
+ `for (const __wvRGK__ in ${supportModuleRef}) {`,
26993
+ " if (__wvRGK__ in exports) {",
26994
+ " continue",
26995
+ " }",
26996
+ ` Object.defineProperty(exports, __wvRGK__, { enumerable: true, get: () => ${supportModuleRef}[__wvRGK__] })`,
26997
+ "}"
26998
+ ].join("\n"));
26999
+ });
26785
27000
  delete bundle[supportChunkFileName];
26786
27001
  for (const output of Object.values(bundle)) {
26787
27002
  if (!output || output.type !== "chunk") continue;
@@ -26804,7 +27019,7 @@ function injectRequestGlobalsAppRegistration(bundle, installerChunks) {
26804
27019
  requireStatements.push(`require(${JSON.stringify(requirePath)});`);
26805
27020
  }
26806
27021
  if (requireStatements.length === 0) return;
26807
- appChunk.code = `${requireStatements.join("\n")}\n${appChunk.code}`;
27022
+ prependOutputChunkCode(appChunk, `${requireStatements.join("\n")}\n`);
26808
27023
  }
26809
27024
  function inlineRequestGlobalsAppRegisteredInstallerChunks(bundle, installerChunks, preservedInstallerChunks = /* @__PURE__ */ new Set()) {
26810
27025
  if (installerChunks.size === 0) return;
@@ -26847,7 +27062,7 @@ function inlineRequestGlobalsAppRegisteredInstallerChunks(bundle, installerChunk
26847
27062
  if (!hasPreservedAssetRequire) delete bundle[installerChunkFileName];
26848
27063
  }
26849
27064
  if (inlinedModules.length === 0) return;
26850
- appChunk.code = `${inlinedModules.join("\n")}\n${appChunk.code}`;
27065
+ prependOutputChunkCode(appChunk, `${inlinedModules.join("\n")}\n`);
26851
27066
  }
26852
27067
  function createRequestGlobalsPreludeCode(chunk, installerChunks, targets, mode, networkDefaults) {
26853
27068
  const chunkTargets = resolvePreludeRequestGlobalsTargets(chunk.code, targets, mode);
@@ -26936,7 +27151,7 @@ function injectAxiosFetchAdapterEnv(bundle) {
26936
27151
  const moduleIds = Array.isArray(chunk.moduleIds) ? chunk.moduleIds : [];
26937
27152
  const normalizedFileName = toPosixPath(chunk.fileName);
26938
27153
  if (!(moduleIds.some((id) => AXIOS_MODULE_ID_RE.test(id)) || normalizedFileName === "axios.js" || normalizedFileName.endsWith("/axios.js"))) continue;
26939
- chunk.code = `${chunk.code}\n${axiosEnvPatchCode}`;
27154
+ appendOutputChunkCode(chunk, `\n${axiosEnvPatchCode}`);
26940
27155
  }
26941
27156
  }
26942
27157
  //#endregion
@@ -27697,6 +27912,32 @@ function getCssRealPath(res) {
27697
27912
  return res.filename;
27698
27913
  }
27699
27914
  //#endregion
27915
+ //#region src/utils/codeTransform.ts
27916
+ /**
27917
+ * 对 load/transform 结果执行可追踪编辑,并按需组合已有映射。
27918
+ */
27919
+ function editCodeTransformResult(result, sourceId, edit, options) {
27920
+ const magicString = new MagicString(result.code);
27921
+ edit(magicString, result.code);
27922
+ const code = magicString.toString();
27923
+ if (code === result.code) return result;
27924
+ const previousMap = normalizeEncodedSourceMapLike(result.map);
27925
+ if (!options?.sourceMap && !previousMap) return {
27926
+ ...result,
27927
+ code
27928
+ };
27929
+ const rewriteMap = magicString.generateMap({
27930
+ hires: true,
27931
+ includeContent: true,
27932
+ source: sourceId
27933
+ });
27934
+ return {
27935
+ ...result,
27936
+ code,
27937
+ map: previousMap ? composeSourceMaps(rewriteMap, previousMap) : rewriteMap
27938
+ };
27939
+ }
27940
+ //#endregion
27700
27941
  //#region src/plugins/core/lifecycle/load/requestGlobals.ts
27701
27942
  const NORMAL_SFC_SCRIPT_RE = /<script(?![^>]*setup)[^>]*>/u;
27702
27943
  function resolvePassiveRequestGlobalsTargets(code, requestGlobalsTargets) {
@@ -27714,14 +27955,13 @@ function resolveRequestGlobalsTargetsForCode(code, sourceId, options) {
27714
27955
  }
27715
27956
  function injectRequestGlobalsIntoLoadResult(result, sourceId, targets, options) {
27716
27957
  if (!result || typeof result !== "object" || !("code" in result) || typeof result.code !== "string" || targets.length === 0) return result;
27717
- if (sourceId.endsWith(".vue")) return {
27718
- ...result,
27719
- code: injectRequestGlobalsIntoSfc(result.code, targets, options)
27720
- };
27721
- return {
27722
- ...result,
27723
- code: `${createInjectRequestGlobalsCode(targets, options)}${result.code}`
27724
- };
27958
+ if (sourceId.endsWith(".vue")) {
27959
+ const injection = resolveRequestGlobalsSfcInjection(result.code, targets, options);
27960
+ if (!injection) return result;
27961
+ return editCodeTransformResult(result, sourceId, (magicString) => magicString.appendLeft(injection.index, injection.code), { sourceMap: options?.sourceMap });
27962
+ }
27963
+ const injection = createInjectRequestGlobalsCode(targets, options);
27964
+ return editCodeTransformResult(result, sourceId, (magicString) => magicString.prepend(injection), { sourceMap: options?.sourceMap });
27725
27965
  }
27726
27966
  //#endregion
27727
27967
  //#region src/plugins/core/lifecycle/load/weapi.ts
@@ -28044,7 +28284,10 @@ function createLoadHook(state) {
28044
28284
  function injectRequestGlobalsProfiled(result, sourceId, requestGlobalsTargets, options) {
28045
28285
  const startedAt = performance.now();
28046
28286
  try {
28047
- return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets, options);
28287
+ return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets, {
28288
+ ...options,
28289
+ sourceMap: Boolean(configService.inlineConfig?.build?.sourcemap)
28290
+ });
28048
28291
  } finally {
28049
28292
  recordLoadDuration("requestGlobalsMs", startedAt);
28050
28293
  }
@@ -33281,7 +33524,7 @@ async function loadAppEntry(ctx, scanState) {
33281
33524
  const { path: appEntryPath } = appEntry;
33282
33525
  let configFromVue;
33283
33526
  if (!appConfigFile && vueAppPath) {
33284
- const { extractConfigFromVue } = await import("./file-_4iQaFyw.mjs");
33527
+ const { extractConfigFromVue } = await import("./file-D0RifY1q.mjs");
33285
33528
  configFromVue = await extractConfigFromVue(vueAppPath);
33286
33529
  if (configFromVue) appConfigFile = vueAppPath;
33287
33530
  }
@@ -134,7 +134,7 @@ function resolveAutoRoutesMacroImportPath() {
134
134
  }
135
135
  async function resolveAutoRoutesInlineSnapshot() {
136
136
  try {
137
- const { getCompilerContext } = await import("./getInstance-COmUPo24.mjs");
137
+ const { getCompilerContext } = await import("./getInstance-Czvi9cUi.mjs");
138
138
  const compilerContext = getCompilerContext();
139
139
  const service = compilerContext.autoRoutesService;
140
140
  const reference = service?.getReference?.();
@@ -0,0 +1,2 @@
1
+ import { t as extractConfigFromVue } from "./file-AiMZtyLe.mjs";
2
+ export { extractConfigFromVue };
@@ -0,0 +1,2 @@
1
+ import { n as getCompilerContext } from "./createContext-DavT7XIA.mjs";
2
+ export { getCompilerContext };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { a as defineThemeJson, i as defineSitemapJson, n as defineComponentJson, r as definePageJson, t as defineAppJson } from "./json-BL8Dhhk6.mjs";
2
2
  import { a as resolveWeappViteHostMeta, i as isWeappViteHost, n as applyWeappViteHostMeta, r as createWeappViteHostMeta, t as WEAPP_VITE_HOST_NAME } from "./pluginHost--CaeyWpA.mjs";
3
3
  import { t as defineConfig } from "./config-DRGcCi3h.mjs";
4
- import { c as getSupportedWeappViteTargetDescriptors, l as isWebPlatform, o as WEB_PLATFORM_ALIASES, s as getSupportedWeappVitePlatforms, t as createCompilerContext, u as resolveWeappViteTarget } from "./createContext-DiBG4uOB.mjs";
4
+ import { c as getSupportedWeappViteTargetDescriptors, l as isWebPlatform, o as WEB_PLATFORM_ALIASES, s as getSupportedWeappVitePlatforms, t as createCompilerContext, u as resolveWeappViteTarget } from "./createContext-DavT7XIA.mjs";
5
5
  import { a as resolveLayoutHost, c as createWevuComponent, i as registerLayoutHosts, n as defineProps, o as unregisterLayoutHosts, r as setPageLayout, s as waitForLayoutHost, t as defineEmits } from "./runtime-D6VCNhNY.mjs";
6
6
  export { WEAPP_VITE_HOST_NAME, WEB_PLATFORM_ALIASES, applyWeappViteHostMeta, createCompilerContext, createWeappViteHostMeta, createWevuComponent, defineAppJson, defineComponentJson, defineConfig, defineEmits, definePageJson, defineProps, defineSitemapJson, defineThemeJson, getSupportedWeappVitePlatforms, getSupportedWeappViteTargetDescriptors, isWeappViteHost, isWebPlatform, registerLayoutHosts, resolveLayoutHost, resolveWeappViteHostMeta, resolveWeappViteTarget, setPageLayout, unregisterLayoutHosts, waitForLayoutHost };
package/dist/test.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { t as createCompilerContext } from "./createContext-DiBG4uOB.mjs";
1
+ import { t as createCompilerContext } from "./createContext-DavT7XIA.mjs";
2
2
  import path from "node:path";
3
3
  import process from "node:process";
4
4
  import chokidar from "chokidar";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "weapp-vite",
3
3
  "type": "module",
4
- "version": "6.20.2",
4
+ "version": "6.20.3",
5
5
  "description": "weapp-vite 一个现代化的小程序打包工具",
6
6
  "author": "ice breaker <1324318532@qq.com>",
7
7
  "license": "MIT",
@@ -128,21 +128,21 @@
128
128
  "vue": "^3.5.41",
129
129
  "vue-tsc": "^3.3.9",
130
130
  "@weapp-core/constants": "0.1.17",
131
- "@weapp-core/logger": "3.1.1",
132
131
  "@weapp-core/init": "6.0.14",
132
+ "@weapp-core/logger": "3.1.1",
133
133
  "@weapp-core/schematics": "6.1.0",
134
134
  "@weapp-core/shared": "3.1.1",
135
- "@weapp-vite/ast": "6.20.2",
135
+ "@weapp-vite/ast": "6.20.3",
136
136
  "@weapp-vite/mcp": "1.4.14",
137
137
  "@weapp-vite/miniprogram-automator": "1.2.13",
138
138
  "@weapp-vite/volar": "2.1.3",
139
- "@weapp-vite/web": "1.4.7",
139
+ "@weapp-vite/web": "1.4.8",
140
140
  "@wevu/api": "0.2.16",
141
141
  "@wevu/web-apis": "1.2.34",
142
142
  "rolldown-require": "2.0.25",
143
143
  "vite-plugin-performance": "2.0.1",
144
144
  "weapp-ide-cli": "6.0.6",
145
- "wevu": "6.20.2"
145
+ "wevu": "6.20.3"
146
146
  },
147
147
  "publishConfig": {
148
148
  "access": "public",
@@ -1,2 +0,0 @@
1
- import { t as extractConfigFromVue } from "./file-DQ5FlYd5.mjs";
2
- export { extractConfigFromVue };
@@ -1,2 +0,0 @@
1
- import { n as getCompilerContext } from "./createContext-DiBG4uOB.mjs";
2
- export { getCompilerContext };