weapp-vite 6.19.1 → 6.19.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
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-CdNDPmkx.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-K76qLAmU.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";
7
- 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_EXTERNAL_OUTPUT_DIRECTORY, WEAPP_VITE_IMPORT_META_ENV_KEY, WEAPP_VITE_INJECTED_API_IDENTIFIER, WEAPP_VITE_LOGICAL_ENTRY_RESOLVED_PREFIX, WEAPP_VITE_LOGICAL_ENTRY_VIRTUAL_PREFIX, WEAPP_VITE_RUNTIME_CONTRACT_VERSION, WEAPP_VITE_RUNTIME_REACTIVITY_VIRTUAL_ID, WEAPP_VITE_RUNTIME_TEMPLATE_VIRTUAL_ID, WEAPP_VITE_RUNTIME_VIRTUAL_ID, WEAPP_VITE_RUNTIME_VIRTUAL_IDS, WEAPP_VITE_SIDECAR_OWNER_QUERY_MARKER, WEAPP_VITE_SIDECAR_QUERY_MARKER, WEAPP_VITE_SIDECAR_RESOLVED_PREFIX, WEAPP_VITE_SIDECAR_VIRTUAL_PREFIX, WEAPP_VITE_STATEFUL_HMR_BRIDGE_KEY, WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY, WEAPP_VITE_STATEFUL_HMR_CONTROL_FILE, WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY, WEAPP_VITE_STATEFUL_HMR_PRELOAD_FILE, WEAPP_VITE_STATEFUL_HMR_UPDATE_FILE, 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";
7
+ 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_BUNDLE_MARKER as REQUEST_GLOBAL_BUNDLE_MARKER$1, 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_LOCAL_BINDINGS_MARKER as REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER$1, 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_EXTERNAL_OUTPUT_DIRECTORY, WEAPP_VITE_IMPORT_META_ENV_KEY, WEAPP_VITE_INJECTED_API_IDENTIFIER, WEAPP_VITE_LOGICAL_ENTRY_RESOLVED_PREFIX, WEAPP_VITE_LOGICAL_ENTRY_VIRTUAL_PREFIX, WEAPP_VITE_RUNTIME_CONTRACT_VERSION, WEAPP_VITE_RUNTIME_REACTIVITY_VIRTUAL_ID, WEAPP_VITE_RUNTIME_TEMPLATE_VIRTUAL_ID, WEAPP_VITE_RUNTIME_VIRTUAL_ID, WEAPP_VITE_RUNTIME_VIRTUAL_IDS, WEAPP_VITE_SIDECAR_OWNER_QUERY_MARKER, WEAPP_VITE_SIDECAR_QUERY_MARKER, WEAPP_VITE_SIDECAR_RESOLVED_PREFIX, WEAPP_VITE_SIDECAR_VIRTUAL_PREFIX, WEAPP_VITE_STATEFUL_HMR_BRIDGE_KEY, WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY, WEAPP_VITE_STATEFUL_HMR_CONTROL_FILE, WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY, WEAPP_VITE_STATEFUL_HMR_PRELOAD_FILE, WEAPP_VITE_STATEFUL_HMR_UPDATE_FILE, 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";
8
8
  import path, { posix } from "pathe";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import path$1, { normalize, relative, win32 } from "node:path";
@@ -5303,6 +5303,17 @@ async function loadViteConfigFile(configEnv, configFile, configRoot, configFileD
5303
5303
  }
5304
5304
  //#endregion
5305
5305
  //#region src/utils/projectConfig.ts
5306
+ async function readProjectConfigFile(filePath, required) {
5307
+ if (!await fs$1.pathExists(filePath)) {
5308
+ if (required) throw new Error(`找不到项目配置文件:${filePath}`);
5309
+ return {};
5310
+ }
5311
+ try {
5312
+ return await fs$1.readJson(filePath) || {};
5313
+ } catch {
5314
+ throw new Error(`解析 json 格式失败, ${filePath} 为非法的 json 格式`);
5315
+ }
5316
+ }
5306
5317
  const DEFAULT_PROJECT_PRIVATE_CONFIG_FILE_NAME = "project.private.config.json";
5307
5318
  function getProjectConfigFileName(platform) {
5308
5319
  return getProjectPlatformOptions(platform).projectConfigFileName;
@@ -5323,23 +5334,13 @@ function resolveProjectConfigRoot(projectConfig, platform) {
5323
5334
  async function getProjectConfig(root, options) {
5324
5335
  const baseJsonPath = path.resolve(root, options?.basePath ?? "project.config.json");
5325
5336
  const privateJsonPath = path.resolve(root, options?.privatePath ?? "project.private.config.json");
5326
- let baseJson = {};
5327
- let privateJson = {};
5328
- if (await fs$1.pathExists(baseJsonPath)) try {
5329
- baseJson = await fs$1.readJson(baseJsonPath) || {};
5330
- } catch {
5331
- throw new Error(`解析 json 格式失败, ${baseJsonPath} 为非法的 json 格式`);
5332
- }
5333
- else throw new Error(`找不到项目配置文件:${baseJsonPath}`);
5334
- if (!options?.ignorePrivate) {
5335
- if (await fs$1.pathExists(privateJsonPath)) try {
5336
- privateJson = await fs$1.readJson(privateJsonPath) || {};
5337
- } catch {
5338
- throw new Error(`解析 json 格式失败, ${privateJsonPath} 为非法的 json 格式`);
5339
- }
5340
- }
5337
+ const baseJson = await readProjectConfigFile(baseJsonPath, true);
5338
+ const privateJson = options?.ignorePrivate ? {} : await readProjectConfigFile(privateJsonPath, false);
5341
5339
  return Object.assign({}, privateJson, baseJson);
5342
5340
  }
5341
+ async function getProjectPrivateConfig(root, options) {
5342
+ return await readProjectConfigFile(path.resolve(root, options?.privatePath ?? "project.private.config.json"), false);
5343
+ }
5343
5344
  function resolveProjectConfigSyncDirs(options) {
5344
5345
  const outputRoot = path.dirname(options.outDir);
5345
5346
  const sourceBasePath = path.resolve(options.projectConfigPath);
@@ -5734,7 +5735,7 @@ function createRegistryHelpers(state) {
5734
5735
  }
5735
5736
  //#endregion
5736
5737
  //#region src/runtime/autoImport/service/resolver.ts
5737
- const require$1 = createRequire(import.meta.url);
5738
+ const require$2 = createRequire(import.meta.url);
5738
5739
  const COMPONENT_HAS_UPPER_RE = /[A-Z]/;
5739
5740
  const CAMEL_TO_KEBAB_RE$1 = /([a-z0-9])([A-Z])/g;
5740
5741
  const MULTI_UPPER_TO_KEBAB_RE = /([A-Z]+)([A-Z][a-z])/g;
@@ -5812,7 +5813,7 @@ function createResolverHelpers(state) {
5812
5813
  function getMiniprogramDir(pkgName, cwd) {
5813
5814
  if (miniprogramDirCache.has(pkgName)) return miniprogramDirCache.get(pkgName);
5814
5815
  try {
5815
- const packageJsonPath = require$1.resolve(`${pkgName}/package.json`, { paths: [cwd] });
5816
+ const packageJsonPath = require$2.resolve(`${pkgName}/package.json`, { paths: [cwd] });
5816
5817
  const raw = fs$1.readJsonSync(packageJsonPath, { throws: false });
5817
5818
  const normalized = (typeof raw?.miniprogram === "string" ? raw.miniprogram.trim() : void 0)?.replace(TRAILING_RELATIVE_PREFIX_RE, "").replace(TRAILING_SLASH_RE$1, "");
5818
5819
  miniprogramDirCache.set(pkgName, normalized || void 0);
@@ -5827,7 +5828,7 @@ function createResolverHelpers(state) {
5827
5828
  const cached = packageRootCache.get(cacheKey);
5828
5829
  if (cached) return cached;
5829
5830
  try {
5830
- const packageJsonPath = require$1.resolve(`${pkgName}/package.json`, { paths: [cwd] });
5831
+ const packageJsonPath = require$2.resolve(`${pkgName}/package.json`, { paths: [cwd] });
5831
5832
  const packageRoot = path.dirname(packageJsonPath);
5832
5833
  packageRootCache.set(cacheKey, packageRoot);
5833
5834
  return packageRoot;
@@ -5859,7 +5860,7 @@ function createResolverHelpers(state) {
5859
5860
  candidates.push(`${withMiniprogramDir}/index.js`);
5860
5861
  } else candidates.push(withMiniprogramDir);
5861
5862
  for (const candidate of candidates) try {
5862
- require$1.resolve(candidate, { paths: [cwd] });
5863
+ require$2.resolve(candidate, { paths: [cwd] });
5863
5864
  navigationImportCache.set(from, candidate);
5864
5865
  return candidate;
5865
5866
  } catch {}
@@ -6521,8 +6522,10 @@ async function collectCandidateFilesFromRoots(absoluteSrcRoot, matcher, roots, o
6521
6522
  async function collectCandidates(absoluteSrcRoot, include, subPackageRoots, searchRoots) {
6522
6523
  const matcher = createAutoRoutesMatcher(include, subPackageRoots);
6523
6524
  const roots = resolveCandidateSearchRoots(absoluteSrcRoot, matcher, searchRoots) ?? [];
6524
- if (!searchRoots) if (matcher.isDefault) roots.push(...await resolveDefaultSearchRoots(absoluteSrcRoot, subPackageRoots));
6525
- else roots.push(...matcher.getSearchRoots(absoluteSrcRoot));
6525
+ if (!searchRoots) {
6526
+ if (matcher.isDefault) roots.push(...await resolveDefaultSearchRoots(absoluteSrcRoot, subPackageRoots));
6527
+ else roots.push(...matcher.getSearchRoots(absoluteSrcRoot));
6528
+ }
6526
6529
  const createCrawler = () => new fdir({
6527
6530
  includeDirs: false,
6528
6531
  pathSeparator: "/",
@@ -7860,6 +7863,22 @@ function resolveCompilerOutputExtensions(outputExtensions) {
7860
7863
  return resolveOutputExtensions(outputExtensions, { scriptModuleExtensionFallback: "wxs" });
7861
7864
  }
7862
7865
  //#endregion
7866
+ //#region src/runtime/hmrRuntime.ts
7867
+ function resolveHmrRuntime(options) {
7868
+ if (options.configured === "classic" || options.configured === "stateful-experimental") return options.configured;
7869
+ if (options.platform === "weapp" && options.compileHotReLoad === true) return "stateful-experimental";
7870
+ return "classic";
7871
+ }
7872
+ function formatHmrRuntimeStartupMessages(options) {
7873
+ if (options.configured === "classic" || options.configured === "stateful-experimental") {
7874
+ const alternative = options.runtime === "classic" ? "stateful-experimental" : "classic";
7875
+ return [`HMR 模式:${options.runtime}(显式配置)`, `HMR 切换:修改 weapp.hmr.runtime 为 auto 或 ${alternative} 后重启 wv dev。`];
7876
+ }
7877
+ if (options.platform !== "weapp") return ["HMR 模式:classic(自动检测:仅微信小程序支持 stateful-experimental)", "HMR 切换:可通过 weapp.hmr.runtime 显式配置 classic。"];
7878
+ if (options.compileHotReLoad === true) return ["HMR 模式:stateful-experimental(自动检测:微信开发者工具热重载已开启)", "HMR 切换:关闭微信开发者工具“热重载”后重启 wv dev,或通过 weapp.hmr.runtime 显式配置。"];
7879
+ return ["HMR 模式:classic(自动检测:微信开发者工具热重载未开启或无法确认)", "HMR 切换:开启微信开发者工具“热重载”后重启 wv dev,或通过 weapp.hmr.runtime 显式配置。"];
7880
+ }
7881
+ //#endregion
7863
7882
  //#region src/runtime/lib.ts
7864
7883
  function hasLibEntry(entry) {
7865
7884
  if (!entry) return false;
@@ -8450,8 +8469,10 @@ async function generateLibDts(configService) {
8450
8469
  });
8451
8470
  await normalizeRolldownDtsOutput(tsEntries, configService.outDir);
8452
8471
  }
8453
- if (vueEntries.length > 0) if (dtsOptions?.mode === "vue-tsc") await generateVueDtsWithVueTsc(configService, libConfig, vueEntries, dtsOptions);
8454
- else await generateVueDtsWithInternal(configService, vueEntries, dtsOptions);
8472
+ if (vueEntries.length > 0) {
8473
+ if (dtsOptions?.mode === "vue-tsc") await generateVueDtsWithVueTsc(configService, libConfig, vueEntries, dtsOptions);
8474
+ else await generateVueDtsWithInternal(configService, vueEntries, dtsOptions);
8475
+ }
8455
8476
  await Promise.all(entries.map((entry) => ensureStub(entry, configService.outDir)));
8456
8477
  if (vueEntries.length > 0) {
8457
8478
  if (shouldRewriteWevuComponentType(dtsOptions?.mode === "vue-tsc" ? getVueCompilerLibOrUndefined(dtsOptions?.vueTsc?.vueCompilerOptions?.lib) : getVueCompilerLibOrUndefined(dtsOptions?.internal?.vueCompilerOptions?.lib))) await Promise.all(vueEntries.map(async (entry) => {
@@ -8631,7 +8652,7 @@ function getWeappViteConfig() {
8631
8652
  alipayNpmMode: "node_modules"
8632
8653
  },
8633
8654
  hmr: {
8634
- runtime: "classic",
8655
+ runtime: "auto",
8635
8656
  sharedChunks: "auto",
8636
8657
  touchAppWxss: "auto",
8637
8658
  logLevel: "default",
@@ -8765,6 +8786,7 @@ function createDefaultLoadConfigResult() {
8765
8786
  emitDefaultAutoImportOutputs: true,
8766
8787
  projectConfig: {},
8767
8788
  projectConfigPath: void 0,
8789
+ projectPrivateConfig: {},
8768
8790
  projectPrivateConfigPath: void 0,
8769
8791
  mpDistRoot: "",
8770
8792
  multiPlatform: resolveMultiPlatformConfig(false),
@@ -8864,6 +8886,7 @@ function createRuntimeState() {
8864
8886
  css: {
8865
8887
  importerToDependencies: /* @__PURE__ */ new Map(),
8866
8888
  dependencyToImporters: /* @__PURE__ */ new Map(),
8889
+ transformedSidecarSource: /* @__PURE__ */ new Map(),
8867
8890
  emittedSource: /* @__PURE__ */ new Map(),
8868
8891
  sidecarImports: /* @__PURE__ */ new Set()
8869
8892
  },
@@ -8939,6 +8962,7 @@ function resetRuntimeStateForFreshBuild(runtimeState) {
8939
8962
  const css = runtimeState.css;
8940
8963
  css.importerToDependencies.clear();
8941
8964
  css.dependencyToImporters.clear();
8965
+ css.transformedSidecarSource.clear();
8942
8966
  css.emittedSource.clear();
8943
8967
  const wxml = runtimeState.wxml;
8944
8968
  wxml.depsMap.clear();
@@ -10548,45 +10572,6 @@ function createSharedBuildConfig(configService, scanService) {
10548
10572
  return { build: { rolldownOptions: { output: createSharedBuildOutput(configService, () => scanService.subPackageMap.keys()) } } };
10549
10573
  }
10550
10574
  //#endregion
10551
- //#region src/runtime/statefulHmr/outputWriter.ts
10552
- /**
10553
- * @description 通过独立的 Vite write 阶段持久化 DevEngine 已生成的文件,不重新解析业务源码。
10554
- */
10555
- async function writeStatefulHmrOutput(outDir, output) {
10556
- const virtualEntry = "\0weapp-vite-stateful-hmr-output";
10557
- await build({
10558
- configFile: false,
10559
- logLevel: "silent",
10560
- build: {
10561
- emptyOutDir: false,
10562
- minify: false,
10563
- outDir,
10564
- rolldownOptions: { input: virtualEntry },
10565
- write: true
10566
- },
10567
- plugins: [{
10568
- name: "weapp-vite:stateful-hmr-output-writer",
10569
- resolveId(id) {
10570
- return id === virtualEntry ? virtualEntry : void 0;
10571
- },
10572
- load(id) {
10573
- return id === virtualEntry ? "export {}" : void 0;
10574
- },
10575
- buildStart() {
10576
- for (const item of output) this.emitFile({
10577
- type: "asset",
10578
- fileName: item.fileName.replaceAll("\\", "/"),
10579
- source: item.type === "chunk" ? item.code : item.source
10580
- });
10581
- },
10582
- generateBundle(_options, bundle) {
10583
- for (const [fileName, item] of Object.entries(bundle)) if (item.type === "chunk" && item.facadeModuleId === virtualEntry) delete bundle[fileName];
10584
- }
10585
- }],
10586
- root: path$1.dirname(outDir)
10587
- });
10588
- }
10589
- //#endregion
10590
10575
  //#region src/runtime/statefulHmr/runtimeSource.ts
10591
10576
  const statefulHmrRolldownRuntimeSource = `
10592
10577
  var BaseDevRuntime = DevRuntime;
@@ -10617,7 +10602,6 @@ class WeappViteDevRuntime extends BaseDevRuntime {
10617
10602
  registrationModuleId = '';
10618
10603
  createEsmInitializer = (id, initialize, _deduplicate, result) => () => {
10619
10604
  if (!initialize) return result;
10620
- if (!this.applyingPatch && this.patchedModules.has(id)) return result;
10621
10605
  const callback = initialize;
10622
10606
  initialize = undefined;
10623
10607
  const previousId = this.currentModuleId;
@@ -10629,7 +10613,6 @@ class WeappViteDevRuntime extends BaseDevRuntime {
10629
10613
  };
10630
10614
  createCjsInitializer = (id, initialize, _deduplicate, module) => () => {
10631
10615
  if (module) return module.exports;
10632
- if (!this.applyingPatch && this.patchedModules.has(id)) return this.loadExports(id);
10633
10616
  module = { exports: {} };
10634
10617
  const previousId = this.currentModuleId;
10635
10618
  this.currentModuleId = id;
@@ -10652,6 +10635,16 @@ class WeappViteDevRuntime extends BaseDevRuntime {
10652
10635
  this.registrationModuleId = id;
10653
10636
  return super.registerModule(id, exportsHolder);
10654
10637
  }
10638
+ initModule(id) {
10639
+ const previousId = this.currentModuleId;
10640
+ this.currentModuleId = id;
10641
+ try {
10642
+ const result = super.initModule(id);
10643
+ if (this.applyingPatch) this.patchedModules.add(id);
10644
+ return result;
10645
+ }
10646
+ finally { this.currentModuleId = previousId; }
10647
+ }
10655
10648
  beginPatch() { this.applyingPatch = true; }
10656
10649
  endPatch() { this.applyingPatch = false; }
10657
10650
  applyUpdates(boundaries) {
@@ -10945,7 +10938,7 @@ function createStatefulHmrControlSource(control) {
10945
10938
  globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY)}] = ${JSON.stringify(control)};
10946
10939
  (() => {
10947
10940
  const control = globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY)}];
10948
- if (globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY)}]) return;
10941
+ globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY)}]?.stop?.();
10949
10942
  let version = 0;
10950
10943
  let phase = 'registering';
10951
10944
  let pendingBatch;
@@ -11003,7 +10996,38 @@ globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY)}] = ${JSON.stri
11003
10996
  wx.reLaunch({ url: '/' + route + (query ? '?' + query : ''), complete: () => send('poll') });
11004
10997
  };
11005
10998
  globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY)}] = {
10999
+ lastApply: undefined,
11006
11000
  getVersion() { return version; },
11001
+ getLastApply() { return this.lastApply; },
11002
+ stop() {
11003
+ phase = 'stopped';
11004
+ if (timer) {
11005
+ clearTimeout(timer);
11006
+ timer = undefined;
11007
+ }
11008
+ activeRequest?.abort?.();
11009
+ activeRequest = undefined;
11010
+ },
11011
+ applyChangedModules(changedIds) {
11012
+ const runtime = globalThis.__rolldown_runtime__;
11013
+ if (!runtime || !Array.isArray(changedIds)) return;
11014
+ const uniqueIds = [...new Set(changedIds.filter((id) => typeof id === 'string'))];
11015
+ const summary = { changedIds: uniqueIds, initialized: [], missing: [], executedBefore: [], executedAfterRemove: [] };
11016
+ for (const id of uniqueIds) {
11017
+ if (typeof runtime.isExecuted === 'function' && runtime.isExecuted(id)) summary.executedBefore.push(id);
11018
+ if (typeof runtime.removeModuleCache === 'function') runtime.removeModuleCache.call(runtime, id);
11019
+ if (typeof runtime.isExecuted === 'function' && runtime.isExecuted(id)) summary.executedAfterRemove.push(id);
11020
+ }
11021
+ for (const id of uniqueIds) {
11022
+ if (typeof runtime.hasFactory === 'function' && !runtime.hasFactory(id)) {
11023
+ summary.missing.push(id);
11024
+ continue;
11025
+ }
11026
+ if (typeof runtime.initModule === 'function') runtime.initModule.call(runtime, id);
11027
+ summary.initialized.push(id);
11028
+ }
11029
+ this.lastApply = summary;
11030
+ },
11007
11031
  receiveBatch(meta, apply) {
11008
11032
  if (phase === 'registering') {
11009
11033
  pendingBatch = { meta, apply };
@@ -11020,6 +11044,7 @@ globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY)}] = ${JSON.stri
11020
11044
  bridge.beginUpdate?.();
11021
11045
  try {
11022
11046
  apply();
11047
+ globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY)}].applyChangedModules(meta.changedIds);
11023
11048
  version = meta.targetVersion;
11024
11049
  phase = meta.compatible === false ? 'relaunching' : 'polling';
11025
11050
  } catch (error) {
@@ -11038,6 +11063,216 @@ globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY)}] = ${JSON.stri
11038
11063
  `;
11039
11064
  }
11040
11065
  //#endregion
11066
+ //#region src/runtime/statefulHmr/commonRuntime.ts
11067
+ const require$1 = createRequire(import.meta.url);
11068
+ const STATIC_IMPORT_RE = /^import\s+(?:\{[^}\n]*\}|[A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"](?:;\s*)?$/gm;
11069
+ const EXPORT_PREFIX_RE = /^export\s+/gm;
11070
+ const STATEFUL_HMR_RUNTIME_COMPATIBILITY_ERROR_CODE = "WEAPP_VITE_STATEFUL_HMR_RUNTIME_INCOMPATIBLE";
11071
+ var StatefulHmrRuntimeCompatibilityError = class extends Error {
11072
+ code = STATEFUL_HMR_RUNTIME_COMPATIBILITY_ERROR_CODE;
11073
+ constructor(message) {
11074
+ super(message);
11075
+ this.name = "StatefulHmrRuntimeCompatibilityError";
11076
+ }
11077
+ };
11078
+ function readRolldownRuntimeSource(subpath) {
11079
+ try {
11080
+ const filePath = require$1.resolve(subpath);
11081
+ return {
11082
+ filePath,
11083
+ source: readFileSync(filePath, "utf8")
11084
+ };
11085
+ } catch (error) {
11086
+ throw new StatefulHmrRuntimeCompatibilityError(`无法读取 Rolldown 状态保持 HMR 基础运行时 ${subpath}:${error instanceof Error ? error.message : String(error)}`);
11087
+ }
11088
+ }
11089
+ function stripModuleSyntax(source) {
11090
+ return source.replace(STATIC_IMPORT_RE, "").replace(EXPORT_PREFIX_RE, "");
11091
+ }
11092
+ function resolveRuntimeHelpers(runtime) {
11093
+ return [...runtime.source.matchAll(STATIC_IMPORT_RE)].map((match) => match[1]).filter((specifier) => Boolean(specifier && specifier.startsWith("."))).map((specifier) => {
11094
+ const helperPath = path$1.resolve(path$1.dirname(runtime.filePath), specifier);
11095
+ try {
11096
+ return readFileSync(helperPath, "utf8");
11097
+ } catch (error) {
11098
+ throw new StatefulHmrRuntimeCompatibilityError(`无法读取 Rolldown dev runtime helper ${specifier}:${error instanceof Error ? error.message : String(error)}`);
11099
+ }
11100
+ }).map(stripModuleSyntax).join("\n");
11101
+ }
11102
+ function assertRolldownRuntimeContract(runtime, helpers) {
11103
+ const missing = [
11104
+ [
11105
+ runtime.source,
11106
+ /(?:class\s+DevRuntime|(?:var|let|const)\s+DevRuntime\s*=)/,
11107
+ "DevRuntime"
11108
+ ],
11109
+ [
11110
+ runtime.source,
11111
+ /(?:class\s+Module|(?:var|let|const)\s+Module\s*=)/,
11112
+ "Module"
11113
+ ],
11114
+ [
11115
+ helpers,
11116
+ /(?:var|let|const)\s+__exportAll\s*=|function\s+__exportAll\b/,
11117
+ "common runtime helpers"
11118
+ ]
11119
+ ].filter(([source, pattern]) => !pattern.test(source));
11120
+ if (missing.length > 0) throw new StatefulHmrRuntimeCompatibilityError(`Rolldown dev runtime ${runtime.filePath} 缺少稳定契约:${missing.map(([, , name]) => name).join("、")}。`);
11121
+ }
11122
+ function composeStatefulHmrRuntimeSource(runtime, helpers) {
11123
+ assertRolldownRuntimeContract(runtime, helpers);
11124
+ return `${helpers}\n${stripModuleSyntax(runtime.source)}\n${statefulHmrRolldownRuntimeSource}`;
11125
+ }
11126
+ function createStatefulHmrRolldownRuntimeSource() {
11127
+ const runtime = readRolldownRuntimeSource("rolldown/experimental/runtime");
11128
+ return composeStatefulHmrRuntimeSource(runtime, resolveRuntimeHelpers(runtime));
11129
+ }
11130
+ function assertStatefulHmrRuntimeOutput(output) {
11131
+ const runtime = output.find((item) => item.type === "chunk" && item.fileName === "rolldown-runtime.js");
11132
+ if (!runtime || runtime.type !== "chunk") throw new StatefulHmrRuntimeCompatibilityError("stateful HMR 初始构建未生成 rolldown-runtime.js。");
11133
+ const missing = [
11134
+ /(?:class|var) DevRuntime(?:\s*=\s*class)?/,
11135
+ /(?:class|var) WeappViteDevRuntime(?:\s*=\s*class)?/,
11136
+ "new WeappViteDevRuntime",
11137
+ "__WEAPP_VITE_STATEFUL_HMR_BRIDGE__"
11138
+ ].filter((contract) => typeof contract === "string" ? !runtime.code.includes(contract) : !contract.test(runtime.code));
11139
+ if (missing.length > 0) throw new StatefulHmrRuntimeCompatibilityError(`stateful HMR runtime 不完整,缺少 ${missing.length} 项必要契约。`);
11140
+ }
11141
+ function isStatefulHmrRuntimeCompatibilityError(error) {
11142
+ return error instanceof StatefulHmrRuntimeCompatibilityError || typeof error === "object" && error !== null && Reflect.get(error, "code") === "WEAPP_VITE_STATEFUL_HMR_RUNTIME_INCOMPATIBLE";
11143
+ }
11144
+ //#endregion
11145
+ //#region src/runtime/statefulHmr/outputWriter.ts
11146
+ /**
11147
+ * @description 通过独立的 Vite write 阶段持久化 DevEngine 已生成的文件,不重新解析业务源码。
11148
+ */
11149
+ async function writeStatefulHmrOutput(outDir, output) {
11150
+ const virtualEntry = "\0weapp-vite-stateful-hmr-output";
11151
+ await build({
11152
+ configFile: false,
11153
+ logLevel: "silent",
11154
+ build: {
11155
+ emptyOutDir: false,
11156
+ minify: false,
11157
+ outDir,
11158
+ rolldownOptions: { input: virtualEntry },
11159
+ write: true
11160
+ },
11161
+ plugins: [{
11162
+ name: "weapp-vite:stateful-hmr-output-writer",
11163
+ resolveId(id) {
11164
+ return id === virtualEntry ? virtualEntry : void 0;
11165
+ },
11166
+ load(id) {
11167
+ return id === virtualEntry ? "export {}" : void 0;
11168
+ },
11169
+ buildStart() {
11170
+ for (const item of output) this.emitFile({
11171
+ type: "asset",
11172
+ fileName: item.fileName.replaceAll("\\", "/"),
11173
+ source: item.type === "chunk" ? item.code : item.source
11174
+ });
11175
+ },
11176
+ generateBundle(_options, bundle) {
11177
+ for (const [fileName, item] of Object.entries(bundle)) if (item.type === "chunk" && item.facadeModuleId === virtualEntry) delete bundle[fileName];
11178
+ }
11179
+ }],
11180
+ root: path$1.dirname(outDir)
11181
+ });
11182
+ }
11183
+ //#endregion
11184
+ //#region src/runtime/statefulHmr/sidecarPlugin.ts
11185
+ function createStatefulHmrSidecarModuleCode(id, source) {
11186
+ const request = parseSidecarSourceRequest(id);
11187
+ if (!request || request.kind === "style") return;
11188
+ const digest = createHash("sha256").update(source).digest("hex");
11189
+ return `export default ${JSON.stringify(digest)};\n`;
11190
+ }
11191
+ function createStatefulHmrSidecarPlugin() {
11192
+ return {
11193
+ name: "weapp-vite:stateful-hmr-sidecar",
11194
+ enforce: "pre",
11195
+ async load(id) {
11196
+ const request = parseSidecarSourceRequest(id);
11197
+ if (!request || request.kind === "style") return;
11198
+ this.addWatchFile(request.sourceId);
11199
+ const code = createStatefulHmrSidecarModuleCode(id, await readFile(request.sourceId, "utf8"));
11200
+ return code ? {
11201
+ code,
11202
+ moduleSideEffects: "no-treeshake"
11203
+ } : void 0;
11204
+ }
11205
+ };
11206
+ }
11207
+ //#endregion
11208
+ //#region src/runtime/statefulHmr/snapshotScheduler.ts
11209
+ const DEFAULT_SNAPSHOT_DEBOUNCE_MS = 40;
11210
+ var StatefulHmrSnapshotScheduler = class {
11211
+ closed = false;
11212
+ debounceMs;
11213
+ execute;
11214
+ onError;
11215
+ pendingFiles = /* @__PURE__ */ new Set();
11216
+ pendingMode;
11217
+ revision = 0;
11218
+ runningPromise;
11219
+ timer;
11220
+ constructor(options) {
11221
+ this.debounceMs = options.debounceMs ?? DEFAULT_SNAPSHOT_DEBOUNCE_MS;
11222
+ this.execute = options.execute;
11223
+ this.onError = options.onError;
11224
+ }
11225
+ request(mode, files = []) {
11226
+ if (this.closed) return;
11227
+ for (const file of files) this.pendingFiles.add(file);
11228
+ this.pendingMode = this.pendingMode === "full" || mode === "full" ? "full" : "refresh";
11229
+ this.revision += 1;
11230
+ if (!this.runningPromise) this.schedule();
11231
+ }
11232
+ isPending() {
11233
+ return Boolean(this.timer || this.runningPromise || this.pendingMode);
11234
+ }
11235
+ async close() {
11236
+ this.closed = true;
11237
+ if (this.timer) {
11238
+ clearTimeout(this.timer);
11239
+ this.timer = void 0;
11240
+ }
11241
+ this.pendingFiles.clear();
11242
+ this.pendingMode = void 0;
11243
+ await this.runningPromise;
11244
+ }
11245
+ schedule() {
11246
+ if (this.closed) return;
11247
+ if (this.timer) clearTimeout(this.timer);
11248
+ this.timer = setTimeout(() => {
11249
+ this.timer = void 0;
11250
+ this.startPendingBatch();
11251
+ }, this.debounceMs);
11252
+ }
11253
+ startPendingBatch() {
11254
+ if (this.closed || this.runningPromise || !this.pendingMode) return;
11255
+ const batchRevision = this.revision;
11256
+ const batchFiles = [...this.pendingFiles];
11257
+ const batchMode = this.pendingMode;
11258
+ this.pendingFiles.clear();
11259
+ this.pendingMode = void 0;
11260
+ const isSuperseded = () => this.closed || this.revision !== batchRevision;
11261
+ this.runningPromise = this.execute({
11262
+ files: batchFiles,
11263
+ isSuperseded,
11264
+ mode: batchMode
11265
+ }).catch((error) => this.onError?.(error)).finally(() => {
11266
+ if (!this.closed && isSuperseded()) {
11267
+ for (const file of batchFiles) this.pendingFiles.add(file);
11268
+ this.pendingMode = this.pendingMode === "full" || batchMode === "full" ? "full" : "refresh";
11269
+ }
11270
+ this.runningPromise = void 0;
11271
+ if (this.pendingMode) this.schedule();
11272
+ });
11273
+ }
11274
+ };
11275
+ //#endregion
11041
11276
  //#region src/runtime/statefulHmr/serverState.ts
11042
11277
  function createStatefulHmrServerState(buildId) {
11043
11278
  return {
@@ -11055,6 +11290,7 @@ function transitionStatefulHmrServer(state, event) {
11055
11290
  return unchanged({
11056
11291
  ...state,
11057
11292
  deltas: [...state.deltas, {
11293
+ changedIds: event.changedIds,
11058
11294
  code: event.code,
11059
11295
  version
11060
11296
  }],
@@ -11199,10 +11435,11 @@ var StatefulHmrTransport = class {
11199
11435
  this.closed = true;
11200
11436
  this.respondToAll({ type: "rebuilding" });
11201
11437
  }
11202
- addDelta(code) {
11438
+ addDelta(code, changedIds) {
11203
11439
  this.apply({
11204
11440
  type: "delta-added",
11205
11441
  bytes: Buffer.byteLength(code),
11442
+ changedIds,
11206
11443
  code
11207
11444
  });
11208
11445
  this.respondToAll({ type: "changed" });
@@ -11321,8 +11558,10 @@ var StatefulHmrTransport = class {
11321
11558
  }
11322
11559
  };
11323
11560
  function renderBatch(batch, nonce) {
11561
+ const changedIds = [...new Set(batch.deltas.flatMap((delta) => delta.changedIds))];
11324
11562
  const metadata = {
11325
11563
  buildId: batch.buildId,
11564
+ changedIds,
11326
11565
  compatible: true,
11327
11566
  fromVersion: batch.fromVersion,
11328
11567
  targetVersion: batch.targetVersion
@@ -11367,6 +11606,7 @@ var StatefulHmrViteAdapter = class {
11367
11606
  server;
11368
11607
  callbacks;
11369
11608
  bundledDev;
11609
+ initialOutputError;
11370
11610
  constructor(config, server, callbacks) {
11371
11611
  this.config = config;
11372
11612
  this.server = server;
@@ -11382,32 +11622,45 @@ var StatefulHmrViteAdapter = class {
11382
11622
  this.installPatches(bundledDev);
11383
11623
  this.installListener(bundledDev);
11384
11624
  }
11385
- async rebuild() {
11625
+ async rebuild(prepare) {
11386
11626
  const engine = this.bundledDev?._devEngine;
11387
- if (!engine) return;
11627
+ if (!engine) throw new Error("Vite DevEngine 未初始化,无法执行 stateful HMR 完整刷新。");
11628
+ await prepare?.();
11388
11629
  engine.triggerFullBuild();
11389
11630
  await engine.ensureLatestBuildOutput();
11390
11631
  }
11391
- registerBundleModules(output) {
11632
+ async registerBundleModules(output) {
11392
11633
  const moduleIds = /* @__PURE__ */ new Set();
11634
+ const payloadFilenames = [];
11393
11635
  for (const item of output) {
11394
11636
  if (item.type !== "chunk") continue;
11637
+ payloadFilenames.push(item.fileName);
11395
11638
  for (const match of item.code.matchAll(/registerModule\("([^"]+)"/g)) moduleIds.add(match[1]);
11396
11639
  for (const id of Object.keys(item.modules ?? {})) {
11397
11640
  const normalized = toStableModuleId(id, this.config.root);
11398
11641
  if (!moduleIds.has(normalized)) moduleIds.add(normalized);
11399
11642
  }
11400
11643
  }
11401
- this.registerModules([...moduleIds]);
11644
+ await this.registerModules([...moduleIds]);
11645
+ await this.markPayloadsDelivered(payloadFilenames);
11402
11646
  return moduleIds.size;
11403
11647
  }
11404
- registerPatchModules(code) {
11648
+ async registerPatchModules(code) {
11405
11649
  const moduleIds = /* @__PURE__ */ new Set();
11406
11650
  for (const match of code.matchAll(/create(?:Esm|Cjs)Initializer\("([^"]+)"/g)) moduleIds.add(match[1]);
11407
- this.registerModules([...moduleIds]);
11651
+ await this.registerModules([...moduleIds]);
11408
11652
  }
11409
- registerModules(moduleIds) {
11410
- if (moduleIds.length) this.bundledDev?._devEngine?.registerModules(clientId, moduleIds);
11653
+ async markPayloadDelivered(filename) {
11654
+ await this.markPayloadsDelivered([filename]);
11655
+ }
11656
+ async registerModules(moduleIds) {
11657
+ const engine = this.bundledDev?._devEngine;
11658
+ if (moduleIds.length && typeof engine?.registerModules === "function") await engine.registerModules(clientId, moduleIds);
11659
+ }
11660
+ async markPayloadsDelivered(filenames) {
11661
+ const engine = this.bundledDev?._devEngine;
11662
+ if (typeof engine?.notifyPayloadDelivered !== "function") return;
11663
+ for (const filename of filenames) await engine.notifyPayloadDelivered(filename);
11411
11664
  }
11412
11665
  installOptions(bundledDev) {
11413
11666
  const original = bundledDev.getRolldownOptions.bind(bundledDev);
@@ -11434,8 +11687,9 @@ var StatefulHmrViteAdapter = class {
11434
11687
  options.experimental ??= {};
11435
11688
  options.experimental.devMode = {
11436
11689
  ...typeof options.experimental.devMode === "object" ? options.experimental.devMode : {},
11437
- implement: statefulHmrRolldownRuntimeSource,
11438
- lazy: false
11690
+ implement: createStatefulHmrRolldownRuntimeSource(),
11691
+ lazy: false,
11692
+ skipCommonRuntimeInjection: true
11439
11693
  };
11440
11694
  return options;
11441
11695
  };
@@ -11443,14 +11697,23 @@ var StatefulHmrViteAdapter = class {
11443
11697
  installOutput(bundledDev) {
11444
11698
  const original = bundledDev.storeOutputFiles.bind(bundledDev);
11445
11699
  bundledDev.storeOutputFiles = (output) => {
11446
- original(output);
11447
- this.callbacks.onOutput(output);
11700
+ try {
11701
+ if (output.some((item) => item.fileName === "app.js")) assertStatefulHmrRuntimeOutput(output);
11702
+ original(output);
11703
+ this.callbacks.onOutput(output);
11704
+ } catch (error) {
11705
+ this.initialOutputError = error instanceof Error ? error : new Error(String(error));
11706
+ throw error;
11707
+ }
11448
11708
  };
11449
11709
  }
11450
11710
  installPatches(bundledDev) {
11451
11711
  const original = bundledDev.handleHmrOutput.bind(bundledDev);
11452
11712
  bundledDev.handleHmrOutput = (client, files, output, info) => {
11453
- if (output.type === "Noop") return;
11713
+ if (output.type === "Noop") {
11714
+ this.callbacks.onPatch(files, output);
11715
+ return;
11716
+ }
11454
11717
  if (this.callbacks.onPatch(files, output)) original(client, files, output, info);
11455
11718
  };
11456
11719
  }
@@ -11461,7 +11724,9 @@ var StatefulHmrViteAdapter = class {
11461
11724
  bundledDev.clients.setupIfNeeded({ send: (payload) => this.handlePayload(payload) }, clientId);
11462
11725
  const engine = bundledDev._devEngine;
11463
11726
  if (!engine) throw new Error("Vite 未初始化微信状态保持 HMR 所需的 DevEngine。");
11727
+ await engine.registerClient?.(clientId);
11464
11728
  await engine.ensureCurrentBuildFinish();
11729
+ if (this.initialOutputError) throw this.initialOutputError;
11465
11730
  if ((await engine.getBundleState()).lastBuildErrored) throw new Error("微信状态保持 HMR 初次构建失败。");
11466
11731
  await this.callbacks.waitForInitialBundle();
11467
11732
  };
@@ -11501,7 +11766,7 @@ function toStableModuleId(id, root) {
11501
11766
  //#region src/runtime/statefulHmr/session.ts
11502
11767
  const maxRetainedDeltaCount = 1e3;
11503
11768
  const maxRetainedDeltaBytes = 16777216;
11504
- async function runStatefulHmrDev(ctx, buildOptions, restart) {
11769
+ async function runStatefulHmrDev(ctx, buildOptions, restart, snapshots) {
11505
11770
  const configService = ctx.configService;
11506
11771
  if (configService.platform !== "weapp") throw new Error("weapp.hmr.runtime=\"stateful-experimental\" 目前仅支持微信小程序平台。");
11507
11772
  let session;
@@ -11509,12 +11774,12 @@ async function runStatefulHmrDev(ctx, buildOptions, restart) {
11509
11774
  name: "weapp-vite:stateful-hmr-session",
11510
11775
  enforce: "post",
11511
11776
  configureServer(server) {
11512
- const currentSession = new StatefulHmrSession(ctx, server, restart);
11777
+ const currentSession = new StatefulHmrSession(ctx, server, restart, snapshots);
11513
11778
  session = currentSession;
11514
11779
  currentSession.install();
11515
11780
  },
11516
11781
  transform(code, id) {
11517
- if (!isStatefulHmrBoundary(id, configService.absoluteSrcRoot) || code.includes("import.meta.hot.accept")) return;
11782
+ if (!isStatefulHmrBoundary(id, configService.absoluteSrcRoot, ctx.runtimeState.build.hmr.resolvedEntryMap.keys()) || code.includes("import.meta.hot.accept")) return;
11518
11783
  return `${id.endsWith(".vue") ? code : redirectNativeComponentRegistration(code)}\nif (import.meta.hot) import.meta.hot.accept();\n`;
11519
11784
  }
11520
11785
  };
@@ -11531,7 +11796,11 @@ async function runStatefulHmrDev(ctx, buildOptions, restart) {
11531
11796
  ...buildOptions.experimental ?? {},
11532
11797
  bundledDev: true
11533
11798
  },
11534
- plugins: [installPlugin, ...buildOptions.plugins ?? []],
11799
+ plugins: [
11800
+ createStatefulHmrSidecarPlugin(),
11801
+ installPlugin,
11802
+ ...buildOptions.plugins ?? []
11803
+ ],
11535
11804
  server: {
11536
11805
  ...buildOptions.server ?? {},
11537
11806
  host: "127.0.0.1",
@@ -11543,28 +11812,39 @@ async function runStatefulHmrDev(ctx, buildOptions, restart) {
11543
11812
  write: false
11544
11813
  }
11545
11814
  });
11546
- await server.listen();
11547
- if (!session) {
11548
- await server.close();
11549
- throw new Error("微信状态保持 HMR session 未完成初始化。");
11815
+ try {
11816
+ await server.listen();
11817
+ if (!session) throw new Error("微信状态保持 HMR session 未完成初始化。");
11818
+ await session.refreshControl();
11819
+ return createWatcherAdapter(server, session);
11820
+ } catch (error) {
11821
+ await session?.close().catch(() => {});
11822
+ await server.close().catch(() => {});
11823
+ throw error;
11550
11824
  }
11551
- await session.refreshControl();
11552
- return createWatcherAdapter(server, session);
11553
11825
  }
11554
11826
  var StatefulHmrSession = class {
11555
11827
  ctx;
11556
11828
  server;
11557
11829
  restart;
11830
+ snapshots;
11831
+ activeSnapshotBatch;
11558
11832
  adapter;
11559
11833
  initialBundle = Promise.withResolvers();
11834
+ snapshotScheduler;
11560
11835
  transport;
11561
11836
  outputChain = Promise.resolve();
11562
- rebuildTimer;
11563
11837
  restartTimer;
11564
- constructor(ctx, server, restart) {
11838
+ snapshotAssets = /* @__PURE__ */ new Map();
11839
+ sourceChangeListener = (file, dirtyReasonSummary) => {
11840
+ this.handleSourceUpdate(file, dirtyReasonSummary);
11841
+ };
11842
+ constructor(ctx, server, restart, snapshots) {
11565
11843
  this.ctx = ctx;
11566
11844
  this.server = server;
11567
11845
  this.restart = restart;
11846
+ this.snapshots = snapshots;
11847
+ this.replaceSnapshotAssets(snapshots.initial);
11568
11848
  this.transport = new StatefulHmrTransport(server, async (buildId, source) => {
11569
11849
  await this.enqueueOutput(async () => {
11570
11850
  if (!this.transport.isCurrentBuild(buildId)) return;
@@ -11581,15 +11861,21 @@ var StatefulHmrSession = class {
11581
11861
  onPatch: (files, output) => this.handlePatch(files, output),
11582
11862
  waitForInitialBundle: () => this.waitForInitialBundle()
11583
11863
  });
11864
+ this.snapshotScheduler = new StatefulHmrSnapshotScheduler({
11865
+ execute: (batch) => this.executeSnapshotBatch(batch),
11866
+ onError: (error) => this.server.config.logger.error("[weapp-vite] stateful HMR snapshot refresh failed", { error: error instanceof Error ? error : new Error(String(error)) })
11867
+ });
11584
11868
  }
11585
11869
  install() {
11586
11870
  this.transport.install();
11587
11871
  this.adapter.install();
11872
+ this.ctx.onStatefulHmrSourceChange = this.sourceChangeListener;
11588
11873
  }
11589
11874
  async close() {
11590
- if (this.rebuildTimer) clearTimeout(this.rebuildTimer);
11591
11875
  if (this.restartTimer) clearTimeout(this.restartTimer);
11876
+ if (this.ctx.onStatefulHmrSourceChange === this.sourceChangeListener) this.ctx.onStatefulHmrSourceChange = void 0;
11592
11877
  this.transport.close();
11878
+ await this.snapshotScheduler.close();
11593
11879
  await this.outputChain;
11594
11880
  }
11595
11881
  async refreshControl() {
@@ -11601,13 +11887,30 @@ var StatefulHmrSession = class {
11601
11887
  }]);
11602
11888
  });
11603
11889
  }
11890
+ handleSourceUpdate(file, dirtyReasonSummary = []) {
11891
+ const normalizedFile = normalizeFsResolvedId(path.isAbsolute(file) ? file : path.resolve(this.server.config.root, file));
11892
+ const normalizedOutDir = normalizeFsResolvedId(this.ctx.configService.outDir).replace(/\/$/, "");
11893
+ if (normalizedFile === normalizedOutDir || normalizedFile.startsWith(`${normalizedOutDir}/`)) return;
11894
+ if (shouldRestartStatefulHmrServer([normalizedFile], this.ctx.configService?.configFileDependencies)) {
11895
+ this.requestServerRestart();
11896
+ return;
11897
+ }
11898
+ if (requiresStatefulHmrSnapshot(normalizedFile, dirtyReasonSummary)) {
11899
+ if (!this.snapshotScheduler.isPending()) logger_default.info("HMR 更新:正在同步模板、样式与静态资源...");
11900
+ this.requestSnapshotRefresh([normalizedFile]);
11901
+ }
11902
+ }
11604
11903
  handleOutput(output) {
11904
+ const snapshotBatch = this.activeSnapshotBatch;
11605
11905
  this.enqueueOutput(async () => {
11906
+ if (snapshotBatch?.isSuperseded()) return;
11606
11907
  const compatibleOutput = await transformOutput(output);
11607
11908
  const fullBuild = compatibleOutput.some((item) => item.fileName === "app.js");
11608
11909
  if (fullBuild) {
11910
+ mergeStatefulHmrSnapshotAssets(compatibleOutput, this.snapshotAssets.values());
11609
11911
  const buildId = this.transport.createBuildId();
11610
11912
  this.transport.commitFullBuild(buildId);
11913
+ stampStatefulHmrFullBuild(compatibleOutput, buildId);
11611
11914
  setAsset(compatibleOutput, WEAPP_VITE_STATEFUL_HMR_CONTROL_FILE, createStatefulHmrControlSource({
11612
11915
  ...this.transport.createControl(),
11613
11916
  buildId
@@ -11617,38 +11920,40 @@ var StatefulHmrSession = class {
11617
11920
  }
11618
11921
  await writeStatefulHmrOutput(this.ctx.configService.outDir, compatibleOutput);
11619
11922
  if (fullBuild) {
11620
- const moduleCount = this.adapter.registerBundleModules(compatibleOutput);
11923
+ const moduleCount = await this.adapter.registerBundleModules(compatibleOutput);
11621
11924
  this.server.config.logger.info(`[weapp-vite] 微信状态保持 HMR 已就绪(${moduleCount} modules)`);
11622
11925
  this.initialBundle.resolve();
11623
11926
  }
11624
11927
  });
11625
11928
  }
11626
11929
  handlePatch(files, output) {
11627
- if (!isSafeJavaScriptPatch(files, output, this.ctx.runtimeState.build.hmr.profile.dirtyReasonSummary)) {
11628
- this.requestServerRestart();
11930
+ if (output.type === "Noop") return false;
11931
+ if (!isSafeJavaScriptPatch(files, output, this.ctx.runtimeState.build.hmr.profile.dirtyReasonSummary, this.ctx.runtimeState.build.hmr.resolvedEntryMap.keys(), this.server.config.root)) {
11932
+ if (shouldRestartStatefulHmrServer(files, this.ctx.configService?.configFileDependencies)) this.requestServerRestart();
11933
+ else if (files.length > 0 && files.every(isStatefulHmrAssetFile) || shouldUseStatefulHmrSnapshotOnly(this.ctx.runtimeState.build.hmr.profile.dirtyReasonSummary ?? [])) {
11934
+ if (!this.snapshotScheduler.isPending()) this.requestSnapshotRefresh(files);
11935
+ } else this.requestFullBuild(files);
11629
11936
  return false;
11630
11937
  }
11631
- this.adapter.registerPatchModules(output.code);
11632
- transformJavaScript(output.code, output.filename).then((code) => {
11938
+ this.adapter.registerPatchModules(output.code).then(async () => {
11939
+ const code = await transformJavaScript(output.code, output.filename);
11633
11940
  if (shouldResetStatefulHmrRetention(this.transport.retainedDeltaCount, this.transport.retainedDeltaBytes, Buffer.byteLength(code))) {
11634
11941
  this.requestFullBuild();
11635
11942
  return;
11636
11943
  }
11637
- this.transport.addDelta(code);
11944
+ this.transport.addDelta(code, output.changedIds ?? []);
11945
+ return this.adapter.markPayloadDelivered(output.filename);
11638
11946
  }).catch((error) => {
11639
11947
  this.server.config.logger.error("[weapp-vite] stateful HMR patch transform failed", { error });
11640
11948
  this.requestFullBuild();
11641
11949
  });
11642
11950
  return true;
11643
11951
  }
11644
- requestFullBuild() {
11645
- if (this.rebuildTimer) return;
11646
- this.rebuildTimer = setTimeout(() => {
11647
- this.rebuildTimer = void 0;
11648
- this.adapter.rebuild().catch((error) => {
11649
- this.server.config.logger.error("[weapp-vite] stateful HMR full rebuild failed", { error });
11650
- });
11651
- }, 100);
11952
+ requestFullBuild(files = []) {
11953
+ this.snapshotScheduler.request("full", files);
11954
+ }
11955
+ requestSnapshotRefresh(files = []) {
11956
+ this.snapshotScheduler.request("refresh", files);
11652
11957
  }
11653
11958
  requestServerRestart() {
11654
11959
  if (this.restartTimer) return;
@@ -11661,15 +11966,64 @@ var StatefulHmrSession = class {
11661
11966
  }
11662
11967
  enqueueOutput(task) {
11663
11968
  this.outputChain = this.outputChain.then(task, task).catch((error) => {
11664
- this.server.config.logger.error("[weapp-vite] stateful HMR output failed", { error });
11969
+ this.server.config.logger.error(`[weapp-vite] stateful HMR output failed: ${formatStatefulHmrError(error)}`);
11665
11970
  });
11666
11971
  return this.outputChain;
11667
11972
  }
11973
+ async executeSnapshotBatch(batch) {
11974
+ const output = await this.snapshots.rebuild(batch.files);
11975
+ if (batch.isSuperseded()) return;
11976
+ if (batch.mode === "full") {
11977
+ this.replaceSnapshotAssets(output);
11978
+ this.activeSnapshotBatch = batch;
11979
+ try {
11980
+ await this.adapter.rebuild();
11981
+ await this.outputChain;
11982
+ } finally {
11983
+ if (this.activeSnapshotBatch === batch) this.activeSnapshotBatch = void 0;
11984
+ }
11985
+ return;
11986
+ }
11987
+ const changedOutput = getChangedStatefulHmrSnapshotAssets(this.snapshotAssets.values(), output);
11988
+ this.replaceSnapshotAssets(output);
11989
+ await this.enqueueOutput(async () => {
11990
+ if (!batch.isSuperseded()) await writeStatefulHmrOutput(this.ctx.configService.outDir, changedOutput);
11991
+ });
11992
+ }
11993
+ replaceSnapshotAssets(output) {
11994
+ this.snapshotAssets = new Map(output.filter((item) => item.type === "asset").map((item) => [item.fileName, item]));
11995
+ }
11668
11996
  async waitForInitialBundle() {
11669
11997
  await this.initialBundle.promise;
11670
11998
  await this.outputChain;
11671
11999
  }
11672
12000
  };
12001
+ function shouldRestartStatefulHmrServer(files, configFileDependencies = []) {
12002
+ const normalizedConfigDependencies = new Set(Array.from(configFileDependencies, (dependency) => normalizeFsResolvedId(dependency)));
12003
+ return Array.from(files).some((file) => normalizedConfigDependencies.has(normalizeFsResolvedId(file)));
12004
+ }
12005
+ function mergeStatefulHmrSnapshotAssets(output, snapshotAssets) {
12006
+ for (const asset of snapshotAssets) {
12007
+ if (asset.type !== "asset") continue;
12008
+ const index = output.findIndex((item) => item.fileName === asset.fileName);
12009
+ if (index >= 0) output[index] = asset;
12010
+ else output.push(asset);
12011
+ }
12012
+ }
12013
+ function getChangedStatefulHmrSnapshotAssets(previous, next) {
12014
+ const previousAssets = new Map(Array.from(previous).flatMap((item) => item.type === "asset" ? [[item.fileName, item.source]] : []));
12015
+ return Array.from(next).filter((item) => {
12016
+ if (item.type !== "asset") return true;
12017
+ const previousSource = previousAssets.get(item.fileName);
12018
+ return previousSource === void 0 || !statefulHmrAssetSourcesEqual(previousSource, item.source);
12019
+ });
12020
+ }
12021
+ function statefulHmrAssetSourcesEqual(left, right) {
12022
+ if (left === right) return true;
12023
+ const leftBuffer = Buffer.isBuffer(left) ? left : Buffer.from(left);
12024
+ const rightBuffer = Buffer.isBuffer(right) ? right : Buffer.from(right);
12025
+ return leftBuffer.equals(rightBuffer);
12026
+ }
11673
12027
  function createWatcherAdapter(server, session) {
11674
12028
  return {
11675
12029
  close: async () => {
@@ -11681,13 +12035,16 @@ function createWatcherAdapter(server, session) {
11681
12035
  }
11682
12036
  };
11683
12037
  }
11684
- function isStatefulHmrBoundary(id, srcRoot) {
12038
+ function isStatefulHmrBoundary(id, srcRoot, entryIds) {
11685
12039
  const sidecar = parseSidecarSourceRequest(id);
11686
12040
  const sourceId = sidecar?.kind === "script" ? sidecar.sourceId : id.includes("?") ? void 0 : id;
11687
12041
  if (!sourceId) return false;
11688
- const normalizedSourceId = sourceId.replaceAll("\\", "/");
11689
- const normalizedSrcRoot = srcRoot.replaceAll("\\", "/").replace(/\/$/, "");
11690
- return normalizedSourceId.startsWith(`${normalizedSrcRoot}/`) && /\.(?:[cm]?[jt]sx?|vue)$/.test(normalizedSourceId);
12042
+ const normalizedSourceId = normalizeFsResolvedId(sourceId);
12043
+ const normalizedSrcRoot = normalizeFsResolvedId(srcRoot).replace(/\/$/, "");
12044
+ if (!normalizedSourceId.startsWith(`${normalizedSrcRoot}/`) || !/\.(?:[cm]?[jt]sx?|vue)$/.test(normalizedSourceId)) return false;
12045
+ if (!entryIds) return true;
12046
+ for (const entryId of entryIds) if (normalizeFsResolvedId(entryId) === normalizedSourceId) return true;
12047
+ return false;
11691
12048
  }
11692
12049
  function redirectNativeComponentRegistration(code) {
11693
12050
  if (!code.includes("Component")) return code;
@@ -11702,8 +12059,28 @@ function redirectNativeComponentRegistration(code) {
11702
12059
  } });
11703
12060
  return changed ? magicString.toString() : code;
11704
12061
  }
11705
- function isSafeJavaScriptPatch(files, output, dirtyReasonSummary = []) {
11706
- return output.type === "Patch" && output.hmrBoundaries.length > 0 && files.every((file) => /\.(?:[cm]?[jt]sx?|vue)$/.test(file)) && !dirtyReasonSummary.some((reason) => /^(?:entry-json-only|entry-local-asset|entry-style-only):/.test(reason));
12062
+ function isSafeJavaScriptPatch(files, output, dirtyReasonSummary = [], entryIds, root) {
12063
+ const normalizedEntryIds = entryIds ? new Set(Array.from(entryIds, (entryId) => normalizeFsResolvedId(entryId))) : void 0;
12064
+ return output.type === "Patch" && files.every((file) => /\.(?:[cm]?[jt]sx?|vue)$/.test(file)) && (!normalizedEntryIds || files.every((file) => {
12065
+ const absoluteFile = path.isAbsolute(file) || !root ? file : path.resolve(root, file);
12066
+ return normalizedEntryIds.has(normalizeFsResolvedId(absoluteFile));
12067
+ })) && !output.changedIds?.some(isNonJavaScriptSidecarId) && !dirtyReasonSummary.some(isUnsafeStatefulHmrReason);
12068
+ }
12069
+ function requiresStatefulHmrSnapshot(file, dirtyReasonSummary = []) {
12070
+ return !/\.(?:[cm]?[jt]sx?|vue)$/.test(file) || dirtyReasonSummary.some(isUnsafeStatefulHmrReason);
12071
+ }
12072
+ function isStatefulHmrAssetFile(file) {
12073
+ return !/\.(?:[cm]?[jt]sx?|vue)$/.test(file);
12074
+ }
12075
+ function isUnsafeStatefulHmrReason(reason) {
12076
+ return /^(?:entry-json-only|entry-local-asset|entry-style-only|tailwind-content):/.test(reason);
12077
+ }
12078
+ function shouldUseStatefulHmrSnapshotOnly(dirtyReasonSummary) {
12079
+ return dirtyReasonSummary.some((reason) => /^(?:entry-json-only|entry-local-asset|entry-style-only):/.test(reason)) && dirtyReasonSummary.every((reason) => /^(?:entry-json-only|entry-local-asset|entry-style-only|tailwind-content):/.test(reason));
12080
+ }
12081
+ function isNonJavaScriptSidecarId(id) {
12082
+ const sidecar = parseSidecarSourceRequest(id) ?? parseSidecarModuleId(id);
12083
+ return sidecar !== void 0 && sidecar.kind !== "script";
11707
12084
  }
11708
12085
  function shouldResetStatefulHmrRetention(retainedDeltaCount, retainedDeltaBytes, nextDeltaBytes) {
11709
12086
  return retainedDeltaCount >= maxRetainedDeltaCount || retainedDeltaBytes + nextDeltaBytes >= maxRetainedDeltaBytes;
@@ -11735,6 +12112,13 @@ function setAsset(output, fileName, source) {
11735
12112
  if (index >= 0) output[index] = asset;
11736
12113
  else output.push(asset);
11737
12114
  }
12115
+ function stampStatefulHmrFullBuild(output, buildId) {
12116
+ for (const item of output) if (item.type === "chunk" && item.fileName.endsWith(".js")) item.code = `// weapp-vite-stateful-build:${buildId}\n${item.code}`;
12117
+ }
12118
+ function formatStatefulHmrError(error) {
12119
+ if (error instanceof Error) return error.stack || error.message;
12120
+ return String(error);
12121
+ }
11738
12122
  //#endregion
11739
12123
  //#region src/runtime/watch/options.ts
11740
12124
  function resolvePollingWatchConfig(configService) {
@@ -12983,8 +13367,10 @@ function parseWxml(options) {
12983
13367
  };
12984
13368
  if (Array.isArray(autoImportComponents[componentName])) autoImportComponents[componentName].push(range);
12985
13369
  else autoImportComponents[componentName] = [range];
12986
- if (!excludeComponent(currentTagName)) if (Array.isArray(components[componentName])) components[componentName].push(range);
12987
- else components[componentName] = [range];
13370
+ if (!excludeComponent(currentTagName)) {
13371
+ if (Array.isArray(components[componentName])) components[componentName].push(range);
13372
+ else components[componentName] = [range];
13373
+ }
12988
13374
  }
12989
13375
  if (normalizeComponentTagName && shouldNormalizeTagName(name)) {
12990
13376
  const normalized = toKebabCaseTagName(name);
@@ -13868,6 +14254,7 @@ function resetEmittedOutputCaches(runtimeState) {
13868
14254
  runtimeState.asset.scopedSlotGenerics.clear();
13869
14255
  runtimeState.build?.output?.emittedSource.clear();
13870
14256
  runtimeState.css.emittedSource.clear();
14257
+ runtimeState.css.transformedSidecarSource.clear();
13871
14258
  runtimeState.wxml.emittedCode.clear();
13872
14259
  }
13873
14260
  async function cleanOutputs(configService) {
@@ -13976,6 +14363,10 @@ function watchWorkers(configService, watcherService, workersDir) {
13976
14363
  }
13977
14364
  //#endregion
13978
14365
  //#region src/runtime/buildPlugin/service.ts
14366
+ function toStatefulHmrOutput(output) {
14367
+ if (!Array.isArray(output) && !("output" in output)) throw new TypeError("stateful HMR snapshot build unexpectedly returned a watcher");
14368
+ return (Array.isArray(output) ? output : [output]).flatMap((result) => result.output);
14369
+ }
13979
14370
  function resolveSnapshotSidecarDirtySummary(filePath, affectedEntries) {
13980
14371
  const normalizedFile = normalizeFsResolvedId(filePath);
13981
14372
  if (configSuffixes.find((suffix) => normalizedFile.endsWith(suffix))) return "json-sidecar:1";
@@ -14087,6 +14478,8 @@ function createSnapshotSidecarIgnoredMatcher(ctx) {
14087
14478
  }
14088
14479
  function createBuildService(ctx) {
14089
14480
  let lastHmrSlowTipProfileCount = 0;
14481
+ let devHmrRuntime;
14482
+ let devHmrRuntimeNoticeLogged = false;
14090
14483
  function createHmrProfileJsonSample(totalMs) {
14091
14484
  const profile = ctx.runtimeState.build.hmr.profile;
14092
14485
  const relativeFile = profile.file && ctx.configService ? ctx.configService.relativeCwd(profile.file) : void 0;
@@ -14653,15 +15046,35 @@ function createBuildService(ctx) {
14653
15046
  ...buildOptions.build ?? {},
14654
15047
  write: true
14655
15048
  };
14656
- if (target === "app" && configService.weappViteConfig.hmr?.runtime === "stateful-experimental") {
15049
+ const configuredHmrRuntime = configService.weappViteConfig.hmr?.runtime;
15050
+ const compileHotReLoad = configService.projectPrivateConfig.setting?.compileHotReLoad;
15051
+ devHmrRuntime ??= resolveHmrRuntime({
15052
+ platform: configService.platform,
15053
+ configured: configuredHmrRuntime,
15054
+ compileHotReLoad
15055
+ });
15056
+ const hmrRuntime = devHmrRuntime;
15057
+ if (target === "app" && !devHmrRuntimeNoticeLogged) {
15058
+ devHmrRuntimeNoticeLogged = true;
15059
+ const messages = formatHmrRuntimeStartupMessages({
15060
+ platform: configService.platform,
15061
+ configured: configuredHmrRuntime,
15062
+ compileHotReLoad,
15063
+ runtime: hmrRuntime
15064
+ });
15065
+ for (const message of messages) logger_default.info(message);
15066
+ }
15067
+ if (target === "app" && hmrRuntime === "stateful-experimental") try {
14657
15068
  const snapshotBuildOptions = {
14658
15069
  ...buildOptions,
14659
15070
  build: {
14660
15071
  ...buildOptions.build ?? {},
14661
- watch: void 0
15072
+ watch: void 0,
15073
+ write: false
14662
15074
  }
14663
15075
  };
14664
- await build(snapshotBuildOptions);
15076
+ const initialSnapshot = toStatefulHmrOutput(await build(snapshotBuildOptions));
15077
+ await configService.load(configService.loadOptions);
14665
15078
  resetRuntimeStateForFreshBuild(ctx.runtimeState);
14666
15079
  await scanService.loadAppEntry();
14667
15080
  scanService.loadSubPackages();
@@ -14676,14 +15089,49 @@ function createBuildService(ctx) {
14676
15089
  await statefulWatcher?.close();
14677
15090
  logger_default.info("检测到非兼容更新,正在重启微信状态保持 HMR 构建...");
14678
15091
  resetRuntimeStateForFreshBuild(ctx.runtimeState);
15092
+ await configService.load(configService.loadOptions);
14679
15093
  await scanService.loadAppEntry();
14680
15094
  scanService.loadSubPackages();
14681
15095
  await runDev(target);
14682
15096
  logger_default.success("微信状态保持 HMR 构建已完成完整重载。");
15097
+ }, {
15098
+ initial: initialSnapshot,
15099
+ rebuild: async (files) => {
15100
+ for (const file of files) invalidateFileCache(file);
15101
+ resetRuntimeStateForFreshBuild(ctx.runtimeState);
15102
+ await configService.load(configService.loadOptions);
15103
+ await scanService.loadAppEntry();
15104
+ scanService.loadSubPackages();
15105
+ const snapshotOptions = createDevBuildOptions();
15106
+ snapshotOptions.build = {
15107
+ ...snapshotOptions.build ?? {},
15108
+ emptyOutDir: false,
15109
+ watch: void 0,
15110
+ write: false
15111
+ };
15112
+ snapshotOptions.plugins = [...snapshotOptions.plugins ?? [], {
15113
+ name: "weapp-vite:stateful-hmr-snapshot-assets",
15114
+ enforce: "post",
15115
+ generateBundle(_options, bundle) {
15116
+ for (const [fileName, item] of Object.entries(bundle)) if (item.type === "chunk") delete bundle[fileName];
15117
+ }
15118
+ }];
15119
+ return toStatefulHmrOutput(await build(snapshotOptions));
15120
+ }
14683
15121
  }), workerPromise]);
14684
15122
  statefulWatcher = watcher;
14685
15123
  watcherService.setRollupWatcher(watcher, "/");
14686
15124
  return watcher;
15125
+ } catch (error) {
15126
+ if (configuredHmrRuntime !== "auto" || !isStatefulHmrRuntimeCompatibilityError(error)) throw error;
15127
+ devHmrRuntime = "classic";
15128
+ logger_default.warn(`微信状态保持 HMR 运行时不可用,已自动降级为 classic:${error instanceof Error ? error.message : String(error)}`);
15129
+ logger_default.info("HMR 模式:classic(自动降级:stateful HMR 运行时兼容性检查失败)");
15130
+ resetRuntimeStateForFreshBuild(ctx.runtimeState);
15131
+ await configService.load(configService.loadOptions);
15132
+ await scanService.loadAppEntry();
15133
+ scanService.loadSubPackages();
15134
+ return await runDev(target);
14687
15135
  }
14688
15136
  const snapshotBuildOptions = {
14689
15137
  ...buildOptions,
@@ -15940,13 +16388,15 @@ function configureBuildAndPlugins(options) {
15940
16388
  }
15941
16389
  if (resolvedLibConfig?.enabled) {
15942
16390
  const entryFileNames = createLibEntryFileNameResolver(resolvedLibConfig);
15943
- if (entryFileNames) if (Array.isArray(rdOptions.output)) rdOptions.output = rdOptions.output.map((output) => ({
15944
- ...output,
15945
- entryFileNames
15946
- }));
15947
- else {
15948
- const output = rdOptions.output ?? (rdOptions.output = {});
15949
- output.entryFileNames = entryFileNames;
16391
+ if (entryFileNames) {
16392
+ if (Array.isArray(rdOptions.output)) rdOptions.output = rdOptions.output.map((output) => ({
16393
+ ...output,
16394
+ entryFileNames
16395
+ }));
16396
+ else {
16397
+ const output = rdOptions.output ?? (rdOptions.output = {});
16398
+ output.entryFileNames = entryFileNames;
16399
+ }
15950
16400
  }
15951
16401
  }
15952
16402
  const rawPlugins = rdOptions.plugins;
@@ -16251,20 +16701,22 @@ function createLoadConfig(options) {
16251
16701
  }
16252
16702
  const loadedConfig = loaded?.config ?? {};
16253
16703
  let weappLoaded;
16254
- if (weappConfigFilePath) if (shouldReuseLoadedWeappConfig(weappConfigFilePath, loaded?.path)) weappLoaded = loaded;
16255
- else try {
16256
- weappLoaded = await loadConfigFileWithFallback({
16257
- command: isDev ? "serve" : "build",
16258
- mode
16259
- }, weappConfigFilePath, cwd, configLoader);
16260
- } catch (error) {
16261
- const cjsError = createCjsConfigLoadError({
16262
- error,
16263
- configPath: weappConfigFilePath,
16264
- cwd
16265
- });
16266
- if (cjsError) throw cjsError;
16267
- throw error;
16704
+ if (weappConfigFilePath) {
16705
+ if (shouldReuseLoadedWeappConfig(weappConfigFilePath, loaded?.path)) weappLoaded = loaded;
16706
+ else try {
16707
+ weappLoaded = await loadConfigFileWithFallback({
16708
+ command: isDev ? "serve" : "build",
16709
+ mode
16710
+ }, weappConfigFilePath, cwd, configLoader);
16711
+ } catch (error) {
16712
+ const cjsError = createCjsConfigLoadError({
16713
+ error,
16714
+ configPath: weappConfigFilePath,
16715
+ cwd
16716
+ });
16717
+ if (cjsError) throw cjsError;
16718
+ throw error;
16719
+ }
16268
16720
  }
16269
16721
  const mergedLoadedConfig = weappLoaded?.config ? defu(weappLoaded.config, loadedConfig) : loadedConfig;
16270
16722
  const config = defu(inlineConfig, {
@@ -16353,6 +16805,7 @@ function createLoadConfig(options) {
16353
16805
  cwd
16354
16806
  });
16355
16807
  let projectConfig = {};
16808
+ let projectPrivateConfig = {};
16356
16809
  let projectConfigPathResolved;
16357
16810
  let projectPrivateConfigPathResolved;
16358
16811
  let mpDistRoot = "";
@@ -16368,6 +16821,7 @@ function createLoadConfig(options) {
16368
16821
  basePath,
16369
16822
  privatePath
16370
16823
  });
16824
+ projectPrivateConfig = await getProjectPrivateConfig(cwd, { privatePath });
16371
16825
  mpDistRoot = resolveProjectConfigRoot(projectConfig, platform) ?? "";
16372
16826
  if (!mpDistRoot) {
16373
16827
  const displayPath = formatProjectConfigPath(cwd, basePath ?? getProjectConfigFileName(platform));
@@ -16428,6 +16882,7 @@ function createLoadConfig(options) {
16428
16882
  emitDefaultAutoImportOutputs: opts.emitDefaultAutoImportOutputs ?? true,
16429
16883
  chunksConfigured,
16430
16884
  projectConfig,
16885
+ projectPrivateConfig,
16431
16886
  projectConfigPath: projectConfigPathResolved,
16432
16887
  projectPrivateConfigPath: projectPrivateConfigPathResolved,
16433
16888
  mpDistRoot,
@@ -20615,6 +21070,7 @@ async function invalidateEntryForSidecar(ctx, filePath, event = "update") {
20615
21070
  }
20616
21071
  const isCssSidecar = Boolean(ext && watchedCssExts.has(ext));
20617
21072
  const isTemplateSidecar = Boolean(ext && watchedTemplateExts.has(ext));
21073
+ if (isCssSidecar) ctx.runtimeState?.css?.transformedSidecarSource.delete(normalizedPath);
20618
21074
  const sidecarCause = configSuffix ? "json-sidecar" : isCssSidecar ? "style-sidecar" : "sidecar-direct";
20619
21075
  const configService = ctx.configService;
20620
21076
  const relativeSource = configService.relativeCwd(normalizedPath);
@@ -23409,6 +23865,10 @@ function hasCustomAutoRuleConfig(config) {
23409
23865
  function hasConfiguredNetworkDefaults(config) {
23410
23866
  return Boolean(config && typeof config === "object" && hasOwn$5(config, "networkDefaults"));
23411
23867
  }
23868
+ function resolveAutoPrelude(config) {
23869
+ if (!config || typeof config !== "object" || !hasOwn$5(config, "prelude")) return true;
23870
+ return config.prelude === true;
23871
+ }
23412
23872
  function resolveAutoRules(config) {
23413
23873
  if (hasCustomAutoRuleConfig(config)) return [{
23414
23874
  dependencyPatterns: resolveDependencyPatterns(config),
@@ -23447,7 +23907,7 @@ function resolveInjectRequestGlobalsOptions(config, packageJson) {
23447
23907
  return {
23448
23908
  mode: "auto",
23449
23909
  targets: [...matchedTargets],
23450
- prelude: config && typeof config === "object" ? config.prelude === true : false
23910
+ prelude: resolveAutoPrelude(config)
23451
23911
  };
23452
23912
  }
23453
23913
  function resolveRequestRuntimeOptions(input, packageJson, warn) {
@@ -23803,18 +24263,20 @@ function removeConditionalBlock(start) {
23803
24263
  while (node && depth > 0) {
23804
24264
  if (node.type === "comment") {
23805
24265
  const directive = parseDirective(node.text);
23806
- if (directive) if (directive.type === "endif") {
23807
- depth -= 1;
23808
- const comment = node;
23809
- node = comment.next();
23810
- comment.remove();
23811
- continue;
23812
- } else {
23813
- depth += 1;
23814
- const comment = node;
23815
- node = comment.next();
23816
- comment.remove();
23817
- continue;
24266
+ if (directive) {
24267
+ if (directive.type === "endif") {
24268
+ depth -= 1;
24269
+ const comment = node;
24270
+ node = comment.next();
24271
+ comment.remove();
24272
+ continue;
24273
+ } else {
24274
+ depth += 1;
24275
+ const comment = node;
24276
+ node = comment.next();
24277
+ comment.remove();
24278
+ continue;
24279
+ }
23818
24280
  }
23819
24281
  }
23820
24282
  const next = node.next();
@@ -23836,10 +24298,12 @@ const postCreator = (options = { platform: "weapp" }) => {
23836
24298
  atRule.name = "import";
23837
24299
  return;
23838
24300
  }
23839
- if (atRule.name === `wv-if`) if (![...atRule.params.matchAll(/\(([^)]+)\)/g)].some((match) => {
23840
- return match[1].trim() === platform;
23841
- })) atRule.remove();
23842
- else atRule.replaceWith(atRule.nodes);
24301
+ if (atRule.name === `wv-if`) {
24302
+ if (![...atRule.params.matchAll(/\(([^)]+)\)/g)].some((match) => {
24303
+ return match[1].trim() === platform;
24304
+ })) atRule.remove();
24305
+ else atRule.replaceWith(atRule.nodes);
24306
+ }
23843
24307
  },
23844
24308
  Comment(comment) {
23845
24309
  const directive = parseDirective(comment.text);
@@ -24164,6 +24628,16 @@ async function readStyleGraphSource(stylePath, fallback) {
24164
24628
  return fallback;
24165
24629
  }
24166
24630
  }
24631
+ async function resolveMemoryStyleSource(ctx, stylePath) {
24632
+ const sourceId = normalizeFsResolvedId(stylePath, { stripLeadingNullByte: true });
24633
+ const cache = ctx.runtimeState?.css?.transformedSidecarSource;
24634
+ const cached = cache?.get(sourceId);
24635
+ if (!cached) return;
24636
+ try {
24637
+ if (await fs$1.readFile(stylePath, "utf8") === cached.diskSource) return cached.code;
24638
+ } catch {}
24639
+ cache?.delete(sourceId);
24640
+ }
24167
24641
  function resolveOutputStyleFileName(configService, stylePath) {
24168
24642
  return configService.relativeOutputPath(changeFileExtension(stylePath, configService.outputExtensions.wxss));
24169
24643
  }
@@ -24267,7 +24741,7 @@ async function emitStyleSidecarAsset(ctx, pluginCtx, bundle, stylePath, resolved
24267
24741
  const { configService } = ctx;
24268
24742
  const fileName = resolveOutputStyleFileName(configService, stylePath);
24269
24743
  if (!fileName) return false;
24270
- const rawCss = await fs$1.readFile(stylePath, "utf8");
24744
+ const rawCss = await resolveMemoryStyleSource(ctx, stylePath) ?? await fs$1.readFile(stylePath, "utf8");
24271
24745
  const { css, dependencies } = await preprocessStyleSource(rawCss, stylePath, resolvedConfig);
24272
24746
  syncCssImportDependencies(ctx, stylePath, rawCss, dependencies);
24273
24747
  if (typeof pluginCtx.addWatchFile === "function") for (const dependency of dependencies) pluginCtx.addWatchFile(normalizeWatchPath(dependency));
@@ -24323,7 +24797,7 @@ async function handleBundleEntry(ctx, bundle, bundleKey, asset, configService, s
24323
24797
  const normalizedFileName = toPosixPath(fileName);
24324
24798
  const freshHmrStyleSourcePath = resolveFreshHmrStyleSourcePath(ctx, normalizedFileName);
24325
24799
  const preprocessId = freshHmrStyleSourcePath ?? absOriginal;
24326
- const preprocessInput = freshHmrStyleSourcePath ? await readStyleGraphSource(freshHmrStyleSourcePath, canonicalSource) : canonicalSource;
24800
+ const preprocessInput = freshHmrStyleSourcePath ? await resolveMemoryStyleSource(ctx, freshHmrStyleSourcePath) ?? await readStyleGraphSource(freshHmrStyleSourcePath, canonicalSource) : canonicalSource;
24327
24801
  const { css, dependencies } = await preprocessStyleSource(preprocessInput, preprocessId, resolvedConfig, { enabled: shouldPreprocessWithVite(preprocessId) });
24328
24802
  syncCssImportDependencies(ctx, preprocessId, freshHmrStyleSourcePath ? preprocessInput : await readStyleGraphSource(absOriginal, canonicalSource), dependencies);
24329
24803
  if (typeof this.addWatchFile === "function") for (const dependency of dependencies) this.addWatchFile(normalizeWatchPath(dependency));
@@ -24470,6 +24944,23 @@ function css(ctx) {
24470
24944
  await generateBundleSharedCss.call(this, ctx, configService, bundle, styleAnalysis, resolvedConfig);
24471
24945
  await emitCollectedStyleSidecars.call(this, ctx, rolldownBundle, resolvedConfig);
24472
24946
  }
24947
+ }, {
24948
+ name: "weapp-vite:css-sidecar-source",
24949
+ async transform(code, id) {
24950
+ const sidecar = parseSidecarSourceRequest(id);
24951
+ if (!sidecar || sidecar.kind !== "style") return null;
24952
+ const sourceId = normalizeFsResolvedId(sidecar.sourceId, { stripLeadingNullByte: true });
24953
+ try {
24954
+ const diskSource = await fs$1.readFile(sourceId, "utf8");
24955
+ ctx.runtimeState?.css?.transformedSidecarSource.set(sourceId, {
24956
+ code,
24957
+ diskSource
24958
+ });
24959
+ } catch {
24960
+ ctx.runtimeState?.css?.transformedSidecarSource.delete(sourceId);
24961
+ }
24962
+ return null;
24963
+ }
24473
24964
  }];
24474
24965
  }
24475
24966
  //#endregion
@@ -24892,12 +25383,6 @@ function setRequireImportLiteral(node, nextValue) {
24892
25383
  function normalizeRelativeChunkImport(fileName, importee) {
24893
25384
  return toPosixPath(path.normalize(path.join(path.dirname(fileName), importee)));
24894
25385
  }
24895
- function prependChunkCodePreservingDirectives(code, injectedCode) {
24896
- const directiveMatch = code.match(DIRECTIVE_PROLOGUE_RE);
24897
- if (!directiveMatch?.[0]) return `${injectedCode}\n${code}`;
24898
- const directivePrologue = directiveMatch[0];
24899
- return `${directivePrologue}${injectedCode}\n${code.slice(directivePrologue.length)}`;
24900
- }
24901
25386
  //#endregion
24902
25387
  //#region src/utils/weapi.ts
24903
25388
  function getWeapiGlobalRootCandidateItems() {
@@ -25141,14 +25626,14 @@ function composeSourceMaps(transformedMap, originalMap) {
25141
25626
  }
25142
25627
  //#endregion
25143
25628
  //#region src/plugins/core/lifecycle/emit/rewrite/sourcemap.ts
25144
- function applyMagicStringChunkRewrite(chunk, magicString) {
25629
+ function applyMagicStringChunkRewrite(chunk, magicString, options) {
25145
25630
  const previousCode = chunk.code;
25146
25631
  const nextCode = magicString.toString();
25147
25632
  if (nextCode === previousCode) return false;
25148
25633
  const previousMap = normalizeEncodedSourceMapLike(chunk.map);
25149
25634
  chunk.code = nextCode;
25150
25635
  if (previousMap) chunk.map = composeSourceMaps(magicString.generateMap({
25151
- hires: "boundary",
25636
+ hires: options?.hires ?? "boundary",
25152
25637
  includeContent: true,
25153
25638
  source: chunk.fileName
25154
25639
  }), previousMap);
@@ -25337,6 +25822,9 @@ const REQUEST_GLOBAL_APP_MODULE_KEY_PREFIX = "__weappViteRequestGlobalsModule:";
25337
25822
  function resolveChunkRequestGlobalsTargets(code, targets, mode) {
25338
25823
  return mode === "auto" ? resolveAutoRequestGlobalsTargets(code, targets) : targets;
25339
25824
  }
25825
+ function resolvePreludeRequestGlobalsTargets(code, targets, mode) {
25826
+ return mode === "auto" ? targets : resolveChunkRequestGlobalsTargets(code, targets, mode);
25827
+ }
25340
25828
  function collectTopLevelDeclaredIdentifiers(code) {
25341
25829
  const identifiers = /* @__PURE__ */ new Set();
25342
25830
  try {
@@ -25760,7 +26248,7 @@ function inlineRequestGlobalsAppRegisteredInstallerChunks(bundle, installerChunk
25760
26248
  appChunk.code = `${inlinedModules.join("\n")}\n${appChunk.code}`;
25761
26249
  }
25762
26250
  function createRequestGlobalsPreludeCode(chunk, installerChunks, targets, mode, networkDefaults) {
25763
- const chunkTargets = resolveChunkRequestGlobalsTargets(chunk.code, targets, mode);
26251
+ const chunkTargets = resolvePreludeRequestGlobalsTargets(chunk.code, targets, mode);
25764
26252
  if (chunkTargets.length === 0 || chunk.code.includes(REQUEST_GLOBAL_PRELUDE_MARKER)) return;
25765
26253
  const bindingTargets = resolveRequestGlobalsBindingTargets(chunkTargets);
25766
26254
  if (bindingTargets.length === 0) return;
@@ -25788,13 +26276,22 @@ function createRequestGlobalsPreludeCode(chunk, installerChunks, targets, mode,
25788
26276
  ].join("\n");
25789
26277
  }
25790
26278
  function createRequestGlobalsPreludeAssetCode(preludeFileName, chunk, installerChunks, targets, mode, networkDefaults) {
25791
- const chunkTargets = resolveChunkRequestGlobalsTargets(chunk.code, targets, mode);
26279
+ const chunkTargets = resolvePreludeRequestGlobalsTargets(chunk.code, targets, mode);
25792
26280
  if (chunkTargets.length === 0) return;
25793
26281
  const bindingTargets = resolveRequestGlobalsBindingTargets(chunkTargets);
25794
26282
  if (bindingTargets.length === 0) return;
25795
26283
  const installerImport = resolveRequestGlobalsInstallerImport(chunk, installerChunks);
25796
- if (!installerImport?.installerChunkFileName || !installerImport.exportName) return;
25797
- const installerHostCode = `${toRequestGlobalsInstallerModuleExpression(preludeFileName, installerImport.installerChunkFileName, { appRegisteredModule: false })}[${JSON.stringify(installerImport.exportName)}](${createRequestGlobalsInstallerOptionsCode(chunkTargets, networkDefaults)}) || globalThis`;
26284
+ let installerChunkFileName = installerImport?.installerChunkFileName;
26285
+ let exportName = installerImport?.exportName;
26286
+ if (!installerChunkFileName || !exportName) {
26287
+ const ownExportName = installerChunks.get(toPosixPath(chunk.fileName));
26288
+ if (ownExportName) {
26289
+ installerChunkFileName = chunk.fileName;
26290
+ exportName = ownExportName;
26291
+ }
26292
+ }
26293
+ if (!installerChunkFileName || !exportName) return;
26294
+ const installerHostCode = `${toRequestGlobalsInstallerModuleExpression(preludeFileName, installerChunkFileName, { appRegisteredModule: false })}[${JSON.stringify(exportName)}](${createRequestGlobalsInstallerOptionsCode(chunkTargets, networkDefaults)}) || globalThis`;
25798
26295
  return [
25799
26296
  `/* ${REQUEST_GLOBAL_PRELUDE_MARKER} */`,
25800
26297
  `(() => {`,
@@ -25917,9 +26414,20 @@ function createAppPreludeRequireStatement(chunkFileName, preludeFileName) {
25917
26414
  const requestPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
25918
26415
  return `/* ${APP_PRELUDE_REQUIRE_MARKER} */require(${JSON.stringify(requestPath)})`;
25919
26416
  }
26417
+ function prependChunkCodeWithSourcemap(chunk, injectedCode) {
26418
+ const directiveMatch = chunk.code.match(DIRECTIVE_PROLOGUE_RE);
26419
+ const insertIndex = directiveMatch?.[0] ? directiveMatch[0].length : 0;
26420
+ const magicString = new MagicString(chunk.code);
26421
+ magicString.prependLeft(insertIndex, `${injectedCode}\n`);
26422
+ applyMagicStringChunkRewrite(chunk, magicString, { hires: true });
26423
+ }
26424
+ function hasRequestGlobalsPreludeDependency(chunk, requestGlobalsPreludeOptions) {
26425
+ if (!requestGlobalsPreludeOptions.enabled) return false;
26426
+ return requestGlobalsPreludeOptions.installerChunks.has(toPosixPath(chunk.fileName)) || Boolean(resolveRequestGlobalsInstallerImport(chunk, requestGlobalsPreludeOptions.installerChunks)) || chunk.code.includes(REQUEST_GLOBAL_BUNDLE_MARKER$1) || chunk.code.includes(REQUEST_GLOBAL_LOCAL_BINDINGS_MARKER$1) || chunk.code.includes(REQUEST_GLOBAL_PASSIVE_BINDINGS_MARKER$1);
26427
+ }
25920
26428
  function emitAppPreludeRequireAssets(bundle, appPreludeCode, state, requestGlobalsPreludeOptions, emitFile) {
25921
26429
  const preservedRequestGlobalsInstallerChunks = /* @__PURE__ */ new Set();
25922
- if (!appPreludeCode) return preservedRequestGlobalsInstallerChunks;
26430
+ if (!appPreludeCode && !requestGlobalsPreludeOptions.enabled) return preservedRequestGlobalsInstallerChunks;
25923
26431
  const preludeFileNames = /* @__PURE__ */ new Set();
25924
26432
  if (state.subPackageMeta?.subPackage.root) preludeFileNames.add(`${state.subPackageMeta.subPackage.root}/${APP_PRELUDE_REQUIRE_FILE_BASENAME}`);
25925
26433
  else {
@@ -25931,7 +26439,8 @@ function emitAppPreludeRequireAssets(bundle, appPreludeCode, state, requestGloba
25931
26439
  const scopeChunks = Object.values(bundle).filter((output) => {
25932
26440
  return output?.type === "chunk" && resolveAppPreludeRequireFileName(output.fileName, state) === fileName;
25933
26441
  });
25934
- const requestGlobalsPreludeCode = requestGlobalsPreludeOptions.enabled ? scopeChunks.map((chunk) => createRequestGlobalsPreludeAssetCode(fileName, chunk, requestGlobalsPreludeOptions.installerChunks, requestGlobalsPreludeOptions.targets, requestGlobalsPreludeOptions.mode, requestGlobalsPreludeOptions.networkDefaults)).find(Boolean) : void 0;
26442
+ const sortedScopeChunks = [...scopeChunks.filter((chunk) => !requestGlobalsPreludeOptions.installerChunks.has(toPosixPath(chunk.fileName))), ...scopeChunks.filter((chunk) => requestGlobalsPreludeOptions.installerChunks.has(toPosixPath(chunk.fileName)))];
26443
+ const requestGlobalsPreludeCode = requestGlobalsPreludeOptions.enabled ? sortedScopeChunks.map((chunk) => createRequestGlobalsPreludeAssetCode(fileName, chunk, requestGlobalsPreludeOptions.installerChunks, requestGlobalsPreludeOptions.targets, requestGlobalsPreludeOptions.mode, requestGlobalsPreludeOptions.networkDefaults)).find(Boolean) : void 0;
25935
26444
  if (requestGlobalsPreludeCode) {
25936
26445
  const installerImport = scopeChunks.map((chunk) => resolveRequestGlobalsInstallerImport(chunk, requestGlobalsPreludeOptions.installerChunks)).find(Boolean);
25937
26446
  if (installerImport?.installerChunkFileName) preservedRequestGlobalsInstallerChunks.add(installerImport.installerChunkFileName);
@@ -25949,16 +26458,18 @@ function injectAppPreludeCode(bundle, appPreludeCode, options, state, requestGlo
25949
26458
  let preservedRequestGlobalsInstallerChunks = /* @__PURE__ */ new Set();
25950
26459
  if (!options.enabled) return preservedRequestGlobalsInstallerChunks;
25951
26460
  const entryChunkFileNames = options.mode === "entry" ? collectAppPreludeEntryChunkFileNames(state) : void 0;
25952
- if (options.mode === "require" && appPreludeCode) preservedRequestGlobalsInstallerChunks = emitAppPreludeRequireAssets(bundle, appPreludeCode, state, requestGlobalsPreludeOptions, emitFile);
26461
+ if (options.mode === "require" && (appPreludeCode || requestGlobalsPreludeOptions.enabled)) preservedRequestGlobalsInstallerChunks = emitAppPreludeRequireAssets(bundle, appPreludeCode, state, requestGlobalsPreludeOptions, emitFile);
25953
26462
  for (const output of Object.values(bundle)) {
25954
26463
  if (output?.type !== "chunk") continue;
25955
26464
  const chunk = output;
25956
26465
  if (chunk.code.includes(APP_PRELUDE_CHUNK_MARKER) || chunk.code.includes(APP_PRELUDE_REQUIRE_MARKER)) continue;
25957
26466
  const isTargetEntryChunk = chunk.isEntry === true || entryChunkFileNames?.has(chunk.fileName) === true;
25958
26467
  if (entryChunkFileNames && !isTargetEntryChunk) continue;
25959
- const injectedCode = [requestGlobalsPreludeOptions.enabled && options.mode !== "require" ? createRequestGlobalsPreludeCode(chunk, requestGlobalsPreludeOptions.installerChunks, requestGlobalsPreludeOptions.targets, requestGlobalsPreludeOptions.mode, requestGlobalsPreludeOptions.networkDefaults) : void 0, options.mode === "require" ? appPreludeCode ? createAppPreludeRequireStatement(chunk.fileName, resolveAppPreludeRequireFileName(chunk.fileName, state)) : void 0 : appPreludeCode].filter(Boolean).join("\n");
26468
+ const requestGlobalsPreludeCode = requestGlobalsPreludeOptions.enabled && options.mode !== "require" ? createRequestGlobalsPreludeCode(chunk, requestGlobalsPreludeOptions.installerChunks, requestGlobalsPreludeOptions.targets, requestGlobalsPreludeOptions.mode, requestGlobalsPreludeOptions.networkDefaults) : void 0;
26469
+ const shouldInjectRequirePrelude = appPreludeCode || hasRequestGlobalsPreludeDependency(chunk, requestGlobalsPreludeOptions);
26470
+ const injectedCode = [requestGlobalsPreludeCode, options.mode === "require" ? shouldInjectRequirePrelude ? createAppPreludeRequireStatement(chunk.fileName, resolveAppPreludeRequireFileName(chunk.fileName, state)) : void 0 : appPreludeCode].filter(Boolean).join("\n");
25960
26471
  if (!injectedCode) continue;
25961
- chunk.code = prependChunkCodePreservingDirectives(chunk.code, injectedCode);
26472
+ prependChunkCodeWithSourcemap(chunk, injectedCode);
25962
26473
  }
25963
26474
  return preservedRequestGlobalsInstallerChunks;
25964
26475
  }
@@ -26372,7 +26883,7 @@ function createGenerateBundleHook(state, isPluginBuild) {
26372
26883
  collapseRequestGlobalsRuntimeSupportChunk(rolldownBundle);
26373
26884
  }
26374
26885
  const appPreludePath = scanService.appEntry?.preludePath;
26375
- const shouldInjectRequestGlobalsPrelude = injectRequestGlobalsOptions?.prelude === true;
26886
+ const shouldInjectRequestGlobalsPrelude = injectRequestGlobalsOptions?.prelude === true && Boolean(scanService.appEntry || subPackageMeta);
26376
26887
  const appPreludeOptions = resolveAppPreludeOptions(state);
26377
26888
  const preservedRequestGlobalsInstallerChunks = appPreludeOptions.enabled && Boolean(appPreludePath) || shouldInjectRequestGlobalsPrelude ? injectAppPreludeCode(rolldownBundle, await resolveAppPreludeCode(appPreludePath, {
26378
26889
  importMetaDefineRegistry: configService.importMetaDefineRegistry,
@@ -27718,6 +28229,7 @@ function createWatchChangeHook(state) {
27718
28229
  watchToDirtyMs: performance.now() - startedAt,
27719
28230
  dirtyReasonSummary
27720
28231
  };
28232
+ state.ctx.onStatefulHmrSourceChange?.(normalizedId, dirtyReasonSummary ?? []);
27721
28233
  };
27722
28234
  }
27723
28235
  //#endregion
@@ -31170,15 +31682,17 @@ function hasTsconfigReference(tsconfig, target) {
31170
31682
  return false;
31171
31683
  }
31172
31684
  }
31173
- function resolveDefaultRolldownTsconfig(cwd) {
31174
- const appTsconfig = path.resolve(cwd, ".weapp-vite/tsconfig.app.json");
31175
- const rootTsconfig = path.resolve(cwd, "tsconfig.json");
31685
+ function resolveDefaultRolldownTsconfig(cwd, configFilePath) {
31686
+ const configRoot = configFilePath ? path.dirname(configFilePath) : void 0;
31687
+ const projectRoot = configRoot && existsSync(path.resolve(configRoot, ".weapp-vite/tsconfig.app.json")) ? configRoot : cwd;
31688
+ const appTsconfig = path.resolve(projectRoot, ".weapp-vite/tsconfig.app.json");
31689
+ const rootTsconfig = path.resolve(projectRoot, "tsconfig.json");
31176
31690
  if (existsSync(appTsconfig)) return appTsconfig;
31177
31691
  if (hasTsconfigReference(rootTsconfig, appTsconfig)) return appTsconfig;
31178
31692
  if (existsSync(rootTsconfig)) return rootTsconfig;
31179
31693
  }
31180
31694
  function normalizeInlineConfigAfterDefu(inline, options) {
31181
- const { cwd, ctx, platform, rolldownOptions, subPackageMeta } = options;
31695
+ const { cwd, configFilePath, ctx, platform, rolldownOptions, subPackageMeta } = options;
31182
31696
  const build = inline.build ?? (inline.build = {});
31183
31697
  const userRolldownOptions = build.rolldownOptions;
31184
31698
  const mergedRolldownOptions = {
@@ -31189,8 +31703,11 @@ function normalizeInlineConfigAfterDefu(inline, options) {
31189
31703
  ...userRolldownOptions?.output ?? {}
31190
31704
  }
31191
31705
  };
31192
- const defaultTsconfig = resolveDefaultRolldownTsconfig(cwd);
31193
- if (!Object.prototype.hasOwnProperty.call(mergedRolldownOptions, "tsconfig") && !mergedRolldownOptions.resolve?.tsconfigFilename && defaultTsconfig) mergedRolldownOptions.tsconfig = defaultTsconfig;
31706
+ const defaultTsconfig = resolveDefaultRolldownTsconfig(cwd, configFilePath);
31707
+ const resolveOptions = mergedRolldownOptions.resolve;
31708
+ if (defaultTsconfig) {
31709
+ if (!Object.prototype.hasOwnProperty.call(mergedRolldownOptions, "tsconfig")) mergedRolldownOptions.tsconfig = configFilePath && !resolveOptions?.tsconfigFilename ? false : defaultTsconfig;
31710
+ } else if (!Object.prototype.hasOwnProperty.call(mergedRolldownOptions, "tsconfig") && !resolveOptions?.tsconfigFilename) mergedRolldownOptions.tsconfig = false;
31194
31711
  build.rolldownOptions = mergedRolldownOptions;
31195
31712
  inline.define = {
31196
31713
  ...inline.define ?? {},
@@ -31220,7 +31737,7 @@ function resolveMiniprogramWatchInclude(options) {
31220
31737
  });
31221
31738
  }
31222
31739
  function mergeMiniprogram(options, ...configs) {
31223
- const { ctx, subPackageMeta, config, cwd, srcRoot, mpDistRoot, configFileDependencies = [], packageJson, isDev, applyRuntimePlatform, injectBuiltinAliases, getDefineImportMetaEnv, setOptions, oxcRolldownPlugin } = options;
31740
+ const { ctx, subPackageMeta, config, cwd, srcRoot, mpDistRoot, configFileDependencies = [], configFilePath, packageJson, isDev, applyRuntimePlatform, injectBuiltinAliases, getDefineImportMetaEnv, setOptions, oxcRolldownPlugin } = options;
31224
31741
  const platform = ctx.configService?.platform;
31225
31742
  applyRuntimePlatform("miniprogram");
31226
31743
  const createMiniprogramCustomLogger = () => {
@@ -31289,6 +31806,7 @@ function mergeMiniprogram(options, ...configs) {
31289
31806
  });
31290
31807
  normalizeInlineConfigAfterDefu(inline, {
31291
31808
  cwd,
31809
+ configFilePath,
31292
31810
  ctx,
31293
31811
  platform,
31294
31812
  rolldownOptions,
@@ -31311,6 +31829,7 @@ function mergeMiniprogram(options, ...configs) {
31311
31829
  if (inlineConfig.build) delete inlineConfig.build.watch;
31312
31830
  normalizeInlineConfigAfterDefu(inlineConfig, {
31313
31831
  cwd,
31832
+ configFilePath,
31314
31833
  ctx,
31315
31834
  platform,
31316
31835
  rolldownOptions,
@@ -31466,6 +31985,7 @@ function createMergeFactories(options) {
31466
31985
  srcRoot: currentOptions.srcRoot,
31467
31986
  mpDistRoot: currentOptions.mpDistRoot,
31468
31987
  configFileDependencies: currentOptions.configFileDependencies,
31988
+ configFilePath: currentOptions.configFilePath,
31469
31989
  packageJson: currentOptions.packageJson,
31470
31990
  isDev: currentOptions.isDev,
31471
31991
  applyRuntimePlatform,
@@ -31675,6 +32195,7 @@ function createConfigService(ctx) {
31675
32195
  isDev: false,
31676
32196
  emitDefaultAutoImportOutputs: true,
31677
32197
  projectConfig: {},
32198
+ projectPrivateConfig: {},
31678
32199
  config: {},
31679
32200
  loadOptions: input,
31680
32201
  packageJson: {},
@@ -31786,6 +32307,9 @@ function createConfigService(ctx) {
31786
32307
  get projectConfig() {
31787
32308
  return options.projectConfig;
31788
32309
  },
32310
+ get projectPrivateConfig() {
32311
+ return options.projectPrivateConfig;
32312
+ },
31789
32313
  get projectConfigPath() {
31790
32314
  return options.projectConfigPath;
31791
32315
  },
@@ -32095,7 +32619,7 @@ async function loadAppEntry(ctx, scanState) {
32095
32619
  const { path: appEntryPath } = appEntry;
32096
32620
  let configFromVue;
32097
32621
  if (!appConfigFile && vueAppPath) {
32098
- const { extractConfigFromVue } = await import("./file-TBExd8Jd.mjs");
32622
+ const { extractConfigFromVue } = await import("./file-DHCIIIYD.mjs");
32099
32623
  configFromVue = await extractConfigFromVue(vueAppPath);
32100
32624
  if (configFromVue) appConfigFile = vueAppPath;
32101
32625
  }