weapp-vite 6.16.46 → 6.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 { _ as jsExtensions, a as findJsonEntry, b as vueExtensions, 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 supportedCssLangs, y as templateExtensions } from "./file-_O6M6mJG.mjs";
3
+ import { _ as jsExtensions, a as findJsonEntry, b as vueExtensions, 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 supportedCssLangs, y as templateExtensions } from "./file-Byezg0ta.mjs";
4
4
  import { createRequire, isBuiltin } from "node:module";
5
5
  import path, { posix } from "pathe";
6
6
  import path$1, { normalize, relative, win32 } from "node:path";
@@ -38,7 +38,9 @@ import PQueue from "p-queue";
38
38
  import { APP_PRELUDE_CHUNK_MARKER, APP_PRELUDE_GUARD_KEY, APP_PRELUDE_REQUIRE_MARKER, REQUEST_GLOBAL_ACTUALS_KEY, REQUEST_GLOBAL_BUNDLE_HOST_REF, REQUEST_GLOBAL_BUNDLE_MARKER, REQUEST_GLOBAL_CHUNK_HOST_REF, REQUEST_GLOBAL_CHUNK_MODULE_REF, REQUEST_GLOBAL_EXPOSE_HELPER, REQUEST_GLOBAL_INSTALLER_HOST_REF, REQUEST_GLOBAL_LAZY_CONSTRUCTOR_HELPER, REQUEST_GLOBAL_LAZY_FUNCTION_HELPER, REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER, REQUEST_GLOBAL_MARK_PLACEHOLDER_HELPER, REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER, REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER as REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER$1, REQUEST_GLOBAL_PLACEHOLDER_KEY, REQUEST_GLOBAL_PRELUDE_GUARD_KEY, REQUEST_GLOBAL_PRELUDE_MARKER, REQUEST_GLOBAL_SYNTHETIC_EXPORT_NAME, REQUEST_GLOBAL_USABLE_CONSTRUCTOR_HELPER, WEAPP_VITE_IMPORT_META_ENV_KEY, WEAPP_VITE_INJECTED_API_IDENTIFIER, WEVU_APP_SHELL_COMPONENT_BASE, WEVU_APP_SHELL_TAG_NAME, WEVU_EXPRESSION_ERROR_IDENTIFIER, WEVU_INTERNAL_KEY_IDENTIFIER, WEVU_LAYOUT_BIND_PREFIX, WEVU_PAGE_LAYOUT_CURRENT_NAME_IDENTIFIER, WEVU_PAGE_LAYOUT_CURRENT_PROPS_IDENTIFIER, WEVU_PAGE_LAYOUT_NAME_KEY, WEVU_PAGE_LAYOUT_NEXT_NAME_IDENTIFIER, WEVU_PAGE_LAYOUT_NEXT_PROPS_IDENTIFIER, WEVU_PAGE_LAYOUT_NONE, WEVU_PAGE_LAYOUT_PROPS_KEY, WEVU_PAGE_LAYOUT_SETTER_KEY, WEVU_SCOPED_SLOT_CREATOR_KEY, WEVU_SLOT_FALLBACK_VIRTUAL_HOST_BASE, WEVU_SLOT_FALLBACK_VIRTUAL_HOST_GLOBAL_PATH, WEVU_SLOT_FALLBACK_VIRTUAL_HOST_TAG_NAME, WEVU_SLOT_NAMES_PROP, WEVU_SLOT_OWNER_ID_ATTR, WEVU_SLOT_OWNER_ID_KEY, WEVU_SLOT_OWNER_ID_PROP, WEVU_SLOT_PROPS_ATTR, WEVU_SLOT_SCOPE_ATTR, WEVU_SLOT_SCOPE_KEY } from "@weapp-core/constants";
39
39
  import { Buffer } from "node:buffer";
40
40
  import MagicString from "magic-string";
41
- import babel from "@weapp-vite/ast/babelCore";
41
+ import babelPresetEnv from "@babel/preset-env";
42
+ import babelPresetTypescript from "@babel/preset-typescript";
43
+ import * as babel from "@weapp-vite/ast/babelCore";
42
44
  import { Parser } from "htmlparser2";
43
45
  import { detect } from "package-manager-detector/detect";
44
46
  import tsconfigPaths from "vite-tsconfig-paths";
@@ -1011,7 +1013,7 @@ function extractInlinePropsTypeFromCode(code) {
1011
1013
  };
1012
1014
  traverse(ast, { CallExpression(path) {
1013
1015
  if (!path.node.callee || path.node.callee.type !== "Identifier" || path.node.callee.name !== "defineProps") return;
1014
- const typeParameter = path.node.typeParameters?.params?.[0];
1016
+ const typeParameter = (path.node.typeParameters ?? path.node.typeArguments)?.params?.[0];
1015
1017
  if (!typeParameter) return;
1016
1018
  if (typeParameter.type === "TSTypeLiteral") {
1017
1019
  pushTypeLiteralMembers(typeParameter);
@@ -9329,6 +9331,10 @@ function createRuntimeState() {
9329
9331
  queue: new PQueue({ autoStart: false }),
9330
9332
  npmBuilt: false,
9331
9333
  independent: { outputs: /* @__PURE__ */ new Map() },
9334
+ output: {
9335
+ emittedSource: /* @__PURE__ */ new Map(),
9336
+ wevuInternalRuntimeFileName: void 0
9337
+ },
9332
9338
  hmr: {
9333
9339
  loadedEntrySet: /* @__PURE__ */ new Set(),
9334
9340
  dirtyEntrySet: /* @__PURE__ */ new Set(),
@@ -9341,10 +9347,12 @@ function createRuntimeState() {
9341
9347
  vueEntryHasTemplate: /* @__PURE__ */ new Map(),
9342
9348
  vueEntryNonJsonSignatures: /* @__PURE__ */ new Map(),
9343
9349
  vueEntryScriptSignatures: /* @__PURE__ */ new Map(),
9350
+ appEntryAutoRoutesSignature: void 0,
9344
9351
  dirtyVueEntryIds: /* @__PURE__ */ new Set(),
9345
9352
  didEmitAllEntries: false,
9346
9353
  lastHmrEntryIds: /* @__PURE__ */ new Set(),
9347
9354
  lastEmittedEntryIds: /* @__PURE__ */ new Set(),
9355
+ lastEmittedChunkFileNames: /* @__PURE__ */ new Set(),
9348
9356
  recentProfiles: [],
9349
9357
  profile: {}
9350
9358
  }
@@ -11256,7 +11264,10 @@ function transformWxsCode(code, options) {
11256
11264
  result: babel.transformSync(code, {
11257
11265
  babelrc: false,
11258
11266
  configFile: false,
11259
- presets: [["@babel/preset-env"], ["@babel/preset-typescript"]],
11267
+ presets: [[babelPresetEnv, {
11268
+ modules: "commonjs",
11269
+ targets: { ie: "11" }
11270
+ }], babelPresetTypescript],
11260
11271
  filename,
11261
11272
  plugins: [{ visitor: {
11262
11273
  Directive: { enter(p) {
@@ -11288,7 +11299,7 @@ function transformWxsCode(code, options) {
11288
11299
  const node = p.node;
11289
11300
  if (!t.isIdentifier(node.object, { name: "exports" })) return;
11290
11301
  const moduleExports = t.memberExpression(t.identifier("module"), t.identifier("exports"));
11291
- p.replaceWith(t.memberExpression(moduleExports, node.property, node.computed, node.optional));
11302
+ p.replaceWith(t.memberExpression(moduleExports, node.property, node.computed));
11292
11303
  } },
11293
11304
  ImportDeclaration: { enter(p) {
11294
11305
  maybePushImportee(p.node.source.value);
@@ -12307,6 +12318,7 @@ function createHmrProfileMetricsPlugin(ctx) {
12307
12318
  let writeStartAt;
12308
12319
  return {
12309
12320
  name: "weapp-vite:hmr-profile-metrics",
12321
+ enforce: "post",
12310
12322
  generateBundle(_options, _bundle, isWrite) {
12311
12323
  if (!ctx.configService?.isDev || !isWrite) return;
12312
12324
  writeStartAt = performance.now();
@@ -12508,6 +12520,7 @@ function resetEmittedOutputCaches(runtimeState) {
12508
12520
  runtimeState.json.emittedSource.clear();
12509
12521
  runtimeState.asset.emittedBuffer.clear();
12510
12522
  runtimeState.asset.scopedSlotGenerics.clear();
12523
+ runtimeState.build?.output?.emittedSource.clear();
12511
12524
  runtimeState.css.emittedSource.clear();
12512
12525
  runtimeState.wxml.emittedCode.clear();
12513
12526
  }
@@ -12617,6 +12630,14 @@ function watchWorkers(configService, watcherService, workersDir) {
12617
12630
  }
12618
12631
  //#endregion
12619
12632
  //#region src/runtime/buildPlugin/service.ts
12633
+ function resolveSnapshotSidecarDirtySummary(filePath) {
12634
+ const normalizedFile = normalizeFsResolvedId(filePath);
12635
+ if (configSuffixes$1.find((suffix) => normalizedFile.endsWith(suffix))) return "json-sidecar:1";
12636
+ const ext = path.extname(normalizedFile);
12637
+ if (ext && watchedCssExts.has(ext)) return "style-sidecar:1";
12638
+ if (ext && watchedTemplateExts.has(ext)) return "sidecar-direct:1";
12639
+ return "sidecar-direct:1";
12640
+ }
12620
12641
  function shouldHandleSnapshotSidecarFile(filePath, configService) {
12621
12642
  if (isSidecarFile(filePath)) return true;
12622
12643
  const normalizedFile = normalizeFsResolvedId(filePath);
@@ -12894,6 +12915,8 @@ function createBuildService(ctx) {
12894
12915
  let autoTouchChecked = false;
12895
12916
  const { buildIndependentBundle, getIndependentOutput, invalidateIndependentOutput } = createIndependentBuilder(configService, buildState);
12896
12917
  function shouldTouchAppWxss() {
12918
+ const dirtyReasonSummary = ctx.runtimeState.build.hmr.profile.dirtyReasonSummary;
12919
+ if (dirtyReasonSummary?.length && !dirtyReasonSummary.some((reason) => reason.startsWith("style-sidecar:") || reason.startsWith("css-importer:") || reason.startsWith("entry-local-asset:"))) return false;
12897
12920
  const option = configService.weappViteConfig.hmr?.touchAppWxss ?? "auto";
12898
12921
  if (option === true) return true;
12899
12922
  if (option === false) return false;
@@ -13017,14 +13040,14 @@ function createBuildService(ctx) {
13017
13040
  dirtyReasonSummary: [`snapshot-full:${ctx.runtimeState.build.hmr.resolvedEntryMap.size}`]
13018
13041
  };
13019
13042
  }
13020
- function markSnapshotEntryDirty(entryId) {
13043
+ function markSnapshotEntryDirty(entryId, reason) {
13021
13044
  ctx.runtimeState.build.hmr.dirtyEntrySet.add(entryId);
13022
- ctx.runtimeState.build.hmr.dirtyEntryReasons.set(entryId, "direct");
13045
+ ctx.runtimeState.build.hmr.dirtyEntryReasons.set(entryId, "metadata");
13023
13046
  ctx.runtimeState.build.hmr.loadedEntrySet.delete(entryId);
13024
13047
  ctx.runtimeState.build.hmr.profile = {
13025
13048
  ...ctx.runtimeState.build.hmr.profile,
13026
13049
  dirtyCount: ctx.runtimeState.build.hmr.dirtyEntrySet.size,
13027
- dirtyReasonSummary: ["sidecar-direct:1"]
13050
+ dirtyReasonSummary: reason?.file ? [resolveSnapshotSidecarDirtySummary(reason.file)] : ["sidecar-direct:1"]
13028
13051
  };
13029
13052
  }
13030
13053
  const runSnapshotBuild = (reason) => {
@@ -13044,7 +13067,7 @@ function createBuildService(ctx) {
13044
13067
  }
13045
13068
  const sidecarEntryId = await resolveSnapshotSidecarEntryId(reason);
13046
13069
  if (sidecarEntryId) {
13047
- markSnapshotEntryDirty(sidecarEntryId);
13070
+ markSnapshotEntryDirty(sidecarEntryId, reason);
13048
13071
  await build(snapshotBuildOptions);
13049
13072
  return "snapshot";
13050
13073
  }
@@ -13109,9 +13132,9 @@ function createBuildService(ctx) {
13109
13132
  });
13110
13133
  logger_default.success(formatHmrLogLine(durationMs));
13111
13134
  shouldLogSlowHmrTip();
13135
+ if (appWxssPath && shouldTouchAppWxss()) touch(appWxssPath).catch(() => {});
13112
13136
  } else firstBuildCompleted = true;
13113
13137
  resetHmrProfile();
13114
- if (appWxssPath && shouldTouchAppWxss()) touch(appWxssPath).catch(() => {});
13115
13138
  resolveWatcher(e);
13116
13139
  })().catch((error) => {
13117
13140
  resetHmrProfile();
@@ -14486,6 +14509,20 @@ function emitSfcJsonAsset(ctx, bundle, relativeBase, result, options) {
14486
14509
  });
14487
14510
  emittedAssetSourceCache.set(cacheKey, nextSource);
14488
14511
  }
14512
+ function emitSfcScriptAssetReplacingBundleEntry(ctx, bundle, relativeBase, code, extension = "js") {
14513
+ const jsFileName = resolveSfcAssetFileName(relativeBase, extension);
14514
+ const existing = bundle[jsFileName];
14515
+ if (existing) {
14516
+ if (existing.type === "chunk") existing.code = code;
14517
+ else existing.source = code;
14518
+ return;
14519
+ }
14520
+ ctx.emitFile({
14521
+ type: "asset",
14522
+ fileName: jsFileName,
14523
+ source: code
14524
+ });
14525
+ }
14489
14526
  function emitClassStyleWxsAssetIfMissing(ctx, bundle, fileName, source) {
14490
14527
  const existing = bundle[fileName];
14491
14528
  const cacheKey = `asset:${fileName}`;
@@ -14871,6 +14908,7 @@ function isAutoSetDataPickEnabled(config) {
14871
14908
  return isAutoSetDataPickEnabledWithPreset(config);
14872
14909
  }
14873
14910
  function isKnownWevuComponentCallee(callee) {
14911
+ if (!t.isExpression(callee) && !t.isV8IntrinsicIdentifier(callee)) return false;
14874
14912
  if (callee.type === "Identifier") return callee.name === "createWevuComponent" || callee.name === "defineComponent";
14875
14913
  if (callee.type !== "MemberExpression" || callee.computed) return false;
14876
14914
  return callee.property.type === "Identifier" && (callee.property.name === "createWevuComponent" || callee.property.name === "defineComponent" || callee.property.name === "so");
@@ -15157,7 +15195,7 @@ function transformTargetWevuOptionsInJs(source, transformOptions) {
15157
15195
  traverse(ast, { CallExpression(path) {
15158
15196
  const firstArg = path.node.arguments[0];
15159
15197
  if (!firstArg || firstArg.type === "SpreadElement") return;
15160
- const resolvedOptions = resolveOptionsObjectExpression(firstArg, path.scope);
15198
+ const resolvedOptions = t.isExpression(firstArg) ? resolveOptionsObjectExpression(firstArg, path.scope) : null;
15161
15199
  if (resolvedOptions && (isKnownWevuComponentCallee(path.node.callee) || hasCompiledWevuOptionsMarker(resolvedOptions))) candidateOptions.add(resolvedOptions);
15162
15200
  } });
15163
15201
  if (!candidateOptions.size) return {
@@ -15767,7 +15805,7 @@ function resolveRelativeJsonOutputFileName(configService, filePath) {
15767
15805
  }
15768
15806
  //#endregion
15769
15807
  //#region src/plugins/hooks/useLoadEntry/chunkEmitter.ts
15770
- function createChunkEmitter(configService, loadedEntrySet, debug, trackEmittedEntryId, trackEmittedChunkId, shouldEmitEntryChunk, preloadAssetOnlyEntry) {
15808
+ function createChunkEmitter(configService, loadedEntrySet, debug, trackEmittedEntryId, trackEmittedChunkId, shouldEmitEntryChunk, preloadAssetOnlyEntry, trackEmittedChunkFileName) {
15771
15809
  return function emitEntriesChunks(resolvedIds) {
15772
15810
  return resolvedIds.map(async (resolvedId) => {
15773
15811
  if (!resolvedId) return;
@@ -15787,6 +15825,7 @@ function createChunkEmitter(configService, loadedEntrySet, debug, trackEmittedEn
15787
15825
  preserveSignature: "exports-only"
15788
15826
  });
15789
15827
  trackEmittedChunkId?.(normalizedId);
15828
+ trackEmittedChunkFileName?.(fileName);
15790
15829
  }
15791
15830
  trackEmittedEntryId?.(normalizedId);
15792
15831
  if (shouldPreload) debug?.(`load ${fileName} 耗时 ${(performance$1.now() - start).toFixed(2)}ms`);
@@ -16906,6 +16945,7 @@ function resolveWxmlEmitContext(compiler) {
16906
16945
  function resolveWxmlEmitTargets(options) {
16907
16946
  const { compiler, subPackageMeta, buildTarget = "app" } = options;
16908
16947
  const { wxmlService, configService, scanService, templateExtension } = resolveWxmlEmitContext(compiler);
16948
+ const targetIds = options.targetIds?.size ? new Set(Array.from(options.targetIds, normalizeWatchPath)) : void 0;
16909
16949
  return Array.from(wxmlService.tokenMap.entries()).filter(([id]) => isTemplate(id)).map(([id, token]) => {
16910
16950
  return {
16911
16951
  id,
@@ -16913,6 +16953,7 @@ function resolveWxmlEmitTargets(options) {
16913
16953
  fileName: resolveRelativeOutputFileNameWithExtension(configService, id, templateExtension)
16914
16954
  };
16915
16955
  }).filter(({ id, fileName }) => {
16956
+ if (targetIds?.size && !targetIds.has(normalizeWatchPath(id))) return false;
16916
16957
  if (subPackageMeta) return fileName.startsWith(subPackageMeta.subPackage.root);
16917
16958
  if (buildTarget === "plugin") {
16918
16959
  const pluginRoot = configService.absolutePluginRoot;
@@ -16949,7 +16990,8 @@ function emitWxmlAssetsWithCache(options) {
16949
16990
  const currentPackageWxmls = resolveWxmlEmitTargets({
16950
16991
  compiler,
16951
16992
  subPackageMeta,
16952
- buildTarget
16993
+ buildTarget,
16994
+ targetIds: options.targetIds
16953
16995
  });
16954
16996
  const emittedFiles = [];
16955
16997
  for (const { id, fileName, token } of currentPackageWxmls) {
@@ -17480,14 +17522,17 @@ function createEntryLoader(options) {
17480
17522
  emittedWxmlCodeCache: ctx.runtimeState?.wxml?.emittedCode,
17481
17523
  skipEntries: shouldSkipAppEntries
17482
17524
  });
17483
- if (type === "app" && !shouldSkipAppEntries && appResult) appEntryOutputCache.current = {
17484
- appSignature: appResult.appSignature,
17485
- appVueNonJsonSignature,
17486
- pluginSignature: appResult.pluginSignature,
17487
- pluginJsonPath: appResult.pluginJsonPath,
17488
- autoRoutesSignature,
17489
- resolveCacheVersion
17490
- };
17525
+ if (type === "app" && !shouldSkipAppEntries && appResult) {
17526
+ ctx.runtimeState.build.hmr.appEntryAutoRoutesSignature = autoRoutesSignature;
17527
+ appEntryOutputCache.current = {
17528
+ appSignature: appResult.appSignature,
17529
+ appVueNonJsonSignature,
17530
+ pluginSignature: appResult.pluginSignature,
17531
+ pluginJsonPath: appResult.pluginJsonPath,
17532
+ autoRoutesSignature,
17533
+ resolveCacheVersion
17534
+ };
17535
+ }
17491
17536
  return result;
17492
17537
  }, { invalidateResolveCache() {
17493
17538
  entryResolver.invalidate();
@@ -17550,6 +17595,9 @@ function resolveUpstreamPendingReasonSummary(dirtyReasonSummary) {
17550
17595
  if (hasAutoRoutesTopology) pendingReasonSummary.push("auto-routes-topology");
17551
17596
  return pendingReasonSummary;
17552
17597
  }
17598
+ function isEntryAutoRoutesRefresh(dirtyReasonSummary) {
17599
+ return dirtyReasonSummary?.some((item) => item.startsWith("entry-auto-routes:")) === true;
17600
+ }
17553
17601
  function resolvePendingEntryIds(options) {
17554
17602
  const pending = new Set(options.dirtyEntrySet);
17555
17603
  const pendingReasonSummary = resolveUpstreamPendingReasonSummary(options.dirtyReasonSummary);
@@ -17650,11 +17698,13 @@ function useLoadEntry(ctx, options) {
17650
17698
  const loadedEntrySet = ctx.runtimeState.build.hmr.loadedEntrySet;
17651
17699
  const dirtyEntrySet = ctx.runtimeState.build.hmr.dirtyEntrySet;
17652
17700
  const dirtyEntryReasons = ctx.runtimeState.build.hmr.dirtyEntryReasons;
17701
+ const dirtyEntryEventIds = /* @__PURE__ */ new Map();
17653
17702
  const resolvedEntryMap = ctx.runtimeState.build.hmr.resolvedEntryMap;
17654
17703
  const layoutEntryDependents = ctx.runtimeState.build.hmr.layoutEntryDependents;
17655
17704
  const entryLayoutDependencies = ctx.runtimeState.build.hmr.entryLayoutDependencies;
17656
17705
  const lastActualEmittedEntryIds = /* @__PURE__ */ new Set();
17657
17706
  const lastChunkEmittedEntryIds = /* @__PURE__ */ new Set();
17707
+ const lastEmittedChunkFileNames = ctx.runtimeState.build.hmr.lastEmittedChunkFileNames ??= /* @__PURE__ */ new Set();
17658
17708
  const metadataEntryIds = /* @__PURE__ */ new Set();
17659
17709
  const jsonEmitManager = createJsonEmitManager(ctx.configService);
17660
17710
  const registerJsonAsset = jsonEmitManager.register.bind(jsonEmitManager);
@@ -17678,6 +17728,8 @@ function useLoadEntry(ctx, options) {
17678
17728
  }
17679
17729
  const entryType = entriesMap.get(entryId)?.type === "page" ? "page" : "component";
17680
17730
  await loadEntry.call(this, resolvedId.id, entryType);
17731
+ }, (fileName) => {
17732
+ lastEmittedChunkFileNames.add(fileName);
17681
17733
  });
17682
17734
  loadEntry = createEntryLoader({
17683
17735
  ctx,
@@ -17731,6 +17783,7 @@ function useLoadEntry(ctx, options) {
17731
17783
  normalizeEntry,
17732
17784
  markEntryDirty(entryId, reason = "direct") {
17733
17785
  dirtyEntrySet.add(entryId);
17786
+ dirtyEntryEventIds.set(entryId, ctx.runtimeState.build.hmr.profile.eventId);
17734
17787
  const previous = dirtyEntryReasons.get(entryId);
17735
17788
  const nextReason = previous === "dependency" || reason === "dependency" ? "dependency" : previous === "direct" || reason === "direct" ? "direct" : reason;
17736
17789
  dirtyEntryReasons.set(entryId, nextReason);
@@ -17745,12 +17798,24 @@ function useLoadEntry(ctx, options) {
17745
17798
  return;
17746
17799
  }
17747
17800
  const emitStartedAt = performance.now();
17748
- const dirtyCount = dirtyEntrySet.size;
17801
+ const currentEventId = ctx.runtimeState.build.hmr.profile.eventId;
17802
+ const activeDirtyEntrySet = currentEventId ? new Set([...dirtyEntrySet].filter((entryId) => {
17803
+ const eventId = dirtyEntryEventIds.get(entryId);
17804
+ return eventId === void 0 || eventId === currentEventId;
17805
+ })) : dirtyEntrySet;
17806
+ if (!activeDirtyEntrySet.size) {
17807
+ options?.hmr?.setDidEmitAllEntries?.(false);
17808
+ options?.hmr?.setLastEmittedEntries?.(/* @__PURE__ */ new Set());
17809
+ options?.hmr?.setLastHmrEntries?.(/* @__PURE__ */ new Set());
17810
+ options?.hmr?.setSkipSharedChunkRefresh?.(true);
17811
+ return;
17812
+ }
17813
+ const dirtyCount = activeDirtyEntrySet.size;
17749
17814
  const pendingResolution = resolvePendingEntryIds({
17750
17815
  isDev: Boolean(ctx.configService?.isDev),
17751
17816
  mode: hmrSharedChunksMode,
17752
17817
  resolvedEntryMap,
17753
- dirtyEntrySet,
17818
+ dirtyEntrySet: activeDirtyEntrySet,
17754
17819
  dirtyEntryReasons,
17755
17820
  dirtyReasonSummary: ctx.runtimeState.build.hmr.profile.dirtyReasonSummary,
17756
17821
  sharedChunkImporters: hmrSharedChunkImporters,
@@ -17761,11 +17826,13 @@ function useLoadEntry(ctx, options) {
17761
17826
  const pending = [];
17762
17827
  lastActualEmittedEntryIds.clear();
17763
17828
  lastChunkEmittedEntryIds.clear();
17829
+ lastEmittedChunkFileNames.clear();
17764
17830
  metadataEntryIds.clear();
17765
17831
  for (const entryId of pendingEntryIds) {
17766
17832
  if (dirtyEntryReasons.get(entryId) === "metadata") metadataEntryIds.add(entryId);
17767
17833
  dirtyEntrySet.delete(entryId);
17768
17834
  dirtyEntryReasons.delete(entryId);
17835
+ dirtyEntryEventIds.delete(entryId);
17769
17836
  const resolvedId = resolvedEntryMap.get(entryId);
17770
17837
  if (!resolvedId) continue;
17771
17838
  pending.push(resolvedId);
@@ -17779,6 +17846,11 @@ function useLoadEntry(ctx, options) {
17779
17846
  if (pending.length) await Promise.all(emitEntriesChunks.call(this, pending));
17780
17847
  const actualEmittedEntryIds = new Set(lastActualEmittedEntryIds);
17781
17848
  const actualChunkEmittedEntryIds = new Set(lastChunkEmittedEntryIds);
17849
+ for (const entryId of actualEmittedEntryIds) {
17850
+ if (!rootInputIds?.has(entryId)) continue;
17851
+ lastEmittedChunkFileNames.add(changeFileExtension(ctx.configService.relativeOutputPath(entryId), ".js"));
17852
+ }
17853
+ if (isEntryAutoRoutesRefresh(ctx.runtimeState.build.hmr.profile.dirtyReasonSummary)) for (const entryId of actualChunkEmittedEntryIds) lastEmittedChunkFileNames.add(changeFileExtension(ctx.configService.relativeOutputPath(entryId), ".js"));
17782
17854
  const hmrEntryIds = new Set(actualEmittedEntryIds);
17783
17855
  const skipSharedChunkRefresh = actualChunkEmittedEntryIds.size === 0;
17784
17856
  const shouldEmitAllEntries = actualChunkEmittedEntryIds.size > 0 && (actualEmittedEntryIds.size === resolvedEntryMap.size || pendingResolution.shouldEmitAllEntries === true);
@@ -17805,6 +17877,7 @@ const IMPLICIT_REQUIRE_RE = /\b(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*requir
17805
17877
  const REQUIRE_CALL_RE = /\brequire\((`[^`]+`|'[^']+'|"[^"]+")\)/g;
17806
17878
  const WEVU_SRC_CHUNK_RE = /(?:^|\/)wevu-src\.js$/;
17807
17879
  const WEVU_EXPORT_ALIASES = [["defineComponent", "__wevuDefineComponent"], ["createWevuComponent", "__wevuCreateWevuComponent"]];
17880
+ const WEVU_INTERNAL_RUNTIME_EXPORTS = ["createApp", "setWevuDefaults"];
17808
17881
  const JS_IDENTIFIER_RE = /^[A-Z_$][\w$]*$/i;
17809
17882
  function filterPluginBundleOutputs(bundle, configService) {
17810
17883
  if (configService.pluginOnly) return;
@@ -17850,6 +17923,10 @@ function resolveRelativeImport(fromFile, specifier) {
17850
17923
  const absolute = path.posix.resolve("/", dir, specifier);
17851
17924
  return absolute.startsWith("/") ? absolute.slice(1) : absolute;
17852
17925
  }
17926
+ function normalizeRelativeRequireSpecifier(fromFile, targetFile) {
17927
+ const relative = path.posix.relative(path.posix.dirname(fromFile), targetFile);
17928
+ return relative.startsWith(".") ? relative : `./${relative}`;
17929
+ }
17853
17930
  function findImplicitRequireRemovalRanges(chunk, targetFileNames) {
17854
17931
  const code = chunk.code;
17855
17932
  const ranges = [];
@@ -17913,6 +17990,101 @@ function syncChunkImportsFromRequireCalls(bundle) {
17913
17990
  chunk.imports = [...nextImports];
17914
17991
  }
17915
17992
  }
17993
+ function parseNamedImportBindings(importClause) {
17994
+ return importClause.split(",").map((segment) => {
17995
+ const trimmed = segment.trim();
17996
+ if (!trimmed) return;
17997
+ const [imported, local] = trimmed.split(/\s+as\s+/);
17998
+ const importedName = imported?.trim();
17999
+ const localName = local?.trim() || importedName;
18000
+ if (!importedName || !localName) return;
18001
+ return {
18002
+ importedName,
18003
+ localName
18004
+ };
18005
+ }).filter((item) => Boolean(item));
18006
+ }
18007
+ function collectExistingExportNames(code) {
18008
+ return new Set(Array.from(code.matchAll(/Object\.defineProperty\(exports,\s*["']([^"']+)["']/g), (match) => match[1]));
18009
+ }
18010
+ function collectChunkExportNames(chunk) {
18011
+ return collectExistingExportNames(chunk.code);
18012
+ }
18013
+ function resolveWevuInternalRuntimeChunk(bundle, importNames) {
18014
+ const requiredNames = new Set(importNames);
18015
+ if (!requiredNames.size) return;
18016
+ return Object.values(bundle).find((output) => {
18017
+ if (!output || output.type !== "chunk" || typeof output.code !== "string" || !output.fileName.startsWith("weapp-vendors/")) return false;
18018
+ const exports = collectChunkExportNames(output);
18019
+ return [...requiredNames].every((name) => exports.has(name));
18020
+ });
18021
+ }
18022
+ function resolveOutputCode(output) {
18023
+ if (output.type === "chunk") return output.code;
18024
+ if (typeof output.source === "string") return output.source;
18025
+ if (output.source == null) return;
18026
+ return Buffer.from(output.source).toString();
18027
+ }
18028
+ function updateOutputCode(output, code) {
18029
+ if (output.type === "chunk") {
18030
+ output.code = code;
18031
+ return;
18032
+ }
18033
+ output.source = code;
18034
+ }
18035
+ function formatNamedRequireBindings(bindings) {
18036
+ return bindings.map(({ importedName, localName }) => {
18037
+ return importedName === localName ? importedName : `${importedName}: ${localName}`;
18038
+ }).join(", ");
18039
+ }
18040
+ function rewriteWevuInternalRuntimeImports(bundle, options = {}) {
18041
+ const importRe = /\bimport\s*\{([^}]*)\}\s*from\s*["']wevu\/internal-runtime["'];?/g;
18042
+ const currentRuntimeChunk = resolveWevuInternalRuntimeChunk(bundle, WEVU_INTERNAL_RUNTIME_EXPORTS);
18043
+ if (currentRuntimeChunk) options.onRuntimeFileName?.(currentRuntimeChunk.fileName);
18044
+ for (const output of Object.values(bundle)) {
18045
+ if (!output || output.type !== "chunk" && output.type !== "asset") continue;
18046
+ const code = resolveOutputCode(output);
18047
+ if (typeof code !== "string") continue;
18048
+ const fileName = output.fileName;
18049
+ if (!fileName.endsWith(".js")) continue;
18050
+ let rewritten = code;
18051
+ let changed = false;
18052
+ const requiredRuntimeFileNames = /* @__PURE__ */ new Set();
18053
+ rewritten = rewritten.replace(importRe, (full, importClause) => {
18054
+ const bindings = parseNamedImportBindings(importClause);
18055
+ const runtimeChunk = resolveWevuInternalRuntimeChunk(bundle, bindings.map((binding) => binding.importedName));
18056
+ const runtimeFileName = runtimeChunk?.fileName ?? options.runtimeFileName;
18057
+ if (!runtimeFileName) return full;
18058
+ if (runtimeChunk?.fileName) options.onRuntimeFileName?.(runtimeChunk.fileName);
18059
+ changed = true;
18060
+ requiredRuntimeFileNames.add(runtimeFileName);
18061
+ const specifier = normalizeRelativeRequireSpecifier(fileName, runtimeFileName);
18062
+ return `const { ${formatNamedRequireBindings(bindings)} } = require(${JSON.stringify(specifier)});`;
18063
+ });
18064
+ if (!changed) continue;
18065
+ updateOutputCode(output, rewritten);
18066
+ if (output.type !== "chunk") continue;
18067
+ const chunk = output;
18068
+ const nextImports = new Set(Array.isArray(chunk.imports) ? chunk.imports : []);
18069
+ for (const runtimeFileName of requiredRuntimeFileNames) nextImports.add(runtimeFileName);
18070
+ for (const match of chunk.code.matchAll(REQUIRE_CALL_RE)) {
18071
+ const specifier = stripQuotes(match[1]);
18072
+ const resolved = resolveRelativeImport(chunk.fileName, specifier);
18073
+ if (resolved && resolved !== chunk.fileName && bundle[resolved]?.type === "chunk") nextImports.add(resolved);
18074
+ }
18075
+ chunk.imports = [...nextImports];
18076
+ }
18077
+ }
18078
+ function rewriteWevuInternalRuntimeImportCode(fileName, code, runtimeFileName) {
18079
+ if (!runtimeFileName || !code.includes("wevu/internal-runtime")) return code;
18080
+ const output = {
18081
+ type: "asset",
18082
+ fileName,
18083
+ source: code
18084
+ };
18085
+ rewriteWevuInternalRuntimeImports({ [fileName]: output }, { runtimeFileName });
18086
+ return typeof output.source === "string" ? output.source : Buffer.from(output.source).toString();
18087
+ }
17916
18088
  function resolveRequireTarget(fromFile, specifier) {
17917
18089
  if (!specifier.startsWith(".")) return "";
17918
18090
  return resolveRelativeImport(fromFile, specifier);
@@ -17959,9 +18131,6 @@ function resolveWevuExportAliasMap(wevuChunk) {
17959
18131
  }
17960
18132
  return aliases;
17961
18133
  }
17962
- function collectExistingExportNames(code) {
17963
- return new Set(Array.from(code.matchAll(/Object\.defineProperty\(exports,\s*["']([^"']+)["']/g), (match) => match[1]));
17964
- }
17965
18134
  function collectImportedWevuRuntimeMembers(bundle, wevuChunkFileName) {
17966
18135
  const members = /* @__PURE__ */ new Set();
17967
18136
  for (const output of Object.values(bundle)) {
@@ -18611,6 +18780,21 @@ function stripLeadingBlankLines(code) {
18611
18780
  function isSourceStyleAsset(fileName) {
18612
18781
  return SOURCE_STYLE_ASSET_RE.test(fileName);
18613
18782
  }
18783
+ function hasStyleAssetOutput(bundle) {
18784
+ return Object.entries(bundle).some(([bundleKey, output]) => {
18785
+ if (output?.type !== "asset") return false;
18786
+ return isSourceStyleAsset(output.fileName || bundleKey);
18787
+ });
18788
+ }
18789
+ function hasStyleDirtyReason(dirtyReasonSummary) {
18790
+ return dirtyReasonSummary.some((reason) => reason.startsWith("style-sidecar:") || reason.startsWith("css-importer:") || reason.startsWith("entry-local-asset:"));
18791
+ }
18792
+ function shouldSkipUnchangedStyleHmrBundle(ctx, bundle) {
18793
+ if (!ctx.configService?.isDev) return false;
18794
+ const dirtyReasonSummary = ctx.runtimeState?.build?.hmr?.profile?.dirtyReasonSummary;
18795
+ if (!dirtyReasonSummary?.length) return false;
18796
+ return !hasStyleDirtyReason(dirtyReasonSummary) && !hasStyleAssetOutput(bundle);
18797
+ }
18614
18798
  function shouldPreprocessWithVite(fileName) {
18615
18799
  return VITE_PREPROCESS_STYLE_RE.test(fileName);
18616
18800
  }
@@ -18629,12 +18813,26 @@ async function preprocessStyleSource(code, fileName, resolvedConfig, options) {
18629
18813
  function resolveOutputStyleFileName(configService, stylePath) {
18630
18814
  return configService.relativeOutputPath(changeFileExtension(stylePath, configService.outputExtensions.wxss));
18631
18815
  }
18816
+ function isUnchangedDevHmrStyleAsset(ctx, normalizedFileName, current, source) {
18817
+ const hmrState = ctx.runtimeState?.build?.hmr;
18818
+ const currentHmrFile = hmrState?.profile.file;
18819
+ if (typeof currentHmrFile === "string") {
18820
+ const currentOutputFile = resolveOutputStyleFileName(ctx.configService, currentHmrFile);
18821
+ if (currentOutputFile && toPosixPath(currentOutputFile) === normalizedFileName) return false;
18822
+ }
18823
+ return ctx.configService?.isDev === true && (hmrState?.didEmitAllEntries === true || (hmrState?.lastHmrEntryIds?.size ?? 0) > 0 || (hmrState?.lastEmittedEntryIds?.size ?? 0) > 0 || hmrState?.profile.event !== void 0) && current === source && ctx.runtimeState?.css?.emittedSource.get(normalizedFileName) === source;
18824
+ }
18632
18825
  function emitCssAssetIfChanged(ctx, pluginCtx, bundle, fileName, source) {
18633
18826
  const normalizedFileName = toPosixPath(fileName);
18634
- const cache = ctx.runtimeState?.css.emittedSource;
18827
+ const cache = ctx.runtimeState?.css?.emittedSource;
18635
18828
  const existing = bundle[fileName];
18636
18829
  if (existing?.type === "asset") {
18637
- if ((existing.source?.toString?.() ?? "") !== source) existing.source = source;
18830
+ const current = existing.source?.toString?.() ?? "";
18831
+ if (isUnchangedDevHmrStyleAsset(ctx, normalizedFileName, current, source)) {
18832
+ delete bundle[fileName];
18833
+ return false;
18834
+ }
18835
+ if (current !== source) existing.source = source;
18638
18836
  cache?.set(normalizedFileName, source);
18639
18837
  return true;
18640
18838
  }
@@ -18702,7 +18900,9 @@ async function handleBundleEntry(ctx, bundle, bundleKey, asset, configService, s
18702
18900
  if (fileName !== bundleKey) {
18703
18901
  delete bundle[bundleKey];
18704
18902
  emitCssAssetIfChanged(ctx, this, bundle, fileName, processedCss);
18705
- } else if (processedCss !== source) asset.source = processedCss;
18903
+ } else if (isUnchangedDevHmrStyleAsset(ctx, toPosixPath(fileName), source, processedCss)) delete bundle[bundleKey];
18904
+ else if (processedCss !== source) asset.source = processedCss;
18905
+ ctx.runtimeState?.css?.emittedSource.set(toPosixPath(fileName), processedCss);
18706
18906
  }
18707
18907
  return;
18708
18908
  }
@@ -18783,6 +18983,7 @@ function css(ctx) {
18783
18983
  resolvedConfig = config;
18784
18984
  },
18785
18985
  async generateBundle(_opts, bundle) {
18986
+ if (shouldSkipUnchangedStyleHmrBundle(ctx, bundle)) return;
18786
18987
  await generateBundleSharedCss.call(this, ctx, configService, bundle, resolvedConfig);
18787
18988
  }
18788
18989
  }];
@@ -19198,6 +19399,11 @@ function injectRequestGlobalsIntoSfc(source, targets, options) {
19198
19399
  //#endregion
19199
19400
  //#region src/plugins/outputFinalizer.ts
19200
19401
  const PREPROCESSOR_STYLE_ASSET_RE = /\.(?:less|sass|scss|styl|stylus|pcss|postcss|sss)$/i;
19402
+ function outputSourceToString(output) {
19403
+ if (output.type === "chunk") return output.code;
19404
+ const source = output.source;
19405
+ return typeof source === "string" ? source : Buffer.from(source).toString("base64");
19406
+ }
19201
19407
  function normalizePreprocessorStyleAssets(bundle, styleExtension, emitAsset) {
19202
19408
  if (!styleExtension) return;
19203
19409
  for (const [bundleFileName, output] of Object.entries(bundle)) {
@@ -19221,12 +19427,43 @@ function normalizePreprocessorStyleAssets(bundle, styleExtension, emitAsset) {
19221
19427
  });
19222
19428
  }
19223
19429
  }
19430
+ function pruneUneventedDevHmrChunks(ctx, bundle) {
19431
+ const emittedChunkFileNames = ctx.runtimeState?.build?.hmr?.lastEmittedChunkFileNames;
19432
+ if (!ctx.configService?.isDev || ctx.runtimeState?.build?.hmr?.profile?.event === void 0 || !emittedChunkFileNames?.size) return;
19433
+ for (const [fileName, output] of Object.entries(bundle)) if (output?.type === "chunk" && !emittedChunkFileNames.has(fileName) && !emittedChunkFileNames.has(output.fileName)) delete bundle[fileName];
19434
+ }
19435
+ function pruneUnchangedDevHmrOutputs(ctx, bundle, rewriteOptions) {
19436
+ const cache = ctx.runtimeState?.build?.output?.emittedSource;
19437
+ if (!ctx.configService?.isDev || !cache) return;
19438
+ const isHmrBuild = ctx.runtimeState?.build?.hmr?.profile?.event !== void 0;
19439
+ rewriteWevuInternalRuntimeImports(bundle, rewriteOptions);
19440
+ pruneUneventedDevHmrChunks(ctx, bundle);
19441
+ for (const [fileName, output] of Object.entries(bundle)) {
19442
+ const source = outputSourceToString(output);
19443
+ if (isHmrBuild && cache.get(fileName) === source) {
19444
+ delete bundle[fileName];
19445
+ continue;
19446
+ }
19447
+ cache.set(fileName, source);
19448
+ }
19449
+ }
19224
19450
  function createOutputFinalizerPlugin(ctx) {
19451
+ const wevuRuntimeRewriteOptions = {
19452
+ get runtimeFileName() {
19453
+ return ctx.runtimeState?.build?.output?.wevuInternalRuntimeFileName;
19454
+ },
19455
+ onRuntimeFileName(fileName) {
19456
+ const outputState = ctx.runtimeState?.build?.output;
19457
+ if (outputState) outputState.wevuInternalRuntimeFileName = fileName;
19458
+ }
19459
+ };
19225
19460
  return {
19226
19461
  name: "weapp-vite:output-finalizer",
19227
19462
  enforce: "post",
19228
19463
  generateBundle(_options, bundle) {
19464
+ rewriteWevuInternalRuntimeImports(bundle, wevuRuntimeRewriteOptions);
19229
19465
  normalizePreprocessorStyleAssets(bundle, ctx.configService.outputExtensions?.wxss, (asset) => this.emitFile(asset));
19466
+ pruneUnchangedDevHmrOutputs(ctx, bundle, wevuRuntimeRewriteOptions);
19230
19467
  }
19231
19468
  };
19232
19469
  }
@@ -20339,6 +20576,9 @@ function pruneHmrMetadataOnlyChunks(bundle, state) {
20339
20576
  function hasChunkOutputs(bundle) {
20340
20577
  return Object.values(bundle).some((output) => output?.type === "chunk");
20341
20578
  }
20579
+ function isAssetOnlyDevHmrBundle(bundle, state) {
20580
+ return state.ctx.configService.isDev && state.hmrState.hasBuiltOnce && state.hmrState.skipSharedChunkRefresh && !hasChunkOutputs(bundle);
20581
+ }
20342
20582
  function isStableHmrSharedChunk(fileName) {
20343
20583
  return fileName.startsWith("weapp-vendors/") || !fileName.includes("/") && fileName !== "app.js";
20344
20584
  }
@@ -20352,7 +20592,25 @@ function prunePartialHmrStableSharedChunks(bundle, state) {
20352
20592
  continue;
20353
20593
  }
20354
20594
  const activeEntryIds = state.hmrState.lastHmrEntryIds?.size ? state.hmrState.lastHmrEntryIds : state.hmrState.lastEmittedEntryIds;
20355
- if (!Array.from(knownImporters).every((entryId) => activeEntryIds?.has(entryId))) delete bundle[fileName];
20595
+ if (!Array.from(knownImporters).every((entryId) => activeEntryIds?.has(entryId))) {
20596
+ delete bundle[fileName];
20597
+ continue;
20598
+ }
20599
+ const emittedChunkFileNames = state.ctx.runtimeState?.build?.hmr?.lastEmittedChunkFileNames;
20600
+ if (emittedChunkFileNames) {
20601
+ emittedChunkFileNames.add(fileName);
20602
+ if (output.fileName) emittedChunkFileNames.add(output.fileName);
20603
+ }
20604
+ }
20605
+ }
20606
+ function retainFullEntryHmrChunks(bundle, state) {
20607
+ if (!state.ctx.configService.isDev || !state.hmrState.hasBuiltOnce || !state.hmrState.didEmitAllEntries) return;
20608
+ const emittedChunkFileNames = state.ctx.runtimeState?.build?.hmr?.lastEmittedChunkFileNames;
20609
+ if (!emittedChunkFileNames?.size) return;
20610
+ for (const [fileName, output] of Object.entries(bundle)) {
20611
+ if (output?.type !== "chunk") continue;
20612
+ emittedChunkFileNames.add(fileName);
20613
+ if (output.fileName) emittedChunkFileNames.add(output.fileName);
20356
20614
  }
20357
20615
  }
20358
20616
  function createGenerateBundleHook(state, isPluginBuild) {
@@ -20369,6 +20627,7 @@ function createGenerateBundleHook(state, isPluginBuild) {
20369
20627
  const rolldownBundle = bundle;
20370
20628
  await flushIndependentBuilds.call(this, state);
20371
20629
  pruneHmrMetadataOnlyChunks(rolldownBundle, state);
20630
+ const assetOnlyDevHmrBundle = isAssetOnlyDevHmrBundle(rolldownBundle, state);
20372
20631
  if (isPluginBuild) {
20373
20632
  filterPluginBundleOutputs(rolldownBundle, configService);
20374
20633
  if (!shouldRewriteBundleNpmImports(configService.platform)) {
@@ -20390,12 +20649,20 @@ function createGenerateBundleHook(state, isPluginBuild) {
20390
20649
  let redundantBytesTotal = 0;
20391
20650
  if (configService.isDev && state.hmrSharedChunksMode === "auto") {
20392
20651
  const forceFullSharedChunkRefresh = process.env.WEAPP_VITE_FORCE_FULL_HMR_SHARED_CHUNKS === "1";
20393
- if (state.hmrState.skipSharedChunkRefresh && state.hmrState.hasBuiltOnce && !forceFullSharedChunkRefresh && !hasChunkOutputs(rolldownBundle)) {} else if (state.hmrState.didEmitAllEntries || !state.hmrState.hasBuiltOnce) refreshSharedChunkImporters(rolldownBundle, state);
20652
+ if (assetOnlyDevHmrBundle && !forceFullSharedChunkRefresh) {} else if (state.hmrState.didEmitAllEntries || !state.hmrState.hasBuiltOnce) refreshSharedChunkImporters(rolldownBundle, state);
20394
20653
  else if (forceFullSharedChunkRefresh) refreshSharedChunkImporters(rolldownBundle, state);
20395
20654
  else if (state.hmrState.lastHmrEntryIds?.size) refreshPartialSharedChunkImporters(rolldownBundle, state, state.hmrState.lastHmrEntryIds);
20396
20655
  else if (state.hmrState.lastEmittedEntryIds?.size) refreshPartialSharedChunkImporters(rolldownBundle, state, state.hmrState.lastEmittedEntryIds);
20397
20656
  state.hmrState.hasBuiltOnce = true;
20398
20657
  }
20658
+ prunePartialHmrStableSharedChunks(rolldownBundle, state);
20659
+ retainFullEntryHmrChunks(rolldownBundle, state);
20660
+ pruneUneventedDevHmrChunks(ctx, rolldownBundle);
20661
+ if (assetOnlyDevHmrBundle) {
20662
+ normalizePreprocessorStyleAssets(rolldownBundle, state.ctx.configService.outputExtensions?.wxss, (asset) => this.emitFile(asset));
20663
+ refreshModuleGraph(this, state);
20664
+ return;
20665
+ }
20399
20666
  function matchSubPackage(filePath) {
20400
20667
  return subPackageRoots.find((root) => filePath === root || filePath.startsWith(`${root}/`));
20401
20668
  }
@@ -20537,9 +20804,15 @@ function createGenerateBundleHook(state, isPluginBuild) {
20537
20804
  targets: injectRequestGlobalsOptions?.targets ?? []
20538
20805
  }, (asset) => this.emitFile(asset));
20539
20806
  if (injectRequestGlobalsOptions?.targets?.length) inlineRequestGlobalsAppRegisteredInstallerChunks(rolldownBundle, installerChunks, preservedRequestGlobalsInstallerChunks);
20807
+ rewriteWevuInternalRuntimeImports(rolldownBundle, {
20808
+ runtimeFileName: state.ctx.runtimeState?.build?.output?.wevuInternalRuntimeFileName,
20809
+ onRuntimeFileName(fileName) {
20810
+ const outputState = state.ctx.runtimeState?.build?.output;
20811
+ if (outputState) outputState.wevuInternalRuntimeFileName = fileName;
20812
+ }
20813
+ });
20540
20814
  stabilizeWevuRuntimeChunkAccess(rolldownBundle);
20541
20815
  syncChunkImportsFromRequireCalls(rolldownBundle);
20542
- prunePartialHmrStableSharedChunks(rolldownBundle, state);
20543
20816
  normalizePreprocessorStyleAssets(rolldownBundle, state.ctx.configService.outputExtensions?.wxss, (asset) => this.emitFile(asset));
20544
20817
  refreshModuleGraph(this, state);
20545
20818
  if (configService.weappViteConfig?.debug?.watchFiles) {
@@ -20559,6 +20832,34 @@ function createGenerateBundleHook(state, isPluginBuild) {
20559
20832
  function isCurrentStyleSidecarUpdate(state) {
20560
20833
  return state.ctx.runtimeState.build?.hmr?.profile.dirtyReasonSummary?.some((item) => item.startsWith("style-sidecar:")) === true;
20561
20834
  }
20835
+ function shouldEmitJsonDuringRenderStart(state) {
20836
+ const { ctx, hmrState } = state;
20837
+ if (!ctx.configService.isDev || !hmrState.hasBuiltOnce || hmrState.didEmitAllEntries) return true;
20838
+ const dirtyReasons = ctx.runtimeState.build.hmr.profile.dirtyReasonSummary;
20839
+ if (!dirtyReasons?.length) return true;
20840
+ return dirtyReasons.some((reason) => reason.startsWith("json-sidecar:") || reason.startsWith("entry-json-only:") || reason.startsWith("config-restart:") || reason.startsWith("auto-routes-topology:") || reason.startsWith("app-shell-dependent:") || reason.startsWith("layout-self:") || reason.startsWith("layout-dependent:") || reason.startsWith("layout-fallback-full:"));
20841
+ }
20842
+ function resolveIncrementalHmrWxmlTargetIds(state) {
20843
+ const { ctx, hmrState, entriesMap } = state;
20844
+ if (!ctx.configService.isDev || !hmrState.hasBuiltOnce || hmrState.didEmitAllEntries) return;
20845
+ const targets = /* @__PURE__ */ new Set();
20846
+ const currentFile = ctx.runtimeState.build.hmr.profile.file;
20847
+ if (typeof currentFile === "string" && isTemplate(currentFile)) targets.add(normalizeWatchPath(currentFile));
20848
+ const entryIds = hmrState.lastHmrEntryIds?.size ? hmrState.lastHmrEntryIds : hmrState.lastEmittedEntryIds;
20849
+ for (const entryId of entryIds ?? []) {
20850
+ const candidates = [
20851
+ entryId,
20852
+ ctx.configService.relativeAbsoluteSrcRoot(entryId),
20853
+ removeExtensionDeep(entryId),
20854
+ removeExtensionDeep(ctx.configService.relativeAbsoluteSrcRoot(entryId))
20855
+ ];
20856
+ for (const candidate of candidates) {
20857
+ const entry = entriesMap.get(candidate);
20858
+ if (entry && "templatePath" in entry && entry.templatePath) targets.add(normalizeWatchPath(entry.templatePath));
20859
+ }
20860
+ }
20861
+ return targets.size ? targets : void 0;
20862
+ }
20562
20863
  function createRenderStartHook(state) {
20563
20864
  const { ctx, subPackageMeta, buildTarget } = state;
20564
20865
  return async function renderStart() {
@@ -20566,20 +20867,22 @@ function createRenderStartHook(state) {
20566
20867
  const currentFile = ctx.runtimeState.build.hmr.profile.file;
20567
20868
  if (typeof currentFile === "string" && path.extname(currentFile)) await emitStyleSidecarAsset(ctx, this, {}, currentFile, state.resolvedConfig);
20568
20869
  }
20569
- emitJsonAssets.call(this, state);
20870
+ const runtime = {
20871
+ addWatchFile: typeof this.addWatchFile === "function" ? (id) => {
20872
+ this.addWatchFile(normalizeWatchPath(id));
20873
+ } : void 0,
20874
+ emitFile: (asset) => {
20875
+ this.emitFile(asset);
20876
+ }
20877
+ };
20878
+ if (shouldEmitJsonDuringRenderStart(state)) emitJsonAssets.call(this, state);
20570
20879
  state.watchFilesSnapshot = emitWxmlAssetsWithCache({
20571
- runtime: {
20572
- addWatchFile: typeof this.addWatchFile === "function" ? (id) => {
20573
- this.addWatchFile(normalizeWatchPath(id));
20574
- } : void 0,
20575
- emitFile: (asset) => {
20576
- this.emitFile(asset);
20577
- }
20578
- },
20880
+ runtime,
20579
20881
  compiler: ctx,
20580
20882
  subPackageMeta,
20581
20883
  emittedCodeCache: ctx.runtimeState.wxml.emittedCode,
20582
- buildTarget
20884
+ buildTarget,
20885
+ targetIds: resolveIncrementalHmrWxmlTargetIds(state)
20583
20886
  });
20584
20887
  };
20585
20888
  }
@@ -20961,6 +21264,7 @@ function shouldTransformId(id, options) {
20961
21264
  function createTransformHook(state) {
20962
21265
  const { configService } = state.ctx;
20963
21266
  const astEngine = resolveAstEngine(configService.weappViteConfig);
21267
+ const injectOptions = resolveInjectWeapiOptions(configService);
20964
21268
  const injectRequestGlobalsOptions = resolveRequestRuntimeOptions({
20965
21269
  appPrelude: configService.weappViteConfig?.appPrelude,
20966
21270
  webRuntime: configService.weappViteConfig?.injectWebRuntimeGlobals,
@@ -20991,7 +21295,6 @@ function createTransformHook(state) {
20991
21295
  })}${code}`;
20992
21296
  }
20993
21297
  return async function transform(code, id) {
20994
- const injectOptions = resolveInjectWeapiOptions(configService);
20995
21298
  if (!shouldTransformId(id, {
20996
21299
  absoluteSrcRoot: configService.absoluteSrcRoot,
20997
21300
  isEntry: (sourceId) => state.loadedEntrySet?.has(sourceId) === true || state.resolvedEntryMap?.has(sourceId) === true
@@ -21426,6 +21729,24 @@ function isAutoRoutesGeneratedFileChange(state, normalizedId) {
21426
21729
  managedOutputPaths: resolveAutoRoutesManagedOutputPaths(state.ctx)
21427
21730
  });
21428
21731
  }
21732
+ function isAutoRoutesPagesRelatedChange(state, normalizedId) {
21733
+ const configService = state.ctx.configService;
21734
+ if (!configService) return false;
21735
+ const { autoRoutesConfig, subPackageRoots } = resolveAutoRoutesMatcherContext(state.ctx);
21736
+ return isAutoRoutesPagesRelatedPath(normalizedId, {
21737
+ cwd: configService.cwd,
21738
+ absoluteSrcRoot: configService.absoluteSrcRoot,
21739
+ include: autoRoutesConfig.include,
21740
+ managedOutputPaths: resolveAutoRoutesManagedOutputPaths(state.ctx),
21741
+ subPackageRoots
21742
+ });
21743
+ }
21744
+ function invalidateAutoRoutesModuleCache(state) {
21745
+ invalidateFileCache("weapp-vite/auto-routes");
21746
+ invalidateFileCache("virtual:weapp-vite-auto-routes");
21747
+ invalidateFileCache("\0weapp-vite:auto-routes");
21748
+ for (const target of resolveAutoRoutesAliasTargets(state.ctx.configService?.packageInfo?.rootPath)) invalidateFileCache(normalizeFsResolvedId(target));
21749
+ }
21429
21750
  function isConfigFileDependencyChange(state, normalizedId) {
21430
21751
  return state.ctx.configService.configFileDependencies.some((dependency) => normalizeFsResolvedId(dependency) === normalizedId);
21431
21752
  }
@@ -21442,6 +21763,7 @@ async function normalizeWatchEvent(id, event, options) {
21442
21763
  const primaryScriptId = primaryScript.path ? normalizeFsResolvedId(primaryScript.path) : "";
21443
21764
  if (primaryScriptId && options.resolvedEntryMap.has(primaryScriptId)) return "update";
21444
21765
  }
21766
+ if (options.emittedJsonPaths?.has(id)) return "update";
21445
21767
  }
21446
21768
  if (event !== "delete") return event;
21447
21769
  for (const delayMs of ATOMIC_SAVE_RECHECK_DELAYS_MS) {
@@ -21499,6 +21821,13 @@ async function isAppShellTopologyUpdate(state, normalizedId) {
21499
21821
  return false;
21500
21822
  }
21501
21823
  }
21824
+ function isAppEntryAutoRoutesSignatureStale(state, normalizedId) {
21825
+ if (!isAppVueFile(normalizedId)) return false;
21826
+ const currentSignature = state.ctx.autoRoutesService?.getSignature?.();
21827
+ const previousSignature = state.ctx.runtimeState.build.hmr.appEntryAutoRoutesSignature;
21828
+ if (typeof currentSignature !== "string") return false;
21829
+ return previousSignature !== currentSignature;
21830
+ }
21502
21831
  async function processChangedFile(state, id, event) {
21503
21832
  const { ctx, subPackageMeta, loadEntry, loadedEntrySet, resolvedEntryMap } = state;
21504
21833
  const { scanService, configService, buildService } = ctx;
@@ -21566,6 +21895,25 @@ async function processChangedFile(state, id, event) {
21566
21895
  }
21567
21896
  markEntryDirtyWithCause(normalizedId, reason, cause);
21568
21897
  };
21898
+ const markAppEntryForJsonEmit = () => {
21899
+ const appEntryId = scanService.appEntry?.path ? normalizeFsResolvedId(scanService.appEntry.path) : void 0;
21900
+ if (!appEntryId || !resolvedEntryMap.has(appEntryId)) return false;
21901
+ for (const jsonEmitRecord of state.jsonEmitFilesMap.values()) if (jsonEmitRecord.entry.jsonPath && normalizeFsResolvedId(jsonEmitRecord.entry.jsonPath) === normalizedId) {
21902
+ markEntryDirtyWithCause(appEntryId, "metadata", "json-sidecar");
21903
+ return true;
21904
+ }
21905
+ return false;
21906
+ };
21907
+ const markAppEntryForAutoRoutesTopology = () => {
21908
+ const appEntryId = scanService.appEntry?.path ? normalizeFsResolvedId(scanService.appEntry.path) : void 0;
21909
+ if (!appEntryId || !resolvedEntryMap.has(appEntryId)) return false;
21910
+ invalidateFileCache(appEntryId);
21911
+ invalidateAutoRoutesModuleCache(state);
21912
+ loadEntry?.invalidateResolveCache?.();
21913
+ ctx.runtimeState.build.hmr.appEntryAutoRoutesSignature = void 0;
21914
+ markEntryDirtyWithCause(appEntryId, "direct", "auto-routes-topology");
21915
+ return true;
21916
+ };
21569
21917
  const addCssImporterEntries = async (startId) => {
21570
21918
  const { importers, scripts } = await collectAffectedScriptsAndImporters(ctx, startId);
21571
21919
  for (const importer of importers) {
@@ -21580,17 +21928,20 @@ async function processChangedFile(state, id, event) {
21580
21928
  ctx.runtimeState.build.hmr.vueEntryScriptSignatures.delete(normalizedId);
21581
21929
  }
21582
21930
  if ((event === "create" || isDeletedMissingSelf) && isAutoRouteFile) {
21583
- if (await ctx.autoRoutesService?.handleFileChange(normalizedId, event)) {
21584
- dirtyReasonStats.set("auto-routes-topology", 1);
21585
- const appEntryId = scanService.appEntry?.path ? normalizeFsResolvedId(scanService.appEntry.path) : void 0;
21586
- if (appEntryId && resolvedEntryMap.has(appEntryId)) state.markEntryDirty(appEntryId, "direct");
21587
- }
21931
+ if (await ctx.autoRoutesService?.handleFileChange(normalizedId, event)) markAppEntryForAutoRoutesTopology();
21932
+ } else if ((event === "create" || isDeletedMissingSelf) && isAutoRoutesPagesRelatedChange(state, normalizedId)) {
21933
+ const didChangeRoutes = await ctx.autoRoutesService?.handleFileChange(normalizedId, event === "create" ? "create" : "delete");
21934
+ const currentSignature = ctx.autoRoutesService?.getSignature?.();
21935
+ const appEntrySignature = ctx.runtimeState.build.hmr.appEntryAutoRoutesSignature;
21936
+ if (didChangeRoutes || typeof currentSignature === "string" && typeof appEntrySignature === "string" && currentSignature !== appEntrySignature) markAppEntryForAutoRoutesTopology();
21588
21937
  }
21589
21938
  if (event === "update" && isAppVueFile(normalizedId) && resolvedEntryMap.size) {
21590
21939
  const isJsonOnlyVueEntryUpdate = await isVueEntryJsonOnlyUpdate(state, normalizedId);
21940
+ const isAutoRoutesStaleAppEntry = isJsonOnlyVueEntryUpdate && isAppEntryAutoRoutesSignatureStale(state, normalizedId);
21591
21941
  isAppShellTopologyChanged = !isJsonOnlyVueEntryUpdate && await isAppShellTopologyUpdate(state, normalizedId);
21592
21942
  const isLocalAssetOnlyVueEntryUpdate = !isJsonOnlyVueEntryUpdate && !isAppShellTopologyChanged && await isVueEntryLocalAssetOnlyUpdate(state, normalizedId);
21593
- if (!isJsonOnlyVueEntryUpdate && !isLocalAssetOnlyVueEntryUpdate) {
21943
+ if (isAutoRoutesStaleAppEntry) loadEntry?.invalidateResolveCache?.();
21944
+ else if (!isJsonOnlyVueEntryUpdate && !isLocalAssetOnlyVueEntryUpdate) {
21594
21945
  loadEntry?.invalidateResolveCache?.();
21595
21946
  for (const entryId of resolvedEntryMap.keys()) {
21596
21947
  if (entryId === normalizedId || entryId === concreteChangedEntryId) continue;
@@ -21617,7 +21968,8 @@ async function processChangedFile(state, id, event) {
21617
21968
  if (primaryScript.path) {
21618
21969
  markScriptDirty(primaryScript.path, configSuffix ? "json-sidecar" : isStyleFile ? "style-sidecar" : "sidecar-direct");
21619
21970
  handledSidecarMetadataUpdate = true;
21620
- } else if (isStyleFile) {
21971
+ } else if (configSuffix && markAppEntryForJsonEmit()) handledSidecarMetadataUpdate = true;
21972
+ else if (isStyleFile) {
21621
21973
  await addCssImporterEntries(normalizedId);
21622
21974
  handledSidecarMetadataUpdate = true;
21623
21975
  }
@@ -21645,8 +21997,9 @@ async function processChangedFile(state, id, event) {
21645
21997
  }
21646
21998
  if (!isDeletedMissingSelf && isCurrentSubPackageFile(relativeSrc, subPackageMeta) && !handledSidecarMetadataUpdate && (loadedEntrySet.has(normalizedId) || loadedEntrySet.has(concreteChangedEntryId) || resolvedEntryMap.has(normalizedId) || resolvedEntryMap.has(concreteChangedEntryId) || declaredEntryType === "page" || declaredEntryType === "component")) {
21647
21999
  const isJsonOnlyVueEntryUpdate = event === "update" && await isVueEntryJsonOnlyUpdate(state, normalizedId);
22000
+ const isAutoRoutesStaleAppEntry = isJsonOnlyVueEntryUpdate && isAppEntryAutoRoutesSignatureStale(state, normalizedId);
21648
22001
  const isLocalAssetOnlyVueEntryUpdate = !isJsonOnlyVueEntryUpdate && !isAppShellTopologyChanged && event === "update" && await isVueEntryLocalAssetOnlyUpdate(state, normalizedId);
21649
- markChangedEntryDirty(isJsonOnlyVueEntryUpdate || isLocalAssetOnlyVueEntryUpdate ? "metadata" : "direct", isJsonOnlyVueEntryUpdate ? "entry-json-only" : isAppShellTopologyChanged ? "entry-direct" : isLocalAssetOnlyVueEntryUpdate ? "entry-local-asset" : "entry-direct");
22002
+ markChangedEntryDirty(isJsonOnlyVueEntryUpdate && !isAutoRoutesStaleAppEntry || isLocalAssetOnlyVueEntryUpdate ? "metadata" : "direct", isJsonOnlyVueEntryUpdate ? isAutoRoutesStaleAppEntry ? "entry-auto-routes" : "entry-json-only" : isAppShellTopologyChanged ? "entry-direct" : isLocalAssetOnlyVueEntryUpdate ? "entry-local-asset" : "entry-direct");
21650
22003
  } else if (state.layoutEntryDependents.size && state.layoutEntryDependents.get(normalizedId)?.size) {
21651
22004
  const affectedEntries = state.layoutEntryDependents.get(normalizedId);
21652
22005
  for (const entryId of affectedEntries) markEntryDirtyWithCause(entryId, "dependency", "layout-dependent");
@@ -21707,18 +22060,26 @@ async function processChangedFile(state, id, event) {
21707
22060
  function createWatchChangeHook(state) {
21708
22061
  return async function watchChange(id, change) {
21709
22062
  const startedAt = performance.now();
22063
+ const eventId = createHmrProfileEventId();
21710
22064
  const normalizedId = normalizeFsResolvedId(id);
21711
22065
  if (isSkippableResolvedId(normalizedId)) return;
21712
22066
  if (isOutputFileChange(state, normalizedId)) return;
21713
22067
  if (isAutoRoutesGeneratedFileChange(state, normalizedId)) return;
21714
22068
  const event = await normalizeWatchEvent(normalizedId, change.event, {
22069
+ emittedJsonPaths: new Set([...state.jsonEmitFilesMap.values()].map((record) => record.entry.jsonPath ? normalizeFsResolvedId(record.entry.jsonPath) : "").filter(Boolean)),
21715
22070
  loadedEntrySet: state.loadedEntrySet,
21716
22071
  resolvedEntryMap: state.resolvedEntryMap
21717
22072
  });
22073
+ state.ctx.runtimeState.build.hmr.profile = {
22074
+ ...state.ctx.runtimeState.build.hmr.profile,
22075
+ eventId,
22076
+ event,
22077
+ file: normalizedId
22078
+ };
21718
22079
  const dirtyReasonSummary = await processChangedFile(state, normalizedId, event);
21719
22080
  state.ctx.runtimeState.build.hmr.profile = {
21720
22081
  ...state.ctx.runtimeState.build.hmr.profile,
21721
- eventId: createHmrProfileEventId(),
22082
+ eventId,
21722
22083
  event,
21723
22084
  file: normalizedId,
21724
22085
  watchToDirtyMs: performance.now() - startedAt,
@@ -21728,6 +22089,7 @@ function createWatchChangeHook(state) {
21728
22089
  }
21729
22090
  //#endregion
21730
22091
  //#region src/plugins/core/lifecycle/index.ts
22092
+ const CORE_TRANSFORM_FILTER_RE = /\.(?:[cm]?[jt]sx?|vue)(?:\?.*)?$/;
21731
22093
  function createCoreLifecyclePlugin(state) {
21732
22094
  const isPluginBuild = state.buildTarget === "plugin";
21733
22095
  return {
@@ -21740,7 +22102,10 @@ function createCoreLifecyclePlugin(state) {
21740
22102
  watchChange: createWatchChangeHook(state),
21741
22103
  options: createOptionsHook(state),
21742
22104
  load: createLoadHook(state),
21743
- transform: createTransformHook(state),
22105
+ transform: {
22106
+ filter: { id: CORE_TRANSFORM_FILTER_RE },
22107
+ handler: createTransformHook(state)
22108
+ },
21744
22109
  renderStart: createRenderStartHook(state),
21745
22110
  generateBundle: createGenerateBundleHook(state, isPluginBuild),
21746
22111
  buildEnd: createBuildEndHook(state)
@@ -22559,7 +22924,7 @@ async function emitCompiledEntryBundleAssets(options) {
22559
22924
  const shouldMergeJsonAsset = isAppVue;
22560
22925
  const jsonKind = isAppVue ? "app" : options.isPage ? "page" : "component";
22561
22926
  const isAssetOnlyHmr = (hmrState?.profile?.dirtyReasonSummary)?.some((item) => item.startsWith("entry-local-asset:") || item.startsWith("style-sidecar:")) === true;
22562
- const isAppVueHmrUpdate = Boolean(isAppVue && options.configService.isDev && hmrState?.profile?.file === options.filename);
22927
+ const isAppVueHmrUpdate = Boolean(isAppVue && options.configService.isDev && typeof hmrState?.profile?.file === "string" && normalizeFsResolvedId(hmrState.profile.file) === normalizeFsResolvedId(options.filename));
22563
22928
  const sfcStyle = options.result.style;
22564
22929
  const shouldEmitSfcStyleAsset = typeof sfcStyle === "string" && sfcStyle.length > 0 && (isAppVue && (!options.configService.isDev || isAppVueHmrUpdate) || options.configService.isDev && isAssetOnlyHmr && hmrState?.lastHmrEntryIds?.has(options.filename));
22565
22930
  const { jsonConfig } = emitBundleVueEntryAssets({
@@ -22944,7 +23309,7 @@ async function resolveTransformAutoRoutesSource(options) {
22944
23309
  const APP_ENTRY_RE = /[\\/]app\.(?:vue|jsx|tsx)$/;
22945
23310
  const TEMPLATE_MUSTACHE_HINT = "{{";
22946
23311
  const TEMPLATE_EVENT_HINT_RE = /\b(?:bind|catch)[A-Za-z:_-]+=/;
22947
- const PAGE_FEATURE_HOOK_HINTS = [
23312
+ const PAGE_FEATURE_HOOK_HINTS$1 = [
22948
23313
  "onPageScroll",
22949
23314
  "onPullDownRefresh",
22950
23315
  "onReachBottom",
@@ -22957,6 +23322,12 @@ const PAGE_FEATURE_HOOK_HINTS = [
22957
23322
  "onSaveExitState"
22958
23323
  ];
22959
23324
  const PAGE_SCROLL_HOOK_HINT = "onPageScroll";
23325
+ const WEVU_RUNTIME_MODULE_HINTS$1 = [
23326
+ "'wevu'",
23327
+ "\"wevu\"",
23328
+ "'wevu/internal-runtime'",
23329
+ "\"wevu/internal-runtime\""
23330
+ ];
22960
23331
  function resolveScriptlessVueEntryStub(isPage) {
22961
23332
  return isPage ? "Page({})" : "Component({})";
22962
23333
  }
@@ -22973,7 +23344,7 @@ function mayNeedTransformSetDataPick(template, options) {
22973
23344
  return TEMPLATE_EVENT_HINT_RE.test(template);
22974
23345
  }
22975
23346
  function mayNeedTransformPageFeatureInjection(script) {
22976
- return PAGE_FEATURE_HOOK_HINTS.some((hint) => script.includes(hint));
23347
+ return WEVU_RUNTIME_MODULE_HINTS$1.some((hint) => script.includes(hint)) || PAGE_FEATURE_HOOK_HINTS$1.some((hint) => script.includes(hint));
22977
23348
  }
22978
23349
  function mayNeedTransformPageScrollDiagnostics(script) {
22979
23350
  return script.includes(PAGE_SCROLL_HOOK_HINT);
@@ -23254,8 +23625,7 @@ async function finalizeTransformCompiledResult(options) {
23254
23625
  pluginCtx,
23255
23626
  configService,
23256
23627
  isPage,
23257
- isApp,
23258
- forcePageFeatureInjection: isPage
23628
+ isApp
23259
23629
  });
23260
23630
  compilationCache.set(filename, {
23261
23631
  result,
@@ -23411,8 +23781,11 @@ async function refreshCompiledVueEntryCacheInDev(options) {
23411
23781
  const source = transformed.source;
23412
23782
  const dirtyVueEntryIds = ctx.runtimeState?.build?.hmr?.dirtyVueEntryIds;
23413
23783
  const normalizedDirtyFilename = normalizeFsResolvedId(filename);
23414
- const currentRefreshToken = (cached.refreshToken ?? 0) + (dirtyVueEntryIds?.has(normalizedDirtyFilename) ? 1 : 0);
23415
- if (source === cached.source && transformed.signature === cached.autoRoutesSignature && currentRefreshToken === 0) return cached.result;
23784
+ if (!(dirtyVueEntryIds?.has(normalizedDirtyFilename) === true) && source === cached.source && transformed.signature === cached.autoRoutesSignature) {
23785
+ cached.refreshToken = 0;
23786
+ dirtyVueEntryIds?.delete(normalizedDirtyFilename);
23787
+ return cached.result;
23788
+ }
23416
23789
  const compiled = await compileAndFinalizeVueLikeFile({
23417
23790
  source,
23418
23791
  filename,
@@ -23698,11 +24071,27 @@ function emitAppShellAssetsIfNeeded(options) {
23698
24071
  }
23699
24072
  //#endregion
23700
24073
  //#region src/plugins/vue/transform/bundle/emitCompiledEntry.ts
24074
+ function shouldReplaceAppScriptBundleEntry(options) {
24075
+ if (!isAppVueFile(options.filename) || !options.isDev || !options.hasDevHmrEvent) return false;
24076
+ return true;
24077
+ }
24078
+ function retainReplacedDevHmrScriptChunk(state, fileName) {
24079
+ const hmrState = state.ctx.runtimeState?.build?.hmr;
24080
+ if (!state.ctx.configService?.isDev || hmrState?.profile?.event === void 0) return;
24081
+ hmrState.lastEmittedChunkFileNames ??= /* @__PURE__ */ new Set();
24082
+ hmrState.lastEmittedChunkFileNames.add(fileName);
24083
+ }
23701
24084
  async function emitResolvedCompiledVueEntryAssets(options) {
23702
24085
  const { bundle, state, filename, cached, result, relativeBase, compileOptionsState } = options;
23703
24086
  const { ctx, pluginCtx } = state;
23704
24087
  const { configService } = ctx;
23705
24088
  if (!configService) return;
24089
+ const hmrState = ctx.runtimeState?.build?.hmr;
24090
+ const shouldReplaceAppScript = shouldReplaceAppScriptBundleEntry({
24091
+ filename,
24092
+ isDev: configService.isDev,
24093
+ hasDevHmrEvent: hmrState?.profile?.event !== void 0
24094
+ });
23706
24095
  if (isAppVueFile(filename) && hasAppShellTemplate(result)) emitAppShellAssetsIfNeeded({
23707
24096
  bundle,
23708
24097
  pluginCtx,
@@ -23758,6 +24147,11 @@ async function emitResolvedCompiledVueEntryAssets(options) {
23758
24147
  outputExtensions: options.outputExtensions,
23759
24148
  platformAssetOptions: options.platformAssetOptions
23760
24149
  });
24150
+ if (shouldReplaceAppScript && result.script?.trim()) {
24151
+ const scriptFileName = `${relativeBase}.${options.scriptExtension}`;
24152
+ emitSfcScriptAssetReplacingBundleEntry(pluginCtx, bundle, relativeBase, rewriteWevuInternalRuntimeImportCode(scriptFileName, result.script, ctx.runtimeState?.build?.output?.wevuInternalRuntimeFileName), options.scriptExtension);
24153
+ retainReplacedDevHmrScriptChunk(state, scriptFileName);
24154
+ }
23761
24155
  if (shouldEmitComponentJson && !result.script?.trim()) emitScriptlessComponentJsFallbackIfMissing({
23762
24156
  pluginCtx,
23763
24157
  bundle,
@@ -23935,6 +24329,9 @@ async function emitFallbackPageAssets(bundle, state, options) {
23935
24329
  }
23936
24330
  //#endregion
23937
24331
  //#region src/plugins/vue/transform/bundle/index.ts
24332
+ function isAutoRoutesAppRefreshHmrUpdate(hmrState) {
24333
+ return hmrState?.profile?.dirtyReasonSummary?.some((item) => item.startsWith("entry-auto-routes:") || item.startsWith("auto-routes-topology:")) === true;
24334
+ }
23938
24335
  function resolveVueBundleEmitState(state) {
23939
24336
  const { ctx, compilationCache } = state;
23940
24337
  const { configService, scanService } = ctx;
@@ -23943,11 +24340,19 @@ function resolveVueBundleEmitState(state) {
23943
24340
  return isAppVueFile(filename) && hasAppShellTemplate(cached.result);
23944
24341
  }) ? resolveAppShellLayout(configService) : void 0;
23945
24342
  const hmrState = ctx.runtimeState?.build?.hmr;
23946
- const isAppVueHmrUpdate = Boolean(configService.isDev && hmrState?.profile?.file && isAppVueFile(hmrState.profile.file));
24343
+ const currentHmrFile = hmrState?.profile?.file;
24344
+ const isAppVueHmrUpdate = Boolean(configService.isDev && typeof currentHmrFile === "string" && isAppVueFile(normalizeFsResolvedId(currentHmrFile)));
24345
+ const isAutoRoutesAppRefreshUpdate = configService.isDev && isAutoRoutesAppRefreshHmrUpdate(hmrState);
23947
24346
  const emittedEntryIds = Boolean(configService.isDev && hmrState && !isAppVueHmrUpdate && !hmrState.didEmitAllEntries && (hmrState.lastHmrEntryIds?.size ?? hmrState.lastEmittedEntryIds?.size ?? 0) > 0) && hmrState ? hmrState.lastHmrEntryIds?.size ? hmrState.lastHmrEntryIds : hmrState.lastEmittedEntryIds : void 0;
24347
+ const dirtyVueEntryIds = hmrState?.dirtyVueEntryIds;
24348
+ const currentAutoRoutesSignature = ctx.autoRoutesService?.getSignature?.();
23948
24349
  return {
23949
24350
  compilationEntries: Array.from(compilationCache.entries()).filter(([id]) => {
23950
- return !emittedEntryIds || emittedEntryIds.has(normalizeFsResolvedId(id));
24351
+ const normalizedId = normalizeFsResolvedId(id);
24352
+ const cached = compilationCache.get(id);
24353
+ const isStaleAutoRoutesAppEntry = Boolean(cached && isAppVueFile(normalizedId) && typeof currentAutoRoutesSignature === "string" && cached.autoRoutesSignature !== currentAutoRoutesSignature);
24354
+ const isAutoRoutesAppRefreshAppEntry = isAutoRoutesAppRefreshUpdate && isAppVueFile(normalizedId);
24355
+ return !emittedEntryIds || emittedEntryIds.has(normalizedId) || dirtyVueEntryIds?.has(normalizedId) || isStaleAutoRoutesAppEntry || isAutoRoutesAppRefreshAppEntry;
23951
24356
  }),
23952
24357
  emittedEntryIds
23953
24358
  };
@@ -23965,60 +24370,95 @@ async function emitVueBundleAssets(bundle, state) {
23965
24370
  //#endregion
23966
24371
  //#region src/plugins/wevu.ts
23967
24372
  const JS_LIKE_SOURCE_RE = /\.[cm]?[jt]sx?$/;
24373
+ const JS_LIKE_SOURCE_FILTER_RE = /\.[cm]?[jt]sx?(?:\?.*)?$/;
24374
+ const WEVU_RUNTIME_MODULE_HINTS = [
24375
+ "'wevu'",
24376
+ "\"wevu\"",
24377
+ "'wevu/internal-runtime'",
24378
+ "\"wevu/internal-runtime\""
24379
+ ];
24380
+ const PAGE_FEATURE_HOOK_HINTS = [
24381
+ "onPageScroll",
24382
+ "onPullDownRefresh",
24383
+ "onReachBottom",
24384
+ "onRouteDone",
24385
+ "onTabItemTap",
24386
+ "onResize",
24387
+ "onShareAppMessage",
24388
+ "onShareTimeline",
24389
+ "onAddToFavorites",
24390
+ "onSaveExitState"
24391
+ ];
24392
+ function mayNeedPageFeatureWork(code) {
24393
+ return WEVU_RUNTIME_MODULE_HINTS.some((hint) => code.includes(hint)) || PAGE_FEATURE_HOOK_HINTS.some((hint) => code.includes(hint));
24394
+ }
23968
24395
  function createWevuAutoPageFeaturesPlugin(ctx) {
23969
24396
  let matcher = null;
23970
24397
  let scanDirtySynced = false;
24398
+ const pageFileCache = /* @__PURE__ */ new Map();
23971
24399
  return {
23972
24400
  name: "weapp-vite:wevu:page-features",
23973
24401
  enforce: "pre",
23974
- async transform(code, id) {
23975
- const configService = ctx.configService;
23976
- const scanService = ctx.scanService;
23977
- if (!configService || !scanService) return null;
23978
- const pageMatcher = matcher ?? (matcher = createPageEntryMatcher({
23979
- srcRoot: configService.absoluteSrcRoot,
23980
- loadEntries: async () => {
23981
- const appEntry = await scanService.loadAppEntry();
23982
- const subPackages = scanService.loadSubPackages().map((meta) => ({
23983
- root: meta.subPackage.root,
23984
- pages: meta.subPackage.pages
23985
- }));
23986
- const pluginPages = scanService.pluginJson ? Object.values(scanService.pluginJson.pages ?? {}).map((page) => String(page)) : [];
24402
+ transform: {
24403
+ filter: { id: JS_LIKE_SOURCE_FILTER_RE },
24404
+ async handler(code, id) {
24405
+ const configService = ctx.configService;
24406
+ const scanService = ctx.scanService;
24407
+ if (!configService || !scanService) return null;
24408
+ const pageMatcher = matcher ?? (matcher = createPageEntryMatcher({
24409
+ srcRoot: configService.absoluteSrcRoot,
24410
+ loadEntries: async () => {
24411
+ const appEntry = await scanService.loadAppEntry();
24412
+ const subPackages = scanService.loadSubPackages().map((meta) => ({
24413
+ root: meta.subPackage.root,
24414
+ pages: meta.subPackage.pages
24415
+ }));
24416
+ const pluginPages = scanService.pluginJson ? Object.values(scanService.pluginJson.pages ?? {}).map((page) => String(page)) : [];
24417
+ return {
24418
+ pages: appEntry.json?.pages ?? [],
24419
+ subPackages,
24420
+ pluginPages
24421
+ };
24422
+ },
24423
+ warn: (message) => logger_default.warn(message)
24424
+ }));
24425
+ if (ctx.runtimeState.scan.isDirty && !scanDirtySynced) {
24426
+ pageMatcher.markDirty();
24427
+ pageFileCache.clear();
24428
+ scanDirtySynced = true;
24429
+ } else if (!ctx.runtimeState.scan.isDirty && scanDirtySynced) scanDirtySynced = false;
24430
+ const sourceId = normalizeFsResolvedId(id);
24431
+ if (!sourceId) return null;
24432
+ if (sourceId.endsWith(".vue")) return null;
24433
+ if (!JS_LIKE_SOURCE_RE.test(sourceId)) return null;
24434
+ const filename = toAbsoluteId(sourceId, configService, void 0, { base: "cwd" });
24435
+ if (!filename || !path.isAbsolute(filename)) return null;
24436
+ const startedAt = performance.now();
24437
+ try {
24438
+ let isPageFile = pageFileCache.get(filename);
24439
+ if (isPageFile === void 0) {
24440
+ isPageFile = await pageMatcher.isPageFile(filename);
24441
+ pageFileCache.set(filename, isPageFile);
24442
+ }
24443
+ if (!isPageFile) return null;
24444
+ if (!mayNeedPageFeatureWork(code)) return null;
24445
+ const astEngine = resolveAstEngine(configService.weappViteConfig);
24446
+ if (code.includes("onPageScroll")) for (const warning of collectOnPageScrollPerformanceWarnings(code, filename, { engine: astEngine })) logger_default.warn(warning);
24447
+ const result = await injectWevuPageFeaturesInJsWithResolver(code, {
24448
+ id: filename,
24449
+ astEngine,
24450
+ resolver: createViteResolverAdapter({ resolve: async (source, importer) => {
24451
+ return await this.resolve(source, importer);
24452
+ } }, { readFile: readFile$1 }, { checkMtime: getReadFileCheckMtime(configService) })
24453
+ });
24454
+ if (!result.transformed) return null;
23987
24455
  return {
23988
- pages: appEntry.json?.pages ?? [],
23989
- subPackages,
23990
- pluginPages
24456
+ code: result.code,
24457
+ map: null
23991
24458
  };
23992
- },
23993
- warn: (message) => logger_default.warn(message)
23994
- }));
23995
- if (ctx.runtimeState.scan.isDirty && !scanDirtySynced) {
23996
- pageMatcher.markDirty();
23997
- scanDirtySynced = true;
23998
- } else if (!ctx.runtimeState.scan.isDirty && scanDirtySynced) scanDirtySynced = false;
23999
- const sourceId = normalizeFsResolvedId(id);
24000
- if (!sourceId) return null;
24001
- if (sourceId.endsWith(".vue")) return null;
24002
- if (!JS_LIKE_SOURCE_RE.test(sourceId)) return null;
24003
- const filename = toAbsoluteId(sourceId, configService, void 0, { base: "cwd" });
24004
- if (!filename || !path.isAbsolute(filename)) return null;
24005
- const startedAt = performance.now();
24006
- try {
24007
- if (!await pageMatcher.isPageFile(filename)) return null;
24008
- for (const warning of collectOnPageScrollPerformanceWarnings(code, filename, { engine: resolveAstEngine(configService.weappViteConfig) })) logger_default.warn(warning);
24009
- const result = await injectWevuPageFeaturesInJsWithResolver(code, {
24010
- id: filename,
24011
- resolver: createViteResolverAdapter({ resolve: async (source, importer) => {
24012
- return await this.resolve(source, importer);
24013
- } }, { readFile: readFile$1 }, { checkMtime: getReadFileCheckMtime(configService) })
24014
- });
24015
- if (!result.transformed) return null;
24016
- return {
24017
- code: result.code,
24018
- map: null
24019
- };
24020
- } finally {
24021
- recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "transformMs", performance.now() - startedAt);
24459
+ } finally {
24460
+ recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "transformMs", performance.now() - startedAt);
24461
+ }
24022
24462
  }
24023
24463
  }
24024
24464
  };
@@ -24167,6 +24607,18 @@ async function transformVueLikeFile(options) {
24167
24607
  }
24168
24608
  //#endregion
24169
24609
  //#region src/plugins/vue/transform/plugin/index.ts
24610
+ const VUE_TRANSFORM_FILTER_RE = /\.(?:vue|tsx|jsx)(?:\?.*)?$/;
24611
+ const VUE_LOAD_FILTER_RE = /^(?:\0weapp-vite:scoped-slot:|.*[?&]weapp-vite-vue(?:[=&]|$))/;
24612
+ const SCOPED_SLOT_VIRTUAL_ID_RE = /^\0weapp-vite:scoped-slot:/;
24613
+ function invalidateDirtyVueEntryCaches(dirtyVueEntryIds, compilationCache) {
24614
+ if (!dirtyVueEntryIds?.size) return;
24615
+ for (const entryId of dirtyVueEntryIds) {
24616
+ const cached = compilationCache.get(entryId);
24617
+ if (!cached) continue;
24618
+ cached.source = void 0;
24619
+ cached.refreshToken = (cached.refreshToken ?? 0) + 1;
24620
+ }
24621
+ }
24170
24622
  function createVueTransformPlugin(ctx) {
24171
24623
  const compilationCache = /* @__PURE__ */ new Map();
24172
24624
  let appShell;
@@ -24198,52 +24650,61 @@ function createVueTransformPlugin(ctx) {
24198
24650
  readFile: fs.readFile
24199
24651
  });
24200
24652
  },
24201
- resolveId(id) {
24202
- return resolveScopedSlotVirtualId(id);
24203
- },
24204
- async load(id) {
24205
- return await loadTransformStyleBlock({
24206
- id,
24207
- pluginCtx: this,
24208
- ctx,
24209
- configService: ctx.configService,
24210
- styleBlocksCache,
24211
- loadScopedSlotModule: (id) => {
24212
- return loadScopedSlotModule(id, scopedSlotModules)?.code ?? null;
24213
- },
24214
- scopedSlotModules,
24215
- parseWeappVueStyleRequest: (id) => parseWeappVueStyleRequest(id) ?? null,
24216
- readAndParseSfc,
24217
- createReadAndParseSfcOptions
24218
- });
24653
+ resolveId: {
24654
+ filter: { id: SCOPED_SLOT_VIRTUAL_ID_RE },
24655
+ handler(id) {
24656
+ return resolveScopedSlotVirtualId(id);
24657
+ }
24219
24658
  },
24220
- async transform(code, id) {
24221
- if (!isVueLikeId(id)) return null;
24222
- const startedAt = performance.now();
24223
- try {
24224
- return await transformVueLikeFile({
24225
- ctx,
24226
- pluginCtx: this,
24227
- code,
24659
+ load: {
24660
+ filter: { id: VUE_LOAD_FILTER_RE },
24661
+ async handler(id) {
24662
+ return await loadTransformStyleBlock({
24228
24663
  id,
24229
- compilationCache,
24230
- setAppShell: (shell) => appShell = shell,
24231
- pageMatcher,
24232
- setPageMatcher: (matcher) => pageMatcher = matcher,
24233
- scanDirtySynced,
24234
- setScanDirtySynced: (synced) => scanDirtySynced = synced,
24235
- reExportResolutionCache,
24236
- compileOptionsCache,
24664
+ pluginCtx: this,
24665
+ ctx,
24666
+ configService: ctx.configService,
24237
24667
  styleBlocksCache,
24238
- styleRefreshTokens,
24668
+ loadScopedSlotModule: (id) => {
24669
+ return loadScopedSlotModule(id, scopedSlotModules)?.code ?? null;
24670
+ },
24239
24671
  scopedSlotModules,
24240
- emittedScopedSlotChunks,
24241
- classStyleRuntimeWarned,
24672
+ parseWeappVueStyleRequest: (id) => parseWeappVueStyleRequest(id) ?? null,
24242
24673
  readAndParseSfc,
24243
24674
  createReadAndParseSfcOptions
24244
24675
  });
24245
- } finally {
24246
- recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "transformMs", performance.now() - startedAt);
24676
+ }
24677
+ },
24678
+ transform: {
24679
+ filter: { id: VUE_TRANSFORM_FILTER_RE },
24680
+ async handler(code, id) {
24681
+ if (!isVueLikeId(id)) return null;
24682
+ const startedAt = performance.now();
24683
+ try {
24684
+ return await transformVueLikeFile({
24685
+ ctx,
24686
+ pluginCtx: this,
24687
+ code,
24688
+ id,
24689
+ compilationCache,
24690
+ setAppShell: (shell) => appShell = shell,
24691
+ pageMatcher,
24692
+ setPageMatcher: (matcher) => pageMatcher = matcher,
24693
+ scanDirtySynced,
24694
+ setScanDirtySynced: (synced) => scanDirtySynced = synced,
24695
+ reExportResolutionCache,
24696
+ compileOptionsCache,
24697
+ styleBlocksCache,
24698
+ styleRefreshTokens,
24699
+ scopedSlotModules,
24700
+ emittedScopedSlotChunks,
24701
+ classStyleRuntimeWarned,
24702
+ readAndParseSfc,
24703
+ createReadAndParseSfcOptions
24704
+ });
24705
+ } finally {
24706
+ recordHmrProfileDuration(ctx.runtimeState?.build?.hmr?.profile, "transformMs", performance.now() - startedAt);
24707
+ }
24247
24708
  }
24248
24709
  },
24249
24710
  async generateBundle(_options, bundle) {
@@ -24274,6 +24735,7 @@ function createVueTransformPlugin(ctx) {
24274
24735
  styleRefreshTokens,
24275
24736
  existsSync: fs.existsSync
24276
24737
  });
24738
+ invalidateDirtyVueEntryCaches(ctx.runtimeState?.build?.hmr?.dirtyVueEntryIds, compilationCache);
24277
24739
  const profile = ctx.runtimeState?.build?.hmr?.profile;
24278
24740
  if (profile && !profile.file) {
24279
24741
  profile.eventId = createHmrProfileEventId();
@@ -25473,7 +25935,7 @@ async function loadAppEntry(ctx, scanState) {
25473
25935
  const vueAppPath = await findVueEntry(appBasename);
25474
25936
  let configFromVue;
25475
25937
  if (!appConfigFile && vueAppPath) {
25476
- const { extractConfigFromVue } = await import("./file-BQG0E0sq.mjs");
25938
+ const { extractConfigFromVue } = await import("./file-BrdaHBHs.mjs");
25477
25939
  configFromVue = await extractConfigFromVue(vueAppPath);
25478
25940
  if (configFromVue) appConfigFile = vueAppPath;
25479
25941
  }