weapp-vite 6.19.0 → 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-BgstESAr.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";
@@ -480,7 +480,8 @@ function normalizeRelativePath$1(value) {
480
480
  }
481
481
  function normalizeWatchPath(value) {
482
482
  if (!value) return value;
483
- return toPosixPath(normalize(toPosixPath(stripWindowsDevicePath(value))));
483
+ const posix = toPosixPath(stripWindowsDevicePath(value));
484
+ return toPosixPath(normalize(posix));
484
485
  }
485
486
  function stripLeadingSlashes(value) {
486
487
  return value.replace(LEADING_SLASH_RE$3, "");
@@ -1320,10 +1321,11 @@ function extractFromPropsInterfaceMembers(node) {
1320
1321
  }
1321
1322
  function extractComponentPropsFromDts(code) {
1322
1323
  let props = /* @__PURE__ */ new Map();
1323
- traverse(parse$2(code, {
1324
+ const ast = parse$2(code, {
1324
1325
  ...BABEL_TS_MODULE_PARSER_OPTIONS,
1325
1326
  errorRecovery: true
1326
- }), {
1327
+ });
1328
+ traverse(ast, {
1327
1329
  TSInterfaceDeclaration(path) {
1328
1330
  if (props.size > 0) {
1329
1331
  path.stop();
@@ -5301,6 +5303,17 @@ async function loadViteConfigFile(configEnv, configFile, configRoot, configFileD
5301
5303
  }
5302
5304
  //#endregion
5303
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
+ }
5304
5317
  const DEFAULT_PROJECT_PRIVATE_CONFIG_FILE_NAME = "project.private.config.json";
5305
5318
  function getProjectConfigFileName(platform) {
5306
5319
  return getProjectPlatformOptions(platform).projectConfigFileName;
@@ -5321,23 +5334,13 @@ function resolveProjectConfigRoot(projectConfig, platform) {
5321
5334
  async function getProjectConfig(root, options) {
5322
5335
  const baseJsonPath = path.resolve(root, options?.basePath ?? "project.config.json");
5323
5336
  const privateJsonPath = path.resolve(root, options?.privatePath ?? "project.private.config.json");
5324
- let baseJson = {};
5325
- let privateJson = {};
5326
- if (await fs$1.pathExists(baseJsonPath)) try {
5327
- baseJson = await fs$1.readJson(baseJsonPath) || {};
5328
- } catch {
5329
- throw new Error(`解析 json 格式失败, ${baseJsonPath} 为非法的 json 格式`);
5330
- }
5331
- else throw new Error(`找不到项目配置文件:${baseJsonPath}`);
5332
- if (!options?.ignorePrivate) {
5333
- if (await fs$1.pathExists(privateJsonPath)) try {
5334
- privateJson = await fs$1.readJson(privateJsonPath) || {};
5335
- } catch {
5336
- throw new Error(`解析 json 格式失败, ${privateJsonPath} 为非法的 json 格式`);
5337
- }
5338
- }
5337
+ const baseJson = await readProjectConfigFile(baseJsonPath, true);
5338
+ const privateJson = options?.ignorePrivate ? {} : await readProjectConfigFile(privateJsonPath, false);
5339
5339
  return Object.assign({}, privateJson, baseJson);
5340
5340
  }
5341
+ async function getProjectPrivateConfig(root, options) {
5342
+ return await readProjectConfigFile(path.resolve(root, options?.privatePath ?? "project.private.config.json"), false);
5343
+ }
5341
5344
  function resolveProjectConfigSyncDirs(options) {
5342
5345
  const outputRoot = path.dirname(options.outDir);
5343
5346
  const sourceBasePath = path.resolve(options.projectConfigPath);
@@ -5732,7 +5735,7 @@ function createRegistryHelpers(state) {
5732
5735
  }
5733
5736
  //#endregion
5734
5737
  //#region src/runtime/autoImport/service/resolver.ts
5735
- const require$1 = createRequire(import.meta.url);
5738
+ const require$2 = createRequire(import.meta.url);
5736
5739
  const COMPONENT_HAS_UPPER_RE = /[A-Z]/;
5737
5740
  const CAMEL_TO_KEBAB_RE$1 = /([a-z0-9])([A-Z])/g;
5738
5741
  const MULTI_UPPER_TO_KEBAB_RE = /([A-Z]+)([A-Z][a-z])/g;
@@ -5810,7 +5813,7 @@ function createResolverHelpers(state) {
5810
5813
  function getMiniprogramDir(pkgName, cwd) {
5811
5814
  if (miniprogramDirCache.has(pkgName)) return miniprogramDirCache.get(pkgName);
5812
5815
  try {
5813
- const packageJsonPath = require$1.resolve(`${pkgName}/package.json`, { paths: [cwd] });
5816
+ const packageJsonPath = require$2.resolve(`${pkgName}/package.json`, { paths: [cwd] });
5814
5817
  const raw = fs$1.readJsonSync(packageJsonPath, { throws: false });
5815
5818
  const normalized = (typeof raw?.miniprogram === "string" ? raw.miniprogram.trim() : void 0)?.replace(TRAILING_RELATIVE_PREFIX_RE, "").replace(TRAILING_SLASH_RE$1, "");
5816
5819
  miniprogramDirCache.set(pkgName, normalized || void 0);
@@ -5825,7 +5828,7 @@ function createResolverHelpers(state) {
5825
5828
  const cached = packageRootCache.get(cacheKey);
5826
5829
  if (cached) return cached;
5827
5830
  try {
5828
- const packageJsonPath = require$1.resolve(`${pkgName}/package.json`, { paths: [cwd] });
5831
+ const packageJsonPath = require$2.resolve(`${pkgName}/package.json`, { paths: [cwd] });
5829
5832
  const packageRoot = path.dirname(packageJsonPath);
5830
5833
  packageRootCache.set(cacheKey, packageRoot);
5831
5834
  return packageRoot;
@@ -5857,7 +5860,7 @@ function createResolverHelpers(state) {
5857
5860
  candidates.push(`${withMiniprogramDir}/index.js`);
5858
5861
  } else candidates.push(withMiniprogramDir);
5859
5862
  for (const candidate of candidates) try {
5860
- require$1.resolve(candidate, { paths: [cwd] });
5863
+ require$2.resolve(candidate, { paths: [cwd] });
5861
5864
  navigationImportCache.set(from, candidate);
5862
5865
  return candidate;
5863
5866
  } catch {}
@@ -6042,7 +6045,7 @@ function createAutoImportScheduling(options) {
6042
6045
  //#region src/runtime/autoImport/service/shared.ts
6043
6046
  const logWarnCache = new LRUCache({
6044
6047
  max: 512,
6045
- ttl: 1e3 * 60 * 60
6048
+ ttl: 36e5
6046
6049
  });
6047
6050
  function logWarnOnce(message) {
6048
6051
  if (logWarnCache.get(message)) return;
@@ -6519,8 +6522,10 @@ async function collectCandidateFilesFromRoots(absoluteSrcRoot, matcher, roots, o
6519
6522
  async function collectCandidates(absoluteSrcRoot, include, subPackageRoots, searchRoots) {
6520
6523
  const matcher = createAutoRoutesMatcher(include, subPackageRoots);
6521
6524
  const roots = resolveCandidateSearchRoots(absoluteSrcRoot, matcher, searchRoots) ?? [];
6522
- if (!searchRoots) if (matcher.isDefault) roots.push(...await resolveDefaultSearchRoots(absoluteSrcRoot, subPackageRoots));
6523
- 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
+ }
6524
6529
  const createCrawler = () => new fdir({
6525
6530
  includeDirs: false,
6526
6531
  pathSeparator: "/",
@@ -7646,8 +7651,10 @@ async function transformVueSource(code, id) {
7646
7651
  const { descriptor, errors } = parse(code, { filename: id });
7647
7652
  if (errors.length) throw errors[0];
7648
7653
  const blocks = [descriptor.script, descriptor.scriptSetup].filter((block) => block?.content);
7649
- return await transformWithOxc(blocks.map((block) => block.content).join("\n") || "export default {}", id, {
7650
- lang: blocks.some((block) => block?.lang === "tsx") ? "tsx" : blocks.some((block) => block?.lang === "ts") ? "ts" : "js",
7654
+ const source = blocks.map((block) => block.content).join("\n") || "export default {}";
7655
+ const lang = blocks.some((block) => block?.lang === "tsx") ? "tsx" : blocks.some((block) => block?.lang === "ts") ? "ts" : "js";
7656
+ return await transformWithOxc(source, id, {
7657
+ lang,
7651
7658
  sourcemap: false,
7652
7659
  target: "esnext"
7653
7660
  });
@@ -7856,6 +7863,22 @@ function resolveCompilerOutputExtensions(outputExtensions) {
7856
7863
  return resolveOutputExtensions(outputExtensions, { scriptModuleExtensionFallback: "wxs" });
7857
7864
  }
7858
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
7859
7882
  //#region src/runtime/lib.ts
7860
7883
  function hasLibEntry(entry) {
7861
7884
  if (!entry) return false;
@@ -8221,9 +8244,7 @@ function ensureModuleResolution(ts, compilerOptions) {
8221
8244
  case ts.ModuleKind.NodeNext:
8222
8245
  moduleResolution = ts.ModuleResolutionKind.NodeNext;
8223
8246
  break;
8224
- default:
8225
- moduleResolution = ts.version.startsWith("5") ? ts.ModuleResolutionKind.Bundler : ts.ModuleResolutionKind.Classic;
8226
- break;
8247
+ default: moduleResolution = ts.version.startsWith("5") ? ts.ModuleResolutionKind.Bundler : ts.ModuleResolutionKind.Classic;
8227
8248
  }
8228
8249
  compilerOptions.moduleResolution = moduleResolution;
8229
8250
  }
@@ -8448,8 +8469,10 @@ async function generateLibDts(configService) {
8448
8469
  });
8449
8470
  await normalizeRolldownDtsOutput(tsEntries, configService.outDir);
8450
8471
  }
8451
- if (vueEntries.length > 0) if (dtsOptions?.mode === "vue-tsc") await generateVueDtsWithVueTsc(configService, libConfig, vueEntries, dtsOptions);
8452
- 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
+ }
8453
8476
  await Promise.all(entries.map((entry) => ensureStub(entry, configService.outDir)));
8454
8477
  if (vueEntries.length > 0) {
8455
8478
  if (shouldRewriteWevuComponentType(dtsOptions?.mode === "vue-tsc" ? getVueCompilerLibOrUndefined(dtsOptions?.vueTsc?.vueCompilerOptions?.lib) : getVueCompilerLibOrUndefined(dtsOptions?.internal?.vueCompilerOptions?.lib))) await Promise.all(vueEntries.map(async (entry) => {
@@ -8604,13 +8627,13 @@ function getWeappViteConfig() {
8604
8627
  platform: DEFAULT_MP_PLATFORM,
8605
8628
  multiPlatform: false,
8606
8629
  es5: false,
8607
- packageSizeWarningBytes: 2 * 1024 * 1024,
8630
+ packageSizeWarningBytes: 2097152,
8608
8631
  analyze: {
8609
8632
  budgets: {
8610
- totalBytes: 20 * 1024 * 1024,
8611
- mainBytes: 2 * 1024 * 1024,
8612
- subPackageBytes: 2 * 1024 * 1024,
8613
- independentBytes: 2 * 1024 * 1024,
8633
+ totalBytes: 20971520,
8634
+ mainBytes: 2097152,
8635
+ subPackageBytes: 2097152,
8636
+ independentBytes: 2097152,
8614
8637
  warningRatio: .85
8615
8638
  },
8616
8639
  history: {
@@ -8629,7 +8652,7 @@ function getWeappViteConfig() {
8629
8652
  alipayNpmMode: "node_modules"
8630
8653
  },
8631
8654
  hmr: {
8632
- runtime: "classic",
8655
+ runtime: "auto",
8633
8656
  sharedChunks: "auto",
8634
8657
  touchAppWxss: "auto",
8635
8658
  logLevel: "default",
@@ -8663,7 +8686,7 @@ function getWeappViteConfig() {
8663
8686
  dynamicImports: "preserve",
8664
8687
  logOptimization: true,
8665
8688
  forceDuplicatePatterns: [],
8666
- duplicateWarningBytes: 512 * 1024
8689
+ duplicateWarningBytes: 524288
8667
8690
  }
8668
8691
  };
8669
8692
  }
@@ -8763,6 +8786,7 @@ function createDefaultLoadConfigResult() {
8763
8786
  emitDefaultAutoImportOutputs: true,
8764
8787
  projectConfig: {},
8765
8788
  projectConfigPath: void 0,
8789
+ projectPrivateConfig: {},
8766
8790
  projectPrivateConfigPath: void 0,
8767
8791
  mpDistRoot: "",
8768
8792
  multiPlatform: resolveMultiPlatformConfig(false),
@@ -8862,6 +8886,7 @@ function createRuntimeState() {
8862
8886
  css: {
8863
8887
  importerToDependencies: /* @__PURE__ */ new Map(),
8864
8888
  dependencyToImporters: /* @__PURE__ */ new Map(),
8889
+ transformedSidecarSource: /* @__PURE__ */ new Map(),
8865
8890
  emittedSource: /* @__PURE__ */ new Map(),
8866
8891
  sidecarImports: /* @__PURE__ */ new Set()
8867
8892
  },
@@ -8937,6 +8962,7 @@ function resetRuntimeStateForFreshBuild(runtimeState) {
8937
8962
  const css = runtimeState.css;
8938
8963
  css.importerToDependencies.clear();
8939
8964
  css.dependencyToImporters.clear();
8965
+ css.transformedSidecarSource.clear();
8940
8966
  css.emittedSource.clear();
8941
8967
  const wxml = runtimeState.wxml;
8942
8968
  wxml.depsMap.clear();
@@ -10061,7 +10087,8 @@ function resolveTakeSharedChunkName(options) {
10061
10087
  function createSharedChunkNameFromKeys(keys) {
10062
10088
  const sanitize = (value) => value.replace(/[\\/]+/g, "_");
10063
10089
  const combination = keys.filter(Boolean).map(sanitize).sort().join("+");
10064
- return `${SHARED_CHUNK_VIRTUAL_PREFIX}/${combination ? `${combination}/` : ""}common`;
10090
+ const combinationSegment = combination ? `${combination}/` : "";
10091
+ return `${SHARED_CHUNK_VIRTUAL_PREFIX}/${combinationSegment}common`;
10065
10092
  }
10066
10093
  function resolveSharedChunkName(options) {
10067
10094
  const { id, ctx, relativeAbsoluteSrcRoot, subPackageRoots, strategy, sharedMode, resolveSharedMode, resolveSharedPath, forceDuplicateTester } = options;
@@ -10545,45 +10572,6 @@ function createSharedBuildConfig(configService, scanService) {
10545
10572
  return { build: { rolldownOptions: { output: createSharedBuildOutput(configService, () => scanService.subPackageMap.keys()) } } };
10546
10573
  }
10547
10574
  //#endregion
10548
- //#region src/runtime/statefulHmr/outputWriter.ts
10549
- /**
10550
- * @description 通过独立的 Vite write 阶段持久化 DevEngine 已生成的文件,不重新解析业务源码。
10551
- */
10552
- async function writeStatefulHmrOutput(outDir, output) {
10553
- const virtualEntry = "\0weapp-vite-stateful-hmr-output";
10554
- await build({
10555
- configFile: false,
10556
- logLevel: "silent",
10557
- build: {
10558
- emptyOutDir: false,
10559
- minify: false,
10560
- outDir,
10561
- rolldownOptions: { input: virtualEntry },
10562
- write: true
10563
- },
10564
- plugins: [{
10565
- name: "weapp-vite:stateful-hmr-output-writer",
10566
- resolveId(id) {
10567
- return id === virtualEntry ? virtualEntry : void 0;
10568
- },
10569
- load(id) {
10570
- return id === virtualEntry ? "export {}" : void 0;
10571
- },
10572
- buildStart() {
10573
- for (const item of output) this.emitFile({
10574
- type: "asset",
10575
- fileName: item.fileName.replaceAll("\\", "/"),
10576
- source: item.type === "chunk" ? item.code : item.source
10577
- });
10578
- },
10579
- generateBundle(_options, bundle) {
10580
- for (const [fileName, item] of Object.entries(bundle)) if (item.type === "chunk" && item.facadeModuleId === virtualEntry) delete bundle[fileName];
10581
- }
10582
- }],
10583
- root: path$1.dirname(outDir)
10584
- });
10585
- }
10586
- //#endregion
10587
10575
  //#region src/runtime/statefulHmr/runtimeSource.ts
10588
10576
  const statefulHmrRolldownRuntimeSource = `
10589
10577
  var BaseDevRuntime = DevRuntime;
@@ -10614,7 +10602,6 @@ class WeappViteDevRuntime extends BaseDevRuntime {
10614
10602
  registrationModuleId = '';
10615
10603
  createEsmInitializer = (id, initialize, _deduplicate, result) => () => {
10616
10604
  if (!initialize) return result;
10617
- if (!this.applyingPatch && this.patchedModules.has(id)) return result;
10618
10605
  const callback = initialize;
10619
10606
  initialize = undefined;
10620
10607
  const previousId = this.currentModuleId;
@@ -10626,7 +10613,6 @@ class WeappViteDevRuntime extends BaseDevRuntime {
10626
10613
  };
10627
10614
  createCjsInitializer = (id, initialize, _deduplicate, module) => () => {
10628
10615
  if (module) return module.exports;
10629
- if (!this.applyingPatch && this.patchedModules.has(id)) return this.loadExports(id);
10630
10616
  module = { exports: {} };
10631
10617
  const previousId = this.currentModuleId;
10632
10618
  this.currentModuleId = id;
@@ -10649,6 +10635,16 @@ class WeappViteDevRuntime extends BaseDevRuntime {
10649
10635
  this.registrationModuleId = id;
10650
10636
  return super.registerModule(id, exportsHolder);
10651
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
+ }
10652
10648
  beginPatch() { this.applyingPatch = true; }
10653
10649
  endPatch() { this.applyingPatch = false; }
10654
10650
  applyUpdates(boundaries) {
@@ -10942,7 +10938,7 @@ function createStatefulHmrControlSource(control) {
10942
10938
  globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY)}] = ${JSON.stringify(control)};
10943
10939
  (() => {
10944
10940
  const control = globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY)}];
10945
- if (globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY)}]) return;
10941
+ globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY)}]?.stop?.();
10946
10942
  let version = 0;
10947
10943
  let phase = 'registering';
10948
10944
  let pendingBatch;
@@ -11000,7 +10996,38 @@ globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY)}] = ${JSON.stri
11000
10996
  wx.reLaunch({ url: '/' + route + (query ? '?' + query : ''), complete: () => send('poll') });
11001
10997
  };
11002
10998
  globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY)}] = {
10999
+ lastApply: undefined,
11003
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
+ },
11004
11031
  receiveBatch(meta, apply) {
11005
11032
  if (phase === 'registering') {
11006
11033
  pendingBatch = { meta, apply };
@@ -11017,6 +11044,7 @@ globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY)}] = ${JSON.stri
11017
11044
  bridge.beginUpdate?.();
11018
11045
  try {
11019
11046
  apply();
11047
+ globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CLIENT_KEY)}].applyChangedModules(meta.changedIds);
11020
11048
  version = meta.targetVersion;
11021
11049
  phase = meta.compatible === false ? 'relaunching' : 'polling';
11022
11050
  } catch (error) {
@@ -11035,6 +11063,148 @@ globalThis[${JSON.stringify(WEAPP_VITE_STATEFUL_HMR_CONTROL_KEY)}] = ${JSON.stri
11035
11063
  `;
11036
11064
  }
11037
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
11038
11208
  //#region src/runtime/statefulHmr/serverState.ts
11039
11209
  function createStatefulHmrServerState(buildId) {
11040
11210
  return {
@@ -11052,6 +11222,7 @@ function transitionStatefulHmrServer(state, event) {
11052
11222
  return unchanged({
11053
11223
  ...state,
11054
11224
  deltas: [...state.deltas, {
11225
+ changedIds: event.changedIds,
11055
11226
  code: event.code,
11056
11227
  version
11057
11228
  }],
@@ -11196,10 +11367,11 @@ var StatefulHmrTransport = class {
11196
11367
  this.closed = true;
11197
11368
  this.respondToAll({ type: "rebuilding" });
11198
11369
  }
11199
- addDelta(code) {
11370
+ addDelta(code, changedIds) {
11200
11371
  this.apply({
11201
11372
  type: "delta-added",
11202
11373
  bytes: Buffer.byteLength(code),
11374
+ changedIds,
11203
11375
  code
11204
11376
  });
11205
11377
  this.respondToAll({ type: "changed" });
@@ -11318,8 +11490,10 @@ var StatefulHmrTransport = class {
11318
11490
  }
11319
11491
  };
11320
11492
  function renderBatch(batch, nonce) {
11493
+ const changedIds = [...new Set(batch.deltas.flatMap((delta) => delta.changedIds))];
11321
11494
  const metadata = {
11322
11495
  buildId: batch.buildId,
11496
+ changedIds,
11323
11497
  compatible: true,
11324
11498
  fromVersion: batch.fromVersion,
11325
11499
  targetVersion: batch.targetVersion
@@ -11342,7 +11516,7 @@ async function readBody(request) {
11342
11516
  for await (const chunk of request) {
11343
11517
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
11344
11518
  size += buffer.length;
11345
- if (size > 64 * 1024) throw new Error("stateful HMR request body is too large");
11519
+ if (size > 65536) throw new Error("stateful HMR request body is too large");
11346
11520
  chunks.push(buffer);
11347
11521
  }
11348
11522
  return Buffer.concat(chunks).toString("utf8");
@@ -11364,6 +11538,7 @@ var StatefulHmrViteAdapter = class {
11364
11538
  server;
11365
11539
  callbacks;
11366
11540
  bundledDev;
11541
+ initialOutputError;
11367
11542
  constructor(config, server, callbacks) {
11368
11543
  this.config = config;
11369
11544
  this.server = server;
@@ -11379,32 +11554,45 @@ var StatefulHmrViteAdapter = class {
11379
11554
  this.installPatches(bundledDev);
11380
11555
  this.installListener(bundledDev);
11381
11556
  }
11382
- async rebuild() {
11557
+ async rebuild(prepare) {
11383
11558
  const engine = this.bundledDev?._devEngine;
11384
- if (!engine) return;
11559
+ if (!engine) throw new Error("Vite DevEngine 未初始化,无法执行 stateful HMR 完整刷新。");
11560
+ await prepare?.();
11385
11561
  engine.triggerFullBuild();
11386
11562
  await engine.ensureLatestBuildOutput();
11387
11563
  }
11388
- registerBundleModules(output) {
11564
+ async registerBundleModules(output) {
11389
11565
  const moduleIds = /* @__PURE__ */ new Set();
11566
+ const payloadFilenames = [];
11390
11567
  for (const item of output) {
11391
11568
  if (item.type !== "chunk") continue;
11569
+ payloadFilenames.push(item.fileName);
11392
11570
  for (const match of item.code.matchAll(/registerModule\("([^"]+)"/g)) moduleIds.add(match[1]);
11393
11571
  for (const id of Object.keys(item.modules ?? {})) {
11394
11572
  const normalized = toStableModuleId(id, this.config.root);
11395
11573
  if (!moduleIds.has(normalized)) moduleIds.add(normalized);
11396
11574
  }
11397
11575
  }
11398
- this.registerModules([...moduleIds]);
11576
+ await this.registerModules([...moduleIds]);
11577
+ await this.markPayloadsDelivered(payloadFilenames);
11399
11578
  return moduleIds.size;
11400
11579
  }
11401
- registerPatchModules(code) {
11580
+ async registerPatchModules(code) {
11402
11581
  const moduleIds = /* @__PURE__ */ new Set();
11403
11582
  for (const match of code.matchAll(/create(?:Esm|Cjs)Initializer\("([^"]+)"/g)) moduleIds.add(match[1]);
11404
- this.registerModules([...moduleIds]);
11583
+ await this.registerModules([...moduleIds]);
11584
+ }
11585
+ async markPayloadDelivered(filename) {
11586
+ await this.markPayloadsDelivered([filename]);
11405
11587
  }
11406
- registerModules(moduleIds) {
11407
- if (moduleIds.length) this.bundledDev?._devEngine?.registerModules(clientId, moduleIds);
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);
11408
11596
  }
11409
11597
  installOptions(bundledDev) {
11410
11598
  const original = bundledDev.getRolldownOptions.bind(bundledDev);
@@ -11431,8 +11619,9 @@ var StatefulHmrViteAdapter = class {
11431
11619
  options.experimental ??= {};
11432
11620
  options.experimental.devMode = {
11433
11621
  ...typeof options.experimental.devMode === "object" ? options.experimental.devMode : {},
11434
- implement: statefulHmrRolldownRuntimeSource,
11435
- lazy: false
11622
+ implement: createStatefulHmrRolldownRuntimeSource(),
11623
+ lazy: false,
11624
+ skipCommonRuntimeInjection: true
11436
11625
  };
11437
11626
  return options;
11438
11627
  };
@@ -11440,14 +11629,23 @@ var StatefulHmrViteAdapter = class {
11440
11629
  installOutput(bundledDev) {
11441
11630
  const original = bundledDev.storeOutputFiles.bind(bundledDev);
11442
11631
  bundledDev.storeOutputFiles = (output) => {
11443
- original(output);
11444
- 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
+ }
11445
11640
  };
11446
11641
  }
11447
11642
  installPatches(bundledDev) {
11448
11643
  const original = bundledDev.handleHmrOutput.bind(bundledDev);
11449
11644
  bundledDev.handleHmrOutput = (client, files, output, info) => {
11450
- if (output.type === "Noop") return;
11645
+ if (output.type === "Noop") {
11646
+ this.callbacks.onPatch(files, output);
11647
+ return;
11648
+ }
11451
11649
  if (this.callbacks.onPatch(files, output)) original(client, files, output, info);
11452
11650
  };
11453
11651
  }
@@ -11458,7 +11656,9 @@ var StatefulHmrViteAdapter = class {
11458
11656
  bundledDev.clients.setupIfNeeded({ send: (payload) => this.handlePayload(payload) }, clientId);
11459
11657
  const engine = bundledDev._devEngine;
11460
11658
  if (!engine) throw new Error("Vite 未初始化微信状态保持 HMR 所需的 DevEngine。");
11659
+ await engine.registerClient?.(clientId);
11461
11660
  await engine.ensureCurrentBuildFinish();
11661
+ if (this.initialOutputError) throw this.initialOutputError;
11462
11662
  if ((await engine.getBundleState()).lastBuildErrored) throw new Error("微信状态保持 HMR 初次构建失败。");
11463
11663
  await this.callbacks.waitForInitialBundle();
11464
11664
  };
@@ -11497,8 +11697,8 @@ function toStableModuleId(id, root) {
11497
11697
  //#endregion
11498
11698
  //#region src/runtime/statefulHmr/session.ts
11499
11699
  const maxRetainedDeltaCount = 1e3;
11500
- const maxRetainedDeltaBytes = 16 * 1024 * 1024;
11501
- async function runStatefulHmrDev(ctx, buildOptions, restart) {
11700
+ const maxRetainedDeltaBytes = 16777216;
11701
+ async function runStatefulHmrDev(ctx, buildOptions, restart, snapshots) {
11502
11702
  const configService = ctx.configService;
11503
11703
  if (configService.platform !== "weapp") throw new Error("weapp.hmr.runtime=\"stateful-experimental\" 目前仅支持微信小程序平台。");
11504
11704
  let session;
@@ -11506,12 +11706,12 @@ async function runStatefulHmrDev(ctx, buildOptions, restart) {
11506
11706
  name: "weapp-vite:stateful-hmr-session",
11507
11707
  enforce: "post",
11508
11708
  configureServer(server) {
11509
- const currentSession = new StatefulHmrSession(ctx, server, restart);
11709
+ const currentSession = new StatefulHmrSession(ctx, server, restart, snapshots);
11510
11710
  session = currentSession;
11511
11711
  currentSession.install();
11512
11712
  },
11513
11713
  transform(code, id) {
11514
- 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;
11515
11715
  return `${id.endsWith(".vue") ? code : redirectNativeComponentRegistration(code)}\nif (import.meta.hot) import.meta.hot.accept();\n`;
11516
11716
  }
11517
11717
  };
@@ -11528,7 +11728,11 @@ async function runStatefulHmrDev(ctx, buildOptions, restart) {
11528
11728
  ...buildOptions.experimental ?? {},
11529
11729
  bundledDev: true
11530
11730
  },
11531
- plugins: [installPlugin, ...buildOptions.plugins ?? []],
11731
+ plugins: [
11732
+ createStatefulHmrSidecarPlugin(),
11733
+ installPlugin,
11734
+ ...buildOptions.plugins ?? []
11735
+ ],
11532
11736
  server: {
11533
11737
  ...buildOptions.server ?? {},
11534
11738
  host: "127.0.0.1",
@@ -11540,28 +11744,40 @@ async function runStatefulHmrDev(ctx, buildOptions, restart) {
11540
11744
  write: false
11541
11745
  }
11542
11746
  });
11543
- await server.listen();
11544
- if (!session) {
11545
- await server.close();
11546
- 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;
11547
11756
  }
11548
- await session.refreshControl();
11549
- return createWatcherAdapter(server, session);
11550
11757
  }
11551
11758
  var StatefulHmrSession = class {
11552
11759
  ctx;
11553
11760
  server;
11554
11761
  restart;
11762
+ snapshots;
11555
11763
  adapter;
11556
11764
  initialBundle = Promise.withResolvers();
11557
11765
  transport;
11766
+ fullBuildTimer;
11558
11767
  outputChain = Promise.resolve();
11559
- rebuildTimer;
11560
11768
  restartTimer;
11561
- 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) {
11562
11776
  this.ctx = ctx;
11563
11777
  this.server = server;
11564
11778
  this.restart = restart;
11779
+ this.snapshots = snapshots;
11780
+ this.replaceSnapshotAssets(snapshots.initial);
11565
11781
  this.transport = new StatefulHmrTransport(server, async (buildId, source) => {
11566
11782
  await this.enqueueOutput(async () => {
11567
11783
  if (!this.transport.isCurrentBuild(buildId)) return;
@@ -11582,10 +11798,13 @@ var StatefulHmrSession = class {
11582
11798
  install() {
11583
11799
  this.transport.install();
11584
11800
  this.adapter.install();
11801
+ this.ctx.onStatefulHmrSourceChange = this.sourceChangeListener;
11585
11802
  }
11586
11803
  async close() {
11587
- if (this.rebuildTimer) clearTimeout(this.rebuildTimer);
11804
+ if (this.fullBuildTimer) clearTimeout(this.fullBuildTimer);
11805
+ if (this.snapshotTimer) clearTimeout(this.snapshotTimer);
11588
11806
  if (this.restartTimer) clearTimeout(this.restartTimer);
11807
+ if (this.ctx.onStatefulHmrSourceChange === this.sourceChangeListener) this.ctx.onStatefulHmrSourceChange = void 0;
11589
11808
  this.transport.close();
11590
11809
  await this.outputChain;
11591
11810
  }
@@ -11598,13 +11817,28 @@ var StatefulHmrSession = class {
11598
11817
  }]);
11599
11818
  });
11600
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
+ }
11601
11833
  handleOutput(output) {
11602
11834
  this.enqueueOutput(async () => {
11603
11835
  const compatibleOutput = await transformOutput(output);
11604
11836
  const fullBuild = compatibleOutput.some((item) => item.fileName === "app.js");
11605
11837
  if (fullBuild) {
11838
+ mergeStatefulHmrSnapshotAssets(compatibleOutput, this.snapshotAssets.values());
11606
11839
  const buildId = this.transport.createBuildId();
11607
11840
  this.transport.commitFullBuild(buildId);
11841
+ stampStatefulHmrFullBuild(compatibleOutput, buildId);
11608
11842
  setAsset(compatibleOutput, WEAPP_VITE_STATEFUL_HMR_CONTROL_FILE, createStatefulHmrControlSource({
11609
11843
  ...this.transport.createControl(),
11610
11844
  buildId
@@ -11614,39 +11848,59 @@ var StatefulHmrSession = class {
11614
11848
  }
11615
11849
  await writeStatefulHmrOutput(this.ctx.configService.outDir, compatibleOutput);
11616
11850
  if (fullBuild) {
11617
- const moduleCount = this.adapter.registerBundleModules(compatibleOutput);
11851
+ const moduleCount = await this.adapter.registerBundleModules(compatibleOutput);
11618
11852
  this.server.config.logger.info(`[weapp-vite] 微信状态保持 HMR 已就绪(${moduleCount} modules)`);
11619
11853
  this.initialBundle.resolve();
11620
11854
  }
11621
11855
  });
11622
11856
  }
11623
11857
  handlePatch(files, output) {
11624
- if (!isSafeJavaScriptPatch(files, output, this.ctx.runtimeState.build.hmr.profile.dirtyReasonSummary)) {
11625
- 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);
11626
11862
  return false;
11627
11863
  }
11628
- this.adapter.registerPatchModules(output.code);
11629
- transformJavaScript(output.code, output.filename).then((code) => {
11864
+ this.adapter.registerPatchModules(output.code).then(async () => {
11865
+ const code = await transformJavaScript(output.code, output.filename);
11630
11866
  if (shouldResetStatefulHmrRetention(this.transport.retainedDeltaCount, this.transport.retainedDeltaBytes, Buffer.byteLength(code))) {
11631
11867
  this.requestFullBuild();
11632
11868
  return;
11633
11869
  }
11634
- this.transport.addDelta(code);
11870
+ this.transport.addDelta(code, output.changedIds ?? []);
11871
+ return this.adapter.markPayloadDelivered(output.filename);
11635
11872
  }).catch((error) => {
11636
11873
  this.server.config.logger.error("[weapp-vite] stateful HMR patch transform failed", { error });
11637
11874
  this.requestFullBuild();
11638
11875
  });
11639
11876
  return true;
11640
11877
  }
11641
- requestFullBuild() {
11642
- if (this.rebuildTimer) return;
11643
- this.rebuildTimer = setTimeout(() => {
11644
- this.rebuildTimer = void 0;
11645
- 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) => {
11646
11889
  this.server.config.logger.error("[weapp-vite] stateful HMR full rebuild failed", { error });
11647
11890
  });
11648
11891
  }, 100);
11649
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
+ }
11650
11904
  requestServerRestart() {
11651
11905
  if (this.restartTimer) return;
11652
11906
  this.restartTimer = setTimeout(() => {
@@ -11658,15 +11912,43 @@ var StatefulHmrSession = class {
11658
11912
  }
11659
11913
  enqueueOutput(task) {
11660
11914
  this.outputChain = this.outputChain.then(task, task).catch((error) => {
11661
- 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)}`);
11662
11916
  });
11663
11917
  return this.outputChain;
11664
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
+ }
11665
11935
  async waitForInitialBundle() {
11666
11936
  await this.initialBundle.promise;
11667
11937
  await this.outputChain;
11668
11938
  }
11669
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
+ }
11670
11952
  function createWatcherAdapter(server, session) {
11671
11953
  return {
11672
11954
  close: async () => {
@@ -11678,13 +11960,16 @@ function createWatcherAdapter(server, session) {
11678
11960
  }
11679
11961
  };
11680
11962
  }
11681
- function isStatefulHmrBoundary(id, srcRoot) {
11963
+ function isStatefulHmrBoundary(id, srcRoot, entryIds) {
11682
11964
  const sidecar = parseSidecarSourceRequest(id);
11683
11965
  const sourceId = sidecar?.kind === "script" ? sidecar.sourceId : id.includes("?") ? void 0 : id;
11684
11966
  if (!sourceId) return false;
11685
- const normalizedSourceId = sourceId.replaceAll("\\", "/");
11686
- const normalizedSrcRoot = srcRoot.replaceAll("\\", "/").replace(/\/$/, "");
11687
- 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;
11688
11973
  }
11689
11974
  function redirectNativeComponentRegistration(code) {
11690
11975
  if (!code.includes("Component")) return code;
@@ -11699,8 +11984,22 @@ function redirectNativeComponentRegistration(code) {
11699
11984
  } });
11700
11985
  return changed ? magicString.toString() : code;
11701
11986
  }
11702
- function isSafeJavaScriptPatch(files, output, dirtyReasonSummary = []) {
11703
- 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";
11704
12003
  }
11705
12004
  function shouldResetStatefulHmrRetention(retainedDeltaCount, retainedDeltaBytes, nextDeltaBytes) {
11706
12005
  return retainedDeltaCount >= maxRetainedDeltaCount || retainedDeltaBytes + nextDeltaBytes >= maxRetainedDeltaBytes;
@@ -11732,6 +12031,13 @@ function setAsset(output, fileName, source) {
11732
12031
  if (index >= 0) output[index] = asset;
11733
12032
  else output.push(asset);
11734
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
+ }
11735
12041
  //#endregion
11736
12042
  //#region src/runtime/watch/options.ts
11737
12043
  function resolvePollingWatchConfig(configService) {
@@ -12980,8 +13286,10 @@ function parseWxml(options) {
12980
13286
  };
12981
13287
  if (Array.isArray(autoImportComponents[componentName])) autoImportComponents[componentName].push(range);
12982
13288
  else autoImportComponents[componentName] = [range];
12983
- if (!excludeComponent(currentTagName)) if (Array.isArray(components[componentName])) components[componentName].push(range);
12984
- else components[componentName] = [range];
13289
+ if (!excludeComponent(currentTagName)) {
13290
+ if (Array.isArray(components[componentName])) components[componentName].push(range);
13291
+ else components[componentName] = [range];
13292
+ }
12985
13293
  }
12986
13294
  if (normalizeComponentTagName && shouldNormalizeTagName(name)) {
12987
13295
  const normalized = toKebabCaseTagName(name);
@@ -13139,7 +13447,8 @@ function getManagedTypeScriptConfig(ctx) {
13139
13447
  }
13140
13448
  async function readLegacyManagedTsconfigFile(filePath) {
13141
13449
  try {
13142
- const parsed = parse$1(await fs$1.readFile(filePath, "utf8"), void 0, true);
13450
+ const content = await fs$1.readFile(filePath, "utf8");
13451
+ const parsed = parse$1(content, void 0, true);
13143
13452
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return;
13144
13453
  return parsed;
13145
13454
  } catch {
@@ -13864,6 +14173,7 @@ function resetEmittedOutputCaches(runtimeState) {
13864
14173
  runtimeState.asset.scopedSlotGenerics.clear();
13865
14174
  runtimeState.build?.output?.emittedSource.clear();
13866
14175
  runtimeState.css.emittedSource.clear();
14176
+ runtimeState.css.transformedSidecarSource.clear();
13867
14177
  runtimeState.wxml.emittedCode.clear();
13868
14178
  }
13869
14179
  async function cleanOutputs(configService) {
@@ -13972,6 +14282,10 @@ function watchWorkers(configService, watcherService, workersDir) {
13972
14282
  }
13973
14283
  //#endregion
13974
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
+ }
13975
14289
  function resolveSnapshotSidecarDirtySummary(filePath, affectedEntries) {
13976
14290
  const normalizedFile = normalizeFsResolvedId(filePath);
13977
14291
  if (configSuffixes.find((suffix) => normalizedFile.endsWith(suffix))) return "json-sidecar:1";
@@ -14083,6 +14397,8 @@ function createSnapshotSidecarIgnoredMatcher(ctx) {
14083
14397
  }
14084
14398
  function createBuildService(ctx) {
14085
14399
  let lastHmrSlowTipProfileCount = 0;
14400
+ let devHmrRuntime;
14401
+ let devHmrRuntimeNoticeLogged = false;
14086
14402
  function createHmrProfileJsonSample(totalMs) {
14087
14403
  const profile = ctx.runtimeState.build.hmr.profile;
14088
14404
  const relativeFile = profile.file && ctx.configService ? ctx.configService.relativeCwd(profile.file) : void 0;
@@ -14649,14 +14965,34 @@ function createBuildService(ctx) {
14649
14965
  ...buildOptions.build ?? {},
14650
14966
  write: true
14651
14967
  };
14652
- if (target === "app" && configService.weappViteConfig.hmr?.runtime === "stateful-experimental") {
14653
- await build({
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 {
14987
+ const snapshotBuildOptions = {
14654
14988
  ...buildOptions,
14655
14989
  build: {
14656
14990
  ...buildOptions.build ?? {},
14657
14991
  watch: void 0
14658
14992
  }
14659
- });
14993
+ };
14994
+ const initialSnapshot = toStatefulHmrOutput(await build(snapshotBuildOptions));
14995
+ await configService.load(configService.loadOptions);
14660
14996
  resetRuntimeStateForFreshBuild(ctx.runtimeState);
14661
14997
  await scanService.loadAppEntry();
14662
14998
  scanService.loadSubPackages();
@@ -14671,14 +15007,49 @@ function createBuildService(ctx) {
14671
15007
  await statefulWatcher?.close();
14672
15008
  logger_default.info("检测到非兼容更新,正在重启微信状态保持 HMR 构建...");
14673
15009
  resetRuntimeStateForFreshBuild(ctx.runtimeState);
15010
+ await configService.load(configService.loadOptions);
14674
15011
  await scanService.loadAppEntry();
14675
15012
  scanService.loadSubPackages();
14676
15013
  await runDev(target);
14677
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
+ }
14678
15039
  }), workerPromise]);
14679
15040
  statefulWatcher = watcher;
14680
15041
  watcherService.setRollupWatcher(watcher, "/");
14681
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);
14682
15053
  }
14683
15054
  const snapshotBuildOptions = {
14684
15055
  ...buildOptions,
@@ -15918,6 +16289,7 @@ function configureBuildAndPlugins(options) {
15918
16289
  if (config.oxc !== false) {
15919
16290
  const oxcOptions = config.oxc ?? {};
15920
16291
  if (!Object.prototype.hasOwnProperty.call(oxcOptions, "tsconfig")) oxcOptions.tsconfig = false;
16292
+ if (config.esbuild !== false && config.esbuild?.jsx === "preserve" && !Object.prototype.hasOwnProperty.call(oxcOptions, "jsx")) oxcOptions.jsx = "preserve";
15921
16293
  config.oxc = oxcOptions;
15922
16294
  }
15923
16295
  const rdTransform = rdOptions.transform ?? {};
@@ -15934,13 +16306,15 @@ function configureBuildAndPlugins(options) {
15934
16306
  }
15935
16307
  if (resolvedLibConfig?.enabled) {
15936
16308
  const entryFileNames = createLibEntryFileNameResolver(resolvedLibConfig);
15937
- if (entryFileNames) if (Array.isArray(rdOptions.output)) rdOptions.output = rdOptions.output.map((output) => ({
15938
- ...output,
15939
- entryFileNames
15940
- }));
15941
- else {
15942
- const output = rdOptions.output ?? (rdOptions.output = {});
15943
- 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
+ }
15944
16318
  }
15945
16319
  }
15946
16320
  const rawPlugins = rdOptions.plugins;
@@ -16245,20 +16619,22 @@ function createLoadConfig(options) {
16245
16619
  }
16246
16620
  const loadedConfig = loaded?.config ?? {};
16247
16621
  let weappLoaded;
16248
- if (weappConfigFilePath) if (shouldReuseLoadedWeappConfig(weappConfigFilePath, loaded?.path)) weappLoaded = loaded;
16249
- else try {
16250
- weappLoaded = await loadConfigFileWithFallback({
16251
- command: isDev ? "serve" : "build",
16252
- mode
16253
- }, weappConfigFilePath, cwd, configLoader);
16254
- } catch (error) {
16255
- const cjsError = createCjsConfigLoadError({
16256
- error,
16257
- configPath: weappConfigFilePath,
16258
- cwd
16259
- });
16260
- if (cjsError) throw cjsError;
16261
- 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
+ }
16262
16638
  }
16263
16639
  const mergedLoadedConfig = weappLoaded?.config ? defu(weappLoaded.config, loadedConfig) : loadedConfig;
16264
16640
  const config = defu(inlineConfig, {
@@ -16347,6 +16723,7 @@ function createLoadConfig(options) {
16347
16723
  cwd
16348
16724
  });
16349
16725
  let projectConfig = {};
16726
+ let projectPrivateConfig = {};
16350
16727
  let projectConfigPathResolved;
16351
16728
  let projectPrivateConfigPathResolved;
16352
16729
  let mpDistRoot = "";
@@ -16362,6 +16739,7 @@ function createLoadConfig(options) {
16362
16739
  basePath,
16363
16740
  privatePath
16364
16741
  });
16742
+ projectPrivateConfig = await getProjectPrivateConfig(cwd, { privatePath });
16365
16743
  mpDistRoot = resolveProjectConfigRoot(projectConfig, platform) ?? "";
16366
16744
  if (!mpDistRoot) {
16367
16745
  const displayPath = formatProjectConfigPath(cwd, basePath ?? getProjectConfigFileName(platform));
@@ -16422,6 +16800,7 @@ function createLoadConfig(options) {
16422
16800
  emitDefaultAutoImportOutputs: opts.emitDefaultAutoImportOutputs ?? true,
16423
16801
  chunksConfigured,
16424
16802
  projectConfig,
16803
+ projectPrivateConfig,
16425
16804
  projectConfigPath: projectConfigPathResolved,
16426
16805
  projectPrivateConfigPath: projectPrivateConfigPathResolved,
16427
16806
  mpDistRoot,
@@ -17031,8 +17410,9 @@ function createDependenciesCache(ctx) {
17031
17410
  return resolveMainPackageDependencyScope(ctx);
17032
17411
  }
17033
17412
  function dependenciesCacheHash(root) {
17413
+ const configService = requireConfigService(ctx, "读取依赖缓存哈希前必须初始化 configService。");
17034
17414
  return objectHash({
17035
- dependencies: requireConfigService(ctx, "读取依赖缓存哈希前必须初始化 configService。").packageJson.dependencies ?? {},
17415
+ dependencies: configService.packageJson.dependencies ?? {},
17036
17416
  scope: serializeDependencyScope(resolveDependencyScope(root))
17037
17417
  });
17038
17418
  }
@@ -20608,6 +20988,7 @@ async function invalidateEntryForSidecar(ctx, filePath, event = "update") {
20608
20988
  }
20609
20989
  const isCssSidecar = Boolean(ext && watchedCssExts.has(ext));
20610
20990
  const isTemplateSidecar = Boolean(ext && watchedTemplateExts.has(ext));
20991
+ if (isCssSidecar) ctx.runtimeState?.css?.transformedSidecarSource.delete(normalizedPath);
20611
20992
  const sidecarCause = configSuffix ? "json-sidecar" : isCssSidecar ? "style-sidecar" : "sidecar-direct";
20612
20993
  const configService = ctx.configService;
20613
20994
  const relativeSource = configService.relativeCwd(normalizedPath);
@@ -22495,7 +22876,8 @@ function removeImplicitPagePreloads(bundle, options, snapshot = createBundleChun
22495
22876
  const pageChunkFileNames = /* @__PURE__ */ new Set();
22496
22877
  for (const entry of entriesMap.values()) {
22497
22878
  if (!entry || entry.type !== "page") continue;
22498
- const outputFile = changeFileExtension(configService.relativeAbsoluteSrcRoot(entry.path), ".js");
22879
+ const relative = configService.relativeAbsoluteSrcRoot(entry.path);
22880
+ const outputFile = changeFileExtension(relative, ".js");
22499
22881
  pageChunkFileNames.add(outputFile);
22500
22882
  }
22501
22883
  if (pageChunkFileNames.size === 0) return;
@@ -23401,6 +23783,10 @@ function hasCustomAutoRuleConfig(config) {
23401
23783
  function hasConfiguredNetworkDefaults(config) {
23402
23784
  return Boolean(config && typeof config === "object" && hasOwn$5(config, "networkDefaults"));
23403
23785
  }
23786
+ function resolveAutoPrelude(config) {
23787
+ if (!config || typeof config !== "object" || !hasOwn$5(config, "prelude")) return true;
23788
+ return config.prelude === true;
23789
+ }
23404
23790
  function resolveAutoRules(config) {
23405
23791
  if (hasCustomAutoRuleConfig(config)) return [{
23406
23792
  dependencyPatterns: resolveDependencyPatterns(config),
@@ -23439,7 +23825,7 @@ function resolveInjectRequestGlobalsOptions(config, packageJson) {
23439
23825
  return {
23440
23826
  mode: "auto",
23441
23827
  targets: [...matchedTargets],
23442
- prelude: config && typeof config === "object" ? config.prelude === true : false
23828
+ prelude: resolveAutoPrelude(config)
23443
23829
  };
23444
23830
  }
23445
23831
  function resolveRequestRuntimeOptions(input, packageJson, warn) {
@@ -23610,7 +23996,8 @@ function analyzeRequestGlobalsUsage(code, allowedTargets) {
23610
23996
  if (typeof specifier === "string" && specifier.length > 0) matchedSpecifiers.add(specifier);
23611
23997
  };
23612
23998
  try {
23613
- traverse(parseJsLike(usageSource), {
23999
+ const ast = parseJsLike(usageSource);
24000
+ traverse(ast, {
23614
24001
  ImportDeclaration(path) {
23615
24002
  addSpecifier(path.node?.source?.value);
23616
24003
  },
@@ -23794,18 +24181,20 @@ function removeConditionalBlock(start) {
23794
24181
  while (node && depth > 0) {
23795
24182
  if (node.type === "comment") {
23796
24183
  const directive = parseDirective(node.text);
23797
- if (directive) if (directive.type === "endif") {
23798
- depth -= 1;
23799
- const comment = node;
23800
- node = comment.next();
23801
- comment.remove();
23802
- continue;
23803
- } else {
23804
- depth += 1;
23805
- const comment = node;
23806
- node = comment.next();
23807
- comment.remove();
23808
- 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
+ }
23809
24198
  }
23810
24199
  }
23811
24200
  const next = node.next();
@@ -23827,10 +24216,12 @@ const postCreator = (options = { platform: "weapp" }) => {
23827
24216
  atRule.name = "import";
23828
24217
  return;
23829
24218
  }
23830
- if (atRule.name === `wv-if`) if (![...atRule.params.matchAll(/\(([^)]+)\)/g)].some((match) => {
23831
- return match[1].trim() === platform;
23832
- })) atRule.remove();
23833
- 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
+ }
23834
24225
  },
23835
24226
  Comment(comment) {
23836
24227
  const directive = parseDirective(comment.text);
@@ -24155,6 +24546,16 @@ async function readStyleGraphSource(stylePath, fallback) {
24155
24546
  return fallback;
24156
24547
  }
24157
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
+ }
24158
24559
  function resolveOutputStyleFileName(configService, stylePath) {
24159
24560
  return configService.relativeOutputPath(changeFileExtension(stylePath, configService.outputExtensions.wxss));
24160
24561
  }
@@ -24258,7 +24659,7 @@ async function emitStyleSidecarAsset(ctx, pluginCtx, bundle, stylePath, resolved
24258
24659
  const { configService } = ctx;
24259
24660
  const fileName = resolveOutputStyleFileName(configService, stylePath);
24260
24661
  if (!fileName) return false;
24261
- const rawCss = await fs$1.readFile(stylePath, "utf8");
24662
+ const rawCss = await resolveMemoryStyleSource(ctx, stylePath) ?? await fs$1.readFile(stylePath, "utf8");
24262
24663
  const { css, dependencies } = await preprocessStyleSource(rawCss, stylePath, resolvedConfig);
24263
24664
  syncCssImportDependencies(ctx, stylePath, rawCss, dependencies);
24264
24665
  if (typeof pluginCtx.addWatchFile === "function") for (const dependency of dependencies) pluginCtx.addWatchFile(normalizeWatchPath(dependency));
@@ -24314,7 +24715,7 @@ async function handleBundleEntry(ctx, bundle, bundleKey, asset, configService, s
24314
24715
  const normalizedFileName = toPosixPath(fileName);
24315
24716
  const freshHmrStyleSourcePath = resolveFreshHmrStyleSourcePath(ctx, normalizedFileName);
24316
24717
  const preprocessId = freshHmrStyleSourcePath ?? absOriginal;
24317
- const preprocessInput = freshHmrStyleSourcePath ? await readStyleGraphSource(freshHmrStyleSourcePath, canonicalSource) : canonicalSource;
24718
+ const preprocessInput = freshHmrStyleSourcePath ? await resolveMemoryStyleSource(ctx, freshHmrStyleSourcePath) ?? await readStyleGraphSource(freshHmrStyleSourcePath, canonicalSource) : canonicalSource;
24318
24719
  const { css, dependencies } = await preprocessStyleSource(preprocessInput, preprocessId, resolvedConfig, { enabled: shouldPreprocessWithVite(preprocessId) });
24319
24720
  syncCssImportDependencies(ctx, preprocessId, freshHmrStyleSourcePath ? preprocessInput : await readStyleGraphSource(absOriginal, canonicalSource), dependencies);
24320
24721
  if (typeof this.addWatchFile === "function") for (const dependency of dependencies) this.addWatchFile(normalizeWatchPath(dependency));
@@ -24461,6 +24862,23 @@ function css(ctx) {
24461
24862
  await generateBundleSharedCss.call(this, ctx, configService, bundle, styleAnalysis, resolvedConfig);
24462
24863
  await emitCollectedStyleSidecars.call(this, ctx, rolldownBundle, resolvedConfig);
24463
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
+ }
24464
24882
  }];
24465
24883
  }
24466
24884
  //#endregion
@@ -24883,12 +25301,6 @@ function setRequireImportLiteral(node, nextValue) {
24883
25301
  function normalizeRelativeChunkImport(fileName, importee) {
24884
25302
  return toPosixPath(path.normalize(path.join(path.dirname(fileName), importee)));
24885
25303
  }
24886
- function prependChunkCodePreservingDirectives(code, injectedCode) {
24887
- const directiveMatch = code.match(DIRECTIVE_PROLOGUE_RE);
24888
- if (!directiveMatch?.[0]) return `${injectedCode}\n${code}`;
24889
- const directivePrologue = directiveMatch[0];
24890
- return `${directivePrologue}${injectedCode}\n${code.slice(directivePrologue.length)}`;
24891
- }
24892
25304
  //#endregion
24893
25305
  //#region src/utils/weapi.ts
24894
25306
  function getWeapiGlobalRootCandidateItems() {
@@ -25132,14 +25544,14 @@ function composeSourceMaps(transformedMap, originalMap) {
25132
25544
  }
25133
25545
  //#endregion
25134
25546
  //#region src/plugins/core/lifecycle/emit/rewrite/sourcemap.ts
25135
- function applyMagicStringChunkRewrite(chunk, magicString) {
25547
+ function applyMagicStringChunkRewrite(chunk, magicString, options) {
25136
25548
  const previousCode = chunk.code;
25137
25549
  const nextCode = magicString.toString();
25138
25550
  if (nextCode === previousCode) return false;
25139
25551
  const previousMap = normalizeEncodedSourceMapLike(chunk.map);
25140
25552
  chunk.code = nextCode;
25141
25553
  if (previousMap) chunk.map = composeSourceMaps(magicString.generateMap({
25142
- hires: "boundary",
25554
+ hires: options?.hires ?? "boundary",
25143
25555
  includeContent: true,
25144
25556
  source: chunk.fileName
25145
25557
  }), previousMap);
@@ -25328,6 +25740,9 @@ const REQUEST_GLOBAL_APP_MODULE_KEY_PREFIX = "__weappViteRequestGlobalsModule:";
25328
25740
  function resolveChunkRequestGlobalsTargets(code, targets, mode) {
25329
25741
  return mode === "auto" ? resolveAutoRequestGlobalsTargets(code, targets) : targets;
25330
25742
  }
25743
+ function resolvePreludeRequestGlobalsTargets(code, targets, mode) {
25744
+ return mode === "auto" ? targets : resolveChunkRequestGlobalsTargets(code, targets, mode);
25745
+ }
25331
25746
  function collectTopLevelDeclaredIdentifiers(code) {
25332
25747
  const identifiers = /* @__PURE__ */ new Set();
25333
25748
  try {
@@ -25425,8 +25840,9 @@ function injectRequestGlobalsBundleRuntime(bundle, targets, mode, networkDefault
25425
25840
  const topLevelDeclaredIdentifiers = collectTopLevelDeclaredIdentifiers(chunk.code);
25426
25841
  const passiveBindingsCode = createRequestGlobalsPassiveBindingsCode(chunkTargets, bindingTargets.filter((target) => !topLevelDeclaredIdentifiers.has(target)));
25427
25842
  const syntheticExportCode = exportName ? "" : `Object.defineProperty(exports,${JSON.stringify(REQUEST_GLOBAL_SYNTHETIC_EXPORT_NAME)},{enumerable:false,get:function(){return ${installerName}}});`;
25843
+ const installerOptionsCode = createRequestGlobalsInstallerOptionsCode(chunkTargets, networkDefaults);
25428
25844
  const runtimeBindingCode = [
25429
- `const ${REQUEST_GLOBAL_BUNDLE_HOST_REF} = ${installerName}(${createRequestGlobalsInstallerOptionsCode(chunkTargets, networkDefaults)}) || globalThis`,
25845
+ `const ${REQUEST_GLOBAL_BUNDLE_HOST_REF} = ${installerName}(${installerOptionsCode}) || globalThis`,
25430
25846
  ...bindingTargets.map((target) => `${REQUEST_GLOBAL_ACTUALS_KEY}[${JSON.stringify(target)}] = ${REQUEST_GLOBAL_BUNDLE_HOST_REF}.${target}`),
25431
25847
  ...bindingTargets.map((target) => `try{globalThis[${JSON.stringify(target)}]=${REQUEST_GLOBAL_BUNDLE_HOST_REF}.${target}}catch{}`)
25432
25848
  ].join(";");
@@ -25750,7 +26166,7 @@ function inlineRequestGlobalsAppRegisteredInstallerChunks(bundle, installerChunk
25750
26166
  appChunk.code = `${inlinedModules.join("\n")}\n${appChunk.code}`;
25751
26167
  }
25752
26168
  function createRequestGlobalsPreludeCode(chunk, installerChunks, targets, mode, networkDefaults) {
25753
- const chunkTargets = resolveChunkRequestGlobalsTargets(chunk.code, targets, mode);
26169
+ const chunkTargets = resolvePreludeRequestGlobalsTargets(chunk.code, targets, mode);
25754
26170
  if (chunkTargets.length === 0 || chunk.code.includes(REQUEST_GLOBAL_PRELUDE_MARKER)) return;
25755
26171
  const bindingTargets = resolveRequestGlobalsBindingTargets(chunkTargets);
25756
26172
  if (bindingTargets.length === 0) return;
@@ -25778,13 +26194,22 @@ function createRequestGlobalsPreludeCode(chunk, installerChunks, targets, mode,
25778
26194
  ].join("\n");
25779
26195
  }
25780
26196
  function createRequestGlobalsPreludeAssetCode(preludeFileName, chunk, installerChunks, targets, mode, networkDefaults) {
25781
- const chunkTargets = resolveChunkRequestGlobalsTargets(chunk.code, targets, mode);
26197
+ const chunkTargets = resolvePreludeRequestGlobalsTargets(chunk.code, targets, mode);
25782
26198
  if (chunkTargets.length === 0) return;
25783
26199
  const bindingTargets = resolveRequestGlobalsBindingTargets(chunkTargets);
25784
26200
  if (bindingTargets.length === 0) return;
25785
26201
  const installerImport = resolveRequestGlobalsInstallerImport(chunk, installerChunks);
25786
- if (!installerImport?.installerChunkFileName || !installerImport.exportName) return;
25787
- 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`;
25788
26213
  return [
25789
26214
  `/* ${REQUEST_GLOBAL_PRELUDE_MARKER} */`,
25790
26215
  `(() => {`,
@@ -25907,9 +26332,20 @@ function createAppPreludeRequireStatement(chunkFileName, preludeFileName) {
25907
26332
  const requestPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
25908
26333
  return `/* ${APP_PRELUDE_REQUIRE_MARKER} */require(${JSON.stringify(requestPath)})`;
25909
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
+ }
25910
26346
  function emitAppPreludeRequireAssets(bundle, appPreludeCode, state, requestGlobalsPreludeOptions, emitFile) {
25911
26347
  const preservedRequestGlobalsInstallerChunks = /* @__PURE__ */ new Set();
25912
- if (!appPreludeCode) return preservedRequestGlobalsInstallerChunks;
26348
+ if (!appPreludeCode && !requestGlobalsPreludeOptions.enabled) return preservedRequestGlobalsInstallerChunks;
25913
26349
  const preludeFileNames = /* @__PURE__ */ new Set();
25914
26350
  if (state.subPackageMeta?.subPackage.root) preludeFileNames.add(`${state.subPackageMeta.subPackage.root}/${APP_PRELUDE_REQUIRE_FILE_BASENAME}`);
25915
26351
  else {
@@ -25921,7 +26357,8 @@ function emitAppPreludeRequireAssets(bundle, appPreludeCode, state, requestGloba
25921
26357
  const scopeChunks = Object.values(bundle).filter((output) => {
25922
26358
  return output?.type === "chunk" && resolveAppPreludeRequireFileName(output.fileName, state) === fileName;
25923
26359
  });
25924
- 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;
25925
26362
  if (requestGlobalsPreludeCode) {
25926
26363
  const installerImport = scopeChunks.map((chunk) => resolveRequestGlobalsInstallerImport(chunk, requestGlobalsPreludeOptions.installerChunks)).find(Boolean);
25927
26364
  if (installerImport?.installerChunkFileName) preservedRequestGlobalsInstallerChunks.add(installerImport.installerChunkFileName);
@@ -25939,16 +26376,18 @@ function injectAppPreludeCode(bundle, appPreludeCode, options, state, requestGlo
25939
26376
  let preservedRequestGlobalsInstallerChunks = /* @__PURE__ */ new Set();
25940
26377
  if (!options.enabled) return preservedRequestGlobalsInstallerChunks;
25941
26378
  const entryChunkFileNames = options.mode === "entry" ? collectAppPreludeEntryChunkFileNames(state) : void 0;
25942
- 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);
25943
26380
  for (const output of Object.values(bundle)) {
25944
26381
  if (output?.type !== "chunk") continue;
25945
26382
  const chunk = output;
25946
26383
  if (chunk.code.includes(APP_PRELUDE_CHUNK_MARKER) || chunk.code.includes(APP_PRELUDE_REQUIRE_MARKER)) continue;
25947
26384
  const isTargetEntryChunk = chunk.isEntry === true || entryChunkFileNames?.has(chunk.fileName) === true;
25948
26385
  if (entryChunkFileNames && !isTargetEntryChunk) continue;
25949
- 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");
25950
26389
  if (!injectedCode) continue;
25951
- chunk.code = prependChunkCodePreservingDirectives(chunk.code, injectedCode);
26390
+ prependChunkCodeWithSourcemap(chunk, injectedCode);
25952
26391
  }
25953
26392
  return preservedRequestGlobalsInstallerChunks;
25954
26393
  }
@@ -26362,7 +26801,7 @@ function createGenerateBundleHook(state, isPluginBuild) {
26362
26801
  collapseRequestGlobalsRuntimeSupportChunk(rolldownBundle);
26363
26802
  }
26364
26803
  const appPreludePath = scanService.appEntry?.preludePath;
26365
- const shouldInjectRequestGlobalsPrelude = injectRequestGlobalsOptions?.prelude === true;
26804
+ const shouldInjectRequestGlobalsPrelude = injectRequestGlobalsOptions?.prelude === true && Boolean(scanService.appEntry || subPackageMeta);
26366
26805
  const appPreludeOptions = resolveAppPreludeOptions(state);
26367
26806
  const preservedRequestGlobalsInstallerChunks = appPreludeOptions.enabled && Boolean(appPreludePath) || shouldInjectRequestGlobalsPrelude ? injectAppPreludeCode(rolldownBundle, await resolveAppPreludeCode(appPreludePath, {
26368
26807
  importMetaDefineRegistry: configService.importMetaDefineRegistry,
@@ -27415,7 +27854,8 @@ async function normalizeWatchEvent(id, event, options) {
27415
27854
  if (event === "create" && await fs$1.pathExists(id)) {
27416
27855
  const ext = path.extname(id);
27417
27856
  if (ext) {
27418
- const primaryScript = await findJsEntry(id.slice(0, -ext.length));
27857
+ const basePath = id.slice(0, -ext.length);
27858
+ const primaryScript = await findJsEntry(basePath);
27419
27859
  const primaryScriptId = primaryScript.path ? normalizeFsResolvedId(primaryScript.path) : "";
27420
27860
  if (primaryScriptId && options.resolvedEntryMap.has(primaryScriptId)) return "update";
27421
27861
  }
@@ -27707,6 +28147,7 @@ function createWatchChangeHook(state) {
27707
28147
  watchToDirtyMs: performance.now() - startedAt,
27708
28148
  dirtyReasonSummary
27709
28149
  };
28150
+ state.ctx.onStatefulHmrSourceChange?.(normalizedId, dirtyReasonSummary ?? []);
27710
28151
  };
27711
28152
  }
27712
28153
  //#endregion
@@ -28218,13 +28659,14 @@ function resolveClassStylePackageRoot(ctx, relativeBase, configService) {
28218
28659
  return "";
28219
28660
  }
28220
28661
  function resolveClassStyleWxsLocationForBase(ctx, relativeBase, extension, configService) {
28662
+ const packageRoot = configService.weappViteConfig?.vue?.template?.classStyleWxsShared ?? true ? resolveClassStylePackageRoot(ctx, relativeBase, configService) : (() => {
28663
+ const dir = path.posix.dirname(toPosixPath(relativeBase));
28664
+ return dir === "." ? "" : dir;
28665
+ })();
28221
28666
  return resolveClassStyleWxsLocation({
28222
28667
  relativeBase,
28223
28668
  extension,
28224
- packageRoot: configService.weappViteConfig?.vue?.template?.classStyleWxsShared ?? true ? resolveClassStylePackageRoot(ctx, relativeBase, configService) : (() => {
28225
- const dir = path.posix.dirname(toPosixPath(relativeBase));
28226
- return dir === "." ? "" : dir;
28227
- })()
28669
+ packageRoot
28228
28670
  });
28229
28671
  }
28230
28672
  //#endregion
@@ -29345,7 +29787,8 @@ async function finalizeTransformEntryScript(options) {
29345
29787
  }
29346
29788
  function finalizeTransformEntryCode(options) {
29347
29789
  const { result, filename, styleBlocks, isPage, isApp, isDev, sourceMap = true, hmrStyleToken } = options;
29348
- const returned = new MagicString(result.script ?? "");
29790
+ const script = result.script ?? "";
29791
+ const returned = new MagicString(script);
29349
29792
  let hasMutation = false;
29350
29793
  if (styleBlocks?.length) {
29351
29794
  const styleImports = buildWeappVueStyleRequests(filename, styleBlocks, { hmrToken: hmrStyleToken }).map((request) => `import ${JSON.stringify(request)};\n`).join("");
@@ -29888,7 +30331,8 @@ function hasUnresolvedModuleImportDeclaration(script) {
29888
30331
  if (!script?.includes("import")) return false;
29889
30332
  try {
29890
30333
  let hasUnresolvedImport = false;
29891
- traverse(parseJsLike(script), { ImportDeclaration(path) {
30334
+ const ast = parseJsLike(script);
30335
+ traverse(ast, { ImportDeclaration(path) {
29892
30336
  const source = path.node.source.value;
29893
30337
  if (typeof source === "string" && !(source === "wevu" || source === "wevu/router" || source === "wevu/store" || source === "wevu/api" || source === "wevu/fetch" || source === "wevu/web-apis" || source === "wevu/internal-runtime" || source === "wevu/internal-reactivity" || source === "wevu/internal-template" || Object.values(WEAPP_VITE_RUNTIME_VIRTUAL_IDS).includes(source))) {
29894
30338
  hasUnresolvedImport = true;
@@ -31156,15 +31600,17 @@ function hasTsconfigReference(tsconfig, target) {
31156
31600
  return false;
31157
31601
  }
31158
31602
  }
31159
- function resolveDefaultRolldownTsconfig(cwd) {
31160
- const appTsconfig = path.resolve(cwd, ".weapp-vite/tsconfig.app.json");
31161
- 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");
31162
31608
  if (existsSync(appTsconfig)) return appTsconfig;
31163
31609
  if (hasTsconfigReference(rootTsconfig, appTsconfig)) return appTsconfig;
31164
31610
  if (existsSync(rootTsconfig)) return rootTsconfig;
31165
31611
  }
31166
31612
  function normalizeInlineConfigAfterDefu(inline, options) {
31167
- const { cwd, ctx, platform, rolldownOptions, subPackageMeta } = options;
31613
+ const { cwd, configFilePath, ctx, platform, rolldownOptions, subPackageMeta } = options;
31168
31614
  const build = inline.build ?? (inline.build = {});
31169
31615
  const userRolldownOptions = build.rolldownOptions;
31170
31616
  const mergedRolldownOptions = {
@@ -31175,8 +31621,11 @@ function normalizeInlineConfigAfterDefu(inline, options) {
31175
31621
  ...userRolldownOptions?.output ?? {}
31176
31622
  }
31177
31623
  };
31178
- const defaultTsconfig = resolveDefaultRolldownTsconfig(cwd);
31179
- 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;
31180
31629
  build.rolldownOptions = mergedRolldownOptions;
31181
31630
  inline.define = {
31182
31631
  ...inline.define ?? {},
@@ -31206,7 +31655,7 @@ function resolveMiniprogramWatchInclude(options) {
31206
31655
  });
31207
31656
  }
31208
31657
  function mergeMiniprogram(options, ...configs) {
31209
- 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;
31210
31659
  const platform = ctx.configService?.platform;
31211
31660
  applyRuntimePlatform("miniprogram");
31212
31661
  const createMiniprogramCustomLogger = () => {
@@ -31275,6 +31724,7 @@ function mergeMiniprogram(options, ...configs) {
31275
31724
  });
31276
31725
  normalizeInlineConfigAfterDefu(inline, {
31277
31726
  cwd,
31727
+ configFilePath,
31278
31728
  ctx,
31279
31729
  platform,
31280
31730
  rolldownOptions,
@@ -31297,6 +31747,7 @@ function mergeMiniprogram(options, ...configs) {
31297
31747
  if (inlineConfig.build) delete inlineConfig.build.watch;
31298
31748
  normalizeInlineConfigAfterDefu(inlineConfig, {
31299
31749
  cwd,
31750
+ configFilePath,
31300
31751
  ctx,
31301
31752
  platform,
31302
31753
  rolldownOptions,
@@ -31452,6 +31903,7 @@ function createMergeFactories(options) {
31452
31903
  srcRoot: currentOptions.srcRoot,
31453
31904
  mpDistRoot: currentOptions.mpDistRoot,
31454
31905
  configFileDependencies: currentOptions.configFileDependencies,
31906
+ configFilePath: currentOptions.configFilePath,
31455
31907
  packageJson: currentOptions.packageJson,
31456
31908
  isDev: currentOptions.isDev,
31457
31909
  applyRuntimePlatform,
@@ -31661,6 +32113,7 @@ function createConfigService(ctx) {
31661
32113
  isDev: false,
31662
32114
  emitDefaultAutoImportOutputs: true,
31663
32115
  projectConfig: {},
32116
+ projectPrivateConfig: {},
31664
32117
  config: {},
31665
32118
  loadOptions: input,
31666
32119
  packageJson: {},
@@ -31772,6 +32225,9 @@ function createConfigService(ctx) {
31772
32225
  get projectConfig() {
31773
32226
  return options.projectConfig;
31774
32227
  },
32228
+ get projectPrivateConfig() {
32229
+ return options.projectPrivateConfig;
32230
+ },
31775
32231
  get projectConfigPath() {
31776
32232
  return options.projectConfigPath;
31777
32233
  },
@@ -31980,7 +32436,8 @@ function resolveScanAppPreludeBasename(absoluteSrcRoot) {
31980
32436
  return path.resolve(absoluteSrcRoot, "app.prelude");
31981
32437
  }
31982
32438
  async function resolveScanAppPreludePath(absoluteSrcRoot) {
31983
- return (await findJsEntry(resolveScanAppPreludeBasename(absoluteSrcRoot))).path;
32439
+ const basename = resolveScanAppPreludeBasename(absoluteSrcRoot);
32440
+ return (await findJsEntry(basename)).path;
31984
32441
  }
31985
32442
  function resolveScanPluginBasename(absolutePluginRoot) {
31986
32443
  return absolutePluginRoot ? path.resolve(absolutePluginRoot, "plugin") : void 0;
@@ -32080,14 +32537,15 @@ async function loadAppEntry(ctx, scanState) {
32080
32537
  const { path: appEntryPath } = appEntry;
32081
32538
  let configFromVue;
32082
32539
  if (!appConfigFile && vueAppPath) {
32083
- const { extractConfigFromVue } = await import("./file-DDpy9efy.mjs");
32540
+ const { extractConfigFromVue } = await import("./file-BTZg_nyD.mjs");
32084
32541
  configFromVue = await extractConfigFromVue(vueAppPath);
32085
32542
  if (configFromVue) appConfigFile = vueAppPath;
32086
32543
  }
32087
32544
  if (appEntryPath && vueAppPath) warnOnce(`[app] 检测到 ${path.basename(appEntryPath)} 与 ${path.basename(vueAppPath)} 同时存在,当前将优先使用 ${path.basename(appEntryPath)} 作为应用入口,${path.basename(vueAppPath)} 将被忽略。`);
32088
32545
  if (discoveredAppConfigFile && vueAppPath) warnOnce(`[app] 检测到 ${path.basename(discoveredAppConfigFile)} 与 ${path.basename(vueAppPath)} 同时存在,当前将优先使用 ${path.basename(discoveredAppConfigFile)} 作为应用配置来源,${path.basename(vueAppPath)} 中的 app 配置不会生效。`);
32089
32546
  if (ctx.configService.absolutePluginRoot) {
32090
- const { path: pluginConfigFile } = await findJsonEntry(resolveScanPluginBasename(ctx.configService.absolutePluginRoot));
32547
+ const pluginBasename = resolveScanPluginBasename(ctx.configService.absolutePluginRoot);
32548
+ const { path: pluginConfigFile } = await findJsonEntry(pluginBasename);
32091
32549
  if (pluginConfigFile) {
32092
32550
  scanState.pluginJson = await ctx.jsonService.read(pluginConfigFile);
32093
32551
  scanState.pluginJsonPath = pluginConfigFile;