weapp-vite 6.20.2 → 6.20.4

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-DoH-W4mj.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-DoH-W4mj.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-DnVj_L9_.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";
@@ -3654,7 +3654,10 @@ async function readLatestHmrProfileSummary(options) {
3654
3654
  //#region src/cli/commands/ide.ts
3655
3655
  async function runIdeDoctor(projectPath, options) {
3656
3656
  const resolvedCli = await resolveCliPath();
3657
- const servicePort = await detectWechatDevtoolsServicePort().catch((error) => ({
3657
+ const servicePort = await detectWechatDevtoolsServicePort().then((result) => ({
3658
+ ...result,
3659
+ error: void 0
3660
+ })).catch((error) => ({
3658
3661
  servicePortEnabled: void 0,
3659
3662
  servicePort: void 0,
3660
3663
  error
@@ -3810,50 +3813,51 @@ async function runIdeCommand(action, root, options) {
3810
3813
  cliPlatform: targets.rawPlatform
3811
3814
  });
3812
3815
  if (action !== "doctor" && resolved.platform !== "weapp") throw new Error("`weapp-vite ide logs` 当前仅支持微信小程序平台。");
3813
- if (action !== "doctor" && !resolved.projectPath) throw new Error("无法解析微信开发者工具项目目录,请显式传入 root 或检查 project.config.json。");
3814
3816
  if (action === "doctor") {
3815
3817
  await runIdeDoctor(resolved.projectPath, options);
3816
3818
  return;
3817
3819
  }
3820
+ const projectPath = resolved.projectPath;
3821
+ if (!projectPath) throw new Error("无法解析微信开发者工具项目目录,请显式传入 root 或检查 project.config.json。");
3818
3822
  if (action === "setup") {
3819
3823
  const result = await bootstrapWechatDevtoolsSettings({
3820
- projectPath: resolved.projectPath,
3824
+ projectPath,
3821
3825
  trustProject: options.trustProject
3822
3826
  });
3823
3827
  logger_default.info(`已完成微信开发者工具配置预热:扫描实例 ${result.touchedInstanceCount} 个,检测服务端口配置 ${result.detectedSecurityCount} 处,写入项目信任 ${result.trustedProjectCount} 处。`);
3824
3828
  return;
3825
3829
  }
3826
- if (options.open) await openIde(resolved.platform, resolved.projectPath, {
3830
+ if (options.open) await openIde(resolved.platform, projectPath, {
3827
3831
  openRecovery: options.openRecovery,
3828
3832
  trustProject: options.trustProject,
3829
3833
  openStrategy: options.ideOpenStrategy
3830
3834
  });
3831
3835
  if (action === "info") {
3832
- const result = await getWechatIdeToolInfo({ projectPath: resolved.projectPath });
3836
+ const result = await getWechatIdeToolInfo({ projectPath });
3833
3837
  logger_default.info(formatIdeOutput(result, options));
3834
3838
  return;
3835
3839
  }
3836
3840
  if (action === "test-accounts") {
3837
- const result = await getWechatIdeTestAccounts({ projectPath: resolved.projectPath });
3841
+ const result = await getWechatIdeTestAccounts({ projectPath });
3838
3842
  logger_default.info(formatIdeOutput(result, options));
3839
3843
  return;
3840
3844
  }
3841
3845
  if (action === "ticket") {
3842
- const result = await getWechatIdeTicket({ projectPath: resolved.projectPath });
3846
+ const result = await getWechatIdeTicket({ projectPath });
3843
3847
  logger_default.info(formatIdeOutput(result, options));
3844
3848
  return;
3845
3849
  }
3846
3850
  if (action === "ticket:set") {
3847
3851
  if (!options.ticket) throw new Error("`weapp-vite ide ticket:set` 需要提供 --ticket。");
3848
3852
  await setWechatIdeTicket({
3849
- projectPath: resolved.projectPath,
3853
+ projectPath,
3850
3854
  ticket: options.ticket
3851
3855
  });
3852
3856
  logger_default.info(`已设置微信开发者工具 ticket:${options.ticket}`);
3853
3857
  return;
3854
3858
  }
3855
3859
  if (action === "ticket:refresh") {
3856
- await refreshWechatIdeTicket({ projectPath: resolved.projectPath });
3860
+ await refreshWechatIdeTicket({ projectPath });
3857
3861
  logger_default.info("已刷新微信开发者工具 ticket。");
3858
3862
  return;
3859
3863
  }
@@ -3871,8 +3875,8 @@ async function runIdeCommand(action, root, options) {
3871
3875
  });
3872
3876
  if (latestHmrSummary) logger_default.info(latestHmrSummary.line);
3873
3877
  const session = await startForwardConsoleBridge({
3874
- projectPath: resolved.projectPath,
3875
- port: resolveProjectAutomatorPort(resolved.projectPath),
3878
+ projectPath,
3879
+ port: resolveProjectAutomatorPort(projectPath),
3876
3880
  agentName: void 0,
3877
3881
  logLevels: forwardConsoleOptions.logLevels,
3878
3882
  unhandledErrors: forwardConsoleOptions.unhandledErrors,
@@ -4727,7 +4731,7 @@ function resolveRunnableHotkeyDefinition(input) {
4727
4731
  }
4728
4732
  //#endregion
4729
4733
  //#region package.json
4730
- var version = "6.20.2";
4734
+ var version = "6.20.4";
4731
4735
  //#endregion
4732
4736
  //#region src/cli/devHotkeys/format.ts
4733
4737
  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-DnVj_L9_.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
@@ -263,6 +263,11 @@ function createModuleGraphService() {
263
263
  let topologyRescan;
264
264
  const entryDependencies = /* @__PURE__ */ new Map();
265
265
  const pendingChanges = /* @__PURE__ */ new Map();
266
+ const hasRegisteredEntryDependency = (file) => {
267
+ if (entryDependencies.has(file)) return true;
268
+ for (const dependenciesByKind of entryDependencies.values()) for (const sourceIds of dependenciesByKind.values()) if (sourceIds.has(file)) return true;
269
+ return false;
270
+ };
266
271
  const collectFromBuildGraph = (file, affected) => {
267
272
  for (const buildContext of buildContexts.values()) {
268
273
  if (typeof buildContext.getModuleInfo !== "function") continue;
@@ -368,6 +373,7 @@ function createModuleGraphService() {
368
373
  },
369
374
  hasModule(rawFile) {
370
375
  const file = normalizeSourceId(rawFile);
376
+ if (hasRegisteredEntryDependency(file)) return true;
371
377
  if (devServer) return collectDevStartNodes(devServer, file).size > 0;
372
378
  return Array.from(buildContexts.values()).some((context) => collectBuildStartIds(context, file).size > 0);
373
379
  },
@@ -9067,17 +9073,174 @@ function setCachedSharedChunkName(moduleId, value) {
9067
9073
  sharedChunkNameCache.set(moduleId, value ?? null);
9068
9074
  }
9069
9075
  //#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);
9076
+ //#region src/utils/sourcemap.ts
9077
+ function isEncodedSourceMapLike(value) {
9078
+ return Boolean(value && typeof value === "object" && "version" in value && typeof value.version === "number" && "mappings" in value && "names" in value && "sources" in value);
9079
+ }
9080
+ function normalizeEncodedSourceMapLike(value) {
9081
+ if (!value || typeof value !== "object") return null;
9082
+ const sourceMap = value;
9083
+ const numericVersion = typeof sourceMap.version === "number" ? sourceMap.version : typeof sourceMap.version === "string" ? Number(sourceMap.version) : NaN;
9084
+ if (!Number.isFinite(numericVersion)) return null;
9085
+ const normalized = {
9086
+ ...sourceMap,
9087
+ version: numericVersion
9088
+ };
9089
+ return isEncodedSourceMapLike(normalized) ? normalized : null;
9090
+ }
9091
+ function composeSourceMaps(transformedMap, originalMap) {
9092
+ if (isEncodedSourceMapLike(transformedMap) && isEncodedSourceMapLike(originalMap)) return remapping([transformedMap, originalMap], () => null);
9093
+ if (isEncodedSourceMapLike(transformedMap)) return transformedMap;
9094
+ if (isEncodedSourceMapLike(originalMap)) return originalMap;
9095
+ return null;
9096
+ }
9097
+ //#endregion
9098
+ //#region src/utils/outputChunk.ts
9099
+ const INLINE_SOURCE_MAP_RE = /\n?\/\/[#@]\s*sourceMappingURL=(data:application\/json\S*)\s*$/u;
9100
+ function resolveInlineSourceMap(code) {
9101
+ const match = INLINE_SOURCE_MAP_RE.exec(code);
9102
+ if (typeof match?.index !== "number") return null;
9103
+ const dataUrl = match[1];
9104
+ const commaIndex = dataUrl.indexOf(",");
9105
+ if (commaIndex < 0) return null;
9106
+ try {
9107
+ const metadata = dataUrl.slice(0, commaIndex);
9108
+ const payload = dataUrl.slice(commaIndex + 1);
9109
+ const json = metadata.includes(";base64") ? Buffer.from(payload, "base64").toString("utf8") : decodeURIComponent(payload);
9110
+ const map = normalizeEncodedSourceMapLike(JSON.parse(json));
9111
+ return map ? {
9112
+ code: code.slice(0, match.index),
9113
+ map,
9114
+ start: match.index
9115
+ } : null;
9116
+ } catch {
9117
+ return null;
9078
9118
  }
9079
- return source;
9080
9119
  }
9120
+ function appendInlineSourceMap(code, map) {
9121
+ return `${code}${code.endsWith("\n") ? "" : "\n"}//# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(JSON.stringify(map)).toString("base64")}`;
9122
+ }
9123
+ /**
9124
+ * 返回不含 inline sourcemap 数据 URI 的实际脚本,供 AST 转换使用。
9125
+ */
9126
+ function resolveOutputChunkTransformCode(chunk) {
9127
+ return resolveInlineSourceMap(chunk.code)?.code ?? chunk.code;
9128
+ }
9129
+ /**
9130
+ * 应用 MagicString 改写,并把本轮映射与 chunk 既有映射组合。
9131
+ */
9132
+ function applyMagicStringChunkRewrite(chunk, magicString, options) {
9133
+ const previousCode = chunk.code;
9134
+ const inlineSourceMap = resolveInlineSourceMap(previousCode);
9135
+ if (inlineSourceMap) magicString.remove(inlineSourceMap.start, previousCode.length);
9136
+ const nextCode = magicString.toString();
9137
+ if (nextCode === (inlineSourceMap?.code ?? previousCode)) return false;
9138
+ const previousMap = normalizeEncodedSourceMapLike(chunk.map) ?? inlineSourceMap?.map;
9139
+ if (previousMap) {
9140
+ const composedMap = composeSourceMaps(magicString.generateMap({
9141
+ hires: options?.hires ?? "boundary",
9142
+ includeContent: true,
9143
+ source: chunk.fileName
9144
+ }), previousMap);
9145
+ chunk.map = composedMap;
9146
+ chunk.code = inlineSourceMap && composedMap ? appendInlineSourceMap(nextCode, composedMap) : nextCode;
9147
+ } else chunk.code = nextCode;
9148
+ return true;
9149
+ }
9150
+ /**
9151
+ * 在 chunk 当前代码上执行一次可追踪编辑。
9152
+ */
9153
+ function editOutputChunkCode(chunk, edit, options) {
9154
+ const code = chunk.code;
9155
+ const magicString = new MagicString(code);
9156
+ edit(magicString, code);
9157
+ return applyMagicStringChunkRewrite(chunk, magicString, options);
9158
+ }
9159
+ /**
9160
+ * 在 chunk 前方插入无源代码,同时保留原代码映射。
9161
+ */
9162
+ function prependOutputChunkCode(chunk, code) {
9163
+ if (!code) return false;
9164
+ return editOutputChunkCode(chunk, (magicString) => magicString.prepend(code));
9165
+ }
9166
+ /**
9167
+ * 在 chunk 后方插入无源代码,同时保留原代码映射。
9168
+ */
9169
+ function appendOutputChunkCode(chunk, code) {
9170
+ if (!code) return false;
9171
+ return editOutputChunkCode(chunk, (magicString) => magicString.append(code));
9172
+ }
9173
+ /**
9174
+ * 按原始代码坐标批量替换互不重叠的区间。
9175
+ */
9176
+ function replaceOutputChunkCodeRanges(chunk, replacements) {
9177
+ if (replacements.length === 0) return false;
9178
+ const sorted = [...replacements].sort((left, right) => left.start - right.start);
9179
+ let previousEnd = -1;
9180
+ for (const replacement of sorted) {
9181
+ 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}`);
9182
+ previousEnd = replacement.end;
9183
+ }
9184
+ return editOutputChunkCode(chunk, (magicString) => {
9185
+ for (const replacement of sorted) magicString.overwrite(replacement.start, replacement.end, replacement.content);
9186
+ });
9187
+ }
9188
+ /**
9189
+ * 使用正则匹配的原始坐标改写 chunk,避免整段字符串替换破坏映射。
9190
+ */
9191
+ function replaceOutputChunkCode(chunk, pattern, replace) {
9192
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
9193
+ const matcher = new RegExp(pattern.source, flags);
9194
+ const replacements = [];
9195
+ for (const match of chunk.code.matchAll(matcher)) {
9196
+ if (typeof match.index !== "number") continue;
9197
+ const content = replace(match);
9198
+ if (content == null || content === match[0]) continue;
9199
+ replacements.push({
9200
+ content,
9201
+ end: match.index + match[0].length,
9202
+ start: match.index
9203
+ });
9204
+ }
9205
+ return replaceOutputChunkCodeRanges(chunk, replacements);
9206
+ }
9207
+ /**
9208
+ * 应用自带映射的完整代码转换,并组合 chunk 既有映射。
9209
+ */
9210
+ function applyOutputChunkTransform(chunk, code, map) {
9211
+ const previousInlineSourceMap = resolveInlineSourceMap(chunk.code);
9212
+ const transformedInlineSourceMap = resolveInlineSourceMap(code);
9213
+ const previousCode = previousInlineSourceMap?.code ?? chunk.code;
9214
+ const transformedCode = transformedInlineSourceMap?.code ?? code;
9215
+ if (transformedCode === previousCode) return false;
9216
+ const previousMap = normalizeEncodedSourceMapLike(chunk.map) ?? previousInlineSourceMap?.map;
9217
+ const transformedMap = normalizeEncodedSourceMapLike(map);
9218
+ if (previousMap && !transformedMap) throw new Error(`Output chunk transform for ${chunk.fileName} must provide a source map`);
9219
+ if (previousMap && transformedMap) {
9220
+ const composedMap = composeSourceMaps(transformedMap, previousMap);
9221
+ chunk.map = composedMap;
9222
+ chunk.code = previousInlineSourceMap && composedMap ? appendInlineSourceMap(transformedCode, composedMap) : transformedCode;
9223
+ } else chunk.code = transformedCode;
9224
+ return true;
9225
+ }
9226
+ /**
9227
+ * 将 generateBundle 阶段组合后的 chunk map 提交到 Rolldown 管理的 map asset。
9228
+ */
9229
+ function syncOutputChunkSourceMapAssets(bundle) {
9230
+ let synced = 0;
9231
+ for (const output of Object.values(bundle)) {
9232
+ if (output?.type !== "chunk") continue;
9233
+ const map = normalizeEncodedSourceMapLike(output.map);
9234
+ if (!map) continue;
9235
+ const mapAsset = bundle[output.sourcemapFileName ?? `${output.fileName}.map`];
9236
+ if (!mapAsset || mapAsset.type !== "asset") continue;
9237
+ mapAsset.source = JSON.stringify(map);
9238
+ synced += 1;
9239
+ }
9240
+ return synced;
9241
+ }
9242
+ //#endregion
9243
+ //#region src/runtime/chunkStrategy/utils.ts
9081
9244
  function createRelativeImport(fromFile, toFile) {
9082
9245
  const relative = posix.relative(posix.dirname(fromFile), toFile);
9083
9246
  if (!relative || relative.startsWith(".")) return relative || "./";
@@ -9085,6 +9248,20 @@ function createRelativeImport(fromFile, toFile) {
9085
9248
  }
9086
9249
  //#endregion
9087
9250
  //#region src/runtime/chunkStrategy/bundle.ts
9251
+ function escapeRegExp$2(value) {
9252
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9253
+ }
9254
+ function replaceChunkCodeAll(chunk, searchValue, replaceValue) {
9255
+ if (!searchValue) return false;
9256
+ const replaceExact = () => replaceOutputChunkCode(chunk, new RegExp(escapeRegExp$2(searchValue), "g"), () => replaceValue);
9257
+ if (chunk.code.includes(searchValue)) return replaceExact();
9258
+ if (searchValue.startsWith("./") && replaceValue.startsWith("./")) {
9259
+ const trimmedSearch = searchValue.slice(2);
9260
+ const trimmedReplace = replaceValue.slice(2);
9261
+ if (trimmedSearch && chunk.code.includes(trimmedSearch)) return replaceOutputChunkCode(chunk, new RegExp(escapeRegExp$2(trimmedSearch), "g"), () => trimmedReplace);
9262
+ }
9263
+ return false;
9264
+ }
9088
9265
  function addDirectImporter(directImporters, imported, importer) {
9089
9266
  if (typeof imported !== "string" || !imported || imported === importer) return;
9090
9267
  let importers = directImporters.get(imported);
@@ -9346,11 +9523,7 @@ function updateImporters(bundle, importerToChunk, originalFileName, index) {
9346
9523
  for (const originalFileName of originalFileNames) {
9347
9524
  const originalImportPath = createRelativeImport(importerFile, originalFileName);
9348
9525
  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
- }
9526
+ codeUpdated = replaceChunkCodeAll(importerChunk, originalImportPath, newImportPath) || codeUpdated;
9354
9527
  }
9355
9528
  importerChunk.imports = replaceInArray(importerChunk.imports, originalFileNames, newChunkFile, codeUpdated);
9356
9529
  importerChunk.dynamicImports = replaceInArray(importerChunk.dynamicImports, originalFileNames, newChunkFile, codeUpdated);
@@ -9526,6 +9699,17 @@ function resolveSourceMapSource(originalMap, assetSource) {
9526
9699
  }
9527
9700
  if (isSourceLike(assetSource)) return cloneSourceLike(assetSource);
9528
9701
  }
9702
+ function resolveEncodedSourceMap(originalMap, assetSource) {
9703
+ const chunkMap = normalizeEncodedSourceMapLike(originalMap);
9704
+ if (chunkMap) return chunkMap;
9705
+ if (!isSourceLike(assetSource)) return null;
9706
+ try {
9707
+ const source = typeof assetSource === "string" ? assetSource : Buffer.from(assetSource).toString("utf8");
9708
+ return normalizeEncodedSourceMapLike(JSON.parse(source));
9709
+ } catch {
9710
+ return null;
9711
+ }
9712
+ }
9529
9713
  function emitSourceMapAsset(ctx, targetFileName, sourceMapAssetInfo, fallbackSource) {
9530
9714
  if (!targetFileName) return;
9531
9715
  if (sourceMapAssetInfo?.asset && isSourceLike(sourceMapAssetInfo.asset.source)) {
@@ -9683,29 +9867,39 @@ function reserveUniqueFileName(reservedFileNames, fileName) {
9683
9867
  reservedFileNames.add(candidate);
9684
9868
  return candidate;
9685
9869
  }
9686
- function rewriteChunkImportSpecifiersInCode(sourceCode, options) {
9870
+ function createChunkImportSpecifiersRewrite(sourceCode, options) {
9687
9871
  const { sourceFileName, sourceFileNames, targetFileName, imports, dynamicImports, runtimeFileName, resolveImportTarget } = options;
9688
9872
  const sourceFileNameCandidates = (sourceFileNames ?? [sourceFileName ?? ""]).filter(Boolean);
9689
9873
  const specifiers = new Set([...imports, ...dynamicImports].filter(Boolean));
9690
- let rewrittenCode = sourceCode;
9874
+ const magicString = new MagicString(sourceCode);
9875
+ const rewrittenRanges = /* @__PURE__ */ new Set();
9691
9876
  for (const specifier of specifiers) {
9692
9877
  const targetImportPath = createRelativeImportPath(targetFileName, posix.basename(specifier) === ROLLDOWN_RUNTIME_FILE_NAME$1 ? runtimeFileName : resolveImportTarget?.(specifier) ?? specifier);
9693
9878
  if (!targetImportPath) continue;
9694
9879
  for (const sourceCandidate of sourceFileNameCandidates) {
9695
9880
  const sourceImportPath = createRelativeImportPath(sourceCandidate, specifier);
9696
9881
  if (!sourceImportPath || sourceImportPath === targetImportPath) continue;
9697
- rewrittenCode = replaceQuotedImportLiteralValue(rewrittenCode, sourceImportPath, targetImportPath);
9882
+ replaceQuotedImportLiteralValue(magicString, sourceCode, sourceImportPath, targetImportPath, rewrittenRanges);
9698
9883
  }
9699
9884
  }
9700
- return rewrittenCode;
9885
+ return magicString;
9701
9886
  }
9702
9887
  function resolveChunkSourceFileNameForRewrite(fileName) {
9703
9888
  if (!fileName.startsWith(`weapp_shared_virtual/`)) return fileName;
9704
9889
  return fileName.slice(21);
9705
9890
  }
9706
- function replaceQuotedImportLiteralValue(sourceCode, sourcePath, targetPath) {
9891
+ function replaceQuotedImportLiteralValue(magicString, sourceCode, sourcePath, targetPath, rewrittenRanges) {
9707
9892
  const escapedSourcePath = escapeRegExpForPattern(sourcePath);
9708
- return sourceCode.replace(new RegExp(`(['"\`])${escapedSourcePath}\\1`, "g"), (_match, quote) => `${quote}${targetPath}${quote}`);
9893
+ const pattern = new RegExp(`(['"\`])${escapedSourcePath}\\1`, "g");
9894
+ for (const match of sourceCode.matchAll(pattern)) {
9895
+ if (typeof match.index !== "number") continue;
9896
+ const end = match.index + match[0].length;
9897
+ const rangeKey = `${match.index}:${end}`;
9898
+ if (rewrittenRanges.has(rangeKey)) continue;
9899
+ const quote = match[1];
9900
+ magicString.overwrite(match.index, end, `${quote}${targetPath}${quote}`);
9901
+ rewrittenRanges.add(rangeKey);
9902
+ }
9709
9903
  }
9710
9904
  function escapeRegExpForPattern(value) {
9711
9905
  return value.replace(REGEXP_ESCAPE_PATTERN, "\\$&");
@@ -9744,7 +9938,13 @@ function ensureLocalizedDuplicate(args) {
9744
9938
  }
9745
9939
  function rewriteDuplicatedChunkSource(args) {
9746
9940
  const runtimeFileName = posix.join(args.root, ROLLDOWN_RUNTIME_FILE_NAME);
9747
- let rewrittenSource = rewriteChunkImportSpecifiersInCode(args.chunk.code ?? "", {
9941
+ const sourceMapKeys = collectSourceMapKeys(args.sourceFileName, args.chunk);
9942
+ const sourceMapAssetInfo = findSourceMapAsset(args.runtimeContext.bundle, sourceMapKeys);
9943
+ const rewrittenChunk = {
9944
+ ...args.chunk,
9945
+ map: resolveEncodedSourceMap(args.chunk.map, sourceMapAssetInfo?.asset.source)
9946
+ };
9947
+ applyMagicStringChunkRewrite(rewrittenChunk, createChunkImportSpecifiersRewrite(rewrittenChunk.code ?? "", {
9748
9948
  sourceFileNames: createChunkSourceFileNameCandidates(args.sourceFileName),
9749
9949
  targetFileName: args.targetFileName,
9750
9950
  imports: args.chunk.imports,
@@ -9758,7 +9958,7 @@ function rewriteDuplicatedChunkSource(args) {
9758
9958
  sourceFileName: specifier
9759
9959
  });
9760
9960
  }
9761
- });
9961
+ }));
9762
9962
  for (const specifier of [...args.chunk.imports, ...args.chunk.dynamicImports]) {
9763
9963
  const localizedSpecifier = ensureLocalizedDuplicate({
9764
9964
  runtimeContext: args.runtimeContext,
@@ -9767,20 +9967,20 @@ function rewriteDuplicatedChunkSource(args) {
9767
9967
  sourceFileName: specifier
9768
9968
  });
9769
9969
  if (!localizedSpecifier || localizedSpecifier === specifier) continue;
9770
- rewrittenSource = rewriteChunkImportSpecifiersInCode(rewrittenSource, {
9970
+ applyMagicStringChunkRewrite(rewrittenChunk, createChunkImportSpecifiersRewrite(rewrittenChunk.code, {
9771
9971
  sourceFileName: args.targetFileName,
9772
9972
  targetFileName: args.targetFileName,
9773
9973
  imports: [specifier],
9774
9974
  dynamicImports: [],
9775
9975
  runtimeFileName,
9776
9976
  resolveImportTarget: () => localizedSpecifier
9777
- });
9977
+ }));
9778
9978
  }
9779
- return rewrittenSource;
9979
+ return rewrittenChunk;
9780
9980
  }
9781
9981
  function emitDuplicatedChunkAsset(args) {
9782
9982
  if (args.emittedLocalizedDuplicateFiles.has(args.targetFileName)) return;
9783
- const duplicatedSource = rewriteDuplicatedChunkSource({
9983
+ const duplicatedChunk = rewriteDuplicatedChunkSource({
9784
9984
  runtimeContext: args.runtimeContext,
9785
9985
  pendingLocalizedDuplicates: args.pendingLocalizedDuplicates,
9786
9986
  root: args.root,
@@ -9791,17 +9991,24 @@ function emitDuplicatedChunkAsset(args) {
9791
9991
  args.runtimeContext.pluginContext.emitFile({
9792
9992
  type: "asset",
9793
9993
  fileName: args.targetFileName,
9794
- source: duplicatedSource
9994
+ source: duplicatedChunk.code
9795
9995
  });
9796
9996
  const sourceMapKeys = collectSourceMapKeys(args.sourceFileName, args.chunk);
9797
9997
  const sourceMapAssetInfo = findSourceMapAsset(args.runtimeContext.bundle, sourceMapKeys);
9798
- const resolvedSourceMap = resolveSourceMapSource(args.chunk.map, sourceMapAssetInfo?.asset.source);
9799
- if (resolvedSourceMap) {
9998
+ const unchangedSourceMap = duplicatedChunk.code === args.chunk.code ? resolveSourceMapSource(args.chunk.map, sourceMapAssetInfo?.asset.source) : void 0;
9999
+ if (duplicatedChunk.map) {
10000
+ const sourceMapFileName = reserveUniqueFileName(args.runtimeContext.reservedFileNames, `${args.targetFileName}.map`);
10001
+ args.runtimeContext.pluginContext.emitFile({
10002
+ type: "asset",
10003
+ fileName: sourceMapFileName,
10004
+ source: JSON.stringify(duplicatedChunk.map)
10005
+ });
10006
+ } else if (unchangedSourceMap) {
9800
10007
  const sourceMapFileName = reserveUniqueFileName(args.runtimeContext.reservedFileNames, `${args.targetFileName}.map`);
9801
10008
  args.runtimeContext.pluginContext.emitFile({
9802
10009
  type: "asset",
9803
10010
  fileName: sourceMapFileName,
9804
- source: cloneSourceLike(resolvedSourceMap)
10011
+ source: cloneSourceLike(unchangedSourceMap)
9805
10012
  });
9806
10013
  }
9807
10014
  args.emittedLocalizedDuplicateFiles.add(args.targetFileName);
@@ -9840,7 +10047,7 @@ function localizeCrossSubPackageChunkLeaks(bundle, options) {
9840
10047
  if (crossRootImporters.size === 0) continue;
9841
10048
  const chunk = output;
9842
10049
  const sourceMapAssetInfo = findSourceMapAsset(bundle, collectSourceMapKeys(fileName, chunk));
9843
- const resolvedSourceMap = resolveSourceMapSource(chunk.map, sourceMapAssetInfo?.asset.source);
10050
+ const resolvedSourceMap = resolveEncodedSourceMap(chunk.map, sourceMapAssetInfo?.asset.source);
9844
10051
  const importerToChunk = /* @__PURE__ */ new Map();
9845
10052
  const duplicates = [];
9846
10053
  for (const [targetRoot, importerFiles] of crossRootImporters.entries()) {
@@ -9855,25 +10062,39 @@ function localizeCrossSubPackageChunkLeaks(bundle, options) {
9855
10062
  })();
9856
10063
  const runtimeFileName = posix.join(targetRoot, ROLLDOWN_RUNTIME_FILE_NAME);
9857
10064
  if (!existingDuplicateFileName) {
9858
- const duplicatedSource = rewriteChunkImportSpecifiersInCode(chunk.code ?? "", {
10065
+ const duplicatedChunk = {
10066
+ ...chunk,
10067
+ map: resolvedSourceMap
10068
+ };
10069
+ applyMagicStringChunkRewrite(duplicatedChunk, createChunkImportSpecifiersRewrite(duplicatedChunk.code ?? "", {
9859
10070
  sourceFileName: fileName,
9860
10071
  targetFileName: uniqueFileName,
9861
10072
  imports: chunk.imports,
9862
10073
  dynamicImports: chunk.dynamicImports,
9863
10074
  runtimeFileName
9864
- });
10075
+ }));
9865
10076
  this.emitFile({
9866
10077
  type: "asset",
9867
10078
  fileName: uniqueFileName,
9868
- source: duplicatedSource
10079
+ source: duplicatedChunk.code
9869
10080
  });
9870
- if (resolvedSourceMap) {
10081
+ if (duplicatedChunk.map) {
9871
10082
  const sourceMapFileName = reserveUniqueFileName(reservedFileNames, `${uniqueFileName}.map`);
9872
10083
  this.emitFile({
9873
10084
  type: "asset",
9874
10085
  fileName: sourceMapFileName,
9875
- source: cloneSourceLike(resolvedSourceMap)
10086
+ source: JSON.stringify(duplicatedChunk.map)
9876
10087
  });
10088
+ } else if (duplicatedChunk.code === chunk.code) {
10089
+ const unchangedSourceMap = resolveSourceMapSource(chunk.map, sourceMapAssetInfo?.asset.source);
10090
+ if (unchangedSourceMap) {
10091
+ const sourceMapFileName = reserveUniqueFileName(reservedFileNames, `${uniqueFileName}.map`);
10092
+ this.emitFile({
10093
+ type: "asset",
10094
+ fileName: sourceMapFileName,
10095
+ source: cloneSourceLike(unchangedSourceMap)
10096
+ });
10097
+ }
9877
10098
  }
9878
10099
  }
9879
10100
  for (const importerFile of importerFiles) importerToChunk.set(importerFile, uniqueFileName);
@@ -9923,12 +10144,12 @@ function applySharedChunkStrategy(bundle, options) {
9923
10144
  if (!isSharedVirtualChunk(fileName, output)) continue;
9924
10145
  const originalSharedFileName = fileName;
9925
10146
  const chunk = output;
9926
- const originalMap = chunk.map;
9927
10147
  const importers = findChunkImporters(bundle, fileName, importerIndex);
9928
10148
  if (importers.length === 0) continue;
9929
10149
  const sourceMapKeys = collectSourceMapKeys(fileName, chunk);
9930
10150
  const sourceMapAssetInfo = findSourceMapAsset(bundle, sourceMapKeys);
9931
- const resolvedSourceMap = resolveSourceMapSource(originalMap, sourceMapAssetInfo?.asset.source);
10151
+ const resolvedSourceMap = resolveEncodedSourceMap(chunk.map, sourceMapAssetInfo?.asset.source);
10152
+ if (resolvedSourceMap) chunk.map = resolvedSourceMap;
9932
10153
  const importerMap = /* @__PURE__ */ new Map();
9933
10154
  const mainImporters = [];
9934
10155
  let hasMainImporter = false;
@@ -9957,17 +10178,17 @@ function applySharedChunkStrategy(bundle, options) {
9957
10178
  let finalFileName = chunk.fileName;
9958
10179
  if (fileName.startsWith(`weapp_shared_virtual/`)) {
9959
10180
  const newFileName = fileName.slice(21);
9960
- chunk.code = rewriteChunkImportSpecifiersInCode(chunk.code ?? "", {
10181
+ const codeRewritten = applyMagicStringChunkRewrite(chunk, createChunkImportSpecifiersRewrite(chunk.code ?? "", {
9961
10182
  sourceFileNames: createChunkSourceFileNameCandidates(fileName),
9962
10183
  targetFileName: newFileName,
9963
10184
  imports: chunk.imports,
9964
10185
  dynamicImports: chunk.dynamicImports,
9965
10186
  runtimeFileName: ROLLDOWN_RUNTIME_FILE_NAME
9966
- });
10187
+ }));
9967
10188
  chunk.fileName = newFileName;
9968
10189
  if (typeof chunk.sourcemapFileName === "string" && chunk.sourcemapFileName) chunk.sourcemapFileName = `${newFileName}.map`;
9969
10190
  const targetKey = `${newFileName}.map`;
9970
- emitSourceMapAsset(this, targetKey, sourceMapAssetInfo, resolvedSourceMap);
10191
+ emitSourceMapAsset(this, targetKey, codeRewritten ? void 0 : sourceMapAssetInfo, resolveSourceMapSource(chunk.map, void 0));
9971
10192
  for (const mapKey of sourceMapKeys) {
9972
10193
  if (!mapKey || mapKey === targetKey) continue;
9973
10194
  if (bundle[mapKey]) delete bundle[mapKey];
@@ -9989,17 +10210,17 @@ function applySharedChunkStrategy(bundle, options) {
9989
10210
  }
9990
10211
  if (shouldRetainOriginalChunk && fileName.startsWith(`weapp_shared_virtual/`)) {
9991
10212
  const newFileName = fileName.slice(21);
9992
- chunk.code = rewriteChunkImportSpecifiersInCode(chunk.code ?? "", {
10213
+ const codeRewritten = applyMagicStringChunkRewrite(chunk, createChunkImportSpecifiersRewrite(chunk.code ?? "", {
9993
10214
  sourceFileNames: createChunkSourceFileNameCandidates(fileName),
9994
10215
  targetFileName: newFileName,
9995
10216
  imports: chunk.imports,
9996
10217
  dynamicImports: chunk.dynamicImports,
9997
10218
  runtimeFileName: ROLLDOWN_RUNTIME_FILE_NAME
9998
- });
10219
+ }));
9999
10220
  chunk.fileName = newFileName;
10000
10221
  if (typeof chunk.sourcemapFileName === "string" && chunk.sourcemapFileName) chunk.sourcemapFileName = `${newFileName}.map`;
10001
10222
  const targetKey = `${newFileName}.map`;
10002
- emitSourceMapAsset(this, targetKey, sourceMapAssetInfo, resolvedSourceMap);
10223
+ emitSourceMapAsset(this, targetKey, codeRewritten ? void 0 : sourceMapAssetInfo, resolveSourceMapSource(chunk.map, void 0));
10003
10224
  for (const mapKey of sourceMapKeys) {
10004
10225
  if (!mapKey || mapKey === targetKey) continue;
10005
10226
  if (bundle[mapKey]) delete bundle[mapKey];
@@ -19591,12 +19812,15 @@ function withScopedSlotHostAsset(ctx, fileName, buffer) {
19591
19812
  }
19592
19813
  function patchScopedSlotHostAssetForBundle(ctx, fileName, output) {
19593
19814
  if (output.type === "chunk") {
19594
- const current = output.code;
19815
+ const chunk = output;
19816
+ const current = chunk.code;
19595
19817
  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;
19818
+ if (!getScopedSlotGenericKeys(ctx, fileName)?.size || ctx.configService.platform !== "weapp" || current.includes(WEVU_SLOT_OWNER_ID_PROP)) return false;
19819
+ const transformCode = resolveOutputChunkTransformCode(chunk);
19820
+ const injected = injectScopedSlotHostPropertiesInJs(transformCode, { sourceMap: Boolean(normalizeEncodedSourceMapLike(chunk.map)) || transformCode !== current });
19821
+ if (injected.transformed) return applyOutputChunkTransform(chunk, injected.code, injected.map);
19822
+ const propertySource = createScopedSlotHostPropertiesSource();
19823
+ return replaceOutputChunkCode(chunk, /Component\(\s*\{/, (match) => `${match[0]} properties: { ${propertySource} },`);
19600
19824
  }
19601
19825
  const current = output.source;
19602
19826
  if (typeof current !== "string" && !Buffer.isBuffer(current) && !(current instanceof Uint8Array)) return false;
@@ -22219,7 +22443,13 @@ async function emitEntryOutput(options) {
22219
22443
  if (styleImports.length === 0) return { code };
22220
22444
  const ms = new MagicString(code);
22221
22445
  for (const styleImport of styleImports) ms.prepend(`import '${styleImport}';\n`);
22222
- return { code: ms.toString() };
22446
+ const result = { code: ms.toString() };
22447
+ if (configService.inlineConfig?.build?.sourcemap) result.map = ms.generateMap({
22448
+ hires: true,
22449
+ includeContent: true,
22450
+ source: id
22451
+ });
22452
+ return result;
22223
22453
  }
22224
22454
  //#endregion
22225
22455
  //#region src/plugins/hooks/useLoadEntry/loadEntry/resolve.ts
@@ -23580,9 +23810,9 @@ function removeImplicitPagePreloads(bundle, options, snapshot = createBundleChun
23580
23810
  const targets = targetSet;
23581
23811
  const ranges = findImplicitRequireRemovalRanges(chunk, targets);
23582
23812
  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();
23813
+ editOutputChunkCode(chunk, (magicString) => {
23814
+ for (const { start, end } of ranges) magicString.remove(start, end);
23815
+ });
23586
23816
  if (Array.isArray(chunk.imports) && chunk.imports.length) chunk.imports = chunk.imports.filter((name) => !targets.has(name));
23587
23817
  if (implicitlyLoaded && implicitlyLoaded.length) chunk.implicitlyLoadedBefore = implicitlyLoaded.filter((name) => !targets.has(name));
23588
23818
  }
@@ -23708,12 +23938,23 @@ function resolveOutputCode(output) {
23708
23938
  if (output.source == null) return;
23709
23939
  return Buffer.from(output.source).toString();
23710
23940
  }
23711
- function updateOutputCode(output, code) {
23712
- if (output.type === "chunk") {
23713
- output.code = code;
23714
- return;
23941
+ function replaceOutputCode(output, pattern, replace) {
23942
+ if (output.type === "chunk") return replaceOutputChunkCode(output, pattern, replace);
23943
+ const code = resolveOutputCode(output);
23944
+ if (typeof code !== "string") return false;
23945
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
23946
+ const matcher = new RegExp(pattern.source, flags);
23947
+ const magicString = new MagicString(code);
23948
+ let changed = false;
23949
+ for (const match of code.matchAll(matcher)) {
23950
+ if (typeof match.index !== "number") continue;
23951
+ const content = replace(match);
23952
+ if (content == null || content === match[0]) continue;
23953
+ magicString.overwrite(match.index, match.index + match[0].length, content);
23954
+ changed = true;
23715
23955
  }
23716
- output.source = code;
23956
+ if (changed) output.source = magicString.toString();
23957
+ return changed;
23717
23958
  }
23718
23959
  function formatNamedRequireBindings(bindings) {
23719
23960
  return bindings.map(({ importedName, localName }) => {
@@ -23797,45 +24038,41 @@ function rewriteWevuInternalRuntimeImports(bundle, options = {}, snapshot = crea
23797
24038
  const fileName = output.fileName;
23798
24039
  if (!fileName.endsWith(".js")) continue;
23799
24040
  if (!mayContainWevuRuntimeImport(code)) continue;
23800
- let rewritten = code;
23801
- let changed = false;
23802
24041
  const requiredRuntimeFileNames = /* @__PURE__ */ new Set();
23803
24042
  let containsRootWevuRuntimeExport;
23804
- rewritten = rewritten.replace(WEVU_RUNTIME_NAMED_IMPORT_RE, (full, importClause, source) => {
24043
+ const changedNamedImports = replaceOutputCode(output, WEVU_RUNTIME_NAMED_IMPORT_RE, (match) => {
24044
+ const [full, importClause, source] = match;
23805
24045
  const bindings = parseNamedImportBindings(importClause);
23806
24046
  const importedNames = bindings.map((binding) => binding.importedName);
23807
24047
  if (source === "wevu") {
23808
24048
  const result = rewriteRootWevuImport(runtimeChunkIndex, fileName, full, bindings, options, requiredRuntimeFileNames);
23809
- changed ||= result.changed;
23810
- return result.code;
24049
+ return result.changed ? result.code : void 0;
23811
24050
  }
23812
24051
  const resolvedInternalModuleId = normalizeWevuRuntimeModuleId(source);
23813
- if (!resolvedInternalModuleId) return full;
24052
+ if (!resolvedInternalModuleId) return;
23814
24053
  const runtimeChunk = resolveWevuRuntimeChunkForModuleId(runtimeChunkIndex, resolvedInternalModuleId, importedNames);
23815
24054
  const rememberedRuntimeFileName = resolveRememberedWevuRuntimeFileName(resolvedInternalModuleId, importedNames, options);
23816
24055
  const runtimeFileName = runtimeChunk?.fileName ?? rememberedRuntimeFileName;
23817
- if (!runtimeFileName) return full;
24056
+ if (!runtimeFileName) return;
23818
24057
  rememberWevuRuntimeChunk(resolvedInternalModuleId, runtimeChunk, options);
23819
- changed = true;
23820
24058
  requiredRuntimeFileNames.add(runtimeFileName);
23821
24059
  const specifier = normalizeRelativeRequireSpecifier(fileName, runtimeFileName);
23822
24060
  return `const { ${formatNamedRequireBindings(bindings)} } = require(${JSON.stringify(specifier)});`;
23823
24061
  });
23824
- rewritten = rewritten.replace(WEVU_RUNTIME_REQUIRE_RE, (full, rawSpecifier) => {
24062
+ const changedRequires = replaceOutputCode(output, WEVU_RUNTIME_REQUIRE_RE, (match) => {
24063
+ const rawSpecifier = match[1];
23825
24064
  const specifierValue = stripQuotes(rawSpecifier);
23826
24065
  if (specifierValue === "wevu" && containsRootWevuRuntimeExport === void 0) containsRootWevuRuntimeExport = containsWevuInternalRuntimeExportReference(code);
23827
24066
  const normalizedModuleId = normalizeWevuRuntimeModuleId(specifierValue);
23828
24067
  const canUseRememberedRuntime = normalizedModuleId === "wevu/internal-runtime" || specifierValue === "wevu" && containsRootWevuRuntimeExport === true;
23829
24068
  const rememberedRuntimeFileName = normalizedModuleId ? options.runtimeFileNames?.get(normalizedModuleId) : void 0;
23830
24069
  const runtimeFileName = canUseRememberedRuntime ? currentRuntimeChunk?.fileName ?? rememberedRuntimeFileName ?? options.runtimeFileName : rememberedRuntimeFileName;
23831
- if (!runtimeFileName) return full;
23832
- changed = true;
24070
+ if (!runtimeFileName) return;
23833
24071
  requiredRuntimeFileNames.add(runtimeFileName);
23834
24072
  const specifier = normalizeRelativeRequireSpecifier(fileName, runtimeFileName);
23835
24073
  return `require(${JSON.stringify(specifier)})`;
23836
24074
  });
23837
- if (!changed) continue;
23838
- updateOutputCode(output, rewritten);
24075
+ if (!changedNamedImports && !changedRequires) continue;
23839
24076
  if (output.type !== "chunk") continue;
23840
24077
  const chunk = output;
23841
24078
  const nextImports = new Set(Array.isArray(chunk.imports) ? chunk.imports : []);
@@ -23970,7 +24207,7 @@ function appendWevuRuntimeExports(chunk, aliases, importedMembers) {
23970
24207
  lines.push(`Object.defineProperty(exports, ${JSON.stringify(member)}, { enumerable: true, get: function() { return ${member}; } });`);
23971
24208
  existingExports.add(member);
23972
24209
  }
23973
- if (lines.length) chunk.code = `${chunk.code}\n${lines.join("\n")}`;
24210
+ if (lines.length) appendOutputChunkCode(chunk, `\n${lines.join("\n")}`);
23974
24211
  }
23975
24212
  function formatSyntheticSinglePageHookExport(exportName) {
23976
24213
  return [
@@ -23990,7 +24227,7 @@ function appendSyntheticWevuHookExports(chunk, importedMembers) {
23990
24227
  lines.push(formatSyntheticSinglePageHookExport(exportName));
23991
24228
  existingExports.add(exportName);
23992
24229
  }
23993
- if (lines.length) chunk.code = `${chunk.code}\n${lines.join("\n")}`;
24230
+ if (lines.length) appendOutputChunkCode(chunk, `\n${lines.join("\n")}`);
23994
24231
  }
23995
24232
  function resolveWevuBaseChunk(bundleOrSnapshot) {
23996
24233
  return resolveWevuInternalChunk(bundleOrSnapshot, ["assertInSetup", "pushHook"]);
@@ -24005,44 +24242,37 @@ function rewriteSyntheticWevuHookAccess(chunk, wevuChunkFileName, baseChunkFileN
24005
24242
  });
24006
24243
  if (!hookNames.length) return;
24007
24244
  const baseRequireSpecifier = normalizeRelativeRequireSpecifier(chunk.fileName, baseChunkFileName);
24008
- let nextCode = chunk.code;
24009
24245
  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
- }
24246
+ for (const ref of usage.runtimeRefs) replaceOutputChunkCode(chunk, new RegExp(`\\b${escapeRegExp(ref)}\\.${hookName}\\s*\\(`, "g"), () => {
24247
+ return formatSyntheticSinglePageHookFallback(hookName, `${ref}.${hookName}`, baseRequireSpecifier);
24248
+ });
24016
24249
  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;
24250
+ replaceOutputChunkCode(chunk, /require\((`[^`]+`|'[^']+'|"[^"]+")\)\.([A-Za-z_$][\w$]*)\s*\(/g, (match) => {
24251
+ const rawSpecifier = match[1];
24252
+ if (match[2] !== hookName) return;
24253
+ if (resolveRequireTarget(chunk.fileName, stripQuotes(rawSpecifier)) !== wevuChunkFileName) return;
24020
24254
  return formatSyntheticSinglePageHookFallback(hookName, `require(${rawSpecifier}).${hookName}`, baseRequireSpecifier);
24021
24255
  });
24022
24256
  }
24023
- chunk.code = nextCode;
24024
24257
  }
24025
24258
  function rewriteStableWevuRuntimeAccess(chunk, wevuChunkFileName, aliases, usage) {
24026
24259
  if (!aliases.size) return;
24027
- let nextCode = chunk.code;
24028
24260
  for (const [exportName, stableName] of WEVU_EXPORT_ALIASES) {
24029
24261
  const localName = aliases.get(exportName);
24030
24262
  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;
24263
+ if (usage.inlineMembers.has(localName) || usage.inlineMembers.has(stableName)) replaceOutputChunkCode(chunk, /require\((`[^`]+`|'[^']+'|"[^"]+")\)\.([A-Za-z_$][\w$]*)\s*\(/g, (match) => {
24264
+ const rawSpecifier = match[1];
24265
+ const property = match[2];
24266
+ if (property !== localName && property !== stableName) return;
24267
+ if (resolveRequireTarget(chunk.fileName, stripQuotes(rawSpecifier)) !== wevuChunkFileName) return;
24034
24268
  return `(require(${rawSpecifier}).${stableName} || require(${rawSpecifier}).${property})(`;
24035
24269
  });
24036
24270
  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
- }
24271
+ for (const ref of usage.runtimeRefs) replaceOutputChunkCode(chunk, new RegExp(`\\b${escapeRegExp(ref)}\\.(?:${stableName}|${localName})\\s*\\(`, "g"), (match) => {
24272
+ const property = match[0].includes(`.${stableName}`) ? stableName : localName;
24273
+ return `(${ref}.${stableName} || ${ref}.${property})(`;
24274
+ });
24044
24275
  }
24045
- chunk.code = nextCode;
24046
24276
  }
24047
24277
  function stabilizeWevuRuntimeChunkAccess(bundle, snapshot = createBundleChunkSnapshot(bundle)) {
24048
24278
  const wevuChunks = snapshot.wevuChunks;
@@ -24772,14 +25002,8 @@ function createInjectRequestGlobalsCode(targets, options) {
24772
25002
  function createInjectRequestGlobalsSfcCode(targets, options) {
24773
25003
  return `<script${options?.setup ? " setup lang=\"ts\"" : " lang=\"ts\""}>\n${createInjectRequestGlobalsCode(targets, options)}<\/script>\n`;
24774
25004
  }
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;
25005
+ function resolveRequestGlobalsSfcInjection(source, targets, options) {
25006
+ if (targets.length === 0) return null;
24783
25007
  const { descriptor, errors } = parse$1(source, {
24784
25008
  filename: "request-globals.vue",
24785
25009
  ignoreEmpty: false
@@ -24789,19 +25013,42 @@ function injectRequestGlobalsIntoSfc(source, targets, options) {
24789
25013
  localBindings: false
24790
25014
  } : options;
24791
25015
  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}`;
25016
+ if (errors.length > 0) return {
25017
+ code: createInjectRequestGlobalsSfcCode(targets, source.includes("<script setup") ? {
25018
+ ...options,
25019
+ localBindings: false
25020
+ } : options),
25021
+ index: 0
25022
+ };
24796
25023
  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;
25024
+ if (inlineScript) return {
25025
+ code: injection,
25026
+ index: inlineScript.loc.start.offset
25027
+ };
25028
+ if (descriptor.scriptSetup && !descriptor.scriptSetup.src ? descriptor.scriptSetup : void 0) return {
25029
+ code: createInjectRequestGlobalsSfcCode(targets, injectionOptions),
25030
+ index: 0
25031
+ };
25032
+ if (!descriptor.script) return {
25033
+ code: createInjectRequestGlobalsSfcCode(targets, injectionOptions),
25034
+ index: 0
25035
+ };
25036
+ if (!descriptor.scriptSetup) return {
25037
+ code: createInjectRequestGlobalsSfcCode(targets, {
25038
+ ...options,
25039
+ setup: true
25040
+ }),
25041
+ index: 0
25042
+ };
25043
+ return null;
25044
+ }
25045
+ /**
25046
+ * @description 将请求全局对象注入到现有 SFC 脚本块,避免生成额外的重复 `<script>`。
25047
+ */
25048
+ function injectRequestGlobalsIntoSfc(source, targets, options) {
25049
+ const injection = resolveRequestGlobalsSfcInjection(source, targets, options);
25050
+ if (!injection) return source;
25051
+ return `${source.slice(0, injection.index)}${injection.code}${source.slice(injection.index)}`;
24805
25052
  }
24806
25053
  //#endregion
24807
25054
  //#region src/postcss/constants.ts
@@ -25780,6 +26027,7 @@ function createOutputFinalizerPlugin(ctx) {
25780
26027
  normalizePreprocessorStyleAssetEntries(outputBundle, assetEntries.preprocessorStyleAssets, ctx.configService.outputExtensions?.wxss, (asset) => this.emitFile(asset));
25781
26028
  normalizeTemplateAssetEntries(ctx, assetEntries.templateAssets);
25782
26029
  pruneUnchangedDevHmrOutputs(ctx, outputBundle, wevuRuntimeRewriteOptions, { runtimeRewriteDone: true });
26030
+ syncOutputChunkSourceMapAssets(outputBundle);
25783
26031
  }
25784
26032
  }
25785
26033
  };
@@ -26045,43 +26293,6 @@ function rewriteMiniProgramPlatformApiAccess(code, globalName, options) {
26045
26293
  return createMiniProgramPlatformApiRewrite(code, globalName, options)?.toString() ?? code;
26046
26294
  }
26047
26295
  //#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
26296
  //#region src/plugins/core/lifecycle/emit/rewrite/platform.ts
26086
26297
  function mayNeedChunkScriptAnalysis(code) {
26087
26298
  if (code.includes("require")) return true;
@@ -26526,7 +26737,11 @@ function injectRequestGlobalsBundleRuntime(bundle, targets, mode, networkDefault
26526
26737
  ...bindingTargets.map((target) => `${REQUEST_GLOBAL_ACTUALS_KEY}[${JSON.stringify(target)}] = ${REQUEST_GLOBAL_BUNDLE_HOST_REF}.${target}`),
26527
26738
  ...bindingTargets.map((target) => `try{globalThis[${JSON.stringify(target)}]=${REQUEST_GLOBAL_BUNDLE_HOST_REF}.${target}}catch{}`)
26528
26739
  ].join(";");
26529
- chunk.code = `${`/* ${REQUEST_GLOBAL_BUNDLE_MARKER} */ ${passiveBindingsCode ? `${passiveBindingsCode}\n` : ""}`}${syntheticExportCode}${chunk.code}\n;${runtimeBindingCode};\n`;
26740
+ const bundlePrelude = `/* ${REQUEST_GLOBAL_BUNDLE_MARKER} */ ${passiveBindingsCode ? `${passiveBindingsCode}\n` : ""}`;
26741
+ editOutputChunkCode(chunk, (magicString) => {
26742
+ magicString.prepend(`${bundlePrelude}${syntheticExportCode}`);
26743
+ magicString.append(`\n;${runtimeBindingCode};\n`);
26744
+ });
26530
26745
  }
26531
26746
  return installerChunks;
26532
26747
  }
@@ -26544,7 +26759,7 @@ function injectRequestGlobalsPassiveBindings(bundle, installerChunks, targets, m
26544
26759
  if (chunkTargets.length === 0) continue;
26545
26760
  const passiveBindingsCode = createRequestGlobalsPassiveBindingsCode(chunkTargets, resolveRequestGlobalsBindingTargets(chunkTargets));
26546
26761
  if (!passiveBindingsCode) continue;
26547
- chunk.code = `/* ${REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER} */ ${passiveBindingsCode}\n${chunk.code}`;
26762
+ prependOutputChunkCode(chunk, `/* ${REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER} */ ${passiveBindingsCode}\n`);
26548
26763
  }
26549
26764
  }
26550
26765
  function injectRequestGlobalsLocalBindings(bundle, installerChunks, targets, mode, entriesMap, networkDefaults) {
@@ -26561,7 +26776,7 @@ function injectRequestGlobalsLocalBindings(bundle, installerChunks, targets, mod
26561
26776
  const bindingTargets = resolveRequestGlobalsBindingTargets(chunkTargets);
26562
26777
  if (bindingTargets.length === 0) continue;
26563
26778
  const inlineInstallerName = resolveRequestGlobalsInstallerName(chunk.code);
26564
- const firstRequireMatch = chunk.code.match(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE);
26779
+ const firstRequireMatch = chunk.code.matchAll(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE).next().value;
26565
26780
  let requireImportLiteral = null;
26566
26781
  let exportName;
26567
26782
  for (const requireMatch of chunk.code.matchAll(REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE)) {
@@ -26578,7 +26793,7 @@ function injectRequestGlobalsLocalBindings(bundle, installerChunks, targets, mod
26578
26793
  if (!installerHostExpression) {
26579
26794
  const passiveBindingsCode = createRequestGlobalsPassiveBindingsCode(chunkTargets);
26580
26795
  if (!passiveBindingsCode) continue;
26581
- chunk.code = `/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ ${passiveBindingsCode}\n${chunk.code}`;
26796
+ prependOutputChunkCode(chunk, `/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ ${passiveBindingsCode}\n`);
26582
26797
  continue;
26583
26798
  }
26584
26799
  const injectionCode = [
@@ -26589,11 +26804,16 @@ function injectRequestGlobalsLocalBindings(bundle, installerChunks, targets, mod
26589
26804
  ...bindingTargets.map((target) => `try{globalThis[${JSON.stringify(target)}]=${REQUEST_GLOBAL_CHUNK_HOST_REF}.${target}}catch{}`),
26590
26805
  ...bindingTargets.map((target) => `var ${target} = ${REQUEST_GLOBAL_CHUNK_HOST_REF}.${target}`)
26591
26806
  ].join(";");
26592
- if (inlineInstallerName && firstRequireMatch?.[0]) {
26593
- chunk.code = `/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ ${chunk.code.replace(firstRequireMatch[0], (match) => `${match};${injectionCode}`)}\n`;
26807
+ if (inlineInstallerName && firstRequireMatch?.[0] && typeof firstRequireMatch.index === "number") {
26808
+ const firstRequireIndex = firstRequireMatch.index;
26809
+ editOutputChunkCode(chunk, (magicString) => {
26810
+ magicString.prepend(`/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ `);
26811
+ magicString.overwrite(firstRequireIndex, firstRequireIndex + firstRequireMatch[0].length, `${firstRequireMatch[0]};${injectionCode}`);
26812
+ magicString.append("\n");
26813
+ });
26594
26814
  continue;
26595
26815
  }
26596
- chunk.code = `/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ ${injectionCode};\n${chunk.code}`;
26816
+ prependOutputChunkCode(chunk, `/* ${REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER} */ ${injectionCode};\n`);
26597
26817
  }
26598
26818
  }
26599
26819
  function resolveRequestGlobalsInstallerImport(chunk, installerChunks) {
@@ -26636,17 +26856,13 @@ function isRequestGlobalsSupportChunkFileName(fileName) {
26636
26856
  return baseName.startsWith("request-globals-") || baseName === "web-apis-shared.js";
26637
26857
  }
26638
26858
  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)));
26859
+ replaceOutputChunkCode(chunk, REQUEST_GLOBAL_REQUIRE_DECLARATOR_RE, (match) => {
26860
+ const requireLiteral = match[2];
26861
+ const importee = match[3] ?? match[4] ?? match[5];
26862
+ if (!requireLiteral || !importee) return;
26863
+ if (normalizeRelativeChunkImport(chunk.fileName, importee) !== fromFileName) return;
26864
+ return match[0].replace(requireLiteral, JSON.stringify(toRequireRequestPath(chunk.fileName, toFileName)));
26648
26865
  });
26649
- if (didRewrite) chunk.code = nextCode;
26650
26866
  }
26651
26867
  function hasBareRequireRegistration(code, requirePath) {
26652
26868
  const escapedRequireLiteral = JSON.stringify(requirePath).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -26671,14 +26887,12 @@ function rewriteEmbeddedRequirePaths(code, fromFileName, toFileName) {
26671
26887
  });
26672
26888
  }
26673
26889
  function rewriteChunkRequireCallsToExpression(chunk, targetFileName, expression) {
26674
- let didRewrite = false;
26675
- const nextCode = rewriteRequireCallLiterals(chunk.code, (_requireLiteral, importee) => {
26890
+ return replaceOutputChunkCode(chunk, REQUEST_GLOBAL_REQUIRE_CALL_RE, (match) => {
26891
+ const importee = match[2] ?? match[3] ?? match[4];
26892
+ if (!importee) return;
26676
26893
  if (normalizeRelativeChunkImport(chunk.fileName, importee) !== targetFileName) return;
26677
- didRewrite = true;
26678
26894
  return expression;
26679
26895
  });
26680
- if (didRewrite) chunk.code = nextCode;
26681
- return didRewrite;
26682
26896
  }
26683
26897
  function createRequestGlobalsStaticImportReplacement(node, expression) {
26684
26898
  const declarations = [];
@@ -26717,10 +26931,11 @@ function rewriteChunkStaticImportsToExpression(chunk, targetFileName, expression
26717
26931
  });
26718
26932
  } });
26719
26933
  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;
26934
+ return replaceOutputChunkCodeRanges(chunk, replacements.map((replacement) => ({
26935
+ content: replacement.value,
26936
+ end: replacement.end,
26937
+ start: replacement.start
26938
+ })));
26724
26939
  } catch {
26725
26940
  return false;
26726
26941
  }
@@ -26766,22 +26981,29 @@ function collapseRequestGlobalsRuntimeSupportChunk(bundle) {
26766
26981
  if (!supportChunk || supportChunk.type !== "chunk") return;
26767
26982
  const supportModuleRef = "__wvRGS__";
26768
26983
  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");
26984
+ editOutputChunkCode(runtimeOutput, (magicString) => {
26985
+ const runtimeRequireIndex = runtimeRequireMatch.index;
26986
+ if (typeof runtimeRequireIndex !== "number") return;
26987
+ magicString.overwrite(runtimeRequireIndex, runtimeRequireIndex + runtimeRequireMatch[0].length, `${supportRequireIdentifier} = ${supportModuleRef}`);
26988
+ magicString.prepend([
26989
+ `const ${supportModuleRef} = (() => {`,
26990
+ " const module = { exports: {} }",
26991
+ " const exports = module.exports",
26992
+ String(supportChunk.code),
26993
+ " return module.exports",
26994
+ "})();",
26995
+ ""
26996
+ ].join("\n"));
26997
+ magicString.append([
26998
+ "",
26999
+ `for (const __wvRGK__ in ${supportModuleRef}) {`,
27000
+ " if (__wvRGK__ in exports) {",
27001
+ " continue",
27002
+ " }",
27003
+ ` Object.defineProperty(exports, __wvRGK__, { enumerable: true, get: () => ${supportModuleRef}[__wvRGK__] })`,
27004
+ "}"
27005
+ ].join("\n"));
27006
+ });
26785
27007
  delete bundle[supportChunkFileName];
26786
27008
  for (const output of Object.values(bundle)) {
26787
27009
  if (!output || output.type !== "chunk") continue;
@@ -26804,7 +27026,7 @@ function injectRequestGlobalsAppRegistration(bundle, installerChunks) {
26804
27026
  requireStatements.push(`require(${JSON.stringify(requirePath)});`);
26805
27027
  }
26806
27028
  if (requireStatements.length === 0) return;
26807
- appChunk.code = `${requireStatements.join("\n")}\n${appChunk.code}`;
27029
+ prependOutputChunkCode(appChunk, `${requireStatements.join("\n")}\n`);
26808
27030
  }
26809
27031
  function inlineRequestGlobalsAppRegisteredInstallerChunks(bundle, installerChunks, preservedInstallerChunks = /* @__PURE__ */ new Set()) {
26810
27032
  if (installerChunks.size === 0) return;
@@ -26847,7 +27069,7 @@ function inlineRequestGlobalsAppRegisteredInstallerChunks(bundle, installerChunk
26847
27069
  if (!hasPreservedAssetRequire) delete bundle[installerChunkFileName];
26848
27070
  }
26849
27071
  if (inlinedModules.length === 0) return;
26850
- appChunk.code = `${inlinedModules.join("\n")}\n${appChunk.code}`;
27072
+ prependOutputChunkCode(appChunk, `${inlinedModules.join("\n")}\n`);
26851
27073
  }
26852
27074
  function createRequestGlobalsPreludeCode(chunk, installerChunks, targets, mode, networkDefaults) {
26853
27075
  const chunkTargets = resolvePreludeRequestGlobalsTargets(chunk.code, targets, mode);
@@ -26936,7 +27158,7 @@ function injectAxiosFetchAdapterEnv(bundle) {
26936
27158
  const moduleIds = Array.isArray(chunk.moduleIds) ? chunk.moduleIds : [];
26937
27159
  const normalizedFileName = toPosixPath(chunk.fileName);
26938
27160
  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}`;
27161
+ appendOutputChunkCode(chunk, `\n${axiosEnvPatchCode}`);
26940
27162
  }
26941
27163
  }
26942
27164
  //#endregion
@@ -27697,6 +27919,32 @@ function getCssRealPath(res) {
27697
27919
  return res.filename;
27698
27920
  }
27699
27921
  //#endregion
27922
+ //#region src/utils/codeTransform.ts
27923
+ /**
27924
+ * 对 load/transform 结果执行可追踪编辑,并按需组合已有映射。
27925
+ */
27926
+ function editCodeTransformResult(result, sourceId, edit, options) {
27927
+ const magicString = new MagicString(result.code);
27928
+ edit(magicString, result.code);
27929
+ const code = magicString.toString();
27930
+ if (code === result.code) return result;
27931
+ const previousMap = normalizeEncodedSourceMapLike(result.map);
27932
+ if (!options?.sourceMap && !previousMap) return {
27933
+ ...result,
27934
+ code
27935
+ };
27936
+ const rewriteMap = magicString.generateMap({
27937
+ hires: true,
27938
+ includeContent: true,
27939
+ source: sourceId
27940
+ });
27941
+ return {
27942
+ ...result,
27943
+ code,
27944
+ map: previousMap ? composeSourceMaps(rewriteMap, previousMap) : rewriteMap
27945
+ };
27946
+ }
27947
+ //#endregion
27700
27948
  //#region src/plugins/core/lifecycle/load/requestGlobals.ts
27701
27949
  const NORMAL_SFC_SCRIPT_RE = /<script(?![^>]*setup)[^>]*>/u;
27702
27950
  function resolvePassiveRequestGlobalsTargets(code, requestGlobalsTargets) {
@@ -27714,14 +27962,13 @@ function resolveRequestGlobalsTargetsForCode(code, sourceId, options) {
27714
27962
  }
27715
27963
  function injectRequestGlobalsIntoLoadResult(result, sourceId, targets, options) {
27716
27964
  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
- };
27965
+ if (sourceId.endsWith(".vue")) {
27966
+ const injection = resolveRequestGlobalsSfcInjection(result.code, targets, options);
27967
+ if (!injection) return result;
27968
+ return editCodeTransformResult(result, sourceId, (magicString) => magicString.appendLeft(injection.index, injection.code), { sourceMap: options?.sourceMap });
27969
+ }
27970
+ const injection = createInjectRequestGlobalsCode(targets, options);
27971
+ return editCodeTransformResult(result, sourceId, (magicString) => magicString.prepend(injection), { sourceMap: options?.sourceMap });
27725
27972
  }
27726
27973
  //#endregion
27727
27974
  //#region src/plugins/core/lifecycle/load/weapi.ts
@@ -28044,7 +28291,10 @@ function createLoadHook(state) {
28044
28291
  function injectRequestGlobalsProfiled(result, sourceId, requestGlobalsTargets, options) {
28045
28292
  const startedAt = performance.now();
28046
28293
  try {
28047
- return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets, options);
28294
+ return injectRequestGlobalsIntoLoadResult(result, sourceId, requestGlobalsTargets, {
28295
+ ...options,
28296
+ sourceMap: Boolean(configService.inlineConfig?.build?.sourcemap)
28297
+ });
28048
28298
  } finally {
28049
28299
  recordLoadDuration("requestGlobalsMs", startedAt);
28050
28300
  }
@@ -33281,7 +33531,7 @@ async function loadAppEntry(ctx, scanState) {
33281
33531
  const { path: appEntryPath } = appEntry;
33282
33532
  let configFromVue;
33283
33533
  if (!appConfigFile && vueAppPath) {
33284
- const { extractConfigFromVue } = await import("./file-_4iQaFyw.mjs");
33534
+ const { extractConfigFromVue } = await import("./file-BPMjkByK.mjs");
33285
33535
  configFromVue = await extractConfigFromVue(vueAppPath);
33286
33536
  if (configFromVue) appConfigFile = vueAppPath;
33287
33537
  }
@@ -0,0 +1,2 @@
1
+ import { t as extractConfigFromVue } from "./file-DnVj_L9_.mjs";
2
+ export { extractConfigFromVue };
@@ -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-BPs9XIGi.mjs");
138
138
  const compilerContext = getCompilerContext();
139
139
  const service = compilerContext.autoRoutesService;
140
140
  const reference = service?.getReference?.();
@@ -0,0 +1,2 @@
1
+ import { n as getCompilerContext } from "./createContext-DoH-W4mj.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-DoH-W4mj.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-DoH-W4mj.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.4",
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/schematics": "6.1.0",
131
132
  "@weapp-core/logger": "3.1.1",
132
133
  "@weapp-core/init": "6.0.14",
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.4",
136
136
  "@weapp-vite/mcp": "1.4.14",
137
137
  "@weapp-vite/miniprogram-automator": "1.2.13",
138
- "@weapp-vite/volar": "2.1.3",
139
- "@weapp-vite/web": "1.4.7",
138
+ "@weapp-vite/web": "1.4.9",
140
139
  "@wevu/api": "0.2.16",
140
+ "@weapp-vite/volar": "2.1.3",
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.4"
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 };