@mpcore/simulator 0.7.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
@@ -21,6 +22,41 @@ function validateConstructedBehaviors(definition, visited = /* @__PURE__ */ new
21
22
  }
22
23
  }
23
24
  //#endregion
25
+ //#region src/host/attachmentBindingUpdates.ts
26
+ const bindingUpdates = /* @__PURE__ */ new WeakMap();
27
+ const instanceScopes = /* @__PURE__ */ new WeakMap();
28
+ /** 实例经渲染上下文归属页面,不扩展公开 renderer context 的参数契约。 */
29
+ function bindAttachmentBindingScope(instance, scope) {
30
+ instanceScopes.set(instance, instanceScopes.get(scope) ?? scope);
31
+ }
32
+ /** 仅在挂载回调内同步逻辑绑定,不接管视图提交和 setData 回调。 */
33
+ function runWithAttachmentBindingUpdates(scope, update, callback, value) {
34
+ const previous = bindingUpdates.get(scope);
35
+ const state = previous ?? {
36
+ revision: 0,
37
+ update
38
+ };
39
+ const previousUpdate = state.update;
40
+ state.update = update;
41
+ bindingUpdates.set(scope, state);
42
+ try {
43
+ return callback(value);
44
+ } finally {
45
+ if (previous) state.update = previousUpdate;
46
+ else bindingUpdates.delete(scope);
47
+ }
48
+ }
49
+ function getAttachmentBindingRevision(instance) {
50
+ return bindingUpdates.get(instanceScopes.get(instance) ?? instance);
51
+ }
52
+ function synchronizeAttachmentBindings(instance) {
53
+ const state = bindingUpdates.get(instanceScopes.get(instance) ?? instance);
54
+ if (state) {
55
+ state.revision++;
56
+ state.update();
57
+ }
58
+ }
59
+ //#endregion
24
60
  //#region src/host/componentPageAttachment.ts
25
61
  const definitionAttachments = /* @__PURE__ */ new WeakMap();
26
62
  const instanceAttachments = /* @__PURE__ */ new WeakMap();
@@ -36,8 +72,11 @@ function getComponentPageStyleIsolation(instance) {
36
72
  function isComponentPageAttaching(instance) {
37
73
  return attachingInstances.has(instance);
38
74
  }
39
- function registerComponentPageAttachment(definition, attach) {
40
- definitionAttachments.set(definition, attach);
75
+ function registerComponentPageAttachment(definition, created, attached) {
76
+ definitionAttachments.set(definition, {
77
+ created,
78
+ attached
79
+ });
41
80
  }
42
81
  function bindComponentPageAttachment(instance, definition) {
43
82
  const attach = definitionAttachments.get(definition);
@@ -48,13 +87,14 @@ function bindComponentPageAttachment(instance, definition) {
48
87
  if (typeof options?.styleIsolation === "string") instanceStyleIsolation.set(instance, options.styleIsolation);
49
88
  }
50
89
  }
51
- function attachComponentPage(instance) {
90
+ function attachComponentPage(instance, updateBindings) {
52
91
  const attach = instanceAttachments.get(instance);
53
92
  if (!attach) return false;
54
93
  instanceAttachments.delete(instance);
55
94
  attachingInstances.add(instance);
56
95
  try {
57
- attach.call(instance);
96
+ attach.created(instance);
97
+ runWithAttachmentBindingUpdates(instance, updateBindings, attach.attached, instance);
58
98
  } finally {
59
99
  attachingInstances.delete(instance);
60
100
  }
@@ -68,15 +108,23 @@ function createDuplicateRegistrationError(kind, id) {
68
108
  function callDefinitionMethod(instance, method, args) {
69
109
  if (typeof method === "function") return method.apply(instance, args);
70
110
  }
111
+ function composeDefinitionMethods(primary, secondary) {
112
+ if (typeof primary !== "function" || typeof secondary !== "function" || primary === secondary) return primary ?? secondary;
113
+ return function composedDefinitionMethod(...args) {
114
+ const result = primary.apply(this, args);
115
+ secondary.apply(this, args);
116
+ return result;
117
+ };
118
+ }
71
119
  function normalizeComponentPageDefinition(definition) {
72
120
  const { lifetimes = {}, methods = {}, pageLifetimes = {}, ...rest } = definition;
73
121
  const created = lifetimes.created ?? rest.created;
74
122
  const attached = lifetimes.attached ?? rest.attached;
75
- const ready = lifetimes.ready ?? rest.ready ?? methods.onReady ?? rest.onReady;
123
+ const ready = composeDefinitionMethods(lifetimes.ready ?? rest.ready, methods.onReady ?? rest.onReady);
76
124
  const detached = lifetimes.detached ?? rest.detached ?? methods.onUnload ?? rest.onUnload;
77
125
  const load = methods.onLoad ?? rest.onLoad;
78
- const show = pageLifetimes.show ?? methods.onShow ?? rest.onShow;
79
- const hide = pageLifetimes.hide ?? methods.onHide ?? rest.onHide;
126
+ const show = typeof pageLifetimes.show === "function" ? composeDefinitionMethods(pageLifetimes.show, methods.onShow) : methods.onShow ?? rest.onShow;
127
+ const hide = typeof pageLifetimes.hide === "function" ? composeDefinitionMethods(pageLifetimes.hide, methods.onHide) : methods.onHide ?? rest.onHide;
80
128
  const resize = pageLifetimes.resize ?? methods.onResize ?? rest.onResize;
81
129
  const routeDone = pageLifetimes.routeDone ?? methods.onRouteDone ?? rest.onRouteDone;
82
130
  const pageDefinition = {
@@ -104,10 +152,7 @@ function normalizeComponentPageDefinition(definition) {
104
152
  return callDefinitionMethod(this, routeDone, args);
105
153
  }
106
154
  };
107
- registerComponentPageAttachment(pageDefinition, function() {
108
- callDefinitionMethod(this, created, []);
109
- callDefinitionMethod(this, attached, []);
110
- });
155
+ registerComponentPageAttachment(pageDefinition, (instance) => callDefinitionMethod(instance, created, []), (instance) => callDefinitionMethod(instance, attached, []));
111
156
  return pageDefinition;
112
157
  }
113
158
  function createHostRegistries() {
@@ -298,7 +343,7 @@ function resolveCapabilityValue(source, schema) {
298
343
  }
299
344
  return current;
300
345
  }
301
- function createHeadlessWx(driver, runtimeConsole = console) {
346
+ function createHeadlessWx(driver, runtimeConsole = console, workers) {
302
347
  const eventBus = createHeadlessUniEventBus();
303
348
  const rpx2px = (value) => {
304
349
  const width = driver.getWindowInfoSync().windowWidth;
@@ -306,6 +351,10 @@ function createHeadlessWx(driver, runtimeConsole = console) {
306
351
  };
307
352
  const capabilityTree = {
308
353
  canIUse: true,
354
+ ...workers ? {
355
+ createWorker: true,
356
+ preDownloadSubpackage: true
357
+ } : {},
309
358
  canvasToTempFilePath: true,
310
359
  chooseImage: { return: {
311
360
  errMsg: true,
@@ -563,6 +612,14 @@ function createHeadlessWx(driver, runtimeConsole = console) {
563
612
  ...eventBus,
564
613
  [WEVU_ROUTE_EVENT_CONTRACT_KEY]: 1,
565
614
  [WEVU_PAGE_SCROLL_EVENT_CONTRACT_KEY]: 1,
615
+ createWorker: (script) => {
616
+ if (!workers) throw new Error("Worker host is unavailable");
617
+ return workers.createWorker(script);
618
+ },
619
+ preDownloadSubpackage: (option) => {
620
+ if (!workers) throw new Error("Worker host is unavailable");
621
+ workers.preDownloadSubpackage(option);
622
+ },
566
623
  canIUse: (schema) => typeof schema === "string" && schema.trim() !== "" && resolveCapabilityValue(capabilityTree, schema.trim()) != null,
567
624
  canvasToTempFilePath: (option) => invokeWxApi(() => driver.canvasToTempFilePath(option), option),
568
625
  chooseImage: (option) => invokeWxApi(() => driver.chooseImage(option ?? {}), option),
@@ -686,9 +743,7 @@ function createHeadlessWx(driver, runtimeConsole = console) {
686
743
  navigateBack: (option) => runNavigationApi(driver, option, (deferred) => invokeWxApi(() => {
687
744
  driver.navigateBack(deferred);
688
745
  }, deferred)),
689
- navigateTo: (option) => runNavigationApi(driver, option, (deferred) => invokeWxApi(() => {
690
- driver.navigateTo(deferred);
691
- }, deferred)),
746
+ navigateTo: (option) => runNavigationApi(driver, option, (deferred) => driver.navigateTo(deferred)),
692
747
  nextTick: (callback) => driver.nextTick(callback),
693
748
  offBeforeAppRoute: (listener) => driver.offBeforeAppRoute(listener),
694
749
  offBeforePageUnload: (listener) => driver.offBeforePageUnload(listener),
@@ -785,6 +840,360 @@ function resolveMiniProgramModule(importer, request, miniprogramRootPath, hasFil
785
840
  }
786
841
  }
787
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
788
1197
  //#region src/runtime/runtimeGlobals.ts
789
1198
  const MINI_PROGRAM_UNAVAILABLE_GLOBAL_NAMES = [
790
1199
  "window",
@@ -827,6 +1236,208 @@ function createMiniProgramRuntimeGlobals(availableGlobals, overrides) {
827
1236
  return Object.assign(globals, availableGlobals, overrides);
828
1237
  }
829
1238
  //#endregion
1239
+ //#region src/kernel/scheduler.ts
1240
+ var RuntimeScheduler = class {
1241
+ intervals = /* @__PURE__ */ new Set();
1242
+ timeouts = /* @__PURE__ */ new Set();
1243
+ closed = false;
1244
+ canceledHandle;
1245
+ onError;
1246
+ constructor(onError) {
1247
+ this.onError = onError;
1248
+ }
1249
+ clearInterval(handle) {
1250
+ this.intervals.delete(handle);
1251
+ clearInterval(handle);
1252
+ }
1253
+ clearTimeout(handle) {
1254
+ this.timeouts.delete(handle);
1255
+ clearTimeout(handle);
1256
+ }
1257
+ close() {
1258
+ if (this.closed) return;
1259
+ this.closed = true;
1260
+ for (const handle of this.intervals) clearInterval(handle);
1261
+ for (const handle of this.timeouts) clearTimeout(handle);
1262
+ this.intervals.clear();
1263
+ this.timeouts.clear();
1264
+ }
1265
+ queueMicrotask(handler) {
1266
+ if (this.closed) return;
1267
+ queueMicrotask(() => {
1268
+ if (this.closed) return;
1269
+ try {
1270
+ handler();
1271
+ } catch (error) {
1272
+ this.onError(error);
1273
+ }
1274
+ });
1275
+ }
1276
+ setInterval(handler, timeout, ...args) {
1277
+ if (this.closed) return this.getCanceledHandle();
1278
+ const handle = setInterval(() => {
1279
+ try {
1280
+ handler(...args);
1281
+ } catch (error) {
1282
+ this.onError(error);
1283
+ }
1284
+ }, timeout);
1285
+ this.intervals.add(handle);
1286
+ return handle;
1287
+ }
1288
+ setTimeout(handler, timeout, ...args) {
1289
+ if (this.closed) return this.getCanceledHandle();
1290
+ const handle = setTimeout(() => {
1291
+ this.timeouts.delete(handle);
1292
+ try {
1293
+ handler(...args);
1294
+ } catch (error) {
1295
+ this.onError(error);
1296
+ }
1297
+ }, timeout);
1298
+ this.timeouts.add(handle);
1299
+ return handle;
1300
+ }
1301
+ /** 已销毁 realm 的 Promise 回调不能复活任务,也不能向外泄漏异步拒绝。 */
1302
+ getCanceledHandle() {
1303
+ if (!this.canceledHandle) {
1304
+ this.canceledHandle = setTimeout(() => {}, 0);
1305
+ clearTimeout(this.canceledHandle);
1306
+ }
1307
+ return this.canceledHandle;
1308
+ }
1309
+ };
1310
+ //#endregion
1311
+ //#region src/runtime/workerHost.ts
1312
+ /** 两种 simulator 共用消息与生命周期;每个 worker 独立模块缓存、全局对象及计时器。 */
1313
+ function createWorkerHost(options) {
1314
+ const active = /* @__PURE__ */ new Set();
1315
+ let closed = false;
1316
+ const configuredRoot = () => {
1317
+ return JSON.parse(options.read(join(options.root, "app.json")) ?? "{}").workers;
1318
+ };
1319
+ return {
1320
+ apis: {
1321
+ preDownloadSubpackage(option) {
1322
+ const config = configuredRoot();
1323
+ if (option.packageType !== "workers" || typeof config !== "object" || !config.isSubpackage) {
1324
+ const error = /* @__PURE__ */ new Error("preDownloadSubpackage:fail workers subpackage is not configured");
1325
+ option.fail?.(error);
1326
+ option.complete?.();
1327
+ return;
1328
+ }
1329
+ const result = { errMsg: "preDownloadSubpackage:ok" };
1330
+ option.success?.(result);
1331
+ option.complete?.(result);
1332
+ },
1333
+ createWorker(scriptPath) {
1334
+ if (closed) throw new Error("createWorker:fail runtime has closed");
1335
+ const config = configuredRoot();
1336
+ const directory = typeof config === "string" ? config : config?.path;
1337
+ if (!directory || typeof scriptPath !== "string" || !scriptPath.endsWith(".js")) throw new Error("createWorker:fail invalid worker path");
1338
+ const root = normalize(join(options.root, directory));
1339
+ const entry = normalize(join(options.root, scriptPath));
1340
+ const inside = (file) => file.startsWith(`${root}/`);
1341
+ if (!inside(entry) || options.read(entry) === void 0) throw new Error("createWorker:fail worker entry is outside the configured directory or missing");
1342
+ const messages = /* @__PURE__ */ new Set();
1343
+ const incoming = /* @__PURE__ */ new Set();
1344
+ const errors = /* @__PURE__ */ new Set();
1345
+ const cache = /* @__PURE__ */ new Map();
1346
+ let terminated = false;
1347
+ const scheduler = new RuntimeScheduler((error) => {
1348
+ const value = { message: error instanceof Error ? error.message : String(error) };
1349
+ if (errors.size) for (const listener of errors) listener(value);
1350
+ else options.console.error(value.message);
1351
+ });
1352
+ const post = (listeners, message) => {
1353
+ if (terminated) return;
1354
+ const copy = structuredClone(message);
1355
+ scheduler.setTimeout(() => {
1356
+ for (const listener of [...listeners]) {
1357
+ if (terminated) break;
1358
+ listener(copy);
1359
+ }
1360
+ }, 0);
1361
+ };
1362
+ const globals = {
1363
+ wx: void 0,
1364
+ App: void 0,
1365
+ Page: void 0,
1366
+ Component: void 0,
1367
+ getApp: void 0,
1368
+ console: options.console,
1369
+ worker: {
1370
+ onMessage: (listener) => incoming.add(listener),
1371
+ postMessage: (message) => post(messages, message)
1372
+ },
1373
+ setTimeout: scheduler.setTimeout.bind(scheduler),
1374
+ clearTimeout: scheduler.clearTimeout.bind(scheduler),
1375
+ setInterval: scheduler.setInterval.bind(scheduler),
1376
+ clearInterval: scheduler.clearInterval.bind(scheduler)
1377
+ };
1378
+ globals.globalThis = globals;
1379
+ const execute = options.createExecutor(globals);
1380
+ const load = (file) => {
1381
+ if (terminated) return;
1382
+ if (!inside(file)) throw new Error("Worker require cannot leave its configured directory");
1383
+ if (cache.has(file)) return cache.get(file).exports;
1384
+ const source = options.read(file);
1385
+ if (source === void 0) throw new Error(`Missing worker module: ${file}`);
1386
+ if (file.endsWith(".json")) return JSON.parse(source);
1387
+ const module = { exports: {} };
1388
+ cache.set(file, module);
1389
+ const require = Object.assign((request) => {
1390
+ const target = resolveMiniProgramModule(file, request, root, (candidate) => options.read(candidate) !== void 0);
1391
+ if (!target) throw new Error(`Cannot resolve worker module: ${request}`);
1392
+ return load(target);
1393
+ }, { async: (request) => Promise.resolve().then(() => require(request)) });
1394
+ try {
1395
+ execute(source, file, module, require);
1396
+ } catch (error) {
1397
+ cache.delete(file);
1398
+ throw error;
1399
+ }
1400
+ return module.exports;
1401
+ };
1402
+ const worker = {
1403
+ onMessage: (listener) => {
1404
+ messages.add(listener);
1405
+ },
1406
+ offMessage: (listener) => {
1407
+ if (listener) messages.delete(listener);
1408
+ else messages.clear();
1409
+ },
1410
+ postMessage: (message) => post(incoming, message),
1411
+ onError: (listener) => {
1412
+ errors.add(listener);
1413
+ },
1414
+ offError: (listener) => {
1415
+ if (listener) errors.delete(listener);
1416
+ else errors.clear();
1417
+ },
1418
+ terminate() {
1419
+ if (terminated) return;
1420
+ terminated = true;
1421
+ scheduler.close();
1422
+ messages.clear();
1423
+ incoming.clear();
1424
+ errors.clear();
1425
+ cache.clear();
1426
+ active.delete(worker);
1427
+ }
1428
+ };
1429
+ active.add(worker);
1430
+ scheduler.setTimeout(() => load(entry), 0);
1431
+ return worker;
1432
+ }
1433
+ },
1434
+ close() {
1435
+ closed = true;
1436
+ for (const worker of active) worker.terminate();
1437
+ }
1438
+ };
1439
+ }
1440
+ //#endregion
830
1441
  //#region src/browser/virtualFiles.ts
831
1442
  function normalizeBrowserFilePath(filePath) {
832
1443
  return normalize(filePath).replace(/^\/+/, "").replace(/^\.\//, "");
@@ -932,9 +1543,9 @@ function getBrowserWxsLoader(owner, files) {
932
1543
  function createRequireNotFoundError$1(request, importer) {
933
1544
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in browser simulator runtime.`);
934
1545
  }
935
- function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, kernel, globals) {
1546
+ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, kernel, globals, workers) {
936
1547
  const runtimeConsole = kernel.diagnostics.createConsole();
937
- const wx = createHeadlessWx(wxDriver, runtimeConsole);
1548
+ const wx = createHeadlessWx(wxDriver, runtimeConsole, workers);
938
1549
  return createMiniProgramRuntimeGlobals({
939
1550
  App(definition) {
940
1551
  return registerAppDefinition(registries, definition);
@@ -964,8 +1575,18 @@ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver,
964
1575
  }, globals);
965
1576
  }
966
1577
  function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, wxDriver, options) {
1578
+ const workers = createWorkerHost({
1579
+ root: options.miniprogramRootPath,
1580
+ read: (file) => readBrowserVirtualFile(files, file),
1581
+ console: options.kernel.diagnostics.createConsole(),
1582
+ createExecutor(globals) {
1583
+ return (source, _file, module, require) => {
1584
+ new Function(`with (this) { return function(module, exports, require) {${source}\n}; }`).call(globals).call(globals, module, module.exports, require);
1585
+ };
1586
+ }
1587
+ });
967
1588
  const moduleCache = /* @__PURE__ */ new Map();
968
- const executionContext = createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {});
1589
+ const executionContext = createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {}, workers.apis);
969
1590
  executionContext.globalThis = executionContext;
970
1591
  function executeModule(filePath, loadContext) {
971
1592
  const resolvedPath = normalize(filePath);
@@ -974,6 +1595,7 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
974
1595
  const source = readBrowserVirtualFile(files, resolvedPath);
975
1596
  if (typeof source !== "string") throw new TypeError(`Missing virtual module in browser simulator runtime: ${resolvedPath}`);
976
1597
  const module = {
1598
+ source,
977
1599
  componentDefinitions: [],
978
1600
  exports: {}
979
1601
  };
@@ -999,7 +1621,7 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
999
1621
  new Function(`
1000
1622
  with (this) {
1001
1623
  return function(exports, module, require, __filename, __dirname) {
1002
- ${source}
1624
+ ${transformMiniProgramModule(source)}
1003
1625
  };
1004
1626
  }
1005
1627
  `).call(executionContext).call(executionContext, module.exports, module, localRequire, resolvedPath, dirname(resolvedPath));
@@ -1025,6 +1647,7 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
1025
1647
  };
1026
1648
  const loader = {
1027
1649
  close() {
1650
+ workers.close();
1028
1651
  moduleCache.clear();
1029
1652
  closeBrowserWxsLoader(loader);
1030
1653
  },
@@ -1043,6 +1666,17 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
1043
1666
  if (!definition) throw new Error(`Page() was not registered for route "${route}" while executing ${normalize(filePath)}.`);
1044
1667
  return definition;
1045
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
+ },
1046
1680
  executeComponentModule(filePath, id) {
1047
1681
  const loadedModule = executeModule(filePath, {
1048
1682
  kind: "component",
@@ -1063,7 +1697,13 @@ function normalizeArtifactPath(filePath) {
1063
1697
  }
1064
1698
  function createFileSystemArtifactSource() {
1065
1699
  return {
1066
- has: (filePath) => fs.existsSync(filePath),
1700
+ has(filePath) {
1701
+ try {
1702
+ return fs.statSync(filePath).isFile();
1703
+ } catch {
1704
+ return false;
1705
+ }
1706
+ },
1067
1707
  readText(filePath) {
1068
1708
  try {
1069
1709
  return fs.readFileSync(filePath, "utf8");
@@ -1137,78 +1777,6 @@ function wechat() {
1137
1777
  return { name: "wechat" };
1138
1778
  }
1139
1779
  //#endregion
1140
- //#region src/kernel/scheduler.ts
1141
- var RuntimeScheduler = class {
1142
- intervals = /* @__PURE__ */ new Set();
1143
- timeouts = /* @__PURE__ */ new Set();
1144
- closed = false;
1145
- canceledHandle;
1146
- onError;
1147
- constructor(onError) {
1148
- this.onError = onError;
1149
- }
1150
- clearInterval(handle) {
1151
- this.intervals.delete(handle);
1152
- clearInterval(handle);
1153
- }
1154
- clearTimeout(handle) {
1155
- this.timeouts.delete(handle);
1156
- clearTimeout(handle);
1157
- }
1158
- close() {
1159
- if (this.closed) return;
1160
- this.closed = true;
1161
- for (const handle of this.intervals) clearInterval(handle);
1162
- for (const handle of this.timeouts) clearTimeout(handle);
1163
- this.intervals.clear();
1164
- this.timeouts.clear();
1165
- }
1166
- queueMicrotask(handler) {
1167
- if (this.closed) return;
1168
- queueMicrotask(() => {
1169
- if (this.closed) return;
1170
- try {
1171
- handler();
1172
- } catch (error) {
1173
- this.onError(error);
1174
- }
1175
- });
1176
- }
1177
- setInterval(handler, timeout, ...args) {
1178
- if (this.closed) return this.getCanceledHandle();
1179
- const handle = setInterval(() => {
1180
- try {
1181
- handler(...args);
1182
- } catch (error) {
1183
- this.onError(error);
1184
- }
1185
- }, timeout);
1186
- this.intervals.add(handle);
1187
- return handle;
1188
- }
1189
- setTimeout(handler, timeout, ...args) {
1190
- if (this.closed) return this.getCanceledHandle();
1191
- const handle = setTimeout(() => {
1192
- this.timeouts.delete(handle);
1193
- try {
1194
- handler(...args);
1195
- } catch (error) {
1196
- this.onError(error);
1197
- }
1198
- }, timeout);
1199
- this.timeouts.add(handle);
1200
- return handle;
1201
- }
1202
- /** 已销毁 realm 的 Promise 回调不能复活任务,也不能向外泄漏异步拒绝。 */
1203
- getCanceledHandle() {
1204
- if (!this.canceledHandle) {
1205
- this.canceledHandle = setTimeout(() => {}, 0);
1206
- clearTimeout(this.canceledHandle);
1207
- }
1208
- return this.canceledHandle;
1209
- }
1210
- };
1211
- //#endregion
1212
1780
  //#region src/kernel/runtimeKernel.ts
1213
1781
  var RuntimeKernel = class {
1214
1782
  diagnostics = new RuntimeDiagnostics();
@@ -1461,11 +2029,14 @@ function runPropertyObservers(definition, instance, changedKeys, previousPropert
1461
2029
  const changedRoots = new Set(changedKeys.map((key) => parseDataPath$1(key)[0]));
1462
2030
  for (const changedKey of Object.keys(propOptions)) {
1463
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;
1464
2034
  const option = propOptions[changedKey];
1465
2035
  if (!option || typeof option !== "object" || Array.isArray(option)) continue;
1466
2036
  const observer = typeof option.observer === "string" ? instance[option.observer] : option.observer;
1467
2037
  if (typeof observer !== "function") continue;
1468
- 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);
1469
2040
  }
1470
2041
  }
1471
2042
  function normalizeObserverPattern(pattern) {
@@ -1676,7 +2247,6 @@ function resolveInitialProperties(definition, properties) {
1676
2247
  if (option && typeof option === "object" && !Array.isArray(option) && "value" in option) resolved[key] = resolvePropertyDefaultValue(option, definition);
1677
2248
  else resolved[key] = cloneValue(resolveDefaultValueByType(normalizePropertyType(option)));
1678
2249
  }
1679
- for (const [key, value] of Object.entries(properties)) if (!(key in resolved)) resolved[key] = value;
1680
2250
  return resolved;
1681
2251
  }
1682
2252
  //#endregion
@@ -1691,11 +2261,11 @@ const opposite = {
1691
2261
  function definitions(instance) {
1692
2262
  return Object.entries(instance.__definition__?.relations ?? {});
1693
2263
  }
1694
- function includesBehavior(behaviors, target) {
1695
- 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));
1696
2266
  }
1697
2267
  function matches(source, key, relation, target) {
1698
- if (relation.target) return includesBehavior(target.__definition__?.behaviors, relation.target);
2268
+ if (relation.target) return includesBehavior$1(target.__definition__?.behaviors, relation.target);
1699
2269
  const targetPath = key.startsWith("/") ? key.slice(1) : posix.join(posix.dirname(String(source.is)), key);
1700
2270
  return posix.normalize(targetPath) === target.is;
1701
2271
  }
@@ -1769,29 +2339,24 @@ function detachComponentRelations(instances) {
1769
2339
  //#region src/runtime/componentInstance/index.ts
1770
2340
  function createComponentInstance(options) {
1771
2341
  const definition = normalizeComponentDefinition(options.definition);
1772
- const inputProperties = resolveInitialProperties(definition, options.properties ?? {});
1773
2342
  const data = {
1774
2343
  ...resolveInitialData$2(definition),
1775
- ...Object.fromEntries(Object.keys(definition.properties ?? {}).map((key) => [key, inputProperties[key]]))
2344
+ ...resolveInitialProperties(definition, options.properties ?? {})
1776
2345
  };
1777
2346
  const instance = {
1778
2347
  __definition__: definition,
1779
2348
  data,
1780
2349
  __propertySnapshots__: {},
1781
- properties: {
1782
- ...data,
1783
- ...inputProperties
1784
- },
2350
+ properties: data,
1785
2351
  getRelationNodes(key) {
1786
2352
  return getComponentRelationNodes(instance, key);
1787
2353
  },
1788
2354
  setData(patch, callback) {
1789
2355
  const changedKeys = Object.keys(patch);
1790
- const dataKeys = [...new Set(changedKeys.map((key) => parseDataPath$1(key)[0]))];
1791
- 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));
1792
2357
  const previousProperties = Object.fromEntries(propertyKeys.map((key) => [key, cloneValue(instance.properties[key])]));
1793
2358
  for (const [key, value] of Object.entries(patch)) assignByPath$1(instance.data, key, value);
1794
- for (const key of dataKeys) instance.properties[key] = instance.data[key];
2359
+ synchronizeAttachmentBindings(instance);
1795
2360
  runComponentObservers(definition, instance, changedKeys, previousProperties);
1796
2361
  if (options.requestRender) options.requestRender(callback);
1797
2362
  else callback?.();
@@ -1835,7 +2400,8 @@ function isComponentAttached(instance) {
1835
2400
  return attachmentStates.get(instance) === "attached";
1836
2401
  }
1837
2402
  function hasPendingComponentAttachments(instances) {
1838
- return [...instances].some((instance) => attachmentStates.get(instance) === "attaching");
2403
+ for (const instance of instances) if (attachmentStates.get(instance) === "attaching") return true;
2404
+ return false;
1839
2405
  }
1840
2406
  function flushComponentReady(instances, ready) {
1841
2407
  const all = [...instances];
@@ -1845,19 +2411,71 @@ function flushComponentReady(instances, ready) {
1845
2411
  for (const instance of pending) ready(instance);
1846
2412
  return pending.length > 0;
1847
2413
  }
1848
- function flushComponentAttachments(instances, attach) {
1849
- const pending = [...instances].filter((instance) => !attachmentStates.has(instance));
1850
- for (const instance of pending) attachmentStates.set(instance, "attaching");
2414
+ function flushComponentAttachments(componentCache, scopeIds, attach) {
2415
+ const pending = /* @__PURE__ */ new Map();
2416
+ for (const scopeId of scopeIds) {
2417
+ const instance = componentCache.get(scopeId);
2418
+ if (!instance) continue;
2419
+ const state = attachmentStates.get(instance);
2420
+ if (state === "attaching") return false;
2421
+ if (!state) pending.set(scopeId, instance);
2422
+ }
2423
+ for (const instance of pending.values()) attachmentStates.set(instance, "attaching");
1851
2424
  try {
1852
- for (const instance of pending) try {
1853
- attach(instance);
1854
- } finally {
1855
- attachmentStates.set(instance, "attached");
2425
+ for (const [scopeId, instance] of pending) {
2426
+ if (componentCache.get(scopeId) !== instance) return "restart";
2427
+ let restart;
2428
+ try {
2429
+ restart = attach(instance);
2430
+ } finally {
2431
+ attachmentStates.set(instance, "attached");
2432
+ }
2433
+ if (restart) return "restart";
1856
2434
  }
1857
2435
  } finally {
1858
- for (const instance of pending) if (attachmentStates.get(instance) === "attaching") attachmentStates.delete(instance);
2436
+ for (const instance of pending.values()) if (attachmentStates.get(instance) === "attaching") attachmentStates.delete(instance);
1859
2437
  }
1860
- return pending.length > 0;
2438
+ return pending.size > 0 ? "attached" : false;
2439
+ }
2440
+ //#endregion
2441
+ //#region src/runtime/componentInstance/construction.ts
2442
+ const constructionStates = /* @__PURE__ */ new WeakMap();
2443
+ const constructingInstances = /* @__PURE__ */ new WeakSet();
2444
+ function isComponentConstructing(instance) {
2445
+ return instance !== void 0 && constructingInstances.has(instance);
2446
+ }
2447
+ function hasPendingComponentConstruction(componentCache) {
2448
+ return constructionStates.has(componentCache);
2449
+ }
2450
+ function beginComponentConstruction(componentCache, scopeId, instance) {
2451
+ let state = constructionStates.get(componentCache);
2452
+ if (!state) {
2453
+ state = {
2454
+ depth: 0,
2455
+ created: /* @__PURE__ */ new Map()
2456
+ };
2457
+ constructionStates.set(componentCache, state);
2458
+ }
2459
+ state.depth++;
2460
+ state.created.set(scopeId, instance);
2461
+ constructingInstances.add(instance);
2462
+ }
2463
+ function discardComponentConstruction(componentCache, componentScopes, scopeId) {
2464
+ const state = constructionStates.get(componentCache);
2465
+ const prefix = `${scopeId}/`;
2466
+ for (const [createdScopeId, instance] of state.created) {
2467
+ if (createdScopeId !== scopeId && !createdScopeId.startsWith(prefix)) continue;
2468
+ if (componentCache.get(createdScopeId) === instance) {
2469
+ componentCache.delete(createdScopeId);
2470
+ componentScopes.delete(createdScopeId);
2471
+ }
2472
+ state.created.delete(createdScopeId);
2473
+ }
2474
+ }
2475
+ function finishComponentConstruction(componentCache, instance) {
2476
+ constructingInstances.delete(instance);
2477
+ const state = constructionStates.get(componentCache);
2478
+ if (--state.depth === 0) constructionStates.delete(componentCache);
1861
2479
  }
1862
2480
  //#endregion
1863
2481
  //#region src/runtime/componentInstance/discardedReady.ts
@@ -1880,6 +2498,61 @@ function flushDiscardedComponentReady(cache, pageScopeId, ready) {
1880
2498
  if (!pending.size) discardedReady.delete(cache);
1881
2499
  }
1882
2500
  //#endregion
2501
+ //#region src/runtime/componentInstance/propertyBindings.ts
2502
+ const consumedPageChanges = /* @__PURE__ */ new WeakMap();
2503
+ function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys, beforeObservers) {
2504
+ const freshPageChanges = changedPageKeys.length > 0 && consumedPageChanges.get(instance) !== changedPageKeys;
2505
+ if (freshPageChanges) consumedPageChanges.set(instance, changedPageKeys);
2506
+ const changedRootKeys = [];
2507
+ const previousProperties = {};
2508
+ for (const [key, value] of Object.entries(nextProperties)) {
2509
+ if (!Object.hasOwn(definition.properties ?? {}, key)) continue;
2510
+ const nextValue = normalizeComponentPropertyValue(definition, key, value);
2511
+ const bindingExpression = bindingExpressions[key];
2512
+ const bindingAffected = freshPageChanges && !!bindingExpression && changedPageKeys.some((changedKey) => {
2513
+ return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
2514
+ });
2515
+ const previousSnapshot = instance.__propertySnapshots?.[key];
2516
+ if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
2517
+ previousProperties[key] = instance.properties[key];
2518
+ const deliveredValue = cloneValue(nextValue);
2519
+ instance.properties[key] = deliveredValue;
2520
+ changedRootKeys.push(key);
2521
+ }
2522
+ instance.__propertySnapshots ??= {};
2523
+ instance.__propertySnapshots[key] = cloneValue(nextValue);
2524
+ }
2525
+ if (changedRootKeys.length === 0) return;
2526
+ beforeObservers?.(instance, "properties");
2527
+ runComponentObservers(definition, instance, changedRootKeys, previousProperties);
2528
+ }
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
1883
2556
  //#region src/runtime/pageLifecycle.ts
1884
2557
  const loadingPages = /* @__PURE__ */ new WeakSet();
1885
2558
  function isPageBeforeReady(page) {
@@ -1907,6 +2580,287 @@ function runInitialPageLifecycles(page, query, scheduler, isAlive, renderCompone
1907
2580
  }, 0);
1908
2581
  }
1909
2582
  //#endregion
2583
+ //#region src/view/eventBindingParser.ts
2584
+ const LEGACY_EVENT_NAME_RE = /^\w+$/;
2585
+ const EVENT_BINDING_PREFIXES = [
2586
+ {
2587
+ prefix: "capture-bind:",
2588
+ priority: 0,
2589
+ stopAfter: false,
2590
+ phase: "capture"
2591
+ },
2592
+ {
2593
+ prefix: "capture-catch:",
2594
+ priority: 0,
2595
+ stopAfter: true,
2596
+ phase: "capture"
2597
+ },
2598
+ {
2599
+ prefix: "capture-bind",
2600
+ priority: 1,
2601
+ stopAfter: false,
2602
+ phase: "capture"
2603
+ },
2604
+ {
2605
+ prefix: "capture-catch",
2606
+ priority: 1,
2607
+ stopAfter: true,
2608
+ phase: "capture"
2609
+ },
2610
+ {
2611
+ prefix: "bind:",
2612
+ priority: 0,
2613
+ stopAfter: false,
2614
+ phase: "bubble"
2615
+ },
2616
+ {
2617
+ prefix: "catch:",
2618
+ priority: 0,
2619
+ stopAfter: true,
2620
+ phase: "bubble"
2621
+ },
2622
+ {
2623
+ prefix: "bind",
2624
+ priority: 1,
2625
+ stopAfter: false,
2626
+ phase: "bubble"
2627
+ },
2628
+ {
2629
+ prefix: "catch",
2630
+ priority: 1,
2631
+ stopAfter: true,
2632
+ phase: "bubble"
2633
+ }
2634
+ ];
2635
+ function parseEventBinding(attributeName, method) {
2636
+ const definition = EVENT_BINDING_PREFIXES.find((item) => attributeName.startsWith(item.prefix));
2637
+ if (!definition) return null;
2638
+ const eventName = attributeName.slice(definition.prefix.length);
2639
+ if (!eventName || !definition.prefix.endsWith(":") && !LEGACY_EVENT_NAME_RE.test(eventName)) return null;
2640
+ return {
2641
+ eventName,
2642
+ method,
2643
+ phase: definition.phase,
2644
+ priority: definition.priority,
2645
+ stopAfter: definition.stopAfter
2646
+ };
2647
+ }
2648
+ function collectEventBindings(attributes = {}, includeCapture = true) {
2649
+ const eventBindings = /* @__PURE__ */ new Map();
2650
+ let captureEventBindings;
2651
+ const priorities = /* @__PURE__ */ new Map();
2652
+ for (const [attributeName, method] of Object.entries(attributes)) {
2653
+ const candidate = parseEventBinding(attributeName, method);
2654
+ if (!candidate || !includeCapture && candidate.phase === "capture") continue;
2655
+ const eventPriorities = priorities.get(candidate.eventName) ?? {};
2656
+ if (candidate.priority < (eventPriorities[candidate.phase] ?? -1)) continue;
2657
+ (candidate.phase === "bubble" ? eventBindings : captureEventBindings ??= /* @__PURE__ */ new Map()).set(candidate.eventName, {
2658
+ method: candidate.method,
2659
+ stopAfter: candidate.stopAfter
2660
+ });
2661
+ eventPriorities[candidate.phase] = candidate.priority;
2662
+ priorities.set(candidate.eventName, eventPriorities);
2663
+ }
2664
+ return {
2665
+ eventBindings,
2666
+ captureEventBindings
2667
+ };
2668
+ }
2669
+ /** 单事件查询只保留命中的绑定,原生交互不构造整张事件表。 */
2670
+ function resolveEventBindingPhases(attributes, eventName, includeCapture = true) {
2671
+ if (!attributes) return null;
2672
+ let bindings = null;
2673
+ let bubblePriority = -1;
2674
+ let capturePriority = -1;
2675
+ for (const [attributeName, method] of Object.entries(attributes)) {
2676
+ const candidate = parseEventBinding(attributeName, method);
2677
+ if (!candidate || candidate.eventName !== eventName || !includeCapture && candidate.phase === "capture") continue;
2678
+ const priority = candidate.phase === "bubble" ? bubblePriority : capturePriority;
2679
+ if (candidate.priority < priority) continue;
2680
+ bindings ??= {};
2681
+ bindings[candidate.phase] = {
2682
+ method: candidate.method,
2683
+ stopAfter: candidate.stopAfter
2684
+ };
2685
+ if (candidate.phase === "bubble") bubblePriority = candidate.priority;
2686
+ else capturePriority = candidate.priority;
2687
+ }
2688
+ return bindings;
2689
+ }
2690
+ //#endregion
2691
+ //#region src/view/nodeDataset.ts
2692
+ const DATASET_NAME_RE = /-([a-z])/g;
2693
+ function isDatasetAttribute(attributeName) {
2694
+ return attributeName.startsWith("data-") && !attributeName.startsWith("data-sim-");
2695
+ }
2696
+ function toDatasetKey(attributeName) {
2697
+ return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
2698
+ }
2699
+ function collectNodeDataset(node) {
2700
+ if (node.dataset) return { ...node.dataset };
2701
+ const dataset = {};
2702
+ for (const [key, value] of Object.entries(node.attribs ?? {})) if (isDatasetAttribute(key)) dataset[toDatasetKey(key)] = value;
2703
+ return dataset;
2704
+ }
2705
+ //#endregion
2706
+ //#region src/view/componentEvent.ts
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
+ }
2733
+ /** 在构造子树之前建立父链,created/observer 中的事件也能访问声明树。 */
2734
+ function registerComponentEventNode(node, scope, parent) {
2735
+ node.parent = parent ?? null;
2736
+ eventNodes.set(node, {
2737
+ scope,
2738
+ target: node
2739
+ });
2740
+ }
2741
+ /** 宿主与作用域共享同一份分阶段绑定,eventBindings 仍是原有的冒泡存储。 */
2742
+ function bindComponentEventHost(node) {
2743
+ const bindings = collectEventBindings(node.attribs);
2744
+ eventNodes.get(node).bindings = bindings;
2745
+ return bindings;
2746
+ }
2747
+ /** 渲染会把宿主折叠进模板根;事件仍保留两层独立的绑定和声明所有者。 */
2748
+ function mergeComponentEventRoot(root, host) {
2749
+ const entry = eventNodes.get(root);
2750
+ if (entry.target === root) entry.target = {
2751
+ attribs: root.attribs,
2752
+ dataset: root.dataset
2753
+ };
2754
+ entry.hosts ??= [];
2755
+ entry.hosts.push(host);
2756
+ root.parent = host.parent;
2757
+ }
2758
+ /** 按渲染完成后的实际宿主父链排序;输入只包含本轮存活的组件作用域。 */
2759
+ function orderComponentAttachmentScopes(scopeIds, componentScopes) {
2760
+ const hostScopes = /* @__PURE__ */ new Map();
2761
+ for (const scopeId of scopeIds) hostScopes.set(componentScopes.get(scopeId).hostNode, scopeId);
2762
+ const ordered = [];
2763
+ const visited = /* @__PURE__ */ new Set();
2764
+ const visit = (node) => {
2765
+ if (!node || visited.has(node)) return;
2766
+ visited.add(node);
2767
+ visit(node.parent);
2768
+ const hosts = eventNodes.get(node)?.hosts;
2769
+ if (hosts) for (let index = hosts.length - 1; index >= 0; index--) visit(hosts[index]);
2770
+ const scopeId = hostScopes.get(node);
2771
+ if (scopeId !== void 0) ordered.push(scopeId);
2772
+ };
2773
+ for (const host of hostScopes.keys()) visit(host);
2774
+ return ordered;
2775
+ }
2776
+ function buildComponentTrigger(componentScopeId, context) {
2777
+ return (instance, eventName, detail, triggerOptions) => {
2778
+ const originScope = context.componentScopes.get(componentScopeId);
2779
+ const origin = originScope?.hostNode;
2780
+ if (!originScope || !origin) return;
2781
+ const bubbles = triggerOptions?.bubbles ?? false;
2782
+ const capturePhase = triggerOptions?.capturePhase ?? false;
2783
+ const composed = triggerOptions?.composed ?? false;
2784
+ const target = {
2785
+ dataset: originScope.dataset ?? collectNodeDataset(origin),
2786
+ id: originScope.hostId ?? ""
2787
+ };
2788
+ const mark = instance.__lastInteractionEvent__?.mark;
2789
+ const listeners = [];
2790
+ const collect = (entry, isOrigin) => {
2791
+ if (!composed && entry.scope.getScopeId() !== originScope.listenerScopeId) return false;
2792
+ const bindings = entry.bindings ? {
2793
+ bubble: entry.bindings.eventBindings?.get(eventName),
2794
+ capture: entry.bindings.captureEventBindings?.get(eventName)
2795
+ } : resolveEventBindingPhases(entry.target.attribs, eventName);
2796
+ if (bindings?.bubble || bindings?.capture) listeners.push({
2797
+ scope: entry.scope,
2798
+ bindings,
2799
+ currentTarget: isOrigin ? target : {
2800
+ dataset: collectNodeDataset(entry.target),
2801
+ id: entry.target.attribs?.id ?? ""
2802
+ },
2803
+ origin: isOrigin
2804
+ });
2805
+ return true;
2806
+ };
2807
+ let current = origin;
2808
+ while (current) {
2809
+ const entry = eventNodes.get(current);
2810
+ if (entry) {
2811
+ if (!collect(entry, current === origin)) break;
2812
+ let crossedBoundary = false;
2813
+ for (const host of entry.hosts ?? []) if (!collect(eventNodes.get(host), false)) {
2814
+ crossedBoundary = true;
2815
+ break;
2816
+ }
2817
+ if (crossedBoundary) break;
2818
+ }
2819
+ if (!bubbles && !capturePhase) break;
2820
+ current = current.parent;
2821
+ }
2822
+ const handlers = [];
2823
+ let stopped = false;
2824
+ if (capturePhase) for (let index = listeners.length - 1; index >= 0; index--) {
2825
+ const listener = listeners[index];
2826
+ const binding = listener.bindings.capture;
2827
+ if (binding) {
2828
+ handlers.push({
2829
+ scope: listener.scope,
2830
+ binding,
2831
+ currentTarget: listener.currentTarget
2832
+ });
2833
+ if (binding.stopAfter) {
2834
+ stopped = true;
2835
+ break;
2836
+ }
2837
+ }
2838
+ }
2839
+ if (!stopped) for (const listener of listeners) {
2840
+ if (!bubbles && !listener.origin) continue;
2841
+ const binding = listener.bindings.bubble;
2842
+ if (binding) {
2843
+ handlers.push({
2844
+ scope: listener.scope,
2845
+ binding,
2846
+ currentTarget: listener.currentTarget
2847
+ });
2848
+ if (binding.stopAfter) break;
2849
+ }
2850
+ }
2851
+ for (const { scope, binding, currentTarget } of handlers) scope.getMethod(binding.method)?.({
2852
+ bubbles,
2853
+ capturePhase,
2854
+ composed,
2855
+ currentTarget,
2856
+ detail,
2857
+ mark,
2858
+ target,
2859
+ type: eventName
2860
+ });
2861
+ };
2862
+ }
2863
+ //#endregion
1910
2864
  //#region src/view/conditionalChildren.ts
1911
2865
  function selectConditionalChildren(children, evaluate) {
1912
2866
  const selected = [];
@@ -1962,11 +2916,77 @@ function customTabBarHostScope() {
1962
2916
  };
1963
2917
  }
1964
2918
  //#endregion
2919
+ //#region src/view/inspectionTree.ts
2920
+ const inspectionChildren = /* @__PURE__ */ new WeakMap();
2921
+ const inspectionParents = /* @__PURE__ */ new WeakMap();
2922
+ const emptyChildren = [];
2923
+ function getInspectionChildren(node) {
2924
+ return inspectionChildren.get(node) ?? node.children ?? emptyChildren;
2925
+ }
2926
+ function getInspectionParent(node) {
2927
+ return inspectionParents.get(node) ?? node.parent ?? null;
2928
+ }
2929
+ function collectRenderedNodes(node, nodes) {
2930
+ if (nodes.has(node)) return;
2931
+ nodes.add(node);
2932
+ for (const child of node.children ?? emptyChildren) collectRenderedNodes(child, nodes);
2933
+ }
2934
+ /** 原生检查器保留未投影声明;可见 DOM、WXML 和事件父链不因此增加节点。 */
2935
+ function registerInspectionTrees(root, pass, scopes) {
2936
+ if (!pass.hasUnprojectedSlots) return;
2937
+ const rendered = /* @__PURE__ */ new Set();
2938
+ collectRenderedNodes(root, rendered);
2939
+ const candidates = /* @__PURE__ */ new Map();
2940
+ for (const [entries, group] of pass.slotDeclarations) {
2941
+ if (scopes.get(group.scopeId)?.hostNode !== group.parent) continue;
2942
+ const host = pass.componentRoots.get(group.scopeId);
2943
+ if (!host) continue;
2944
+ for (const entry of entries) for (const node of pass.renderedSlots.get(entry) ?? emptyChildren) candidates.set(node, host);
2945
+ }
2946
+ const nested = /* @__PURE__ */ new Set();
2947
+ const visited = /* @__PURE__ */ new Set();
2948
+ const indexChildren = (node) => {
2949
+ if (visited.has(node)) return;
2950
+ visited.add(node);
2951
+ for (const child of node.children ?? emptyChildren) {
2952
+ nested.add(child);
2953
+ if (!rendered.has(child)) inspectionParents.set(child, node);
2954
+ indexChildren(child);
2955
+ }
2956
+ };
2957
+ for (const node of candidates.keys()) indexChildren(node);
2958
+ for (const [node, host] of candidates) {
2959
+ if (rendered.has(node) || nested.has(node) || node === host) continue;
2960
+ let children = inspectionChildren.get(host);
2961
+ if (!children) {
2962
+ children = [...host.children ?? emptyChildren];
2963
+ inspectionChildren.set(host, children);
2964
+ }
2965
+ children.push(node);
2966
+ inspectionParents.set(node, host);
2967
+ }
2968
+ }
2969
+ //#endregion
1965
2970
  //#region src/view/loopEntries.ts
2971
+ const LOOP_SCOPE_ESCAPE_RE = /[^\w-]/g;
2972
+ function escapeScopeCodeUnit(character) {
2973
+ return `~${character.charCodeAt(0).toString(16).padStart(4, "0")}`;
2974
+ }
2975
+ function encodeLoopCoordinate(value) {
2976
+ return value.replace(LOOP_SCOPE_ESCAPE_RE, escapeScopeCodeUnit);
2977
+ }
1966
2978
  function resolveLoopEntries(value) {
1967
2979
  if (Array.isArray(value)) return value.map((item, index) => [index, item]);
1968
2980
  return value !== null && typeof value === "object" ? Object.entries(value) : [];
1969
2981
  }
2982
+ function resolveLoopInstanceSuffix(item, index, key, occurrences) {
2983
+ if (!key || !occurrences) return `:for-${encodeLoopCoordinate(String(index))}`;
2984
+ const value = key === "*this" ? item : item?.[key];
2985
+ const normalized = encodeLoopCoordinate(String(value ?? ""));
2986
+ const occurrence = occurrences.get(normalized) ?? 0;
2987
+ occurrences.set(normalized, occurrence + 1);
2988
+ return `:key-${normalized}${occurrence ? `:duplicate-${occurrence}` : ""}`;
2989
+ }
1970
2990
  //#endregion
1971
2991
  //#region src/view/renderedTree.ts
1972
2992
  /** 在循环展开和组件替换完成后,让父节点关系指向本次渲染树。 */
@@ -1975,6 +2995,44 @@ function linkRenderedParents(root, parent = null) {
1975
2995
  for (const child of root.children ?? []) linkRenderedParents(child, root);
1976
2996
  }
1977
2997
  //#endregion
2998
+ //#region src/view/renderPass.ts
2999
+ const initializedPages = /* @__PURE__ */ new WeakMap();
3000
+ function createRenderPass(propertyUpdate = false, parent) {
3001
+ return {
3002
+ seenComponentScopes: /* @__PURE__ */ new Set(),
3003
+ componentRoots: /* @__PURE__ */ new Map(),
3004
+ slotDeclarations: /* @__PURE__ */ new Map(),
3005
+ renderedSlots: /* @__PURE__ */ new Map(),
3006
+ hasUnprojectedSlots: false,
3007
+ propertyUpdate,
3008
+ bindingUpdate: parent?.bindingUpdate,
3009
+ bindingRevision: parent?.bindingUpdate?.revision ?? 0
3010
+ };
3011
+ }
3012
+ function createPageRenderPass(page, cache) {
3013
+ const pass = createRenderPass(initializedPages.get(cache)?.has(page) ?? false);
3014
+ pass.bindingUpdate = getAttachmentBindingRevision(page);
3015
+ pass.bindingRevision = pass.bindingUpdate?.revision ?? 0;
3016
+ return pass;
3017
+ }
3018
+ function isRenderPassStale(pass) {
3019
+ return pass.bindingUpdate !== void 0 && pass.bindingUpdate.revision !== pass.bindingRevision;
3020
+ }
3021
+ function markPageTreeConstructed(page, cache) {
3022
+ let pages = initializedPages.get(cache);
3023
+ if (!pages) {
3024
+ pages = /* @__PURE__ */ new WeakSet();
3025
+ initializedPages.set(cache, pages);
3026
+ }
3027
+ pages.add(page);
3028
+ }
3029
+ function registerSlotDeclarations(pass, slots, parent, scopeId) {
3030
+ for (const entries of slots.values()) if (!pass.slotDeclarations.has(entries)) pass.slotDeclarations.set(entries, {
3031
+ parent,
3032
+ scopeId
3033
+ });
3034
+ }
3035
+ //#endregion
1978
3036
  //#region src/view/templateInterpolation.ts
1979
3037
  /** 按表达式词法寻找插值边界,字符串和对象内部的大括号不结束绑定。 */
1980
3038
  function templateInterpolations(source) {
@@ -2267,124 +3325,32 @@ function resolveBrowserComponentPageStyleIsolation(files, page, route, miniprogr
2267
3325
  config = JSON.parse(source);
2268
3326
  } catch {
2269
3327
  throw new Error(`Invalid browser Component page JSON: ${filename}`);
2270
- }
2271
- if (!config || typeof config !== "object" || Array.isArray(config)) throw new Error(`Invalid browser Component page JSON: ${filename}`);
2272
- const isolation = "styleIsolation" in config ? config.styleIsolation : void 0;
2273
- return isolation === void 0 ? definitionIsolation : typeof isolation === "string" ? isolation : void 0;
2274
- }
2275
- //#endregion
2276
- //#region src/runtime/componentInstance/selection.ts
2277
- function hasExportBehavior(definition, visited = /* @__PURE__ */ new Set()) {
2278
- if (visited.has(definition)) return false;
2279
- visited.add(definition);
2280
- return (Array.isArray(definition.behaviors) ? definition.behaviors : []).some((behavior) => behavior === "wx://component-export" || behavior !== null && typeof behavior === "object" && hasExportBehavior(behavior, visited));
2281
- }
2282
- /** 原生选择器尊重组件导出行为;测试桥接继续保留完整组件实例。 */
2283
- function resolveNativeComponentSelection(instance) {
2284
- if (!instance) return null;
2285
- const definition = instance.__definition__;
2286
- if (!definition || !hasExportBehavior(definition) || typeof instance.export !== "function") return instance;
2287
- return instance.export();
2288
- }
2289
- //#endregion
2290
- //#region src/runtime/componentResolution.ts
2291
- function resolveMiniProgramComponent(ownerFilePath, request, miniprogramRootPath, hasFile) {
2292
- const localPath = request.startsWith("/") ? request.replace(/^\/+/, "") : join(dirname(ownerFilePath), request);
2293
- if (request.startsWith("/") || request.startsWith(".") || hasFile(join(miniprogramRootPath, `${localPath}.js`))) return localPath;
2294
- const npmPath = resolveMiniProgramModule(join(miniprogramRootPath, ownerFilePath), request, miniprogramRootPath, (candidate) => candidate.endsWith(".js") && hasFile(candidate));
2295
- return npmPath ? relative(miniprogramRootPath, npmPath).slice(0, -3) : localPath;
2296
- }
2297
- //#endregion
2298
- //#region src/view/nodeDataset.ts
2299
- const DATASET_NAME_RE = /-([a-z])/g;
2300
- function isDatasetAttribute(attributeName) {
2301
- return attributeName.startsWith("data-") && !attributeName.startsWith("data-sim-");
2302
- }
2303
- function toDatasetKey(attributeName) {
2304
- return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
2305
- }
2306
- function collectNodeDataset(node) {
2307
- if (node.dataset) return { ...node.dataset };
2308
- const dataset = {};
2309
- for (const [key, value] of Object.entries(node.attribs ?? {})) if (isDatasetAttribute(key)) dataset[toDatasetKey(key)] = value;
2310
- return dataset;
2311
- }
2312
- //#endregion
2313
- //#region src/view/eventBinding.ts
2314
- const LEGACY_EVENT_NAME_RE = /^\w+$/;
2315
- const EVENT_BINDING_PREFIXES = [
2316
- {
2317
- prefix: "bind:",
2318
- priority: 0,
2319
- stopAfter: false
2320
- },
2321
- {
2322
- prefix: "catch:",
2323
- priority: 0,
2324
- stopAfter: true
2325
- },
2326
- {
2327
- prefix: "bind",
2328
- priority: 1,
2329
- stopAfter: false
2330
- },
2331
- {
2332
- prefix: "catch",
2333
- priority: 1,
2334
- stopAfter: true
2335
- }
2336
- ];
2337
- function parseEventBinding(attributeName, method) {
2338
- const definition = EVENT_BINDING_PREFIXES.find((item) => attributeName.startsWith(item.prefix));
2339
- if (!definition) return null;
2340
- const eventName = attributeName.slice(definition.prefix.length);
2341
- if (!eventName || !definition.prefix.endsWith(":") && !LEGACY_EVENT_NAME_RE.test(eventName)) return null;
2342
- return {
2343
- eventName,
2344
- method,
2345
- priority: definition.priority,
2346
- stopAfter: definition.stopAfter
2347
- };
2348
- }
2349
- function collectMiniProgramEventBindings(attributes = {}) {
2350
- const bindings = /* @__PURE__ */ new Map();
2351
- const priorities = /* @__PURE__ */ new Map();
2352
- for (const [attributeName, method] of Object.entries(attributes)) {
2353
- const candidate = parseEventBinding(attributeName, method);
2354
- if (!candidate || candidate.priority < (priorities.get(candidate.eventName) ?? -1)) continue;
2355
- bindings.set(candidate.eventName, {
2356
- method: candidate.method,
2357
- stopAfter: candidate.stopAfter
2358
- });
2359
- priorities.set(candidate.eventName, candidate.priority);
2360
- }
2361
- return bindings;
2362
- }
2363
- function resolveMiniProgramEventBinding(attributes, eventName) {
2364
- return collectMiniProgramEventBindings(attributes).get(eventName) ?? null;
2365
- }
2366
- /** 冒泡时保留原始 target,currentTarget 则属于当前执行绑定的节点。 */
2367
- function createMiniProgramEventPayload(node, eventName, event, origin = node) {
2368
- const dataset = collectNodeDataset(node);
2369
- const nodeId = node.attribs?.id ?? "";
2370
- const isOrigin = node === origin;
2371
- return {
2372
- bubbles: false,
2373
- capturePhase: false,
2374
- composed: false,
2375
- currentTarget: {
2376
- dataset: isOrigin ? event.currentTarget?.dataset ?? event.dataset ?? dataset : dataset,
2377
- id: isOrigin ? event.currentTarget?.id ?? event.id ?? nodeId : nodeId
2378
- },
2379
- detail: event.detail,
2380
- mark: event.mark,
2381
- target: {
2382
- dataset: event.target?.dataset ?? event.dataset ?? (isOrigin ? dataset : collectNodeDataset(origin)),
2383
- id: event.target?.id ?? event.id ?? origin.attribs?.id ?? ""
2384
- },
2385
- timeStamp: Date.now(),
2386
- type: eventName
2387
- };
3328
+ }
3329
+ if (!config || typeof config !== "object" || Array.isArray(config)) throw new Error(`Invalid browser Component page JSON: ${filename}`);
3330
+ const isolation = "styleIsolation" in config ? config.styleIsolation : void 0;
3331
+ return isolation === void 0 ? definitionIsolation : typeof isolation === "string" ? isolation : void 0;
3332
+ }
3333
+ //#endregion
3334
+ //#region src/runtime/componentInstance/selection.ts
3335
+ function hasExportBehavior(definition, visited = /* @__PURE__ */ new Set()) {
3336
+ if (visited.has(definition)) return false;
3337
+ visited.add(definition);
3338
+ return (Array.isArray(definition.behaviors) ? definition.behaviors : []).some((behavior) => behavior === "wx://component-export" || behavior !== null && typeof behavior === "object" && hasExportBehavior(behavior, visited));
3339
+ }
3340
+ /** 原生选择器尊重组件导出行为;测试桥接继续保留完整组件实例。 */
3341
+ function resolveNativeComponentSelection(instance) {
3342
+ if (!instance) return null;
3343
+ const definition = instance.__definition__;
3344
+ if (!definition || !hasExportBehavior(definition) || typeof instance.export !== "function") return instance;
3345
+ return instance.export();
3346
+ }
3347
+ //#endregion
3348
+ //#region src/runtime/componentResolution.ts
3349
+ function resolveMiniProgramComponent(ownerFilePath, request, miniprogramRootPath, hasFile) {
3350
+ const localPath = request.startsWith("/") ? request.replace(/^\/+/, "") : join(dirname(ownerFilePath), request);
3351
+ if (request.startsWith("/") || request.startsWith(".") || hasFile(join(miniprogramRootPath, `${localPath}.js`))) return localPath;
3352
+ const npmPath = resolveMiniProgramModule(join(miniprogramRootPath, ownerFilePath), request, miniprogramRootPath, (candidate) => candidate.endsWith(".js") && hasFile(candidate));
3353
+ return npmPath ? relative(miniprogramRootPath, npmPath).slice(0, -3) : localPath;
2388
3354
  }
2389
3355
  //#endregion
2390
3356
  //#region src/view/selectorQueryScope.ts
@@ -2446,6 +3412,209 @@ function resolveSelectorQueryScopeSnapshot(scope, snapshots) {
2446
3412
  return null;
2447
3413
  }
2448
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
2449
3618
  //#region src/view/templateImports.ts
2450
3619
  function createImportedTemplateState(root, filePath, loadImport, loadWxs) {
2451
3620
  const documents = /* @__PURE__ */ new Map();
@@ -2454,6 +3623,7 @@ function createImportedTemplateState(root, filePath, loadImport, loadWxs) {
2454
3623
  const collect = (node, owner) => {
2455
3624
  const existing = documents.get(owner);
2456
3625
  if (existing) return existing;
3626
+ const owners = expandTemplateIncludes(node, owner, loadImport);
2457
3627
  const state = createTemplateRenderState(node);
2458
3628
  const wxsModules = Object.create(null);
2459
3629
  const ownDefinitions = new Map(state.definitions);
@@ -2463,6 +3633,7 @@ function createImportedTemplateState(root, filePath, loadImport, loadWxs) {
2463
3633
  };
2464
3634
  documents.set(owner, document);
2465
3635
  const visit = (child) => {
3636
+ const sourceOwner = owners.get(child) ?? owner;
2466
3637
  if (child.name === "wxs" && loadWxs) {
2467
3638
  const name = child.attribs?.module;
2468
3639
  if (!name || !/^[a-z_$][\w$]*$/i.test(name) || [
@@ -2471,12 +3642,12 @@ function createImportedTemplateState(root, filePath, loadImport, loadWxs) {
2471
3642
  "prototype"
2472
3643
  ].includes(name)) throw new Error(`Invalid WXS module name in ${owner}: ${String(name)}`);
2473
3644
  if (Object.hasOwn(wxsModules, name)) throw new Error(`Duplicate WXS module in ${owner}: ${name}`);
2474
- wxsModules[name] = loadWxs(owner, child);
3645
+ wxsModules[name] = loadWxs(sourceOwner, child);
2475
3646
  return;
2476
3647
  }
2477
3648
  if (child.name === "import" && child.attribs?.src) {
2478
3649
  const source = child.attribs.src;
2479
- const imported = loadImport(owner, source.endsWith(".wxml") ? source : `${source}.wxml`);
3650
+ const imported = loadImport(sourceOwner, source.endsWith(".wxml") ? source : `${source}.wxml`);
2480
3651
  const importedDocument = collect(imported.root, imported.filePath);
2481
3652
  for (const [name, definition] of importedDocument.exports) state.definitions.set(name, definition);
2482
3653
  }
@@ -2562,17 +3733,18 @@ function maskTemplateAttributes(source) {
2562
3733
  const INLINE_WXS_RE = /<wxs\b([^>]*)(?<!\/)>([\s\S]*?)<\/wxs\s*>/g;
2563
3734
  function parseWxsTemplateDocument(templateSource) {
2564
3735
  const scripts = [];
2565
- const masked = maskTemplateAttributes(templateSource.replace(INLINE_WXS_RE, (_match, attributes, script) => {
3736
+ const source = templateSource.replace(INLINE_WXS_RE, (_match, attributes, script) => {
2566
3737
  return `<wxs data-sim-wxs="${scripts.push(script) - 1}"${attributes}>wxs-source</wxs>`;
2567
- }));
3738
+ });
3739
+ const masked = maskTemplateAttributes(source);
2568
3740
  const document = parseDocument(`<page>${masked.source}</page>`, {
2569
- xmlMode: false,
3741
+ xmlMode: true,
2570
3742
  decodeEntities: false,
2571
3743
  lowerCaseAttributeNames: false,
2572
3744
  lowerCaseTags: false,
2573
3745
  recognizeSelfClosing: true
2574
3746
  });
2575
- if (!scripts.length && !masked.attributes.size) return document;
3747
+ if (!scripts.length && !masked.attributes.size && !/[\r\n]/.test(source)) return document;
2576
3748
  const hasAttributes = masked.attributes.size > 0;
2577
3749
  const restore = (node) => {
2578
3750
  if (hasAttributes && node.attribs) {
@@ -2581,7 +3753,9 @@ function parseWxsTemplateDocument(templateSource) {
2581
3753
  if (node.name === "wxs" && Object.hasOwn(node.attribs ?? {}, "data-sim-wxs")) {
2582
3754
  node.children[0].data = scripts[Number(node.attribs["data-sim-wxs"])];
2583
3755
  delete node.attribs["data-sim-wxs"];
3756
+ return;
2584
3757
  }
3758
+ if (node.children) node.children = node.children.filter((child) => child.type !== "text" || !/^[\t\r\n ]+$/.test(child.data ?? "") || !/[\r\n]/.test(child.data ?? ""));
2585
3759
  for (const child of node.children ?? []) restore(child);
2586
3760
  };
2587
3761
  restore(document);
@@ -2622,7 +3796,7 @@ function collectDataset$1(node, source) {
2622
3796
  function escapeText$3(text) {
2623
3797
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
2624
3798
  }
2625
- function escapeAttribute$3(value) {
3799
+ function escapeAttribute$2(value) {
2626
3800
  return escapeText$3(value).replaceAll("\"", "&quot;");
2627
3801
  }
2628
3802
  function cloneNode$1(node) {
@@ -2639,18 +3813,18 @@ function resolveRawValueByPath$2(source, expression) {
2639
3813
  function interpolateTemplate$2(input, data) {
2640
3814
  return interpolateTemplateText(input, data, true);
2641
3815
  }
2642
- function readTemplateSource$1(files, filePath) {
2643
- const templateSource = readBrowserVirtualFile(files, filePath);
3816
+ function readTemplateSource$1(files, filePath, artifactSource) {
3817
+ const templateSource = artifactSource ? artifactSource.readText(filePath) : readBrowserVirtualFile(files, filePath);
2644
3818
  if (typeof templateSource !== "string") throw new TypeError(`Missing template in browser simulator runtime: ${filePath}`);
2645
3819
  return templateSource;
2646
3820
  }
2647
3821
  function parseTemplateDocument$1(templateSource) {
2648
3822
  return parseWxsTemplateDocument(templateSource);
2649
3823
  }
2650
- function prepareTemplateRenderState$1(files, root, filePath, projectRoot, loadWxs) {
3824
+ function prepareTemplateRenderState$1(files, root, filePath, projectRoot, loadWxs, artifactSource) {
2651
3825
  return createImportedTemplateState(root, filePath, (owner, source) => {
2652
3826
  const resolved = normalize(source.startsWith("/") ? join(projectRoot, source.slice(1)) : join(dirname(owner), source));
2653
- const document = parseTemplateDocument$1(readTemplateSource$1(files, resolved));
3827
+ const document = parseTemplateDocument$1(readTemplateSource$1(files, resolved, artifactSource));
2654
3828
  return {
2655
3829
  filePath: resolved,
2656
3830
  root: document.children?.[0] ?? document
@@ -2667,7 +3841,7 @@ function serializeDomNode$2(node) {
2667
3841
  if (node.type === "root") return (node.children ?? []).map(serializeDomNode$2).join("");
2668
3842
  const tagName = node.name ?? "";
2669
3843
  if (!tagName) return (node.children ?? []).map(serializeDomNode$2).join("");
2670
- 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}>`;
2671
3845
  }
2672
3846
  function isTagNode$1(node) {
2673
3847
  return node.type === "tag" && typeof node.name === "string";
@@ -2686,7 +3860,7 @@ function resolveComponentAttributeValue$1(value, scope) {
2686
3860
  }
2687
3861
  return interpolateTemplate$2(value, wxsScopeData(scope));
2688
3862
  }
2689
- function applyNodeBindings$1(node, scope) {
3863
+ function applyNodeBindings$1(node, scope, richText = false) {
2690
3864
  if (!isTagNode$1(node)) {
2691
3865
  if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplateText(node.data, wxsScopeData(scope));
2692
3866
  return;
@@ -2694,6 +3868,7 @@ function applyNodeBindings$1(node, scope) {
2694
3868
  node.attribs ??= {};
2695
3869
  node.attribs["data-sim-scope"] = scope.getScopeId();
2696
3870
  for (const key of STRUCTURAL_ATTRS$1) delete node.attribs[key];
3871
+ if (richText) node.children = [];
2697
3872
  let dataset;
2698
3873
  for (const [key, value] of Object.entries({ ...node.attribs })) {
2699
3874
  if (EVENT_BINDING_ATTRS$1.includes(key)) {
@@ -2701,6 +3876,8 @@ function applyNodeBindings$1(node, scope) {
2701
3876
  continue;
2702
3877
  }
2703
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);
2704
3881
  node.attribs[key] = String(resolvedValue ?? "");
2705
3882
  if (isDatasetAttribute(key)) {
2706
3883
  dataset ??= {};
@@ -2727,8 +3904,7 @@ function createLoopScope$1(scope, itemName, indexName, item, index) {
2727
3904
  //#endregion
2728
3905
  //#region src/browser/render/component.ts
2729
3906
  function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, alias, genericComponentBasePath) {
2730
- const usingComponents = resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath);
2731
- const componentBasePath = genericComponentBasePath ?? usingComponents.get(alias);
3907
+ const componentBasePath = genericComponentBasePath ?? resolveUsingComponent$1(context, ownerJsonPath, ownerFilePath, alias);
2732
3908
  if (!componentBasePath) return null;
2733
3909
  const filePath = `${componentBasePath}.js`;
2734
3910
  const templatePath = `${componentBasePath}.wxml`;
@@ -2747,30 +3923,25 @@ function readComponentConfig$1(files, jsonPath) {
2747
3923
  return {};
2748
3924
  }
2749
3925
  }
2750
- function resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath) {
3926
+ function resolveUsingComponent$1(context, ownerJsonPath, ownerFilePath, alias) {
2751
3927
  try {
2752
3928
  const usingComponents = readComponentConfig$1(context.files, join(context.project.miniprogramRootPath, ownerJsonPath)).usingComponents;
2753
- if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
2754
- const resolved = /* @__PURE__ */ new Map();
2755
- for (const [alias, rawPath] of Object.entries(usingComponents)) {
2756
- if (typeof rawPath !== "string") continue;
2757
- const basePath = resolvePluginRequest(context.project.plugins, rawPath, "publicComponent")?.resourcePath ?? resolveMiniProgramComponent(ownerFilePath, rawPath, context.project.miniprogramRootPath, (candidate) => readBrowserVirtualFile(context.files, candidate) !== void 0);
2758
- resolved.set(alias, basePath.replace(LEADING_SLASH_RE$5, ""));
2759
- }
2760
- 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, "");
2761
3933
  } catch {
2762
- return /* @__PURE__ */ new Map();
3934
+ return;
2763
3935
  }
2764
3936
  }
2765
3937
  function resolveComponentGenerics$1(context, hostNode, ownerJsonPath, ownerFilePath, componentFilePath, ownerGenerics) {
2766
3938
  const componentJsonPath = join(context.project.miniprogramRootPath, `${componentFilePath.replace(JS_FILE_RE$1, "")}.json`);
2767
3939
  const componentGenerics = readComponentConfig$1(context.files, componentJsonPath).componentGenerics;
2768
3940
  if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return;
2769
- const ownerComponents = resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath);
2770
3941
  const resolved = /* @__PURE__ */ new Map();
2771
3942
  for (const [genericName, definition] of Object.entries(componentGenerics)) {
2772
3943
  const selectedAlias = hostNode.attribs?.[`generic:${genericName}`];
2773
- 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;
2774
3945
  if (selectedPath) {
2775
3946
  resolved.set(genericName, selectedPath);
2776
3947
  continue;
@@ -2782,67 +3953,6 @@ function resolveComponentGenerics$1(context, hostNode, ownerJsonPath, ownerFileP
2782
3953
  }
2783
3954
  return resolved.size > 0 ? resolved : void 0;
2784
3955
  }
2785
- function collectComponentEventBindings$1(hostNode) {
2786
- return collectMiniProgramEventBindings(hostNode.attribs);
2787
- }
2788
- function buildComponentTrigger$1(componentScopeId, context, hostNode) {
2789
- const hostDataset = collectDataset$1(hostNode);
2790
- const hostId = hostNode.attribs?.id ?? "";
2791
- return (instance, eventName, detail, triggerOptions) => {
2792
- const originScope = context.componentScopes.get(componentScopeId);
2793
- const interactionMark = instance.__lastInteractionEvent__?.mark;
2794
- const target = {
2795
- dataset: originScope?.dataset ?? hostDataset,
2796
- id: originScope?.hostId ?? hostId
2797
- };
2798
- let currentScopeId = componentScopeId;
2799
- while (currentScopeId) {
2800
- const currentScope = context.componentScopes.get(currentScopeId);
2801
- const binding = currentScope?.eventBindings?.get(eventName);
2802
- const listenerScope = currentScope?.listenerScopeId ? context.componentScopes.get(currentScope.listenerScopeId) : null;
2803
- const handler = binding && listenerScope ? listenerScope.getMethod(binding.method) : void 0;
2804
- if (handler) handler({
2805
- bubbles: triggerOptions?.bubbles ?? false,
2806
- capturePhase: false,
2807
- composed: triggerOptions?.composed ?? false,
2808
- detail,
2809
- mark: interactionMark,
2810
- target,
2811
- type: eventName,
2812
- currentTarget: {
2813
- dataset: currentScope?.dataset ?? hostDataset,
2814
- id: currentScope?.hostId ?? hostId
2815
- }
2816
- });
2817
- if (binding?.stopAfter) break;
2818
- if (!triggerOptions?.bubbles || !triggerOptions?.composed) break;
2819
- currentScopeId = currentScope?.ownerScopeId;
2820
- }
2821
- };
2822
- }
2823
- function syncComponentProperties$1(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
2824
- const changedRootKeys = [];
2825
- const previousProperties = {};
2826
- for (const [key, value] of Object.entries(nextProperties)) {
2827
- const nextValue = normalizeComponentPropertyValue(definition, key, value);
2828
- const bindingExpression = bindingExpressions[key];
2829
- const bindingAffected = !!bindingExpression && changedPageKeys.some((changedKey) => {
2830
- return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
2831
- });
2832
- const previousSnapshot = instance.__propertySnapshots?.[key];
2833
- if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
2834
- previousProperties[key] = instance.properties[key];
2835
- const deliveredValue = cloneValue(nextValue);
2836
- instance.properties[key] = deliveredValue;
2837
- if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = deliveredValue;
2838
- changedRootKeys.push(key);
2839
- }
2840
- instance.__propertySnapshots ??= {};
2841
- instance.__propertySnapshots[key] = cloneValue(nextValue);
2842
- }
2843
- if (changedRootKeys.length === 0) return;
2844
- runComponentObservers(definition, instance, changedRootKeys, previousProperties);
2845
- }
2846
3956
  function createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots) {
2847
3957
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
2848
3958
  return {
@@ -2850,7 +3960,7 @@ function createComponentScope$1(clonedNode, scope, componentScopeId, componentIn
2850
3960
  classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
2851
3961
  data: { ...componentInstance.data },
2852
3962
  dataset: collectDataset$1(clonedNode, wxsScopeData(scope)),
2853
- eventBindings: collectComponentEventBindings$1(clonedNode),
3963
+ ...bindComponentEventHost(clonedNode),
2854
3964
  getMethod: (methodName) => {
2855
3965
  const method = componentInstance?.[methodName];
2856
3966
  return typeof method === "function" ? method.bind(componentInstance) : void 0;
@@ -2858,6 +3968,7 @@ function createComponentScope$1(clonedNode, scope, componentScopeId, componentIn
2858
3968
  getScopeId: () => componentScopeId,
2859
3969
  genericComponents,
2860
3970
  hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
3971
+ hostNode: clonedNode,
2861
3972
  id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
2862
3973
  listenerScopeId: scope.getScopeId(),
2863
3974
  ownerScopeId,
@@ -2880,13 +3991,13 @@ function resolveComponentProperties$1(clonedNode, scope, definition) {
2880
3991
  bindingExpressions
2881
3992
  };
2882
3993
  }
2883
- function createBrowserComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId, beforeCreated) {
2884
- 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;
2885
- const componentInstance = createComponentInstance({
3994
+ function createBrowserComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, renderTemplate, bindEventsBeforeProperties = false) {
3995
+ const instanceOptions = {
2886
3996
  definition: componentEntry.definition,
2887
- requestRender: (callback) => context.session.requestRender(callback),
2888
- triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
2889
- });
3997
+ requestRender: (callback) => context.session.requestRender(callback)
3998
+ };
3999
+ const componentInstance = createComponentInstance(instanceOptions);
4000
+ bindAttachmentBindingScope(componentInstance, context);
2890
4001
  setSelectorQueryScopeId(componentInstance, componentScopeId);
2891
4002
  componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE$1, "");
2892
4003
  componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
@@ -2894,20 +4005,30 @@ function createBrowserComponentInstance(componentScopeId, context, clonedNode, c
2894
4005
  componentInstance.createSelectorQuery = () => context.moduleLoader.wx.createSelectorQuery().in(componentInstance);
2895
4006
  componentInstance.selectComponent = (selector) => resolveNativeComponentSelection(context.session.selectComponentWithin(componentScopeId, selector));
2896
4007
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector).map(resolveNativeComponentSelection);
2897
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
4008
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? resolveNativeComponentSelection(context.componentCache.get(ownerScopeId)) : null;
4009
+ beginComponentConstruction(context.componentCache, componentScopeId, componentInstance);
2898
4010
  context.componentCache.set(componentScopeId, componentInstance);
2899
- beforeCreated?.(componentInstance);
2900
- runComponentLifecycle(componentInstance, "created");
2901
- componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
2902
- syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, []);
2903
- return componentInstance;
4011
+ try {
4012
+ renderTemplate?.(componentInstance, "defaults");
4013
+ runComponentLifecycle(componentInstance, "created");
4014
+ if (bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
4015
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
4016
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, {}, [], renderTemplate);
4017
+ if (!bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
4018
+ return componentInstance;
4019
+ } catch (error) {
4020
+ discardComponentConstruction(context.componentCache, context.componentScopes, componentScopeId);
4021
+ throw error;
4022
+ } finally {
4023
+ finishComponentConstruction(context.componentCache, componentInstance);
4024
+ }
2904
4025
  }
2905
- function renderBrowserComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
4026
+ function renderBrowserComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, renderPass) {
2906
4027
  const templatePath = join(context.project.miniprogramRootPath, componentEntry.templatePath);
2907
- const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
4028
+ const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath, context.templateSource));
2908
4029
  const componentRoot = (componentDocument.children ?? [])[0] ?? componentDocument;
2909
- const templateRenderState = prepareTemplateRenderState$1(context.files, componentRoot, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
2910
- return renderNodeTree(componentRoot, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes, templateRenderState);
4030
+ const templateRenderState = prepareTemplateRenderState$1(context.files, componentRoot, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files), context.templateSource);
4031
+ return renderNodeTree(componentRoot, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, renderPass, templateRenderState, componentScope.hostNode);
2911
4032
  }
2912
4033
  //#endregion
2913
4034
  //#region src/browser/render/index.ts
@@ -2921,24 +4042,33 @@ function expandNodeByFor$1(node, scope) {
2921
4042
  const items = resolveLoopEntries(resolveRawValueByPath$2(wxsScopeData(scope), forExpression));
2922
4043
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
2923
4044
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
4045
+ const key = node.attribs?.["wx:key"]?.trim();
4046
+ const keyOccurrences = key ? /* @__PURE__ */ new Map() : void 0;
2924
4047
  return items.map(([index, item]) => ({
2925
4048
  node: cloneNode$1(node),
2926
4049
  scope: createLoopScope$1(scope, itemName, indexName, item, index),
2927
- instanceSuffix: `:for-${index}`
4050
+ instanceSuffix: resolveLoopInstanceSuffix(item, index, key, keyOccurrences)
2928
4051
  }));
2929
4052
  }
2930
- function renderNodeVariants$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
2931
- return expandNodeByFor$1(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree$1(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes, templateRenderState));
4053
+ function renderNodeVariants$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
4054
+ const nodes = [];
4055
+ if (isRenderPassStale(renderPass)) return nodes;
4056
+ for (const { node: expandedNode, scope: expandedScope, instanceSuffix } of expandNodeByFor$1(node, scope)) {
4057
+ if (isRenderPassStale(renderPass)) break;
4058
+ nodes.push(renderNodeTree$1(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, renderPass, templateRenderState, parent));
4059
+ }
4060
+ return nodes;
2932
4061
  }
2933
- function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
4062
+ function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
2934
4063
  const renderedChildren = [];
2935
4064
  for (const { node: child, index } of selectConditionalChildren(children, (node) => evaluateConditionalBranch$1(node, scope))) {
4065
+ if (isRenderPassStale(renderPass)) break;
2936
4066
  if (!isTagNode$1(child)) {
2937
- renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
4067
+ renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, renderPass, templateRenderState, parent));
2938
4068
  continue;
2939
4069
  }
2940
4070
  if (isTemplateDefinition(child) || child.name === "import" || child.name === "wxs") continue;
2941
- renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
4071
+ renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, renderPass, templateRenderState, parent));
2942
4072
  }
2943
4073
  return renderedChildren;
2944
4074
  }
@@ -2970,22 +4100,38 @@ function collectComponentSlots$1(componentNode, scope, ownerJsonPath, ownerFileP
2970
4100
  }
2971
4101
  return slots;
2972
4102
  }
2973
- function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
4103
+ function reconcileSlotDeclarations$1(context, renderPass) {
4104
+ for (const [entries, { parent, scopeId }] of renderPass.slotDeclarations) {
4105
+ if (isRenderPassStale(renderPass)) return;
4106
+ if (isComponentConstructing(context.componentCache.get(scopeId))) continue;
4107
+ for (const { index } of selectConditionalChildren(entries.map((entry) => entry.node), (node, index) => evaluateConditionalBranch$1(node, entries[index].scope))) {
4108
+ if (isRenderPassStale(renderPass)) return;
4109
+ const entry = entries[index];
4110
+ if (renderPass.renderedSlots.has(entry)) continue;
4111
+ const nodes = renderNodeVariants$1(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, renderPass, entry.templateRenderState, parent);
4112
+ renderPass.renderedSlots.set(entry, nodes);
4113
+ renderPass.hasUnprojectedSlots ||= nodes.length > 0;
4114
+ }
4115
+ }
4116
+ }
4117
+ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
4118
+ if (isRenderPassStale(renderPass)) return node;
2974
4119
  if (scope.wxs !== templateRenderState.wxsModules) scope = {
2975
4120
  ...scope,
2976
4121
  wxs: templateRenderState.wxsModules
2977
4122
  };
2978
4123
  const clonedNode = cloneNode$1(node);
4124
+ registerComponentEventNode(clonedNode, scope, parent);
2979
4125
  if (!isTagNode$1(clonedNode)) {
2980
4126
  applyNodeBindings$1(clonedNode, scope);
2981
4127
  return clonedNode;
2982
4128
  }
2983
- if (isTemplateDefinition(clonedNode)) return {
2984
- type: "tag",
2985
- name: "block",
2986
- attribs: {},
2987
- children: []
2988
- };
4129
+ if (isTemplateDefinition(clonedNode)) {
4130
+ clonedNode.name = "block";
4131
+ clonedNode.attribs = {};
4132
+ clonedNode.children = [];
4133
+ return clonedNode;
4134
+ }
2989
4135
  const templateName = resolveTemplateCall(clonedNode, wxsScopeData(scope));
2990
4136
  if (templateName) {
2991
4137
  const definition = templateRenderState.definitions.get(templateName);
@@ -2994,36 +4140,39 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
2994
4140
  data: resolveTemplateData(clonedNode, wxsScopeData(scope)),
2995
4141
  wxs: definition && templateRenderState.definitionWxsScopes?.get(definition)
2996
4142
  };
2997
- const children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren$1(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, seenComponentScopes, {
4143
+ clonedNode.name = "block";
4144
+ clonedNode.attribs = {
4145
+ "data-sim-node": instancePath,
4146
+ "data-sim-scope": scope.getScopeId()
4147
+ };
4148
+ clonedNode.children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren$1(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, renderPass, {
2998
4149
  definitions: templateRenderState.definitionScopes?.get(definition) ?? templateRenderState.definitions,
2999
4150
  definitionScopes: templateRenderState.definitionScopes,
3000
4151
  definitionWxsScopes: templateRenderState.definitionWxsScopes,
3001
4152
  wxsModules: templateScope.wxs,
3002
4153
  stack: [...templateRenderState.stack, templateName]
3003
- }) : [];
3004
- return {
3005
- type: "tag",
3006
- name: "block",
3007
- attribs: {
3008
- "data-sim-node": instancePath,
3009
- "data-sim-scope": scope.getScopeId()
3010
- },
3011
- children
3012
- };
4154
+ }, clonedNode) : [];
4155
+ return clonedNode;
3013
4156
  }
3014
4157
  if (clonedNode.name === "slot") {
3015
4158
  const slotName = clonedNode.attribs?.name?.trim() || "default";
3016
4159
  const projected = scope.slots?.get(slotName) ?? [];
3017
- const children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch$1(node, projected[index].scope)).flatMap(({ index }) => {
4160
+ const fallbackChildren = clonedNode.children ?? [];
4161
+ bindComponentEventHost(clonedNode);
4162
+ clonedNode.name = "block";
4163
+ clonedNode.attribs = { "data-sim-scope": scope.getScopeId() };
4164
+ const slotOwner = scope.getScopeId();
4165
+ if (projected.length && slotOwner && isComponentConstructing(context.componentCache.get(slotOwner))) {
4166
+ clonedNode.children = [];
4167
+ return clonedNode;
4168
+ }
4169
+ clonedNode.children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch$1(node, projected[index].scope)).flatMap(({ index }) => {
3018
4170
  const entry = projected[index];
3019
- return renderNodeVariants$1(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, seenComponentScopes, entry.templateRenderState);
3020
- }) : renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, seenComponentScopes, templateRenderState);
3021
- return {
3022
- type: "tag",
3023
- name: "block",
3024
- attribs: { "data-sim-scope": scope.getScopeId() },
3025
- children
3026
- };
4171
+ const nodes = renderNodeVariants$1(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, renderPass, entry.templateRenderState, clonedNode);
4172
+ renderPass.renderedSlots.set(entry, nodes);
4173
+ return nodes;
4174
+ }) : renderChildren$1(fallbackChildren, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, renderPass, templateRenderState, clonedNode);
4175
+ return clonedNode;
3027
4176
  }
3028
4177
  const componentEntry = resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, clonedNode.name, scope.genericComponents?.get(clonedNode.name));
3029
4178
  if (componentEntry) {
@@ -3032,19 +4181,31 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
3032
4181
  const { nextProperties, bindingExpressions } = resolveComponentProperties$1(clonedNode, scope, componentEntry.definition);
3033
4182
  const genericComponents = resolveComponentGenerics$1(context, clonedNode, ownerJsonPath, ownerFilePath, componentEntry.filePath, scope.genericComponents);
3034
4183
  const slots = collectComponentSlots$1(clonedNode, scope, ownerJsonPath, ownerFilePath, componentScopeId, templateRenderState);
4184
+ registerSlotDeclarations(renderPass, slots, clonedNode, componentScopeId);
4185
+ applyNodeBindings$1(clonedNode, scope);
4186
+ const reconcilePrivateTemplate = (instance, phase) => {
4187
+ let bindingPass;
4188
+ do {
4189
+ const bindingScope = createComponentScope$1(clonedNode, scope, componentScopeId, instance, genericComponents, slots);
4190
+ context.componentScopes.set(componentScopeId, bindingScope);
4191
+ bindingPass = createRenderPass(phase === "properties", renderPass);
4192
+ renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, bindingScope, componentScopeId, bindingPass);
4193
+ reconcileSlotDeclarations$1(context, bindingPass);
4194
+ } while (isRenderPassStale(bindingPass));
4195
+ };
3035
4196
  let componentInstance = context.componentCache.get(componentScopeId);
3036
- if (!componentInstance) componentInstance = createBrowserComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId, (instance) => {
3037
- const initialScope = createComponentScope$1(clonedNode, scope, componentScopeId, instance, genericComponents, slots);
3038
- context.componentScopes.set(componentScopeId, initialScope);
3039
- renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, initialScope, componentScopeId, /* @__PURE__ */ new Set());
3040
- });
3041
- else syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
3042
- seenComponentScopes.add(componentScopeId);
4197
+ if (!componentInstance) componentInstance = createBrowserComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, reconcilePrivateTemplate, renderPass.propertyUpdate);
4198
+ else {
4199
+ context.componentScopes.set(componentScopeId, createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots));
4200
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys, reconcilePrivateTemplate);
4201
+ }
4202
+ if (isRenderPassStale(renderPass)) return clonedNode;
4203
+ renderPass.seenComponentScopes.add(componentScopeId);
3043
4204
  const componentScope = createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots);
3044
4205
  context.componentScopes.set(componentScopeId, componentScope);
3045
- const renderedComponentRoot = renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, componentScope, componentScopeId, seenComponentScopes);
4206
+ const renderedComponentRoot = renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, componentScope, componentScopeId, renderPass);
4207
+ mergeComponentEventRoot(renderedComponentRoot, clonedNode);
3046
4208
  if (renderedComponentRoot.attribs) {
3047
- applyNodeBindings$1(clonedNode, scope);
3048
4209
  renderedComponentRoot.attribs = {
3049
4210
  ...clonedNode.attribs,
3050
4211
  ...renderedComponentRoot.attribs
@@ -3056,66 +4217,94 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
3056
4217
  renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
3057
4218
  renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
3058
4219
  }
4220
+ renderPass.componentRoots.set(componentScopeId, renderedComponentRoot);
3059
4221
  return renderedComponentRoot;
3060
4222
  }
3061
- applyNodeBindings$1(clonedNode, scope);
4223
+ const richText = clonedNode.name === "rich-text";
4224
+ applyNodeBindings$1(clonedNode, scope, richText);
3062
4225
  clonedNode.attribs["data-sim-node"] = instancePath;
3063
- clonedNode.children = renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes, templateRenderState);
4226
+ if (richText) return clonedNode;
4227
+ clonedNode.children = renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, renderPass, templateRenderState, clonedNode);
3064
4228
  return clonedNode;
3065
4229
  }
4230
+ function reconcileBrowserPageTree(context, page, bindingsOnly = false) {
4231
+ for (;;) {
4232
+ bindAttachmentBindingScope(context, page);
4233
+ if (page.__lastChangedKeys__) context.changedPageKeys = page.__lastChangedKeys__;
4234
+ const route = page.route.replace(LEADING_SLASH_RE$5, "");
4235
+ const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
4236
+ const templatePath = join(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
4237
+ const document = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath, context.templateSource));
4238
+ const pageScopeId = `page:${route}`;
4239
+ const pageScope = {
4240
+ data: page.data,
4241
+ getMethod: (methodName) => {
4242
+ const method = page[methodName];
4243
+ return typeof method === "function" ? method.bind(page) : void 0;
4244
+ },
4245
+ getScopeId: () => pageScopeId,
4246
+ id: "page-root"
4247
+ };
4248
+ for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
4249
+ context.componentScopes.set(pageScopeId, pageScope);
4250
+ const renderPass = createPageRenderPass(page, context.componentCache);
4251
+ const root = (document.children ?? [])[0] ?? document;
4252
+ const templateRenderState = prepareTemplateRenderState$1(context.files, root, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files), context.templateSource);
4253
+ const renderedRoot = renderNodeTree$1(root, pageScope, context, `${resourcePath}.json`, `${resourcePath}.js`, pageScopeId, renderPass, templateRenderState);
4254
+ const roots = [renderedRoot];
4255
+ if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree$1({
4256
+ type: "tag",
4257
+ name: "custom-tab-bar",
4258
+ attribs: {},
4259
+ children: []
4260
+ }, customTabBarHostScope(), context, "app.json", "app.js", pageScopeId, renderPass, templateRenderState));
4261
+ reconcileSlotDeclarations$1(context, renderPass);
4262
+ if (isRenderPassStale(renderPass)) continue;
4263
+ markPageTreeConstructed(page, context.componentCache);
4264
+ const treeRoot = roots.length > 1 ? {
4265
+ type: "root",
4266
+ children: roots
4267
+ } : renderedRoot;
4268
+ linkRenderedParents(treeRoot);
4269
+ registerInspectionTrees(treeRoot, renderPass, context.componentScopes);
4270
+ if (bindingsOnly) return {
4271
+ root: treeRoot,
4272
+ roots,
4273
+ resourcePath
4274
+ };
4275
+ let bindingsRefreshed = false;
4276
+ const updateBindings = () => {
4277
+ bindingsRefreshed = true;
4278
+ if (hasPendingComponentConstruction(context.componentCache)) return;
4279
+ reconcileBrowserPageTree(context, page, true);
4280
+ };
4281
+ const pageAttached = attachComponentPage(page, updateBindings);
4282
+ if (bindingsRefreshed) continue;
4283
+ const pageAttaching = isComponentPageAttaching(page);
4284
+ const scopeIds = orderComponentAttachmentScopes(renderPass.seenComponentScopes, context.componentScopes);
4285
+ const instances = scopeIds.map((scopeId) => context.componentCache.get(scopeId));
4286
+ const attached = !pageAttaching && runWithAttachmentBindingUpdates(page, updateBindings, (scopes) => flushComponentAttachments(context.componentCache, scopes, (instance) => {
4287
+ runComponentLifecycle(instance, "attached");
4288
+ if (instance !== context.componentCache.get(customTabBarScopeId(route))) runComponentPageLifetime(instance, "show");
4289
+ return bindingsRefreshed;
4290
+ }), scopeIds);
4291
+ if (attached === "restart") continue;
4292
+ const canFinalize = !pageAttaching && !hasPendingComponentAttachments(instances);
4293
+ const relationsChanged = canFinalize && reconcileRemovedComponents(context.componentCache, context.componentScopes, renderPass.seenComponentScopes, pageScopeId);
4294
+ if (pageAttached || attached || relationsChanged) continue;
4295
+ if (canFinalize && !isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
4296
+ if (canFinalize && !isPageBeforeReady(page) && flushComponentReady(instances, (instance) => runComponentLifecycle(instance, "ready"))) continue;
4297
+ return {
4298
+ root: treeRoot,
4299
+ roots,
4300
+ resourcePath
4301
+ };
4302
+ }
4303
+ }
3066
4304
  function renderBrowserPageTree(context, page) {
3067
- const route = page.route.replace(LEADING_SLASH_RE$5, "");
3068
- const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
3069
- const templatePath = join(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
3070
- const document = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
3071
- const pageScopeId = `page:${route}`;
3072
- const pageScope = {
3073
- data: page.data,
3074
- getMethod: (methodName) => {
3075
- const method = page[methodName];
3076
- return typeof method === "function" ? method.bind(page) : void 0;
3077
- },
3078
- getScopeId: () => pageScopeId,
3079
- id: "page-root"
3080
- };
3081
- for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
3082
- context.componentScopes.set(pageScopeId, pageScope);
3083
- const seenComponentScopes = /* @__PURE__ */ new Set();
3084
- const root = (document.children ?? [])[0] ?? document;
3085
- const templateRenderState = prepareTemplateRenderState$1(context.files, root, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
3086
- const renderedRoot = renderNodeTree$1(root, pageScope, context, `${resourcePath}.json`, `${resourcePath}.js`, pageScopeId, seenComponentScopes, templateRenderState);
3087
- const roots = [renderedRoot];
3088
- if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree$1({
3089
- type: "tag",
3090
- name: "custom-tab-bar",
3091
- attribs: {},
3092
- children: []
3093
- }, customTabBarHostScope(), context, "app.json", "app.js", pageScopeId, seenComponentScopes, templateRenderState));
3094
- const pageAttached = attachComponentPage(page);
3095
- const pageAttaching = isComponentPageAttaching(page);
3096
- const attached = !pageAttaching && flushComponentAttachments([...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId)), (instance) => {
3097
- runComponentLifecycle(instance, "attached");
3098
- if (instance !== context.componentCache.get(customTabBarScopeId(route))) runComponentPageLifetime(instance, "show");
3099
- });
3100
- const removed = [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !seenComponentScopes.has(scopeId));
3101
- for (const [scopeId, instance] of removed) if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
3102
- else scheduleDiscardedComponentReady(context.componentCache, scopeId, instance);
3103
- const instances = [...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId));
3104
- const relationsChanged = !pageAttaching && !hasPendingComponentAttachments(instances) && syncComponentRelations(context.componentCache, seenComponentScopes, pageScopeId);
3105
- for (const [scopeId] of removed) {
3106
- context.componentCache.delete(scopeId);
3107
- context.componentScopes.delete(scopeId);
3108
- }
3109
- if (pageAttached || attached || relationsChanged) return renderBrowserPageTree(context, page);
3110
- if (!isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
3111
- if (!isPageBeforeReady(page) && flushComponentReady(instances, (instance) => runComponentLifecycle(instance, "ready"))) return renderBrowserPageTree(context, page);
3112
- const treeRoot = roots.length > 1 ? {
3113
- type: "root",
3114
- children: roots
3115
- } : renderedRoot;
3116
- linkRenderedParents(treeRoot);
4305
+ const { root, roots, resourcePath } = reconcileBrowserPageTree(context, page);
3117
4306
  return {
3118
- root: treeRoot,
4307
+ root,
3119
4308
  styles: resolveBrowserPageStyles(context.files, resourcePath, {
3120
4309
  miniprogramRootPath: context.project.miniprogramRootPath,
3121
4310
  styleIsolation: resolveBrowserComponentPageStyleIsolation(context.files, page, resourcePath, context.project.miniprogramRootPath)
@@ -3161,6 +4350,62 @@ function invokePreparedNavigationApi(prepare, option) {
3161
4350
  }
3162
4351
  }
3163
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
3164
4409
  //#region src/project/hostConfig.ts
3165
4410
  /**
3166
4411
  * @description 根据构建后的 app.json 创建模拟器提供给小程序脚本读取的宿主配置。
@@ -3429,6 +4674,7 @@ function createPageInstance(route, definition, options = {}, pageState = {}) {
3429
4674
  const rootKey = parseDataPath(key)[0];
3430
4675
  if (rootKey) instance.properties[rootKey] = instance.data[rootKey];
3431
4676
  }
4677
+ synchronizeAttachmentBindings(instance);
3432
4678
  if (pageState.requestRender) pageState.requestRender(callback);
3433
4679
  else callback?.();
3434
4680
  }
@@ -3451,6 +4697,7 @@ var HeadlessRouteEvents = class {
3451
4697
  nextRouteId = 0;
3452
4698
  nextWebviewId = 0;
3453
4699
  activeEvent;
4700
+ activeState;
3454
4701
  constructor(requestRender, isCurrentPage) {
3455
4702
  this.requestRender = requestRender;
3456
4703
  this.isCurrentPage = isCurrentPage;
@@ -3462,6 +4709,7 @@ var HeadlessRouteEvents = class {
3462
4709
  this.bus.$off(name, listener);
3463
4710
  }
3464
4711
  begin(path, query, openType, renderer, page) {
4712
+ this.cancel(this.activeState, /* @__PURE__ */ new Error("navigateTo:fail navigation was superseded"));
3465
4713
  const previous = page ? this.pages.get(page) : void 0;
3466
4714
  const event = {
3467
4715
  path,
@@ -3478,12 +4726,28 @@ var HeadlessRouteEvents = class {
3478
4726
  }
3479
4727
  attach(page, event) {
3480
4728
  const state = this.pages.get(page);
3481
- this.pages.set(page, {
4729
+ const next = {
3482
4730
  webviewId: event.webviewId,
3483
4731
  ready: state?.ready ?? false,
3484
4732
  event,
3485
- committed: false
3486
- });
4733
+ committed: false,
4734
+ completed: false
4735
+ };
4736
+ this.pages.set(page, next);
4737
+ if (this.activeEvent === event) this.activeState = next;
4738
+ }
4739
+ /** 原生 navigateTo 的回调属于本次路由记录,不能以当前页面或提交栈代替完成。 */
4740
+ navigateTo(operation, callbacks) {
4741
+ let state;
4742
+ try {
4743
+ state = this.pages.get(operation());
4744
+ } catch (error) {
4745
+ this.settle(callbacks, error);
4746
+ return;
4747
+ }
4748
+ if (!state || state.canceled) this.settle(callbacks, state?.canceled ?? /* @__PURE__ */ new Error("navigateTo:fail target page was unloaded"));
4749
+ else if (state.completed) this.settle(callbacks);
4750
+ else state.callbacks = callbacks;
3487
4751
  }
3488
4752
  commit(page, event) {
3489
4753
  const state = this.pages.get(page);
@@ -3500,10 +4764,40 @@ var HeadlessRouteEvents = class {
3500
4764
  }
3501
4765
  complete(page, state) {
3502
4766
  this.requestRender(() => {
3503
- if (this.pages.get(page) !== state || this.activeEvent !== state.event || !this.isCurrentPage(page)) return;
3504
- this.bus.$emit("appRouteDone", state.event);
4767
+ if (state.completed || state.canceled || this.pages.get(page) !== state || this.activeEvent !== state.event || !this.isCurrentPage(page)) return;
4768
+ state.completed = true;
4769
+ const callbacks = state.callbacks;
4770
+ state.callbacks = void 0;
4771
+ try {
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
+ });
4781
+ } finally {
4782
+ this.settle(callbacks);
4783
+ }
3505
4784
  });
3506
4785
  }
4786
+ settle(callbacks, error) {
4787
+ try {
4788
+ if (error) callbacks?.fail?.(error);
4789
+ else callbacks?.success?.();
4790
+ } finally {
4791
+ callbacks?.complete?.();
4792
+ }
4793
+ }
4794
+ cancel(state, error) {
4795
+ if (!state || state.completed || state.canceled) return;
4796
+ state.canceled = error;
4797
+ const callbacks = state.callbacks;
4798
+ state.callbacks = void 0;
4799
+ this.settle(callbacks, error);
4800
+ }
3507
4801
  beforeUnload(page, event) {
3508
4802
  const state = this.pages.get(page);
3509
4803
  if (event && state) this.bus.$emit("beforePageUnload", {
@@ -3514,9 +4808,12 @@ var HeadlessRouteEvents = class {
3514
4808
  webviewId: state.webviewId,
3515
4809
  page
3516
4810
  });
4811
+ this.cancel(state, /* @__PURE__ */ new Error("navigateTo:fail target page was unloaded"));
3517
4812
  this.pages.delete(page);
3518
4813
  }
3519
4814
  close() {
4815
+ this.cancel(this.activeState, /* @__PURE__ */ new Error("navigateTo:fail runtime session closed"));
4816
+ this.activeState = void 0;
3520
4817
  this.activeEvent = void 0;
3521
4818
  this.bus.$off();
3522
4819
  }
@@ -5293,24 +6590,48 @@ function createHeadlessWxState(scheduler = nativeScheduler, options = {}) {
5293
6590
  };
5294
6591
  }
5295
6592
  //#endregion
6593
+ //#region src/view/nodeSerialization.ts
6594
+ function escapeText$2(text) {
6595
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
6596
+ }
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 ?? ""}>`;
6603
+ }
6604
+ function collectNodeText$1(node) {
6605
+ if (node.type === "text") return node.data ?? "";
6606
+ return (node.children ?? []).map(collectNodeText$1).join("");
6607
+ }
6608
+ //#endregion
5296
6609
  //#region src/view/selectors.ts
5297
- const adapter = {
5298
- isTag: (node) => node.type === "tag",
5299
- getAttributeValue: (node, name) => node.attribs?.[name],
5300
- getChildren: (node) => node.children ?? [],
5301
- getName: (node) => node.name ?? "",
5302
- getParent: (node) => node.parent ?? null,
5303
- getSiblings: (node) => node.parent?.children ?? [node],
5304
- getText: (node) => node.type === "text" ? node.data ?? "" : (node.children ?? []).map((child) => adapter.getText(child)).join(""),
5305
- hasAttrib: (node, name) => Object.hasOwn(node.attribs ?? {}, name),
5306
- removeSubsets: (nodes) => {
5307
- const unique = new Set(nodes);
5308
- return [...unique].filter((node) => {
5309
- for (let parent = node.parent; parent; parent = parent.parent) if (unique.has(parent)) return false;
5310
- return true;
5311
- });
5312
- }
5313
- };
6610
+ function createAdapter(getChildren, getParent) {
6611
+ const adapter = {
6612
+ isTag: (node) => node.type === "tag",
6613
+ getAttributeValue: (node, name) => node.attribs?.[name],
6614
+ getChildren,
6615
+ getName: (node) => node.name ?? "",
6616
+ getParent,
6617
+ getSiblings: (node) => {
6618
+ const parent = getParent(node);
6619
+ return parent ? getChildren(parent) : [node];
6620
+ },
6621
+ getText: (node) => node.type === "text" ? node.data ?? "" : getChildren(node).map((child) => adapter.getText(child)).join(""),
6622
+ hasAttrib: (node, name) => Object.hasOwn(node.attribs ?? {}, name),
6623
+ removeSubsets: (nodes) => {
6624
+ const unique = new Set(nodes);
6625
+ return [...unique].filter((node) => {
6626
+ for (let parent = getParent(node); parent; parent = getParent(parent)) if (unique.has(parent)) return false;
6627
+ return true;
6628
+ });
6629
+ }
6630
+ };
6631
+ return adapter;
6632
+ }
6633
+ const renderedAdapter = createAdapter((node) => node.children ?? [], (node) => node.parent ?? null);
6634
+ const inspectionAdapter = createAdapter(getInspectionChildren, getInspectionParent);
5314
6635
  function resolveComponentTags(selectors) {
5315
6636
  return selectors.map((group) => group.map((token) => {
5316
6637
  if (token.type === SelectorType.Pseudo && Array.isArray(token.data)) return {
@@ -5333,8 +6654,8 @@ function resolveComponentTags(selectors) {
5333
6654
  };
5334
6655
  }));
5335
6656
  }
5336
- function querySelectorAll(root, selector) {
5337
- const parsed = parse(selector);
6657
+ function queryWithAdapter(root, selector, adapter) {
6658
+ const parsed = parse$1(selector);
5338
6659
  const query = resolveComponentTags(parsed);
5339
6660
  const includesPageRoot = root.type === "tag" && root.name === "page" && parsed.some((group) => group.some((token) => token.type === SelectorType.Tag && token.name === "page"));
5340
6661
  return selectAll(query, includesPageRoot ? [root] : root, {
@@ -5342,10 +6663,19 @@ function querySelectorAll(root, selector) {
5342
6663
  cacheResults: false
5343
6664
  });
5344
6665
  }
6666
+ function querySelectorAll(root, selector) {
6667
+ return queryWithAdapter(root, selector, renderedAdapter);
6668
+ }
6669
+ function queryInspectionSelectorAll(root, selector) {
6670
+ return queryWithAdapter(root, selector, inspectionAdapter);
6671
+ }
5345
6672
  //#endregion
5346
6673
  //#region src/view/xpath.ts
5347
6674
  const xpathEngine = Reflect.get(fontoxpath, "default") ?? fontoxpath;
5348
- function wrapNode(source, parent = null) {
6675
+ function getRenderedChildren(node) {
6676
+ return node.children ?? [];
6677
+ }
6678
+ function wrapNode(source, getChildren, parent = null) {
5349
6679
  const node = {
5350
6680
  attributes: [],
5351
6681
  children: [],
@@ -5368,7 +6698,7 @@ function wrapNode(source, parent = null) {
5368
6698
  prefix: null,
5369
6699
  value
5370
6700
  }));
5371
- node.children = (source.children ?? []).map((child) => wrapNode(child, node));
6701
+ node.children = getChildren(source).map((child) => wrapNode(child, getChildren, node));
5372
6702
  return node;
5373
6703
  }
5374
6704
  function sibling(node, offset) {
@@ -5388,39 +6718,27 @@ const domFacade = {
5388
6718
  getParentNode: (node) => node.parent,
5389
6719
  getPreviousSibling: (node) => sibling(node, -1)
5390
6720
  };
5391
- function queryXPathElements(root, expression) {
6721
+ function queryElements(root, expression, getChildren) {
5392
6722
  if (!expression.trim()) throw new Error("XPath must be a non-empty expression in headless testing runtime.");
5393
6723
  const document = wrapNode(root.type === "root" ? root : {
5394
6724
  type: "root",
5395
6725
  children: [root]
5396
- });
6726
+ }, getChildren);
5397
6727
  return xpathEngine.evaluateXPathToNodes(expression, document, domFacade).filter((node) => node.nodeType === 1).map((node) => node.source);
5398
6728
  }
6729
+ function queryXPathElements(root, expression) {
6730
+ return queryElements(root, expression, getRenderedChildren);
6731
+ }
6732
+ function queryInspectionXPathElements(root, expression) {
6733
+ return queryElements(root, expression, getInspectionChildren);
6734
+ }
5399
6735
  //#endregion
5400
6736
  //#region src/view/nodeHandle.ts
5401
- function escapeText$2(text) {
5402
- return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
5403
- }
5404
6737
  function createValueEventDetail(value, detail) {
5405
6738
  return {
5406
6739
  value,
5407
6740
  ...detail ?? {}
5408
- };
5409
- }
5410
- function escapeAttribute$2(value) {
5411
- return escapeText$2(value).replaceAll("\"", "&quot;");
5412
- }
5413
- function serializeNode(node) {
5414
- if (node.type === "text") return escapeText$2(node.data ?? "");
5415
- if (node.type !== "tag") return (node.children ?? []).map(serializeNode).join("");
5416
- if (node.name === "page") return (node.children ?? []).filter((child) => !(child.type === "tag" && (child.name === "import" || child.name === "wxs"))).map(serializeNode).join("");
5417
- const attrs = Object.entries(node.attribs ?? {}).filter(([key]) => !key.startsWith("data-sim-")).map(([key, value]) => ` ${key}="${escapeAttribute$2(value)}"`).join("");
5418
- const children = (node.children ?? []).map(serializeNode).join("");
5419
- return `<${node.name ?? ""}${attrs}>${children}</${node.name ?? ""}>`;
5420
- }
5421
- function collectText(node) {
5422
- if (node.type === "text") return node.data ?? "";
5423
- return (node.children ?? []).map(collectText).join("");
6741
+ };
5424
6742
  }
5425
6743
  function resolvePageScopeId$1(scopeId) {
5426
6744
  if (!scopeId) return null;
@@ -5442,7 +6760,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
5442
6760
  this.interactions?.assertActive?.();
5443
6761
  }
5444
6762
  query(selector) {
5445
- const nodes = querySelectorAll(this.node, selector);
6763
+ const nodes = (this.interactions?.projectionOnly ? querySelectorAll : queryInspectionSelectorAll)(this.node, selector);
5446
6764
  const scope = this.node.attribs?.["data-sim-scope"];
5447
6765
  if (!scope || !this.interactions) return nodes;
5448
6766
  return nodes.filter((node) => {
@@ -5461,7 +6779,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
5461
6779
  }
5462
6780
  async getElementsByXpath(expression) {
5463
6781
  this.assertActive();
5464
- return queryXPathElements(this.node, expression).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
6782
+ return (this.interactions?.projectionOnly ? queryXPathElements : queryInspectionXPathElements)(this.node, expression).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
5465
6783
  }
5466
6784
  async attr(name) {
5467
6785
  this.assertActive();
@@ -5499,7 +6817,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
5499
6817
  }
5500
6818
  async text() {
5501
6819
  this.assertActive();
5502
- return collectText(this.node);
6820
+ return collectNodeText$1(this.node);
5503
6821
  }
5504
6822
  async tagName() {
5505
6823
  this.assertActive();
@@ -5511,10 +6829,23 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
5511
6829
  const normalizedEventName = eventName.trim();
5512
6830
  if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
5513
6831
  let handlerResults;
5514
- const nativeHandled = this.interactions.dispatchNativeEvent?.(this.node, normalizedEventName, event, normalizedEventName === "tap" ? (result) => {
5515
- handlerResults ??= [];
5516
- handlerResults.push(result);
5517
- } : 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
+ }
5518
6849
  if (normalizedEventName === "tap" && nativeHandled) return handlerResults ? (await Promise.all(handlerResults))[0] : void 0;
5519
6850
  const binding = resolveMiniProgramEventBinding(this.node.attribs, normalizedEventName);
5520
6851
  if (!binding?.method) {
@@ -5526,6 +6857,20 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
5526
6857
  async tap(event = {}) {
5527
6858
  return await this.trigger("tap", event);
5528
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
+ }
5529
6874
  async input(value, event = {}) {
5530
6875
  return await this.trigger("input", {
5531
6876
  ...event,
@@ -5578,16 +6923,20 @@ function isMustacheOnly$1(value) {
5578
6923
  return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
5579
6924
  }
5580
6925
  function visitDom(node, visitor) {
5581
- visitor(node);
6926
+ if (visitor(node) === false) return;
5582
6927
  for (const child of node.children ?? []) visitDom(child, visitor);
5583
6928
  }
5584
6929
  function interpolateDomTree(root, data) {
5585
6930
  visitDom(root, (node) => {
6931
+ const richText = node.type === "tag" && node.name === "rich-text";
6932
+ if (richText) node.children = [];
5586
6933
  if (typeof node.data === "string") node.data = interpolateTemplateText(node.data, data);
5587
6934
  if (node.attribs) {
5588
6935
  let dataset;
5589
6936
  for (const [key, value] of Object.entries(node.attribs)) {
5590
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);
5591
6940
  node.attribs[key] = String(resolvedValue ?? "");
5592
6941
  if (isDatasetAttribute(key)) {
5593
6942
  dataset ??= {};
@@ -5596,6 +6945,7 @@ function interpolateDomTree(root, data) {
5596
6945
  }
5597
6946
  node.dataset = dataset;
5598
6947
  }
6948
+ if (richText) return false;
5599
6949
  });
5600
6950
  }
5601
6951
  function escapeText$1(text) {
@@ -5617,11 +6967,12 @@ function renderPageTree(project, page) {
5617
6967
  const templateSource = project.artifactSource.readText(templatePath);
5618
6968
  if (templateSource == null) throw new Error(`Missing template in headless runtime: ${templatePath}`);
5619
6969
  const document = parseDocument(`<page>${templateSource}</page>`, {
5620
- xmlMode: false,
6970
+ xmlMode: true,
5621
6971
  decodeEntities: false,
5622
6972
  recognizeSelfClosing: true
5623
6973
  });
5624
6974
  interpolateDomTree(document, page.data);
6975
+ linkRenderedParents(document);
5625
6976
  return {
5626
6977
  root: document,
5627
6978
  wxml: serializeDomNode$1((document.children ?? [])[0] ?? document)
@@ -5792,7 +7143,7 @@ function getNativeScrollOffset(page, node) {
5792
7143
  };
5793
7144
  }
5794
7145
  /** 原生交互更新宿主状态,导航仍交给统一 wx 路由入口。 */
5795
- function dispatchNativeNodeEvent(page, node, eventName, event, wx, resolveMethod, onHandlerResult) {
7146
+ function dispatchNativeNodeEvent(page, node, eventName, event, wx, resolveMethod, onHandlerResult, resolveComponent) {
5796
7147
  if (eventName === "scroll" && node.name === "scroll-view") {
5797
7148
  const detail = event.detail;
5798
7149
  const state = pageScrollViews.get(page)?.get(nodeKey(node));
@@ -5806,30 +7157,42 @@ function dispatchNativeNodeEvent(page, node, eventName, event, wx, resolveMethod
5806
7157
  if (eventName !== "tap") return false;
5807
7158
  let current = node;
5808
7159
  let navigator;
7160
+ let button;
7161
+ const origin = getNativeNodeOwner(node)?.target ?? node;
5809
7162
  let handlers;
5810
7163
  let handled = false;
5811
- while (current) {
5812
- if (!navigator && current.name === "navigator") navigator = current;
5813
- const binding = resolveMiniProgramEventBinding(current.attribs, "tap");
5814
- if (binding?.method) {
5815
- 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);
5816
7167
  handlers ??= [];
5817
7168
  handlers.push({
5818
- node: current,
7169
+ event: createMiniProgramEventPayload(target, "tap", event, origin),
5819
7170
  call
5820
7171
  });
5821
7172
  handled = true;
5822
7173
  }
5823
- 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)) {
5824
7179
  handled = true;
5825
7180
  break;
5826
7181
  }
5827
7182
  current = current.parent;
5828
7183
  }
7184
+ const submit = button ? prepareNativeFormSubmit(button, `page:${page.route}`, event, resolveMethod, resolveComponent) : void 0;
5829
7185
  if (handlers) for (const handler of handlers) {
5830
- const result = handler.call(createMiniProgramEventPayload(handler.node, "tap", event, node));
7186
+ const result = handler.call(handler.event);
5831
7187
  onHandlerResult?.(result);
5832
7188
  }
7189
+ if (submit) {
7190
+ handled = true;
7191
+ if (submit.call) {
7192
+ const result = submit.call(submit.event);
7193
+ onHandlerResult?.(result);
7194
+ }
7195
+ }
5833
7196
  if (!navigator) return handled;
5834
7197
  const openType = navigator.attribs?.["open-type"] ?? "navigate";
5835
7198
  const url = navigator.attribs?.url ?? "";
@@ -6614,6 +7977,64 @@ function createHeadlessMediaQueryObserver(driver, onDisconnect) {
6614
7977
  };
6615
7978
  }
6616
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
6617
8038
  //#region src/view/videoContext.ts
6618
8039
  function createEventPayload(node, eventName, detail) {
6619
8040
  const dataset = collectNodeDataset(node);
@@ -6759,6 +8180,7 @@ var BrowserHeadlessSession = class {
6759
8180
  appInstance = null;
6760
8181
  appLifecycle = new HeadlessAppLifecycle();
6761
8182
  moduleLoader;
8183
+ templateRegistration;
6762
8184
  onRender;
6763
8185
  registries;
6764
8186
  currentPageInstance = null;
@@ -6766,9 +8188,14 @@ var BrowserHeadlessSession = class {
6766
8188
  componentCache = /* @__PURE__ */ new Map();
6767
8189
  componentScopes = /* @__PURE__ */ new Map();
6768
8190
  selectorQueryScopeSnapshots = /* @__PURE__ */ new WeakMap();
6769
- renderRequestPending = false;
6770
- renderInProgress = false;
6771
- 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
+ });
6772
8199
  tabBarRoutes;
6773
8200
  tabPages = /* @__PURE__ */ new Map();
6774
8201
  tabBarItems = /* @__PURE__ */ new Map();
@@ -6795,6 +8222,7 @@ var BrowserHeadlessSession = class {
6795
8222
  });
6796
8223
  this.onRender = options.onRender;
6797
8224
  this.project = options.project ?? createBrowserProject(options.files);
8225
+ this.templateRegistration = createTemplateRegistration(this.project.artifactSource, this.project.miniprogramRootPath, options.compiledTemplatePaths);
6798
8226
  this.registries = createHostRegistries();
6799
8227
  const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
6800
8228
  this.tabBarRoutes = /* @__PURE__ */ new Set();
@@ -6844,7 +8272,7 @@ var BrowserHeadlessSession = class {
6844
8272
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
6845
8273
  getNetworkType: () => this.wxState.getNetworkType(),
6846
8274
  navigateBack: (option) => this.navigateBack(option?.delta),
6847
- navigateTo: (option) => this.navigateTo(option.url),
8275
+ navigateTo: (option) => this.routeEvents.navigateTo(() => this.navigateTo(option.url), option),
6848
8276
  pageScrollTo: (option) => this.pageScrollTo(option),
6849
8277
  openDocument: (option) => this.wxState.openDocument(option),
6850
8278
  clearStorageSync: () => this.wxState.clearStorageSync(),
@@ -6926,8 +8354,7 @@ var BrowserHeadlessSession = class {
6926
8354
  failure = { error };
6927
8355
  }
6928
8356
  this.canvasContexts.clear();
6929
- this.renderRequestCallbacks.length = 0;
6930
- this.renderRequestPending = false;
8357
+ this.renderQueue.close();
6931
8358
  this.appLifecycle.close();
6932
8359
  this.routeEvents.close();
6933
8360
  this.wxState.close();
@@ -6949,6 +8376,23 @@ var BrowserHeadlessSession = class {
6949
8376
  this.assertActive();
6950
8377
  return this.pages.slice();
6951
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
+ }
6952
8396
  getCurrentPageNavigationBarTitle() {
6953
8397
  return this.currentPageInstance?.__navigationBarTitle__ ?? null;
6954
8398
  }
@@ -7219,19 +8663,19 @@ var BrowserHeadlessSession = class {
7219
8663
  return this.getComponentScopeId(component);
7220
8664
  }
7221
8665
  selectComponent(selector) {
7222
- this.renderCurrentPage();
8666
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
7223
8667
  return this.selectComponentsWithin(null, selector)[0] ?? null;
7224
8668
  }
7225
8669
  selectAllComponents(selector) {
7226
- this.renderCurrentPage();
8670
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
7227
8671
  return this.selectComponentsWithin(null, selector);
7228
8672
  }
7229
8673
  selectComponentWithin(scopeId, selector) {
7230
- this.renderCurrentPage();
8674
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
7231
8675
  return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
7232
8676
  }
7233
8677
  selectAllComponentsWithin(scopeId, selector) {
7234
- this.renderCurrentPage();
8678
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
7235
8679
  return this.selectComponentsWithin(scopeId, selector);
7236
8680
  }
7237
8681
  selectOwnerComponent(scopeId) {
@@ -7267,6 +8711,7 @@ var BrowserHeadlessSession = class {
7267
8711
  componentCache: this.componentCache,
7268
8712
  componentScopes: this.componentScopes,
7269
8713
  files: this.files,
8714
+ templateSource: this.templateRegistration.artifactSource,
7270
8715
  moduleLoader: this.moduleLoader,
7271
8716
  project: this.project,
7272
8717
  session: {
@@ -7295,35 +8740,18 @@ var BrowserHeadlessSession = class {
7295
8740
  dispatchNativeNodeEvent(node, eventName, event, onHandlerResult) {
7296
8741
  const current = this.requireCurrentPage("dispatchNativeNodeEvent()");
7297
8742
  if (eventName === "tap") this.renderCurrentPage();
7298
- 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
+ });
7299
8751
  }
7300
8752
  requestRender(callback) {
7301
8753
  this.assertActive();
7302
- if (callback) this.renderRequestCallbacks.push(callback);
7303
- if (this.renderRequestPending) return;
7304
- this.renderRequestPending = true;
7305
- if (this.renderInProgress) return;
7306
- Promise.resolve().then(async () => {
7307
- if (this.kernel.isClosed) return;
7308
- this.renderRequestPending = false;
7309
- this.renderInProgress = true;
7310
- const callbacks = this.renderRequestCallbacks.splice(0);
7311
- try {
7312
- if (this.currentPageInstance) this.renderCurrentPage();
7313
- const rendered = this.onRender?.();
7314
- if (rendered && typeof rendered.then === "function") await rendered;
7315
- for (const cb of callbacks) {
7316
- if (this.kernel.isClosed) break;
7317
- cb();
7318
- }
7319
- } finally {
7320
- this.renderInProgress = false;
7321
- if (this.renderRequestPending && !this.kernel.isClosed) {
7322
- this.renderRequestPending = false;
7323
- this.requestRender();
7324
- }
7325
- }
7326
- });
8754
+ this.renderQueue.request(callback);
7327
8755
  }
7328
8756
  callScopeMethod(scopeId, methodName, event) {
7329
8757
  const current = this.requireCurrentPage(`scope method "${methodName}"`);
@@ -7547,6 +8975,7 @@ var BrowserHeadlessSession = class {
7547
8975
  componentCache: this.componentCache,
7548
8976
  componentScopes: this.componentScopes,
7549
8977
  files: this.files,
8978
+ templateSource: this.templateRegistration.artifactSource,
7550
8979
  moduleLoader: this.moduleLoader,
7551
8980
  project: this.project,
7552
8981
  session: {
@@ -7647,6 +9076,7 @@ var BrowserHeadlessSession = class {
7647
9076
  componentCache: this.componentCache,
7648
9077
  componentScopes: this.componentScopes,
7649
9078
  files: this.files,
9079
+ templateSource: this.templateRegistration.artifactSource,
7650
9080
  moduleLoader: this.moduleLoader,
7651
9081
  project: this.project,
7652
9082
  session: {
@@ -8149,7 +9579,7 @@ function resolveComponentAttributeValue(value, scope) {
8149
9579
  }
8150
9580
  return interpolateTemplate(value, wxsScopeData(scope));
8151
9581
  }
8152
- function applyNodeBindings(node, scope) {
9582
+ function applyNodeBindings(node, scope, richText = false) {
8153
9583
  if (!isTagNode(node)) {
8154
9584
  if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplateText(node.data, wxsScopeData(scope));
8155
9585
  return;
@@ -8157,6 +9587,7 @@ function applyNodeBindings(node, scope) {
8157
9587
  node.attribs ??= {};
8158
9588
  node.attribs["data-sim-scope"] = scope.getScopeId();
8159
9589
  for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
9590
+ if (richText) node.children = [];
8160
9591
  let dataset;
8161
9592
  for (const [key, value] of Object.entries({ ...node.attribs })) {
8162
9593
  if (EVENT_BINDING_ATTRS.includes(key)) {
@@ -8164,6 +9595,8 @@ function applyNodeBindings(node, scope) {
8164
9595
  continue;
8165
9596
  }
8166
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);
8167
9600
  node.attribs[key] = String(resolvedValue ?? "");
8168
9601
  if (isDatasetAttribute(key)) {
8169
9602
  dataset ??= {};
@@ -8190,8 +9623,7 @@ function createLoopScope(scope, itemName, indexName, item, index) {
8190
9623
  //#endregion
8191
9624
  //#region src/runtime/render/component.ts
8192
9625
  function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias, genericComponentBasePath) {
8193
- const usingComponents = resolveUsingComponents(context, ownerJsonPath, ownerFilePath);
8194
- const componentBasePath = genericComponentBasePath ?? usingComponents.get(alias);
9626
+ const componentBasePath = genericComponentBasePath ?? resolveUsingComponent(context, ownerJsonPath, ownerFilePath, alias);
8195
9627
  if (!componentBasePath) return null;
8196
9628
  const filePath = `${componentBasePath}.js`;
8197
9629
  const templatePath = `${componentBasePath}.wxml`;
@@ -8212,30 +9644,25 @@ function readComponentConfig(artifactSource, jsonPath) {
8212
9644
  return {};
8213
9645
  }
8214
9646
  }
8215
- function resolveUsingComponents(context, ownerJsonPath, ownerFilePath) {
9647
+ function resolveUsingComponent(context, ownerJsonPath, ownerFilePath, alias) {
8216
9648
  try {
8217
9649
  const usingComponents = readComponentConfig(context.artifactSource, ownerJsonPath).usingComponents;
8218
- if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
8219
- const resolved = /* @__PURE__ */ new Map();
8220
- for (const [alias, rawPath] of Object.entries(usingComponents)) {
8221
- if (typeof rawPath !== "string") continue;
8222
- const basePath = resolvePluginRequest(context.project.plugins, rawPath, "publicComponent")?.resourcePath ?? resolveMiniProgramComponent(ownerFilePath, rawPath, context.project.miniprogramRootPath, (candidate) => context.artifactSource.readText(candidate) !== void 0);
8223
- resolved.set(alias, basePath.replace(LEADING_SLASH_RE$2, ""));
8224
- }
8225
- 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, "");
8226
9654
  } catch {
8227
- return /* @__PURE__ */ new Map();
9655
+ return;
8228
9656
  }
8229
9657
  }
8230
9658
  function resolveComponentGenerics(context, hostNode, ownerJsonPath, ownerFilePath, componentFilePath, ownerGenerics) {
8231
9659
  const componentJsonPath = path.resolve(context.project.miniprogramRootPath, `${componentFilePath.replace(JS_FILE_RE, "")}.json`);
8232
9660
  const componentGenerics = readComponentConfig(context.artifactSource, componentJsonPath).componentGenerics;
8233
9661
  if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return;
8234
- const ownerComponents = resolveUsingComponents(context, ownerJsonPath, ownerFilePath);
8235
9662
  const resolved = /* @__PURE__ */ new Map();
8236
9663
  for (const [genericName, definition] of Object.entries(componentGenerics)) {
8237
9664
  const selectedAlias = hostNode.attribs?.[`generic:${genericName}`];
8238
- 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;
8239
9666
  if (selectedPath) {
8240
9667
  resolved.set(genericName, selectedPath);
8241
9668
  continue;
@@ -8247,67 +9674,6 @@ function resolveComponentGenerics(context, hostNode, ownerJsonPath, ownerFilePat
8247
9674
  }
8248
9675
  return resolved.size > 0 ? resolved : void 0;
8249
9676
  }
8250
- function collectComponentEventBindings(hostNode) {
8251
- return collectMiniProgramEventBindings(hostNode.attribs);
8252
- }
8253
- function buildComponentTrigger(componentScopeId, context, hostNode) {
8254
- const hostDataset = collectDataset(hostNode);
8255
- const hostId = hostNode.attribs?.id ?? "";
8256
- return (instance, eventName, detail, triggerOptions) => {
8257
- const originScope = context.componentScopes.get(componentScopeId);
8258
- const interactionMark = instance.__lastInteractionEvent__?.mark;
8259
- const target = {
8260
- dataset: originScope?.dataset ?? hostDataset,
8261
- id: originScope?.hostId ?? hostId
8262
- };
8263
- let currentScopeId = componentScopeId;
8264
- while (currentScopeId) {
8265
- const currentScope = context.componentScopes.get(currentScopeId);
8266
- const binding = currentScope?.eventBindings?.get(eventName);
8267
- const listenerScope = currentScope?.listenerScopeId ? context.componentScopes.get(currentScope.listenerScopeId) : null;
8268
- const handler = binding && listenerScope ? listenerScope.getMethod(binding.method) : void 0;
8269
- if (handler) handler({
8270
- bubbles: triggerOptions?.bubbles ?? false,
8271
- capturePhase: false,
8272
- composed: triggerOptions?.composed ?? false,
8273
- currentTarget: {
8274
- dataset: currentScope?.dataset ?? hostDataset,
8275
- id: currentScope?.hostId ?? hostId
8276
- },
8277
- detail,
8278
- mark: interactionMark,
8279
- target,
8280
- type: eventName
8281
- });
8282
- if (binding?.stopAfter) break;
8283
- if (!triggerOptions?.bubbles || !triggerOptions?.composed) break;
8284
- currentScopeId = currentScope?.ownerScopeId;
8285
- }
8286
- };
8287
- }
8288
- function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
8289
- const changedRootKeys = [];
8290
- const previousProperties = {};
8291
- for (const [key, value] of Object.entries(nextProperties)) {
8292
- const nextValue = normalizeComponentPropertyValue(definition, key, value);
8293
- const bindingExpression = bindingExpressions[key];
8294
- const bindingAffected = !!bindingExpression && changedPageKeys.some((changedKey) => {
8295
- return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
8296
- });
8297
- const previousSnapshot = instance.__propertySnapshots?.[key];
8298
- if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
8299
- previousProperties[key] = instance.properties[key];
8300
- const deliveredValue = cloneValue(nextValue);
8301
- instance.properties[key] = deliveredValue;
8302
- if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = deliveredValue;
8303
- changedRootKeys.push(key);
8304
- }
8305
- instance.__propertySnapshots ??= {};
8306
- instance.__propertySnapshots[key] = cloneValue(nextValue);
8307
- }
8308
- if (changedRootKeys.length === 0) return;
8309
- runComponentObservers(definition, instance, changedRootKeys, previousProperties);
8310
- }
8311
9677
  function createComponentScope(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots) {
8312
9678
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
8313
9679
  return {
@@ -8315,7 +9681,7 @@ function createComponentScope(clonedNode, scope, componentScopeId, componentInst
8315
9681
  classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
8316
9682
  data: { ...componentInstance.data },
8317
9683
  dataset: collectDataset(clonedNode, wxsScopeData(scope)),
8318
- eventBindings: collectComponentEventBindings(clonedNode),
9684
+ ...bindComponentEventHost(clonedNode),
8319
9685
  getMethod: (methodName) => {
8320
9686
  const method = componentInstance?.[methodName];
8321
9687
  return typeof method === "function" ? method.bind(componentInstance) : void 0;
@@ -8323,6 +9689,7 @@ function createComponentScope(clonedNode, scope, componentScopeId, componentInst
8323
9689
  getScopeId: () => componentScopeId,
8324
9690
  genericComponents,
8325
9691
  hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
9692
+ hostNode: clonedNode,
8326
9693
  id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
8327
9694
  listenerScopeId: scope.getScopeId(),
8328
9695
  ownerScopeId,
@@ -8345,13 +9712,13 @@ function resolveComponentProperties(clonedNode, scope, definition) {
8345
9712
  bindingExpressions
8346
9713
  };
8347
9714
  }
8348
- function createRuntimeComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId, beforeCreated) {
8349
- 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;
8350
- const componentInstance = createComponentInstance({
9715
+ function createRuntimeComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, renderTemplate, bindEventsBeforeProperties = false) {
9716
+ const instanceOptions = {
8351
9717
  definition: componentEntry.definition,
8352
- requestRender: (callback) => context.session.requestRender(callback),
8353
- triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
8354
- });
9718
+ requestRender: (callback) => context.session.requestRender(callback)
9719
+ };
9720
+ const componentInstance = createComponentInstance(instanceOptions);
9721
+ bindAttachmentBindingScope(componentInstance, context);
8355
9722
  setSelectorQueryScopeId(componentInstance, componentScopeId);
8356
9723
  componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE, "");
8357
9724
  componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
@@ -8359,19 +9726,29 @@ function createRuntimeComponentInstance(componentScopeId, context, clonedNode, c
8359
9726
  componentInstance.createSelectorQuery = () => context.moduleLoader.wx.createSelectorQuery().in(componentInstance);
8360
9727
  componentInstance.selectComponent = (selector) => resolveNativeComponentSelection(context.session.selectComponentWithin(componentScopeId, selector));
8361
9728
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector).map(resolveNativeComponentSelection);
8362
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
9729
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? resolveNativeComponentSelection(context.componentCache.get(ownerScopeId)) : null;
9730
+ beginComponentConstruction(context.componentCache, componentScopeId, componentInstance);
8363
9731
  context.componentCache.set(componentScopeId, componentInstance);
8364
- beforeCreated?.(componentInstance);
8365
- runComponentLifecycle(componentInstance, "created");
8366
- componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
8367
- syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, []);
8368
- return componentInstance;
9732
+ try {
9733
+ renderTemplate?.(componentInstance, "defaults");
9734
+ runComponentLifecycle(componentInstance, "created");
9735
+ if (bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
9736
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
9737
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, {}, [], renderTemplate);
9738
+ if (!bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
9739
+ return componentInstance;
9740
+ } catch (error) {
9741
+ discardComponentConstruction(context.componentCache, context.componentScopes, componentScopeId);
9742
+ throw error;
9743
+ } finally {
9744
+ finishComponentConstruction(context.componentCache, componentInstance);
9745
+ }
8369
9746
  }
8370
- function renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
9747
+ function renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, renderPass) {
8371
9748
  const componentDocument = parseTemplateDocument(readTemplateSource(context.artifactSource, componentEntry.absoluteTemplatePath));
8372
9749
  const componentRoot = (componentDocument.children ?? [])[0] ?? componentDocument;
8373
9750
  const templateRenderState = prepareTemplateRenderState(context.artifactSource, componentRoot, componentEntry.absoluteTemplatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
8374
- return renderNodeTree(componentRoot, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, seenComponentScopes, templateRenderState);
9751
+ return renderNodeTree(componentRoot, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, renderPass, templateRenderState, componentScope.hostNode);
8375
9752
  }
8376
9753
  //#endregion
8377
9754
  //#region src/runtime/render/index.ts
@@ -8385,24 +9762,33 @@ function expandNodeByFor(node, scope) {
8385
9762
  const items = resolveLoopEntries(resolveRawValueByPath(wxsScopeData(scope), forExpression));
8386
9763
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
8387
9764
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
9765
+ const key = node.attribs?.["wx:key"]?.trim();
9766
+ const keyOccurrences = key ? /* @__PURE__ */ new Map() : void 0;
8388
9767
  return items.map(([index, item]) => ({
8389
9768
  node: cloneNode(node),
8390
9769
  scope: createLoopScope(scope, itemName, indexName, item, index),
8391
- instanceSuffix: `:for-${index}`
9770
+ instanceSuffix: resolveLoopInstanceSuffix(item, index, key, keyOccurrences)
8392
9771
  }));
8393
9772
  }
8394
- function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
8395
- return expandNodeByFor(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes, templateRenderState));
9773
+ function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
9774
+ const nodes = [];
9775
+ if (isRenderPassStale(renderPass)) return nodes;
9776
+ for (const { node: expandedNode, scope: expandedScope, instanceSuffix } of expandNodeByFor(node, scope)) {
9777
+ if (isRenderPassStale(renderPass)) break;
9778
+ nodes.push(renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, renderPass, templateRenderState, parent));
9779
+ }
9780
+ return nodes;
8396
9781
  }
8397
- function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
9782
+ function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
8398
9783
  const renderedChildren = [];
8399
9784
  for (const { node: child, index } of selectConditionalChildren(children, (node) => evaluateConditionalBranch(node, scope))) {
9785
+ if (isRenderPassStale(renderPass)) break;
8400
9786
  if (!isTagNode(child)) {
8401
- renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
9787
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, renderPass, templateRenderState, parent));
8402
9788
  continue;
8403
9789
  }
8404
9790
  if (isTemplateDefinition(child) || child.name === "import" || child.name === "wxs") continue;
8405
- renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
9791
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, renderPass, templateRenderState, parent));
8406
9792
  }
8407
9793
  return renderedChildren;
8408
9794
  }
@@ -8434,22 +9820,38 @@ function collectComponentSlots(componentNode, scope, ownerJsonPath, ownerFilePat
8434
9820
  }
8435
9821
  return slots;
8436
9822
  }
8437
- function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
9823
+ function reconcileSlotDeclarations(context, renderPass) {
9824
+ for (const [entries, { parent, scopeId }] of renderPass.slotDeclarations) {
9825
+ if (isRenderPassStale(renderPass)) return;
9826
+ if (isComponentConstructing(context.componentCache.get(scopeId))) continue;
9827
+ for (const { index } of selectConditionalChildren(entries.map((entry) => entry.node), (node, index) => evaluateConditionalBranch(node, entries[index].scope))) {
9828
+ if (isRenderPassStale(renderPass)) return;
9829
+ const entry = entries[index];
9830
+ if (renderPass.renderedSlots.has(entry)) continue;
9831
+ const nodes = renderNodeVariants(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, renderPass, entry.templateRenderState, parent);
9832
+ renderPass.renderedSlots.set(entry, nodes);
9833
+ renderPass.hasUnprojectedSlots ||= nodes.length > 0;
9834
+ }
9835
+ }
9836
+ }
9837
+ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
9838
+ if (isRenderPassStale(renderPass)) return node;
8438
9839
  if (scope.wxs !== templateRenderState.wxsModules) scope = {
8439
9840
  ...scope,
8440
9841
  wxs: templateRenderState.wxsModules
8441
9842
  };
8442
9843
  const clonedNode = cloneNode(node);
9844
+ registerComponentEventNode(clonedNode, scope, parent);
8443
9845
  if (!isTagNode(clonedNode)) {
8444
9846
  applyNodeBindings(clonedNode, scope);
8445
9847
  return clonedNode;
8446
9848
  }
8447
- if (isTemplateDefinition(clonedNode)) return {
8448
- type: "tag",
8449
- name: "block",
8450
- attribs: {},
8451
- children: []
8452
- };
9849
+ if (isTemplateDefinition(clonedNode)) {
9850
+ clonedNode.name = "block";
9851
+ clonedNode.attribs = {};
9852
+ clonedNode.children = [];
9853
+ return clonedNode;
9854
+ }
8453
9855
  const templateName = resolveTemplateCall(clonedNode, wxsScopeData(scope));
8454
9856
  if (templateName) {
8455
9857
  const definition = templateRenderState.definitions.get(templateName);
@@ -8458,39 +9860,42 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
8458
9860
  data: resolveTemplateData(clonedNode, wxsScopeData(scope)),
8459
9861
  wxs: definition && templateRenderState.definitionWxsScopes?.get(definition)
8460
9862
  };
8461
- const children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, seenComponentScopes, {
9863
+ clonedNode.name = "block";
9864
+ clonedNode.attribs = {
9865
+ "data-sim-node": instancePath,
9866
+ "data-sim-scope": scope.getScopeId()
9867
+ };
9868
+ clonedNode.children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, renderPass, {
8462
9869
  definitions: templateRenderState.definitionScopes?.get(definition) ?? templateRenderState.definitions,
8463
9870
  definitionScopes: templateRenderState.definitionScopes,
8464
9871
  definitionWxsScopes: templateRenderState.definitionWxsScopes,
8465
9872
  wxsModules: templateScope.wxs,
8466
9873
  stack: [...templateRenderState.stack, templateName]
8467
- }) : [];
8468
- return {
8469
- type: "tag",
8470
- name: "block",
8471
- attribs: {
8472
- "data-sim-node": instancePath,
8473
- "data-sim-scope": scope.getScopeId()
8474
- },
8475
- children
8476
- };
9874
+ }, clonedNode) : [];
9875
+ return clonedNode;
8477
9876
  }
8478
9877
  if (clonedNode.name === "slot") {
8479
9878
  const slotName = clonedNode.attribs?.name?.trim() || "default";
8480
9879
  const projected = scope.slots?.get(slotName) ?? [];
8481
- const children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch(node, projected[index].scope)).flatMap(({ index }) => {
8482
- const entry = projected[index];
8483
- return renderNodeVariants(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, seenComponentScopes, entry.templateRenderState);
8484
- }) : renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, seenComponentScopes, templateRenderState);
8485
- return {
8486
- type: "tag",
8487
- name: "block",
8488
- attribs: {
8489
- "data-sim-node": instancePath,
8490
- "data-sim-scope": scope.getScopeId()
8491
- },
8492
- children
9880
+ const fallbackChildren = clonedNode.children ?? [];
9881
+ bindComponentEventHost(clonedNode);
9882
+ clonedNode.name = "block";
9883
+ clonedNode.attribs = {
9884
+ "data-sim-node": instancePath,
9885
+ "data-sim-scope": scope.getScopeId()
8493
9886
  };
9887
+ const slotOwner = scope.getScopeId();
9888
+ if (projected.length && slotOwner && isComponentConstructing(context.componentCache.get(slotOwner))) {
9889
+ clonedNode.children = [];
9890
+ return clonedNode;
9891
+ }
9892
+ clonedNode.children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch(node, projected[index].scope)).flatMap(({ index }) => {
9893
+ const entry = projected[index];
9894
+ const nodes = renderNodeVariants(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, renderPass, entry.templateRenderState, clonedNode);
9895
+ renderPass.renderedSlots.set(entry, nodes);
9896
+ return nodes;
9897
+ }) : renderChildren(fallbackChildren, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, renderPass, templateRenderState, clonedNode);
9898
+ return clonedNode;
8494
9899
  }
8495
9900
  const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name, scope.genericComponents?.get(clonedNode.name));
8496
9901
  if (componentEntry) {
@@ -8499,19 +9904,31 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
8499
9904
  const { nextProperties, bindingExpressions } = resolveComponentProperties(clonedNode, scope, componentEntry.definition);
8500
9905
  const genericComponents = resolveComponentGenerics(context, clonedNode, ownerJsonPath, ownerFilePath, componentEntry.filePath, scope.genericComponents);
8501
9906
  const slots = collectComponentSlots(clonedNode, scope, ownerJsonPath, ownerFilePath, componentScopeId, templateRenderState);
9907
+ registerSlotDeclarations(renderPass, slots, clonedNode, componentScopeId);
9908
+ applyNodeBindings(clonedNode, scope);
9909
+ const reconcilePrivateTemplate = (instance, phase) => {
9910
+ let bindingPass;
9911
+ do {
9912
+ const bindingScope = createComponentScope(clonedNode, scope, componentScopeId, instance, genericComponents, slots);
9913
+ context.componentScopes.set(componentScopeId, bindingScope);
9914
+ bindingPass = createRenderPass(phase === "properties", renderPass);
9915
+ renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, bindingScope, componentScopeId, bindingPass);
9916
+ reconcileSlotDeclarations(context, bindingPass);
9917
+ } while (isRenderPassStale(bindingPass));
9918
+ };
8502
9919
  let componentInstance = context.componentCache.get(componentScopeId);
8503
- if (!componentInstance) componentInstance = createRuntimeComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId, (instance) => {
8504
- const initialScope = createComponentScope(clonedNode, scope, componentScopeId, instance, genericComponents, slots);
8505
- context.componentScopes.set(componentScopeId, initialScope);
8506
- renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, initialScope, componentScopeId, /* @__PURE__ */ new Set());
8507
- });
8508
- else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
8509
- seenComponentScopes.add(componentScopeId);
9920
+ if (!componentInstance) componentInstance = createRuntimeComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, reconcilePrivateTemplate, renderPass.propertyUpdate);
9921
+ else {
9922
+ context.componentScopes.set(componentScopeId, createComponentScope(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots));
9923
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys, reconcilePrivateTemplate);
9924
+ }
9925
+ if (isRenderPassStale(renderPass)) return clonedNode;
9926
+ renderPass.seenComponentScopes.add(componentScopeId);
8510
9927
  const componentScope = createComponentScope(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots);
8511
9928
  context.componentScopes.set(componentScopeId, componentScope);
8512
- const renderedComponentRoot = renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes);
9929
+ const renderedComponentRoot = renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, renderPass);
9930
+ mergeComponentEventRoot(renderedComponentRoot, clonedNode);
8513
9931
  if (renderedComponentRoot.attribs) {
8514
- applyNodeBindings(clonedNode, scope);
8515
9932
  renderedComponentRoot.attribs = {
8516
9933
  ...clonedNode.attribs,
8517
9934
  ...renderedComponentRoot.attribs
@@ -8524,173 +9941,105 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
8524
9941
  renderedComponentRoot.attribs["data-sim-node"] = instancePath;
8525
9942
  renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
8526
9943
  }
9944
+ renderPass.componentRoots.set(componentScopeId, renderedComponentRoot);
8527
9945
  return renderedComponentRoot;
8528
9946
  }
8529
- applyNodeBindings(clonedNode, scope);
9947
+ const richText = clonedNode.name === "rich-text";
9948
+ applyNodeBindings(clonedNode, scope, richText);
8530
9949
  clonedNode.attribs["data-sim-node"] = instancePath;
8531
- clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes, templateRenderState);
9950
+ if (richText) return clonedNode;
9951
+ clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, renderPass, templateRenderState, clonedNode);
8532
9952
  return clonedNode;
8533
9953
  }
9954
+ function reconcileRuntimePageTree(context, page, bindingsOnly = false) {
9955
+ for (;;) {
9956
+ bindAttachmentBindingScope(context, page);
9957
+ if (page.__lastChangedKeys__) context.changedPageKeys = page.__lastChangedKeys__;
9958
+ const route = page.route.replace(LEADING_SLASH_RE$2, "");
9959
+ const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
9960
+ const templatePath = path.resolve(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
9961
+ const document = parseTemplateDocument(readTemplateSource(context.artifactSource, templatePath));
9962
+ const pageScopeId = `page:${route}`;
9963
+ const pageScope = {
9964
+ data: page.data,
9965
+ getMethod: (methodName) => {
9966
+ const method = page[methodName];
9967
+ return typeof method === "function" ? method.bind(page) : void 0;
9968
+ },
9969
+ getScopeId: () => pageScopeId,
9970
+ id: "page-root"
9971
+ };
9972
+ for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
9973
+ context.componentScopes.set(pageScopeId, pageScope);
9974
+ const renderPass = createPageRenderPass(page, context.componentCache);
9975
+ const root = (document.children ?? [])[0] ?? document;
9976
+ const templateRenderState = prepareTemplateRenderState(context.artifactSource, root, templatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
9977
+ const renderedRoot = renderNodeTree(root, pageScope, context, path.resolve(context.project.miniprogramRootPath, `${resourcePath}.json`), `${resourcePath}.js`, pageScopeId, renderPass, templateRenderState);
9978
+ const roots = [renderedRoot];
9979
+ if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree({
9980
+ type: "tag",
9981
+ name: "custom-tab-bar",
9982
+ attribs: {},
9983
+ children: []
9984
+ }, customTabBarHostScope(), context, path.resolve(context.project.miniprogramRootPath, "app.json"), "app.js", pageScopeId, renderPass, templateRenderState));
9985
+ reconcileSlotDeclarations(context, renderPass);
9986
+ if (isRenderPassStale(renderPass)) continue;
9987
+ markPageTreeConstructed(page, context.componentCache);
9988
+ const treeRoot = roots.length > 1 ? {
9989
+ type: "root",
9990
+ children: roots
9991
+ } : renderedRoot;
9992
+ linkRenderedParents(treeRoot);
9993
+ registerInspectionTrees(treeRoot, renderPass, context.componentScopes);
9994
+ if (bindingsOnly) return {
9995
+ root: treeRoot,
9996
+ roots
9997
+ };
9998
+ let bindingsRefreshed = false;
9999
+ const updateBindings = () => {
10000
+ bindingsRefreshed = true;
10001
+ if (hasPendingComponentConstruction(context.componentCache)) return;
10002
+ reconcileRuntimePageTree(context, page, true);
10003
+ };
10004
+ const pageAttached = attachComponentPage(page, updateBindings);
10005
+ if (bindingsRefreshed) continue;
10006
+ const pageAttaching = isComponentPageAttaching(page);
10007
+ const scopeIds = orderComponentAttachmentScopes(renderPass.seenComponentScopes, context.componentScopes);
10008
+ const instances = scopeIds.map((scopeId) => context.componentCache.get(scopeId));
10009
+ const attached = !pageAttaching && runWithAttachmentBindingUpdates(page, updateBindings, (scopes) => flushComponentAttachments(context.componentCache, scopes, (instance) => {
10010
+ runComponentLifecycle(instance, "attached");
10011
+ return bindingsRefreshed;
10012
+ }), scopeIds);
10013
+ if (attached === "restart") continue;
10014
+ const canFinalize = !pageAttaching && !hasPendingComponentAttachments(instances);
10015
+ const relationsChanged = canFinalize && reconcileRemovedComponents(context.componentCache, context.componentScopes, renderPass.seenComponentScopes, pageScopeId);
10016
+ if (pageAttached || attached || relationsChanged) continue;
10017
+ if (canFinalize && !isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
10018
+ if (canFinalize && !isPageBeforeReady(page) && flushComponentReady(instances, (instance) => {
10019
+ runComponentLifecycle(instance, "ready");
10020
+ if (instance !== context.componentCache.get(customTabBarScopeId(route))) instance.__definition__?.pageLifetimes?.show?.call(instance);
10021
+ })) continue;
10022
+ return {
10023
+ root: treeRoot,
10024
+ roots
10025
+ };
10026
+ }
10027
+ }
8534
10028
  function renderRuntimePageTree(context, page) {
8535
- const route = page.route.replace(LEADING_SLASH_RE$2, "");
8536
- const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
8537
- const templatePath = path.resolve(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
8538
- const document = parseTemplateDocument(readTemplateSource(context.artifactSource, templatePath));
8539
- const pageScopeId = `page:${route}`;
8540
- const pageScope = {
8541
- data: page.data,
8542
- getMethod: (methodName) => {
8543
- const method = page[methodName];
8544
- return typeof method === "function" ? method.bind(page) : void 0;
8545
- },
8546
- getScopeId: () => pageScopeId,
8547
- id: "page-root"
8548
- };
8549
- for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
8550
- context.componentScopes.set(pageScopeId, pageScope);
8551
- const seenComponentScopes = /* @__PURE__ */ new Set();
8552
- const root = (document.children ?? [])[0] ?? document;
8553
- const templateRenderState = prepareTemplateRenderState(context.artifactSource, root, templatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
8554
- const renderedRoot = renderNodeTree(root, pageScope, context, path.resolve(context.project.miniprogramRootPath, `${resourcePath}.json`), `${resourcePath}.js`, pageScopeId, seenComponentScopes, templateRenderState);
8555
- const roots = [renderedRoot];
8556
- if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree({
8557
- type: "tag",
8558
- name: "custom-tab-bar",
8559
- attribs: {},
8560
- children: []
8561
- }, customTabBarHostScope(), context, path.resolve(context.project.miniprogramRootPath, "app.json"), "app.js", pageScopeId, seenComponentScopes, templateRenderState));
8562
- const pageAttached = attachComponentPage(page);
8563
- const pageAttaching = isComponentPageAttaching(page);
8564
- const attached = !pageAttaching && flushComponentAttachments([...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId)), (instance) => runComponentLifecycle(instance, "attached"));
8565
- const removed = [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !seenComponentScopes.has(scopeId));
8566
- for (const [scopeId, instance] of removed) if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
8567
- else scheduleDiscardedComponentReady(context.componentCache, scopeId, instance);
8568
- const instances = [...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId));
8569
- const relationsChanged = !pageAttaching && !hasPendingComponentAttachments(instances) && syncComponentRelations(context.componentCache, seenComponentScopes, pageScopeId);
8570
- for (const [scopeId] of removed) {
8571
- context.componentCache.delete(scopeId);
8572
- context.componentScopes.delete(scopeId);
8573
- }
8574
- if (pageAttached || attached || relationsChanged) return renderRuntimePageTree(context, page);
8575
- if (!isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
8576
- if (!isPageBeforeReady(page) && flushComponentReady(instances, (instance) => {
8577
- runComponentLifecycle(instance, "ready");
8578
- if (instance !== context.componentCache.get(customTabBarScopeId(route))) instance.__definition__?.pageLifetimes?.show?.call(instance);
8579
- })) return renderRuntimePageTree(context, page);
8580
- const treeRoot = roots.length > 1 ? {
8581
- type: "root",
8582
- children: roots
8583
- } : renderedRoot;
8584
- linkRenderedParents(treeRoot);
10029
+ const { root, roots } = reconcileRuntimePageTree(context, page);
8585
10030
  return {
8586
- root: treeRoot,
10031
+ root,
8587
10032
  wxml: roots.map(serializeDomNode).join("")
8588
10033
  };
8589
10034
  }
8590
10035
  //#endregion
8591
10036
  //#region src/runtime/moduleLoader.ts
8592
- const ESM_IMPORT_LINE_RE = /^[ \t]*import[^\n]*$/gm;
8593
- const ESM_EXPORT_LIST_RE = /^[ \t]*export[ \t]*\{([^}\n]+)\}[ \t]*;?$/gm;
8594
- const ESM_EXPORT_DECLARATION_RE = /\bexport\s+(const|let|var|function|class)\s+([A-Za-z_$][\w$]*)/g;
8595
- const ESM_EXPORT_DEFAULT_DECLARATION_RE = /\bexport\s+default\s+(function|class)\s+([A-Za-z_$][\w$]*)/g;
8596
- function isImportWhitespace(value) {
8597
- return value === " " || value === " ";
8598
- }
8599
- function parseEsmImportLine(line) {
8600
- let statement = line.trim().slice(6).trim();
8601
- if (statement.endsWith(";")) statement = statement.slice(0, -1).trimEnd();
8602
- if (statement.startsWith("\"") || statement.startsWith("'")) {
8603
- const quote = statement[0];
8604
- if (statement.endsWith(quote) && statement.length > 1) return {
8605
- request: statement.slice(1, -1),
8606
- sideEffect: true
8607
- };
8608
- return;
8609
- }
8610
- let fromIndex = statement.indexOf("from");
8611
- while (fromIndex >= 0) {
8612
- if (isImportWhitespace(statement[fromIndex - 1]) && isImportWhitespace(statement[fromIndex + 4])) break;
8613
- fromIndex = statement.indexOf("from", fromIndex + 4);
8614
- }
8615
- if (fromIndex < 0) return;
8616
- const specifier = statement.slice(0, fromIndex).trim();
8617
- const requestLiteral = statement.slice(fromIndex + 4).trim();
8618
- const quote = requestLiteral[0];
8619
- if (!specifier || quote !== "\"" && quote !== "'" || requestLiteral.length < 2 || !requestLiteral.endsWith(quote)) return;
8620
- return {
8621
- request: requestLiteral.slice(1, -1),
8622
- sideEffect: false,
8623
- specifier
8624
- };
8625
- }
8626
- function createEsmImportBindings(specifier, request, index) {
8627
- const namespaceName = `__headlessEsmImport${index}`;
8628
- const statements = [`const ${namespaceName} = require(${JSON.stringify(request)});`];
8629
- const normalizedSpecifier = specifier.trim();
8630
- if (normalizedSpecifier.startsWith("{") && normalizedSpecifier.endsWith("}")) {
8631
- const entries = normalizedSpecifier.slice(1, -1).split(",");
8632
- for (const entry of entries) {
8633
- const [importedName, localName] = entry.trim().split(/\s+as\s+/);
8634
- if (!importedName) continue;
8635
- const bindingName = localName || importedName;
8636
- statements.push(`const ${bindingName} = ${namespaceName}[${JSON.stringify(importedName)}];`);
8637
- }
8638
- return statements.join("\n");
8639
- }
8640
- if (normalizedSpecifier.startsWith("* as ")) {
8641
- const bindingName = normalizedSpecifier.slice(5).trim();
8642
- statements.push(`const ${bindingName} = ${namespaceName};`);
8643
- return statements.join("\n");
8644
- }
8645
- const [defaultName, namedPart] = normalizedSpecifier.split(/\s*,\s*/, 2);
8646
- if (defaultName) statements.push(`const ${defaultName.trim()} = ${namespaceName}.default ?? ${namespaceName};`);
8647
- if (namedPart?.startsWith("{") && namedPart.endsWith("}")) statements.push(createEsmImportBindings(namedPart, request, index).split("\n").slice(1).join("\n"));
8648
- return statements.join("\n");
8649
- }
8650
- function transformEsmToCommonJs(source) {
8651
- if (!/^\s*(?:import|export)\b/m.test(source)) return source;
8652
- let importIndex = 0;
8653
- const exportedNames = [];
8654
- let transformed = source.replace(ESM_IMPORT_LINE_RE, (line) => {
8655
- const parsed = parseEsmImportLine(line);
8656
- if (!parsed) return line;
8657
- if (parsed.sideEffect) return `require(${JSON.stringify(parsed.request)});`;
8658
- return createEsmImportBindings(parsed.specifier, parsed.request, importIndex++);
8659
- });
8660
- transformed = transformed.replace(ESM_EXPORT_LIST_RE, (_match, entries) => {
8661
- for (const entry of entries.split(",")) {
8662
- const [local, exported] = entry.trim().split(/\s+as\s+/);
8663
- if (local) exportedNames.push({
8664
- exported: exported || local,
8665
- local
8666
- });
8667
- }
8668
- return "";
8669
- });
8670
- transformed = transformed.replace(ESM_EXPORT_DEFAULT_DECLARATION_RE, (_match, kind, local) => {
8671
- exportedNames.push({
8672
- exported: "default",
8673
- local
8674
- });
8675
- return `${kind} ${local}`;
8676
- });
8677
- transformed = transformed.replace(ESM_EXPORT_DECLARATION_RE, (_match, kind, local) => {
8678
- exportedNames.push({
8679
- exported: local,
8680
- local
8681
- });
8682
- return `${kind} ${local}`;
8683
- });
8684
- transformed = transformed.replace(/\bexport\s+default\s+/g, "module.exports.default = ");
8685
- if (exportedNames.length > 0) transformed += `\n${exportedNames.map(({ exported, local }) => `module.exports[${JSON.stringify(exported)}] = ${local};`).join("\n")}`;
8686
- return transformed;
8687
- }
8688
10037
  function createRequireNotFoundError(request, importer) {
8689
10038
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in headless runtime.`);
8690
10039
  }
8691
- function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, kernel, globals, onConsole) {
10040
+ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, kernel, globals, onConsole, workers) {
8692
10041
  const runtimeConsole = kernel.diagnostics.createConsole(console, onConsole);
8693
- const wx = createHeadlessWx(wxDriver, runtimeConsole);
10042
+ const wx = createHeadlessWx(wxDriver, runtimeConsole, workers);
8694
10043
  return createMiniProgramRuntimeGlobals({
8695
10044
  App(definition) {
8696
10045
  return registerAppDefinition(registries, definition);
@@ -8723,8 +10072,19 @@ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, k
8723
10072
  }, globals);
8724
10073
  }
8725
10074
  function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, options) {
10075
+ const workers = createWorkerHost({
10076
+ root: options.miniprogramRootPath,
10077
+ read: (file) => options.artifactSource.readText(file),
10078
+ console: options.kernel.diagnostics.createConsole(console, options.onConsole),
10079
+ createExecutor(globals) {
10080
+ const realm = vm.createContext(globals);
10081
+ return (source, file, module, require) => {
10082
+ new vm.Script(`(function(module, exports, require) {${source}\n})`, { filename: file }).runInContext(realm)(module, module.exports, require);
10083
+ };
10084
+ }
10085
+ });
8726
10086
  const moduleCache = /* @__PURE__ */ new Map();
8727
- const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {}, options.onConsole);
10087
+ const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {}, options.onConsole, workers.apis);
8728
10088
  executionContext.globalThis = executionContext;
8729
10089
  function executeModule(filePath, loadContext) {
8730
10090
  const resolvedPath = path.resolve(filePath);
@@ -8733,6 +10093,7 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
8733
10093
  const source = options.artifactSource.readText(resolvedPath);
8734
10094
  if (source == null) throw new TypeError(`Missing module in headless runtime: ${normalize(resolvedPath)}`);
8735
10095
  const module = {
10096
+ source,
8736
10097
  componentDefinitions: [],
8737
10098
  exports: {}
8738
10099
  };
@@ -8742,7 +10103,7 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
8742
10103
  const previousLoadContext = registries.currentLoadContext;
8743
10104
  registries.currentLoadContext = loadContext;
8744
10105
  const localRequire = ((request) => {
8745
- 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));
8746
10107
  if (!requiredPath) throw createRequireNotFoundError(request, resolvedPath);
8747
10108
  if (requiredPath.endsWith(".json")) {
8748
10109
  const content = options.artifactSource.readText(requiredPath);
@@ -8755,7 +10116,7 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
8755
10116
  });
8756
10117
  localRequire.async = (request) => Promise.resolve().then(() => localRequire(request));
8757
10118
  try {
8758
- 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));
8759
10120
  const registeredDefinitions = [...registries.components.values()].filter((definition) => !registeredDefinitionsBefore.has(definition));
8760
10121
  module.componentDefinitions = [.../* @__PURE__ */ new Set([
8761
10122
  ...requiredComponentDefinitions,
@@ -8783,6 +10144,7 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
8783
10144
  return callback(...args);
8784
10145
  },
8785
10146
  close() {
10147
+ workers.close();
8786
10148
  moduleCache.clear();
8787
10149
  closeRuntimeWxsLoader(loader);
8788
10150
  },
@@ -8801,6 +10163,17 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
8801
10163
  if (!definition) throw new Error(`Page() was not registered for route "${route}" while executing ${normalize(filePath)}.`);
8802
10164
  return definition;
8803
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
+ },
8804
10177
  executeComponentModule(filePath, id) {
8805
10178
  const loadedModule = executeModule(filePath, {
8806
10179
  kind: "component",
@@ -8886,6 +10259,7 @@ var HeadlessSession = class {
8886
10259
  appInstance = null;
8887
10260
  appLifecycle = new HeadlessAppLifecycle();
8888
10261
  moduleLoader;
10262
+ templateRegistration;
8889
10263
  routeEvents = new HeadlessRouteEvents((callback) => this.requestRender(callback), (page) => this.currentPageInstance === page && !this.kernel.isClosed);
8890
10264
  eventListeners = /* @__PURE__ */ new Map();
8891
10265
  registries;
@@ -8894,8 +10268,13 @@ var HeadlessSession = class {
8894
10268
  componentCache = /* @__PURE__ */ new Map();
8895
10269
  componentScopes = /* @__PURE__ */ new Map();
8896
10270
  selectorQueryScopeSnapshots = /* @__PURE__ */ new WeakMap();
8897
- renderRequestPending = false;
8898
- 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
+ });
8899
10278
  tabBarRoutes;
8900
10279
  tabPages = /* @__PURE__ */ new Map();
8901
10280
  tabBarItems = /* @__PURE__ */ new Map();
@@ -8914,6 +10293,7 @@ var HeadlessSession = class {
8914
10293
  constructor(options) {
8915
10294
  if (!options.project && !options.projectPath) throw new Error("Headless runtime requires projectPath or project.");
8916
10295
  this.project = options.project ?? loadProject(options.projectPath);
10296
+ this.templateRegistration = createTemplateRegistration(this.project.artifactSource, this.project.miniprogramRootPath, options.compiledTemplatePaths);
8917
10297
  this.wxState = createHeadlessWxState(this.kernel.scheduler, {
8918
10298
  strictMocks: options.strictHostMocks,
8919
10299
  readPackageFile: createPackageAssetReader((relative) => this.project.artifactSource.readText(path.join(this.project.miniprogramRootPath, relative)))
@@ -8967,7 +10347,7 @@ var HeadlessSession = class {
8967
10347
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
8968
10348
  getNetworkType: () => this.wxState.getNetworkType(),
8969
10349
  navigateBack: (option) => this.navigateBack(option?.delta),
8970
- navigateTo: (option) => this.navigateTo(option.url),
10350
+ navigateTo: (option) => this.routeEvents.navigateTo(() => this.navigateTo(option.url), option),
8971
10351
  pageScrollTo: (option) => this.pageScrollTo(option),
8972
10352
  openDocument: (option) => this.wxState.openDocument(option),
8973
10353
  clearStorageSync: () => this.wxState.clearStorageSync(),
@@ -9051,8 +10431,7 @@ var HeadlessSession = class {
9051
10431
  failure = { error };
9052
10432
  }
9053
10433
  this.canvasContexts.clear();
9054
- this.renderRequestCallbacks.length = 0;
9055
- this.renderRequestPending = false;
10434
+ this.renderQueue.close();
9056
10435
  this.appLifecycle.close();
9057
10436
  this.routeEvents.close();
9058
10437
  this.wxState.close();
@@ -9102,6 +10481,23 @@ var HeadlessSession = class {
9102
10481
  this.assertActive();
9103
10482
  return this.pages.slice();
9104
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
+ }
9105
10501
  getWx() {
9106
10502
  this.assertActive();
9107
10503
  return this.moduleLoader.wx;
@@ -9157,7 +10553,7 @@ var HeadlessSession = class {
9157
10553
  const current = this.requireCurrentPage("renderCurrentPage()");
9158
10554
  const rendered = renderRuntimePageTree({
9159
10555
  changedPageKeys: current.__lastChangedKeys__ ?? [],
9160
- artifactSource: this.project.artifactSource,
10556
+ artifactSource: this.templateRegistration.artifactSource,
9161
10557
  componentCache: this.componentCache,
9162
10558
  componentScopes: this.componentScopes,
9163
10559
  moduleLoader: this.moduleLoader,
@@ -9187,20 +10583,18 @@ var HeadlessSession = class {
9187
10583
  dispatchNativeNodeEvent(node, eventName, event, onHandlerResult) {
9188
10584
  const current = this.requireCurrentPage("dispatchNativeNodeEvent()");
9189
10585
  if (eventName === "tap") this.renderCurrentPage();
9190
- 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
+ });
9191
10594
  }
9192
10595
  requestRender(callback) {
9193
10596
  this.assertActive();
9194
- if (callback) this.renderRequestCallbacks.push(callback);
9195
- if (this.renderRequestPending) return;
9196
- this.renderRequestPending = true;
9197
- Promise.resolve().then(() => {
9198
- if (this.kernel.isClosed) return;
9199
- this.renderRequestPending = false;
9200
- const callbacks = this.renderRequestCallbacks.splice(0);
9201
- if (this.currentPageInstance) this.renderCurrentPage();
9202
- callbacks.forEach((cb) => cb());
9203
- });
10597
+ this.renderQueue.request(callback);
9204
10598
  }
9205
10599
  getScopeSnapshot(scopeId) {
9206
10600
  const scope = this.componentScopes.get(scopeId);
@@ -9282,19 +10676,19 @@ var HeadlessSession = class {
9282
10676
  return this.wxState.getShareMenu();
9283
10677
  }
9284
10678
  selectComponent(selector) {
9285
- this.renderCurrentPage();
10679
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
9286
10680
  return this.selectComponentsWithin(null, selector)[0] ?? null;
9287
10681
  }
9288
10682
  selectAllComponents(selector) {
9289
- this.renderCurrentPage();
10683
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
9290
10684
  return this.selectComponentsWithin(null, selector);
9291
10685
  }
9292
10686
  selectComponentWithin(scopeId, selector) {
9293
- this.renderCurrentPage();
10687
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
9294
10688
  return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
9295
10689
  }
9296
10690
  selectAllComponentsWithin(scopeId, selector) {
9297
- this.renderCurrentPage();
10691
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
9298
10692
  return this.selectComponentsWithin(scopeId, selector);
9299
10693
  }
9300
10694
  selectOwnerComponent(scopeId) {
@@ -10034,6 +11428,7 @@ function createPageRootNodeHandle(options) {
10034
11428
  const tree = session?.getCurrentPages().includes(page) ? session.renderCurrentPage() : renderPageTree(project, page);
10035
11429
  return new HeadlessTestingNodeHandle(tree.root.type === "root" && !options.includeHostRoots ? tree.root.children?.[0] ?? tree.root : tree.root, {
10036
11430
  assertActive: options.assertActive,
11431
+ projectionOnly: options.projectionOnly,
10037
11432
  dispatchNativeEvent: (node, eventName, event, onHandlerResult) => session?.getCurrentPages().at(-1) === page ? session.dispatchNativeNodeEvent(node, eventName, event, onHandlerResult) : false,
10038
11433
  callMethod: (scopeId, methodName, event) => {
10039
11434
  if (session?.getCurrentPages().includes(page)) return session.callScopeMethod(scopeId, methodName, event);
@@ -10396,7 +11791,18 @@ var HeadlessTestingPageHandle = class {
10396
11791
  renderedAccess() {
10397
11792
  return {
10398
11793
  assertActive: () => this.assertActive(),
10399
- findAll: async (selector) => await this.$$(selector),
11794
+ findAll: async (selector) => {
11795
+ this.assertActive();
11796
+ const root = createPageRootNodeHandle({
11797
+ assertActive: () => this.assertActive(),
11798
+ createPageHandle: () => this,
11799
+ page: this.page,
11800
+ project: this.project,
11801
+ projectionOnly: true,
11802
+ session: this.session
11803
+ });
11804
+ return selector === "page" ? [root] : await root.$$(selector);
11805
+ },
10400
11806
  waitFor: async (ms) => await this.waitFor(ms),
10401
11807
  wxml: async () => await this.wxml()
10402
11808
  };
@@ -10413,6 +11819,133 @@ var HeadlessTestingPageHandle = class {
10413
11819
  }
10414
11820
  };
10415
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
10416
11949
  //#region src/testing/sessionHandle/scope.ts
10417
11950
  var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
10418
11951
  scopeId;
@@ -10474,16 +12007,41 @@ var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
10474
12007
  var HeadlessTestingSessionHandle = class {
10475
12008
  project;
10476
12009
  session;
10477
- pendingNavigations = /* @__PURE__ */ new Set();
12010
+ navigation;
12011
+ disconnection;
12012
+ cdp;
10478
12013
  constructor(project, session) {
10479
12014
  this.project = project;
10480
12015
  this.session = session;
10481
- this.session.on("close", () => {
10482
- for (const reject of this.pendingNavigations) reject(/* @__PURE__ */ new Error("The headless testing session closed before navigation completed."));
10483
- });
12016
+ this.navigation = new HeadlessTestingNavigation(session);
12017
+ }
12018
+ close() {
12019
+ return this.disconnect();
12020
+ }
12021
+ /** 先保存共享结果,再同步开始关闭,覆盖关闭监听器内的重入调用。 */
12022
+ disconnect() {
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;
10484
12038
  }
10485
- async close() {
10486
- this.session.close();
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());
10487
12045
  }
10488
12046
  async toolInfo() {
10489
12047
  return { version: "mpcore-simulator" };
@@ -10522,6 +12080,10 @@ var HeadlessTestingSessionHandle = class {
10522
12080
  const normalizedMethodName = normalizeNonEmptyInput(methodName, "wx method name");
10523
12081
  return await runWithTimeout(() => this.session.callWxMethod(normalizedMethodName, ...args), options.timeout, `Timed out calling wx.${normalizedMethodName} in headless testing runtime.`);
10524
12082
  }
12083
+ /** 返回与 DevTools automator 兼容的运行时系统信息。 */
12084
+ async systemInfo() {
12085
+ return await this.callWxMethod("getSystemInfoSync");
12086
+ }
10525
12087
  async scopeSnapshot(scopeId) {
10526
12088
  const normalizedScopeId = normalizeNonEmptyInput(scopeId, "Scope id");
10527
12089
  return this.session.getScopeSnapshot(normalizedScopeId);
@@ -10549,23 +12111,31 @@ var HeadlessTestingSessionHandle = class {
10549
12111
  }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
10550
12112
  }
10551
12113
  async reLaunch(route) {
10552
- await this.invokeNavigation("reLaunch", { url: route });
12114
+ await this.navigation.invoke("reLaunch", { url: route });
10553
12115
  return await this.requireCurrentPage("reLaunch", route);
10554
12116
  }
12117
+ /** 只更新页面定义;不隐式导航,也不替换当前页面或应用实例。 */
12118
+ async reloadPageDefinition(route) {
12119
+ return this.session.reloadPageDefinition(route);
12120
+ }
12121
+ /** 显式提交宿主编译模板;不隐式重载脚本或导航。 */
12122
+ async reloadTemplates() {
12123
+ return this.session.reloadTemplates();
12124
+ }
10555
12125
  async navigateTo(route) {
10556
- await this.invokeNavigation("navigateTo", { url: route });
12126
+ await this.navigation.invoke("navigateTo", { url: route });
10557
12127
  return await this.requireCurrentPage("navigateTo", route);
10558
12128
  }
10559
12129
  async redirectTo(route) {
10560
- await this.invokeNavigation("redirectTo", { url: route });
12130
+ await this.navigation.invoke("redirectTo", { url: route });
10561
12131
  return await this.requireCurrentPage("redirectTo", route);
10562
12132
  }
10563
12133
  async navigateBack(delta = 1) {
10564
- await this.invokeNavigation("navigateBack", { delta });
12134
+ await this.navigation.invoke("navigateBack", { delta });
10565
12135
  return await this.currentPage();
10566
12136
  }
10567
12137
  async switchTab(route) {
10568
- await this.invokeNavigation("switchTab", { url: route });
12138
+ await this.navigation.invoke("switchTab", { url: route });
10569
12139
  return await this.requireCurrentPage("switchTab", route);
10570
12140
  }
10571
12141
  async waitForCurrentPage(route, options = {}) {
@@ -10601,32 +12171,6 @@ var HeadlessTestingSessionHandle = class {
10601
12171
  async triggerRouteDone(options) {
10602
12172
  this.session.triggerRouteDone(options);
10603
12173
  }
10604
- invokeNavigation(methodName, options) {
10605
- return new Promise((resolve, reject) => {
10606
- const rejectNavigation = (error) => {
10607
- this.pendingNavigations.delete(rejectNavigation);
10608
- reject(error);
10609
- };
10610
- this.pendingNavigations.add(rejectNavigation);
10611
- try {
10612
- this.session.callWxMethod(methodName, {
10613
- ...options,
10614
- success: () => {
10615
- this.pendingNavigations.delete(rejectNavigation);
10616
- resolve();
10617
- },
10618
- fail: (error) => {
10619
- const details = error && typeof error === "object" ? error : void 0;
10620
- const reason = typeof details?.errMsg === "string" ? details.errMsg : typeof details?.message === "string" ? details.message : String(error);
10621
- const target = options.url ? ` route "${options.url}"` : "";
10622
- rejectNavigation(new Error(`Failed to ${methodName}${target} through the headless wx runtime: ${reason}`, { cause: error }));
10623
- }
10624
- });
10625
- } catch (error) {
10626
- rejectNavigation(error);
10627
- }
10628
- });
10629
- }
10630
12174
  async requireCurrentPage(methodName, route) {
10631
12175
  const page = await this.currentPage();
10632
12176
  if (!page) throw new Error(`Failed to ${methodName} route "${route}" through the headless wx runtime.`);
@@ -10645,7 +12189,10 @@ function resolveInitialRoute(session) {
10645
12189
  return session.project.routes[0]?.route ?? null;
10646
12190
  }
10647
12191
  async function launch(options) {
10648
- const session = createHeadlessSession({ projectPath: options.projectPath });
12192
+ const session = createHeadlessSession({
12193
+ compiledTemplatePaths: options.compiledTemplatePaths,
12194
+ projectPath: options.projectPath
12195
+ });
10649
12196
  const handle = new HeadlessTestingSessionHandle(session.project, session);
10650
12197
  try {
10651
12198
  await options.onSessionCreated?.(handle);
@@ -10660,4 +12207,4 @@ async function launch(options) {
10660
12207
  }
10661
12208
  }
10662
12209
  //#endregion
10663
- 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 };