weapp-vite 6.19.1 → 6.19.2

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-CFQYYS_3.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}(weapp.hmr.runtime 显式配置)`, `切换模式:将 weapp.hmr.runtime 改为 auto 或 ${alternative},并重启 wv dev。`];
7876
+ }
7877
+ if (options.platform !== "weapp") return ["HMR 模式:classic(auto:stateful-experimental 仅支持微信小程序)", "切换模式:可通过 weapp.hmr.runtime 显式锁定 classic;stateful-experimental 仅支持微信小程序。"];
7878
+ if (options.compileHotReLoad === true) return ["HMR 模式:stateful-experimental(auto:微信开发者工具热重载已开启)", "切换模式:在微信开发者工具中关闭“热重载”并重启 wv dev,可切换为 classic;也可通过 weapp.hmr.runtime 显式锁定模式。"];
7879
+ return ["HMR 模式:classic(auto:微信开发者工具热重载未开启或无法确认)", "切换模式:在微信开发者工具中开启“热重载”并重启 wv dev,可切换为 stateful-experimental;也可通过 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,148 @@ 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
11041
11208
  //#region src/runtime/statefulHmr/serverState.ts
11042
11209
  function createStatefulHmrServerState(buildId) {
11043
11210
  return {
@@ -11055,6 +11222,7 @@ function transitionStatefulHmrServer(state, event) {
11055
11222
  return unchanged({
11056
11223
  ...state,
11057
11224
  deltas: [...state.deltas, {
11225
+ changedIds: event.changedIds,
11058
11226
  code: event.code,
11059
11227
  version
11060
11228
  }],
@@ -11199,10 +11367,11 @@ var StatefulHmrTransport = class {
11199
11367
  this.closed = true;
11200
11368
  this.respondToAll({ type: "rebuilding" });
11201
11369
  }
11202
- addDelta(code) {
11370
+ addDelta(code, changedIds) {
11203
11371
  this.apply({
11204
11372
  type: "delta-added",
11205
11373
  bytes: Buffer.byteLength(code),
11374
+ changedIds,
11206
11375
  code
11207
11376
  });
11208
11377
  this.respondToAll({ type: "changed" });
@@ -11321,8 +11490,10 @@ var StatefulHmrTransport = class {
11321
11490
  }
11322
11491
  };
11323
11492
  function renderBatch(batch, nonce) {
11493
+ const changedIds = [...new Set(batch.deltas.flatMap((delta) => delta.changedIds))];
11324
11494
  const metadata = {
11325
11495
  buildId: batch.buildId,
11496
+ changedIds,
11326
11497
  compatible: true,
11327
11498
  fromVersion: batch.fromVersion,
11328
11499
  targetVersion: batch.targetVersion
@@ -11367,6 +11538,7 @@ var StatefulHmrViteAdapter = class {
11367
11538
  server;
11368
11539
  callbacks;
11369
11540
  bundledDev;
11541
+ initialOutputError;
11370
11542
  constructor(config, server, callbacks) {
11371
11543
  this.config = config;
11372
11544
  this.server = server;
@@ -11382,32 +11554,45 @@ var StatefulHmrViteAdapter = class {
11382
11554
  this.installPatches(bundledDev);
11383
11555
  this.installListener(bundledDev);
11384
11556
  }
11385
- async rebuild() {
11557
+ async rebuild(prepare) {
11386
11558
  const engine = this.bundledDev?._devEngine;
11387
- if (!engine) return;
11559
+ if (!engine) throw new Error("Vite DevEngine 未初始化,无法执行 stateful HMR 完整刷新。");
11560
+ await prepare?.();
11388
11561
  engine.triggerFullBuild();
11389
11562
  await engine.ensureLatestBuildOutput();
11390
11563
  }
11391
- registerBundleModules(output) {
11564
+ async registerBundleModules(output) {
11392
11565
  const moduleIds = /* @__PURE__ */ new Set();
11566
+ const payloadFilenames = [];
11393
11567
  for (const item of output) {
11394
11568
  if (item.type !== "chunk") continue;
11569
+ payloadFilenames.push(item.fileName);
11395
11570
  for (const match of item.code.matchAll(/registerModule\("([^"]+)"/g)) moduleIds.add(match[1]);
11396
11571
  for (const id of Object.keys(item.modules ?? {})) {
11397
11572
  const normalized = toStableModuleId(id, this.config.root);
11398
11573
  if (!moduleIds.has(normalized)) moduleIds.add(normalized);
11399
11574
  }
11400
11575
  }
11401
- this.registerModules([...moduleIds]);
11576
+ await this.registerModules([...moduleIds]);
11577
+ await this.markPayloadsDelivered(payloadFilenames);
11402
11578
  return moduleIds.size;
11403
11579
  }
11404
- registerPatchModules(code) {
11580
+ async registerPatchModules(code) {
11405
11581
  const moduleIds = /* @__PURE__ */ new Set();
11406
11582
  for (const match of code.matchAll(/create(?:Esm|Cjs)Initializer\("([^"]+)"/g)) moduleIds.add(match[1]);
11407
- this.registerModules([...moduleIds]);
11583
+ await this.registerModules([...moduleIds]);
11408
11584
  }
11409
- registerModules(moduleIds) {
11410
- if (moduleIds.length) this.bundledDev?._devEngine?.registerModules(clientId, moduleIds);
11585
+ async markPayloadDelivered(filename) {
11586
+ await this.markPayloadsDelivered([filename]);
11587
+ }
11588
+ async registerModules(moduleIds) {
11589
+ const engine = this.bundledDev?._devEngine;
11590
+ if (moduleIds.length && typeof engine?.registerModules === "function") await engine.registerModules(clientId, moduleIds);
11591
+ }
11592
+ async markPayloadsDelivered(filenames) {
11593
+ const engine = this.bundledDev?._devEngine;
11594
+ if (typeof engine?.notifyPayloadDelivered !== "function") return;
11595
+ for (const filename of filenames) await engine.notifyPayloadDelivered(filename);
11411
11596
  }
11412
11597
  installOptions(bundledDev) {
11413
11598
  const original = bundledDev.getRolldownOptions.bind(bundledDev);
@@ -11434,8 +11619,9 @@ var StatefulHmrViteAdapter = class {
11434
11619
  options.experimental ??= {};
11435
11620
  options.experimental.devMode = {
11436
11621
  ...typeof options.experimental.devMode === "object" ? options.experimental.devMode : {},
11437
- implement: statefulHmrRolldownRuntimeSource,
11438
- lazy: false
11622
+ implement: createStatefulHmrRolldownRuntimeSource(),
11623
+ lazy: false,
11624
+ skipCommonRuntimeInjection: true
11439
11625
  };
11440
11626
  return options;
11441
11627
  };
@@ -11443,14 +11629,23 @@ var StatefulHmrViteAdapter = class {
11443
11629
  installOutput(bundledDev) {
11444
11630
  const original = bundledDev.storeOutputFiles.bind(bundledDev);
11445
11631
  bundledDev.storeOutputFiles = (output) => {
11446
- original(output);
11447
- this.callbacks.onOutput(output);
11632
+ try {
11633
+ if (output.some((item) => item.fileName === "app.js")) assertStatefulHmrRuntimeOutput(output);
11634
+ original(output);
11635
+ this.callbacks.onOutput(output);
11636
+ } catch (error) {
11637
+ this.initialOutputError = error instanceof Error ? error : new Error(String(error));
11638
+ throw error;
11639
+ }
11448
11640
  };
11449
11641
  }
11450
11642
  installPatches(bundledDev) {
11451
11643
  const original = bundledDev.handleHmrOutput.bind(bundledDev);
11452
11644
  bundledDev.handleHmrOutput = (client, files, output, info) => {
11453
- if (output.type === "Noop") return;
11645
+ if (output.type === "Noop") {
11646
+ this.callbacks.onPatch(files, output);
11647
+ return;
11648
+ }
11454
11649
  if (this.callbacks.onPatch(files, output)) original(client, files, output, info);
11455
11650
  };
11456
11651
  }
@@ -11461,7 +11656,9 @@ var StatefulHmrViteAdapter = class {
11461
11656
  bundledDev.clients.setupIfNeeded({ send: (payload) => this.handlePayload(payload) }, clientId);
11462
11657
  const engine = bundledDev._devEngine;
11463
11658
  if (!engine) throw new Error("Vite 未初始化微信状态保持 HMR 所需的 DevEngine。");
11659
+ await engine.registerClient?.(clientId);
11464
11660
  await engine.ensureCurrentBuildFinish();
11661
+ if (this.initialOutputError) throw this.initialOutputError;
11465
11662
  if ((await engine.getBundleState()).lastBuildErrored) throw new Error("微信状态保持 HMR 初次构建失败。");
11466
11663
  await this.callbacks.waitForInitialBundle();
11467
11664
  };
@@ -11501,7 +11698,7 @@ function toStableModuleId(id, root) {
11501
11698
  //#region src/runtime/statefulHmr/session.ts
11502
11699
  const maxRetainedDeltaCount = 1e3;
11503
11700
  const maxRetainedDeltaBytes = 16777216;
11504
- async function runStatefulHmrDev(ctx, buildOptions, restart) {
11701
+ async function runStatefulHmrDev(ctx, buildOptions, restart, snapshots) {
11505
11702
  const configService = ctx.configService;
11506
11703
  if (configService.platform !== "weapp") throw new Error("weapp.hmr.runtime=\"stateful-experimental\" 目前仅支持微信小程序平台。");
11507
11704
  let session;
@@ -11509,12 +11706,12 @@ async function runStatefulHmrDev(ctx, buildOptions, restart) {
11509
11706
  name: "weapp-vite:stateful-hmr-session",
11510
11707
  enforce: "post",
11511
11708
  configureServer(server) {
11512
- const currentSession = new StatefulHmrSession(ctx, server, restart);
11709
+ const currentSession = new StatefulHmrSession(ctx, server, restart, snapshots);
11513
11710
  session = currentSession;
11514
11711
  currentSession.install();
11515
11712
  },
11516
11713
  transform(code, id) {
11517
- if (!isStatefulHmrBoundary(id, configService.absoluteSrcRoot) || code.includes("import.meta.hot.accept")) return;
11714
+ if (!isStatefulHmrBoundary(id, configService.absoluteSrcRoot, ctx.runtimeState.build.hmr.resolvedEntryMap.keys()) || code.includes("import.meta.hot.accept")) return;
11518
11715
  return `${id.endsWith(".vue") ? code : redirectNativeComponentRegistration(code)}\nif (import.meta.hot) import.meta.hot.accept();\n`;
11519
11716
  }
11520
11717
  };
@@ -11531,7 +11728,11 @@ async function runStatefulHmrDev(ctx, buildOptions, restart) {
11531
11728
  ...buildOptions.experimental ?? {},
11532
11729
  bundledDev: true
11533
11730
  },
11534
- plugins: [installPlugin, ...buildOptions.plugins ?? []],
11731
+ plugins: [
11732
+ createStatefulHmrSidecarPlugin(),
11733
+ installPlugin,
11734
+ ...buildOptions.plugins ?? []
11735
+ ],
11535
11736
  server: {
11536
11737
  ...buildOptions.server ?? {},
11537
11738
  host: "127.0.0.1",
@@ -11543,28 +11744,40 @@ async function runStatefulHmrDev(ctx, buildOptions, restart) {
11543
11744
  write: false
11544
11745
  }
11545
11746
  });
11546
- await server.listen();
11547
- if (!session) {
11548
- await server.close();
11549
- throw new Error("微信状态保持 HMR session 未完成初始化。");
11747
+ try {
11748
+ await server.listen();
11749
+ if (!session) throw new Error("微信状态保持 HMR session 未完成初始化。");
11750
+ await session.refreshControl();
11751
+ return createWatcherAdapter(server, session);
11752
+ } catch (error) {
11753
+ await session?.close().catch(() => {});
11754
+ await server.close().catch(() => {});
11755
+ throw error;
11550
11756
  }
11551
- await session.refreshControl();
11552
- return createWatcherAdapter(server, session);
11553
11757
  }
11554
11758
  var StatefulHmrSession = class {
11555
11759
  ctx;
11556
11760
  server;
11557
11761
  restart;
11762
+ snapshots;
11558
11763
  adapter;
11559
11764
  initialBundle = Promise.withResolvers();
11560
11765
  transport;
11766
+ fullBuildTimer;
11561
11767
  outputChain = Promise.resolve();
11562
- rebuildTimer;
11563
11768
  restartTimer;
11564
- constructor(ctx, server, restart) {
11769
+ snapshotTimer;
11770
+ snapshotFiles = /* @__PURE__ */ new Set();
11771
+ snapshotAssets = /* @__PURE__ */ new Map();
11772
+ sourceChangeListener = (file, dirtyReasonSummary) => {
11773
+ this.handleSourceUpdate(file, dirtyReasonSummary);
11774
+ };
11775
+ constructor(ctx, server, restart, snapshots) {
11565
11776
  this.ctx = ctx;
11566
11777
  this.server = server;
11567
11778
  this.restart = restart;
11779
+ this.snapshots = snapshots;
11780
+ this.replaceSnapshotAssets(snapshots.initial);
11568
11781
  this.transport = new StatefulHmrTransport(server, async (buildId, source) => {
11569
11782
  await this.enqueueOutput(async () => {
11570
11783
  if (!this.transport.isCurrentBuild(buildId)) return;
@@ -11585,10 +11798,13 @@ var StatefulHmrSession = class {
11585
11798
  install() {
11586
11799
  this.transport.install();
11587
11800
  this.adapter.install();
11801
+ this.ctx.onStatefulHmrSourceChange = this.sourceChangeListener;
11588
11802
  }
11589
11803
  async close() {
11590
- if (this.rebuildTimer) clearTimeout(this.rebuildTimer);
11804
+ if (this.fullBuildTimer) clearTimeout(this.fullBuildTimer);
11805
+ if (this.snapshotTimer) clearTimeout(this.snapshotTimer);
11591
11806
  if (this.restartTimer) clearTimeout(this.restartTimer);
11807
+ if (this.ctx.onStatefulHmrSourceChange === this.sourceChangeListener) this.ctx.onStatefulHmrSourceChange = void 0;
11592
11808
  this.transport.close();
11593
11809
  await this.outputChain;
11594
11810
  }
@@ -11601,13 +11817,28 @@ var StatefulHmrSession = class {
11601
11817
  }]);
11602
11818
  });
11603
11819
  }
11820
+ handleSourceUpdate(file, dirtyReasonSummary = []) {
11821
+ const normalizedFile = normalizeFsResolvedId(path.isAbsolute(file) ? file : path.resolve(this.server.config.root, file));
11822
+ const normalizedOutDir = normalizeFsResolvedId(this.ctx.configService.outDir).replace(/\/$/, "");
11823
+ if (normalizedFile === normalizedOutDir || normalizedFile.startsWith(`${normalizedOutDir}/`)) return;
11824
+ if (shouldRestartStatefulHmrServer([normalizedFile], this.ctx.configService?.configFileDependencies)) {
11825
+ this.requestServerRestart();
11826
+ return;
11827
+ }
11828
+ if (requiresStatefulHmrSnapshot(normalizedFile, dirtyReasonSummary)) {
11829
+ if (!this.snapshotTimer && !this.fullBuildTimer) logger_default.info("微信状态保持 HMR 正在刷新模板、样式与静态资源产物...");
11830
+ this.requestSnapshotRefresh([normalizedFile]);
11831
+ }
11832
+ }
11604
11833
  handleOutput(output) {
11605
11834
  this.enqueueOutput(async () => {
11606
11835
  const compatibleOutput = await transformOutput(output);
11607
11836
  const fullBuild = compatibleOutput.some((item) => item.fileName === "app.js");
11608
11837
  if (fullBuild) {
11838
+ mergeStatefulHmrSnapshotAssets(compatibleOutput, this.snapshotAssets.values());
11609
11839
  const buildId = this.transport.createBuildId();
11610
11840
  this.transport.commitFullBuild(buildId);
11841
+ stampStatefulHmrFullBuild(compatibleOutput, buildId);
11611
11842
  setAsset(compatibleOutput, WEAPP_VITE_STATEFUL_HMR_CONTROL_FILE, createStatefulHmrControlSource({
11612
11843
  ...this.transport.createControl(),
11613
11844
  buildId
@@ -11617,39 +11848,59 @@ var StatefulHmrSession = class {
11617
11848
  }
11618
11849
  await writeStatefulHmrOutput(this.ctx.configService.outDir, compatibleOutput);
11619
11850
  if (fullBuild) {
11620
- const moduleCount = this.adapter.registerBundleModules(compatibleOutput);
11851
+ const moduleCount = await this.adapter.registerBundleModules(compatibleOutput);
11621
11852
  this.server.config.logger.info(`[weapp-vite] 微信状态保持 HMR 已就绪(${moduleCount} modules)`);
11622
11853
  this.initialBundle.resolve();
11623
11854
  }
11624
11855
  });
11625
11856
  }
11626
11857
  handlePatch(files, output) {
11627
- if (!isSafeJavaScriptPatch(files, output, this.ctx.runtimeState.build.hmr.profile.dirtyReasonSummary)) {
11628
- this.requestServerRestart();
11858
+ if (output.type === "Noop") return false;
11859
+ if (!isSafeJavaScriptPatch(files, output, this.ctx.runtimeState.build.hmr.profile.dirtyReasonSummary, this.ctx.runtimeState.build.hmr.resolvedEntryMap.keys(), this.server.config.root)) {
11860
+ if (shouldRestartStatefulHmrServer(files, this.ctx.configService?.configFileDependencies)) this.requestServerRestart();
11861
+ else this.requestFullBuild(files);
11629
11862
  return false;
11630
11863
  }
11631
- this.adapter.registerPatchModules(output.code);
11632
- transformJavaScript(output.code, output.filename).then((code) => {
11864
+ this.adapter.registerPatchModules(output.code).then(async () => {
11865
+ const code = await transformJavaScript(output.code, output.filename);
11633
11866
  if (shouldResetStatefulHmrRetention(this.transport.retainedDeltaCount, this.transport.retainedDeltaBytes, Buffer.byteLength(code))) {
11634
11867
  this.requestFullBuild();
11635
11868
  return;
11636
11869
  }
11637
- this.transport.addDelta(code);
11870
+ this.transport.addDelta(code, output.changedIds ?? []);
11871
+ return this.adapter.markPayloadDelivered(output.filename);
11638
11872
  }).catch((error) => {
11639
11873
  this.server.config.logger.error("[weapp-vite] stateful HMR patch transform failed", { error });
11640
11874
  this.requestFullBuild();
11641
11875
  });
11642
11876
  return true;
11643
11877
  }
11644
- requestFullBuild() {
11645
- if (this.rebuildTimer) return;
11646
- this.rebuildTimer = setTimeout(() => {
11647
- this.rebuildTimer = void 0;
11648
- this.adapter.rebuild().catch((error) => {
11878
+ requestFullBuild(files = []) {
11879
+ for (const file of files) this.snapshotFiles.add(file);
11880
+ if (this.snapshotTimer) {
11881
+ clearTimeout(this.snapshotTimer);
11882
+ this.snapshotTimer = void 0;
11883
+ }
11884
+ if (this.fullBuildTimer) return;
11885
+ this.fullBuildTimer = setTimeout(() => {
11886
+ this.fullBuildTimer = void 0;
11887
+ const snapshotFiles = this.takeSnapshotFiles();
11888
+ this.rebuildFromSnapshot(snapshotFiles).catch((error) => {
11649
11889
  this.server.config.logger.error("[weapp-vite] stateful HMR full rebuild failed", { error });
11650
11890
  });
11651
11891
  }, 100);
11652
11892
  }
11893
+ requestSnapshotRefresh(files = []) {
11894
+ for (const file of files) this.snapshotFiles.add(file);
11895
+ if (this.fullBuildTimer || this.snapshotTimer) return;
11896
+ this.snapshotTimer = setTimeout(() => {
11897
+ this.snapshotTimer = void 0;
11898
+ const snapshotFiles = this.takeSnapshotFiles();
11899
+ this.refreshSnapshotAssets(snapshotFiles).catch((error) => {
11900
+ this.server.config.logger.error("[weapp-vite] stateful HMR snapshot refresh failed", { error });
11901
+ });
11902
+ }, 100);
11903
+ }
11653
11904
  requestServerRestart() {
11654
11905
  if (this.restartTimer) return;
11655
11906
  this.restartTimer = setTimeout(() => {
@@ -11661,15 +11912,43 @@ var StatefulHmrSession = class {
11661
11912
  }
11662
11913
  enqueueOutput(task) {
11663
11914
  this.outputChain = this.outputChain.then(task, task).catch((error) => {
11664
- this.server.config.logger.error("[weapp-vite] stateful HMR output failed", { error });
11915
+ this.server.config.logger.error(`[weapp-vite] stateful HMR output failed: ${formatStatefulHmrError(error)}`);
11665
11916
  });
11666
11917
  return this.outputChain;
11667
11918
  }
11919
+ async rebuildFromSnapshot(files) {
11920
+ await this.adapter.rebuild(async () => {
11921
+ this.replaceSnapshotAssets(await this.snapshots.rebuild(files));
11922
+ });
11923
+ }
11924
+ async refreshSnapshotAssets(files) {
11925
+ this.replaceSnapshotAssets(await this.snapshots.rebuild(files));
11926
+ }
11927
+ takeSnapshotFiles() {
11928
+ const files = [...this.snapshotFiles];
11929
+ this.snapshotFiles.clear();
11930
+ return files;
11931
+ }
11932
+ replaceSnapshotAssets(output) {
11933
+ this.snapshotAssets = new Map(output.filter((item) => item.type === "asset").map((item) => [item.fileName, item]));
11934
+ }
11668
11935
  async waitForInitialBundle() {
11669
11936
  await this.initialBundle.promise;
11670
11937
  await this.outputChain;
11671
11938
  }
11672
11939
  };
11940
+ function shouldRestartStatefulHmrServer(files, configFileDependencies = []) {
11941
+ const normalizedConfigDependencies = new Set(Array.from(configFileDependencies, (dependency) => normalizeFsResolvedId(dependency)));
11942
+ return Array.from(files).some((file) => normalizedConfigDependencies.has(normalizeFsResolvedId(file)));
11943
+ }
11944
+ function mergeStatefulHmrSnapshotAssets(output, snapshotAssets) {
11945
+ for (const asset of snapshotAssets) {
11946
+ if (asset.type !== "asset") continue;
11947
+ const index = output.findIndex((item) => item.fileName === asset.fileName);
11948
+ if (index >= 0) output[index] = asset;
11949
+ else output.push(asset);
11950
+ }
11951
+ }
11673
11952
  function createWatcherAdapter(server, session) {
11674
11953
  return {
11675
11954
  close: async () => {
@@ -11681,13 +11960,16 @@ function createWatcherAdapter(server, session) {
11681
11960
  }
11682
11961
  };
11683
11962
  }
11684
- function isStatefulHmrBoundary(id, srcRoot) {
11963
+ function isStatefulHmrBoundary(id, srcRoot, entryIds) {
11685
11964
  const sidecar = parseSidecarSourceRequest(id);
11686
11965
  const sourceId = sidecar?.kind === "script" ? sidecar.sourceId : id.includes("?") ? void 0 : id;
11687
11966
  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);
11967
+ const normalizedSourceId = normalizeFsResolvedId(sourceId);
11968
+ const normalizedSrcRoot = normalizeFsResolvedId(srcRoot).replace(/\/$/, "");
11969
+ if (!normalizedSourceId.startsWith(`${normalizedSrcRoot}/`) || !/\.(?:[cm]?[jt]sx?|vue)$/.test(normalizedSourceId)) return false;
11970
+ if (!entryIds) return true;
11971
+ for (const entryId of entryIds) if (normalizeFsResolvedId(entryId) === normalizedSourceId) return true;
11972
+ return false;
11691
11973
  }
11692
11974
  function redirectNativeComponentRegistration(code) {
11693
11975
  if (!code.includes("Component")) return code;
@@ -11702,8 +11984,22 @@ function redirectNativeComponentRegistration(code) {
11702
11984
  } });
11703
11985
  return changed ? magicString.toString() : code;
11704
11986
  }
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));
11987
+ function isSafeJavaScriptPatch(files, output, dirtyReasonSummary = [], entryIds, root) {
11988
+ const normalizedEntryIds = entryIds ? new Set(Array.from(entryIds, (entryId) => normalizeFsResolvedId(entryId))) : void 0;
11989
+ return output.type === "Patch" && files.every((file) => /\.(?:[cm]?[jt]sx?|vue)$/.test(file)) && (!normalizedEntryIds || files.every((file) => {
11990
+ const absoluteFile = path.isAbsolute(file) || !root ? file : path.resolve(root, file);
11991
+ return normalizedEntryIds.has(normalizeFsResolvedId(absoluteFile));
11992
+ })) && !output.changedIds?.some(isNonJavaScriptSidecarId) && !dirtyReasonSummary.some(isUnsafeStatefulHmrReason);
11993
+ }
11994
+ function requiresStatefulHmrSnapshot(file, dirtyReasonSummary = []) {
11995
+ return !/\.(?:[cm]?[jt]sx?|vue)$/.test(file) || dirtyReasonSummary.some(isUnsafeStatefulHmrReason);
11996
+ }
11997
+ function isUnsafeStatefulHmrReason(reason) {
11998
+ return /^(?:entry-json-only|entry-local-asset|entry-style-only|tailwind-content):/.test(reason);
11999
+ }
12000
+ function isNonJavaScriptSidecarId(id) {
12001
+ const sidecar = parseSidecarSourceRequest(id) ?? parseSidecarModuleId(id);
12002
+ return sidecar !== void 0 && sidecar.kind !== "script";
11707
12003
  }
11708
12004
  function shouldResetStatefulHmrRetention(retainedDeltaCount, retainedDeltaBytes, nextDeltaBytes) {
11709
12005
  return retainedDeltaCount >= maxRetainedDeltaCount || retainedDeltaBytes + nextDeltaBytes >= maxRetainedDeltaBytes;
@@ -11735,6 +12031,13 @@ function setAsset(output, fileName, source) {
11735
12031
  if (index >= 0) output[index] = asset;
11736
12032
  else output.push(asset);
11737
12033
  }
12034
+ function stampStatefulHmrFullBuild(output, buildId) {
12035
+ for (const item of output) if (item.type === "chunk" && item.fileName.endsWith(".js")) item.code = `// weapp-vite-stateful-build:${buildId}\n${item.code}`;
12036
+ }
12037
+ function formatStatefulHmrError(error) {
12038
+ if (error instanceof Error) return error.stack || error.message;
12039
+ return String(error);
12040
+ }
11738
12041
  //#endregion
11739
12042
  //#region src/runtime/watch/options.ts
11740
12043
  function resolvePollingWatchConfig(configService) {
@@ -12983,8 +13286,10 @@ function parseWxml(options) {
12983
13286
  };
12984
13287
  if (Array.isArray(autoImportComponents[componentName])) autoImportComponents[componentName].push(range);
12985
13288
  else autoImportComponents[componentName] = [range];
12986
- if (!excludeComponent(currentTagName)) if (Array.isArray(components[componentName])) components[componentName].push(range);
12987
- else components[componentName] = [range];
13289
+ if (!excludeComponent(currentTagName)) {
13290
+ if (Array.isArray(components[componentName])) components[componentName].push(range);
13291
+ else components[componentName] = [range];
13292
+ }
12988
13293
  }
12989
13294
  if (normalizeComponentTagName && shouldNormalizeTagName(name)) {
12990
13295
  const normalized = toKebabCaseTagName(name);
@@ -13868,6 +14173,7 @@ function resetEmittedOutputCaches(runtimeState) {
13868
14173
  runtimeState.asset.scopedSlotGenerics.clear();
13869
14174
  runtimeState.build?.output?.emittedSource.clear();
13870
14175
  runtimeState.css.emittedSource.clear();
14176
+ runtimeState.css.transformedSidecarSource.clear();
13871
14177
  runtimeState.wxml.emittedCode.clear();
13872
14178
  }
13873
14179
  async function cleanOutputs(configService) {
@@ -13976,6 +14282,10 @@ function watchWorkers(configService, watcherService, workersDir) {
13976
14282
  }
13977
14283
  //#endregion
13978
14284
  //#region src/runtime/buildPlugin/service.ts
14285
+ function toStatefulHmrOutput(output) {
14286
+ if (!Array.isArray(output) && !("output" in output)) throw new TypeError("stateful HMR snapshot build unexpectedly returned a watcher");
14287
+ return (Array.isArray(output) ? output : [output]).flatMap((result) => result.output);
14288
+ }
13979
14289
  function resolveSnapshotSidecarDirtySummary(filePath, affectedEntries) {
13980
14290
  const normalizedFile = normalizeFsResolvedId(filePath);
13981
14291
  if (configSuffixes.find((suffix) => normalizedFile.endsWith(suffix))) return "json-sidecar:1";
@@ -14087,6 +14397,8 @@ function createSnapshotSidecarIgnoredMatcher(ctx) {
14087
14397
  }
14088
14398
  function createBuildService(ctx) {
14089
14399
  let lastHmrSlowTipProfileCount = 0;
14400
+ let devHmrRuntime;
14401
+ let devHmrRuntimeNoticeLogged = false;
14090
14402
  function createHmrProfileJsonSample(totalMs) {
14091
14403
  const profile = ctx.runtimeState.build.hmr.profile;
14092
14404
  const relativeFile = profile.file && ctx.configService ? ctx.configService.relativeCwd(profile.file) : void 0;
@@ -14653,7 +14965,25 @@ function createBuildService(ctx) {
14653
14965
  ...buildOptions.build ?? {},
14654
14966
  write: true
14655
14967
  };
14656
- if (target === "app" && configService.weappViteConfig.hmr?.runtime === "stateful-experimental") {
14968
+ const configuredHmrRuntime = configService.weappViteConfig.hmr?.runtime;
14969
+ const compileHotReLoad = configService.projectPrivateConfig.setting?.compileHotReLoad;
14970
+ devHmrRuntime ??= resolveHmrRuntime({
14971
+ platform: configService.platform,
14972
+ configured: configuredHmrRuntime,
14973
+ compileHotReLoad
14974
+ });
14975
+ const hmrRuntime = devHmrRuntime;
14976
+ if (target === "app" && !devHmrRuntimeNoticeLogged) {
14977
+ devHmrRuntimeNoticeLogged = true;
14978
+ const messages = formatHmrRuntimeStartupMessages({
14979
+ platform: configService.platform,
14980
+ configured: configuredHmrRuntime,
14981
+ compileHotReLoad,
14982
+ runtime: hmrRuntime
14983
+ });
14984
+ for (const message of messages) logger_default.info(message);
14985
+ }
14986
+ if (target === "app" && hmrRuntime === "stateful-experimental") try {
14657
14987
  const snapshotBuildOptions = {
14658
14988
  ...buildOptions,
14659
14989
  build: {
@@ -14661,7 +14991,8 @@ function createBuildService(ctx) {
14661
14991
  watch: void 0
14662
14992
  }
14663
14993
  };
14664
- await build(snapshotBuildOptions);
14994
+ const initialSnapshot = toStatefulHmrOutput(await build(snapshotBuildOptions));
14995
+ await configService.load(configService.loadOptions);
14665
14996
  resetRuntimeStateForFreshBuild(ctx.runtimeState);
14666
14997
  await scanService.loadAppEntry();
14667
14998
  scanService.loadSubPackages();
@@ -14676,14 +15007,49 @@ function createBuildService(ctx) {
14676
15007
  await statefulWatcher?.close();
14677
15008
  logger_default.info("检测到非兼容更新,正在重启微信状态保持 HMR 构建...");
14678
15009
  resetRuntimeStateForFreshBuild(ctx.runtimeState);
15010
+ await configService.load(configService.loadOptions);
14679
15011
  await scanService.loadAppEntry();
14680
15012
  scanService.loadSubPackages();
14681
15013
  await runDev(target);
14682
15014
  logger_default.success("微信状态保持 HMR 构建已完成完整重载。");
15015
+ }, {
15016
+ initial: initialSnapshot,
15017
+ rebuild: async (files) => {
15018
+ for (const file of files) invalidateFileCache(file);
15019
+ resetRuntimeStateForFreshBuild(ctx.runtimeState);
15020
+ await configService.load(configService.loadOptions);
15021
+ await scanService.loadAppEntry();
15022
+ scanService.loadSubPackages();
15023
+ const snapshotOptions = createDevBuildOptions();
15024
+ snapshotOptions.build = {
15025
+ ...snapshotOptions.build ?? {},
15026
+ emptyOutDir: false,
15027
+ watch: void 0,
15028
+ write: true
15029
+ };
15030
+ snapshotOptions.plugins = [...snapshotOptions.plugins ?? [], {
15031
+ name: "weapp-vite:stateful-hmr-snapshot-assets",
15032
+ enforce: "post",
15033
+ generateBundle(_options, bundle) {
15034
+ for (const [fileName, item] of Object.entries(bundle)) if (item.type === "chunk") delete bundle[fileName];
15035
+ }
15036
+ }];
15037
+ return toStatefulHmrOutput(await build(snapshotOptions));
15038
+ }
14683
15039
  }), workerPromise]);
14684
15040
  statefulWatcher = watcher;
14685
15041
  watcherService.setRollupWatcher(watcher, "/");
14686
15042
  return watcher;
15043
+ } catch (error) {
15044
+ if (configuredHmrRuntime !== "auto" || !isStatefulHmrRuntimeCompatibilityError(error)) throw error;
15045
+ devHmrRuntime = "classic";
15046
+ logger_default.warn(`微信状态保持 HMR 运行时不可用,已自动降级为 classic:${error instanceof Error ? error.message : String(error)}`);
15047
+ logger_default.info("HMR 模式:classic(auto fallback:stateful runtime compatibility check failed)");
15048
+ resetRuntimeStateForFreshBuild(ctx.runtimeState);
15049
+ await configService.load(configService.loadOptions);
15050
+ await scanService.loadAppEntry();
15051
+ scanService.loadSubPackages();
15052
+ return await runDev(target);
14687
15053
  }
14688
15054
  const snapshotBuildOptions = {
14689
15055
  ...buildOptions,
@@ -15940,13 +16306,15 @@ function configureBuildAndPlugins(options) {
15940
16306
  }
15941
16307
  if (resolvedLibConfig?.enabled) {
15942
16308
  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;
16309
+ if (entryFileNames) {
16310
+ if (Array.isArray(rdOptions.output)) rdOptions.output = rdOptions.output.map((output) => ({
16311
+ ...output,
16312
+ entryFileNames
16313
+ }));
16314
+ else {
16315
+ const output = rdOptions.output ?? (rdOptions.output = {});
16316
+ output.entryFileNames = entryFileNames;
16317
+ }
15950
16318
  }
15951
16319
  }
15952
16320
  const rawPlugins = rdOptions.plugins;
@@ -16251,20 +16619,22 @@ function createLoadConfig(options) {
16251
16619
  }
16252
16620
  const loadedConfig = loaded?.config ?? {};
16253
16621
  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;
16622
+ if (weappConfigFilePath) {
16623
+ if (shouldReuseLoadedWeappConfig(weappConfigFilePath, loaded?.path)) weappLoaded = loaded;
16624
+ else try {
16625
+ weappLoaded = await loadConfigFileWithFallback({
16626
+ command: isDev ? "serve" : "build",
16627
+ mode
16628
+ }, weappConfigFilePath, cwd, configLoader);
16629
+ } catch (error) {
16630
+ const cjsError = createCjsConfigLoadError({
16631
+ error,
16632
+ configPath: weappConfigFilePath,
16633
+ cwd
16634
+ });
16635
+ if (cjsError) throw cjsError;
16636
+ throw error;
16637
+ }
16268
16638
  }
16269
16639
  const mergedLoadedConfig = weappLoaded?.config ? defu(weappLoaded.config, loadedConfig) : loadedConfig;
16270
16640
  const config = defu(inlineConfig, {
@@ -16353,6 +16723,7 @@ function createLoadConfig(options) {
16353
16723
  cwd
16354
16724
  });
16355
16725
  let projectConfig = {};
16726
+ let projectPrivateConfig = {};
16356
16727
  let projectConfigPathResolved;
16357
16728
  let projectPrivateConfigPathResolved;
16358
16729
  let mpDistRoot = "";
@@ -16368,6 +16739,7 @@ function createLoadConfig(options) {
16368
16739
  basePath,
16369
16740
  privatePath
16370
16741
  });
16742
+ projectPrivateConfig = await getProjectPrivateConfig(cwd, { privatePath });
16371
16743
  mpDistRoot = resolveProjectConfigRoot(projectConfig, platform) ?? "";
16372
16744
  if (!mpDistRoot) {
16373
16745
  const displayPath = formatProjectConfigPath(cwd, basePath ?? getProjectConfigFileName(platform));
@@ -16428,6 +16800,7 @@ function createLoadConfig(options) {
16428
16800
  emitDefaultAutoImportOutputs: opts.emitDefaultAutoImportOutputs ?? true,
16429
16801
  chunksConfigured,
16430
16802
  projectConfig,
16803
+ projectPrivateConfig,
16431
16804
  projectConfigPath: projectConfigPathResolved,
16432
16805
  projectPrivateConfigPath: projectPrivateConfigPathResolved,
16433
16806
  mpDistRoot,
@@ -20615,6 +20988,7 @@ async function invalidateEntryForSidecar(ctx, filePath, event = "update") {
20615
20988
  }
20616
20989
  const isCssSidecar = Boolean(ext && watchedCssExts.has(ext));
20617
20990
  const isTemplateSidecar = Boolean(ext && watchedTemplateExts.has(ext));
20991
+ if (isCssSidecar) ctx.runtimeState?.css?.transformedSidecarSource.delete(normalizedPath);
20618
20992
  const sidecarCause = configSuffix ? "json-sidecar" : isCssSidecar ? "style-sidecar" : "sidecar-direct";
20619
20993
  const configService = ctx.configService;
20620
20994
  const relativeSource = configService.relativeCwd(normalizedPath);
@@ -23409,6 +23783,10 @@ function hasCustomAutoRuleConfig(config) {
23409
23783
  function hasConfiguredNetworkDefaults(config) {
23410
23784
  return Boolean(config && typeof config === "object" && hasOwn$5(config, "networkDefaults"));
23411
23785
  }
23786
+ function resolveAutoPrelude(config) {
23787
+ if (!config || typeof config !== "object" || !hasOwn$5(config, "prelude")) return true;
23788
+ return config.prelude === true;
23789
+ }
23412
23790
  function resolveAutoRules(config) {
23413
23791
  if (hasCustomAutoRuleConfig(config)) return [{
23414
23792
  dependencyPatterns: resolveDependencyPatterns(config),
@@ -23447,7 +23825,7 @@ function resolveInjectRequestGlobalsOptions(config, packageJson) {
23447
23825
  return {
23448
23826
  mode: "auto",
23449
23827
  targets: [...matchedTargets],
23450
- prelude: config && typeof config === "object" ? config.prelude === true : false
23828
+ prelude: resolveAutoPrelude(config)
23451
23829
  };
23452
23830
  }
23453
23831
  function resolveRequestRuntimeOptions(input, packageJson, warn) {
@@ -23803,18 +24181,20 @@ function removeConditionalBlock(start) {
23803
24181
  while (node && depth > 0) {
23804
24182
  if (node.type === "comment") {
23805
24183
  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;
24184
+ if (directive) {
24185
+ if (directive.type === "endif") {
24186
+ depth -= 1;
24187
+ const comment = node;
24188
+ node = comment.next();
24189
+ comment.remove();
24190
+ continue;
24191
+ } else {
24192
+ depth += 1;
24193
+ const comment = node;
24194
+ node = comment.next();
24195
+ comment.remove();
24196
+ continue;
24197
+ }
23818
24198
  }
23819
24199
  }
23820
24200
  const next = node.next();
@@ -23836,10 +24216,12 @@ const postCreator = (options = { platform: "weapp" }) => {
23836
24216
  atRule.name = "import";
23837
24217
  return;
23838
24218
  }
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);
24219
+ if (atRule.name === `wv-if`) {
24220
+ if (![...atRule.params.matchAll(/\(([^)]+)\)/g)].some((match) => {
24221
+ return match[1].trim() === platform;
24222
+ })) atRule.remove();
24223
+ else atRule.replaceWith(atRule.nodes);
24224
+ }
23843
24225
  },
23844
24226
  Comment(comment) {
23845
24227
  const directive = parseDirective(comment.text);
@@ -24164,6 +24546,16 @@ async function readStyleGraphSource(stylePath, fallback) {
24164
24546
  return fallback;
24165
24547
  }
24166
24548
  }
24549
+ async function resolveMemoryStyleSource(ctx, stylePath) {
24550
+ const sourceId = normalizeFsResolvedId(stylePath, { stripLeadingNullByte: true });
24551
+ const cache = ctx.runtimeState?.css?.transformedSidecarSource;
24552
+ const cached = cache?.get(sourceId);
24553
+ if (!cached) return;
24554
+ try {
24555
+ if (await fs$1.readFile(stylePath, "utf8") === cached.diskSource) return cached.code;
24556
+ } catch {}
24557
+ cache?.delete(sourceId);
24558
+ }
24167
24559
  function resolveOutputStyleFileName(configService, stylePath) {
24168
24560
  return configService.relativeOutputPath(changeFileExtension(stylePath, configService.outputExtensions.wxss));
24169
24561
  }
@@ -24267,7 +24659,7 @@ async function emitStyleSidecarAsset(ctx, pluginCtx, bundle, stylePath, resolved
24267
24659
  const { configService } = ctx;
24268
24660
  const fileName = resolveOutputStyleFileName(configService, stylePath);
24269
24661
  if (!fileName) return false;
24270
- const rawCss = await fs$1.readFile(stylePath, "utf8");
24662
+ const rawCss = await resolveMemoryStyleSource(ctx, stylePath) ?? await fs$1.readFile(stylePath, "utf8");
24271
24663
  const { css, dependencies } = await preprocessStyleSource(rawCss, stylePath, resolvedConfig);
24272
24664
  syncCssImportDependencies(ctx, stylePath, rawCss, dependencies);
24273
24665
  if (typeof pluginCtx.addWatchFile === "function") for (const dependency of dependencies) pluginCtx.addWatchFile(normalizeWatchPath(dependency));
@@ -24323,7 +24715,7 @@ async function handleBundleEntry(ctx, bundle, bundleKey, asset, configService, s
24323
24715
  const normalizedFileName = toPosixPath(fileName);
24324
24716
  const freshHmrStyleSourcePath = resolveFreshHmrStyleSourcePath(ctx, normalizedFileName);
24325
24717
  const preprocessId = freshHmrStyleSourcePath ?? absOriginal;
24326
- const preprocessInput = freshHmrStyleSourcePath ? await readStyleGraphSource(freshHmrStyleSourcePath, canonicalSource) : canonicalSource;
24718
+ const preprocessInput = freshHmrStyleSourcePath ? await resolveMemoryStyleSource(ctx, freshHmrStyleSourcePath) ?? await readStyleGraphSource(freshHmrStyleSourcePath, canonicalSource) : canonicalSource;
24327
24719
  const { css, dependencies } = await preprocessStyleSource(preprocessInput, preprocessId, resolvedConfig, { enabled: shouldPreprocessWithVite(preprocessId) });
24328
24720
  syncCssImportDependencies(ctx, preprocessId, freshHmrStyleSourcePath ? preprocessInput : await readStyleGraphSource(absOriginal, canonicalSource), dependencies);
24329
24721
  if (typeof this.addWatchFile === "function") for (const dependency of dependencies) this.addWatchFile(normalizeWatchPath(dependency));
@@ -24470,6 +24862,23 @@ function css(ctx) {
24470
24862
  await generateBundleSharedCss.call(this, ctx, configService, bundle, styleAnalysis, resolvedConfig);
24471
24863
  await emitCollectedStyleSidecars.call(this, ctx, rolldownBundle, resolvedConfig);
24472
24864
  }
24865
+ }, {
24866
+ name: "weapp-vite:css-sidecar-source",
24867
+ async transform(code, id) {
24868
+ const sidecar = parseSidecarSourceRequest(id);
24869
+ if (!sidecar || sidecar.kind !== "style") return null;
24870
+ const sourceId = normalizeFsResolvedId(sidecar.sourceId, { stripLeadingNullByte: true });
24871
+ try {
24872
+ const diskSource = await fs$1.readFile(sourceId, "utf8");
24873
+ ctx.runtimeState?.css?.transformedSidecarSource.set(sourceId, {
24874
+ code,
24875
+ diskSource
24876
+ });
24877
+ } catch {
24878
+ ctx.runtimeState?.css?.transformedSidecarSource.delete(sourceId);
24879
+ }
24880
+ return null;
24881
+ }
24473
24882
  }];
24474
24883
  }
24475
24884
  //#endregion
@@ -24892,12 +25301,6 @@ function setRequireImportLiteral(node, nextValue) {
24892
25301
  function normalizeRelativeChunkImport(fileName, importee) {
24893
25302
  return toPosixPath(path.normalize(path.join(path.dirname(fileName), importee)));
24894
25303
  }
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
25304
  //#endregion
24902
25305
  //#region src/utils/weapi.ts
24903
25306
  function getWeapiGlobalRootCandidateItems() {
@@ -25141,14 +25544,14 @@ function composeSourceMaps(transformedMap, originalMap) {
25141
25544
  }
25142
25545
  //#endregion
25143
25546
  //#region src/plugins/core/lifecycle/emit/rewrite/sourcemap.ts
25144
- function applyMagicStringChunkRewrite(chunk, magicString) {
25547
+ function applyMagicStringChunkRewrite(chunk, magicString, options) {
25145
25548
  const previousCode = chunk.code;
25146
25549
  const nextCode = magicString.toString();
25147
25550
  if (nextCode === previousCode) return false;
25148
25551
  const previousMap = normalizeEncodedSourceMapLike(chunk.map);
25149
25552
  chunk.code = nextCode;
25150
25553
  if (previousMap) chunk.map = composeSourceMaps(magicString.generateMap({
25151
- hires: "boundary",
25554
+ hires: options?.hires ?? "boundary",
25152
25555
  includeContent: true,
25153
25556
  source: chunk.fileName
25154
25557
  }), previousMap);
@@ -25337,6 +25740,9 @@ const REQUEST_GLOBAL_APP_MODULE_KEY_PREFIX = "__weappViteRequestGlobalsModule:";
25337
25740
  function resolveChunkRequestGlobalsTargets(code, targets, mode) {
25338
25741
  return mode === "auto" ? resolveAutoRequestGlobalsTargets(code, targets) : targets;
25339
25742
  }
25743
+ function resolvePreludeRequestGlobalsTargets(code, targets, mode) {
25744
+ return mode === "auto" ? targets : resolveChunkRequestGlobalsTargets(code, targets, mode);
25745
+ }
25340
25746
  function collectTopLevelDeclaredIdentifiers(code) {
25341
25747
  const identifiers = /* @__PURE__ */ new Set();
25342
25748
  try {
@@ -25760,7 +26166,7 @@ function inlineRequestGlobalsAppRegisteredInstallerChunks(bundle, installerChunk
25760
26166
  appChunk.code = `${inlinedModules.join("\n")}\n${appChunk.code}`;
25761
26167
  }
25762
26168
  function createRequestGlobalsPreludeCode(chunk, installerChunks, targets, mode, networkDefaults) {
25763
- const chunkTargets = resolveChunkRequestGlobalsTargets(chunk.code, targets, mode);
26169
+ const chunkTargets = resolvePreludeRequestGlobalsTargets(chunk.code, targets, mode);
25764
26170
  if (chunkTargets.length === 0 || chunk.code.includes(REQUEST_GLOBAL_PRELUDE_MARKER)) return;
25765
26171
  const bindingTargets = resolveRequestGlobalsBindingTargets(chunkTargets);
25766
26172
  if (bindingTargets.length === 0) return;
@@ -25788,13 +26194,22 @@ function createRequestGlobalsPreludeCode(chunk, installerChunks, targets, mode,
25788
26194
  ].join("\n");
25789
26195
  }
25790
26196
  function createRequestGlobalsPreludeAssetCode(preludeFileName, chunk, installerChunks, targets, mode, networkDefaults) {
25791
- const chunkTargets = resolveChunkRequestGlobalsTargets(chunk.code, targets, mode);
26197
+ const chunkTargets = resolvePreludeRequestGlobalsTargets(chunk.code, targets, mode);
25792
26198
  if (chunkTargets.length === 0) return;
25793
26199
  const bindingTargets = resolveRequestGlobalsBindingTargets(chunkTargets);
25794
26200
  if (bindingTargets.length === 0) return;
25795
26201
  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`;
26202
+ let installerChunkFileName = installerImport?.installerChunkFileName;
26203
+ let exportName = installerImport?.exportName;
26204
+ if (!installerChunkFileName || !exportName) {
26205
+ const ownExportName = installerChunks.get(toPosixPath(chunk.fileName));
26206
+ if (ownExportName) {
26207
+ installerChunkFileName = chunk.fileName;
26208
+ exportName = ownExportName;
26209
+ }
26210
+ }
26211
+ if (!installerChunkFileName || !exportName) return;
26212
+ const installerHostCode = `${toRequestGlobalsInstallerModuleExpression(preludeFileName, installerChunkFileName, { appRegisteredModule: false })}[${JSON.stringify(exportName)}](${createRequestGlobalsInstallerOptionsCode(chunkTargets, networkDefaults)}) || globalThis`;
25798
26213
  return [
25799
26214
  `/* ${REQUEST_GLOBAL_PRELUDE_MARKER} */`,
25800
26215
  `(() => {`,
@@ -25917,9 +26332,20 @@ function createAppPreludeRequireStatement(chunkFileName, preludeFileName) {
25917
26332
  const requestPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
25918
26333
  return `/* ${APP_PRELUDE_REQUIRE_MARKER} */require(${JSON.stringify(requestPath)})`;
25919
26334
  }
26335
+ function prependChunkCodeWithSourcemap(chunk, injectedCode) {
26336
+ const directiveMatch = chunk.code.match(DIRECTIVE_PROLOGUE_RE);
26337
+ const insertIndex = directiveMatch?.[0] ? directiveMatch[0].length : 0;
26338
+ const magicString = new MagicString(chunk.code);
26339
+ magicString.prependLeft(insertIndex, `${injectedCode}\n`);
26340
+ applyMagicStringChunkRewrite(chunk, magicString, { hires: true });
26341
+ }
26342
+ function hasRequestGlobalsPreludeDependency(chunk, requestGlobalsPreludeOptions) {
26343
+ if (!requestGlobalsPreludeOptions.enabled) return false;
26344
+ 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);
26345
+ }
25920
26346
  function emitAppPreludeRequireAssets(bundle, appPreludeCode, state, requestGlobalsPreludeOptions, emitFile) {
25921
26347
  const preservedRequestGlobalsInstallerChunks = /* @__PURE__ */ new Set();
25922
- if (!appPreludeCode) return preservedRequestGlobalsInstallerChunks;
26348
+ if (!appPreludeCode && !requestGlobalsPreludeOptions.enabled) return preservedRequestGlobalsInstallerChunks;
25923
26349
  const preludeFileNames = /* @__PURE__ */ new Set();
25924
26350
  if (state.subPackageMeta?.subPackage.root) preludeFileNames.add(`${state.subPackageMeta.subPackage.root}/${APP_PRELUDE_REQUIRE_FILE_BASENAME}`);
25925
26351
  else {
@@ -25931,7 +26357,8 @@ function emitAppPreludeRequireAssets(bundle, appPreludeCode, state, requestGloba
25931
26357
  const scopeChunks = Object.values(bundle).filter((output) => {
25932
26358
  return output?.type === "chunk" && resolveAppPreludeRequireFileName(output.fileName, state) === fileName;
25933
26359
  });
25934
- const requestGlobalsPreludeCode = requestGlobalsPreludeOptions.enabled ? scopeChunks.map((chunk) => createRequestGlobalsPreludeAssetCode(fileName, chunk, requestGlobalsPreludeOptions.installerChunks, requestGlobalsPreludeOptions.targets, requestGlobalsPreludeOptions.mode, requestGlobalsPreludeOptions.networkDefaults)).find(Boolean) : void 0;
26360
+ const sortedScopeChunks = [...scopeChunks.filter((chunk) => !requestGlobalsPreludeOptions.installerChunks.has(toPosixPath(chunk.fileName))), ...scopeChunks.filter((chunk) => requestGlobalsPreludeOptions.installerChunks.has(toPosixPath(chunk.fileName)))];
26361
+ const requestGlobalsPreludeCode = requestGlobalsPreludeOptions.enabled ? sortedScopeChunks.map((chunk) => createRequestGlobalsPreludeAssetCode(fileName, chunk, requestGlobalsPreludeOptions.installerChunks, requestGlobalsPreludeOptions.targets, requestGlobalsPreludeOptions.mode, requestGlobalsPreludeOptions.networkDefaults)).find(Boolean) : void 0;
25935
26362
  if (requestGlobalsPreludeCode) {
25936
26363
  const installerImport = scopeChunks.map((chunk) => resolveRequestGlobalsInstallerImport(chunk, requestGlobalsPreludeOptions.installerChunks)).find(Boolean);
25937
26364
  if (installerImport?.installerChunkFileName) preservedRequestGlobalsInstallerChunks.add(installerImport.installerChunkFileName);
@@ -25949,16 +26376,18 @@ function injectAppPreludeCode(bundle, appPreludeCode, options, state, requestGlo
25949
26376
  let preservedRequestGlobalsInstallerChunks = /* @__PURE__ */ new Set();
25950
26377
  if (!options.enabled) return preservedRequestGlobalsInstallerChunks;
25951
26378
  const entryChunkFileNames = options.mode === "entry" ? collectAppPreludeEntryChunkFileNames(state) : void 0;
25952
- if (options.mode === "require" && appPreludeCode) preservedRequestGlobalsInstallerChunks = emitAppPreludeRequireAssets(bundle, appPreludeCode, state, requestGlobalsPreludeOptions, emitFile);
26379
+ if (options.mode === "require" && (appPreludeCode || requestGlobalsPreludeOptions.enabled)) preservedRequestGlobalsInstallerChunks = emitAppPreludeRequireAssets(bundle, appPreludeCode, state, requestGlobalsPreludeOptions, emitFile);
25953
26380
  for (const output of Object.values(bundle)) {
25954
26381
  if (output?.type !== "chunk") continue;
25955
26382
  const chunk = output;
25956
26383
  if (chunk.code.includes(APP_PRELUDE_CHUNK_MARKER) || chunk.code.includes(APP_PRELUDE_REQUIRE_MARKER)) continue;
25957
26384
  const isTargetEntryChunk = chunk.isEntry === true || entryChunkFileNames?.has(chunk.fileName) === true;
25958
26385
  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");
26386
+ const requestGlobalsPreludeCode = requestGlobalsPreludeOptions.enabled && options.mode !== "require" ? createRequestGlobalsPreludeCode(chunk, requestGlobalsPreludeOptions.installerChunks, requestGlobalsPreludeOptions.targets, requestGlobalsPreludeOptions.mode, requestGlobalsPreludeOptions.networkDefaults) : void 0;
26387
+ const shouldInjectRequirePrelude = appPreludeCode || hasRequestGlobalsPreludeDependency(chunk, requestGlobalsPreludeOptions);
26388
+ const injectedCode = [requestGlobalsPreludeCode, options.mode === "require" ? shouldInjectRequirePrelude ? createAppPreludeRequireStatement(chunk.fileName, resolveAppPreludeRequireFileName(chunk.fileName, state)) : void 0 : appPreludeCode].filter(Boolean).join("\n");
25960
26389
  if (!injectedCode) continue;
25961
- chunk.code = prependChunkCodePreservingDirectives(chunk.code, injectedCode);
26390
+ prependChunkCodeWithSourcemap(chunk, injectedCode);
25962
26391
  }
25963
26392
  return preservedRequestGlobalsInstallerChunks;
25964
26393
  }
@@ -26372,7 +26801,7 @@ function createGenerateBundleHook(state, isPluginBuild) {
26372
26801
  collapseRequestGlobalsRuntimeSupportChunk(rolldownBundle);
26373
26802
  }
26374
26803
  const appPreludePath = scanService.appEntry?.preludePath;
26375
- const shouldInjectRequestGlobalsPrelude = injectRequestGlobalsOptions?.prelude === true;
26804
+ const shouldInjectRequestGlobalsPrelude = injectRequestGlobalsOptions?.prelude === true && Boolean(scanService.appEntry || subPackageMeta);
26376
26805
  const appPreludeOptions = resolveAppPreludeOptions(state);
26377
26806
  const preservedRequestGlobalsInstallerChunks = appPreludeOptions.enabled && Boolean(appPreludePath) || shouldInjectRequestGlobalsPrelude ? injectAppPreludeCode(rolldownBundle, await resolveAppPreludeCode(appPreludePath, {
26378
26807
  importMetaDefineRegistry: configService.importMetaDefineRegistry,
@@ -27718,6 +28147,7 @@ function createWatchChangeHook(state) {
27718
28147
  watchToDirtyMs: performance.now() - startedAt,
27719
28148
  dirtyReasonSummary
27720
28149
  };
28150
+ state.ctx.onStatefulHmrSourceChange?.(normalizedId, dirtyReasonSummary ?? []);
27721
28151
  };
27722
28152
  }
27723
28153
  //#endregion
@@ -31170,15 +31600,17 @@ function hasTsconfigReference(tsconfig, target) {
31170
31600
  return false;
31171
31601
  }
31172
31602
  }
31173
- function resolveDefaultRolldownTsconfig(cwd) {
31174
- const appTsconfig = path.resolve(cwd, ".weapp-vite/tsconfig.app.json");
31175
- const rootTsconfig = path.resolve(cwd, "tsconfig.json");
31603
+ function resolveDefaultRolldownTsconfig(cwd, configFilePath) {
31604
+ const configRoot = configFilePath ? path.dirname(configFilePath) : void 0;
31605
+ const projectRoot = configRoot && existsSync(path.resolve(configRoot, ".weapp-vite/tsconfig.app.json")) ? configRoot : cwd;
31606
+ const appTsconfig = path.resolve(projectRoot, ".weapp-vite/tsconfig.app.json");
31607
+ const rootTsconfig = path.resolve(projectRoot, "tsconfig.json");
31176
31608
  if (existsSync(appTsconfig)) return appTsconfig;
31177
31609
  if (hasTsconfigReference(rootTsconfig, appTsconfig)) return appTsconfig;
31178
31610
  if (existsSync(rootTsconfig)) return rootTsconfig;
31179
31611
  }
31180
31612
  function normalizeInlineConfigAfterDefu(inline, options) {
31181
- const { cwd, ctx, platform, rolldownOptions, subPackageMeta } = options;
31613
+ const { cwd, configFilePath, ctx, platform, rolldownOptions, subPackageMeta } = options;
31182
31614
  const build = inline.build ?? (inline.build = {});
31183
31615
  const userRolldownOptions = build.rolldownOptions;
31184
31616
  const mergedRolldownOptions = {
@@ -31189,8 +31621,11 @@ function normalizeInlineConfigAfterDefu(inline, options) {
31189
31621
  ...userRolldownOptions?.output ?? {}
31190
31622
  }
31191
31623
  };
31192
- const defaultTsconfig = resolveDefaultRolldownTsconfig(cwd);
31193
- if (!Object.prototype.hasOwnProperty.call(mergedRolldownOptions, "tsconfig") && !mergedRolldownOptions.resolve?.tsconfigFilename && defaultTsconfig) mergedRolldownOptions.tsconfig = defaultTsconfig;
31624
+ const defaultTsconfig = resolveDefaultRolldownTsconfig(cwd, configFilePath);
31625
+ const resolveOptions = mergedRolldownOptions.resolve;
31626
+ if (defaultTsconfig) {
31627
+ if (!Object.prototype.hasOwnProperty.call(mergedRolldownOptions, "tsconfig")) mergedRolldownOptions.tsconfig = configFilePath && !resolveOptions?.tsconfigFilename ? false : defaultTsconfig;
31628
+ } else if (!Object.prototype.hasOwnProperty.call(mergedRolldownOptions, "tsconfig") && !resolveOptions?.tsconfigFilename) mergedRolldownOptions.tsconfig = false;
31194
31629
  build.rolldownOptions = mergedRolldownOptions;
31195
31630
  inline.define = {
31196
31631
  ...inline.define ?? {},
@@ -31220,7 +31655,7 @@ function resolveMiniprogramWatchInclude(options) {
31220
31655
  });
31221
31656
  }
31222
31657
  function mergeMiniprogram(options, ...configs) {
31223
- const { ctx, subPackageMeta, config, cwd, srcRoot, mpDistRoot, configFileDependencies = [], packageJson, isDev, applyRuntimePlatform, injectBuiltinAliases, getDefineImportMetaEnv, setOptions, oxcRolldownPlugin } = options;
31658
+ const { ctx, subPackageMeta, config, cwd, srcRoot, mpDistRoot, configFileDependencies = [], configFilePath, packageJson, isDev, applyRuntimePlatform, injectBuiltinAliases, getDefineImportMetaEnv, setOptions, oxcRolldownPlugin } = options;
31224
31659
  const platform = ctx.configService?.platform;
31225
31660
  applyRuntimePlatform("miniprogram");
31226
31661
  const createMiniprogramCustomLogger = () => {
@@ -31289,6 +31724,7 @@ function mergeMiniprogram(options, ...configs) {
31289
31724
  });
31290
31725
  normalizeInlineConfigAfterDefu(inline, {
31291
31726
  cwd,
31727
+ configFilePath,
31292
31728
  ctx,
31293
31729
  platform,
31294
31730
  rolldownOptions,
@@ -31311,6 +31747,7 @@ function mergeMiniprogram(options, ...configs) {
31311
31747
  if (inlineConfig.build) delete inlineConfig.build.watch;
31312
31748
  normalizeInlineConfigAfterDefu(inlineConfig, {
31313
31749
  cwd,
31750
+ configFilePath,
31314
31751
  ctx,
31315
31752
  platform,
31316
31753
  rolldownOptions,
@@ -31466,6 +31903,7 @@ function createMergeFactories(options) {
31466
31903
  srcRoot: currentOptions.srcRoot,
31467
31904
  mpDistRoot: currentOptions.mpDistRoot,
31468
31905
  configFileDependencies: currentOptions.configFileDependencies,
31906
+ configFilePath: currentOptions.configFilePath,
31469
31907
  packageJson: currentOptions.packageJson,
31470
31908
  isDev: currentOptions.isDev,
31471
31909
  applyRuntimePlatform,
@@ -31675,6 +32113,7 @@ function createConfigService(ctx) {
31675
32113
  isDev: false,
31676
32114
  emitDefaultAutoImportOutputs: true,
31677
32115
  projectConfig: {},
32116
+ projectPrivateConfig: {},
31678
32117
  config: {},
31679
32118
  loadOptions: input,
31680
32119
  packageJson: {},
@@ -31786,6 +32225,9 @@ function createConfigService(ctx) {
31786
32225
  get projectConfig() {
31787
32226
  return options.projectConfig;
31788
32227
  },
32228
+ get projectPrivateConfig() {
32229
+ return options.projectPrivateConfig;
32230
+ },
31789
32231
  get projectConfigPath() {
31790
32232
  return options.projectConfigPath;
31791
32233
  },
@@ -32095,7 +32537,7 @@ async function loadAppEntry(ctx, scanState) {
32095
32537
  const { path: appEntryPath } = appEntry;
32096
32538
  let configFromVue;
32097
32539
  if (!appConfigFile && vueAppPath) {
32098
- const { extractConfigFromVue } = await import("./file-TBExd8Jd.mjs");
32540
+ const { extractConfigFromVue } = await import("./file-BTZg_nyD.mjs");
32099
32541
  configFromVue = await extractConfigFromVue(vueAppPath);
32100
32542
  if (configFromVue) appConfigFile = vueAppPath;
32101
32543
  }