@mpcore/simulator 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,12 +1,13 @@
1
- import { dirname, join, normalize, posix, relative } from "pathe";
2
- import { WEVU_NATIVE_INSTANCE_KEY, WEVU_PAGE_SCROLL_EVENT_CONTRACT_KEY, WEVU_ROUTE_EVENT_CONTRACT_KEY } from "@weapp-core/constants";
1
+ import { dirname, isAbsolute, join, normalize, posix, relative } from "pathe";
2
+ import { HEADLESS_PROTOCOL_UNSUPPORTED, WEVU_NATIVE_INSTANCE_KEY, WEVU_PAGE_SCROLL_EVENT_CONTRACT_KEY, WEVU_ROUTE_EVENT_CONTRACT_KEY } from "@weapp-core/constants";
3
+ import { parse, parseExpression } from "@babel/parser";
3
4
  import fs from "node:fs";
4
5
  import path from "node:path";
5
- import { parseExpression } from "@babel/parser";
6
6
  import postcss from "postcss";
7
+ import { normalizeRichTextNodes } from "@weapp-core/shared/rich-text";
7
8
  import { parseDocument } from "htmlparser2";
8
9
  import { selectAll } from "css-select";
9
- import { AttributeAction, SelectorType, parse } from "css-what";
10
+ import { AttributeAction, SelectorType, parse as parse$1 } from "css-what";
10
11
  import * as fontoxpath from "fontoxpath";
11
12
  import vm from "node:vm";
12
13
  //#region src/host/behavior.ts
@@ -839,6 +840,360 @@ function resolveMiniProgramModule(importer, request, miniprogramRootPath, hasFil
839
840
  }
840
841
  }
841
842
  //#endregion
843
+ //#region src/runtime/moduleSyntax/ast.ts
844
+ function isSyntaxNode(value) {
845
+ return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
846
+ }
847
+ function childNodes(node) {
848
+ const children = [];
849
+ for (const [key, value] of Object.entries(node)) for (const child of Array.isArray(value) ? value : [value]) if (isSyntaxNode(child)) children.push({
850
+ key,
851
+ node: child
852
+ });
853
+ return children;
854
+ }
855
+ function patternIdentifiers(node) {
856
+ if (node.type === "Identifier") return [node];
857
+ const keys = node.type === "ObjectPattern" ? ["properties"] : node.type === "ObjectProperty" ? ["value"] : node.type === "AssignmentPattern" ? ["left"] : node.type === "RestElement" ? ["argument"] : ["elements"];
858
+ return childNodes(node).filter((child) => keys.includes(child.key)).flatMap((child) => patternIdentifiers(child.node));
859
+ }
860
+ function createUniqueName(root) {
861
+ const used = /* @__PURE__ */ new Set();
862
+ const visit = (node) => {
863
+ if (node.type === "Identifier" && typeof node.name === "string") used.add(node.name);
864
+ childNodes(node).forEach((child) => visit(child.node));
865
+ };
866
+ visit(root);
867
+ let index = 0;
868
+ return () => {
869
+ let name;
870
+ do
871
+ name = `__mpcoreEsm${index++}`;
872
+ while (used.has(name));
873
+ used.add(name);
874
+ return name;
875
+ };
876
+ }
877
+ function applySourceEdits(source, edits) {
878
+ for (const edit of edits.toSorted((left, right) => right.start - left.start || right.end - left.end)) source = source.slice(0, edit.start) + edit.content + source.slice(edit.end);
879
+ return source;
880
+ }
881
+ //#endregion
882
+ //#region src/runtime/moduleSyntax/bindings.ts
883
+ const functionTypes = /* @__PURE__ */ new Set([
884
+ "FunctionDeclaration",
885
+ "FunctionExpression",
886
+ "ArrowFunctionExpression",
887
+ "ObjectMethod",
888
+ "ClassMethod",
889
+ "ClassPrivateMethod"
890
+ ]);
891
+ const blockTypes = /* @__PURE__ */ new Set([
892
+ "BlockStatement",
893
+ "CatchClause",
894
+ "ForStatement",
895
+ "ForInStatement",
896
+ "ForOfStatement",
897
+ "SwitchStatement",
898
+ "StaticBlock"
899
+ ]);
900
+ /** 按词法作用域改写导入引用;声明、键名及同名局部变量保持原样。 */
901
+ function rewriteImportReferences(root, imports, bindingName) {
902
+ const scopes = /* @__PURE__ */ new WeakMap();
903
+ const declarations = /* @__PURE__ */ new WeakSet();
904
+ const moduleScope = {
905
+ bindings: /* @__PURE__ */ new Set(),
906
+ variable: true,
907
+ functionDepth: 0
908
+ };
909
+ const declare = (pattern, scope) => {
910
+ if (!isSyntaxNode(pattern)) return;
911
+ for (const identifier of patternIdentifiers(pattern)) {
912
+ scope.bindings.add(String(identifier.name));
913
+ declarations.add(identifier);
914
+ }
915
+ };
916
+ const visit = (node, inherited, parent, key) => {
917
+ let scope = inherited;
918
+ if (functionTypes.has(node.type)) {
919
+ if (node.type === "FunctionDeclaration") declare(node.id, inherited);
920
+ scope = {
921
+ parent: inherited,
922
+ bindings: /* @__PURE__ */ new Set(),
923
+ variable: false,
924
+ functionDepth: inherited.functionDepth + 1
925
+ };
926
+ declare(node.id, scope);
927
+ if (Array.isArray(node.params)) node.params.forEach((parameter) => declare(parameter, scope));
928
+ } else if (node.type === "ClassDeclaration" || node.type === "ClassExpression") {
929
+ if (node.type === "ClassDeclaration") declare(node.id, inherited);
930
+ scope = {
931
+ parent: inherited,
932
+ bindings: /* @__PURE__ */ new Set(),
933
+ variable: false,
934
+ functionDepth: inherited.functionDepth
935
+ };
936
+ declare(node.id, scope);
937
+ } else if (blockTypes.has(node.type)) {
938
+ scope = {
939
+ parent: inherited,
940
+ bindings: /* @__PURE__ */ new Set(),
941
+ variable: node.type === "StaticBlock" || key === "body" && !!parent && functionTypes.has(parent.type),
942
+ functionDepth: inherited.functionDepth
943
+ };
944
+ if (node.type === "CatchClause") declare(node.param, scope);
945
+ }
946
+ scopes.set(node, scope);
947
+ if (node.type === "VariableDeclaration") {
948
+ let owner = scope;
949
+ while (node.kind === "var" && !owner.variable && owner.parent) owner = owner.parent;
950
+ for (const child of childNodes(node)) declare(child.node.id, owner);
951
+ }
952
+ if (node.type === "ImportDeclaration") {
953
+ for (const child of childNodes(node)) if (child.key === "specifiers") declare(child.node.local, moduleScope);
954
+ return;
955
+ }
956
+ if (node.type === "ImportExpression" || node.type === "CallExpression" && isSyntaxNode(node.callee) && node.callee.type === "Import") throw new SyntaxError("Dynamic import is not supported by the synchronous mini-program module loader.");
957
+ if (node.type === "MetaProperty" && isSyntaxNode(node.meta) && node.meta.name === "import") throw new SyntaxError("import.meta is not supported by the synchronous mini-program module loader.");
958
+ if (scope.functionDepth === 0 && (node.type === "AwaitExpression" || node.type === "ForOfStatement" && node.await)) throw new SyntaxError("Top-level await is not supported by the synchronous mini-program module loader.");
959
+ if (scope.functionDepth === 0 && node.type === "ReturnStatement") throw new SyntaxError("Top-level return is not valid in a mini-program ES module.");
960
+ for (const child of childNodes(node)) {
961
+ const computedMethodKey = functionTypes.has(node.type) && child.key === "key";
962
+ const switchDiscriminant = node.type === "SwitchStatement" && child.key === "discriminant";
963
+ visit(child.node, computedMethodKey || switchDiscriminant ? inherited : scope, node, child.key);
964
+ }
965
+ };
966
+ visit(root, moduleScope);
967
+ const edits = [];
968
+ const rewrite = (node, parent, key) => {
969
+ if (node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportNamedDeclaration" && !node.declaration) return;
970
+ if (node.type === "Identifier" && !declarations.has(node) && imports.has(String(node.name))) {
971
+ const property = parent && key === "key" && !parent.computed && [
972
+ "ObjectProperty",
973
+ "ObjectMethod",
974
+ "ClassMethod",
975
+ "ClassPrivateMethod",
976
+ "ClassProperty"
977
+ ].includes(parent.type);
978
+ const member = parent && key === "property" && !parent.computed && ["MemberExpression", "OptionalMemberExpression"].includes(parent.type);
979
+ const label = key === "label" || parent?.type === "PrivateName" || parent?.type === "MetaProperty";
980
+ let owner = scopes.get(node);
981
+ while (owner && !owner.bindings.has(String(node.name))) owner = owner.parent;
982
+ if (!property && !member && !label && owner === moduleScope) {
983
+ let content = `${bindingName}[${JSON.stringify(node.name)}]`;
984
+ if (parent && (key === "callee" && ["CallExpression", "OptionalCallExpression"].includes(parent.type) || key === "tag" && parent.type === "TaggedTemplateExpression")) content = `(0, ${content})`;
985
+ if (parent?.type === "ObjectProperty" && parent.shorthand && key === "value") content = `${node.name}: ${content}`;
986
+ edits.push({
987
+ start: node.start,
988
+ end: node.end,
989
+ content
990
+ });
991
+ }
992
+ }
993
+ childNodes(node).forEach((child) => rewrite(child.node, node, child.key));
994
+ };
995
+ rewrite(root);
996
+ return edits;
997
+ }
998
+ //#endregion
999
+ //#region src/runtime/moduleSyntax/index.ts
1000
+ function position(node, edge) {
1001
+ const value = node[edge];
1002
+ if (typeof value !== "number") throw new SyntaxError("Missing source range in mini-program module syntax.");
1003
+ return value;
1004
+ }
1005
+ function identifierName(node) {
1006
+ return node.type === "Identifier" ? String(node.name) : String(node.value);
1007
+ }
1008
+ /** 同步转换静态 ESM;CJS 保留原字节,Node 与浏览器共享导入和导出语义。 */
1009
+ function transformMiniProgramModule(source) {
1010
+ if (!/\b(?:import|export)\b/.test(source)) return source;
1011
+ const ast = parse(source, {
1012
+ sourceType: "unambiguous",
1013
+ allowReturnOutsideFunction: true,
1014
+ tokens: true
1015
+ });
1016
+ const moduleNodes = ast.program.body.filter((node) => [
1017
+ "ImportDeclaration",
1018
+ "ExportNamedDeclaration",
1019
+ "ExportDefaultDeclaration",
1020
+ "ExportAllDeclaration"
1021
+ ].includes(node.type));
1022
+ if (moduleNodes.length === 0) return source;
1023
+ const root = ast.program;
1024
+ const fresh = createUniqueName(root);
1025
+ const moduleName = fresh();
1026
+ const requireName = fresh();
1027
+ const objectName = fresh();
1028
+ const bindingsName = fresh();
1029
+ const dependencies = /* @__PURE__ */ new Map();
1030
+ const imports = /* @__PURE__ */ new Map();
1031
+ const exports = /* @__PURE__ */ new Map();
1032
+ const hoistedDefaultNames = [];
1033
+ const starExports = [];
1034
+ const edits = [];
1035
+ const dependency = (request) => {
1036
+ let name = dependencies.get(request);
1037
+ if (!name) {
1038
+ name = fresh();
1039
+ dependencies.set(request, name);
1040
+ }
1041
+ return name;
1042
+ };
1043
+ const remove = (node) => edits.push({
1044
+ start: position(node, "start"),
1045
+ end: position(node, "end"),
1046
+ content: ""
1047
+ });
1048
+ const own = (object, key) => `${objectName}.prototype.hasOwnProperty.call(${object}, ${key})`;
1049
+ for (const node of moduleNodes) {
1050
+ if ("attributes" in node && node.attributes?.length) throw new SyntaxError("Import attributes are not supported by the synchronous mini-program module loader.");
1051
+ if (node.type === "ImportDeclaration") {
1052
+ if (node.phase) throw new SyntaxError("Import phases are not supported by the synchronous mini-program module loader.");
1053
+ const namespace = dependency(node.source.value);
1054
+ for (const specifier of node.specifiers) {
1055
+ const binding = specifier.type === "ImportNamespaceSpecifier" ? namespace : specifier.type === "ImportDefaultSpecifier" ? `${namespace} != null && ${own(namespace, "\"default\"")} ? ${namespace}.default : ${namespace}` : `${namespace}[${JSON.stringify(identifierName(specifier.imported))}]`;
1056
+ imports.set(specifier.local.name, binding);
1057
+ }
1058
+ remove(node);
1059
+ } else if (node.type === "ExportNamedDeclaration") {
1060
+ if (node.declaration) {
1061
+ edits.push({
1062
+ start: position(node, "start"),
1063
+ end: position(node.declaration, "start"),
1064
+ content: ""
1065
+ });
1066
+ const patterns = node.declaration.type === "VariableDeclaration" ? node.declaration.declarations.map((declaration) => declaration.id) : "id" in node.declaration && node.declaration.id ? [node.declaration.id] : [];
1067
+ for (const pattern of patterns) for (const identifier of patternIdentifiers(pattern)) exports.set(String(identifier.name), String(identifier.name));
1068
+ } else {
1069
+ const namespace = node.source ? dependency(node.source.value) : void 0;
1070
+ for (const specifier of node.specifiers) {
1071
+ const exported = identifierName(specifier.exported);
1072
+ if (specifier.type === "ExportNamespaceSpecifier" && namespace) exports.set(exported, namespace);
1073
+ else if (specifier.type === "ExportSpecifier") {
1074
+ const local = identifierName(specifier.local);
1075
+ exports.set(exported, namespace ? `${namespace}[${JSON.stringify(local)}]` : local);
1076
+ } else throw new SyntaxError(`Unsupported mini-program export specifier: ${specifier.type}.`);
1077
+ }
1078
+ remove(node);
1079
+ }
1080
+ } else if (node.type === "ExportAllDeclaration") {
1081
+ starExports.push(dependency(node.source.value));
1082
+ remove(node);
1083
+ } else if (node.type === "ExportDefaultDeclaration") {
1084
+ const declaration = node.declaration;
1085
+ const defaultToken = ast.tokens?.find((token) => token.start > position(node, "start") && token.end <= position(declaration, "start") && token.type.label === "default");
1086
+ if (!defaultToken) throw new SyntaxError("Missing default export token in mini-program module syntax.");
1087
+ if (declaration.type === "FunctionDeclaration" && !declaration.id) {
1088
+ const name = fresh();
1089
+ const keyword = ast.tokens?.find((token) => token.start >= position(declaration, "start") && token.type.label === "function");
1090
+ const nameToken = declaration.generator ? ast.tokens?.find((token) => token.start >= (keyword?.end ?? position(declaration, "start")) && token.type.label === "*") : keyword;
1091
+ if (!nameToken) throw new SyntaxError("Missing default function token in mini-program module syntax.");
1092
+ exports.set("default", name);
1093
+ hoistedDefaultNames.push(name);
1094
+ edits.push({
1095
+ start: position(node, "start"),
1096
+ end: defaultToken.end,
1097
+ content: ""
1098
+ });
1099
+ edits.push({
1100
+ start: nameToken.end,
1101
+ end: nameToken.end,
1102
+ content: ` ${name}`
1103
+ });
1104
+ } else if ((declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration") && declaration.id) {
1105
+ exports.set("default", declaration.id.name);
1106
+ edits.push({
1107
+ start: position(node, "start"),
1108
+ end: defaultToken.end,
1109
+ content: ""
1110
+ });
1111
+ } else {
1112
+ const name = fresh();
1113
+ exports.set("default", name);
1114
+ edits.push({
1115
+ start: position(node, "start"),
1116
+ end: defaultToken.end,
1117
+ content: `const ${name} = `
1118
+ });
1119
+ edits.push({
1120
+ start: position(node, "end"),
1121
+ end: position(node, "end"),
1122
+ content: ";"
1123
+ });
1124
+ }
1125
+ }
1126
+ }
1127
+ edits.push(...rewriteImportReferences(root, new Set(imports.keys()), bindingsName));
1128
+ const declarations = [
1129
+ dependencies.size ? `let ${[...dependencies.values()].join(", ")};` : "",
1130
+ `const ${bindingsName} = ${objectName}.create(null);`,
1131
+ ...[...imports].map(([name, expression]) => `${objectName}.defineProperty(${bindingsName}, ${JSON.stringify(name)}, { get: () => (${expression}) });`),
1132
+ ...[...exports].map(([name, expression]) => {
1133
+ const value = imports.has(expression) ? `${bindingsName}[${JSON.stringify(expression)}]` : expression;
1134
+ return `${objectName}.defineProperty(${moduleName}.exports, ${JSON.stringify(name)}, { enumerable: true, get: () => ${value} });`;
1135
+ }),
1136
+ ...hoistedDefaultNames.map((name) => `${objectName}.defineProperty(${name}, 'name', { value: 'default', configurable: true });`),
1137
+ ...[...dependencies].map(([request, namespace]) => `${namespace} = ${requireName}(${JSON.stringify(request)});`)
1138
+ ];
1139
+ if (starExports.length) {
1140
+ const owners = fresh();
1141
+ const namespace = fresh();
1142
+ const key = fresh();
1143
+ declarations.push(`
1144
+ const ${owners} = ${objectName}.create(null);
1145
+ for (const ${namespace} of [${starExports.join(", ")}]) {
1146
+ for (const ${key} of ${objectName}.keys(${namespace})) {
1147
+ if (${key} === 'default' || ${own(`${moduleName}.exports`, key)}) continue;
1148
+ ${owners}[${key}] = ${own(owners, key)} && ${owners}[${key}] !== ${namespace} ? null : ${namespace};
1149
+ }
1150
+ }
1151
+ for (const ${key} of ${objectName}.keys(${owners})) {
1152
+ if (${owners}[${key}] !== null) ${objectName}.defineProperty(${moduleName}.exports, ${key}, { enumerable: true, get: () => ${owners}[${key}][${key}] });
1153
+ }
1154
+ `);
1155
+ }
1156
+ return `(function(${moduleName}, ${requireName}, ${objectName}) {\n"use strict";\n${declarations.join("\n")}\n${applySourceEdits(source, edits)}\n${objectName}.preventExtensions(${moduleName}.exports);\n}).call(undefined, module, require, Object);`;
1157
+ }
1158
+ //#endregion
1159
+ //#region src/runtime/pageDefinitionReload.ts
1160
+ /** 定义更新只解析已有路由,不触发普通导航的启动或 page-not-found 生命周期。 */
1161
+ function resolvePageDefinitionReloadRoute(project, route) {
1162
+ if (typeof route !== "string" || !route.trim() || /[?#]/.test(route)) throw new TypeError("Page definition reload requires a route path without query or hash.");
1163
+ const normalized = route.trim().replace(/^\/+/, "");
1164
+ const record = project.routes.find((record) => record.route === normalized);
1165
+ if (!record) throw new Error(`Unknown page definition reload route: ${route}`);
1166
+ return record;
1167
+ }
1168
+ function restoreMap(target, snapshot) {
1169
+ target.clear();
1170
+ for (const [key, value] of snapshot) target.set(key, value);
1171
+ }
1172
+ /** 仅替换目标 entry;失败恢复缓存和注册表,保留未变依赖的对象身份。 */
1173
+ function reloadPageModuleDefinition(options) {
1174
+ const { filePath, route, source, cache, registries } = options;
1175
+ const previous = cache.get(filePath);
1176
+ if (!previous || !registries.pages.has(route)) throw new Error(`Cannot reload a page definition before it is loaded: ${route}`);
1177
+ if (source === void 0) throw new Error(`Missing page script for definition reload: ${route}`);
1178
+ if (source === previous.source) return false;
1179
+ const modules = new Map(cache);
1180
+ const pages = new Map(registries.pages);
1181
+ const components = new Map(registries.components);
1182
+ const app = registries.appDefinition;
1183
+ cache.delete(filePath);
1184
+ registries.pages.delete(route);
1185
+ try {
1186
+ options.execute();
1187
+ return true;
1188
+ } catch (error) {
1189
+ restoreMap(cache, modules);
1190
+ restoreMap(registries.pages, pages);
1191
+ restoreMap(registries.components, components);
1192
+ registries.appDefinition = app;
1193
+ throw error;
1194
+ }
1195
+ }
1196
+ //#endregion
842
1197
  //#region src/runtime/runtimeGlobals.ts
843
1198
  const MINI_PROGRAM_UNAVAILABLE_GLOBAL_NAMES = [
844
1199
  "window",
@@ -1240,6 +1595,7 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
1240
1595
  const source = readBrowserVirtualFile(files, resolvedPath);
1241
1596
  if (typeof source !== "string") throw new TypeError(`Missing virtual module in browser simulator runtime: ${resolvedPath}`);
1242
1597
  const module = {
1598
+ source,
1243
1599
  componentDefinitions: [],
1244
1600
  exports: {}
1245
1601
  };
@@ -1265,7 +1621,7 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
1265
1621
  new Function(`
1266
1622
  with (this) {
1267
1623
  return function(exports, module, require, __filename, __dirname) {
1268
- ${source}
1624
+ ${transformMiniProgramModule(source)}
1269
1625
  };
1270
1626
  }
1271
1627
  `).call(executionContext).call(executionContext, module.exports, module, localRequire, resolvedPath, dirname(resolvedPath));
@@ -1310,6 +1666,17 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
1310
1666
  if (!definition) throw new Error(`Page() was not registered for route "${route}" while executing ${normalize(filePath)}.`);
1311
1667
  return definition;
1312
1668
  },
1669
+ reloadPageModule(filePath, route) {
1670
+ const resolvedPath = normalize(filePath);
1671
+ return reloadPageModuleDefinition({
1672
+ filePath: resolvedPath,
1673
+ route,
1674
+ source: readBrowserVirtualFile(files, resolvedPath),
1675
+ cache: moduleCache,
1676
+ registries,
1677
+ execute: () => loader.executePageModule(resolvedPath, route)
1678
+ });
1679
+ },
1313
1680
  executeComponentModule(filePath, id) {
1314
1681
  const loadedModule = executeModule(filePath, {
1315
1682
  kind: "component",
@@ -1330,7 +1697,13 @@ function normalizeArtifactPath(filePath) {
1330
1697
  }
1331
1698
  function createFileSystemArtifactSource() {
1332
1699
  return {
1333
- has: (filePath) => fs.existsSync(filePath),
1700
+ has(filePath) {
1701
+ try {
1702
+ return fs.statSync(filePath).isFile();
1703
+ } catch {
1704
+ return false;
1705
+ }
1706
+ },
1334
1707
  readText(filePath) {
1335
1708
  try {
1336
1709
  return fs.readFileSync(filePath, "utf8");
@@ -1656,11 +2029,14 @@ function runPropertyObservers(definition, instance, changedKeys, previousPropert
1656
2029
  const changedRoots = new Set(changedKeys.map((key) => parseDataPath$1(key)[0]));
1657
2030
  for (const changedKey of Object.keys(propOptions)) {
1658
2031
  if (!changedRoots.has(changedKey)) continue;
2032
+ const value = instance.properties[changedKey];
2033
+ if ((value === null || typeof value !== "object") && Object.hasOwn(previousProperties, changedKey) && Object.is(value, previousProperties[changedKey])) continue;
1659
2034
  const option = propOptions[changedKey];
1660
2035
  if (!option || typeof option !== "object" || Array.isArray(option)) continue;
1661
2036
  const observer = typeof option.observer === "string" ? instance[option.observer] : option.observer;
1662
2037
  if (typeof observer !== "function") continue;
1663
- observer.call(instance, instance.properties[changedKey], previousProperties[changedKey]);
2038
+ const changedPath = parseDataPath$1(changedKeys.find((key) => parseDataPath$1(key)[0] === changedKey)).map((segment) => isArrayIndexSegment$1(segment) ? Number(segment) : segment);
2039
+ observer.call(instance, value, previousProperties[changedKey], changedPath);
1664
2040
  }
1665
2041
  }
1666
2042
  function normalizeObserverPattern(pattern) {
@@ -1871,7 +2247,6 @@ function resolveInitialProperties(definition, properties) {
1871
2247
  if (option && typeof option === "object" && !Array.isArray(option) && "value" in option) resolved[key] = resolvePropertyDefaultValue(option, definition);
1872
2248
  else resolved[key] = cloneValue(resolveDefaultValueByType(normalizePropertyType(option)));
1873
2249
  }
1874
- for (const [key, value] of Object.entries(properties)) if (!(key in resolved)) resolved[key] = value;
1875
2250
  return resolved;
1876
2251
  }
1877
2252
  //#endregion
@@ -1886,11 +2261,11 @@ const opposite = {
1886
2261
  function definitions(instance) {
1887
2262
  return Object.entries(instance.__definition__?.relations ?? {});
1888
2263
  }
1889
- function includesBehavior(behaviors, target) {
1890
- return Array.isArray(behaviors) && behaviors.some((behavior) => behavior === target || behavior && typeof behavior === "object" && includesBehavior(behavior.behaviors, target));
2264
+ function includesBehavior$1(behaviors, target) {
2265
+ return Array.isArray(behaviors) && behaviors.some((behavior) => behavior === target || behavior && typeof behavior === "object" && includesBehavior$1(behavior.behaviors, target));
1891
2266
  }
1892
2267
  function matches(source, key, relation, target) {
1893
- if (relation.target) return includesBehavior(target.__definition__?.behaviors, relation.target);
2268
+ if (relation.target) return includesBehavior$1(target.__definition__?.behaviors, relation.target);
1894
2269
  const targetPath = key.startsWith("/") ? key.slice(1) : posix.join(posix.dirname(String(source.is)), key);
1895
2270
  return posix.normalize(targetPath) === target.is;
1896
2271
  }
@@ -1964,29 +2339,23 @@ function detachComponentRelations(instances) {
1964
2339
  //#region src/runtime/componentInstance/index.ts
1965
2340
  function createComponentInstance(options) {
1966
2341
  const definition = normalizeComponentDefinition(options.definition);
1967
- const inputProperties = resolveInitialProperties(definition, options.properties ?? {});
1968
2342
  const data = {
1969
2343
  ...resolveInitialData$2(definition),
1970
- ...Object.fromEntries(Object.keys(definition.properties ?? {}).map((key) => [key, inputProperties[key]]))
2344
+ ...resolveInitialProperties(definition, options.properties ?? {})
1971
2345
  };
1972
2346
  const instance = {
1973
2347
  __definition__: definition,
1974
2348
  data,
1975
2349
  __propertySnapshots__: {},
1976
- properties: {
1977
- ...data,
1978
- ...inputProperties
1979
- },
2350
+ properties: data,
1980
2351
  getRelationNodes(key) {
1981
2352
  return getComponentRelationNodes(instance, key);
1982
2353
  },
1983
2354
  setData(patch, callback) {
1984
2355
  const changedKeys = Object.keys(patch);
1985
- const dataKeys = [...new Set(changedKeys.map((key) => parseDataPath$1(key)[0]))];
1986
- const propertyKeys = dataKeys.filter((key) => Object.hasOwn(definition.properties ?? {}, key));
2356
+ const propertyKeys = [...new Set(changedKeys.map((key) => parseDataPath$1(key)[0]))].filter((key) => Object.hasOwn(definition.properties ?? {}, key));
1987
2357
  const previousProperties = Object.fromEntries(propertyKeys.map((key) => [key, cloneValue(instance.properties[key])]));
1988
2358
  for (const [key, value] of Object.entries(patch)) assignByPath$1(instance.data, key, value);
1989
- for (const key of dataKeys) instance.properties[key] = instance.data[key];
1990
2359
  synchronizeAttachmentBindings(instance);
1991
2360
  runComponentObservers(definition, instance, changedKeys, previousProperties);
1992
2361
  if (options.requestRender) options.requestRender(callback);
@@ -2137,6 +2506,7 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
2137
2506
  const changedRootKeys = [];
2138
2507
  const previousProperties = {};
2139
2508
  for (const [key, value] of Object.entries(nextProperties)) {
2509
+ if (!Object.hasOwn(definition.properties ?? {}, key)) continue;
2140
2510
  const nextValue = normalizeComponentPropertyValue(definition, key, value);
2141
2511
  const bindingExpression = bindingExpressions[key];
2142
2512
  const bindingAffected = freshPageChanges && !!bindingExpression && changedPageKeys.some((changedKey) => {
@@ -2147,7 +2517,6 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
2147
2517
  previousProperties[key] = instance.properties[key];
2148
2518
  const deliveredValue = cloneValue(nextValue);
2149
2519
  instance.properties[key] = deliveredValue;
2150
- if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = deliveredValue;
2151
2520
  changedRootKeys.push(key);
2152
2521
  }
2153
2522
  instance.__propertySnapshots ??= {};
@@ -2158,6 +2527,32 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
2158
2527
  runComponentObservers(definition, instance, changedRootKeys, previousProperties);
2159
2528
  }
2160
2529
  //#endregion
2530
+ //#region src/runtime/componentInstance/reconcileRemoved.ts
2531
+ /** 用户卸载钩子失败也要完成关系与缓存收尾,避免下一次渲染重复卸载同一实例。 */
2532
+ function reconcileRemovedComponents(cache, scopes, activeScopeIds, pageScopeId) {
2533
+ const removed = [...cache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !activeScopeIds.has(scopeId));
2534
+ let failure;
2535
+ for (const [scopeId, instance] of removed) try {
2536
+ if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
2537
+ else scheduleDiscardedComponentReady(cache, scopeId, instance);
2538
+ } catch (error) {
2539
+ failure ??= { error };
2540
+ }
2541
+ let relationsChanged = false;
2542
+ try {
2543
+ relationsChanged = syncComponentRelations(cache, activeScopeIds, pageScopeId);
2544
+ } catch (error) {
2545
+ failure ??= { error };
2546
+ } finally {
2547
+ for (const [scopeId] of removed) {
2548
+ cache.delete(scopeId);
2549
+ scopes.delete(scopeId);
2550
+ }
2551
+ }
2552
+ if (failure) throw failure.error;
2553
+ return relationsChanged;
2554
+ }
2555
+ //#endregion
2161
2556
  //#region src/runtime/pageLifecycle.ts
2162
2557
  const loadingPages = /* @__PURE__ */ new WeakSet();
2163
2558
  function isPageBeforeReady(page) {
@@ -2310,6 +2705,31 @@ function collectNodeDataset(node) {
2310
2705
  //#endregion
2311
2706
  //#region src/view/componentEvent.ts
2312
2707
  const eventNodes = /* @__PURE__ */ new WeakMap();
2708
+ /** 原生默认行为读取声明所有者与原始属性,避免组件根折叠覆盖宿主边界。 */
2709
+ function getNativeNodeOwner(node) {
2710
+ const entry = eventNodes.get(node);
2711
+ return entry ? {
2712
+ scopeId: entry.scope.getScopeId(),
2713
+ target: entry.target
2714
+ } : void 0;
2715
+ }
2716
+ /** 原生冒泡包含折叠的宿主绑定;catch 只截断其后的绑定和祖先。 */
2717
+ function visitNativeNodeEventBindings(node, eventName, visit) {
2718
+ const collect = (entry) => {
2719
+ const binding = entry.bindings ? entry.bindings.eventBindings?.get(eventName) : resolveEventBindingPhases(entry.target.attribs, eventName, false)?.bubble;
2720
+ if (binding) visit(entry.scope.getScopeId(), entry.target, binding);
2721
+ return binding?.stopAfter ?? false;
2722
+ };
2723
+ const entry = eventNodes.get(node);
2724
+ if (!entry) {
2725
+ const binding = resolveEventBindingPhases(node.attribs, eventName, false)?.bubble;
2726
+ if (binding) visit(node.attribs?.["data-sim-scope"] ?? null, node, binding);
2727
+ return binding?.stopAfter ?? false;
2728
+ }
2729
+ if (collect(entry)) return true;
2730
+ for (const host of entry.hosts ?? []) if (collect(eventNodes.get(host))) return true;
2731
+ return false;
2732
+ }
2313
2733
  /** 在构造子树之前建立父链,created/observer 中的事件也能访问声明树。 */
2314
2734
  function registerComponentEventNode(node, scope, parent) {
2315
2735
  node.parent = parent ?? null;
@@ -2992,6 +3412,209 @@ function resolveSelectorQueryScopeSnapshot(scope, snapshots) {
2992
3412
  return null;
2993
3413
  }
2994
3414
  //#endregion
3415
+ //#region src/view/nodeEvents.ts
3416
+ /** 正确字段优先;复制触点,避免处理器修改调用者持有的数据。 */
3417
+ function readTouchEventPayload(event) {
3418
+ const changedTouches = event.changedTouches ?? event.changeTouches;
3419
+ return {
3420
+ ...event.touches === void 0 ? {} : { touches: event.touches.map((touch) => ({ ...touch })) },
3421
+ ...changedTouches === void 0 ? {} : { changedTouches: changedTouches.map((touch) => ({ ...touch })) }
3422
+ };
3423
+ }
3424
+ //#endregion
3425
+ //#region src/view/eventBinding.ts
3426
+ function collectMiniProgramEventBindings(attributes = {}) {
3427
+ return collectEventBindings(attributes, false).eventBindings;
3428
+ }
3429
+ function resolveMiniProgramEventBinding(attributes, eventName) {
3430
+ return resolveEventBindingPhases(attributes, eventName, false)?.bubble ?? null;
3431
+ }
3432
+ /** 冒泡时保留原始 target,currentTarget 则属于当前执行绑定的节点。 */
3433
+ function createMiniProgramEventPayload(node, eventName, event, origin = node) {
3434
+ const dataset = collectNodeDataset(node);
3435
+ const nodeId = node.attribs?.id ?? "";
3436
+ const isOrigin = node === origin;
3437
+ return {
3438
+ ...readTouchEventPayload(event),
3439
+ bubbles: false,
3440
+ capturePhase: false,
3441
+ composed: false,
3442
+ currentTarget: {
3443
+ dataset: isOrigin ? event.currentTarget?.dataset ?? event.dataset ?? dataset : dataset,
3444
+ id: isOrigin ? event.currentTarget?.id ?? event.id ?? nodeId : nodeId
3445
+ },
3446
+ detail: event.detail,
3447
+ mark: event.mark,
3448
+ target: {
3449
+ dataset: event.target?.dataset ?? event.dataset ?? (isOrigin ? dataset : collectNodeDataset(origin)),
3450
+ id: event.target?.id ?? event.id ?? origin.attribs?.id ?? ""
3451
+ },
3452
+ timeStamp: Date.now(),
3453
+ type: eventName
3454
+ };
3455
+ }
3456
+ //#endregion
3457
+ //#region src/view/nativeForm.ts
3458
+ const pickerValues = /* @__PURE__ */ new WeakMap();
3459
+ /** 保存 picker 的原始数组属性,不能从渲染后的逗号字符串反推选项值。 */
3460
+ function setNativePickerValue(node, value) {
3461
+ if (node.name === "picker") pickerValues.set(node, value);
3462
+ }
3463
+ function includesBehavior(definition, name, visited = /* @__PURE__ */ new Set()) {
3464
+ if (visited.has(definition)) return false;
3465
+ visited.add(definition);
3466
+ return Array.isArray(definition.behaviors) && definition.behaviors.some((behavior) => behavior === name || behavior !== null && typeof behavior === "object" && includesBehavior(behavior, name, visited));
3467
+ }
3468
+ function nativeOwner(node) {
3469
+ return getNativeNodeOwner(node) ?? {
3470
+ scopeId: node.attribs?.["data-sim-scope"] ?? null,
3471
+ target: node
3472
+ };
3473
+ }
3474
+ function participatingScopes(formScope, pageScope, resolveComponent) {
3475
+ const scopes = /* @__PURE__ */ new Set([null, pageScope]);
3476
+ let current = formScope;
3477
+ while (current && !scopes.has(current)) {
3478
+ scopes.add(current);
3479
+ current = resolveComponent?.(current)?.ownerScopeId ?? null;
3480
+ }
3481
+ return scopes;
3482
+ }
3483
+ function participates(scopeId, formScopes, behavior, resolveComponent) {
3484
+ const visited = /* @__PURE__ */ new Set();
3485
+ while (!formScopes.has(scopeId)) {
3486
+ if (!scopeId || visited.has(scopeId)) return false;
3487
+ visited.add(scopeId);
3488
+ const component = resolveComponent?.(scopeId);
3489
+ if (!component || !includesBehavior(component.definition, behavior)) return false;
3490
+ scopeId = component.ownerScopeId;
3491
+ }
3492
+ return true;
3493
+ }
3494
+ function checked(attributes, name) {
3495
+ const value = attributes?.[name];
3496
+ return value !== void 0 && value !== "false" && value !== "0";
3497
+ }
3498
+ function choiceValues(group, pageScope, resolveComponent) {
3499
+ const values = [];
3500
+ const scopes = participatingScopes(nativeOwner(group).scopeId, pageScope, resolveComponent);
3501
+ const choice = group.name === "radio-group" ? "radio" : "checkbox";
3502
+ const visit = (node) => {
3503
+ if (node.name === "form" || node.name === "radio-group" || node.name === "checkbox-group") return;
3504
+ if (node.name === choice) {
3505
+ const owner = nativeOwner(node);
3506
+ if (checked(owner.target.attribs, "checked") && participates(owner.scopeId, scopes, "wx://form-field-group", resolveComponent)) values.push(owner.target.attribs?.value ?? "");
3507
+ }
3508
+ for (const child of node.children ?? []) visit(child);
3509
+ };
3510
+ for (const child of group.children ?? []) visit(child);
3511
+ return values;
3512
+ }
3513
+ function collectFormValues(form, scopes, pageScope, resolveComponent) {
3514
+ const values = Object.create(null);
3515
+ const visit = (node) => {
3516
+ if (node.name === "form") return;
3517
+ const owner = nativeOwner(node);
3518
+ const attributes = owner.target.attribs;
3519
+ const name = attributes?.name;
3520
+ if (attributes && name && participates(owner.scopeId, scopes, "wx://form-field-group", resolveComponent)) switch (node.name) {
3521
+ case "input":
3522
+ case "textarea":
3523
+ values[name] = attributes.value ?? "";
3524
+ break;
3525
+ case "switch":
3526
+ values[name] = checked(attributes, "checked");
3527
+ break;
3528
+ case "slider":
3529
+ values[name] = Number(attributes.value ?? 0);
3530
+ break;
3531
+ case "picker": {
3532
+ const mode = attributes.mode ?? "selector";
3533
+ if (mode === "multiSelector" || mode === "region") {
3534
+ const value = pickerValues.get(node);
3535
+ values[name] = Array.isArray(value) ? value.slice() : [];
3536
+ } else values[name] = mode === "selector" ? Number(attributes.value ?? 0) : attributes.value ?? "";
3537
+ break;
3538
+ }
3539
+ case "radio-group":
3540
+ values[name] = choiceValues(node, pageScope, resolveComponent)[0] ?? "";
3541
+ break;
3542
+ case "checkbox-group": values[name] = choiceValues(node, pageScope, resolveComponent);
3543
+ }
3544
+ for (const child of node.children ?? []) visit(child);
3545
+ };
3546
+ for (const child of form.children ?? []) visit(child);
3547
+ return values;
3548
+ }
3549
+ /** 先固定提交目标、字段值和方法所有者,再允许 tap 回调改变组件树。 */
3550
+ function prepareNativeFormSubmit(button, pageScope, event, resolveMethod, resolveComponent) {
3551
+ const owner = nativeOwner(button);
3552
+ if (owner.target.attribs?.["form-type"] !== "submit" || checked(owner.target.attribs, "disabled")) return;
3553
+ let form = button.parent;
3554
+ while (form && form.name !== "form") form = form.parent;
3555
+ if (!form) return;
3556
+ const formOwner = nativeOwner(form);
3557
+ const scopes = participatingScopes(formOwner.scopeId, pageScope, resolveComponent);
3558
+ if (!participates(owner.scopeId, scopes, "wx://form-field-button", resolveComponent)) return;
3559
+ const binding = resolveMiniProgramEventBinding(formOwner.target.attribs, "submit");
3560
+ return {
3561
+ call: binding?.method ? resolveMethod(formOwner.scopeId, binding.method) : void 0,
3562
+ event: createMiniProgramEventPayload(formOwner.target, "submit", {
3563
+ detail: { value: collectFormValues(form, scopes, pageScope, resolveComponent) },
3564
+ mark: event.mark
3565
+ })
3566
+ };
3567
+ }
3568
+ //#endregion
3569
+ //#region src/view/richText.ts
3570
+ function materializeNode(node) {
3571
+ if (node.type === "text") return {
3572
+ type: "text",
3573
+ data: node.text
3574
+ };
3575
+ for (const name of Object.keys(node.attrs)) if (name.startsWith("data-sim-")) delete node.attrs[name];
3576
+ return {
3577
+ type: "tag",
3578
+ name: node.name,
3579
+ attribs: node.attrs,
3580
+ children: node.children.map(materializeNode)
3581
+ };
3582
+ }
3583
+ /** 富文本直接成为已渲染节点,不能再进入 WXML 表达式或组件处理流程。 */
3584
+ function renderRichTextNodes(value) {
3585
+ return normalizeRichTextNodes(value).map(materializeNode);
3586
+ }
3587
+ //#endregion
3588
+ //#region src/view/templateIncludes.ts
3589
+ /** 展开 include 的可渲染内容,并保留嵌套引用的来源文件。 */
3590
+ function expandTemplateIncludes(root, filePath, loadTemplate) {
3591
+ const owners = /* @__PURE__ */ new WeakMap();
3592
+ const expand = (node, owner, stack, included = false) => {
3593
+ if (included && (isTemplateDefinition(node) || node.name === "wxs")) return;
3594
+ owners.set(node, owner);
3595
+ if (node.name === "include" && node.attribs?.src) {
3596
+ const source = node.attribs.src;
3597
+ const loaded = loadTemplate(owner, source.endsWith(".wxml") ? source : `${source}.wxml`);
3598
+ if (stack.includes(loaded.filePath)) throw new Error("Circular WXML include is not supported");
3599
+ const { src: _src, ...attributes } = node.attribs;
3600
+ node.name = "block";
3601
+ node.attribs = attributes;
3602
+ node.children = (loaded.root.children ?? []).flatMap((child) => {
3603
+ const expanded = expand(child, loaded.filePath, [...stack, loaded.filePath], true);
3604
+ return expanded ? [expanded] : [];
3605
+ });
3606
+ return node;
3607
+ }
3608
+ node.children = node.children?.flatMap((child) => {
3609
+ const expanded = expand(child, owner, stack, included);
3610
+ return expanded ? [expanded] : [];
3611
+ });
3612
+ return node;
3613
+ };
3614
+ expand(root, filePath, [filePath]);
3615
+ return owners;
3616
+ }
3617
+ //#endregion
2995
3618
  //#region src/view/templateImports.ts
2996
3619
  function createImportedTemplateState(root, filePath, loadImport, loadWxs) {
2997
3620
  const documents = /* @__PURE__ */ new Map();
@@ -3000,6 +3623,7 @@ function createImportedTemplateState(root, filePath, loadImport, loadWxs) {
3000
3623
  const collect = (node, owner) => {
3001
3624
  const existing = documents.get(owner);
3002
3625
  if (existing) return existing;
3626
+ const owners = expandTemplateIncludes(node, owner, loadImport);
3003
3627
  const state = createTemplateRenderState(node);
3004
3628
  const wxsModules = Object.create(null);
3005
3629
  const ownDefinitions = new Map(state.definitions);
@@ -3009,6 +3633,7 @@ function createImportedTemplateState(root, filePath, loadImport, loadWxs) {
3009
3633
  };
3010
3634
  documents.set(owner, document);
3011
3635
  const visit = (child) => {
3636
+ const sourceOwner = owners.get(child) ?? owner;
3012
3637
  if (child.name === "wxs" && loadWxs) {
3013
3638
  const name = child.attribs?.module;
3014
3639
  if (!name || !/^[a-z_$][\w$]*$/i.test(name) || [
@@ -3017,12 +3642,12 @@ function createImportedTemplateState(root, filePath, loadImport, loadWxs) {
3017
3642
  "prototype"
3018
3643
  ].includes(name)) throw new Error(`Invalid WXS module name in ${owner}: ${String(name)}`);
3019
3644
  if (Object.hasOwn(wxsModules, name)) throw new Error(`Duplicate WXS module in ${owner}: ${name}`);
3020
- wxsModules[name] = loadWxs(owner, child);
3645
+ wxsModules[name] = loadWxs(sourceOwner, child);
3021
3646
  return;
3022
3647
  }
3023
3648
  if (child.name === "import" && child.attribs?.src) {
3024
3649
  const source = child.attribs.src;
3025
- const imported = loadImport(owner, source.endsWith(".wxml") ? source : `${source}.wxml`);
3650
+ const imported = loadImport(sourceOwner, source.endsWith(".wxml") ? source : `${source}.wxml`);
3026
3651
  const importedDocument = collect(imported.root, imported.filePath);
3027
3652
  for (const [name, definition] of importedDocument.exports) state.definitions.set(name, definition);
3028
3653
  }
@@ -3113,7 +3738,7 @@ function parseWxsTemplateDocument(templateSource) {
3113
3738
  });
3114
3739
  const masked = maskTemplateAttributes(source);
3115
3740
  const document = parseDocument(`<page>${masked.source}</page>`, {
3116
- xmlMode: false,
3741
+ xmlMode: true,
3117
3742
  decodeEntities: false,
3118
3743
  lowerCaseAttributeNames: false,
3119
3744
  lowerCaseTags: false,
@@ -3171,7 +3796,7 @@ function collectDataset$1(node, source) {
3171
3796
  function escapeText$3(text) {
3172
3797
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
3173
3798
  }
3174
- function escapeAttribute$3(value) {
3799
+ function escapeAttribute$2(value) {
3175
3800
  return escapeText$3(value).replaceAll("\"", "&quot;");
3176
3801
  }
3177
3802
  function cloneNode$1(node) {
@@ -3188,18 +3813,18 @@ function resolveRawValueByPath$2(source, expression) {
3188
3813
  function interpolateTemplate$2(input, data) {
3189
3814
  return interpolateTemplateText(input, data, true);
3190
3815
  }
3191
- function readTemplateSource$1(files, filePath) {
3192
- const templateSource = readBrowserVirtualFile(files, filePath);
3816
+ function readTemplateSource$1(files, filePath, artifactSource) {
3817
+ const templateSource = artifactSource ? artifactSource.readText(filePath) : readBrowserVirtualFile(files, filePath);
3193
3818
  if (typeof templateSource !== "string") throw new TypeError(`Missing template in browser simulator runtime: ${filePath}`);
3194
3819
  return templateSource;
3195
3820
  }
3196
3821
  function parseTemplateDocument$1(templateSource) {
3197
3822
  return parseWxsTemplateDocument(templateSource);
3198
3823
  }
3199
- function prepareTemplateRenderState$1(files, root, filePath, projectRoot, loadWxs) {
3824
+ function prepareTemplateRenderState$1(files, root, filePath, projectRoot, loadWxs, artifactSource) {
3200
3825
  return createImportedTemplateState(root, filePath, (owner, source) => {
3201
3826
  const resolved = normalize(source.startsWith("/") ? join(projectRoot, source.slice(1)) : join(dirname(owner), source));
3202
- const document = parseTemplateDocument$1(readTemplateSource$1(files, resolved));
3827
+ const document = parseTemplateDocument$1(readTemplateSource$1(files, resolved, artifactSource));
3203
3828
  return {
3204
3829
  filePath: resolved,
3205
3830
  root: document.children?.[0] ?? document
@@ -3216,7 +3841,7 @@ function serializeDomNode$2(node) {
3216
3841
  if (node.type === "root") return (node.children ?? []).map(serializeDomNode$2).join("");
3217
3842
  const tagName = node.name ?? "";
3218
3843
  if (!tagName) return (node.children ?? []).map(serializeDomNode$2).join("");
3219
- return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$3(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$2).join("")}</${tagName}>`;
3844
+ return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$2(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$2).join("")}</${tagName}>`;
3220
3845
  }
3221
3846
  function isTagNode$1(node) {
3222
3847
  return node.type === "tag" && typeof node.name === "string";
@@ -3235,7 +3860,7 @@ function resolveComponentAttributeValue$1(value, scope) {
3235
3860
  }
3236
3861
  return interpolateTemplate$2(value, wxsScopeData(scope));
3237
3862
  }
3238
- function applyNodeBindings$1(node, scope) {
3863
+ function applyNodeBindings$1(node, scope, richText = false) {
3239
3864
  if (!isTagNode$1(node)) {
3240
3865
  if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplateText(node.data, wxsScopeData(scope));
3241
3866
  return;
@@ -3243,6 +3868,7 @@ function applyNodeBindings$1(node, scope) {
3243
3868
  node.attribs ??= {};
3244
3869
  node.attribs["data-sim-scope"] = scope.getScopeId();
3245
3870
  for (const key of STRUCTURAL_ATTRS$1) delete node.attribs[key];
3871
+ if (richText) node.children = [];
3246
3872
  let dataset;
3247
3873
  for (const [key, value] of Object.entries({ ...node.attribs })) {
3248
3874
  if (EVENT_BINDING_ATTRS$1.includes(key)) {
@@ -3250,6 +3876,8 @@ function applyNodeBindings$1(node, scope) {
3250
3876
  continue;
3251
3877
  }
3252
3878
  const resolvedValue = typeof value === "string" ? resolveAttributeValue$1(value, scope) : value;
3879
+ if (key === "value") setNativePickerValue(node, resolvedValue);
3880
+ if (richText && key === "nodes") node.children = renderRichTextNodes(resolvedValue);
3253
3881
  node.attribs[key] = String(resolvedValue ?? "");
3254
3882
  if (isDatasetAttribute(key)) {
3255
3883
  dataset ??= {};
@@ -3276,8 +3904,7 @@ function createLoopScope$1(scope, itemName, indexName, item, index) {
3276
3904
  //#endregion
3277
3905
  //#region src/browser/render/component.ts
3278
3906
  function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, alias, genericComponentBasePath) {
3279
- const usingComponents = resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath);
3280
- const componentBasePath = genericComponentBasePath ?? usingComponents.get(alias);
3907
+ const componentBasePath = genericComponentBasePath ?? resolveUsingComponent$1(context, ownerJsonPath, ownerFilePath, alias);
3281
3908
  if (!componentBasePath) return null;
3282
3909
  const filePath = `${componentBasePath}.js`;
3283
3910
  const templatePath = `${componentBasePath}.wxml`;
@@ -3296,30 +3923,25 @@ function readComponentConfig$1(files, jsonPath) {
3296
3923
  return {};
3297
3924
  }
3298
3925
  }
3299
- function resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath) {
3926
+ function resolveUsingComponent$1(context, ownerJsonPath, ownerFilePath, alias) {
3300
3927
  try {
3301
3928
  const usingComponents = readComponentConfig$1(context.files, join(context.project.miniprogramRootPath, ownerJsonPath)).usingComponents;
3302
- if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
3303
- const resolved = /* @__PURE__ */ new Map();
3304
- for (const [alias, rawPath] of Object.entries(usingComponents)) {
3305
- if (typeof rawPath !== "string") continue;
3306
- const basePath = resolvePluginRequest(context.project.plugins, rawPath, "publicComponent")?.resourcePath ?? resolveMiniProgramComponent(ownerFilePath, rawPath, context.project.miniprogramRootPath, (candidate) => readBrowserVirtualFile(context.files, candidate) !== void 0);
3307
- resolved.set(alias, basePath.replace(LEADING_SLASH_RE$5, ""));
3308
- }
3309
- return resolved;
3929
+ if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return;
3930
+ const rawPath = usingComponents[alias];
3931
+ if (typeof rawPath !== "string") return;
3932
+ return (resolvePluginRequest(context.project.plugins, rawPath, "publicComponent")?.resourcePath ?? resolveMiniProgramComponent(ownerFilePath, rawPath, context.project.miniprogramRootPath, (candidate) => readBrowserVirtualFile(context.files, candidate) !== void 0)).replace(LEADING_SLASH_RE$5, "");
3310
3933
  } catch {
3311
- return /* @__PURE__ */ new Map();
3934
+ return;
3312
3935
  }
3313
3936
  }
3314
3937
  function resolveComponentGenerics$1(context, hostNode, ownerJsonPath, ownerFilePath, componentFilePath, ownerGenerics) {
3315
3938
  const componentJsonPath = join(context.project.miniprogramRootPath, `${componentFilePath.replace(JS_FILE_RE$1, "")}.json`);
3316
3939
  const componentGenerics = readComponentConfig$1(context.files, componentJsonPath).componentGenerics;
3317
3940
  if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return;
3318
- const ownerComponents = resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath);
3319
3941
  const resolved = /* @__PURE__ */ new Map();
3320
3942
  for (const [genericName, definition] of Object.entries(componentGenerics)) {
3321
3943
  const selectedAlias = hostNode.attribs?.[`generic:${genericName}`];
3322
- const selectedPath = selectedAlias ? ownerGenerics?.get(selectedAlias) ?? ownerComponents.get(selectedAlias) : void 0;
3944
+ const selectedPath = selectedAlias ? ownerGenerics?.get(selectedAlias) ?? resolveUsingComponent$1(context, ownerJsonPath, ownerFilePath, selectedAlias) : void 0;
3323
3945
  if (selectedPath) {
3324
3946
  resolved.set(genericName, selectedPath);
3325
3947
  continue;
@@ -3370,7 +3992,6 @@ function resolveComponentProperties$1(clonedNode, scope, definition) {
3370
3992
  };
3371
3993
  }
3372
3994
  function createBrowserComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, renderTemplate, bindEventsBeforeProperties = false) {
3373
- const componentProperties = Object.keys(componentEntry.definition.methods ?? {}).some((key) => key.startsWith("__weapp_vite_")) || Object.hasOwn(componentEntry.definition.properties ?? {}, "__wvSlotOwnerId") ? Object.fromEntries(Object.keys(componentEntry.definition.properties ?? {}).filter((key) => Object.hasOwn(nextProperties, key)).map((key) => [key, nextProperties[key]])) : nextProperties;
3374
3995
  const instanceOptions = {
3375
3996
  definition: componentEntry.definition,
3376
3997
  requestRender: (callback) => context.session.requestRender(callback)
@@ -3392,7 +4013,7 @@ function createBrowserComponentInstance(componentScopeId, context, componentEntr
3392
4013
  runComponentLifecycle(componentInstance, "created");
3393
4014
  if (bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
3394
4015
  componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
3395
- syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, [], renderTemplate);
4016
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, {}, [], renderTemplate);
3396
4017
  if (!bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
3397
4018
  return componentInstance;
3398
4019
  } catch (error) {
@@ -3404,9 +4025,9 @@ function createBrowserComponentInstance(componentScopeId, context, componentEntr
3404
4025
  }
3405
4026
  function renderBrowserComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, renderPass) {
3406
4027
  const templatePath = join(context.project.miniprogramRootPath, componentEntry.templatePath);
3407
- const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
4028
+ const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath, context.templateSource));
3408
4029
  const componentRoot = (componentDocument.children ?? [])[0] ?? componentDocument;
3409
- const templateRenderState = prepareTemplateRenderState$1(context.files, componentRoot, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
4030
+ const templateRenderState = prepareTemplateRenderState$1(context.files, componentRoot, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files), context.templateSource);
3410
4031
  return renderNodeTree(componentRoot, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, renderPass, templateRenderState, componentScope.hostNode);
3411
4032
  }
3412
4033
  //#endregion
@@ -3599,8 +4220,10 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
3599
4220
  renderPass.componentRoots.set(componentScopeId, renderedComponentRoot);
3600
4221
  return renderedComponentRoot;
3601
4222
  }
3602
- applyNodeBindings$1(clonedNode, scope);
4223
+ const richText = clonedNode.name === "rich-text";
4224
+ applyNodeBindings$1(clonedNode, scope, richText);
3603
4225
  clonedNode.attribs["data-sim-node"] = instancePath;
4226
+ if (richText) return clonedNode;
3604
4227
  clonedNode.children = renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, renderPass, templateRenderState, clonedNode);
3605
4228
  return clonedNode;
3606
4229
  }
@@ -3611,7 +4234,7 @@ function reconcileBrowserPageTree(context, page, bindingsOnly = false) {
3611
4234
  const route = page.route.replace(LEADING_SLASH_RE$5, "");
3612
4235
  const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
3613
4236
  const templatePath = join(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
3614
- const document = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
4237
+ const document = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath, context.templateSource));
3615
4238
  const pageScopeId = `page:${route}`;
3616
4239
  const pageScope = {
3617
4240
  data: page.data,
@@ -3626,7 +4249,7 @@ function reconcileBrowserPageTree(context, page, bindingsOnly = false) {
3626
4249
  context.componentScopes.set(pageScopeId, pageScope);
3627
4250
  const renderPass = createPageRenderPass(page, context.componentCache);
3628
4251
  const root = (document.children ?? [])[0] ?? document;
3629
- const templateRenderState = prepareTemplateRenderState$1(context.files, root, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
4252
+ const templateRenderState = prepareTemplateRenderState$1(context.files, root, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files), context.templateSource);
3630
4253
  const renderedRoot = renderNodeTree$1(root, pageScope, context, `${resourcePath}.json`, `${resourcePath}.js`, pageScopeId, renderPass, templateRenderState);
3631
4254
  const roots = [renderedRoot];
3632
4255
  if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree$1({
@@ -3667,14 +4290,7 @@ function reconcileBrowserPageTree(context, page, bindingsOnly = false) {
3667
4290
  }), scopeIds);
3668
4291
  if (attached === "restart") continue;
3669
4292
  const canFinalize = !pageAttaching && !hasPendingComponentAttachments(instances);
3670
- const removed = canFinalize ? [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !renderPass.seenComponentScopes.has(scopeId)) : [];
3671
- for (const [scopeId, instance] of removed) if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
3672
- else scheduleDiscardedComponentReady(context.componentCache, scopeId, instance);
3673
- const relationsChanged = canFinalize && syncComponentRelations(context.componentCache, renderPass.seenComponentScopes, pageScopeId);
3674
- for (const [scopeId] of removed) {
3675
- context.componentCache.delete(scopeId);
3676
- context.componentScopes.delete(scopeId);
3677
- }
4293
+ const relationsChanged = canFinalize && reconcileRemovedComponents(context.componentCache, context.componentScopes, renderPass.seenComponentScopes, pageScopeId);
3678
4294
  if (pageAttached || attached || relationsChanged) continue;
3679
4295
  if (canFinalize && !isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
3680
4296
  if (canFinalize && !isPageBeforeReady(page) && flushComponentReady(instances, (instance) => runComponentLifecycle(instance, "ready"))) continue;
@@ -3734,6 +4350,62 @@ function invokePreparedNavigationApi(prepare, option) {
3734
4350
  }
3735
4351
  }
3736
4352
  //#endregion
4353
+ //#region src/kernel/renderQueue.ts
4354
+ /** 两类宿主共享提交、错误诊断与等待回调边界,失败批次不自动重试。 */
4355
+ var RuntimeRenderQueue = class {
4356
+ options;
4357
+ closed = false;
4358
+ pending = false;
4359
+ running = false;
4360
+ callbacks = [];
4361
+ constructor(options) {
4362
+ this.options = options;
4363
+ }
4364
+ close() {
4365
+ this.closed = true;
4366
+ this.pending = false;
4367
+ this.callbacks.length = 0;
4368
+ }
4369
+ request(callback) {
4370
+ if (this.isClosed()) return;
4371
+ if (callback) this.callbacks.push(callback);
4372
+ if (this.pending) return;
4373
+ this.pending = true;
4374
+ if (this.running) return;
4375
+ Promise.resolve().then(async () => {
4376
+ if (this.isClosed()) return;
4377
+ this.pending = false;
4378
+ this.running = true;
4379
+ const callbacks = this.callbacks.splice(0);
4380
+ try {
4381
+ const rendered = this.options.render();
4382
+ if (rendered && typeof rendered.then === "function") await rendered;
4383
+ } catch (error) {
4384
+ this.options.onError(error);
4385
+ callbacks.push(...this.callbacks.splice(0));
4386
+ this.pending = false;
4387
+ } finally {
4388
+ for (const callback of callbacks) {
4389
+ if (this.isClosed()) break;
4390
+ try {
4391
+ callback();
4392
+ } catch (error) {
4393
+ this.options.onError(error);
4394
+ }
4395
+ }
4396
+ this.running = false;
4397
+ if (this.pending && !this.isClosed()) {
4398
+ this.pending = false;
4399
+ this.request();
4400
+ }
4401
+ }
4402
+ });
4403
+ }
4404
+ isClosed() {
4405
+ return this.closed || this.options.isClosed();
4406
+ }
4407
+ };
4408
+ //#endregion
3737
4409
  //#region src/project/hostConfig.ts
3738
4410
  /**
3739
4411
  * @description 根据构建后的 app.json 创建模拟器提供给小程序脚本读取的宿主配置。
@@ -4097,7 +4769,15 @@ var HeadlessRouteEvents = class {
4097
4769
  const callbacks = state.callbacks;
4098
4770
  state.callbacks = void 0;
4099
4771
  try {
4100
- this.bus.$emit("appRouteDone", state.event);
4772
+ const event = state.event;
4773
+ this.bus.$emit("appRouteDone", {
4774
+ path: event.path,
4775
+ query: { ...event.query },
4776
+ openType: event.openType,
4777
+ webviewId: event.webviewId,
4778
+ routeEventId: event.routeEventId,
4779
+ timeStamp: event.timeStamp
4780
+ });
4101
4781
  } finally {
4102
4782
  this.settle(callbacks);
4103
4783
  }
@@ -5910,35 +6590,20 @@ function createHeadlessWxState(scheduler = nativeScheduler, options = {}) {
5910
6590
  };
5911
6591
  }
5912
6592
  //#endregion
5913
- //#region src/view/eventBinding.ts
5914
- function collectMiniProgramEventBindings(attributes = {}) {
5915
- return collectEventBindings(attributes, false).eventBindings;
6593
+ //#region src/view/nodeSerialization.ts
6594
+ function escapeText$2(text) {
6595
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
5916
6596
  }
5917
- function resolveMiniProgramEventBinding(attributes, eventName) {
5918
- return resolveEventBindingPhases(attributes, eventName, false)?.bubble ?? null;
6597
+ function serializeNode(node) {
6598
+ if (node.type === "text") return escapeText$2(node.data ?? "");
6599
+ if (node.type !== "tag") return (node.children ?? []).map(serializeNode).join("");
6600
+ if (node.name === "page") return (node.children ?? []).filter((child) => !(child.type === "tag" && (child.name === "import" || child.name === "wxs"))).map(serializeNode).join("");
6601
+ const attrs = Object.entries(node.attribs ?? {}).filter(([key]) => !key.startsWith("data-sim-")).map(([key, value]) => ` ${key}="${escapeText$2(value).replaceAll("\"", "&quot;")}"`).join("");
6602
+ return `<${node.name ?? ""}${attrs}>${(node.children ?? []).map(serializeNode).join("")}</${node.name ?? ""}>`;
5919
6603
  }
5920
- /** 冒泡时保留原始 target,currentTarget 则属于当前执行绑定的节点。 */
5921
- function createMiniProgramEventPayload(node, eventName, event, origin = node) {
5922
- const dataset = collectNodeDataset(node);
5923
- const nodeId = node.attribs?.id ?? "";
5924
- const isOrigin = node === origin;
5925
- return {
5926
- bubbles: false,
5927
- capturePhase: false,
5928
- composed: false,
5929
- currentTarget: {
5930
- dataset: isOrigin ? event.currentTarget?.dataset ?? event.dataset ?? dataset : dataset,
5931
- id: isOrigin ? event.currentTarget?.id ?? event.id ?? nodeId : nodeId
5932
- },
5933
- detail: event.detail,
5934
- mark: event.mark,
5935
- target: {
5936
- dataset: event.target?.dataset ?? event.dataset ?? (isOrigin ? dataset : collectNodeDataset(origin)),
5937
- id: event.target?.id ?? event.id ?? origin.attribs?.id ?? ""
5938
- },
5939
- timeStamp: Date.now(),
5940
- type: eventName
5941
- };
6604
+ function collectNodeText$1(node) {
6605
+ if (node.type === "text") return node.data ?? "";
6606
+ return (node.children ?? []).map(collectNodeText$1).join("");
5942
6607
  }
5943
6608
  //#endregion
5944
6609
  //#region src/view/selectors.ts
@@ -5990,7 +6655,7 @@ function resolveComponentTags(selectors) {
5990
6655
  }));
5991
6656
  }
5992
6657
  function queryWithAdapter(root, selector, adapter) {
5993
- const parsed = parse(selector);
6658
+ const parsed = parse$1(selector);
5994
6659
  const query = resolveComponentTags(parsed);
5995
6660
  const includesPageRoot = root.type === "tag" && root.name === "page" && parsed.some((group) => group.some((token) => token.type === SelectorType.Tag && token.name === "page"));
5996
6661
  return selectAll(query, includesPageRoot ? [root] : root, {
@@ -6069,30 +6734,12 @@ function queryInspectionXPathElements(root, expression) {
6069
6734
  }
6070
6735
  //#endregion
6071
6736
  //#region src/view/nodeHandle.ts
6072
- function escapeText$2(text) {
6073
- return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
6074
- }
6075
6737
  function createValueEventDetail(value, detail) {
6076
6738
  return {
6077
6739
  value,
6078
6740
  ...detail ?? {}
6079
6741
  };
6080
6742
  }
6081
- function escapeAttribute$2(value) {
6082
- return escapeText$2(value).replaceAll("\"", "&quot;");
6083
- }
6084
- function serializeNode(node) {
6085
- if (node.type === "text") return escapeText$2(node.data ?? "");
6086
- if (node.type !== "tag") return (node.children ?? []).map(serializeNode).join("");
6087
- if (node.name === "page") return (node.children ?? []).filter((child) => !(child.type === "tag" && (child.name === "import" || child.name === "wxs"))).map(serializeNode).join("");
6088
- const attrs = Object.entries(node.attribs ?? {}).filter(([key]) => !key.startsWith("data-sim-")).map(([key, value]) => ` ${key}="${escapeAttribute$2(value)}"`).join("");
6089
- const children = (node.children ?? []).map(serializeNode).join("");
6090
- return `<${node.name ?? ""}${attrs}>${children}</${node.name ?? ""}>`;
6091
- }
6092
- function collectText(node) {
6093
- if (node.type === "text") return node.data ?? "";
6094
- return (node.children ?? []).map(collectText).join("");
6095
- }
6096
6743
  function resolvePageScopeId$1(scopeId) {
6097
6744
  if (!scopeId) return null;
6098
6745
  const pagePathIndex = scopeId.indexOf("/page/");
@@ -6170,7 +6817,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
6170
6817
  }
6171
6818
  async text() {
6172
6819
  this.assertActive();
6173
- return collectText(this.node);
6820
+ return collectNodeText$1(this.node);
6174
6821
  }
6175
6822
  async tagName() {
6176
6823
  this.assertActive();
@@ -6182,10 +6829,23 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
6182
6829
  const normalizedEventName = eventName.trim();
6183
6830
  if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
6184
6831
  let handlerResults;
6185
- const nativeHandled = this.interactions.dispatchNativeEvent?.(this.node, normalizedEventName, event, normalizedEventName === "tap" ? (result) => {
6186
- handlerResults ??= [];
6187
- handlerResults.push(result);
6188
- } : void 0);
6832
+ let nativeHandled;
6833
+ try {
6834
+ nativeHandled = this.interactions.dispatchNativeEvent?.(this.node, normalizedEventName, event, normalizedEventName === "tap" ? (result) => {
6835
+ handlerResults ??= [];
6836
+ handlerResults.push(result);
6837
+ } : void 0);
6838
+ } catch (error) {
6839
+ let failures;
6840
+ if (handlerResults) {
6841
+ for (const result of await Promise.allSettled(handlerResults)) if (result.status === "rejected") {
6842
+ failures ??= [error];
6843
+ failures.push(result.reason);
6844
+ }
6845
+ }
6846
+ if (failures) throw new AggregateError(failures, "Native interaction handlers failed", { cause: error });
6847
+ throw error;
6848
+ }
6189
6849
  if (normalizedEventName === "tap" && nativeHandled) return handlerResults ? (await Promise.all(handlerResults))[0] : void 0;
6190
6850
  const binding = resolveMiniProgramEventBinding(this.node.attribs, normalizedEventName);
6191
6851
  if (!binding?.method) {
@@ -6197,6 +6857,20 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
6197
6857
  async tap(event = {}) {
6198
6858
  return await this.trigger("tap", event);
6199
6859
  }
6860
+ async touchstart(event = {}) {
6861
+ return await this.trigger("touchstart", event);
6862
+ }
6863
+ async touchmove(event = {}) {
6864
+ return await this.trigger("touchmove", event);
6865
+ }
6866
+ async touchend(event = {}) {
6867
+ return await this.trigger("touchend", event);
6868
+ }
6869
+ async dispatchEvent({ eventName, $: selector, ...event }) {
6870
+ const target = selector ? await this.$(selector) : this;
6871
+ if (!target) throw new Error(`No node matching "${selector}" was found for dispatchEvent in headless testing runtime.`);
6872
+ return await target.trigger(eventName, event);
6873
+ }
6200
6874
  async input(value, event = {}) {
6201
6875
  return await this.trigger("input", {
6202
6876
  ...event,
@@ -6249,16 +6923,20 @@ function isMustacheOnly$1(value) {
6249
6923
  return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
6250
6924
  }
6251
6925
  function visitDom(node, visitor) {
6252
- visitor(node);
6926
+ if (visitor(node) === false) return;
6253
6927
  for (const child of node.children ?? []) visitDom(child, visitor);
6254
6928
  }
6255
6929
  function interpolateDomTree(root, data) {
6256
6930
  visitDom(root, (node) => {
6931
+ const richText = node.type === "tag" && node.name === "rich-text";
6932
+ if (richText) node.children = [];
6257
6933
  if (typeof node.data === "string") node.data = interpolateTemplateText(node.data, data);
6258
6934
  if (node.attribs) {
6259
6935
  let dataset;
6260
6936
  for (const [key, value] of Object.entries(node.attribs)) {
6261
6937
  const resolvedValue = isMustacheOnly$1(value) ? resolveRawValueByPath$1(data, value.trim().slice(2, -2)) : interpolateTemplate$1(value, data);
6938
+ if (key === "value") setNativePickerValue(node, resolvedValue);
6939
+ if (richText && key === "nodes") node.children = renderRichTextNodes(resolvedValue);
6262
6940
  node.attribs[key] = String(resolvedValue ?? "");
6263
6941
  if (isDatasetAttribute(key)) {
6264
6942
  dataset ??= {};
@@ -6267,6 +6945,7 @@ function interpolateDomTree(root, data) {
6267
6945
  }
6268
6946
  node.dataset = dataset;
6269
6947
  }
6948
+ if (richText) return false;
6270
6949
  });
6271
6950
  }
6272
6951
  function escapeText$1(text) {
@@ -6288,11 +6967,12 @@ function renderPageTree(project, page) {
6288
6967
  const templateSource = project.artifactSource.readText(templatePath);
6289
6968
  if (templateSource == null) throw new Error(`Missing template in headless runtime: ${templatePath}`);
6290
6969
  const document = parseDocument(`<page>${templateSource}</page>`, {
6291
- xmlMode: false,
6970
+ xmlMode: true,
6292
6971
  decodeEntities: false,
6293
6972
  recognizeSelfClosing: true
6294
6973
  });
6295
6974
  interpolateDomTree(document, page.data);
6975
+ linkRenderedParents(document);
6296
6976
  return {
6297
6977
  root: document,
6298
6978
  wxml: serializeDomNode$1((document.children ?? [])[0] ?? document)
@@ -6463,7 +7143,7 @@ function getNativeScrollOffset(page, node) {
6463
7143
  };
6464
7144
  }
6465
7145
  /** 原生交互更新宿主状态,导航仍交给统一 wx 路由入口。 */
6466
- function dispatchNativeNodeEvent(page, node, eventName, event, wx, resolveMethod, onHandlerResult) {
7146
+ function dispatchNativeNodeEvent(page, node, eventName, event, wx, resolveMethod, onHandlerResult, resolveComponent) {
6467
7147
  if (eventName === "scroll" && node.name === "scroll-view") {
6468
7148
  const detail = event.detail;
6469
7149
  const state = pageScrollViews.get(page)?.get(nodeKey(node));
@@ -6477,30 +7157,42 @@ function dispatchNativeNodeEvent(page, node, eventName, event, wx, resolveMethod
6477
7157
  if (eventName !== "tap") return false;
6478
7158
  let current = node;
6479
7159
  let navigator;
7160
+ let button;
7161
+ const origin = getNativeNodeOwner(node)?.target ?? node;
6480
7162
  let handlers;
6481
7163
  let handled = false;
6482
- while (current) {
6483
- if (!navigator && current.name === "navigator") navigator = current;
6484
- const binding = resolveMiniProgramEventBinding(current.attribs, "tap");
6485
- if (binding?.method) {
6486
- const call = resolveMethod(current.attribs?.["data-sim-scope"] ?? null, binding.method);
7164
+ const collectHandler = (scopeId, target, binding) => {
7165
+ if (binding.method) {
7166
+ const call = resolveMethod(scopeId, binding.method);
6487
7167
  handlers ??= [];
6488
7168
  handlers.push({
6489
- node: current,
7169
+ event: createMiniProgramEventPayload(target, "tap", event, origin),
6490
7170
  call
6491
7171
  });
6492
7172
  handled = true;
6493
7173
  }
6494
- if (binding?.stopAfter) {
7174
+ };
7175
+ while (current) {
7176
+ if (!navigator && current.name === "navigator") navigator = current;
7177
+ if (!button && current.name === "button") button = current;
7178
+ if (visitNativeNodeEventBindings(current, "tap", collectHandler)) {
6495
7179
  handled = true;
6496
7180
  break;
6497
7181
  }
6498
7182
  current = current.parent;
6499
7183
  }
7184
+ const submit = button ? prepareNativeFormSubmit(button, `page:${page.route}`, event, resolveMethod, resolveComponent) : void 0;
6500
7185
  if (handlers) for (const handler of handlers) {
6501
- const result = handler.call(createMiniProgramEventPayload(handler.node, "tap", event, node));
7186
+ const result = handler.call(handler.event);
6502
7187
  onHandlerResult?.(result);
6503
7188
  }
7189
+ if (submit) {
7190
+ handled = true;
7191
+ if (submit.call) {
7192
+ const result = submit.call(submit.event);
7193
+ onHandlerResult?.(result);
7194
+ }
7195
+ }
6504
7196
  if (!navigator) return handled;
6505
7197
  const openType = navigator.attribs?.["open-type"] ?? "navigate";
6506
7198
  const url = navigator.attribs?.url ?? "";
@@ -7285,6 +7977,64 @@ function createHeadlessMediaQueryObserver(driver, onDisconnect) {
7285
7977
  };
7286
7978
  }
7287
7979
  //#endregion
7980
+ //#region src/view/templateRegistration.ts
7981
+ /** 编译模板及递归依赖共用全局注册图,图外原生模板继续实时读取。 */
7982
+ function createTemplateRegistration(source, projectRoot, compiledTemplatePaths = []) {
7983
+ const root = normalize(projectRoot);
7984
+ const normalizeTemplatePath = (filePath) => {
7985
+ const normalized = normalize(filePath);
7986
+ const local = relative(root, normalized);
7987
+ if (!normalized.endsWith(".wxml") || isAbsolute(local) || local === ".." || local.startsWith("../")) throw new TypeError("Compiled template paths must stay inside the mini-program root and end in .wxml.");
7988
+ return normalized;
7989
+ };
7990
+ const resolveRelativeTemplatePath = (filePath) => {
7991
+ const local = normalize(filePath);
7992
+ if (isAbsolute(local) || local === ".." || local.startsWith("../")) throw new TypeError("Compiled template paths must stay inside the mini-program root and end in .wxml.");
7993
+ return normalizeTemplatePath(join(root, local));
7994
+ };
7995
+ const entries = [...new Set(compiledTemplatePaths.map((filePath) => {
7996
+ if (typeof filePath !== "string" || !filePath || isAbsolute(filePath)) throw new TypeError("Compiled template paths must be project-relative WXML paths.");
7997
+ return resolveRelativeTemplatePath(filePath);
7998
+ }))];
7999
+ let registered = /* @__PURE__ */ new Map();
8000
+ function readSnapshot() {
8001
+ const snapshot = /* @__PURE__ */ new Map();
8002
+ const collect = (filePath) => {
8003
+ filePath = normalizeTemplatePath(filePath);
8004
+ if (snapshot.has(filePath)) return;
8005
+ const content = source.readText(filePath);
8006
+ if (content === void 0) throw new Error(`Missing compiled template during host registration: ${relative(root, filePath)}`);
8007
+ snapshot.set(filePath, content);
8008
+ const visit = (node) => {
8009
+ const request = node.attribs?.src;
8010
+ if ((node.name === "include" || node.name === "import") && request) {
8011
+ const target = (request.endsWith(".wxml") ? request : `${request}.wxml`).replaceAll("\\", "/");
8012
+ if (isAbsolute(target) && !target.startsWith("/")) throw new TypeError("Compiled template paths must stay inside the mini-program root and end in .wxml.");
8013
+ collect(resolveRelativeTemplatePath(target.startsWith("/") ? target.slice(1) : join(relative(root, dirname(filePath)), target)));
8014
+ }
8015
+ for (const child of node.children ?? []) visit(child);
8016
+ };
8017
+ visit(parseWxsTemplateDocument(content));
8018
+ };
8019
+ for (const filePath of entries) collect(filePath);
8020
+ return snapshot;
8021
+ }
8022
+ function reload() {
8023
+ const snapshot = readSnapshot();
8024
+ const changed = snapshot.size !== registered.size || [...snapshot].some(([filePath, content]) => registered.get(filePath) !== content);
8025
+ registered = snapshot;
8026
+ return changed;
8027
+ }
8028
+ reload();
8029
+ return {
8030
+ artifactSource: {
8031
+ has: (filePath) => registered.has(normalize(filePath)) || source.has(filePath),
8032
+ readText: (filePath) => registered.get(normalize(filePath)) ?? source.readText(filePath)
8033
+ },
8034
+ reload
8035
+ };
8036
+ }
8037
+ //#endregion
7288
8038
  //#region src/view/videoContext.ts
7289
8039
  function createEventPayload(node, eventName, detail) {
7290
8040
  const dataset = collectNodeDataset(node);
@@ -7430,6 +8180,7 @@ var BrowserHeadlessSession = class {
7430
8180
  appInstance = null;
7431
8181
  appLifecycle = new HeadlessAppLifecycle();
7432
8182
  moduleLoader;
8183
+ templateRegistration;
7433
8184
  onRender;
7434
8185
  registries;
7435
8186
  currentPageInstance = null;
@@ -7437,9 +8188,14 @@ var BrowserHeadlessSession = class {
7437
8188
  componentCache = /* @__PURE__ */ new Map();
7438
8189
  componentScopes = /* @__PURE__ */ new Map();
7439
8190
  selectorQueryScopeSnapshots = /* @__PURE__ */ new WeakMap();
7440
- renderRequestPending = false;
7441
- renderInProgress = false;
7442
- renderRequestCallbacks = [];
8191
+ renderQueue = new RuntimeRenderQueue({
8192
+ isClosed: () => this.kernel.isClosed,
8193
+ onError: (error) => this.kernel.diagnostics.record("exception", [error]),
8194
+ render: () => {
8195
+ if (this.currentPageInstance) this.renderCurrentPage();
8196
+ return this.onRender?.();
8197
+ }
8198
+ });
7443
8199
  tabBarRoutes;
7444
8200
  tabPages = /* @__PURE__ */ new Map();
7445
8201
  tabBarItems = /* @__PURE__ */ new Map();
@@ -7466,6 +8222,7 @@ var BrowserHeadlessSession = class {
7466
8222
  });
7467
8223
  this.onRender = options.onRender;
7468
8224
  this.project = options.project ?? createBrowserProject(options.files);
8225
+ this.templateRegistration = createTemplateRegistration(this.project.artifactSource, this.project.miniprogramRootPath, options.compiledTemplatePaths);
7469
8226
  this.registries = createHostRegistries();
7470
8227
  const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
7471
8228
  this.tabBarRoutes = /* @__PURE__ */ new Set();
@@ -7597,8 +8354,7 @@ var BrowserHeadlessSession = class {
7597
8354
  failure = { error };
7598
8355
  }
7599
8356
  this.canvasContexts.clear();
7600
- this.renderRequestCallbacks.length = 0;
7601
- this.renderRequestPending = false;
8357
+ this.renderQueue.close();
7602
8358
  this.appLifecycle.close();
7603
8359
  this.routeEvents.close();
7604
8360
  this.wxState.close();
@@ -7620,6 +8376,23 @@ var BrowserHeadlessSession = class {
7620
8376
  this.assertActive();
7621
8377
  return this.pages.slice();
7622
8378
  }
8379
+ /** 显式重载已变更的页面 entry,保留 App 与依赖缓存;调用者随后自行导航。 */
8380
+ reloadPageDefinition(route) {
8381
+ this.assertActive();
8382
+ const record = resolvePageDefinitionReloadRoute(this.project, route);
8383
+ const filePath = join(this.project.miniprogramRootPath, `${record.resourcePath ?? record.route}.js`);
8384
+ return this.moduleLoader.reloadPageModule(filePath, record.route);
8385
+ }
8386
+ /** 显式提交编译模板及其 import/include 依赖;不重载脚本、不导航或替换实例。 */
8387
+ reloadTemplates() {
8388
+ this.assertActive();
8389
+ const changed = this.templateRegistration.reload();
8390
+ if (changed) {
8391
+ closeBrowserWxsLoader(this.moduleLoader);
8392
+ this.requestRender();
8393
+ }
8394
+ return changed;
8395
+ }
7623
8396
  getCurrentPageNavigationBarTitle() {
7624
8397
  return this.currentPageInstance?.__navigationBarTitle__ ?? null;
7625
8398
  }
@@ -7938,6 +8711,7 @@ var BrowserHeadlessSession = class {
7938
8711
  componentCache: this.componentCache,
7939
8712
  componentScopes: this.componentScopes,
7940
8713
  files: this.files,
8714
+ templateSource: this.templateRegistration.artifactSource,
7941
8715
  moduleLoader: this.moduleLoader,
7942
8716
  project: this.project,
7943
8717
  session: {
@@ -7966,35 +8740,18 @@ var BrowserHeadlessSession = class {
7966
8740
  dispatchNativeNodeEvent(node, eventName, event, onHandlerResult) {
7967
8741
  const current = this.requireCurrentPage("dispatchNativeNodeEvent()");
7968
8742
  if (eventName === "tap") this.renderCurrentPage();
7969
- return dispatchNativeNodeEvent(current, node, eventName, event, this.moduleLoader.wx, (scopeId, method) => this.resolveScopeMethod(current, scopeId, method), onHandlerResult);
8743
+ return dispatchNativeNodeEvent(current, node, eventName, event, this.moduleLoader.wx, (scopeId, method) => this.resolveScopeMethod(current, scopeId, method), onHandlerResult, (scopeId) => {
8744
+ const instance = this.componentCache.get(scopeId);
8745
+ const scope = this.componentScopes.get(scopeId);
8746
+ return instance?.__definition__ && scope ? {
8747
+ definition: instance.__definition__,
8748
+ ownerScopeId: scope.ownerScopeId ?? null
8749
+ } : void 0;
8750
+ });
7970
8751
  }
7971
8752
  requestRender(callback) {
7972
8753
  this.assertActive();
7973
- if (callback) this.renderRequestCallbacks.push(callback);
7974
- if (this.renderRequestPending) return;
7975
- this.renderRequestPending = true;
7976
- if (this.renderInProgress) return;
7977
- Promise.resolve().then(async () => {
7978
- if (this.kernel.isClosed) return;
7979
- this.renderRequestPending = false;
7980
- this.renderInProgress = true;
7981
- const callbacks = this.renderRequestCallbacks.splice(0);
7982
- try {
7983
- if (this.currentPageInstance) this.renderCurrentPage();
7984
- const rendered = this.onRender?.();
7985
- if (rendered && typeof rendered.then === "function") await rendered;
7986
- for (const cb of callbacks) {
7987
- if (this.kernel.isClosed) break;
7988
- cb();
7989
- }
7990
- } finally {
7991
- this.renderInProgress = false;
7992
- if (this.renderRequestPending && !this.kernel.isClosed) {
7993
- this.renderRequestPending = false;
7994
- this.requestRender();
7995
- }
7996
- }
7997
- });
8754
+ this.renderQueue.request(callback);
7998
8755
  }
7999
8756
  callScopeMethod(scopeId, methodName, event) {
8000
8757
  const current = this.requireCurrentPage(`scope method "${methodName}"`);
@@ -8218,6 +8975,7 @@ var BrowserHeadlessSession = class {
8218
8975
  componentCache: this.componentCache,
8219
8976
  componentScopes: this.componentScopes,
8220
8977
  files: this.files,
8978
+ templateSource: this.templateRegistration.artifactSource,
8221
8979
  moduleLoader: this.moduleLoader,
8222
8980
  project: this.project,
8223
8981
  session: {
@@ -8318,6 +9076,7 @@ var BrowserHeadlessSession = class {
8318
9076
  componentCache: this.componentCache,
8319
9077
  componentScopes: this.componentScopes,
8320
9078
  files: this.files,
9079
+ templateSource: this.templateRegistration.artifactSource,
8321
9080
  moduleLoader: this.moduleLoader,
8322
9081
  project: this.project,
8323
9082
  session: {
@@ -8820,7 +9579,7 @@ function resolveComponentAttributeValue(value, scope) {
8820
9579
  }
8821
9580
  return interpolateTemplate(value, wxsScopeData(scope));
8822
9581
  }
8823
- function applyNodeBindings(node, scope) {
9582
+ function applyNodeBindings(node, scope, richText = false) {
8824
9583
  if (!isTagNode(node)) {
8825
9584
  if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplateText(node.data, wxsScopeData(scope));
8826
9585
  return;
@@ -8828,6 +9587,7 @@ function applyNodeBindings(node, scope) {
8828
9587
  node.attribs ??= {};
8829
9588
  node.attribs["data-sim-scope"] = scope.getScopeId();
8830
9589
  for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
9590
+ if (richText) node.children = [];
8831
9591
  let dataset;
8832
9592
  for (const [key, value] of Object.entries({ ...node.attribs })) {
8833
9593
  if (EVENT_BINDING_ATTRS.includes(key)) {
@@ -8835,6 +9595,8 @@ function applyNodeBindings(node, scope) {
8835
9595
  continue;
8836
9596
  }
8837
9597
  const resolvedValue = typeof value === "string" ? resolveAttributeValue(value, scope) : value;
9598
+ if (key === "value") setNativePickerValue(node, resolvedValue);
9599
+ if (richText && key === "nodes") node.children = renderRichTextNodes(resolvedValue);
8838
9600
  node.attribs[key] = String(resolvedValue ?? "");
8839
9601
  if (isDatasetAttribute(key)) {
8840
9602
  dataset ??= {};
@@ -8861,8 +9623,7 @@ function createLoopScope(scope, itemName, indexName, item, index) {
8861
9623
  //#endregion
8862
9624
  //#region src/runtime/render/component.ts
8863
9625
  function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias, genericComponentBasePath) {
8864
- const usingComponents = resolveUsingComponents(context, ownerJsonPath, ownerFilePath);
8865
- const componentBasePath = genericComponentBasePath ?? usingComponents.get(alias);
9626
+ const componentBasePath = genericComponentBasePath ?? resolveUsingComponent(context, ownerJsonPath, ownerFilePath, alias);
8866
9627
  if (!componentBasePath) return null;
8867
9628
  const filePath = `${componentBasePath}.js`;
8868
9629
  const templatePath = `${componentBasePath}.wxml`;
@@ -8883,30 +9644,25 @@ function readComponentConfig(artifactSource, jsonPath) {
8883
9644
  return {};
8884
9645
  }
8885
9646
  }
8886
- function resolveUsingComponents(context, ownerJsonPath, ownerFilePath) {
9647
+ function resolveUsingComponent(context, ownerJsonPath, ownerFilePath, alias) {
8887
9648
  try {
8888
9649
  const usingComponents = readComponentConfig(context.artifactSource, ownerJsonPath).usingComponents;
8889
- if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
8890
- const resolved = /* @__PURE__ */ new Map();
8891
- for (const [alias, rawPath] of Object.entries(usingComponents)) {
8892
- if (typeof rawPath !== "string") continue;
8893
- const basePath = resolvePluginRequest(context.project.plugins, rawPath, "publicComponent")?.resourcePath ?? resolveMiniProgramComponent(ownerFilePath, rawPath, context.project.miniprogramRootPath, (candidate) => context.artifactSource.readText(candidate) !== void 0);
8894
- resolved.set(alias, basePath.replace(LEADING_SLASH_RE$2, ""));
8895
- }
8896
- return resolved;
9650
+ if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return;
9651
+ const rawPath = usingComponents[alias];
9652
+ if (typeof rawPath !== "string") return;
9653
+ return (resolvePluginRequest(context.project.plugins, rawPath, "publicComponent")?.resourcePath ?? resolveMiniProgramComponent(ownerFilePath, rawPath, context.project.miniprogramRootPath, (candidate) => context.artifactSource.has(candidate))).replace(LEADING_SLASH_RE$2, "");
8897
9654
  } catch {
8898
- return /* @__PURE__ */ new Map();
9655
+ return;
8899
9656
  }
8900
9657
  }
8901
9658
  function resolveComponentGenerics(context, hostNode, ownerJsonPath, ownerFilePath, componentFilePath, ownerGenerics) {
8902
9659
  const componentJsonPath = path.resolve(context.project.miniprogramRootPath, `${componentFilePath.replace(JS_FILE_RE, "")}.json`);
8903
9660
  const componentGenerics = readComponentConfig(context.artifactSource, componentJsonPath).componentGenerics;
8904
9661
  if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return;
8905
- const ownerComponents = resolveUsingComponents(context, ownerJsonPath, ownerFilePath);
8906
9662
  const resolved = /* @__PURE__ */ new Map();
8907
9663
  for (const [genericName, definition] of Object.entries(componentGenerics)) {
8908
9664
  const selectedAlias = hostNode.attribs?.[`generic:${genericName}`];
8909
- const selectedPath = selectedAlias ? ownerGenerics?.get(selectedAlias) ?? ownerComponents.get(selectedAlias) : void 0;
9665
+ const selectedPath = selectedAlias ? ownerGenerics?.get(selectedAlias) ?? resolveUsingComponent(context, ownerJsonPath, ownerFilePath, selectedAlias) : void 0;
8910
9666
  if (selectedPath) {
8911
9667
  resolved.set(genericName, selectedPath);
8912
9668
  continue;
@@ -8957,7 +9713,6 @@ function resolveComponentProperties(clonedNode, scope, definition) {
8957
9713
  };
8958
9714
  }
8959
9715
  function createRuntimeComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, renderTemplate, bindEventsBeforeProperties = false) {
8960
- const componentProperties = Object.keys(componentEntry.definition.methods ?? {}).some((key) => key.startsWith("__weapp_vite_")) || Object.hasOwn(componentEntry.definition.properties ?? {}, "__wvSlotOwnerId") ? Object.fromEntries(Object.keys(componentEntry.definition.properties ?? {}).filter((key) => Object.hasOwn(nextProperties, key)).map((key) => [key, nextProperties[key]])) : nextProperties;
8961
9716
  const instanceOptions = {
8962
9717
  definition: componentEntry.definition,
8963
9718
  requestRender: (callback) => context.session.requestRender(callback)
@@ -8979,7 +9734,7 @@ function createRuntimeComponentInstance(componentScopeId, context, componentEntr
8979
9734
  runComponentLifecycle(componentInstance, "created");
8980
9735
  if (bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
8981
9736
  componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
8982
- syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, [], renderTemplate);
9737
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, {}, [], renderTemplate);
8983
9738
  if (!bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
8984
9739
  return componentInstance;
8985
9740
  } catch (error) {
@@ -9189,8 +9944,10 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
9189
9944
  renderPass.componentRoots.set(componentScopeId, renderedComponentRoot);
9190
9945
  return renderedComponentRoot;
9191
9946
  }
9192
- applyNodeBindings(clonedNode, scope);
9947
+ const richText = clonedNode.name === "rich-text";
9948
+ applyNodeBindings(clonedNode, scope, richText);
9193
9949
  clonedNode.attribs["data-sim-node"] = instancePath;
9950
+ if (richText) return clonedNode;
9194
9951
  clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, renderPass, templateRenderState, clonedNode);
9195
9952
  return clonedNode;
9196
9953
  }
@@ -9255,14 +10012,7 @@ function reconcileRuntimePageTree(context, page, bindingsOnly = false) {
9255
10012
  }), scopeIds);
9256
10013
  if (attached === "restart") continue;
9257
10014
  const canFinalize = !pageAttaching && !hasPendingComponentAttachments(instances);
9258
- const removed = canFinalize ? [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !renderPass.seenComponentScopes.has(scopeId)) : [];
9259
- for (const [scopeId, instance] of removed) if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
9260
- else scheduleDiscardedComponentReady(context.componentCache, scopeId, instance);
9261
- const relationsChanged = canFinalize && syncComponentRelations(context.componentCache, renderPass.seenComponentScopes, pageScopeId);
9262
- for (const [scopeId] of removed) {
9263
- context.componentCache.delete(scopeId);
9264
- context.componentScopes.delete(scopeId);
9265
- }
10015
+ const relationsChanged = canFinalize && reconcileRemovedComponents(context.componentCache, context.componentScopes, renderPass.seenComponentScopes, pageScopeId);
9266
10016
  if (pageAttached || attached || relationsChanged) continue;
9267
10017
  if (canFinalize && !isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
9268
10018
  if (canFinalize && !isPageBeforeReady(page) && flushComponentReady(instances, (instance) => {
@@ -9284,102 +10034,6 @@ function renderRuntimePageTree(context, page) {
9284
10034
  }
9285
10035
  //#endregion
9286
10036
  //#region src/runtime/moduleLoader.ts
9287
- const ESM_IMPORT_LINE_RE = /^[ \t]*import[^\n]*$/gm;
9288
- const ESM_EXPORT_LIST_RE = /^[ \t]*export[ \t]*\{([^}\n]+)\}[ \t]*;?$/gm;
9289
- const ESM_EXPORT_DECLARATION_RE = /\bexport\s+(const|let|var|function|class)\s+([A-Za-z_$][\w$]*)/g;
9290
- const ESM_EXPORT_DEFAULT_DECLARATION_RE = /\bexport\s+default\s+(function|class)\s+([A-Za-z_$][\w$]*)/g;
9291
- function isImportWhitespace(value) {
9292
- return value === " " || value === " ";
9293
- }
9294
- function parseEsmImportLine(line) {
9295
- let statement = line.trim().slice(6).trim();
9296
- if (statement.endsWith(";")) statement = statement.slice(0, -1).trimEnd();
9297
- if (statement.startsWith("\"") || statement.startsWith("'")) {
9298
- const quote = statement[0];
9299
- if (statement.endsWith(quote) && statement.length > 1) return {
9300
- request: statement.slice(1, -1),
9301
- sideEffect: true
9302
- };
9303
- return;
9304
- }
9305
- let fromIndex = statement.indexOf("from");
9306
- while (fromIndex >= 0) {
9307
- if (isImportWhitespace(statement[fromIndex - 1]) && isImportWhitespace(statement[fromIndex + 4])) break;
9308
- fromIndex = statement.indexOf("from", fromIndex + 4);
9309
- }
9310
- if (fromIndex < 0) return;
9311
- const specifier = statement.slice(0, fromIndex).trim();
9312
- const requestLiteral = statement.slice(fromIndex + 4).trim();
9313
- const quote = requestLiteral[0];
9314
- if (!specifier || quote !== "\"" && quote !== "'" || requestLiteral.length < 2 || !requestLiteral.endsWith(quote)) return;
9315
- return {
9316
- request: requestLiteral.slice(1, -1),
9317
- sideEffect: false,
9318
- specifier
9319
- };
9320
- }
9321
- function createEsmImportBindings(specifier, request, index) {
9322
- const namespaceName = `__headlessEsmImport${index}`;
9323
- const statements = [`const ${namespaceName} = require(${JSON.stringify(request)});`];
9324
- const normalizedSpecifier = specifier.trim();
9325
- if (normalizedSpecifier.startsWith("{") && normalizedSpecifier.endsWith("}")) {
9326
- const entries = normalizedSpecifier.slice(1, -1).split(",");
9327
- for (const entry of entries) {
9328
- const [importedName, localName] = entry.trim().split(/\s+as\s+/);
9329
- if (!importedName) continue;
9330
- const bindingName = localName || importedName;
9331
- statements.push(`const ${bindingName} = ${namespaceName}[${JSON.stringify(importedName)}];`);
9332
- }
9333
- return statements.join("\n");
9334
- }
9335
- if (normalizedSpecifier.startsWith("* as ")) {
9336
- const bindingName = normalizedSpecifier.slice(5).trim();
9337
- statements.push(`const ${bindingName} = ${namespaceName};`);
9338
- return statements.join("\n");
9339
- }
9340
- const [defaultName, namedPart] = normalizedSpecifier.split(/\s*,\s*/, 2);
9341
- if (defaultName) statements.push(`const ${defaultName.trim()} = ${namespaceName}.default ?? ${namespaceName};`);
9342
- if (namedPart?.startsWith("{") && namedPart.endsWith("}")) statements.push(createEsmImportBindings(namedPart, request, index).split("\n").slice(1).join("\n"));
9343
- return statements.join("\n");
9344
- }
9345
- function transformEsmToCommonJs(source) {
9346
- if (!/^\s*(?:import|export)\b/m.test(source)) return source;
9347
- let importIndex = 0;
9348
- const exportedNames = [];
9349
- let transformed = source.replace(ESM_IMPORT_LINE_RE, (line) => {
9350
- const parsed = parseEsmImportLine(line);
9351
- if (!parsed) return line;
9352
- if (parsed.sideEffect) return `require(${JSON.stringify(parsed.request)});`;
9353
- return createEsmImportBindings(parsed.specifier, parsed.request, importIndex++);
9354
- });
9355
- transformed = transformed.replace(ESM_EXPORT_LIST_RE, (_match, entries) => {
9356
- for (const entry of entries.split(",")) {
9357
- const [local, exported] = entry.trim().split(/\s+as\s+/);
9358
- if (local) exportedNames.push({
9359
- exported: exported || local,
9360
- local
9361
- });
9362
- }
9363
- return "";
9364
- });
9365
- transformed = transformed.replace(ESM_EXPORT_DEFAULT_DECLARATION_RE, (_match, kind, local) => {
9366
- exportedNames.push({
9367
- exported: "default",
9368
- local
9369
- });
9370
- return `${kind} ${local}`;
9371
- });
9372
- transformed = transformed.replace(ESM_EXPORT_DECLARATION_RE, (_match, kind, local) => {
9373
- exportedNames.push({
9374
- exported: local,
9375
- local
9376
- });
9377
- return `${kind} ${local}`;
9378
- });
9379
- transformed = transformed.replace(/\bexport\s+default\s+/g, "module.exports.default = ");
9380
- if (exportedNames.length > 0) transformed += `\n${exportedNames.map(({ exported, local }) => `module.exports[${JSON.stringify(exported)}] = ${local};`).join("\n")}`;
9381
- return transformed;
9382
- }
9383
10037
  function createRequireNotFoundError(request, importer) {
9384
10038
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in headless runtime.`);
9385
10039
  }
@@ -9439,6 +10093,7 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
9439
10093
  const source = options.artifactSource.readText(resolvedPath);
9440
10094
  if (source == null) throw new TypeError(`Missing module in headless runtime: ${normalize(resolvedPath)}`);
9441
10095
  const module = {
10096
+ source,
9442
10097
  componentDefinitions: [],
9443
10098
  exports: {}
9444
10099
  };
@@ -9448,7 +10103,7 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
9448
10103
  const previousLoadContext = registries.currentLoadContext;
9449
10104
  registries.currentLoadContext = loadContext;
9450
10105
  const localRequire = ((request) => {
9451
- const requiredPath = resolveMiniProgramModule(resolvedPath, request, options.miniprogramRootPath, (candidate) => options.artifactSource.readText(candidate) !== void 0);
10106
+ const requiredPath = resolveMiniProgramModule(resolvedPath, request, options.miniprogramRootPath, (candidate) => options.artifactSource.has(candidate));
9452
10107
  if (!requiredPath) throw createRequireNotFoundError(request, resolvedPath);
9453
10108
  if (requiredPath.endsWith(".json")) {
9454
10109
  const content = options.artifactSource.readText(requiredPath);
@@ -9461,7 +10116,7 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
9461
10116
  });
9462
10117
  localRequire.async = (request) => Promise.resolve().then(() => localRequire(request));
9463
10118
  try {
9464
- new vm.Script(`(function (exports, module, require, __filename, __dirname) { ${transformEsmToCommonJs(source)}\n})`, { filename: resolvedPath }).runInNewContext(executionContext)(module.exports, module, localRequire, resolvedPath, path.dirname(resolvedPath));
10119
+ new vm.Script(`(function (exports, module, require, __filename, __dirname) { ${transformMiniProgramModule(source)}\n})`, { filename: resolvedPath }).runInNewContext(executionContext)(module.exports, module, localRequire, resolvedPath, path.dirname(resolvedPath));
9465
10120
  const registeredDefinitions = [...registries.components.values()].filter((definition) => !registeredDefinitionsBefore.has(definition));
9466
10121
  module.componentDefinitions = [.../* @__PURE__ */ new Set([
9467
10122
  ...requiredComponentDefinitions,
@@ -9508,6 +10163,17 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
9508
10163
  if (!definition) throw new Error(`Page() was not registered for route "${route}" while executing ${normalize(filePath)}.`);
9509
10164
  return definition;
9510
10165
  },
10166
+ reloadPageModule(filePath, route) {
10167
+ const resolvedPath = path.resolve(filePath);
10168
+ return reloadPageModuleDefinition({
10169
+ filePath: resolvedPath,
10170
+ route,
10171
+ source: options.artifactSource.readText(resolvedPath),
10172
+ cache: moduleCache,
10173
+ registries,
10174
+ execute: () => loader.executePageModule(resolvedPath, route)
10175
+ });
10176
+ },
9511
10177
  executeComponentModule(filePath, id) {
9512
10178
  const loadedModule = executeModule(filePath, {
9513
10179
  kind: "component",
@@ -9593,6 +10259,7 @@ var HeadlessSession = class {
9593
10259
  appInstance = null;
9594
10260
  appLifecycle = new HeadlessAppLifecycle();
9595
10261
  moduleLoader;
10262
+ templateRegistration;
9596
10263
  routeEvents = new HeadlessRouteEvents((callback) => this.requestRender(callback), (page) => this.currentPageInstance === page && !this.kernel.isClosed);
9597
10264
  eventListeners = /* @__PURE__ */ new Map();
9598
10265
  registries;
@@ -9601,8 +10268,13 @@ var HeadlessSession = class {
9601
10268
  componentCache = /* @__PURE__ */ new Map();
9602
10269
  componentScopes = /* @__PURE__ */ new Map();
9603
10270
  selectorQueryScopeSnapshots = /* @__PURE__ */ new WeakMap();
9604
- renderRequestPending = false;
9605
- renderRequestCallbacks = [];
10271
+ renderQueue = new RuntimeRenderQueue({
10272
+ isClosed: () => this.kernel.isClosed,
10273
+ onError: (error) => this.kernel.diagnostics.record("exception", [error]),
10274
+ render: () => {
10275
+ if (this.currentPageInstance) this.renderCurrentPage();
10276
+ }
10277
+ });
9606
10278
  tabBarRoutes;
9607
10279
  tabPages = /* @__PURE__ */ new Map();
9608
10280
  tabBarItems = /* @__PURE__ */ new Map();
@@ -9621,6 +10293,7 @@ var HeadlessSession = class {
9621
10293
  constructor(options) {
9622
10294
  if (!options.project && !options.projectPath) throw new Error("Headless runtime requires projectPath or project.");
9623
10295
  this.project = options.project ?? loadProject(options.projectPath);
10296
+ this.templateRegistration = createTemplateRegistration(this.project.artifactSource, this.project.miniprogramRootPath, options.compiledTemplatePaths);
9624
10297
  this.wxState = createHeadlessWxState(this.kernel.scheduler, {
9625
10298
  strictMocks: options.strictHostMocks,
9626
10299
  readPackageFile: createPackageAssetReader((relative) => this.project.artifactSource.readText(path.join(this.project.miniprogramRootPath, relative)))
@@ -9758,8 +10431,7 @@ var HeadlessSession = class {
9758
10431
  failure = { error };
9759
10432
  }
9760
10433
  this.canvasContexts.clear();
9761
- this.renderRequestCallbacks.length = 0;
9762
- this.renderRequestPending = false;
10434
+ this.renderQueue.close();
9763
10435
  this.appLifecycle.close();
9764
10436
  this.routeEvents.close();
9765
10437
  this.wxState.close();
@@ -9809,6 +10481,23 @@ var HeadlessSession = class {
9809
10481
  this.assertActive();
9810
10482
  return this.pages.slice();
9811
10483
  }
10484
+ /** 显式重载已变更的页面 entry,保留 App 与依赖缓存;调用者随后自行导航。 */
10485
+ reloadPageDefinition(route) {
10486
+ this.assertActive();
10487
+ const record = resolvePageDefinitionReloadRoute(this.project, route);
10488
+ const filePath = path.resolve(this.project.miniprogramRootPath, `${record.resourcePath ?? record.route}.js`);
10489
+ return this.moduleLoader.reloadPageModule(filePath, record.route);
10490
+ }
10491
+ /** 显式提交编译模板及其 import/include 依赖;不重载脚本、不导航或替换实例。 */
10492
+ reloadTemplates() {
10493
+ this.assertActive();
10494
+ const changed = this.templateRegistration.reload();
10495
+ if (changed) {
10496
+ closeRuntimeWxsLoader(this.moduleLoader);
10497
+ this.requestRender();
10498
+ }
10499
+ return changed;
10500
+ }
9812
10501
  getWx() {
9813
10502
  this.assertActive();
9814
10503
  return this.moduleLoader.wx;
@@ -9864,7 +10553,7 @@ var HeadlessSession = class {
9864
10553
  const current = this.requireCurrentPage("renderCurrentPage()");
9865
10554
  const rendered = renderRuntimePageTree({
9866
10555
  changedPageKeys: current.__lastChangedKeys__ ?? [],
9867
- artifactSource: this.project.artifactSource,
10556
+ artifactSource: this.templateRegistration.artifactSource,
9868
10557
  componentCache: this.componentCache,
9869
10558
  componentScopes: this.componentScopes,
9870
10559
  moduleLoader: this.moduleLoader,
@@ -9894,20 +10583,18 @@ var HeadlessSession = class {
9894
10583
  dispatchNativeNodeEvent(node, eventName, event, onHandlerResult) {
9895
10584
  const current = this.requireCurrentPage("dispatchNativeNodeEvent()");
9896
10585
  if (eventName === "tap") this.renderCurrentPage();
9897
- return dispatchNativeNodeEvent(current, node, eventName, event, this.moduleLoader.wx, (scopeId, method) => this.resolveScopeMethod(current, scopeId, method), onHandlerResult);
10586
+ return dispatchNativeNodeEvent(current, node, eventName, event, this.moduleLoader.wx, (scopeId, method) => this.resolveScopeMethod(current, scopeId, method), onHandlerResult, (scopeId) => {
10587
+ const instance = this.componentCache.get(scopeId);
10588
+ const scope = this.componentScopes.get(scopeId);
10589
+ return instance?.__definition__ && scope ? {
10590
+ definition: instance.__definition__,
10591
+ ownerScopeId: scope.ownerScopeId ?? null
10592
+ } : void 0;
10593
+ });
9898
10594
  }
9899
10595
  requestRender(callback) {
9900
10596
  this.assertActive();
9901
- if (callback) this.renderRequestCallbacks.push(callback);
9902
- if (this.renderRequestPending) return;
9903
- this.renderRequestPending = true;
9904
- Promise.resolve().then(() => {
9905
- if (this.kernel.isClosed) return;
9906
- this.renderRequestPending = false;
9907
- const callbacks = this.renderRequestCallbacks.splice(0);
9908
- if (this.currentPageInstance) this.renderCurrentPage();
9909
- callbacks.forEach((cb) => cb());
9910
- });
10597
+ this.renderQueue.request(callback);
9911
10598
  }
9912
10599
  getScopeSnapshot(scopeId) {
9913
10600
  const scope = this.componentScopes.get(scopeId);
@@ -11132,6 +11819,133 @@ var HeadlessTestingPageHandle = class {
11132
11819
  }
11133
11820
  };
11134
11821
  //#endregion
11822
+ //#region src/testing/sessionHandle/protocol.ts
11823
+ /** 无头协议只公布已有运行时语义;不把宿主缺失能力伪装为调试器结果。 */
11824
+ var HeadlessTestingProtocolUnsupportedError = class extends Error {
11825
+ method;
11826
+ code = HEADLESS_PROTOCOL_UNSUPPORTED;
11827
+ constructor(method) {
11828
+ super(`Protocol method ${method} is not supported by the headless testing runtime.`);
11829
+ this.method = method;
11830
+ this.name = "HeadlessTestingProtocolUnsupportedError";
11831
+ }
11832
+ };
11833
+ function requireString(params, name) {
11834
+ const value = params[name];
11835
+ if (typeof value !== "string" || !value.trim()) throw new TypeError(`Protocol parameter ${name} must be a non-empty string.`);
11836
+ return value;
11837
+ }
11838
+ function readArgs(params) {
11839
+ if (params.args === void 0) return [];
11840
+ if (!Array.isArray(params.args)) throw new TypeError("Protocol parameter args must be an array.");
11841
+ return cloneProtocolValue(params.args);
11842
+ }
11843
+ function pageSnapshot(page) {
11844
+ return {
11845
+ pageId: page.pageId,
11846
+ path: page.path,
11847
+ query: page.query
11848
+ };
11849
+ }
11850
+ async function dispatch(target, method, params) {
11851
+ switch (method) {
11852
+ case "Tool.getInfo": return await target.toolInfo();
11853
+ case "App.getCurrentPage": {
11854
+ const page = await target.currentPage();
11855
+ return page ? pageSnapshot(page) : null;
11856
+ }
11857
+ case "App.getPageStack": return { pageStack: (await target.getCurrentPages()).map(pageSnapshot) };
11858
+ case "App.callFunction": return { result: cloneProtocolValue(await target.evaluateWithOptions(requireString(params, "functionDeclaration"), {}, ...readArgs(params))) };
11859
+ case "App.callWxMethod": return { result: cloneProtocolValue(await target.callWxMethodWithOptions(requireString(params, "method"), {}, ...readArgs(params))) };
11860
+ default: throw new HeadlessTestingProtocolUnsupportedError(method);
11861
+ }
11862
+ }
11863
+ async function sendHeadlessTestingProtocol(target, method, params, options) {
11864
+ let rejectClosed;
11865
+ const closed = new Promise((_resolve, reject) => {
11866
+ rejectClosed = reject;
11867
+ });
11868
+ const onClose = () => rejectClosed(/* @__PURE__ */ new Error(`The headless testing session closed before protocol method ${method} completed.`));
11869
+ target.on("close", onClose);
11870
+ try {
11871
+ return await runWithTimeout(() => Promise.race([dispatch(target, method, params), closed]), options.timeout, `Timed out executing protocol method ${method} in headless testing runtime.`);
11872
+ } finally {
11873
+ target.off("close", onClose);
11874
+ }
11875
+ }
11876
+ //#endregion
11877
+ //#region src/testing/sessionHandle/cdp.ts
11878
+ /** 保留官方调用形状;当前后端的 enable 会明确报告不支持。 */
11879
+ function createHeadlessTestingCDP(target, assertActive) {
11880
+ let enabling;
11881
+ const enable = (options) => {
11882
+ enabling ??= target.send("App.CDPEnable", {}, options).catch((error) => {
11883
+ enabling = void 0;
11884
+ throw error;
11885
+ });
11886
+ return enabling;
11887
+ };
11888
+ return {
11889
+ enable,
11890
+ async sendCommand(domain, method, params = {}, options) {
11891
+ await enable(options);
11892
+ return await target.send("App.CDPCommand", {
11893
+ domain,
11894
+ method,
11895
+ params
11896
+ }, options);
11897
+ },
11898
+ async listProtocol(options) {
11899
+ await enable(options);
11900
+ return await target.send("App.CDPListProtocol", {}, options);
11901
+ },
11902
+ onEvent() {
11903
+ assertActive();
11904
+ throw new HeadlessTestingProtocolUnsupportedError("App.CDPEvent");
11905
+ }
11906
+ };
11907
+ }
11908
+ //#endregion
11909
+ //#region src/testing/sessionHandle/navigation.ts
11910
+ /** 所有测试句柄通过同一个 wx 导航边界等待成功、失败或关闭通知。 */
11911
+ var HeadlessTestingNavigation = class {
11912
+ session;
11913
+ pending = /* @__PURE__ */ new Set();
11914
+ constructor(session) {
11915
+ this.session = session;
11916
+ session.on("close", () => {
11917
+ for (const reject of this.pending) reject(/* @__PURE__ */ new Error("The headless testing session closed before navigation completed."));
11918
+ this.pending.clear();
11919
+ });
11920
+ }
11921
+ invoke(methodName, options) {
11922
+ return new Promise((resolve, reject) => {
11923
+ const rejectNavigation = (error) => {
11924
+ this.pending.delete(rejectNavigation);
11925
+ reject(error);
11926
+ };
11927
+ this.pending.add(rejectNavigation);
11928
+ try {
11929
+ this.session.callWxMethod(methodName, {
11930
+ ...options,
11931
+ success: () => {
11932
+ this.pending.delete(rejectNavigation);
11933
+ resolve();
11934
+ },
11935
+ fail: (error) => {
11936
+ const details = error && typeof error === "object" ? error : void 0;
11937
+ const reason = typeof details?.errMsg === "string" ? details.errMsg : typeof details?.message === "string" ? details.message : String(error);
11938
+ const target = options.url ? ` route "${options.url}"` : "";
11939
+ rejectNavigation(new Error(`Failed to ${methodName}${target} through the headless wx runtime: ${reason}`, { cause: error }));
11940
+ }
11941
+ });
11942
+ } catch (error) {
11943
+ rejectNavigation(error);
11944
+ }
11945
+ });
11946
+ }
11947
+ };
11948
+ //#endregion
11135
11949
  //#region src/testing/sessionHandle/scope.ts
11136
11950
  var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
11137
11951
  scopeId;
@@ -11193,20 +12007,41 @@ var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
11193
12007
  var HeadlessTestingSessionHandle = class {
11194
12008
  project;
11195
12009
  session;
11196
- pendingNavigations = /* @__PURE__ */ new Set();
12010
+ navigation;
12011
+ disconnection;
12012
+ cdp;
11197
12013
  constructor(project, session) {
11198
12014
  this.project = project;
11199
12015
  this.session = session;
11200
- this.session.on("close", () => {
11201
- for (const reject of this.pendingNavigations) reject(/* @__PURE__ */ new Error("The headless testing session closed before navigation completed."));
11202
- });
12016
+ this.navigation = new HeadlessTestingNavigation(session);
11203
12017
  }
11204
- async close() {
11205
- this.disconnect();
12018
+ close() {
12019
+ return this.disconnect();
11206
12020
  }
11207
- /** 无头会话独占本地 runtime;同步释放与 automator 的连接清理契约一致。 */
12021
+ /** 先保存共享结果,再同步开始关闭,覆盖关闭监听器内的重入调用。 */
11208
12022
  disconnect() {
11209
- this.session.close();
12023
+ if (!this.disconnection) {
12024
+ let resolve;
12025
+ let reject;
12026
+ this.disconnection = new Promise((accept, fail) => {
12027
+ resolve = accept;
12028
+ reject = fail;
12029
+ });
12030
+ try {
12031
+ this.session.close();
12032
+ resolve();
12033
+ } catch (error) {
12034
+ reject(error);
12035
+ }
12036
+ }
12037
+ return this.disconnection;
12038
+ }
12039
+ async send(method, params = {}, options = {}) {
12040
+ this.session.assertActive();
12041
+ return await sendHeadlessTestingProtocol(this, method, params, options);
12042
+ }
12043
+ CDP() {
12044
+ return this.cdp ??= createHeadlessTestingCDP(this, () => this.session.assertActive());
11210
12045
  }
11211
12046
  async toolInfo() {
11212
12047
  return { version: "mpcore-simulator" };
@@ -11276,23 +12111,31 @@ var HeadlessTestingSessionHandle = class {
11276
12111
  }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
11277
12112
  }
11278
12113
  async reLaunch(route) {
11279
- await this.invokeNavigation("reLaunch", { url: route });
12114
+ await this.navigation.invoke("reLaunch", { url: route });
11280
12115
  return await this.requireCurrentPage("reLaunch", route);
11281
12116
  }
12117
+ /** 只更新页面定义;不隐式导航,也不替换当前页面或应用实例。 */
12118
+ async reloadPageDefinition(route) {
12119
+ return this.session.reloadPageDefinition(route);
12120
+ }
12121
+ /** 显式提交宿主编译模板;不隐式重载脚本或导航。 */
12122
+ async reloadTemplates() {
12123
+ return this.session.reloadTemplates();
12124
+ }
11282
12125
  async navigateTo(route) {
11283
- await this.invokeNavigation("navigateTo", { url: route });
12126
+ await this.navigation.invoke("navigateTo", { url: route });
11284
12127
  return await this.requireCurrentPage("navigateTo", route);
11285
12128
  }
11286
12129
  async redirectTo(route) {
11287
- await this.invokeNavigation("redirectTo", { url: route });
12130
+ await this.navigation.invoke("redirectTo", { url: route });
11288
12131
  return await this.requireCurrentPage("redirectTo", route);
11289
12132
  }
11290
12133
  async navigateBack(delta = 1) {
11291
- await this.invokeNavigation("navigateBack", { delta });
12134
+ await this.navigation.invoke("navigateBack", { delta });
11292
12135
  return await this.currentPage();
11293
12136
  }
11294
12137
  async switchTab(route) {
11295
- await this.invokeNavigation("switchTab", { url: route });
12138
+ await this.navigation.invoke("switchTab", { url: route });
11296
12139
  return await this.requireCurrentPage("switchTab", route);
11297
12140
  }
11298
12141
  async waitForCurrentPage(route, options = {}) {
@@ -11328,32 +12171,6 @@ var HeadlessTestingSessionHandle = class {
11328
12171
  async triggerRouteDone(options) {
11329
12172
  this.session.triggerRouteDone(options);
11330
12173
  }
11331
- invokeNavigation(methodName, options) {
11332
- return new Promise((resolve, reject) => {
11333
- const rejectNavigation = (error) => {
11334
- this.pendingNavigations.delete(rejectNavigation);
11335
- reject(error);
11336
- };
11337
- this.pendingNavigations.add(rejectNavigation);
11338
- try {
11339
- this.session.callWxMethod(methodName, {
11340
- ...options,
11341
- success: () => {
11342
- this.pendingNavigations.delete(rejectNavigation);
11343
- resolve();
11344
- },
11345
- fail: (error) => {
11346
- const details = error && typeof error === "object" ? error : void 0;
11347
- const reason = typeof details?.errMsg === "string" ? details.errMsg : typeof details?.message === "string" ? details.message : String(error);
11348
- const target = options.url ? ` route "${options.url}"` : "";
11349
- rejectNavigation(new Error(`Failed to ${methodName}${target} through the headless wx runtime: ${reason}`, { cause: error }));
11350
- }
11351
- });
11352
- } catch (error) {
11353
- rejectNavigation(error);
11354
- }
11355
- });
11356
- }
11357
12174
  async requireCurrentPage(methodName, route) {
11358
12175
  const page = await this.currentPage();
11359
12176
  if (!page) throw new Error(`Failed to ${methodName} route "${route}" through the headless wx runtime.`);
@@ -11372,7 +12189,10 @@ function resolveInitialRoute(session) {
11372
12189
  return session.project.routes[0]?.route ?? null;
11373
12190
  }
11374
12191
  async function launch(options) {
11375
- const session = createHeadlessSession({ projectPath: options.projectPath });
12192
+ const session = createHeadlessSession({
12193
+ compiledTemplatePaths: options.compiledTemplatePaths,
12194
+ projectPath: options.projectPath
12195
+ });
11376
12196
  const handle = new HeadlessTestingSessionHandle(session.project, session);
11377
12197
  try {
11378
12198
  await options.onSessionCreated?.(handle);
@@ -11387,4 +12207,4 @@ async function launch(options) {
11387
12207
  }
11388
12208
  }
11389
12209
  //#endregion
11390
- export { BrowserHeadlessSession, HEADLESS_PLUGIN_VIRTUAL_ROOT, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingScopeHandle, HeadlessTestingSessionHandle, RuntimeDiagnostics, RuntimeKernel, RuntimeScheduler, cloneValue, coerceComponentPropertyValue, collectMiniProgramEventBindings, createAppInstance, createArtifactProject, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createFileSystemArtifactSource, createHeadlessSession, createHeadlessUniEventBus, createHeadlessWx, createHeadlessWxState, createHostRegistries, createLogicalNode, createMemoryArtifactSource, createMiniProgramEventPayload, createMiniProgramHostConfig, createOverlayArtifactSource, createPageInstance, createPluginArtifactSource, createPluginVirtualRoot, createProjectDescriptor, executeSelectorQueryRequests, getPageInstanceId, hasBrowserVirtualFile, hasComponentPropertyValueChanged, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPageDefinition, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, readRenderedNodes, readRenderedSelectorNodes, registerAppDefinition, registerComponentDefinition, registerExportedComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, renderRuntimePageTree, resolveBrowserPageStyles, resolveMiniProgramEventBinding, resolvePluginRequest, resolveRoutesFromAppConfig, resolveSelectorQueryScopeRoot, resolveSelectorScrollTop, runComponentLifecycle, runComponentObservers, runComponentPageLifetime, waitForPageComponent, waitForPageComponents, waitForPageData, waitForPageSelector, waitForPageText, waitForPageTextGone, waitForRenderedPage, wechat };
12210
+ export { BrowserHeadlessSession, HEADLESS_PLUGIN_VIRTUAL_ROOT, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingProtocolUnsupportedError, HeadlessTestingScopeHandle, HeadlessTestingSessionHandle, RuntimeDiagnostics, RuntimeKernel, RuntimeScheduler, cloneValue, coerceComponentPropertyValue, collectMiniProgramEventBindings, createAppInstance, createArtifactProject, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createFileSystemArtifactSource, createHeadlessSession, createHeadlessUniEventBus, createHeadlessWx, createHeadlessWxState, createHostRegistries, createLogicalNode, createMemoryArtifactSource, createMiniProgramEventPayload, createMiniProgramHostConfig, createOverlayArtifactSource, createPageInstance, createPluginArtifactSource, createPluginVirtualRoot, createProjectDescriptor, executeSelectorQueryRequests, getPageInstanceId, hasBrowserVirtualFile, hasComponentPropertyValueChanged, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPageDefinition, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, readRenderedNodes, readRenderedSelectorNodes, registerAppDefinition, registerComponentDefinition, registerExportedComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, renderRuntimePageTree, resolveBrowserPageStyles, resolveMiniProgramEventBinding, resolvePluginRequest, resolveRoutesFromAppConfig, resolveSelectorQueryScopeRoot, resolveSelectorScrollTop, runComponentLifecycle, runComponentObservers, runComponentPageLifetime, waitForPageComponent, waitForPageComponents, waitForPageData, waitForPageSelector, waitForPageText, waitForPageTextGone, waitForRenderedPage, wechat };