@mpcore/simulator 0.6.3 → 1.0.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,9 +1,9 @@
1
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";
2
3
  import fs from "node:fs";
3
4
  import path from "node:path";
4
5
  import { parseExpression } from "@babel/parser";
5
6
  import postcss from "postcss";
6
- import { WEVU_NATIVE_INSTANCE_KEY } from "@weapp-core/constants";
7
7
  import { parseDocument } from "htmlparser2";
8
8
  import { selectAll } from "css-select";
9
9
  import { AttributeAction, SelectorType, parse } from "css-what";
@@ -21,6 +21,41 @@ function validateConstructedBehaviors(definition, visited = /* @__PURE__ */ new
21
21
  }
22
22
  }
23
23
  //#endregion
24
+ //#region src/host/attachmentBindingUpdates.ts
25
+ const bindingUpdates = /* @__PURE__ */ new WeakMap();
26
+ const instanceScopes = /* @__PURE__ */ new WeakMap();
27
+ /** 实例经渲染上下文归属页面,不扩展公开 renderer context 的参数契约。 */
28
+ function bindAttachmentBindingScope(instance, scope) {
29
+ instanceScopes.set(instance, instanceScopes.get(scope) ?? scope);
30
+ }
31
+ /** 仅在挂载回调内同步逻辑绑定,不接管视图提交和 setData 回调。 */
32
+ function runWithAttachmentBindingUpdates(scope, update, callback, value) {
33
+ const previous = bindingUpdates.get(scope);
34
+ const state = previous ?? {
35
+ revision: 0,
36
+ update
37
+ };
38
+ const previousUpdate = state.update;
39
+ state.update = update;
40
+ bindingUpdates.set(scope, state);
41
+ try {
42
+ return callback(value);
43
+ } finally {
44
+ if (previous) state.update = previousUpdate;
45
+ else bindingUpdates.delete(scope);
46
+ }
47
+ }
48
+ function getAttachmentBindingRevision(instance) {
49
+ return bindingUpdates.get(instanceScopes.get(instance) ?? instance);
50
+ }
51
+ function synchronizeAttachmentBindings(instance) {
52
+ const state = bindingUpdates.get(instanceScopes.get(instance) ?? instance);
53
+ if (state) {
54
+ state.revision++;
55
+ state.update();
56
+ }
57
+ }
58
+ //#endregion
24
59
  //#region src/host/componentPageAttachment.ts
25
60
  const definitionAttachments = /* @__PURE__ */ new WeakMap();
26
61
  const instanceAttachments = /* @__PURE__ */ new WeakMap();
@@ -36,8 +71,11 @@ function getComponentPageStyleIsolation(instance) {
36
71
  function isComponentPageAttaching(instance) {
37
72
  return attachingInstances.has(instance);
38
73
  }
39
- function registerComponentPageAttachment(definition, attach) {
40
- definitionAttachments.set(definition, attach);
74
+ function registerComponentPageAttachment(definition, created, attached) {
75
+ definitionAttachments.set(definition, {
76
+ created,
77
+ attached
78
+ });
41
79
  }
42
80
  function bindComponentPageAttachment(instance, definition) {
43
81
  const attach = definitionAttachments.get(definition);
@@ -48,13 +86,14 @@ function bindComponentPageAttachment(instance, definition) {
48
86
  if (typeof options?.styleIsolation === "string") instanceStyleIsolation.set(instance, options.styleIsolation);
49
87
  }
50
88
  }
51
- function attachComponentPage(instance) {
89
+ function attachComponentPage(instance, updateBindings) {
52
90
  const attach = instanceAttachments.get(instance);
53
91
  if (!attach) return false;
54
92
  instanceAttachments.delete(instance);
55
93
  attachingInstances.add(instance);
56
94
  try {
57
- attach.call(instance);
95
+ attach.created(instance);
96
+ runWithAttachmentBindingUpdates(instance, updateBindings, attach.attached, instance);
58
97
  } finally {
59
98
  attachingInstances.delete(instance);
60
99
  }
@@ -68,15 +107,23 @@ function createDuplicateRegistrationError(kind, id) {
68
107
  function callDefinitionMethod(instance, method, args) {
69
108
  if (typeof method === "function") return method.apply(instance, args);
70
109
  }
110
+ function composeDefinitionMethods(primary, secondary) {
111
+ if (typeof primary !== "function" || typeof secondary !== "function" || primary === secondary) return primary ?? secondary;
112
+ return function composedDefinitionMethod(...args) {
113
+ const result = primary.apply(this, args);
114
+ secondary.apply(this, args);
115
+ return result;
116
+ };
117
+ }
71
118
  function normalizeComponentPageDefinition(definition) {
72
119
  const { lifetimes = {}, methods = {}, pageLifetimes = {}, ...rest } = definition;
73
120
  const created = lifetimes.created ?? rest.created;
74
121
  const attached = lifetimes.attached ?? rest.attached;
75
- const ready = lifetimes.ready ?? rest.ready ?? methods.onReady ?? rest.onReady;
122
+ const ready = composeDefinitionMethods(lifetimes.ready ?? rest.ready, methods.onReady ?? rest.onReady);
76
123
  const detached = lifetimes.detached ?? rest.detached ?? methods.onUnload ?? rest.onUnload;
77
124
  const load = methods.onLoad ?? rest.onLoad;
78
- const show = pageLifetimes.show ?? methods.onShow ?? rest.onShow;
79
- const hide = pageLifetimes.hide ?? methods.onHide ?? rest.onHide;
125
+ const show = typeof pageLifetimes.show === "function" ? composeDefinitionMethods(pageLifetimes.show, methods.onShow) : methods.onShow ?? rest.onShow;
126
+ const hide = typeof pageLifetimes.hide === "function" ? composeDefinitionMethods(pageLifetimes.hide, methods.onHide) : methods.onHide ?? rest.onHide;
80
127
  const resize = pageLifetimes.resize ?? methods.onResize ?? rest.onResize;
81
128
  const routeDone = pageLifetimes.routeDone ?? methods.onRouteDone ?? rest.onRouteDone;
82
129
  const pageDefinition = {
@@ -104,10 +151,7 @@ function normalizeComponentPageDefinition(definition) {
104
151
  return callDefinitionMethod(this, routeDone, args);
105
152
  }
106
153
  };
107
- registerComponentPageAttachment(pageDefinition, function() {
108
- callDefinitionMethod(this, created, []);
109
- callDefinitionMethod(this, attached, []);
110
- });
154
+ registerComponentPageAttachment(pageDefinition, (instance) => callDefinitionMethod(instance, created, []), (instance) => callDefinitionMethod(instance, attached, []));
111
155
  return pageDefinition;
112
156
  }
113
157
  function createHostRegistries() {
@@ -241,7 +285,13 @@ var StartupNavigationQueue = class {
241
285
  }
242
286
  }
243
287
  run(option, operation) {
244
- if (!this.collecting) return operation(option);
288
+ if (!this.collecting) {
289
+ const submitted = option && { ...option };
290
+ this.scheduler.queueMicrotask(() => {
291
+ this.scheduler.setTimeout(() => operation(submitted), 0);
292
+ });
293
+ return;
294
+ }
245
295
  const defer = (callback) => callback ? (...args) => {
246
296
  this.scheduler.setTimeout(() => callback(...args), 0);
247
297
  } : void 0;
@@ -292,7 +342,7 @@ function resolveCapabilityValue(source, schema) {
292
342
  }
293
343
  return current;
294
344
  }
295
- function createHeadlessWx(driver, runtimeConsole = console) {
345
+ function createHeadlessWx(driver, runtimeConsole = console, workers) {
296
346
  const eventBus = createHeadlessUniEventBus();
297
347
  const rpx2px = (value) => {
298
348
  const width = driver.getWindowInfoSync().windowWidth;
@@ -300,6 +350,10 @@ function createHeadlessWx(driver, runtimeConsole = console) {
300
350
  };
301
351
  const capabilityTree = {
302
352
  canIUse: true,
353
+ ...workers ? {
354
+ createWorker: true,
355
+ preDownloadSubpackage: true
356
+ } : {},
303
357
  canvasToTempFilePath: true,
304
358
  chooseImage: { return: {
305
359
  errMsg: true,
@@ -500,6 +554,14 @@ function createHeadlessWx(driver, runtimeConsole = console) {
500
554
  navigateBack: true,
501
555
  navigateTo: true,
502
556
  nextTick: true,
557
+ offBeforeAppRoute: true,
558
+ offBeforePageUnload: true,
559
+ offAppRoute: true,
560
+ offAppRouteDone: true,
561
+ onBeforeAppRoute: true,
562
+ onBeforePageUnload: true,
563
+ onAppRoute: true,
564
+ onAppRouteDone: true,
503
565
  offAppHide: true,
504
566
  offAppShow: true,
505
567
  offNetworkStatusChange: true,
@@ -547,6 +609,16 @@ function createHeadlessWx(driver, runtimeConsole = console) {
547
609
  };
548
610
  return {
549
611
  ...eventBus,
612
+ [WEVU_ROUTE_EVENT_CONTRACT_KEY]: 1,
613
+ [WEVU_PAGE_SCROLL_EVENT_CONTRACT_KEY]: 1,
614
+ createWorker: (script) => {
615
+ if (!workers) throw new Error("Worker host is unavailable");
616
+ return workers.createWorker(script);
617
+ },
618
+ preDownloadSubpackage: (option) => {
619
+ if (!workers) throw new Error("Worker host is unavailable");
620
+ workers.preDownloadSubpackage(option);
621
+ },
550
622
  canIUse: (schema) => typeof schema === "string" && schema.trim() !== "" && resolveCapabilityValue(capabilityTree, schema.trim()) != null,
551
623
  canvasToTempFilePath: (option) => invokeWxApi(() => driver.canvasToTempFilePath(option), option),
552
624
  chooseImage: (option) => invokeWxApi(() => driver.chooseImage(option ?? {}), option),
@@ -670,10 +742,16 @@ function createHeadlessWx(driver, runtimeConsole = console) {
670
742
  navigateBack: (option) => runNavigationApi(driver, option, (deferred) => invokeWxApi(() => {
671
743
  driver.navigateBack(deferred);
672
744
  }, deferred)),
673
- navigateTo: (option) => runNavigationApi(driver, option, (deferred) => invokeWxApi(() => {
674
- driver.navigateTo(deferred);
675
- }, deferred)),
745
+ navigateTo: (option) => runNavigationApi(driver, option, (deferred) => driver.navigateTo(deferred)),
676
746
  nextTick: (callback) => driver.nextTick(callback),
747
+ offBeforeAppRoute: (listener) => driver.offBeforeAppRoute(listener),
748
+ offBeforePageUnload: (listener) => driver.offBeforePageUnload(listener),
749
+ offAppRoute: (listener) => driver.offAppRoute(listener),
750
+ offAppRouteDone: (listener) => driver.offAppRouteDone(listener),
751
+ onBeforeAppRoute: (listener) => driver.onBeforeAppRoute(listener),
752
+ onBeforePageUnload: (listener) => driver.onBeforePageUnload(listener),
753
+ onAppRoute: (listener) => driver.onAppRoute(listener),
754
+ onAppRouteDone: (listener) => driver.onAppRouteDone(listener),
677
755
  offAppHide: (callback) => driver.offAppHide(callback),
678
756
  offAppShow: (callback) => driver.offAppShow(callback),
679
757
  offNetworkStatusChange: (callback) => driver.offNetworkStatusChange(callback),
@@ -803,6 +881,208 @@ function createMiniProgramRuntimeGlobals(availableGlobals, overrides) {
803
881
  return Object.assign(globals, availableGlobals, overrides);
804
882
  }
805
883
  //#endregion
884
+ //#region src/kernel/scheduler.ts
885
+ var RuntimeScheduler = class {
886
+ intervals = /* @__PURE__ */ new Set();
887
+ timeouts = /* @__PURE__ */ new Set();
888
+ closed = false;
889
+ canceledHandle;
890
+ onError;
891
+ constructor(onError) {
892
+ this.onError = onError;
893
+ }
894
+ clearInterval(handle) {
895
+ this.intervals.delete(handle);
896
+ clearInterval(handle);
897
+ }
898
+ clearTimeout(handle) {
899
+ this.timeouts.delete(handle);
900
+ clearTimeout(handle);
901
+ }
902
+ close() {
903
+ if (this.closed) return;
904
+ this.closed = true;
905
+ for (const handle of this.intervals) clearInterval(handle);
906
+ for (const handle of this.timeouts) clearTimeout(handle);
907
+ this.intervals.clear();
908
+ this.timeouts.clear();
909
+ }
910
+ queueMicrotask(handler) {
911
+ if (this.closed) return;
912
+ queueMicrotask(() => {
913
+ if (this.closed) return;
914
+ try {
915
+ handler();
916
+ } catch (error) {
917
+ this.onError(error);
918
+ }
919
+ });
920
+ }
921
+ setInterval(handler, timeout, ...args) {
922
+ if (this.closed) return this.getCanceledHandle();
923
+ const handle = setInterval(() => {
924
+ try {
925
+ handler(...args);
926
+ } catch (error) {
927
+ this.onError(error);
928
+ }
929
+ }, timeout);
930
+ this.intervals.add(handle);
931
+ return handle;
932
+ }
933
+ setTimeout(handler, timeout, ...args) {
934
+ if (this.closed) return this.getCanceledHandle();
935
+ const handle = setTimeout(() => {
936
+ this.timeouts.delete(handle);
937
+ try {
938
+ handler(...args);
939
+ } catch (error) {
940
+ this.onError(error);
941
+ }
942
+ }, timeout);
943
+ this.timeouts.add(handle);
944
+ return handle;
945
+ }
946
+ /** 已销毁 realm 的 Promise 回调不能复活任务,也不能向外泄漏异步拒绝。 */
947
+ getCanceledHandle() {
948
+ if (!this.canceledHandle) {
949
+ this.canceledHandle = setTimeout(() => {}, 0);
950
+ clearTimeout(this.canceledHandle);
951
+ }
952
+ return this.canceledHandle;
953
+ }
954
+ };
955
+ //#endregion
956
+ //#region src/runtime/workerHost.ts
957
+ /** 两种 simulator 共用消息与生命周期;每个 worker 独立模块缓存、全局对象及计时器。 */
958
+ function createWorkerHost(options) {
959
+ const active = /* @__PURE__ */ new Set();
960
+ let closed = false;
961
+ const configuredRoot = () => {
962
+ return JSON.parse(options.read(join(options.root, "app.json")) ?? "{}").workers;
963
+ };
964
+ return {
965
+ apis: {
966
+ preDownloadSubpackage(option) {
967
+ const config = configuredRoot();
968
+ if (option.packageType !== "workers" || typeof config !== "object" || !config.isSubpackage) {
969
+ const error = /* @__PURE__ */ new Error("preDownloadSubpackage:fail workers subpackage is not configured");
970
+ option.fail?.(error);
971
+ option.complete?.();
972
+ return;
973
+ }
974
+ const result = { errMsg: "preDownloadSubpackage:ok" };
975
+ option.success?.(result);
976
+ option.complete?.(result);
977
+ },
978
+ createWorker(scriptPath) {
979
+ if (closed) throw new Error("createWorker:fail runtime has closed");
980
+ const config = configuredRoot();
981
+ const directory = typeof config === "string" ? config : config?.path;
982
+ if (!directory || typeof scriptPath !== "string" || !scriptPath.endsWith(".js")) throw new Error("createWorker:fail invalid worker path");
983
+ const root = normalize(join(options.root, directory));
984
+ const entry = normalize(join(options.root, scriptPath));
985
+ const inside = (file) => file.startsWith(`${root}/`);
986
+ if (!inside(entry) || options.read(entry) === void 0) throw new Error("createWorker:fail worker entry is outside the configured directory or missing");
987
+ const messages = /* @__PURE__ */ new Set();
988
+ const incoming = /* @__PURE__ */ new Set();
989
+ const errors = /* @__PURE__ */ new Set();
990
+ const cache = /* @__PURE__ */ new Map();
991
+ let terminated = false;
992
+ const scheduler = new RuntimeScheduler((error) => {
993
+ const value = { message: error instanceof Error ? error.message : String(error) };
994
+ if (errors.size) for (const listener of errors) listener(value);
995
+ else options.console.error(value.message);
996
+ });
997
+ const post = (listeners, message) => {
998
+ if (terminated) return;
999
+ const copy = structuredClone(message);
1000
+ scheduler.setTimeout(() => {
1001
+ for (const listener of [...listeners]) {
1002
+ if (terminated) break;
1003
+ listener(copy);
1004
+ }
1005
+ }, 0);
1006
+ };
1007
+ const globals = {
1008
+ wx: void 0,
1009
+ App: void 0,
1010
+ Page: void 0,
1011
+ Component: void 0,
1012
+ getApp: void 0,
1013
+ console: options.console,
1014
+ worker: {
1015
+ onMessage: (listener) => incoming.add(listener),
1016
+ postMessage: (message) => post(messages, message)
1017
+ },
1018
+ setTimeout: scheduler.setTimeout.bind(scheduler),
1019
+ clearTimeout: scheduler.clearTimeout.bind(scheduler),
1020
+ setInterval: scheduler.setInterval.bind(scheduler),
1021
+ clearInterval: scheduler.clearInterval.bind(scheduler)
1022
+ };
1023
+ globals.globalThis = globals;
1024
+ const execute = options.createExecutor(globals);
1025
+ const load = (file) => {
1026
+ if (terminated) return;
1027
+ if (!inside(file)) throw new Error("Worker require cannot leave its configured directory");
1028
+ if (cache.has(file)) return cache.get(file).exports;
1029
+ const source = options.read(file);
1030
+ if (source === void 0) throw new Error(`Missing worker module: ${file}`);
1031
+ if (file.endsWith(".json")) return JSON.parse(source);
1032
+ const module = { exports: {} };
1033
+ cache.set(file, module);
1034
+ const require = Object.assign((request) => {
1035
+ const target = resolveMiniProgramModule(file, request, root, (candidate) => options.read(candidate) !== void 0);
1036
+ if (!target) throw new Error(`Cannot resolve worker module: ${request}`);
1037
+ return load(target);
1038
+ }, { async: (request) => Promise.resolve().then(() => require(request)) });
1039
+ try {
1040
+ execute(source, file, module, require);
1041
+ } catch (error) {
1042
+ cache.delete(file);
1043
+ throw error;
1044
+ }
1045
+ return module.exports;
1046
+ };
1047
+ const worker = {
1048
+ onMessage: (listener) => {
1049
+ messages.add(listener);
1050
+ },
1051
+ offMessage: (listener) => {
1052
+ if (listener) messages.delete(listener);
1053
+ else messages.clear();
1054
+ },
1055
+ postMessage: (message) => post(incoming, message),
1056
+ onError: (listener) => {
1057
+ errors.add(listener);
1058
+ },
1059
+ offError: (listener) => {
1060
+ if (listener) errors.delete(listener);
1061
+ else errors.clear();
1062
+ },
1063
+ terminate() {
1064
+ if (terminated) return;
1065
+ terminated = true;
1066
+ scheduler.close();
1067
+ messages.clear();
1068
+ incoming.clear();
1069
+ errors.clear();
1070
+ cache.clear();
1071
+ active.delete(worker);
1072
+ }
1073
+ };
1074
+ active.add(worker);
1075
+ scheduler.setTimeout(() => load(entry), 0);
1076
+ return worker;
1077
+ }
1078
+ },
1079
+ close() {
1080
+ closed = true;
1081
+ for (const worker of active) worker.terminate();
1082
+ }
1083
+ };
1084
+ }
1085
+ //#endregion
806
1086
  //#region src/browser/virtualFiles.ts
807
1087
  function normalizeBrowserFilePath(filePath) {
808
1088
  return normalize(filePath).replace(/^\/+/, "").replace(/^\.\//, "");
@@ -908,9 +1188,9 @@ function getBrowserWxsLoader(owner, files) {
908
1188
  function createRequireNotFoundError$1(request, importer) {
909
1189
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in browser simulator runtime.`);
910
1190
  }
911
- function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, kernel, globals) {
1191
+ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, kernel, globals, workers) {
912
1192
  const runtimeConsole = kernel.diagnostics.createConsole();
913
- const wx = createHeadlessWx(wxDriver, runtimeConsole);
1193
+ const wx = createHeadlessWx(wxDriver, runtimeConsole, workers);
914
1194
  return createMiniProgramRuntimeGlobals({
915
1195
  App(definition) {
916
1196
  return registerAppDefinition(registries, definition);
@@ -940,8 +1220,18 @@ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver,
940
1220
  }, globals);
941
1221
  }
942
1222
  function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, wxDriver, options) {
1223
+ const workers = createWorkerHost({
1224
+ root: options.miniprogramRootPath,
1225
+ read: (file) => readBrowserVirtualFile(files, file),
1226
+ console: options.kernel.diagnostics.createConsole(),
1227
+ createExecutor(globals) {
1228
+ return (source, _file, module, require) => {
1229
+ new Function(`with (this) { return function(module, exports, require) {${source}\n}; }`).call(globals).call(globals, module, module.exports, require);
1230
+ };
1231
+ }
1232
+ });
943
1233
  const moduleCache = /* @__PURE__ */ new Map();
944
- const executionContext = createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {});
1234
+ const executionContext = createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {}, workers.apis);
945
1235
  executionContext.globalThis = executionContext;
946
1236
  function executeModule(filePath, loadContext) {
947
1237
  const resolvedPath = normalize(filePath);
@@ -1001,6 +1291,7 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
1001
1291
  };
1002
1292
  const loader = {
1003
1293
  close() {
1294
+ workers.close();
1004
1295
  moduleCache.clear();
1005
1296
  closeBrowserWxsLoader(loader);
1006
1297
  },
@@ -1113,69 +1404,6 @@ function wechat() {
1113
1404
  return { name: "wechat" };
1114
1405
  }
1115
1406
  //#endregion
1116
- //#region src/kernel/scheduler.ts
1117
- var RuntimeScheduler = class {
1118
- intervals = /* @__PURE__ */ new Set();
1119
- timeouts = /* @__PURE__ */ new Set();
1120
- closed = false;
1121
- onError;
1122
- constructor(onError) {
1123
- this.onError = onError;
1124
- }
1125
- clearInterval(handle) {
1126
- this.intervals.delete(handle);
1127
- clearInterval(handle);
1128
- }
1129
- clearTimeout(handle) {
1130
- this.timeouts.delete(handle);
1131
- clearTimeout(handle);
1132
- }
1133
- close() {
1134
- if (this.closed) return;
1135
- this.closed = true;
1136
- for (const handle of this.intervals) clearInterval(handle);
1137
- for (const handle of this.timeouts) clearTimeout(handle);
1138
- this.intervals.clear();
1139
- this.timeouts.clear();
1140
- }
1141
- queueMicrotask(handler) {
1142
- if (this.closed) throw new Error("Cannot schedule work after the runtime session has closed.");
1143
- queueMicrotask(() => {
1144
- if (this.closed) return;
1145
- try {
1146
- handler();
1147
- } catch (error) {
1148
- this.onError(error);
1149
- }
1150
- });
1151
- }
1152
- setInterval(handler, timeout, ...args) {
1153
- if (this.closed) throw new Error("Cannot schedule work after the runtime session has closed.");
1154
- const handle = setInterval(() => {
1155
- try {
1156
- handler(...args);
1157
- } catch (error) {
1158
- this.onError(error);
1159
- }
1160
- }, timeout);
1161
- this.intervals.add(handle);
1162
- return handle;
1163
- }
1164
- setTimeout(handler, timeout, ...args) {
1165
- if (this.closed) throw new Error("Cannot schedule work after the runtime session has closed.");
1166
- const handle = setTimeout(() => {
1167
- this.timeouts.delete(handle);
1168
- try {
1169
- handler(...args);
1170
- } catch (error) {
1171
- this.onError(error);
1172
- }
1173
- }, timeout);
1174
- this.timeouts.add(handle);
1175
- return handle;
1176
- }
1177
- };
1178
- //#endregion
1179
1407
  //#region src/kernel/runtimeKernel.ts
1180
1408
  var RuntimeKernel = class {
1181
1409
  diagnostics = new RuntimeDiagnostics();
@@ -1759,6 +1987,7 @@ function createComponentInstance(options) {
1759
1987
  const previousProperties = Object.fromEntries(propertyKeys.map((key) => [key, cloneValue(instance.properties[key])]));
1760
1988
  for (const [key, value] of Object.entries(patch)) assignByPath$1(instance.data, key, value);
1761
1989
  for (const key of dataKeys) instance.properties[key] = instance.data[key];
1990
+ synchronizeAttachmentBindings(instance);
1762
1991
  runComponentObservers(definition, instance, changedKeys, previousProperties);
1763
1992
  if (options.requestRender) options.requestRender(callback);
1764
1993
  else callback?.();
@@ -1802,7 +2031,8 @@ function isComponentAttached(instance) {
1802
2031
  return attachmentStates.get(instance) === "attached";
1803
2032
  }
1804
2033
  function hasPendingComponentAttachments(instances) {
1805
- return [...instances].some((instance) => attachmentStates.get(instance) === "attaching");
2034
+ for (const instance of instances) if (attachmentStates.get(instance) === "attaching") return true;
2035
+ return false;
1806
2036
  }
1807
2037
  function flushComponentReady(instances, ready) {
1808
2038
  const all = [...instances];
@@ -1812,19 +2042,71 @@ function flushComponentReady(instances, ready) {
1812
2042
  for (const instance of pending) ready(instance);
1813
2043
  return pending.length > 0;
1814
2044
  }
1815
- function flushComponentAttachments(instances, attach) {
1816
- const pending = [...instances].filter((instance) => !attachmentStates.has(instance));
1817
- for (const instance of pending) attachmentStates.set(instance, "attaching");
2045
+ function flushComponentAttachments(componentCache, scopeIds, attach) {
2046
+ const pending = /* @__PURE__ */ new Map();
2047
+ for (const scopeId of scopeIds) {
2048
+ const instance = componentCache.get(scopeId);
2049
+ if (!instance) continue;
2050
+ const state = attachmentStates.get(instance);
2051
+ if (state === "attaching") return false;
2052
+ if (!state) pending.set(scopeId, instance);
2053
+ }
2054
+ for (const instance of pending.values()) attachmentStates.set(instance, "attaching");
1818
2055
  try {
1819
- for (const instance of pending) try {
1820
- attach(instance);
1821
- } finally {
1822
- attachmentStates.set(instance, "attached");
2056
+ for (const [scopeId, instance] of pending) {
2057
+ if (componentCache.get(scopeId) !== instance) return "restart";
2058
+ let restart;
2059
+ try {
2060
+ restart = attach(instance);
2061
+ } finally {
2062
+ attachmentStates.set(instance, "attached");
2063
+ }
2064
+ if (restart) return "restart";
1823
2065
  }
1824
2066
  } finally {
1825
- for (const instance of pending) if (attachmentStates.get(instance) === "attaching") attachmentStates.delete(instance);
2067
+ for (const instance of pending.values()) if (attachmentStates.get(instance) === "attaching") attachmentStates.delete(instance);
1826
2068
  }
1827
- return pending.length > 0;
2069
+ return pending.size > 0 ? "attached" : false;
2070
+ }
2071
+ //#endregion
2072
+ //#region src/runtime/componentInstance/construction.ts
2073
+ const constructionStates = /* @__PURE__ */ new WeakMap();
2074
+ const constructingInstances = /* @__PURE__ */ new WeakSet();
2075
+ function isComponentConstructing(instance) {
2076
+ return instance !== void 0 && constructingInstances.has(instance);
2077
+ }
2078
+ function hasPendingComponentConstruction(componentCache) {
2079
+ return constructionStates.has(componentCache);
2080
+ }
2081
+ function beginComponentConstruction(componentCache, scopeId, instance) {
2082
+ let state = constructionStates.get(componentCache);
2083
+ if (!state) {
2084
+ state = {
2085
+ depth: 0,
2086
+ created: /* @__PURE__ */ new Map()
2087
+ };
2088
+ constructionStates.set(componentCache, state);
2089
+ }
2090
+ state.depth++;
2091
+ state.created.set(scopeId, instance);
2092
+ constructingInstances.add(instance);
2093
+ }
2094
+ function discardComponentConstruction(componentCache, componentScopes, scopeId) {
2095
+ const state = constructionStates.get(componentCache);
2096
+ const prefix = `${scopeId}/`;
2097
+ for (const [createdScopeId, instance] of state.created) {
2098
+ if (createdScopeId !== scopeId && !createdScopeId.startsWith(prefix)) continue;
2099
+ if (componentCache.get(createdScopeId) === instance) {
2100
+ componentCache.delete(createdScopeId);
2101
+ componentScopes.delete(createdScopeId);
2102
+ }
2103
+ state.created.delete(createdScopeId);
2104
+ }
2105
+ }
2106
+ function finishComponentConstruction(componentCache, instance) {
2107
+ constructingInstances.delete(instance);
2108
+ const state = constructionStates.get(componentCache);
2109
+ if (--state.depth === 0) constructionStates.delete(componentCache);
1828
2110
  }
1829
2111
  //#endregion
1830
2112
  //#region src/runtime/componentInstance/discardedReady.ts
@@ -1847,12 +2129,41 @@ function flushDiscardedComponentReady(cache, pageScopeId, ready) {
1847
2129
  if (!pending.size) discardedReady.delete(cache);
1848
2130
  }
1849
2131
  //#endregion
2132
+ //#region src/runtime/componentInstance/propertyBindings.ts
2133
+ const consumedPageChanges = /* @__PURE__ */ new WeakMap();
2134
+ function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys, beforeObservers) {
2135
+ const freshPageChanges = changedPageKeys.length > 0 && consumedPageChanges.get(instance) !== changedPageKeys;
2136
+ if (freshPageChanges) consumedPageChanges.set(instance, changedPageKeys);
2137
+ const changedRootKeys = [];
2138
+ const previousProperties = {};
2139
+ for (const [key, value] of Object.entries(nextProperties)) {
2140
+ const nextValue = normalizeComponentPropertyValue(definition, key, value);
2141
+ const bindingExpression = bindingExpressions[key];
2142
+ const bindingAffected = freshPageChanges && !!bindingExpression && changedPageKeys.some((changedKey) => {
2143
+ return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
2144
+ });
2145
+ const previousSnapshot = instance.__propertySnapshots?.[key];
2146
+ if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
2147
+ previousProperties[key] = instance.properties[key];
2148
+ const deliveredValue = cloneValue(nextValue);
2149
+ instance.properties[key] = deliveredValue;
2150
+ if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = deliveredValue;
2151
+ changedRootKeys.push(key);
2152
+ }
2153
+ instance.__propertySnapshots ??= {};
2154
+ instance.__propertySnapshots[key] = cloneValue(nextValue);
2155
+ }
2156
+ if (changedRootKeys.length === 0) return;
2157
+ beforeObservers?.(instance, "properties");
2158
+ runComponentObservers(definition, instance, changedRootKeys, previousProperties);
2159
+ }
2160
+ //#endregion
1850
2161
  //#region src/runtime/pageLifecycle.ts
1851
2162
  const loadingPages = /* @__PURE__ */ new WeakSet();
1852
2163
  function isPageBeforeReady(page) {
1853
2164
  return loadingPages.has(page);
1854
2165
  }
1855
- function runInitialPageLifecycles(page, query, scheduler, isAlive, renderComponents) {
2166
+ function runInitialPageLifecycles(page, query, scheduler, isAlive, renderComponents, onReady) {
1856
2167
  loadingPages.add(page);
1857
2168
  try {
1858
2169
  renderComponents?.();
@@ -1867,10 +2178,269 @@ function runInitialPageLifecycles(page, query, scheduler, isAlive, renderCompone
1867
2178
  scheduler.setTimeout(() => {
1868
2179
  if (!isAlive()) return;
1869
2180
  page.onReady?.();
1870
- if (isAlive()) page.onRouteDone?.({});
2181
+ if (isAlive()) {
2182
+ page.onRouteDone?.({});
2183
+ onReady?.();
2184
+ }
1871
2185
  }, 0);
1872
2186
  }
1873
2187
  //#endregion
2188
+ //#region src/view/eventBindingParser.ts
2189
+ const LEGACY_EVENT_NAME_RE = /^\w+$/;
2190
+ const EVENT_BINDING_PREFIXES = [
2191
+ {
2192
+ prefix: "capture-bind:",
2193
+ priority: 0,
2194
+ stopAfter: false,
2195
+ phase: "capture"
2196
+ },
2197
+ {
2198
+ prefix: "capture-catch:",
2199
+ priority: 0,
2200
+ stopAfter: true,
2201
+ phase: "capture"
2202
+ },
2203
+ {
2204
+ prefix: "capture-bind",
2205
+ priority: 1,
2206
+ stopAfter: false,
2207
+ phase: "capture"
2208
+ },
2209
+ {
2210
+ prefix: "capture-catch",
2211
+ priority: 1,
2212
+ stopAfter: true,
2213
+ phase: "capture"
2214
+ },
2215
+ {
2216
+ prefix: "bind:",
2217
+ priority: 0,
2218
+ stopAfter: false,
2219
+ phase: "bubble"
2220
+ },
2221
+ {
2222
+ prefix: "catch:",
2223
+ priority: 0,
2224
+ stopAfter: true,
2225
+ phase: "bubble"
2226
+ },
2227
+ {
2228
+ prefix: "bind",
2229
+ priority: 1,
2230
+ stopAfter: false,
2231
+ phase: "bubble"
2232
+ },
2233
+ {
2234
+ prefix: "catch",
2235
+ priority: 1,
2236
+ stopAfter: true,
2237
+ phase: "bubble"
2238
+ }
2239
+ ];
2240
+ function parseEventBinding(attributeName, method) {
2241
+ const definition = EVENT_BINDING_PREFIXES.find((item) => attributeName.startsWith(item.prefix));
2242
+ if (!definition) return null;
2243
+ const eventName = attributeName.slice(definition.prefix.length);
2244
+ if (!eventName || !definition.prefix.endsWith(":") && !LEGACY_EVENT_NAME_RE.test(eventName)) return null;
2245
+ return {
2246
+ eventName,
2247
+ method,
2248
+ phase: definition.phase,
2249
+ priority: definition.priority,
2250
+ stopAfter: definition.stopAfter
2251
+ };
2252
+ }
2253
+ function collectEventBindings(attributes = {}, includeCapture = true) {
2254
+ const eventBindings = /* @__PURE__ */ new Map();
2255
+ let captureEventBindings;
2256
+ const priorities = /* @__PURE__ */ new Map();
2257
+ for (const [attributeName, method] of Object.entries(attributes)) {
2258
+ const candidate = parseEventBinding(attributeName, method);
2259
+ if (!candidate || !includeCapture && candidate.phase === "capture") continue;
2260
+ const eventPriorities = priorities.get(candidate.eventName) ?? {};
2261
+ if (candidate.priority < (eventPriorities[candidate.phase] ?? -1)) continue;
2262
+ (candidate.phase === "bubble" ? eventBindings : captureEventBindings ??= /* @__PURE__ */ new Map()).set(candidate.eventName, {
2263
+ method: candidate.method,
2264
+ stopAfter: candidate.stopAfter
2265
+ });
2266
+ eventPriorities[candidate.phase] = candidate.priority;
2267
+ priorities.set(candidate.eventName, eventPriorities);
2268
+ }
2269
+ return {
2270
+ eventBindings,
2271
+ captureEventBindings
2272
+ };
2273
+ }
2274
+ /** 单事件查询只保留命中的绑定,原生交互不构造整张事件表。 */
2275
+ function resolveEventBindingPhases(attributes, eventName, includeCapture = true) {
2276
+ if (!attributes) return null;
2277
+ let bindings = null;
2278
+ let bubblePriority = -1;
2279
+ let capturePriority = -1;
2280
+ for (const [attributeName, method] of Object.entries(attributes)) {
2281
+ const candidate = parseEventBinding(attributeName, method);
2282
+ if (!candidate || candidate.eventName !== eventName || !includeCapture && candidate.phase === "capture") continue;
2283
+ const priority = candidate.phase === "bubble" ? bubblePriority : capturePriority;
2284
+ if (candidate.priority < priority) continue;
2285
+ bindings ??= {};
2286
+ bindings[candidate.phase] = {
2287
+ method: candidate.method,
2288
+ stopAfter: candidate.stopAfter
2289
+ };
2290
+ if (candidate.phase === "bubble") bubblePriority = candidate.priority;
2291
+ else capturePriority = candidate.priority;
2292
+ }
2293
+ return bindings;
2294
+ }
2295
+ //#endregion
2296
+ //#region src/view/nodeDataset.ts
2297
+ const DATASET_NAME_RE = /-([a-z])/g;
2298
+ function isDatasetAttribute(attributeName) {
2299
+ return attributeName.startsWith("data-") && !attributeName.startsWith("data-sim-");
2300
+ }
2301
+ function toDatasetKey(attributeName) {
2302
+ return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
2303
+ }
2304
+ function collectNodeDataset(node) {
2305
+ if (node.dataset) return { ...node.dataset };
2306
+ const dataset = {};
2307
+ for (const [key, value] of Object.entries(node.attribs ?? {})) if (isDatasetAttribute(key)) dataset[toDatasetKey(key)] = value;
2308
+ return dataset;
2309
+ }
2310
+ //#endregion
2311
+ //#region src/view/componentEvent.ts
2312
+ const eventNodes = /* @__PURE__ */ new WeakMap();
2313
+ /** 在构造子树之前建立父链,created/observer 中的事件也能访问声明树。 */
2314
+ function registerComponentEventNode(node, scope, parent) {
2315
+ node.parent = parent ?? null;
2316
+ eventNodes.set(node, {
2317
+ scope,
2318
+ target: node
2319
+ });
2320
+ }
2321
+ /** 宿主与作用域共享同一份分阶段绑定,eventBindings 仍是原有的冒泡存储。 */
2322
+ function bindComponentEventHost(node) {
2323
+ const bindings = collectEventBindings(node.attribs);
2324
+ eventNodes.get(node).bindings = bindings;
2325
+ return bindings;
2326
+ }
2327
+ /** 渲染会把宿主折叠进模板根;事件仍保留两层独立的绑定和声明所有者。 */
2328
+ function mergeComponentEventRoot(root, host) {
2329
+ const entry = eventNodes.get(root);
2330
+ if (entry.target === root) entry.target = {
2331
+ attribs: root.attribs,
2332
+ dataset: root.dataset
2333
+ };
2334
+ entry.hosts ??= [];
2335
+ entry.hosts.push(host);
2336
+ root.parent = host.parent;
2337
+ }
2338
+ /** 按渲染完成后的实际宿主父链排序;输入只包含本轮存活的组件作用域。 */
2339
+ function orderComponentAttachmentScopes(scopeIds, componentScopes) {
2340
+ const hostScopes = /* @__PURE__ */ new Map();
2341
+ for (const scopeId of scopeIds) hostScopes.set(componentScopes.get(scopeId).hostNode, scopeId);
2342
+ const ordered = [];
2343
+ const visited = /* @__PURE__ */ new Set();
2344
+ const visit = (node) => {
2345
+ if (!node || visited.has(node)) return;
2346
+ visited.add(node);
2347
+ visit(node.parent);
2348
+ const hosts = eventNodes.get(node)?.hosts;
2349
+ if (hosts) for (let index = hosts.length - 1; index >= 0; index--) visit(hosts[index]);
2350
+ const scopeId = hostScopes.get(node);
2351
+ if (scopeId !== void 0) ordered.push(scopeId);
2352
+ };
2353
+ for (const host of hostScopes.keys()) visit(host);
2354
+ return ordered;
2355
+ }
2356
+ function buildComponentTrigger(componentScopeId, context) {
2357
+ return (instance, eventName, detail, triggerOptions) => {
2358
+ const originScope = context.componentScopes.get(componentScopeId);
2359
+ const origin = originScope?.hostNode;
2360
+ if (!originScope || !origin) return;
2361
+ const bubbles = triggerOptions?.bubbles ?? false;
2362
+ const capturePhase = triggerOptions?.capturePhase ?? false;
2363
+ const composed = triggerOptions?.composed ?? false;
2364
+ const target = {
2365
+ dataset: originScope.dataset ?? collectNodeDataset(origin),
2366
+ id: originScope.hostId ?? ""
2367
+ };
2368
+ const mark = instance.__lastInteractionEvent__?.mark;
2369
+ const listeners = [];
2370
+ const collect = (entry, isOrigin) => {
2371
+ if (!composed && entry.scope.getScopeId() !== originScope.listenerScopeId) return false;
2372
+ const bindings = entry.bindings ? {
2373
+ bubble: entry.bindings.eventBindings?.get(eventName),
2374
+ capture: entry.bindings.captureEventBindings?.get(eventName)
2375
+ } : resolveEventBindingPhases(entry.target.attribs, eventName);
2376
+ if (bindings?.bubble || bindings?.capture) listeners.push({
2377
+ scope: entry.scope,
2378
+ bindings,
2379
+ currentTarget: isOrigin ? target : {
2380
+ dataset: collectNodeDataset(entry.target),
2381
+ id: entry.target.attribs?.id ?? ""
2382
+ },
2383
+ origin: isOrigin
2384
+ });
2385
+ return true;
2386
+ };
2387
+ let current = origin;
2388
+ while (current) {
2389
+ const entry = eventNodes.get(current);
2390
+ if (entry) {
2391
+ if (!collect(entry, current === origin)) break;
2392
+ let crossedBoundary = false;
2393
+ for (const host of entry.hosts ?? []) if (!collect(eventNodes.get(host), false)) {
2394
+ crossedBoundary = true;
2395
+ break;
2396
+ }
2397
+ if (crossedBoundary) break;
2398
+ }
2399
+ if (!bubbles && !capturePhase) break;
2400
+ current = current.parent;
2401
+ }
2402
+ const handlers = [];
2403
+ let stopped = false;
2404
+ if (capturePhase) for (let index = listeners.length - 1; index >= 0; index--) {
2405
+ const listener = listeners[index];
2406
+ const binding = listener.bindings.capture;
2407
+ if (binding) {
2408
+ handlers.push({
2409
+ scope: listener.scope,
2410
+ binding,
2411
+ currentTarget: listener.currentTarget
2412
+ });
2413
+ if (binding.stopAfter) {
2414
+ stopped = true;
2415
+ break;
2416
+ }
2417
+ }
2418
+ }
2419
+ if (!stopped) for (const listener of listeners) {
2420
+ if (!bubbles && !listener.origin) continue;
2421
+ const binding = listener.bindings.bubble;
2422
+ if (binding) {
2423
+ handlers.push({
2424
+ scope: listener.scope,
2425
+ binding,
2426
+ currentTarget: listener.currentTarget
2427
+ });
2428
+ if (binding.stopAfter) break;
2429
+ }
2430
+ }
2431
+ for (const { scope, binding, currentTarget } of handlers) scope.getMethod(binding.method)?.({
2432
+ bubbles,
2433
+ capturePhase,
2434
+ composed,
2435
+ currentTarget,
2436
+ detail,
2437
+ mark,
2438
+ target,
2439
+ type: eventName
2440
+ });
2441
+ };
2442
+ }
2443
+ //#endregion
1874
2444
  //#region src/view/conditionalChildren.ts
1875
2445
  function selectConditionalChildren(children, evaluate) {
1876
2446
  const selected = [];
@@ -1926,11 +2496,77 @@ function customTabBarHostScope() {
1926
2496
  };
1927
2497
  }
1928
2498
  //#endregion
2499
+ //#region src/view/inspectionTree.ts
2500
+ const inspectionChildren = /* @__PURE__ */ new WeakMap();
2501
+ const inspectionParents = /* @__PURE__ */ new WeakMap();
2502
+ const emptyChildren = [];
2503
+ function getInspectionChildren(node) {
2504
+ return inspectionChildren.get(node) ?? node.children ?? emptyChildren;
2505
+ }
2506
+ function getInspectionParent(node) {
2507
+ return inspectionParents.get(node) ?? node.parent ?? null;
2508
+ }
2509
+ function collectRenderedNodes(node, nodes) {
2510
+ if (nodes.has(node)) return;
2511
+ nodes.add(node);
2512
+ for (const child of node.children ?? emptyChildren) collectRenderedNodes(child, nodes);
2513
+ }
2514
+ /** 原生检查器保留未投影声明;可见 DOM、WXML 和事件父链不因此增加节点。 */
2515
+ function registerInspectionTrees(root, pass, scopes) {
2516
+ if (!pass.hasUnprojectedSlots) return;
2517
+ const rendered = /* @__PURE__ */ new Set();
2518
+ collectRenderedNodes(root, rendered);
2519
+ const candidates = /* @__PURE__ */ new Map();
2520
+ for (const [entries, group] of pass.slotDeclarations) {
2521
+ if (scopes.get(group.scopeId)?.hostNode !== group.parent) continue;
2522
+ const host = pass.componentRoots.get(group.scopeId);
2523
+ if (!host) continue;
2524
+ for (const entry of entries) for (const node of pass.renderedSlots.get(entry) ?? emptyChildren) candidates.set(node, host);
2525
+ }
2526
+ const nested = /* @__PURE__ */ new Set();
2527
+ const visited = /* @__PURE__ */ new Set();
2528
+ const indexChildren = (node) => {
2529
+ if (visited.has(node)) return;
2530
+ visited.add(node);
2531
+ for (const child of node.children ?? emptyChildren) {
2532
+ nested.add(child);
2533
+ if (!rendered.has(child)) inspectionParents.set(child, node);
2534
+ indexChildren(child);
2535
+ }
2536
+ };
2537
+ for (const node of candidates.keys()) indexChildren(node);
2538
+ for (const [node, host] of candidates) {
2539
+ if (rendered.has(node) || nested.has(node) || node === host) continue;
2540
+ let children = inspectionChildren.get(host);
2541
+ if (!children) {
2542
+ children = [...host.children ?? emptyChildren];
2543
+ inspectionChildren.set(host, children);
2544
+ }
2545
+ children.push(node);
2546
+ inspectionParents.set(node, host);
2547
+ }
2548
+ }
2549
+ //#endregion
1929
2550
  //#region src/view/loopEntries.ts
2551
+ const LOOP_SCOPE_ESCAPE_RE = /[^\w-]/g;
2552
+ function escapeScopeCodeUnit(character) {
2553
+ return `~${character.charCodeAt(0).toString(16).padStart(4, "0")}`;
2554
+ }
2555
+ function encodeLoopCoordinate(value) {
2556
+ return value.replace(LOOP_SCOPE_ESCAPE_RE, escapeScopeCodeUnit);
2557
+ }
1930
2558
  function resolveLoopEntries(value) {
1931
2559
  if (Array.isArray(value)) return value.map((item, index) => [index, item]);
1932
2560
  return value !== null && typeof value === "object" ? Object.entries(value) : [];
1933
2561
  }
2562
+ function resolveLoopInstanceSuffix(item, index, key, occurrences) {
2563
+ if (!key || !occurrences) return `:for-${encodeLoopCoordinate(String(index))}`;
2564
+ const value = key === "*this" ? item : item?.[key];
2565
+ const normalized = encodeLoopCoordinate(String(value ?? ""));
2566
+ const occurrence = occurrences.get(normalized) ?? 0;
2567
+ occurrences.set(normalized, occurrence + 1);
2568
+ return `:key-${normalized}${occurrence ? `:duplicate-${occurrence}` : ""}`;
2569
+ }
1934
2570
  //#endregion
1935
2571
  //#region src/view/renderedTree.ts
1936
2572
  /** 在循环展开和组件替换完成后,让父节点关系指向本次渲染树。 */
@@ -1939,6 +2575,86 @@ function linkRenderedParents(root, parent = null) {
1939
2575
  for (const child of root.children ?? []) linkRenderedParents(child, root);
1940
2576
  }
1941
2577
  //#endregion
2578
+ //#region src/view/renderPass.ts
2579
+ const initializedPages = /* @__PURE__ */ new WeakMap();
2580
+ function createRenderPass(propertyUpdate = false, parent) {
2581
+ return {
2582
+ seenComponentScopes: /* @__PURE__ */ new Set(),
2583
+ componentRoots: /* @__PURE__ */ new Map(),
2584
+ slotDeclarations: /* @__PURE__ */ new Map(),
2585
+ renderedSlots: /* @__PURE__ */ new Map(),
2586
+ hasUnprojectedSlots: false,
2587
+ propertyUpdate,
2588
+ bindingUpdate: parent?.bindingUpdate,
2589
+ bindingRevision: parent?.bindingUpdate?.revision ?? 0
2590
+ };
2591
+ }
2592
+ function createPageRenderPass(page, cache) {
2593
+ const pass = createRenderPass(initializedPages.get(cache)?.has(page) ?? false);
2594
+ pass.bindingUpdate = getAttachmentBindingRevision(page);
2595
+ pass.bindingRevision = pass.bindingUpdate?.revision ?? 0;
2596
+ return pass;
2597
+ }
2598
+ function isRenderPassStale(pass) {
2599
+ return pass.bindingUpdate !== void 0 && pass.bindingUpdate.revision !== pass.bindingRevision;
2600
+ }
2601
+ function markPageTreeConstructed(page, cache) {
2602
+ let pages = initializedPages.get(cache);
2603
+ if (!pages) {
2604
+ pages = /* @__PURE__ */ new WeakSet();
2605
+ initializedPages.set(cache, pages);
2606
+ }
2607
+ pages.add(page);
2608
+ }
2609
+ function registerSlotDeclarations(pass, slots, parent, scopeId) {
2610
+ for (const entries of slots.values()) if (!pass.slotDeclarations.has(entries)) pass.slotDeclarations.set(entries, {
2611
+ parent,
2612
+ scopeId
2613
+ });
2614
+ }
2615
+ //#endregion
2616
+ //#region src/view/templateInterpolation.ts
2617
+ /** 按表达式词法寻找插值边界,字符串和对象内部的大括号不结束绑定。 */
2618
+ function templateInterpolations(source) {
2619
+ const ranges = [];
2620
+ let offset = 0;
2621
+ while (offset < source.length) {
2622
+ const start = source.indexOf("{{", offset);
2623
+ if (start < 0) break;
2624
+ let quote;
2625
+ let depth = 0;
2626
+ let closed = false;
2627
+ for (let i = start + 2; i < source.length; i++) {
2628
+ const char = source[i];
2629
+ if (quote) {
2630
+ if (char === "\\") i++;
2631
+ else if (char === quote) quote = void 0;
2632
+ } else if (char === "'" || char === "\"") quote = char;
2633
+ else if (char === "{") depth++;
2634
+ else if (char === "}") {
2635
+ if (depth === 0 && source[i + 1] === "}") {
2636
+ ranges.push({
2637
+ start,
2638
+ end: i + 2,
2639
+ expression: source.slice(start + 2, i)
2640
+ });
2641
+ offset = i + 2;
2642
+ closed = true;
2643
+ break;
2644
+ }
2645
+ depth--;
2646
+ }
2647
+ }
2648
+ if (!closed) break;
2649
+ }
2650
+ return ranges;
2651
+ }
2652
+ function isTemplateExpression(value) {
2653
+ const trimmed = value.trim();
2654
+ const ranges = templateInterpolations(trimmed);
2655
+ return ranges.length === 1 && ranges[0].start === 0 && ranges[0].end === trimmed.length;
2656
+ }
2657
+ //#endregion
1942
2658
  //#region src/view/templateExpression.ts
1943
2659
  const expressionCache = /* @__PURE__ */ new Map();
1944
2660
  const BLOCKED_MEMBER_KEYS = /* @__PURE__ */ new Set([
@@ -1947,13 +2663,9 @@ const BLOCKED_MEMBER_KEYS = /* @__PURE__ */ new Set([
1947
2663
  "prototype"
1948
2664
  ]);
1949
2665
  const NUMERIC_DOT_PATH_RE = /\.(\d+)(?=[.[\s,}\]]|$)/g;
1950
- function isMustacheOnly$3(value) {
1951
- const trimmed = value.trim();
1952
- return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
1953
- }
1954
2666
  function unwrapMustacheExpression(expression) {
1955
2667
  const normalized = expression.trim();
1956
- if (isMustacheOnly$3(normalized)) return normalized.slice(2, -2).trim();
2668
+ if (isTemplateExpression(normalized)) return normalized.slice(2, -2).trim();
1957
2669
  return normalized;
1958
2670
  }
1959
2671
  function parseTemplateExpression(expression) {
@@ -2180,99 +2892,45 @@ function resolveBrowserPageStyles(files, route, options = {}) {
2180
2892
  };
2181
2893
  }
2182
2894
  //#endregion
2183
- //#region src/browser/styles/componentPage.ts
2184
- /** 已确认的 Component 页面使用最终 JSON 覆盖定义选项,普通 Page 不参与组件隔离。 */
2185
- function resolveBrowserComponentPageStyleIsolation(files, page, route, miniprogramRootPath) {
2186
- if (!isComponentPageInstance(page)) return;
2187
- const definitionIsolation = getComponentPageStyleIsolation(page);
2188
- const filename = `${route}.json`;
2189
- const source = readBrowserVirtualFile(files, join(miniprogramRootPath, filename));
2190
- if (source === void 0) return definitionIsolation;
2191
- let config;
2192
- try {
2193
- config = JSON.parse(source);
2194
- } catch {
2195
- throw new Error(`Invalid browser Component page JSON: ${filename}`);
2196
- }
2197
- if (!config || typeof config !== "object" || Array.isArray(config)) throw new Error(`Invalid browser Component page JSON: ${filename}`);
2198
- const isolation = "styleIsolation" in config ? config.styleIsolation : void 0;
2199
- return isolation === void 0 ? definitionIsolation : typeof isolation === "string" ? isolation : void 0;
2200
- }
2201
- //#endregion
2202
- //#region src/runtime/componentInstance/selection.ts
2203
- function hasExportBehavior(definition, visited = /* @__PURE__ */ new Set()) {
2204
- if (visited.has(definition)) return false;
2205
- visited.add(definition);
2206
- return (Array.isArray(definition.behaviors) ? definition.behaviors : []).some((behavior) => behavior === "wx://component-export" || behavior !== null && typeof behavior === "object" && hasExportBehavior(behavior, visited));
2207
- }
2208
- /** 原生选择器尊重组件导出行为;测试桥接继续保留完整组件实例。 */
2209
- function resolveNativeComponentSelection(instance) {
2210
- if (!instance) return null;
2211
- const definition = instance.__definition__;
2212
- if (!definition || !hasExportBehavior(definition) || typeof instance.export !== "function") return instance;
2213
- return instance.export();
2214
- }
2215
- //#endregion
2216
- //#region src/runtime/componentResolution.ts
2217
- function resolveMiniProgramComponent(ownerFilePath, request, miniprogramRootPath, hasFile) {
2218
- const localPath = request.startsWith("/") ? request.replace(/^\/+/, "") : join(dirname(ownerFilePath), request);
2219
- if (request.startsWith("/") || request.startsWith(".") || hasFile(join(miniprogramRootPath, `${localPath}.js`))) return localPath;
2220
- const npmPath = resolveMiniProgramModule(join(miniprogramRootPath, ownerFilePath), request, miniprogramRootPath, (candidate) => candidate.endsWith(".js") && hasFile(candidate));
2221
- return npmPath ? relative(miniprogramRootPath, npmPath).slice(0, -3) : localPath;
2222
- }
2223
- //#endregion
2224
- //#region src/view/eventBinding.ts
2225
- const LEGACY_EVENT_NAME_RE = /^\w+$/;
2226
- const EVENT_BINDING_PREFIXES = [
2227
- {
2228
- prefix: "bind:",
2229
- priority: 0,
2230
- stopAfter: false
2231
- },
2232
- {
2233
- prefix: "catch:",
2234
- priority: 0,
2235
- stopAfter: true
2236
- },
2237
- {
2238
- prefix: "bind",
2239
- priority: 1,
2240
- stopAfter: false
2241
- },
2242
- {
2243
- prefix: "catch",
2244
- priority: 1,
2245
- stopAfter: true
2246
- }
2247
- ];
2248
- function parseEventBinding(attributeName, method) {
2249
- const definition = EVENT_BINDING_PREFIXES.find((item) => attributeName.startsWith(item.prefix));
2250
- if (!definition) return null;
2251
- const eventName = attributeName.slice(definition.prefix.length);
2252
- if (!eventName || !definition.prefix.endsWith(":") && !LEGACY_EVENT_NAME_RE.test(eventName)) return null;
2253
- return {
2254
- eventName,
2255
- method,
2256
- priority: definition.priority,
2257
- stopAfter: definition.stopAfter
2258
- };
2259
- }
2260
- function collectMiniProgramEventBindings(attributes = {}) {
2261
- const bindings = /* @__PURE__ */ new Map();
2262
- const priorities = /* @__PURE__ */ new Map();
2263
- for (const [attributeName, method] of Object.entries(attributes)) {
2264
- const candidate = parseEventBinding(attributeName, method);
2265
- if (!candidate || candidate.priority < (priorities.get(candidate.eventName) ?? -1)) continue;
2266
- bindings.set(candidate.eventName, {
2267
- method: candidate.method,
2268
- stopAfter: candidate.stopAfter
2269
- });
2270
- priorities.set(candidate.eventName, candidate.priority);
2895
+ //#region src/browser/styles/componentPage.ts
2896
+ /** 已确认的 Component 页面使用最终 JSON 覆盖定义选项,普通 Page 不参与组件隔离。 */
2897
+ function resolveBrowserComponentPageStyleIsolation(files, page, route, miniprogramRootPath) {
2898
+ if (!isComponentPageInstance(page)) return;
2899
+ const definitionIsolation = getComponentPageStyleIsolation(page);
2900
+ const filename = `${route}.json`;
2901
+ const source = readBrowserVirtualFile(files, join(miniprogramRootPath, filename));
2902
+ if (source === void 0) return definitionIsolation;
2903
+ let config;
2904
+ try {
2905
+ config = JSON.parse(source);
2906
+ } catch {
2907
+ throw new Error(`Invalid browser Component page JSON: ${filename}`);
2271
2908
  }
2272
- return bindings;
2909
+ if (!config || typeof config !== "object" || Array.isArray(config)) throw new Error(`Invalid browser Component page JSON: ${filename}`);
2910
+ const isolation = "styleIsolation" in config ? config.styleIsolation : void 0;
2911
+ return isolation === void 0 ? definitionIsolation : typeof isolation === "string" ? isolation : void 0;
2273
2912
  }
2274
- function resolveMiniProgramEventBinding(attributes, eventName) {
2275
- return collectMiniProgramEventBindings(attributes).get(eventName) ?? null;
2913
+ //#endregion
2914
+ //#region src/runtime/componentInstance/selection.ts
2915
+ function hasExportBehavior(definition, visited = /* @__PURE__ */ new Set()) {
2916
+ if (visited.has(definition)) return false;
2917
+ visited.add(definition);
2918
+ return (Array.isArray(definition.behaviors) ? definition.behaviors : []).some((behavior) => behavior === "wx://component-export" || behavior !== null && typeof behavior === "object" && hasExportBehavior(behavior, visited));
2919
+ }
2920
+ /** 原生选择器尊重组件导出行为;测试桥接继续保留完整组件实例。 */
2921
+ function resolveNativeComponentSelection(instance) {
2922
+ if (!instance) return null;
2923
+ const definition = instance.__definition__;
2924
+ if (!definition || !hasExportBehavior(definition) || typeof instance.export !== "function") return instance;
2925
+ return instance.export();
2926
+ }
2927
+ //#endregion
2928
+ //#region src/runtime/componentResolution.ts
2929
+ function resolveMiniProgramComponent(ownerFilePath, request, miniprogramRootPath, hasFile) {
2930
+ const localPath = request.startsWith("/") ? request.replace(/^\/+/, "") : join(dirname(ownerFilePath), request);
2931
+ if (request.startsWith("/") || request.startsWith(".") || hasFile(join(miniprogramRootPath, `${localPath}.js`))) return localPath;
2932
+ const npmPath = resolveMiniProgramModule(join(miniprogramRootPath, ownerFilePath), request, miniprogramRootPath, (candidate) => candidate.endsWith(".js") && hasFile(candidate));
2933
+ return npmPath ? relative(miniprogramRootPath, npmPath).slice(0, -3) : localPath;
2276
2934
  }
2277
2935
  //#endregion
2278
2936
  //#region src/view/selectorQueryScope.ts
@@ -2334,21 +2992,6 @@ function resolveSelectorQueryScopeSnapshot(scope, snapshots) {
2334
2992
  return null;
2335
2993
  }
2336
2994
  //#endregion
2337
- //#region src/view/nodeDataset.ts
2338
- const DATASET_NAME_RE = /-([a-z])/g;
2339
- function isDatasetAttribute(attributeName) {
2340
- return attributeName.startsWith("data-") && !attributeName.startsWith("data-sim-");
2341
- }
2342
- function toDatasetKey(attributeName) {
2343
- return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
2344
- }
2345
- function collectNodeDataset(node) {
2346
- if (node.dataset) return { ...node.dataset };
2347
- const dataset = {};
2348
- for (const [key, value] of Object.entries(node.attribs ?? {})) if (isDatasetAttribute(key)) dataset[toDatasetKey(key)] = value;
2349
- return dataset;
2350
- }
2351
- //#endregion
2352
2995
  //#region src/view/templateImports.ts
2353
2996
  function createImportedTemplateState(root, filePath, loadImport, loadWxs) {
2354
2997
  const documents = /* @__PURE__ */ new Map();
@@ -2400,12 +3043,65 @@ function createImportedTemplateState(root, filePath, loadImport, loadWxs) {
2400
3043
  }
2401
3044
  //#endregion
2402
3045
  //#region src/view/templateText.ts
2403
- const TEMPLATE_INTERPOLATION_RE$3 = /\{\{([^{}]+)\}\}/g;
2404
- function interpolateTemplateText(input, data) {
2405
- return input.replace(TEMPLATE_INTERPOLATION_RE$3, (_match, expression) => {
2406
- const value = resolveTemplateExpression(data, expression);
2407
- return value === void 0 ? "" : String(value);
2408
- });
3046
+ function interpolateTemplateText(input, data, emptyNull = false) {
3047
+ let output = "";
3048
+ let offset = 0;
3049
+ for (const range of templateInterpolations(input)) {
3050
+ const value = resolveTemplateExpression(data, range.expression);
3051
+ output += input.slice(offset, range.start) + (value === void 0 || emptyNull && value === null ? "" : String(value));
3052
+ offset = range.end;
3053
+ }
3054
+ return output + input.slice(offset);
3055
+ }
3056
+ //#endregion
3057
+ //#region src/view/templateAttributes.ts
3058
+ function decodeAttribute(raw, quote) {
3059
+ const source = raw.replaceAll(`\\${quote}`, quote);
3060
+ let value = "";
3061
+ let offset = 0;
3062
+ for (const range of templateInterpolations(source)) {
3063
+ value += source.slice(offset, range.start).replace(/\\([\s\S])/g, "$1");
3064
+ value += source.slice(range.start, range.end);
3065
+ offset = range.end;
3066
+ }
3067
+ return value + source.slice(offset).replace(/\\([\s\S])/g, "$1");
3068
+ }
3069
+ /** 先保存 WXML 属性词法值,再交给 HTML parser 构建标签树,避免反斜杠引号提前截断属性。 */
3070
+ function maskTemplateAttributes(source) {
3071
+ const attributes = /* @__PURE__ */ new Map();
3072
+ if (!source.includes("\\")) return {
3073
+ source,
3074
+ attributes
3075
+ };
3076
+ let prefix = "__mpcore_quoted_attribute_";
3077
+ while (source.includes(prefix)) prefix += "_";
3078
+ let output = "";
3079
+ let offset = 0;
3080
+ for (let i = 0; i < source.length; i++) {
3081
+ if (source.startsWith("<!--", i)) {
3082
+ const end = source.indexOf("-->", i + 4);
3083
+ i = end < 0 ? source.length : end + 2;
3084
+ continue;
3085
+ }
3086
+ if (source[i] !== "<" || !/[a-z_]/i.test(source[i + 1] ?? "")) continue;
3087
+ for (i++; i < source.length && source[i] !== ">"; i++) {
3088
+ if (source[i] !== "\"" && source[i] !== "'") continue;
3089
+ const quote = source[i];
3090
+ const start = i + 1;
3091
+ for (i++; i < source.length && source[i] !== quote; i++) if (source[i] === "\\") i++;
3092
+ if (i >= source.length) break;
3093
+ const raw = source.slice(start, i);
3094
+ if (!raw.includes("\\")) continue;
3095
+ const token = `${prefix}${attributes.size}`;
3096
+ attributes.set(token, decodeAttribute(raw, quote));
3097
+ output += source.slice(offset, start) + token;
3098
+ offset = i;
3099
+ }
3100
+ }
3101
+ return {
3102
+ source: output + source.slice(offset),
3103
+ attributes
3104
+ };
2409
3105
  }
2410
3106
  //#endregion
2411
3107
  //#region src/view/wxsDocument.ts
@@ -2415,18 +3111,26 @@ function parseWxsTemplateDocument(templateSource) {
2415
3111
  const source = templateSource.replace(INLINE_WXS_RE, (_match, attributes, script) => {
2416
3112
  return `<wxs data-sim-wxs="${scripts.push(script) - 1}"${attributes}>wxs-source</wxs>`;
2417
3113
  });
2418
- const document = parseDocument(`<page>${source}</page>`, {
3114
+ const masked = maskTemplateAttributes(source);
3115
+ const document = parseDocument(`<page>${masked.source}</page>`, {
2419
3116
  xmlMode: false,
2420
3117
  decodeEntities: false,
2421
3118
  lowerCaseAttributeNames: false,
2422
3119
  lowerCaseTags: false,
2423
3120
  recognizeSelfClosing: true
2424
3121
  });
3122
+ if (!scripts.length && !masked.attributes.size && !/[\r\n]/.test(source)) return document;
3123
+ const hasAttributes = masked.attributes.size > 0;
2425
3124
  const restore = (node) => {
3125
+ if (hasAttributes && node.attribs) {
3126
+ for (const [name, token] of Object.entries(node.attribs)) if (masked.attributes.has(token)) node.attribs[name] = masked.attributes.get(token);
3127
+ }
2426
3128
  if (node.name === "wxs" && Object.hasOwn(node.attribs ?? {}, "data-sim-wxs")) {
2427
3129
  node.children[0].data = scripts[Number(node.attribs["data-sim-wxs"])];
2428
3130
  delete node.attribs["data-sim-wxs"];
3131
+ return;
2429
3132
  }
3133
+ if (node.children) node.children = node.children.filter((child) => child.type !== "text" || !/^[\t\r\n ]+$/.test(child.data ?? "") || !/[\r\n]/.test(child.data ?? ""));
2430
3134
  for (const child of node.children ?? []) restore(child);
2431
3135
  };
2432
3136
  restore(document);
@@ -2434,7 +3138,6 @@ function parseWxsTemplateDocument(templateSource) {
2434
3138
  }
2435
3139
  //#endregion
2436
3140
  //#region src/browser/render/shared.ts
2437
- const TEMPLATE_INTERPOLATION_RE$2 = /\{\{([^{}]+)\}\}/g;
2438
3141
  const LEADING_SLASH_RE$5 = /^\/+/;
2439
3142
  const EVENT_BINDING_ATTRS$1 = [
2440
3143
  "bindtap",
@@ -2454,8 +3157,7 @@ const STRUCTURAL_ATTRS$1 = [
2454
3157
  const CLASS_SPLIT_RE$1 = /\s+/;
2455
3158
  const JS_FILE_RE$1 = /\.js$/;
2456
3159
  function isMustacheOnly$2(value) {
2457
- const trimmed = value.trim();
2458
- return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
3160
+ return isTemplateExpression(value);
2459
3161
  }
2460
3162
  function collectDataset$1(node, source) {
2461
3163
  if (node.dataset) return collectNodeDataset(node);
@@ -2480,17 +3182,11 @@ function cloneNode$1(node) {
2480
3182
  children: node.children?.map((child) => cloneNode$1(child))
2481
3183
  };
2482
3184
  }
2483
- function resolveValueByPath$2(source, expression) {
2484
- return resolveTemplateExpression(source, expression) ?? "";
2485
- }
2486
3185
  function resolveRawValueByPath$2(source, expression) {
2487
3186
  return resolveTemplateExpression(source, expression);
2488
3187
  }
2489
3188
  function interpolateTemplate$2(input, data) {
2490
- return input.replace(TEMPLATE_INTERPOLATION_RE$2, (_match, expression) => {
2491
- const value = resolveValueByPath$2(data, expression);
2492
- return typeof value === "string" ? value : String(value);
2493
- });
3189
+ return interpolateTemplateText(input, data, true);
2494
3190
  }
2495
3191
  function readTemplateSource$1(files, filePath) {
2496
3192
  const templateSource = readBrowserVirtualFile(files, filePath);
@@ -2615,7 +3311,7 @@ function resolveUsingComponents$1(context, ownerJsonPath, ownerFilePath) {
2615
3311
  return /* @__PURE__ */ new Map();
2616
3312
  }
2617
3313
  }
2618
- function resolveComponentGenerics$1(context, hostNode, ownerJsonPath, ownerFilePath, componentFilePath) {
3314
+ function resolveComponentGenerics$1(context, hostNode, ownerJsonPath, ownerFilePath, componentFilePath, ownerGenerics) {
2619
3315
  const componentJsonPath = join(context.project.miniprogramRootPath, `${componentFilePath.replace(JS_FILE_RE$1, "")}.json`);
2620
3316
  const componentGenerics = readComponentConfig$1(context.files, componentJsonPath).componentGenerics;
2621
3317
  if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return;
@@ -2623,7 +3319,7 @@ function resolveComponentGenerics$1(context, hostNode, ownerJsonPath, ownerFileP
2623
3319
  const resolved = /* @__PURE__ */ new Map();
2624
3320
  for (const [genericName, definition] of Object.entries(componentGenerics)) {
2625
3321
  const selectedAlias = hostNode.attribs?.[`generic:${genericName}`];
2626
- const selectedPath = selectedAlias ? ownerComponents.get(selectedAlias) : void 0;
3322
+ const selectedPath = selectedAlias ? ownerGenerics?.get(selectedAlias) ?? ownerComponents.get(selectedAlias) : void 0;
2627
3323
  if (selectedPath) {
2628
3324
  resolved.set(genericName, selectedPath);
2629
3325
  continue;
@@ -2635,66 +3331,6 @@ function resolveComponentGenerics$1(context, hostNode, ownerJsonPath, ownerFileP
2635
3331
  }
2636
3332
  return resolved.size > 0 ? resolved : void 0;
2637
3333
  }
2638
- function collectComponentEventBindings$1(hostNode) {
2639
- return collectMiniProgramEventBindings(hostNode.attribs);
2640
- }
2641
- function buildComponentTrigger$1(componentScopeId, context, hostNode) {
2642
- const hostDataset = collectDataset$1(hostNode);
2643
- const hostId = hostNode.attribs?.id ?? "";
2644
- return (instance, eventName, detail, triggerOptions) => {
2645
- const originScope = context.componentScopes.get(componentScopeId);
2646
- const interactionMark = instance.__lastInteractionEvent__?.mark;
2647
- const target = {
2648
- dataset: originScope?.dataset ?? hostDataset,
2649
- id: originScope?.hostId ?? hostId
2650
- };
2651
- let currentScopeId = componentScopeId;
2652
- while (currentScopeId) {
2653
- const currentScope = context.componentScopes.get(currentScopeId);
2654
- const binding = currentScope?.eventBindings?.get(eventName);
2655
- const listenerScope = currentScope?.listenerScopeId ? context.componentScopes.get(currentScope.listenerScopeId) : null;
2656
- const handler = binding && listenerScope ? listenerScope.getMethod(binding.method) : void 0;
2657
- if (handler) handler({
2658
- bubbles: triggerOptions?.bubbles ?? false,
2659
- capturePhase: false,
2660
- composed: triggerOptions?.composed ?? false,
2661
- detail,
2662
- mark: interactionMark,
2663
- target,
2664
- type: eventName,
2665
- currentTarget: {
2666
- dataset: currentScope?.dataset ?? hostDataset,
2667
- id: currentScope?.hostId ?? hostId
2668
- }
2669
- });
2670
- if (binding?.stopAfter) break;
2671
- if (!triggerOptions?.bubbles || !triggerOptions?.composed) break;
2672
- currentScopeId = currentScope?.ownerScopeId;
2673
- }
2674
- };
2675
- }
2676
- function syncComponentProperties$1(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
2677
- const changedRootKeys = [];
2678
- const previousProperties = {};
2679
- for (const [key, value] of Object.entries(nextProperties)) {
2680
- const nextValue = normalizeComponentPropertyValue(definition, key, value);
2681
- const bindingExpression = bindingExpressions[key];
2682
- const bindingAffected = !!bindingExpression && changedPageKeys.some((changedKey) => {
2683
- return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
2684
- });
2685
- const previousSnapshot = instance.__propertySnapshots?.[key];
2686
- if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
2687
- previousProperties[key] = instance.properties[key];
2688
- instance.properties[key] = nextValue;
2689
- if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = nextValue;
2690
- changedRootKeys.push(key);
2691
- }
2692
- instance.__propertySnapshots ??= {};
2693
- instance.__propertySnapshots[key] = cloneValue(nextValue);
2694
- }
2695
- if (changedRootKeys.length === 0) return;
2696
- runComponentObservers(definition, instance, changedRootKeys, previousProperties);
2697
- }
2698
3334
  function createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots) {
2699
3335
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
2700
3336
  return {
@@ -2702,7 +3338,7 @@ function createComponentScope$1(clonedNode, scope, componentScopeId, componentIn
2702
3338
  classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
2703
3339
  data: { ...componentInstance.data },
2704
3340
  dataset: collectDataset$1(clonedNode, wxsScopeData(scope)),
2705
- eventBindings: collectComponentEventBindings$1(clonedNode),
3341
+ ...bindComponentEventHost(clonedNode),
2706
3342
  getMethod: (methodName) => {
2707
3343
  const method = componentInstance?.[methodName];
2708
3344
  return typeof method === "function" ? method.bind(componentInstance) : void 0;
@@ -2710,6 +3346,7 @@ function createComponentScope$1(clonedNode, scope, componentScopeId, componentIn
2710
3346
  getScopeId: () => componentScopeId,
2711
3347
  genericComponents,
2712
3348
  hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
3349
+ hostNode: clonedNode,
2713
3350
  id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
2714
3351
  listenerScopeId: scope.getScopeId(),
2715
3352
  ownerScopeId,
@@ -2732,13 +3369,14 @@ function resolveComponentProperties$1(clonedNode, scope, definition) {
2732
3369
  bindingExpressions
2733
3370
  };
2734
3371
  }
2735
- function createBrowserComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId, beforeCreated) {
3372
+ function createBrowserComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, renderTemplate, bindEventsBeforeProperties = false) {
2736
3373
  const componentProperties = Object.keys(componentEntry.definition.methods ?? {}).some((key) => key.startsWith("__weapp_vite_")) || Object.hasOwn(componentEntry.definition.properties ?? {}, "__wvSlotOwnerId") ? Object.fromEntries(Object.keys(componentEntry.definition.properties ?? {}).filter((key) => Object.hasOwn(nextProperties, key)).map((key) => [key, nextProperties[key]])) : nextProperties;
2737
- const componentInstance = createComponentInstance({
3374
+ const instanceOptions = {
2738
3375
  definition: componentEntry.definition,
2739
- requestRender: (callback) => context.session.requestRender(callback),
2740
- triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
2741
- });
3376
+ requestRender: (callback) => context.session.requestRender(callback)
3377
+ };
3378
+ const componentInstance = createComponentInstance(instanceOptions);
3379
+ bindAttachmentBindingScope(componentInstance, context);
2742
3380
  setSelectorQueryScopeId(componentInstance, componentScopeId);
2743
3381
  componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE$1, "");
2744
3382
  componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
@@ -2746,20 +3384,30 @@ function createBrowserComponentInstance(componentScopeId, context, clonedNode, c
2746
3384
  componentInstance.createSelectorQuery = () => context.moduleLoader.wx.createSelectorQuery().in(componentInstance);
2747
3385
  componentInstance.selectComponent = (selector) => resolveNativeComponentSelection(context.session.selectComponentWithin(componentScopeId, selector));
2748
3386
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector).map(resolveNativeComponentSelection);
2749
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
3387
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? resolveNativeComponentSelection(context.componentCache.get(ownerScopeId)) : null;
3388
+ beginComponentConstruction(context.componentCache, componentScopeId, componentInstance);
2750
3389
  context.componentCache.set(componentScopeId, componentInstance);
2751
- beforeCreated?.(componentInstance);
2752
- runComponentLifecycle(componentInstance, "created");
2753
- componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
2754
- syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, []);
2755
- return componentInstance;
3390
+ try {
3391
+ renderTemplate?.(componentInstance, "defaults");
3392
+ runComponentLifecycle(componentInstance, "created");
3393
+ if (bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
3394
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
3395
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, [], renderTemplate);
3396
+ if (!bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
3397
+ return componentInstance;
3398
+ } catch (error) {
3399
+ discardComponentConstruction(context.componentCache, context.componentScopes, componentScopeId);
3400
+ throw error;
3401
+ } finally {
3402
+ finishComponentConstruction(context.componentCache, componentInstance);
3403
+ }
2756
3404
  }
2757
- function renderBrowserComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
3405
+ function renderBrowserComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, renderPass) {
2758
3406
  const templatePath = join(context.project.miniprogramRootPath, componentEntry.templatePath);
2759
3407
  const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
2760
3408
  const componentRoot = (componentDocument.children ?? [])[0] ?? componentDocument;
2761
3409
  const templateRenderState = prepareTemplateRenderState$1(context.files, componentRoot, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
2762
- return renderNodeTree(componentRoot, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes, templateRenderState);
3410
+ return renderNodeTree(componentRoot, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, renderPass, templateRenderState, componentScope.hostNode);
2763
3411
  }
2764
3412
  //#endregion
2765
3413
  //#region src/browser/render/index.ts
@@ -2773,24 +3421,33 @@ function expandNodeByFor$1(node, scope) {
2773
3421
  const items = resolveLoopEntries(resolveRawValueByPath$2(wxsScopeData(scope), forExpression));
2774
3422
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
2775
3423
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
3424
+ const key = node.attribs?.["wx:key"]?.trim();
3425
+ const keyOccurrences = key ? /* @__PURE__ */ new Map() : void 0;
2776
3426
  return items.map(([index, item]) => ({
2777
3427
  node: cloneNode$1(node),
2778
3428
  scope: createLoopScope$1(scope, itemName, indexName, item, index),
2779
- instanceSuffix: `:for-${index}`
3429
+ instanceSuffix: resolveLoopInstanceSuffix(item, index, key, keyOccurrences)
2780
3430
  }));
2781
3431
  }
2782
- function renderNodeVariants$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
2783
- return expandNodeByFor$1(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree$1(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes, templateRenderState));
3432
+ function renderNodeVariants$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
3433
+ const nodes = [];
3434
+ if (isRenderPassStale(renderPass)) return nodes;
3435
+ for (const { node: expandedNode, scope: expandedScope, instanceSuffix } of expandNodeByFor$1(node, scope)) {
3436
+ if (isRenderPassStale(renderPass)) break;
3437
+ nodes.push(renderNodeTree$1(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, renderPass, templateRenderState, parent));
3438
+ }
3439
+ return nodes;
2784
3440
  }
2785
- function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
3441
+ function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
2786
3442
  const renderedChildren = [];
2787
3443
  for (const { node: child, index } of selectConditionalChildren(children, (node) => evaluateConditionalBranch$1(node, scope))) {
3444
+ if (isRenderPassStale(renderPass)) break;
2788
3445
  if (!isTagNode$1(child)) {
2789
- renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
3446
+ renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, renderPass, templateRenderState, parent));
2790
3447
  continue;
2791
3448
  }
2792
3449
  if (isTemplateDefinition(child) || child.name === "import" || child.name === "wxs") continue;
2793
- renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
3450
+ renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, renderPass, templateRenderState, parent));
2794
3451
  }
2795
3452
  return renderedChildren;
2796
3453
  }
@@ -2822,22 +3479,38 @@ function collectComponentSlots$1(componentNode, scope, ownerJsonPath, ownerFileP
2822
3479
  }
2823
3480
  return slots;
2824
3481
  }
2825
- function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
3482
+ function reconcileSlotDeclarations$1(context, renderPass) {
3483
+ for (const [entries, { parent, scopeId }] of renderPass.slotDeclarations) {
3484
+ if (isRenderPassStale(renderPass)) return;
3485
+ if (isComponentConstructing(context.componentCache.get(scopeId))) continue;
3486
+ for (const { index } of selectConditionalChildren(entries.map((entry) => entry.node), (node, index) => evaluateConditionalBranch$1(node, entries[index].scope))) {
3487
+ if (isRenderPassStale(renderPass)) return;
3488
+ const entry = entries[index];
3489
+ if (renderPass.renderedSlots.has(entry)) continue;
3490
+ const nodes = renderNodeVariants$1(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, renderPass, entry.templateRenderState, parent);
3491
+ renderPass.renderedSlots.set(entry, nodes);
3492
+ renderPass.hasUnprojectedSlots ||= nodes.length > 0;
3493
+ }
3494
+ }
3495
+ }
3496
+ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
3497
+ if (isRenderPassStale(renderPass)) return node;
2826
3498
  if (scope.wxs !== templateRenderState.wxsModules) scope = {
2827
3499
  ...scope,
2828
3500
  wxs: templateRenderState.wxsModules
2829
3501
  };
2830
3502
  const clonedNode = cloneNode$1(node);
3503
+ registerComponentEventNode(clonedNode, scope, parent);
2831
3504
  if (!isTagNode$1(clonedNode)) {
2832
3505
  applyNodeBindings$1(clonedNode, scope);
2833
3506
  return clonedNode;
2834
3507
  }
2835
- if (isTemplateDefinition(clonedNode)) return {
2836
- type: "tag",
2837
- name: "block",
2838
- attribs: {},
2839
- children: []
2840
- };
3508
+ if (isTemplateDefinition(clonedNode)) {
3509
+ clonedNode.name = "block";
3510
+ clonedNode.attribs = {};
3511
+ clonedNode.children = [];
3512
+ return clonedNode;
3513
+ }
2841
3514
  const templateName = resolveTemplateCall(clonedNode, wxsScopeData(scope));
2842
3515
  if (templateName) {
2843
3516
  const definition = templateRenderState.definitions.get(templateName);
@@ -2846,57 +3519,72 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
2846
3519
  data: resolveTemplateData(clonedNode, wxsScopeData(scope)),
2847
3520
  wxs: definition && templateRenderState.definitionWxsScopes?.get(definition)
2848
3521
  };
2849
- const children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren$1(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, seenComponentScopes, {
3522
+ clonedNode.name = "block";
3523
+ clonedNode.attribs = {
3524
+ "data-sim-node": instancePath,
3525
+ "data-sim-scope": scope.getScopeId()
3526
+ };
3527
+ clonedNode.children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren$1(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, renderPass, {
2850
3528
  definitions: templateRenderState.definitionScopes?.get(definition) ?? templateRenderState.definitions,
2851
3529
  definitionScopes: templateRenderState.definitionScopes,
2852
3530
  definitionWxsScopes: templateRenderState.definitionWxsScopes,
2853
3531
  wxsModules: templateScope.wxs,
2854
3532
  stack: [...templateRenderState.stack, templateName]
2855
- }) : [];
2856
- return {
2857
- type: "tag",
2858
- name: "block",
2859
- attribs: {
2860
- "data-sim-node": instancePath,
2861
- "data-sim-scope": scope.getScopeId()
2862
- },
2863
- children
2864
- };
3533
+ }, clonedNode) : [];
3534
+ return clonedNode;
2865
3535
  }
2866
3536
  if (clonedNode.name === "slot") {
2867
3537
  const slotName = clonedNode.attribs?.name?.trim() || "default";
2868
3538
  const projected = scope.slots?.get(slotName) ?? [];
2869
- const children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch$1(node, projected[index].scope)).flatMap(({ index }) => {
3539
+ const fallbackChildren = clonedNode.children ?? [];
3540
+ bindComponentEventHost(clonedNode);
3541
+ clonedNode.name = "block";
3542
+ clonedNode.attribs = { "data-sim-scope": scope.getScopeId() };
3543
+ const slotOwner = scope.getScopeId();
3544
+ if (projected.length && slotOwner && isComponentConstructing(context.componentCache.get(slotOwner))) {
3545
+ clonedNode.children = [];
3546
+ return clonedNode;
3547
+ }
3548
+ clonedNode.children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch$1(node, projected[index].scope)).flatMap(({ index }) => {
2870
3549
  const entry = projected[index];
2871
- return renderNodeVariants$1(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, seenComponentScopes, entry.templateRenderState);
2872
- }) : renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, seenComponentScopes, templateRenderState);
2873
- return {
2874
- type: "tag",
2875
- name: "block",
2876
- attribs: { "data-sim-scope": scope.getScopeId() },
2877
- children
2878
- };
3550
+ const nodes = renderNodeVariants$1(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, renderPass, entry.templateRenderState, clonedNode);
3551
+ renderPass.renderedSlots.set(entry, nodes);
3552
+ return nodes;
3553
+ }) : renderChildren$1(fallbackChildren, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, renderPass, templateRenderState, clonedNode);
3554
+ return clonedNode;
2879
3555
  }
2880
3556
  const componentEntry = resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, clonedNode.name, scope.genericComponents?.get(clonedNode.name));
2881
3557
  if (componentEntry) {
2882
3558
  const componentScopeId = `${instancePath}/${clonedNode.name}`;
2883
3559
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
2884
3560
  const { nextProperties, bindingExpressions } = resolveComponentProperties$1(clonedNode, scope, componentEntry.definition);
2885
- const genericComponents = resolveComponentGenerics$1(context, clonedNode, ownerJsonPath, ownerFilePath, componentEntry.filePath);
3561
+ const genericComponents = resolveComponentGenerics$1(context, clonedNode, ownerJsonPath, ownerFilePath, componentEntry.filePath, scope.genericComponents);
2886
3562
  const slots = collectComponentSlots$1(clonedNode, scope, ownerJsonPath, ownerFilePath, componentScopeId, templateRenderState);
3563
+ registerSlotDeclarations(renderPass, slots, clonedNode, componentScopeId);
3564
+ applyNodeBindings$1(clonedNode, scope);
3565
+ const reconcilePrivateTemplate = (instance, phase) => {
3566
+ let bindingPass;
3567
+ do {
3568
+ const bindingScope = createComponentScope$1(clonedNode, scope, componentScopeId, instance, genericComponents, slots);
3569
+ context.componentScopes.set(componentScopeId, bindingScope);
3570
+ bindingPass = createRenderPass(phase === "properties", renderPass);
3571
+ renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, bindingScope, componentScopeId, bindingPass);
3572
+ reconcileSlotDeclarations$1(context, bindingPass);
3573
+ } while (isRenderPassStale(bindingPass));
3574
+ };
2887
3575
  let componentInstance = context.componentCache.get(componentScopeId);
2888
- if (!componentInstance) componentInstance = createBrowserComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId, (instance) => {
2889
- const initialScope = createComponentScope$1(clonedNode, scope, componentScopeId, instance, genericComponents, slots);
2890
- context.componentScopes.set(componentScopeId, initialScope);
2891
- renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, initialScope, componentScopeId, /* @__PURE__ */ new Set());
2892
- });
2893
- else syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
2894
- seenComponentScopes.add(componentScopeId);
3576
+ if (!componentInstance) componentInstance = createBrowserComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, reconcilePrivateTemplate, renderPass.propertyUpdate);
3577
+ else {
3578
+ context.componentScopes.set(componentScopeId, createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots));
3579
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys, reconcilePrivateTemplate);
3580
+ }
3581
+ if (isRenderPassStale(renderPass)) return clonedNode;
3582
+ renderPass.seenComponentScopes.add(componentScopeId);
2895
3583
  const componentScope = createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots);
2896
3584
  context.componentScopes.set(componentScopeId, componentScope);
2897
- const renderedComponentRoot = renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, componentScope, componentScopeId, seenComponentScopes);
3585
+ const renderedComponentRoot = renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, componentScope, componentScopeId, renderPass);
3586
+ mergeComponentEventRoot(renderedComponentRoot, clonedNode);
2898
3587
  if (renderedComponentRoot.attribs) {
2899
- applyNodeBindings$1(clonedNode, scope);
2900
3588
  renderedComponentRoot.attribs = {
2901
3589
  ...clonedNode.attribs,
2902
3590
  ...renderedComponentRoot.attribs
@@ -2908,65 +3596,99 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
2908
3596
  renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
2909
3597
  renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
2910
3598
  }
3599
+ renderPass.componentRoots.set(componentScopeId, renderedComponentRoot);
2911
3600
  return renderedComponentRoot;
2912
3601
  }
2913
3602
  applyNodeBindings$1(clonedNode, scope);
2914
- clonedNode.children = renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes, templateRenderState);
3603
+ clonedNode.attribs["data-sim-node"] = instancePath;
3604
+ clonedNode.children = renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, renderPass, templateRenderState, clonedNode);
2915
3605
  return clonedNode;
2916
3606
  }
3607
+ function reconcileBrowserPageTree(context, page, bindingsOnly = false) {
3608
+ for (;;) {
3609
+ bindAttachmentBindingScope(context, page);
3610
+ if (page.__lastChangedKeys__) context.changedPageKeys = page.__lastChangedKeys__;
3611
+ const route = page.route.replace(LEADING_SLASH_RE$5, "");
3612
+ const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
3613
+ const templatePath = join(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
3614
+ const document = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
3615
+ const pageScopeId = `page:${route}`;
3616
+ const pageScope = {
3617
+ data: page.data,
3618
+ getMethod: (methodName) => {
3619
+ const method = page[methodName];
3620
+ return typeof method === "function" ? method.bind(page) : void 0;
3621
+ },
3622
+ getScopeId: () => pageScopeId,
3623
+ id: "page-root"
3624
+ };
3625
+ for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
3626
+ context.componentScopes.set(pageScopeId, pageScope);
3627
+ const renderPass = createPageRenderPass(page, context.componentCache);
3628
+ const root = (document.children ?? [])[0] ?? document;
3629
+ const templateRenderState = prepareTemplateRenderState$1(context.files, root, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
3630
+ const renderedRoot = renderNodeTree$1(root, pageScope, context, `${resourcePath}.json`, `${resourcePath}.js`, pageScopeId, renderPass, templateRenderState);
3631
+ const roots = [renderedRoot];
3632
+ if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree$1({
3633
+ type: "tag",
3634
+ name: "custom-tab-bar",
3635
+ attribs: {},
3636
+ children: []
3637
+ }, customTabBarHostScope(), context, "app.json", "app.js", pageScopeId, renderPass, templateRenderState));
3638
+ reconcileSlotDeclarations$1(context, renderPass);
3639
+ if (isRenderPassStale(renderPass)) continue;
3640
+ markPageTreeConstructed(page, context.componentCache);
3641
+ const treeRoot = roots.length > 1 ? {
3642
+ type: "root",
3643
+ children: roots
3644
+ } : renderedRoot;
3645
+ linkRenderedParents(treeRoot);
3646
+ registerInspectionTrees(treeRoot, renderPass, context.componentScopes);
3647
+ if (bindingsOnly) return {
3648
+ root: treeRoot,
3649
+ roots,
3650
+ resourcePath
3651
+ };
3652
+ let bindingsRefreshed = false;
3653
+ const updateBindings = () => {
3654
+ bindingsRefreshed = true;
3655
+ if (hasPendingComponentConstruction(context.componentCache)) return;
3656
+ reconcileBrowserPageTree(context, page, true);
3657
+ };
3658
+ const pageAttached = attachComponentPage(page, updateBindings);
3659
+ if (bindingsRefreshed) continue;
3660
+ const pageAttaching = isComponentPageAttaching(page);
3661
+ const scopeIds = orderComponentAttachmentScopes(renderPass.seenComponentScopes, context.componentScopes);
3662
+ const instances = scopeIds.map((scopeId) => context.componentCache.get(scopeId));
3663
+ const attached = !pageAttaching && runWithAttachmentBindingUpdates(page, updateBindings, (scopes) => flushComponentAttachments(context.componentCache, scopes, (instance) => {
3664
+ runComponentLifecycle(instance, "attached");
3665
+ if (instance !== context.componentCache.get(customTabBarScopeId(route))) runComponentPageLifetime(instance, "show");
3666
+ return bindingsRefreshed;
3667
+ }), scopeIds);
3668
+ if (attached === "restart") continue;
3669
+ const canFinalize = !pageAttaching && !hasPendingComponentAttachments(instances);
3670
+ const removed = canFinalize ? [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !renderPass.seenComponentScopes.has(scopeId)) : [];
3671
+ for (const [scopeId, instance] of removed) if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
3672
+ else scheduleDiscardedComponentReady(context.componentCache, scopeId, instance);
3673
+ const relationsChanged = canFinalize && syncComponentRelations(context.componentCache, renderPass.seenComponentScopes, pageScopeId);
3674
+ for (const [scopeId] of removed) {
3675
+ context.componentCache.delete(scopeId);
3676
+ context.componentScopes.delete(scopeId);
3677
+ }
3678
+ if (pageAttached || attached || relationsChanged) continue;
3679
+ if (canFinalize && !isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
3680
+ if (canFinalize && !isPageBeforeReady(page) && flushComponentReady(instances, (instance) => runComponentLifecycle(instance, "ready"))) continue;
3681
+ return {
3682
+ root: treeRoot,
3683
+ roots,
3684
+ resourcePath
3685
+ };
3686
+ }
3687
+ }
2917
3688
  function renderBrowserPageTree(context, page) {
2918
- const route = page.route.replace(LEADING_SLASH_RE$5, "");
2919
- const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
2920
- const templatePath = join(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
2921
- const document = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
2922
- const pageScopeId = `page:${route}`;
2923
- const pageScope = {
2924
- data: page.data,
2925
- getMethod: (methodName) => {
2926
- const method = page[methodName];
2927
- return typeof method === "function" ? method.bind(page) : void 0;
2928
- },
2929
- getScopeId: () => pageScopeId,
2930
- id: "page-root"
2931
- };
2932
- for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
2933
- context.componentScopes.set(pageScopeId, pageScope);
2934
- const seenComponentScopes = /* @__PURE__ */ new Set();
2935
- const root = (document.children ?? [])[0] ?? document;
2936
- const templateRenderState = prepareTemplateRenderState$1(context.files, root, templatePath, context.project.miniprogramRootPath, getBrowserWxsLoader(context.moduleLoader, context.files));
2937
- const renderedRoot = renderNodeTree$1(root, pageScope, context, `${resourcePath}.json`, `${resourcePath}.js`, pageScopeId, seenComponentScopes, templateRenderState);
2938
- const roots = [renderedRoot];
2939
- if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree$1({
2940
- type: "tag",
2941
- name: "custom-tab-bar",
2942
- attribs: {},
2943
- children: []
2944
- }, customTabBarHostScope(), context, "app.json", "app.js", pageScopeId, seenComponentScopes, templateRenderState));
2945
- const pageAttached = attachComponentPage(page);
2946
- const pageAttaching = isComponentPageAttaching(page);
2947
- const attached = !pageAttaching && flushComponentAttachments([...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId)), (instance) => {
2948
- runComponentLifecycle(instance, "attached");
2949
- if (instance !== context.componentCache.get(customTabBarScopeId(route))) runComponentPageLifetime(instance, "show");
2950
- });
2951
- const removed = [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !seenComponentScopes.has(scopeId));
2952
- for (const [scopeId, instance] of removed) if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
2953
- else scheduleDiscardedComponentReady(context.componentCache, scopeId, instance);
2954
- const instances = [...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId));
2955
- const relationsChanged = !pageAttaching && !hasPendingComponentAttachments(instances) && syncComponentRelations(context.componentCache, seenComponentScopes, pageScopeId);
2956
- for (const [scopeId] of removed) {
2957
- context.componentCache.delete(scopeId);
2958
- context.componentScopes.delete(scopeId);
2959
- }
2960
- if (pageAttached || attached || relationsChanged) return renderBrowserPageTree(context, page);
2961
- if (!isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
2962
- if (!isPageBeforeReady(page) && flushComponentReady(instances, (instance) => runComponentLifecycle(instance, "ready"))) return renderBrowserPageTree(context, page);
2963
- const treeRoot = roots.length > 1 ? {
2964
- type: "root",
2965
- children: roots
2966
- } : renderedRoot;
2967
- linkRenderedParents(treeRoot);
3689
+ const { root, roots, resourcePath } = reconcileBrowserPageTree(context, page);
2968
3690
  return {
2969
- root: treeRoot,
3691
+ root,
2970
3692
  styles: resolveBrowserPageStyles(context.files, resourcePath, {
2971
3693
  miniprogramRootPath: context.project.miniprogramRootPath,
2972
3694
  styleIsolation: resolveBrowserComponentPageStyleIsolation(context.files, page, resourcePath, context.project.miniprogramRootPath)
@@ -3188,6 +3910,18 @@ var HeadlessAppLifecycle = class {
3188
3910
  }
3189
3911
  };
3190
3912
  //#endregion
3913
+ //#region src/runtime/packageAsset.ts
3914
+ const assetExtension = /\.(?:png|jpe?g|gif|svg|cer|mp3|aac|m4a|mp4|wav|ogg|silk|wasm|br|cur|ico|skel|crt|cert|gltf|glb|bin|ktx|hdr|exr|xnet|pem)$/i;
3915
+ /** 包内静态资源只读且每次访问宿主当前产物,不缓存为用户文件,也不允许越过包根目录。 */
3916
+ function createPackageAssetReader(read) {
3917
+ return (filePath) => {
3918
+ if (filePath.includes("\\") || filePath.includes(":") || filePath.includes("\0")) return;
3919
+ const relative = posix.normalize(filePath.replace(/^\/+/, ""));
3920
+ if (relative === ".." || relative.startsWith("../") || !assetExtension.test(relative)) return;
3921
+ return read(relative);
3922
+ };
3923
+ }
3924
+ //#endregion
3191
3925
  //#region src/runtime/pageInstance.ts
3192
3926
  const ARRAY_INDEX_PATH_RE = /\[(\d+)\]/g;
3193
3927
  const ARRAY_INDEX_SEGMENT_RE = /^\d+$/;
@@ -3268,6 +4002,7 @@ function createPageInstance(route, definition, options = {}, pageState = {}) {
3268
4002
  const rootKey = parseDataPath(key)[0];
3269
4003
  if (rootKey) instance.properties[rootKey] = instance.data[rootKey];
3270
4004
  }
4005
+ synchronizeAttachmentBindings(instance);
3271
4006
  if (pageState.requestRender) pageState.requestRender(callback);
3272
4007
  else callback?.();
3273
4008
  }
@@ -3280,6 +4015,130 @@ function createPageInstance(route, definition, options = {}, pageState = {}) {
3280
4015
  return instance;
3281
4016
  }
3282
4017
  //#endregion
4018
+ //#region src/runtime/routeEvents.ts
4019
+ /** 两种模拟器共用路由身份与监听状态,完成事件由页面就绪和宿主提交驱动。 */
4020
+ var HeadlessRouteEvents = class {
4021
+ requestRender;
4022
+ isCurrentPage;
4023
+ bus = createHeadlessUniEventBus();
4024
+ pages = /* @__PURE__ */ new WeakMap();
4025
+ nextRouteId = 0;
4026
+ nextWebviewId = 0;
4027
+ activeEvent;
4028
+ activeState;
4029
+ constructor(requestRender, isCurrentPage) {
4030
+ this.requestRender = requestRender;
4031
+ this.isCurrentPage = isCurrentPage;
4032
+ }
4033
+ on(name, listener) {
4034
+ this.bus.$on(name, listener);
4035
+ }
4036
+ off(name, listener) {
4037
+ this.bus.$off(name, listener);
4038
+ }
4039
+ begin(path, query, openType, renderer, page) {
4040
+ this.cancel(this.activeState, /* @__PURE__ */ new Error("navigateTo:fail navigation was superseded"));
4041
+ const previous = page ? this.pages.get(page) : void 0;
4042
+ const event = {
4043
+ path,
4044
+ query: { ...query },
4045
+ openType: this.nextRouteId === 0 ? "appLaunch" : openType,
4046
+ renderer: previous?.event.renderer ?? (renderer === "skyline" || renderer === "xr-frame" ? renderer : "webview"),
4047
+ routeEventId: String(++this.nextRouteId),
4048
+ webviewId: previous?.webviewId ?? ++this.nextWebviewId,
4049
+ timeStamp: Date.now()
4050
+ };
4051
+ this.activeEvent = event;
4052
+ this.bus.$emit("beforeAppRoute", event);
4053
+ return event;
4054
+ }
4055
+ attach(page, event) {
4056
+ const state = this.pages.get(page);
4057
+ const next = {
4058
+ webviewId: event.webviewId,
4059
+ ready: state?.ready ?? false,
4060
+ event,
4061
+ committed: false,
4062
+ completed: false
4063
+ };
4064
+ this.pages.set(page, next);
4065
+ if (this.activeEvent === event) this.activeState = next;
4066
+ }
4067
+ /** 原生 navigateTo 的回调属于本次路由记录,不能以当前页面或提交栈代替完成。 */
4068
+ navigateTo(operation, callbacks) {
4069
+ let state;
4070
+ try {
4071
+ state = this.pages.get(operation());
4072
+ } catch (error) {
4073
+ this.settle(callbacks, error);
4074
+ return;
4075
+ }
4076
+ if (!state || state.canceled) this.settle(callbacks, state?.canceled ?? /* @__PURE__ */ new Error("navigateTo:fail target page was unloaded"));
4077
+ else if (state.completed) this.settle(callbacks);
4078
+ else state.callbacks = callbacks;
4079
+ }
4080
+ commit(page, event) {
4081
+ const state = this.pages.get(page);
4082
+ if (!state || state.event !== event || this.activeEvent !== event || !this.isCurrentPage(page)) return;
4083
+ state.committed = true;
4084
+ this.bus.$emit("appRoute", event);
4085
+ if (state.ready) this.complete(page, state);
4086
+ }
4087
+ ready(page) {
4088
+ const state = this.pages.get(page);
4089
+ if (!state) return;
4090
+ state.ready = true;
4091
+ if (state.committed) this.complete(page, state);
4092
+ }
4093
+ complete(page, state) {
4094
+ this.requestRender(() => {
4095
+ if (state.completed || state.canceled || this.pages.get(page) !== state || this.activeEvent !== state.event || !this.isCurrentPage(page)) return;
4096
+ state.completed = true;
4097
+ const callbacks = state.callbacks;
4098
+ state.callbacks = void 0;
4099
+ try {
4100
+ this.bus.$emit("appRouteDone", state.event);
4101
+ } finally {
4102
+ this.settle(callbacks);
4103
+ }
4104
+ });
4105
+ }
4106
+ settle(callbacks, error) {
4107
+ try {
4108
+ if (error) callbacks?.fail?.(error);
4109
+ else callbacks?.success?.();
4110
+ } finally {
4111
+ callbacks?.complete?.();
4112
+ }
4113
+ }
4114
+ cancel(state, error) {
4115
+ if (!state || state.completed || state.canceled) return;
4116
+ state.canceled = error;
4117
+ const callbacks = state.callbacks;
4118
+ state.callbacks = void 0;
4119
+ this.settle(callbacks, error);
4120
+ }
4121
+ beforeUnload(page, event) {
4122
+ const state = this.pages.get(page);
4123
+ if (event && state) this.bus.$emit("beforePageUnload", {
4124
+ ...event,
4125
+ path: page.route,
4126
+ query: { ...page.options },
4127
+ renderer: state.event.renderer,
4128
+ webviewId: state.webviewId,
4129
+ page
4130
+ });
4131
+ this.cancel(state, /* @__PURE__ */ new Error("navigateTo:fail target page was unloaded"));
4132
+ this.pages.delete(page);
4133
+ }
4134
+ close() {
4135
+ this.cancel(this.activeState, /* @__PURE__ */ new Error("navigateTo:fail runtime session closed"));
4136
+ this.activeState = void 0;
4137
+ this.activeEvent = void 0;
4138
+ this.bus.$off();
4139
+ }
4140
+ };
4141
+ //#endregion
3283
4142
  //#region src/runtime/systemInfo.ts
3284
4143
  function createDefaultLocationResult() {
3285
4144
  return {
@@ -4074,7 +4933,7 @@ function createHeadlessWxState(scheduler = nativeScheduler, options = {}) {
4074
4933
  const readFile = (filePath, encoding) => {
4075
4934
  normalizeEncoding(encoding);
4076
4935
  const normalizedPath = normalizeFsPath(filePath);
4077
- const fileContent = files.get(normalizedPath);
4936
+ const fileContent = files.get(normalizedPath) ?? options.readPackageFile?.(normalizedPath);
4078
4937
  if (fileContent == null) throw new Error(`readFile:fail no such file or directory, open '${normalizedPath}'`);
4079
4938
  return {
4080
4939
  data: fileContent,
@@ -5051,24 +5910,63 @@ function createHeadlessWxState(scheduler = nativeScheduler, options = {}) {
5051
5910
  };
5052
5911
  }
5053
5912
  //#endregion
5913
+ //#region src/view/eventBinding.ts
5914
+ function collectMiniProgramEventBindings(attributes = {}) {
5915
+ return collectEventBindings(attributes, false).eventBindings;
5916
+ }
5917
+ function resolveMiniProgramEventBinding(attributes, eventName) {
5918
+ return resolveEventBindingPhases(attributes, eventName, false)?.bubble ?? null;
5919
+ }
5920
+ /** 冒泡时保留原始 target,currentTarget 则属于当前执行绑定的节点。 */
5921
+ function createMiniProgramEventPayload(node, eventName, event, origin = node) {
5922
+ const dataset = collectNodeDataset(node);
5923
+ const nodeId = node.attribs?.id ?? "";
5924
+ const isOrigin = node === origin;
5925
+ return {
5926
+ bubbles: false,
5927
+ capturePhase: false,
5928
+ composed: false,
5929
+ currentTarget: {
5930
+ dataset: isOrigin ? event.currentTarget?.dataset ?? event.dataset ?? dataset : dataset,
5931
+ id: isOrigin ? event.currentTarget?.id ?? event.id ?? nodeId : nodeId
5932
+ },
5933
+ detail: event.detail,
5934
+ mark: event.mark,
5935
+ target: {
5936
+ dataset: event.target?.dataset ?? event.dataset ?? (isOrigin ? dataset : collectNodeDataset(origin)),
5937
+ id: event.target?.id ?? event.id ?? origin.attribs?.id ?? ""
5938
+ },
5939
+ timeStamp: Date.now(),
5940
+ type: eventName
5941
+ };
5942
+ }
5943
+ //#endregion
5054
5944
  //#region src/view/selectors.ts
5055
- const adapter = {
5056
- isTag: (node) => node.type === "tag",
5057
- getAttributeValue: (node, name) => node.attribs?.[name],
5058
- getChildren: (node) => node.children ?? [],
5059
- getName: (node) => node.name ?? "",
5060
- getParent: (node) => node.parent ?? null,
5061
- getSiblings: (node) => node.parent?.children ?? [node],
5062
- getText: (node) => node.type === "text" ? node.data ?? "" : (node.children ?? []).map((child) => adapter.getText(child)).join(""),
5063
- hasAttrib: (node, name) => Object.hasOwn(node.attribs ?? {}, name),
5064
- removeSubsets: (nodes) => {
5065
- const unique = new Set(nodes);
5066
- return [...unique].filter((node) => {
5067
- for (let parent = node.parent; parent; parent = parent.parent) if (unique.has(parent)) return false;
5068
- return true;
5069
- });
5070
- }
5071
- };
5945
+ function createAdapter(getChildren, getParent) {
5946
+ const adapter = {
5947
+ isTag: (node) => node.type === "tag",
5948
+ getAttributeValue: (node, name) => node.attribs?.[name],
5949
+ getChildren,
5950
+ getName: (node) => node.name ?? "",
5951
+ getParent,
5952
+ getSiblings: (node) => {
5953
+ const parent = getParent(node);
5954
+ return parent ? getChildren(parent) : [node];
5955
+ },
5956
+ getText: (node) => node.type === "text" ? node.data ?? "" : getChildren(node).map((child) => adapter.getText(child)).join(""),
5957
+ hasAttrib: (node, name) => Object.hasOwn(node.attribs ?? {}, name),
5958
+ removeSubsets: (nodes) => {
5959
+ const unique = new Set(nodes);
5960
+ return [...unique].filter((node) => {
5961
+ for (let parent = getParent(node); parent; parent = getParent(parent)) if (unique.has(parent)) return false;
5962
+ return true;
5963
+ });
5964
+ }
5965
+ };
5966
+ return adapter;
5967
+ }
5968
+ const renderedAdapter = createAdapter((node) => node.children ?? [], (node) => node.parent ?? null);
5969
+ const inspectionAdapter = createAdapter(getInspectionChildren, getInspectionParent);
5072
5970
  function resolveComponentTags(selectors) {
5073
5971
  return selectors.map((group) => group.map((token) => {
5074
5972
  if (token.type === SelectorType.Pseudo && Array.isArray(token.data)) return {
@@ -5091,7 +5989,7 @@ function resolveComponentTags(selectors) {
5091
5989
  };
5092
5990
  }));
5093
5991
  }
5094
- function querySelectorAll(root, selector) {
5992
+ function queryWithAdapter(root, selector, adapter) {
5095
5993
  const parsed = parse(selector);
5096
5994
  const query = resolveComponentTags(parsed);
5097
5995
  const includesPageRoot = root.type === "tag" && root.name === "page" && parsed.some((group) => group.some((token) => token.type === SelectorType.Tag && token.name === "page"));
@@ -5100,10 +5998,19 @@ function querySelectorAll(root, selector) {
5100
5998
  cacheResults: false
5101
5999
  });
5102
6000
  }
6001
+ function querySelectorAll(root, selector) {
6002
+ return queryWithAdapter(root, selector, renderedAdapter);
6003
+ }
6004
+ function queryInspectionSelectorAll(root, selector) {
6005
+ return queryWithAdapter(root, selector, inspectionAdapter);
6006
+ }
5103
6007
  //#endregion
5104
6008
  //#region src/view/xpath.ts
5105
6009
  const xpathEngine = Reflect.get(fontoxpath, "default") ?? fontoxpath;
5106
- function wrapNode(source, parent = null) {
6010
+ function getRenderedChildren(node) {
6011
+ return node.children ?? [];
6012
+ }
6013
+ function wrapNode(source, getChildren, parent = null) {
5107
6014
  const node = {
5108
6015
  attributes: [],
5109
6016
  children: [],
@@ -5126,7 +6033,7 @@ function wrapNode(source, parent = null) {
5126
6033
  prefix: null,
5127
6034
  value
5128
6035
  }));
5129
- node.children = (source.children ?? []).map((child) => wrapNode(child, node));
6036
+ node.children = getChildren(source).map((child) => wrapNode(child, getChildren, node));
5130
6037
  return node;
5131
6038
  }
5132
6039
  function sibling(node, offset) {
@@ -5146,40 +6053,25 @@ const domFacade = {
5146
6053
  getParentNode: (node) => node.parent,
5147
6054
  getPreviousSibling: (node) => sibling(node, -1)
5148
6055
  };
5149
- function queryXPathElements(root, expression) {
6056
+ function queryElements(root, expression, getChildren) {
5150
6057
  if (!expression.trim()) throw new Error("XPath must be a non-empty expression in headless testing runtime.");
5151
6058
  const document = wrapNode(root.type === "root" ? root : {
5152
6059
  type: "root",
5153
6060
  children: [root]
5154
- });
6061
+ }, getChildren);
5155
6062
  return xpathEngine.evaluateXPathToNodes(expression, document, domFacade).filter((node) => node.nodeType === 1).map((node) => node.source);
5156
6063
  }
6064
+ function queryXPathElements(root, expression) {
6065
+ return queryElements(root, expression, getRenderedChildren);
6066
+ }
6067
+ function queryInspectionXPathElements(root, expression) {
6068
+ return queryElements(root, expression, getInspectionChildren);
6069
+ }
5157
6070
  //#endregion
5158
6071
  //#region src/view/nodeHandle.ts
5159
6072
  function escapeText$2(text) {
5160
6073
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
5161
6074
  }
5162
- function createEventPayload$1(node, eventName, event) {
5163
- const dataset = collectNodeDataset(node);
5164
- const nodeId = node.attribs?.id ?? "";
5165
- return {
5166
- bubbles: false,
5167
- capturePhase: false,
5168
- composed: false,
5169
- currentTarget: {
5170
- dataset: event.currentTarget?.dataset ?? event.dataset ?? dataset,
5171
- id: event.currentTarget?.id ?? event.id ?? nodeId
5172
- },
5173
- detail: event.detail,
5174
- mark: event.mark,
5175
- target: {
5176
- dataset: event.target?.dataset ?? event.dataset ?? dataset,
5177
- id: event.target?.id ?? event.id ?? nodeId
5178
- },
5179
- timeStamp: Date.now(),
5180
- type: eventName
5181
- };
5182
- }
5183
6075
  function createValueEventDetail(value, detail) {
5184
6076
  return {
5185
6077
  value,
@@ -5221,7 +6113,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
5221
6113
  this.interactions?.assertActive?.();
5222
6114
  }
5223
6115
  query(selector) {
5224
- const nodes = querySelectorAll(this.node, selector);
6116
+ const nodes = (this.interactions?.projectionOnly ? querySelectorAll : queryInspectionSelectorAll)(this.node, selector);
5225
6117
  const scope = this.node.attribs?.["data-sim-scope"];
5226
6118
  if (!scope || !this.interactions) return nodes;
5227
6119
  return nodes.filter((node) => {
@@ -5240,7 +6132,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
5240
6132
  }
5241
6133
  async getElementsByXpath(expression) {
5242
6134
  this.assertActive();
5243
- return queryXPathElements(this.node, expression).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
6135
+ return (this.interactions?.projectionOnly ? queryXPathElements : queryInspectionXPathElements)(this.node, expression).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
5244
6136
  }
5245
6137
  async attr(name) {
5246
6138
  this.assertActive();
@@ -5289,9 +6181,18 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
5289
6181
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
5290
6182
  const normalizedEventName = eventName.trim();
5291
6183
  if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
6184
+ let handlerResults;
6185
+ const nativeHandled = this.interactions.dispatchNativeEvent?.(this.node, normalizedEventName, event, normalizedEventName === "tap" ? (result) => {
6186
+ handlerResults ??= [];
6187
+ handlerResults.push(result);
6188
+ } : void 0);
6189
+ if (normalizedEventName === "tap" && nativeHandled) return handlerResults ? (await Promise.all(handlerResults))[0] : void 0;
5292
6190
  const binding = resolveMiniProgramEventBinding(this.node.attribs, normalizedEventName);
5293
- if (!binding?.method) throw new Error(`No ${normalizedEventName} binding was found on <${this.node.name ?? "unknown"}> in headless testing runtime.`);
5294
- return await this.interactions.callMethod(this.node.attribs?.["data-sim-scope"] ?? null, binding.method, createEventPayload$1(this.node, normalizedEventName, event));
6191
+ if (!binding?.method) {
6192
+ if (nativeHandled) return;
6193
+ throw new Error(`No ${normalizedEventName} binding was found on <${this.node.name ?? "unknown"}> in headless testing runtime.`);
6194
+ }
6195
+ return await this.interactions.callMethod(this.node.attribs?.["data-sim-scope"] ?? null, binding.method, createMiniProgramEventPayload(this.node, normalizedEventName, event));
5295
6196
  }
5296
6197
  async tap(event = {}) {
5297
6198
  return await this.trigger("tap", event);
@@ -5322,7 +6223,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
5322
6223
  //#endregion
5323
6224
  //#region src/view/render.ts
5324
6225
  const LEADING_SLASH_RE$4 = /^\/+/;
5325
- const TEMPLATE_INTERPOLATION_RE$1 = /\{\{([^{}]+)\}\}/g;
6226
+ const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
5326
6227
  function resolveRawValueByPath$1(source, expression) {
5327
6228
  const normalized = expression.trim();
5328
6229
  if (!normalized) return;
@@ -5334,12 +6235,12 @@ function resolveRawValueByPath$1(source, expression) {
5334
6235
  }
5335
6236
  return current;
5336
6237
  }
5337
- function resolveValueByPath$1(source, expression) {
6238
+ function resolveValueByPath(source, expression) {
5338
6239
  return resolveRawValueByPath$1(source, expression) ?? "";
5339
6240
  }
5340
6241
  function interpolateTemplate$1(input, data) {
5341
- return input.replace(TEMPLATE_INTERPOLATION_RE$1, (_match, expression) => {
5342
- const value = resolveValueByPath$1(data, expression);
6242
+ return input.replace(TEMPLATE_INTERPOLATION_RE, (_match, expression) => {
6243
+ const value = resolveValueByPath(data, expression);
5343
6244
  return typeof value === "string" ? value : String(value);
5344
6245
  });
5345
6246
  }
@@ -5397,36 +6298,10 @@ function renderPageTree(project, page) {
5397
6298
  wxml: serializeDomNode$1((document.children ?? [])[0] ?? document)
5398
6299
  };
5399
6300
  }
5400
- //#endregion
5401
- //#region src/view/selectorQuery.ts
5402
- const LEADING_MARK_PREFIX_RE = /^mark[:\-]?/;
5403
- const MARK_NAME_RE = /[:\-]([a-z])/g;
5404
- const NUMERIC_LIKE_VALUE_RE$1 = /-?\d+(?:\.\d+)?/;
5405
- function toMarkKey(attributeName) {
5406
- return attributeName.replace(LEADING_MARK_PREFIX_RE, "").replace(MARK_NAME_RE, (_match, char) => char.toUpperCase());
5407
- }
5408
- function collectMark(node) {
5409
- const mark = {};
5410
- for (const [key, value] of Object.entries(node.attribs ?? {})) {
5411
- if (!(key.startsWith("mark:") || key.startsWith("mark-"))) continue;
5412
- mark[toMarkKey(key)] = value;
5413
- }
5414
- return mark;
5415
- }
5416
- function createScopedRoot(node) {
5417
- return {
5418
- children: [node],
5419
- type: "root"
5420
- };
5421
- }
5422
- function findNodeByScopeId(root, scopeId) {
5423
- if (root.attribs?.["data-sim-scope"] === scopeId) return root;
5424
- for (const child of root.children ?? []) {
5425
- const match = findNodeByScopeId(child, scopeId);
5426
- if (match) return match;
5427
- }
5428
- return null;
5429
- }
6301
+ //#endregion
6302
+ //#region src/view/nodeGeometry.ts
6303
+ const NUMERIC_LIKE_VALUE_RE$1 = /-?\d+(?:\.\d+)?/;
6304
+ const PIXEL_LENGTH_RE = /^\d+(?:\.\d+)?px$|^0$/;
5430
6305
  function parseStyleDeclarations$1(styleValue) {
5431
6306
  const declarations = {};
5432
6307
  if (!styleValue) return declarations;
@@ -5461,18 +6336,229 @@ function resolveRect$1(node, windowInfo) {
5461
6336
  width
5462
6337
  };
5463
6338
  }
6339
+ /** 仅支持显式 px 视口和单个 view 内容盒;未知样式布局不作为已测量滚动范围。 */
6340
+ function resolveNativeScrollBounds(node) {
6341
+ const viewport = parseStyleDeclarations$1(node.attribs?.style);
6342
+ let content;
6343
+ const visit = (parent) => {
6344
+ for (const child of parent.children ?? []) {
6345
+ if (child.type === "comment" || child.type === "text" && !child.data?.trim()) continue;
6346
+ if (child.name === "block") {
6347
+ if (!visit(child)) return false;
6348
+ } else {
6349
+ if (content || child.name !== "view") return false;
6350
+ content = child;
6351
+ }
6352
+ }
6353
+ return true;
6354
+ };
6355
+ if (!visit(node)) return {
6356
+ maxTop: 0,
6357
+ maxLeft: 0
6358
+ };
6359
+ const box = parseStyleDeclarations$1(content?.attribs?.style);
6360
+ const supported = content && !viewport.display && !box.display && !box.position && !box.transform;
6361
+ const extent = (dimension) => {
6362
+ const viewportValue = viewport[dimension];
6363
+ const contentValue = box[dimension];
6364
+ if (!supported || !viewportValue || !contentValue || !PIXEL_LENGTH_RE.test(viewportValue) || !PIXEL_LENGTH_RE.test(contentValue)) return 0;
6365
+ const size = parseNumericLikeValue$1(viewportValue);
6366
+ const contentSize = parseNumericLikeValue$1(contentValue);
6367
+ return size > 0 && Number.isFinite(size) && Number.isFinite(contentSize) ? Math.max(0, contentSize - size) : 0;
6368
+ };
6369
+ return {
6370
+ maxTop: extent("height"),
6371
+ maxLeft: extent("width")
6372
+ };
6373
+ }
6374
+ //#endregion
6375
+ //#region src/view/nativeNode.ts
6376
+ const pageScrollViews = /* @__PURE__ */ new WeakMap();
6377
+ function coordinate(value) {
6378
+ const number = Number(value);
6379
+ return Number.isFinite(number) ? Math.max(0, number) : 0;
6380
+ }
6381
+ function nodeKey(node) {
6382
+ return node.attribs?.["data-sim-node"] ?? "";
6383
+ }
6384
+ /** 原生滚动位置独立于绑定值;未改变的绑定不能覆盖用户滚动。 */
6385
+ function syncNativeScrollViews(page, root, emit) {
6386
+ let states = pageScrollViews.get(page);
6387
+ let present;
6388
+ const visit = (node) => {
6389
+ if (node.name === "scroll-view") {
6390
+ const key = nodeKey(node);
6391
+ present ??= /* @__PURE__ */ new Set();
6392
+ present.add(key);
6393
+ if (!states) {
6394
+ states = /* @__PURE__ */ new Map();
6395
+ pageScrollViews.set(page, states);
6396
+ }
6397
+ const boundTop = coordinate(node.attribs?.["scroll-top"]);
6398
+ const boundLeft = coordinate(node.attribs?.["scroll-left"]);
6399
+ const bounds = resolveNativeScrollBounds(node);
6400
+ const scrollY = node.attribs?.["scroll-y"];
6401
+ const scrollX = node.attribs?.["scroll-x"];
6402
+ const maxTop = scrollY !== void 0 && scrollY !== "false" && scrollY !== "0" ? bounds.maxTop : 0;
6403
+ const maxLeft = scrollX !== void 0 && scrollX !== "false" && scrollX !== "0" ? bounds.maxLeft : 0;
6404
+ let state = states.get(key);
6405
+ const previousTop = state?.scrollTop ?? 0;
6406
+ const previousLeft = state?.scrollLeft ?? 0;
6407
+ if (!state) {
6408
+ state = {
6409
+ boundTop,
6410
+ boundLeft,
6411
+ scrollTop: boundTop,
6412
+ scrollLeft: boundLeft,
6413
+ maxTop,
6414
+ maxLeft
6415
+ };
6416
+ states.set(key, state);
6417
+ } else {
6418
+ if (state.boundTop !== boundTop) {
6419
+ state.scrollTop = boundTop;
6420
+ state.boundTop = boundTop;
6421
+ }
6422
+ if (state.boundLeft !== boundLeft) {
6423
+ state.scrollLeft = boundLeft;
6424
+ state.boundLeft = boundLeft;
6425
+ }
6426
+ }
6427
+ state.maxTop = maxTop;
6428
+ state.maxLeft = maxLeft;
6429
+ state.scrollTop = Math.min(state.scrollTop, maxTop);
6430
+ state.scrollLeft = Math.min(state.scrollLeft, maxLeft);
6431
+ if (state.scrollTop !== previousTop || state.scrollLeft !== previousLeft) {
6432
+ const binding = resolveMiniProgramEventBinding(node.attribs, "scroll");
6433
+ if (binding?.method) {
6434
+ const target = {
6435
+ id: node.attribs?.id ?? "",
6436
+ dataset: collectNodeDataset(node)
6437
+ };
6438
+ emit(node.attribs?.["data-sim-scope"] ?? null, binding.method, {
6439
+ type: "scroll",
6440
+ timeStamp: Date.now(),
6441
+ detail: {
6442
+ scrollTop: state.scrollTop,
6443
+ scrollLeft: state.scrollLeft
6444
+ },
6445
+ target,
6446
+ currentTarget: target
6447
+ });
6448
+ }
6449
+ }
6450
+ }
6451
+ for (const child of node.children ?? []) visit(child);
6452
+ };
6453
+ visit(root);
6454
+ if (states) {
6455
+ for (const key of states.keys()) if (!present?.has(key)) states.delete(key);
6456
+ }
6457
+ }
6458
+ function getNativeScrollOffset(page, node) {
6459
+ const state = pageScrollViews.get(page)?.get(nodeKey(node));
6460
+ return {
6461
+ scrollTop: state?.scrollTop ?? 0,
6462
+ scrollLeft: state?.scrollLeft ?? 0
6463
+ };
6464
+ }
6465
+ /** 原生交互更新宿主状态,导航仍交给统一 wx 路由入口。 */
6466
+ function dispatchNativeNodeEvent(page, node, eventName, event, wx, resolveMethod, onHandlerResult) {
6467
+ if (eventName === "scroll" && node.name === "scroll-view") {
6468
+ const detail = event.detail;
6469
+ const state = pageScrollViews.get(page)?.get(nodeKey(node));
6470
+ if (state) {
6471
+ if (detail?.scrollTop !== void 0) state.scrollTop = Math.min(coordinate(detail.scrollTop), state.maxTop);
6472
+ if (detail?.scrollLeft !== void 0) state.scrollLeft = Math.min(coordinate(detail.scrollLeft), state.maxLeft);
6473
+ }
6474
+ event.detail = Object.assign(event.detail && typeof event.detail === "object" ? event.detail : {}, getNativeScrollOffset(page, node));
6475
+ return true;
6476
+ }
6477
+ if (eventName !== "tap") return false;
6478
+ let current = node;
6479
+ let navigator;
6480
+ let handlers;
6481
+ let handled = false;
6482
+ while (current) {
6483
+ if (!navigator && current.name === "navigator") navigator = current;
6484
+ const binding = resolveMiniProgramEventBinding(current.attribs, "tap");
6485
+ if (binding?.method) {
6486
+ const call = resolveMethod(current.attribs?.["data-sim-scope"] ?? null, binding.method);
6487
+ handlers ??= [];
6488
+ handlers.push({
6489
+ node: current,
6490
+ call
6491
+ });
6492
+ handled = true;
6493
+ }
6494
+ if (binding?.stopAfter) {
6495
+ handled = true;
6496
+ break;
6497
+ }
6498
+ current = current.parent;
6499
+ }
6500
+ if (handlers) for (const handler of handlers) {
6501
+ const result = handler.call(createMiniProgramEventPayload(handler.node, "tap", event, node));
6502
+ onHandlerResult?.(result);
6503
+ }
6504
+ if (!navigator) return handled;
6505
+ const openType = navigator.attribs?.["open-type"] ?? "navigate";
6506
+ const url = navigator.attribs?.url ?? "";
6507
+ switch (openType) {
6508
+ case "navigate":
6509
+ wx.navigateTo({ url });
6510
+ break;
6511
+ case "redirect":
6512
+ wx.redirectTo({ url });
6513
+ break;
6514
+ case "switchTab":
6515
+ wx.switchTab({ url });
6516
+ break;
6517
+ case "reLaunch":
6518
+ wx.reLaunch({ url });
6519
+ break;
6520
+ case "navigateBack":
6521
+ wx.navigateBack({ delta: Number(navigator.attribs?.delta ?? 1) });
6522
+ break;
6523
+ default: return handled;
6524
+ }
6525
+ return true;
6526
+ }
6527
+ //#endregion
6528
+ //#region src/view/selectorQuery.ts
6529
+ const LEADING_MARK_PREFIX_RE = /^mark[:\-]?/;
6530
+ const MARK_NAME_RE = /[:\-]([a-z])/g;
6531
+ function toMarkKey(attributeName) {
6532
+ return attributeName.replace(LEADING_MARK_PREFIX_RE, "").replace(MARK_NAME_RE, (_match, char) => char.toUpperCase());
6533
+ }
6534
+ function collectMark(node) {
6535
+ const mark = {};
6536
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
6537
+ if (!(key.startsWith("mark:") || key.startsWith("mark-"))) continue;
6538
+ mark[toMarkKey(key)] = value;
6539
+ }
6540
+ return mark;
6541
+ }
6542
+ function createScopedRoot(node) {
6543
+ return {
6544
+ children: [node],
6545
+ type: "root"
6546
+ };
6547
+ }
6548
+ function findNodeByScopeId(root, scopeId) {
6549
+ if (root.attribs?.["data-sim-scope"] === scopeId) return root;
6550
+ for (const child of root.children ?? []) {
6551
+ const match = findNodeByScopeId(child, scopeId);
6552
+ if (match) return match;
6553
+ }
6554
+ return null;
6555
+ }
5464
6556
  function resolveSelectorScrollTop(root, selector) {
5465
6557
  const normalizedSelector = selector?.trim();
5466
6558
  if (!normalizedSelector) return null;
5467
6559
  const match = querySelectorAll(root, normalizedSelector)[0];
5468
6560
  return match ? resolveRect$1(match).top : null;
5469
6561
  }
5470
- function resolveScrollOffset(node) {
5471
- return {
5472
- scrollLeft: parseNumericLikeValue$1(node.attribs?.["data-sim-scroll-left"]),
5473
- scrollTop: parseNumericLikeValue$1(node.attribs?.["data-sim-scroll-top"])
5474
- };
5475
- }
5476
6562
  function resolvePropertyValue(node, propertyName) {
5477
6563
  const normalizedPropertyName = propertyName.trim();
5478
6564
  if (!normalizedPropertyName) return;
@@ -5505,7 +6591,7 @@ function resolveFieldsResult(node, fields, options) {
5505
6591
  result.height = rect.height;
5506
6592
  }
5507
6593
  }
5508
- if (fields.scrollOffset) Object.assign(result, resolveScrollOffset(node));
6594
+ if (fields.scrollOffset) Object.assign(result, getNativeScrollOffset(options.page, node));
5509
6595
  if (Array.isArray(fields.properties) && fields.properties.length > 0) Object.assign(result, pickProperties(node, fields.properties));
5510
6596
  if (Array.isArray(fields.computedStyle) && fields.computedStyle.length > 0) Object.assign(result, pickComputedStyle(node, fields.computedStyle));
5511
6597
  if (fields.context) result.context = options.resolveContext?.(node) ?? { type: "unsupported-context" };
@@ -6352,6 +7438,7 @@ var BrowserHeadlessSession = class {
6352
7438
  componentScopes = /* @__PURE__ */ new Map();
6353
7439
  selectorQueryScopeSnapshots = /* @__PURE__ */ new WeakMap();
6354
7440
  renderRequestPending = false;
7441
+ renderInProgress = false;
6355
7442
  renderRequestCallbacks = [];
6356
7443
  tabBarRoutes;
6357
7444
  tabPages = /* @__PURE__ */ new Map();
@@ -6365,6 +7452,7 @@ var BrowserHeadlessSession = class {
6365
7452
  launchOptions = createAppLaunchOptions("", {});
6366
7453
  kernel = new RuntimeKernel();
6367
7454
  startupNavigation = new StartupNavigationQueue(this.kernel.scheduler);
7455
+ routeEvents = new HeadlessRouteEvents((callback) => this.requestRender(callback), (page) => this.currentPageInstance === page && !this.kernel.isClosed);
6368
7456
  wxState;
6369
7457
  pullDownRefreshState = {
6370
7458
  active: false,
@@ -6372,7 +7460,10 @@ var BrowserHeadlessSession = class {
6372
7460
  };
6373
7461
  constructor(options) {
6374
7462
  this.files = options.files;
6375
- this.wxState = createHeadlessWxState(this.kernel.scheduler, { strictMocks: options.strictHostMocks });
7463
+ this.wxState = createHeadlessWxState(this.kernel.scheduler, {
7464
+ strictMocks: options.strictHostMocks,
7465
+ readPackageFile: createPackageAssetReader((relative) => readBrowserVirtualFile(this.files, join(this.project.miniprogramRootPath, relative)))
7466
+ });
6376
7467
  this.onRender = options.onRender;
6377
7468
  this.project = options.project ?? createBrowserProject(options.files);
6378
7469
  this.registries = createHostRegistries();
@@ -6424,7 +7515,7 @@ var BrowserHeadlessSession = class {
6424
7515
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
6425
7516
  getNetworkType: () => this.wxState.getNetworkType(),
6426
7517
  navigateBack: (option) => this.navigateBack(option?.delta),
6427
- navigateTo: (option) => this.navigateTo(option.url),
7518
+ navigateTo: (option) => this.routeEvents.navigateTo(() => this.navigateTo(option.url), option),
6428
7519
  pageScrollTo: (option) => this.pageScrollTo(option),
6429
7520
  openDocument: (option) => this.wxState.openDocument(option),
6430
7521
  clearStorageSync: () => this.wxState.clearStorageSync(),
@@ -6441,6 +7532,14 @@ var BrowserHeadlessSession = class {
6441
7532
  saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
6442
7533
  saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
6443
7534
  nextTick: (callback) => this.kernel.scheduler.queueMicrotask(() => callback?.()),
7535
+ offBeforeAppRoute: (listener) => this.routeEvents.off("beforeAppRoute", listener),
7536
+ offBeforePageUnload: (listener) => this.routeEvents.off("beforePageUnload", listener),
7537
+ offAppRoute: (listener) => this.routeEvents.off("appRoute", listener),
7538
+ offAppRouteDone: (listener) => this.routeEvents.off("appRouteDone", listener),
7539
+ onBeforeAppRoute: (listener) => this.routeEvents.on("beforeAppRoute", listener),
7540
+ onBeforePageUnload: (listener) => this.routeEvents.on("beforePageUnload", listener),
7541
+ onAppRoute: (listener) => this.routeEvents.on("appRoute", listener),
7542
+ onAppRouteDone: (listener) => this.routeEvents.on("appRouteDone", listener),
6444
7543
  offAppHide: (callback) => this.appLifecycle.offAppHide(callback),
6445
7544
  offAppShow: (callback) => this.appLifecycle.offAppShow(callback),
6446
7545
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
@@ -6491,14 +7590,21 @@ var BrowserHeadlessSession = class {
6491
7590
  }
6492
7591
  close() {
6493
7592
  if (this.kernel.isClosed) return;
6494
- this.unloadAllPages();
7593
+ let failure;
7594
+ try {
7595
+ this.unloadAllPages(void 0, true);
7596
+ } catch (error) {
7597
+ failure = { error };
7598
+ }
6495
7599
  this.canvasContexts.clear();
6496
7600
  this.renderRequestCallbacks.length = 0;
6497
7601
  this.renderRequestPending = false;
6498
7602
  this.appLifecycle.close();
7603
+ this.routeEvents.close();
6499
7604
  this.wxState.close();
6500
7605
  this.moduleLoader.close();
6501
7606
  this.kernel.close();
7607
+ if (failure) throw failure.error;
6502
7608
  }
6503
7609
  getDiagnostics() {
6504
7610
  return this.kernel.diagnostics.getEntries();
@@ -6784,19 +7890,19 @@ var BrowserHeadlessSession = class {
6784
7890
  return this.getComponentScopeId(component);
6785
7891
  }
6786
7892
  selectComponent(selector) {
6787
- this.renderCurrentPage();
7893
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
6788
7894
  return this.selectComponentsWithin(null, selector)[0] ?? null;
6789
7895
  }
6790
7896
  selectAllComponents(selector) {
6791
- this.renderCurrentPage();
7897
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
6792
7898
  return this.selectComponentsWithin(null, selector);
6793
7899
  }
6794
7900
  selectComponentWithin(scopeId, selector) {
6795
- this.renderCurrentPage();
7901
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
6796
7902
  return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
6797
7903
  }
6798
7904
  selectAllComponentsWithin(scopeId, selector) {
6799
- this.renderCurrentPage();
7905
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
6800
7906
  return this.selectComponentsWithin(scopeId, selector);
6801
7907
  }
6802
7908
  selectOwnerComponent(scopeId) {
@@ -6843,6 +7949,11 @@ var BrowserHeadlessSession = class {
6843
7949
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
6844
7950
  }
6845
7951
  }, current);
7952
+ syncNativeScrollViews(current, rendered.root, (scopeId, method, event) => {
7953
+ this.kernel.scheduler.queueMicrotask(() => {
7954
+ if (this.currentPageInstance === current) this.callScopeMethod(scopeId, method, event);
7955
+ });
7956
+ });
6846
7957
  current.__lastChangedKeys__ = [];
6847
7958
  const componentScopePrefix = `page:${stripLeadingSlash$1(current.route)}`;
6848
7959
  for (const [scopeId, instance] of this.componentCache.entries()) if (scopeId.startsWith(componentScopePrefix)) this.selectorQueryScopeSnapshots.set(instance, {
@@ -6852,38 +7963,63 @@ var BrowserHeadlessSession = class {
6852
7963
  });
6853
7964
  return rendered;
6854
7965
  }
7966
+ dispatchNativeNodeEvent(node, eventName, event, onHandlerResult) {
7967
+ const current = this.requireCurrentPage("dispatchNativeNodeEvent()");
7968
+ if (eventName === "tap") this.renderCurrentPage();
7969
+ return dispatchNativeNodeEvent(current, node, eventName, event, this.moduleLoader.wx, (scopeId, method) => this.resolveScopeMethod(current, scopeId, method), onHandlerResult);
7970
+ }
6855
7971
  requestRender(callback) {
6856
7972
  this.assertActive();
6857
7973
  if (callback) this.renderRequestCallbacks.push(callback);
6858
7974
  if (this.renderRequestPending) return;
6859
7975
  this.renderRequestPending = true;
6860
- Promise.resolve().then(() => {
7976
+ if (this.renderInProgress) return;
7977
+ Promise.resolve().then(async () => {
6861
7978
  if (this.kernel.isClosed) return;
6862
7979
  this.renderRequestPending = false;
7980
+ this.renderInProgress = true;
6863
7981
  const callbacks = this.renderRequestCallbacks.splice(0);
6864
- if (this.currentPageInstance) this.renderCurrentPage();
6865
- callbacks.forEach((cb) => cb());
6866
- this.onRender?.();
7982
+ try {
7983
+ if (this.currentPageInstance) this.renderCurrentPage();
7984
+ const rendered = this.onRender?.();
7985
+ if (rendered && typeof rendered.then === "function") await rendered;
7986
+ for (const cb of callbacks) {
7987
+ if (this.kernel.isClosed) break;
7988
+ cb();
7989
+ }
7990
+ } finally {
7991
+ this.renderInProgress = false;
7992
+ if (this.renderRequestPending && !this.kernel.isClosed) {
7993
+ this.renderRequestPending = false;
7994
+ this.requestRender();
7995
+ }
7996
+ }
6867
7997
  });
6868
7998
  }
6869
7999
  callScopeMethod(scopeId, methodName, event) {
6870
8000
  const current = this.requireCurrentPage(`scope method "${methodName}"`);
6871
8001
  this.renderCurrentPage();
6872
- if (!scopeId || scopeId === `page:${stripLeadingSlash$1(current.route)}`) {
8002
+ return this.resolveScopeMethod(current, scopeId, methodName)(event);
8003
+ }
8004
+ /** 解析本次交互的实例,后续回调不随重渲染或导航切换所有者。 */
8005
+ resolveScopeMethod(current, scopeId, methodName) {
8006
+ if (!scopeId || scopeId === `page:${stripLeadingSlash$1(current.route)}`) return (event) => {
6873
8007
  const method = current[methodName];
6874
8008
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator page ${current.route}.`);
6875
8009
  return method.call(current, event);
6876
- }
8010
+ };
6877
8011
  const instance = this.componentCache.get(scopeId);
6878
8012
  if (!instance) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
6879
- instance.__lastInteractionEvent__ = {
6880
- currentTarget: event.currentTarget,
6881
- mark: event.mark,
6882
- target: event.target
8013
+ return (event) => {
8014
+ instance.__lastInteractionEvent__ = {
8015
+ currentTarget: event.currentTarget,
8016
+ mark: event.mark,
8017
+ target: event.target
8018
+ };
8019
+ const method = instance[methodName];
8020
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator component scope "${scopeId}".`);
8021
+ return method.call(instance, event);
6883
8022
  };
6884
- const method = instance[methodName];
6885
- if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator component scope "${scopeId}".`);
6886
- return method.call(instance, event);
6887
8023
  }
6888
8024
  callScopeMethodDirect(scopeId, methodName, ...args) {
6889
8025
  const normalizedScopeId = scopeId.trim();
@@ -6971,11 +8107,13 @@ var BrowserHeadlessSession = class {
6971
8107
  const target = this.resolveNavigationTarget(url);
6972
8108
  const launchedPage = this.bootstrapNavigation(createAppLaunchOptions(target.normalizedRoute, target.query));
6973
8109
  if (launchedPage) return launchedPage;
6974
- this.unloadAllPages();
6975
- const pageInstance = this.createFreshPage(target);
8110
+ const event = this.beginRoute(target, "reLaunch");
8111
+ this.unloadAllPages(event);
8112
+ const pageInstance = this.createFreshPage(target, event);
6976
8113
  this.pages.push(pageInstance);
6977
8114
  this.currentPageInstance = pageInstance;
6978
8115
  this.runInitialPageLifecycles(pageInstance, target.query);
8116
+ this.routeEvents.commit(pageInstance, event);
6979
8117
  return pageInstance;
6980
8118
  }
6981
8119
  navigateTo(url) {
@@ -6984,12 +8122,14 @@ var BrowserHeadlessSession = class {
6984
8122
  if (launchedPage) return launchedPage;
6985
8123
  if (this.pages.length >= PAGE_STACK_LIMIT$1) throw new Error(`Cannot navigateTo() beyond a ${PAGE_STACK_LIMIT$1}-page stack in browser simulator runtime.`);
6986
8124
  if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
8125
+ const event = this.beginRoute(target, "navigateTo");
6987
8126
  this.currentPageInstance?.onHide?.();
6988
8127
  if (this.currentPageInstance) this.runPageComponentLifetime(this.currentPageInstance.route, "hide");
6989
- const pageInstance = this.createFreshPage(target);
8128
+ const pageInstance = this.createFreshPage(target, event);
6990
8129
  this.pages.push(pageInstance);
6991
8130
  this.currentPageInstance = pageInstance;
6992
8131
  this.runInitialPageLifecycles(pageInstance, target.query);
8132
+ this.routeEvents.commit(pageInstance, event);
6993
8133
  return pageInstance;
6994
8134
  }
6995
8135
  redirectTo(url) {
@@ -6997,15 +8137,17 @@ var BrowserHeadlessSession = class {
6997
8137
  const launchedPage = this.bootstrapNavigation(createAppLaunchOptions(target.normalizedRoute, target.query));
6998
8138
  if (launchedPage) return launchedPage;
6999
8139
  if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.redirectTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
8140
+ const event = this.beginRoute(target, "redirectTo");
7000
8141
  const current = this.currentPageInstance;
7001
8142
  if (current) {
8143
+ this.unloadPage(current, event);
7002
8144
  this.pages.pop();
7003
- this.unloadPage(current);
7004
8145
  }
7005
- const pageInstance = this.createFreshPage(target);
8146
+ const pageInstance = this.createFreshPage(target, event);
7006
8147
  this.pages.push(pageInstance);
7007
8148
  this.currentPageInstance = pageInstance;
7008
8149
  this.runInitialPageLifecycles(pageInstance, target.query);
8150
+ this.routeEvents.commit(pageInstance, event);
7009
8151
  return pageInstance;
7010
8152
  }
7011
8153
  navigateBack(delta = 1) {
@@ -7013,12 +8155,17 @@ var BrowserHeadlessSession = class {
7013
8155
  if (launchedPage) return launchedPage;
7014
8156
  if (this.pages.length <= 1) return this.currentPageInstance;
7015
8157
  const removableCount = Math.min(Number.isFinite(delta) ? Math.max(1, Math.trunc(delta)) : 1, this.pages.length - 1);
7016
- const removedPages = this.pages.splice(this.pages.length - removableCount, removableCount);
7017
- for (const page of removedPages.reverse()) this.unloadPage(page);
7018
- const nextPage = this.pages.at(-1) ?? null;
8158
+ const nextPage = this.pages[this.pages.length - removableCount - 1];
8159
+ const event = this.routeEvents.begin(nextPage.route, nextPage.options, "navigateBack", void 0, nextPage);
8160
+ this.routeEvents.attach(nextPage, event);
8161
+ for (let index = 0; index < removableCount; index++) {
8162
+ this.unloadPage(this.pages.at(-1), event);
8163
+ this.pages.pop();
8164
+ }
7019
8165
  this.currentPageInstance = nextPage;
7020
8166
  nextPage?.onShow?.();
7021
8167
  if (nextPage) this.runPageComponentLifetime(nextPage.route, "show");
8168
+ this.routeEvents.commit(nextPage, event);
7022
8169
  return nextPage;
7023
8170
  }
7024
8171
  switchTab(url) {
@@ -7036,6 +8183,8 @@ var BrowserHeadlessSession = class {
7036
8183
  const current = this.currentPageInstance;
7037
8184
  const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
7038
8185
  if (current === cachedTarget && current) return () => {};
8186
+ const event = this.beginRoute(target, "switchTab", cachedTarget ?? void 0);
8187
+ if (cachedTarget) this.routeEvents.attach(cachedTarget, event);
7039
8188
  if (current && current !== cachedTarget) {
7040
8189
  current.onHide?.();
7041
8190
  this.runPageComponentLifetime(current.route, "hide");
@@ -7045,7 +8194,7 @@ var BrowserHeadlessSession = class {
7045
8194
  let nextPage = cachedTarget;
7046
8195
  let shouldRunInitialLifecycles = false;
7047
8196
  if (!nextPage) {
7048
- nextPage = this.createFreshPage(target);
8197
+ nextPage = this.createFreshPage(target, event);
7049
8198
  this.tabPages.set(target.routeRecord.route, nextPage);
7050
8199
  shouldRunInitialLifecycles = true;
7051
8200
  }
@@ -7058,7 +8207,8 @@ var BrowserHeadlessSession = class {
7058
8207
  this.runPageComponentLifetime(nextPage.route, "show");
7059
8208
  }
7060
8209
  return () => {
7061
- for (const page of pagesToUnload) this.unloadPage(page);
8210
+ for (const page of pagesToUnload) this.unloadPage(page, event);
8211
+ this.routeEvents.commit(nextPage, event);
7062
8212
  };
7063
8213
  }
7064
8214
  pageScrollTo(option) {
@@ -7182,17 +8332,20 @@ var BrowserHeadlessSession = class {
7182
8332
  windowInfo: this.getWindowInfo()
7183
8333
  });
7184
8334
  }
7185
- createFreshPage(target) {
8335
+ beginRoute(target, openType, page) {
8336
+ return this.routeEvents.begin(target.normalizedRoute, target.query, openType, target.pageConfig?.renderer ?? this.project.appConfig.renderer, page);
8337
+ }
8338
+ createFreshPage(target, event) {
7186
8339
  const resourcePath = target.routeRecord.resourcePath ?? target.routeRecord.route;
7187
8340
  const pageModulePath = join(this.project.miniprogramRootPath, `${resourcePath}.js`);
7188
- const pageConfigPath = join(this.project.miniprogramRootPath, `${resourcePath}.json`);
7189
8341
  const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
7190
- const pageConfig = readJsonObject$2(this.files, pageConfigPath);
8342
+ const pageConfig = target.pageConfig;
7191
8343
  const pageInstance = createPageInstance(target.routeRecord.route, pageDefinition, target.query, {
7192
8344
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
7193
8345
  navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig),
7194
8346
  requestRender: (callback) => this.requestRender(callback)
7195
8347
  });
8348
+ this.routeEvents.attach(pageInstance, event);
7196
8349
  pageInstance.createIntersectionObserver = (options) => this.createIntersectionObserver(pageInstance, options);
7197
8350
  pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
7198
8351
  pageInstance.selectComponent = (selector) => resolveNativeComponentSelection(this.selectComponent(selector));
@@ -7205,7 +8358,7 @@ var BrowserHeadlessSession = class {
7205
8358
  return pageInstance;
7206
8359
  }
7207
8360
  runInitialPageLifecycles(pageInstance, query) {
7208
- runInitialPageLifecycles(pageInstance, query, this.kernel.scheduler, () => this.pages.includes(pageInstance) || this.tabPages.get(pageInstance.route) === pageInstance, () => this.renderCurrentPage());
8361
+ runInitialPageLifecycles(pageInstance, query, this.kernel.scheduler, () => this.pages.includes(pageInstance) || this.tabPages.get(pageInstance.route) === pageInstance, () => this.renderCurrentPage(), () => this.routeEvents.ready(pageInstance));
7209
8362
  }
7210
8363
  isTabBarRoute(route) {
7211
8364
  return this.tabBarRoutes.has(stripLeadingSlash$1(route));
@@ -7228,7 +8381,8 @@ var BrowserHeadlessSession = class {
7228
8381
  return {
7229
8382
  normalizedRoute,
7230
8383
  query,
7231
- routeRecord
8384
+ routeRecord,
8385
+ pageConfig: readJsonObject$2(this.files, join(this.project.miniprogramRootPath, `${routeRecord.resourcePath ?? routeRecord.route}.json`))
7232
8386
  };
7233
8387
  }
7234
8388
  requireTabBarItem(index, action) {
@@ -7237,21 +8391,41 @@ var BrowserHeadlessSession = class {
7237
8391
  if (!item) throw new Error(`Cannot call ${action} with unknown tabBar index ${index} in browser simulator runtime.`);
7238
8392
  return item;
7239
8393
  }
7240
- unloadAllPages() {
8394
+ unloadAllPages(event, closing = false) {
7241
8395
  const pagesToUnload = /* @__PURE__ */ new Set([...this.pages, ...this.tabPages.values()]);
7242
- for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
8396
+ let failure;
8397
+ for (const page of [...pagesToUnload].reverse()) try {
8398
+ this.unloadPage(page, event, closing);
8399
+ } catch (error) {
8400
+ if (!closing) throw error;
8401
+ failure ??= { error };
8402
+ }
7243
8403
  this.pages.length = 0;
7244
8404
  this.tabPages.clear();
7245
8405
  this.componentCache.clear();
7246
8406
  this.componentScopes.clear();
7247
8407
  this.clearMediaQueryObservers();
7248
8408
  this.currentPageInstance = null;
8409
+ if (failure) throw failure.error;
7249
8410
  }
7250
- unloadPage(page) {
7251
- page.onUnload?.();
8411
+ unloadPage(page, event, closing = false) {
8412
+ let failure;
8413
+ try {
8414
+ this.routeEvents.beforeUnload(page, event);
8415
+ page.onUnload?.();
8416
+ } catch (error) {
8417
+ if (!closing) throw error;
8418
+ failure = { error };
8419
+ }
7252
8420
  this.clearMediaQueryObservers(page);
7253
- this.detachPageComponents(page.route);
8421
+ try {
8422
+ this.detachPageComponents(page.route, closing);
8423
+ } catch (error) {
8424
+ if (!closing) throw error;
8425
+ failure ??= { error };
8426
+ }
7254
8427
  this.tabPages.delete(stripLeadingSlash$1(page.route));
8428
+ if (failure) throw failure.error;
7255
8429
  }
7256
8430
  requireCurrentPage(action) {
7257
8431
  this.bootstrap();
@@ -7259,15 +8433,27 @@ var BrowserHeadlessSession = class {
7259
8433
  if (!current) throw new Error(`Cannot call ${action} without an active page in browser simulator runtime.`);
7260
8434
  return current;
7261
8435
  }
7262
- detachPageComponents(route) {
8436
+ detachPageComponents(route, closing = false) {
7263
8437
  const prefix = `page:${stripLeadingSlash$1(route)}`;
7264
8438
  const removed = [...this.componentCache].filter(([scopeId]) => scopeId.startsWith(prefix));
7265
- for (const [, instance] of removed) runComponentLifecycle(instance, "detached");
7266
- detachComponentRelations(removed.map(([, instance]) => instance));
8439
+ let failure;
8440
+ for (const [, instance] of removed) try {
8441
+ runComponentLifecycle(instance, "detached");
8442
+ } catch (error) {
8443
+ if (!closing) throw error;
8444
+ failure ??= { error };
8445
+ }
8446
+ try {
8447
+ detachComponentRelations(removed.map(([, instance]) => instance));
8448
+ } catch (error) {
8449
+ if (!closing) throw error;
8450
+ failure ??= { error };
8451
+ }
7267
8452
  for (const [scopeId] of removed) {
7268
8453
  this.componentCache.delete(scopeId);
7269
8454
  this.componentScopes.delete(scopeId);
7270
8455
  }
8456
+ if (failure) throw failure.error;
7271
8457
  }
7272
8458
  notifyMediaQueryObservers() {
7273
8459
  for (const entry of [...this.mediaQueryObservers]) {
@@ -7537,7 +8723,6 @@ function getRuntimeWxsLoader(owner, artifactSource) {
7537
8723
  }
7538
8724
  //#endregion
7539
8725
  //#region src/runtime/render/shared.ts
7540
- const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
7541
8726
  const LEADING_SLASH_RE$2 = /^\/+/;
7542
8727
  const EVENT_BINDING_ATTRS = [
7543
8728
  "bindtap",
@@ -7557,8 +8742,7 @@ const STRUCTURAL_ATTRS = [
7557
8742
  const CLASS_SPLIT_RE = /\s+/;
7558
8743
  const JS_FILE_RE = /\.js$/;
7559
8744
  function isMustacheOnly(value) {
7560
- const trimmed = value.trim();
7561
- return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
8745
+ return isTemplateExpression(value);
7562
8746
  }
7563
8747
  function collectDataset(node, source) {
7564
8748
  if (node.dataset) return collectNodeDataset(node);
@@ -7583,17 +8767,11 @@ function cloneNode(node) {
7583
8767
  children: node.children?.map((child) => cloneNode(child))
7584
8768
  };
7585
8769
  }
7586
- function resolveValueByPath(source, expression) {
7587
- return resolveTemplateExpression(source, expression) ?? "";
7588
- }
7589
8770
  function resolveRawValueByPath(source, expression) {
7590
8771
  return resolveTemplateExpression(source, expression);
7591
8772
  }
7592
8773
  function interpolateTemplate(input, data) {
7593
- return input.replace(TEMPLATE_INTERPOLATION_RE, (_match, expression) => {
7594
- const value = resolveValueByPath(data, expression);
7595
- return typeof value === "string" ? value : String(value);
7596
- });
8774
+ return interpolateTemplateText(input, data, true);
7597
8775
  }
7598
8776
  function readTemplateSource(artifactSource, filePath) {
7599
8777
  const source = artifactSource.readText(filePath);
@@ -7720,7 +8898,7 @@ function resolveUsingComponents(context, ownerJsonPath, ownerFilePath) {
7720
8898
  return /* @__PURE__ */ new Map();
7721
8899
  }
7722
8900
  }
7723
- function resolveComponentGenerics(context, hostNode, ownerJsonPath, ownerFilePath, componentFilePath) {
8901
+ function resolveComponentGenerics(context, hostNode, ownerJsonPath, ownerFilePath, componentFilePath, ownerGenerics) {
7724
8902
  const componentJsonPath = path.resolve(context.project.miniprogramRootPath, `${componentFilePath.replace(JS_FILE_RE, "")}.json`);
7725
8903
  const componentGenerics = readComponentConfig(context.artifactSource, componentJsonPath).componentGenerics;
7726
8904
  if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return;
@@ -7728,7 +8906,7 @@ function resolveComponentGenerics(context, hostNode, ownerJsonPath, ownerFilePat
7728
8906
  const resolved = /* @__PURE__ */ new Map();
7729
8907
  for (const [genericName, definition] of Object.entries(componentGenerics)) {
7730
8908
  const selectedAlias = hostNode.attribs?.[`generic:${genericName}`];
7731
- const selectedPath = selectedAlias ? ownerComponents.get(selectedAlias) : void 0;
8909
+ const selectedPath = selectedAlias ? ownerGenerics?.get(selectedAlias) ?? ownerComponents.get(selectedAlias) : void 0;
7732
8910
  if (selectedPath) {
7733
8911
  resolved.set(genericName, selectedPath);
7734
8912
  continue;
@@ -7740,66 +8918,6 @@ function resolveComponentGenerics(context, hostNode, ownerJsonPath, ownerFilePat
7740
8918
  }
7741
8919
  return resolved.size > 0 ? resolved : void 0;
7742
8920
  }
7743
- function collectComponentEventBindings(hostNode) {
7744
- return collectMiniProgramEventBindings(hostNode.attribs);
7745
- }
7746
- function buildComponentTrigger(componentScopeId, context, hostNode) {
7747
- const hostDataset = collectDataset(hostNode);
7748
- const hostId = hostNode.attribs?.id ?? "";
7749
- return (instance, eventName, detail, triggerOptions) => {
7750
- const originScope = context.componentScopes.get(componentScopeId);
7751
- const interactionMark = instance.__lastInteractionEvent__?.mark;
7752
- const target = {
7753
- dataset: originScope?.dataset ?? hostDataset,
7754
- id: originScope?.hostId ?? hostId
7755
- };
7756
- let currentScopeId = componentScopeId;
7757
- while (currentScopeId) {
7758
- const currentScope = context.componentScopes.get(currentScopeId);
7759
- const binding = currentScope?.eventBindings?.get(eventName);
7760
- const listenerScope = currentScope?.listenerScopeId ? context.componentScopes.get(currentScope.listenerScopeId) : null;
7761
- const handler = binding && listenerScope ? listenerScope.getMethod(binding.method) : void 0;
7762
- if (handler) handler({
7763
- bubbles: triggerOptions?.bubbles ?? false,
7764
- capturePhase: false,
7765
- composed: triggerOptions?.composed ?? false,
7766
- currentTarget: {
7767
- dataset: currentScope?.dataset ?? hostDataset,
7768
- id: currentScope?.hostId ?? hostId
7769
- },
7770
- detail,
7771
- mark: interactionMark,
7772
- target,
7773
- type: eventName
7774
- });
7775
- if (binding?.stopAfter) break;
7776
- if (!triggerOptions?.bubbles || !triggerOptions?.composed) break;
7777
- currentScopeId = currentScope?.ownerScopeId;
7778
- }
7779
- };
7780
- }
7781
- function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
7782
- const changedRootKeys = [];
7783
- const previousProperties = {};
7784
- for (const [key, value] of Object.entries(nextProperties)) {
7785
- const nextValue = normalizeComponentPropertyValue(definition, key, value);
7786
- const bindingExpression = bindingExpressions[key];
7787
- const bindingAffected = !!bindingExpression && changedPageKeys.some((changedKey) => {
7788
- return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
7789
- });
7790
- const previousSnapshot = instance.__propertySnapshots?.[key];
7791
- if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
7792
- previousProperties[key] = instance.properties[key];
7793
- instance.properties[key] = nextValue;
7794
- if (Object.hasOwn(definition.properties ?? {}, key)) instance.data[key] = nextValue;
7795
- changedRootKeys.push(key);
7796
- }
7797
- instance.__propertySnapshots ??= {};
7798
- instance.__propertySnapshots[key] = cloneValue(nextValue);
7799
- }
7800
- if (changedRootKeys.length === 0) return;
7801
- runComponentObservers(definition, instance, changedRootKeys, previousProperties);
7802
- }
7803
8921
  function createComponentScope(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots) {
7804
8922
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
7805
8923
  return {
@@ -7807,7 +8925,7 @@ function createComponentScope(clonedNode, scope, componentScopeId, componentInst
7807
8925
  classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
7808
8926
  data: { ...componentInstance.data },
7809
8927
  dataset: collectDataset(clonedNode, wxsScopeData(scope)),
7810
- eventBindings: collectComponentEventBindings(clonedNode),
8928
+ ...bindComponentEventHost(clonedNode),
7811
8929
  getMethod: (methodName) => {
7812
8930
  const method = componentInstance?.[methodName];
7813
8931
  return typeof method === "function" ? method.bind(componentInstance) : void 0;
@@ -7815,6 +8933,7 @@ function createComponentScope(clonedNode, scope, componentScopeId, componentInst
7815
8933
  getScopeId: () => componentScopeId,
7816
8934
  genericComponents,
7817
8935
  hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
8936
+ hostNode: clonedNode,
7818
8937
  id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
7819
8938
  listenerScopeId: scope.getScopeId(),
7820
8939
  ownerScopeId,
@@ -7837,13 +8956,14 @@ function resolveComponentProperties(clonedNode, scope, definition) {
7837
8956
  bindingExpressions
7838
8957
  };
7839
8958
  }
7840
- function createRuntimeComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId, beforeCreated) {
8959
+ function createRuntimeComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, renderTemplate, bindEventsBeforeProperties = false) {
7841
8960
  const componentProperties = Object.keys(componentEntry.definition.methods ?? {}).some((key) => key.startsWith("__weapp_vite_")) || Object.hasOwn(componentEntry.definition.properties ?? {}, "__wvSlotOwnerId") ? Object.fromEntries(Object.keys(componentEntry.definition.properties ?? {}).filter((key) => Object.hasOwn(nextProperties, key)).map((key) => [key, nextProperties[key]])) : nextProperties;
7842
- const componentInstance = createComponentInstance({
8961
+ const instanceOptions = {
7843
8962
  definition: componentEntry.definition,
7844
- requestRender: (callback) => context.session.requestRender(callback),
7845
- triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
7846
- });
8963
+ requestRender: (callback) => context.session.requestRender(callback)
8964
+ };
8965
+ const componentInstance = createComponentInstance(instanceOptions);
8966
+ bindAttachmentBindingScope(componentInstance, context);
7847
8967
  setSelectorQueryScopeId(componentInstance, componentScopeId);
7848
8968
  componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE, "");
7849
8969
  componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
@@ -7851,19 +8971,29 @@ function createRuntimeComponentInstance(componentScopeId, context, clonedNode, c
7851
8971
  componentInstance.createSelectorQuery = () => context.moduleLoader.wx.createSelectorQuery().in(componentInstance);
7852
8972
  componentInstance.selectComponent = (selector) => resolveNativeComponentSelection(context.session.selectComponentWithin(componentScopeId, selector));
7853
8973
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector).map(resolveNativeComponentSelection);
7854
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
8974
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? resolveNativeComponentSelection(context.componentCache.get(ownerScopeId)) : null;
8975
+ beginComponentConstruction(context.componentCache, componentScopeId, componentInstance);
7855
8976
  context.componentCache.set(componentScopeId, componentInstance);
7856
- beforeCreated?.(componentInstance);
7857
- runComponentLifecycle(componentInstance, "created");
7858
- componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
7859
- syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, []);
7860
- return componentInstance;
8977
+ try {
8978
+ renderTemplate?.(componentInstance, "defaults");
8979
+ runComponentLifecycle(componentInstance, "created");
8980
+ if (bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
8981
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
8982
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, componentProperties, {}, [], renderTemplate);
8983
+ if (!bindEventsBeforeProperties) instanceOptions.triggerEvent = buildComponentTrigger(componentScopeId, context);
8984
+ return componentInstance;
8985
+ } catch (error) {
8986
+ discardComponentConstruction(context.componentCache, context.componentScopes, componentScopeId);
8987
+ throw error;
8988
+ } finally {
8989
+ finishComponentConstruction(context.componentCache, componentInstance);
8990
+ }
7861
8991
  }
7862
- function renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
8992
+ function renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, renderPass) {
7863
8993
  const componentDocument = parseTemplateDocument(readTemplateSource(context.artifactSource, componentEntry.absoluteTemplatePath));
7864
8994
  const componentRoot = (componentDocument.children ?? [])[0] ?? componentDocument;
7865
8995
  const templateRenderState = prepareTemplateRenderState(context.artifactSource, componentRoot, componentEntry.absoluteTemplatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
7866
- return renderNodeTree(componentRoot, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, seenComponentScopes, templateRenderState);
8996
+ return renderNodeTree(componentRoot, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, renderPass, templateRenderState, componentScope.hostNode);
7867
8997
  }
7868
8998
  //#endregion
7869
8999
  //#region src/runtime/render/index.ts
@@ -7877,24 +9007,33 @@ function expandNodeByFor(node, scope) {
7877
9007
  const items = resolveLoopEntries(resolveRawValueByPath(wxsScopeData(scope), forExpression));
7878
9008
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
7879
9009
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
9010
+ const key = node.attribs?.["wx:key"]?.trim();
9011
+ const keyOccurrences = key ? /* @__PURE__ */ new Map() : void 0;
7880
9012
  return items.map(([index, item]) => ({
7881
9013
  node: cloneNode(node),
7882
9014
  scope: createLoopScope(scope, itemName, indexName, item, index),
7883
- instanceSuffix: `:for-${index}`
9015
+ instanceSuffix: resolveLoopInstanceSuffix(item, index, key, keyOccurrences)
7884
9016
  }));
7885
9017
  }
7886
- function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
7887
- return expandNodeByFor(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes, templateRenderState));
9018
+ function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
9019
+ const nodes = [];
9020
+ if (isRenderPassStale(renderPass)) return nodes;
9021
+ for (const { node: expandedNode, scope: expandedScope, instanceSuffix } of expandNodeByFor(node, scope)) {
9022
+ if (isRenderPassStale(renderPass)) break;
9023
+ nodes.push(renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, renderPass, templateRenderState, parent));
9024
+ }
9025
+ return nodes;
7888
9026
  }
7889
- function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
9027
+ function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
7890
9028
  const renderedChildren = [];
7891
9029
  for (const { node: child, index } of selectConditionalChildren(children, (node) => evaluateConditionalBranch(node, scope))) {
9030
+ if (isRenderPassStale(renderPass)) break;
7892
9031
  if (!isTagNode(child)) {
7893
- renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
9032
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, renderPass, templateRenderState, parent));
7894
9033
  continue;
7895
9034
  }
7896
9035
  if (isTemplateDefinition(child) || child.name === "import" || child.name === "wxs") continue;
7897
- renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes, templateRenderState));
9036
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, renderPass, templateRenderState, parent));
7898
9037
  }
7899
9038
  return renderedChildren;
7900
9039
  }
@@ -7926,22 +9065,38 @@ function collectComponentSlots(componentNode, scope, ownerJsonPath, ownerFilePat
7926
9065
  }
7927
9066
  return slots;
7928
9067
  }
7929
- function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes, templateRenderState) {
9068
+ function reconcileSlotDeclarations(context, renderPass) {
9069
+ for (const [entries, { parent, scopeId }] of renderPass.slotDeclarations) {
9070
+ if (isRenderPassStale(renderPass)) return;
9071
+ if (isComponentConstructing(context.componentCache.get(scopeId))) continue;
9072
+ for (const { index } of selectConditionalChildren(entries.map((entry) => entry.node), (node, index) => evaluateConditionalBranch(node, entries[index].scope))) {
9073
+ if (isRenderPassStale(renderPass)) return;
9074
+ const entry = entries[index];
9075
+ if (renderPass.renderedSlots.has(entry)) continue;
9076
+ const nodes = renderNodeVariants(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, renderPass, entry.templateRenderState, parent);
9077
+ renderPass.renderedSlots.set(entry, nodes);
9078
+ renderPass.hasUnprojectedSlots ||= nodes.length > 0;
9079
+ }
9080
+ }
9081
+ }
9082
+ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, renderPass, templateRenderState, parent) {
9083
+ if (isRenderPassStale(renderPass)) return node;
7930
9084
  if (scope.wxs !== templateRenderState.wxsModules) scope = {
7931
9085
  ...scope,
7932
9086
  wxs: templateRenderState.wxsModules
7933
9087
  };
7934
9088
  const clonedNode = cloneNode(node);
9089
+ registerComponentEventNode(clonedNode, scope, parent);
7935
9090
  if (!isTagNode(clonedNode)) {
7936
9091
  applyNodeBindings(clonedNode, scope);
7937
9092
  return clonedNode;
7938
9093
  }
7939
- if (isTemplateDefinition(clonedNode)) return {
7940
- type: "tag",
7941
- name: "block",
7942
- attribs: {},
7943
- children: []
7944
- };
9094
+ if (isTemplateDefinition(clonedNode)) {
9095
+ clonedNode.name = "block";
9096
+ clonedNode.attribs = {};
9097
+ clonedNode.children = [];
9098
+ return clonedNode;
9099
+ }
7945
9100
  const templateName = resolveTemplateCall(clonedNode, wxsScopeData(scope));
7946
9101
  if (templateName) {
7947
9102
  const definition = templateRenderState.definitions.get(templateName);
@@ -7950,60 +9105,75 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
7950
9105
  data: resolveTemplateData(clonedNode, wxsScopeData(scope)),
7951
9106
  wxs: definition && templateRenderState.definitionWxsScopes?.get(definition)
7952
9107
  };
7953
- const children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, seenComponentScopes, {
9108
+ clonedNode.name = "block";
9109
+ clonedNode.attribs = {
9110
+ "data-sim-node": instancePath,
9111
+ "data-sim-scope": scope.getScopeId()
9112
+ };
9113
+ clonedNode.children = definition && !templateRenderState.stack.includes(templateName) ? renderChildren(definition.children ?? [], templateScope, context, ownerJsonPath, ownerFilePath, `${instancePath}/template-${templateName}`, renderPass, {
7954
9114
  definitions: templateRenderState.definitionScopes?.get(definition) ?? templateRenderState.definitions,
7955
9115
  definitionScopes: templateRenderState.definitionScopes,
7956
9116
  definitionWxsScopes: templateRenderState.definitionWxsScopes,
7957
9117
  wxsModules: templateScope.wxs,
7958
9118
  stack: [...templateRenderState.stack, templateName]
7959
- }) : [];
7960
- return {
7961
- type: "tag",
7962
- name: "block",
7963
- attribs: {
7964
- "data-sim-node": instancePath,
7965
- "data-sim-scope": scope.getScopeId()
7966
- },
7967
- children
7968
- };
9119
+ }, clonedNode) : [];
9120
+ return clonedNode;
7969
9121
  }
7970
9122
  if (clonedNode.name === "slot") {
7971
9123
  const slotName = clonedNode.attribs?.name?.trim() || "default";
7972
9124
  const projected = scope.slots?.get(slotName) ?? [];
7973
- const children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch(node, projected[index].scope)).flatMap(({ index }) => {
7974
- const entry = projected[index];
7975
- return renderNodeVariants(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, seenComponentScopes, entry.templateRenderState);
7976
- }) : renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, seenComponentScopes, templateRenderState);
7977
- return {
7978
- type: "tag",
7979
- name: "block",
7980
- attribs: {
7981
- "data-sim-node": instancePath,
7982
- "data-sim-scope": scope.getScopeId()
7983
- },
7984
- children
9125
+ const fallbackChildren = clonedNode.children ?? [];
9126
+ bindComponentEventHost(clonedNode);
9127
+ clonedNode.name = "block";
9128
+ clonedNode.attribs = {
9129
+ "data-sim-node": instancePath,
9130
+ "data-sim-scope": scope.getScopeId()
7985
9131
  };
9132
+ const slotOwner = scope.getScopeId();
9133
+ if (projected.length && slotOwner && isComponentConstructing(context.componentCache.get(slotOwner))) {
9134
+ clonedNode.children = [];
9135
+ return clonedNode;
9136
+ }
9137
+ clonedNode.children = projected.length ? selectConditionalChildren(projected.map((entry) => entry.node), (node, index) => evaluateConditionalBranch(node, projected[index].scope)).flatMap(({ index }) => {
9138
+ const entry = projected[index];
9139
+ const nodes = renderNodeVariants(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, renderPass, entry.templateRenderState, clonedNode);
9140
+ renderPass.renderedSlots.set(entry, nodes);
9141
+ return nodes;
9142
+ }) : renderChildren(fallbackChildren, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, renderPass, templateRenderState, clonedNode);
9143
+ return clonedNode;
7986
9144
  }
7987
9145
  const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name, scope.genericComponents?.get(clonedNode.name));
7988
9146
  if (componentEntry) {
7989
9147
  const componentScopeId = `${instancePath}/${clonedNode.name}`;
7990
9148
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
7991
9149
  const { nextProperties, bindingExpressions } = resolveComponentProperties(clonedNode, scope, componentEntry.definition);
7992
- const genericComponents = resolveComponentGenerics(context, clonedNode, ownerJsonPath, ownerFilePath, componentEntry.filePath);
9150
+ const genericComponents = resolveComponentGenerics(context, clonedNode, ownerJsonPath, ownerFilePath, componentEntry.filePath, scope.genericComponents);
7993
9151
  const slots = collectComponentSlots(clonedNode, scope, ownerJsonPath, ownerFilePath, componentScopeId, templateRenderState);
9152
+ registerSlotDeclarations(renderPass, slots, clonedNode, componentScopeId);
9153
+ applyNodeBindings(clonedNode, scope);
9154
+ const reconcilePrivateTemplate = (instance, phase) => {
9155
+ let bindingPass;
9156
+ do {
9157
+ const bindingScope = createComponentScope(clonedNode, scope, componentScopeId, instance, genericComponents, slots);
9158
+ context.componentScopes.set(componentScopeId, bindingScope);
9159
+ bindingPass = createRenderPass(phase === "properties", renderPass);
9160
+ renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, bindingScope, componentScopeId, bindingPass);
9161
+ reconcileSlotDeclarations(context, bindingPass);
9162
+ } while (isRenderPassStale(bindingPass));
9163
+ };
7994
9164
  let componentInstance = context.componentCache.get(componentScopeId);
7995
- if (!componentInstance) componentInstance = createRuntimeComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId, (instance) => {
7996
- const initialScope = createComponentScope(clonedNode, scope, componentScopeId, instance, genericComponents, slots);
7997
- context.componentScopes.set(componentScopeId, initialScope);
7998
- renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, initialScope, componentScopeId, /* @__PURE__ */ new Set());
7999
- });
8000
- else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
8001
- seenComponentScopes.add(componentScopeId);
9165
+ if (!componentInstance) componentInstance = createRuntimeComponentInstance(componentScopeId, context, componentEntry, nextProperties, ownerScopeId, reconcilePrivateTemplate, renderPass.propertyUpdate);
9166
+ else {
9167
+ context.componentScopes.set(componentScopeId, createComponentScope(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots));
9168
+ syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys, reconcilePrivateTemplate);
9169
+ }
9170
+ if (isRenderPassStale(renderPass)) return clonedNode;
9171
+ renderPass.seenComponentScopes.add(componentScopeId);
8002
9172
  const componentScope = createComponentScope(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots);
8003
9173
  context.componentScopes.set(componentScopeId, componentScope);
8004
- const renderedComponentRoot = renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes);
9174
+ const renderedComponentRoot = renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, renderPass);
9175
+ mergeComponentEventRoot(renderedComponentRoot, clonedNode);
8005
9176
  if (renderedComponentRoot.attribs) {
8006
- applyNodeBindings(clonedNode, scope);
8007
9177
  renderedComponentRoot.attribs = {
8008
9178
  ...clonedNode.attribs,
8009
9179
  ...renderedComponentRoot.attribs
@@ -8016,66 +9186,99 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
8016
9186
  renderedComponentRoot.attribs["data-sim-node"] = instancePath;
8017
9187
  renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
8018
9188
  }
9189
+ renderPass.componentRoots.set(componentScopeId, renderedComponentRoot);
8019
9190
  return renderedComponentRoot;
8020
9191
  }
8021
9192
  applyNodeBindings(clonedNode, scope);
8022
9193
  clonedNode.attribs["data-sim-node"] = instancePath;
8023
- clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes, templateRenderState);
9194
+ clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, renderPass, templateRenderState, clonedNode);
8024
9195
  return clonedNode;
8025
9196
  }
9197
+ function reconcileRuntimePageTree(context, page, bindingsOnly = false) {
9198
+ for (;;) {
9199
+ bindAttachmentBindingScope(context, page);
9200
+ if (page.__lastChangedKeys__) context.changedPageKeys = page.__lastChangedKeys__;
9201
+ const route = page.route.replace(LEADING_SLASH_RE$2, "");
9202
+ const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
9203
+ const templatePath = path.resolve(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
9204
+ const document = parseTemplateDocument(readTemplateSource(context.artifactSource, templatePath));
9205
+ const pageScopeId = `page:${route}`;
9206
+ const pageScope = {
9207
+ data: page.data,
9208
+ getMethod: (methodName) => {
9209
+ const method = page[methodName];
9210
+ return typeof method === "function" ? method.bind(page) : void 0;
9211
+ },
9212
+ getScopeId: () => pageScopeId,
9213
+ id: "page-root"
9214
+ };
9215
+ for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
9216
+ context.componentScopes.set(pageScopeId, pageScope);
9217
+ const renderPass = createPageRenderPass(page, context.componentCache);
9218
+ const root = (document.children ?? [])[0] ?? document;
9219
+ const templateRenderState = prepareTemplateRenderState(context.artifactSource, root, templatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
9220
+ const renderedRoot = renderNodeTree(root, pageScope, context, path.resolve(context.project.miniprogramRootPath, `${resourcePath}.json`), `${resourcePath}.js`, pageScopeId, renderPass, templateRenderState);
9221
+ const roots = [renderedRoot];
9222
+ if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree({
9223
+ type: "tag",
9224
+ name: "custom-tab-bar",
9225
+ attribs: {},
9226
+ children: []
9227
+ }, customTabBarHostScope(), context, path.resolve(context.project.miniprogramRootPath, "app.json"), "app.js", pageScopeId, renderPass, templateRenderState));
9228
+ reconcileSlotDeclarations(context, renderPass);
9229
+ if (isRenderPassStale(renderPass)) continue;
9230
+ markPageTreeConstructed(page, context.componentCache);
9231
+ const treeRoot = roots.length > 1 ? {
9232
+ type: "root",
9233
+ children: roots
9234
+ } : renderedRoot;
9235
+ linkRenderedParents(treeRoot);
9236
+ registerInspectionTrees(treeRoot, renderPass, context.componentScopes);
9237
+ if (bindingsOnly) return {
9238
+ root: treeRoot,
9239
+ roots
9240
+ };
9241
+ let bindingsRefreshed = false;
9242
+ const updateBindings = () => {
9243
+ bindingsRefreshed = true;
9244
+ if (hasPendingComponentConstruction(context.componentCache)) return;
9245
+ reconcileRuntimePageTree(context, page, true);
9246
+ };
9247
+ const pageAttached = attachComponentPage(page, updateBindings);
9248
+ if (bindingsRefreshed) continue;
9249
+ const pageAttaching = isComponentPageAttaching(page);
9250
+ const scopeIds = orderComponentAttachmentScopes(renderPass.seenComponentScopes, context.componentScopes);
9251
+ const instances = scopeIds.map((scopeId) => context.componentCache.get(scopeId));
9252
+ const attached = !pageAttaching && runWithAttachmentBindingUpdates(page, updateBindings, (scopes) => flushComponentAttachments(context.componentCache, scopes, (instance) => {
9253
+ runComponentLifecycle(instance, "attached");
9254
+ return bindingsRefreshed;
9255
+ }), scopeIds);
9256
+ if (attached === "restart") continue;
9257
+ const canFinalize = !pageAttaching && !hasPendingComponentAttachments(instances);
9258
+ const removed = canFinalize ? [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !renderPass.seenComponentScopes.has(scopeId)) : [];
9259
+ for (const [scopeId, instance] of removed) if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
9260
+ else scheduleDiscardedComponentReady(context.componentCache, scopeId, instance);
9261
+ const relationsChanged = canFinalize && syncComponentRelations(context.componentCache, renderPass.seenComponentScopes, pageScopeId);
9262
+ for (const [scopeId] of removed) {
9263
+ context.componentCache.delete(scopeId);
9264
+ context.componentScopes.delete(scopeId);
9265
+ }
9266
+ if (pageAttached || attached || relationsChanged) continue;
9267
+ if (canFinalize && !isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
9268
+ if (canFinalize && !isPageBeforeReady(page) && flushComponentReady(instances, (instance) => {
9269
+ runComponentLifecycle(instance, "ready");
9270
+ if (instance !== context.componentCache.get(customTabBarScopeId(route))) instance.__definition__?.pageLifetimes?.show?.call(instance);
9271
+ })) continue;
9272
+ return {
9273
+ root: treeRoot,
9274
+ roots
9275
+ };
9276
+ }
9277
+ }
8026
9278
  function renderRuntimePageTree(context, page) {
8027
- const route = page.route.replace(LEADING_SLASH_RE$2, "");
8028
- const resourcePath = context.project.routes.find((item) => item.route === route)?.resourcePath ?? route;
8029
- const templatePath = path.resolve(context.project.miniprogramRootPath, `${resourcePath}.wxml`);
8030
- const document = parseTemplateDocument(readTemplateSource(context.artifactSource, templatePath));
8031
- const pageScopeId = `page:${route}`;
8032
- const pageScope = {
8033
- data: page.data,
8034
- getMethod: (methodName) => {
8035
- const method = page[methodName];
8036
- return typeof method === "function" ? method.bind(page) : void 0;
8037
- },
8038
- getScopeId: () => pageScopeId,
8039
- id: "page-root"
8040
- };
8041
- for (const scopeId of context.componentScopes.keys()) if (scopeId === pageScopeId || scopeId.startsWith(`${pageScopeId}/`)) context.componentScopes.delete(scopeId);
8042
- context.componentScopes.set(pageScopeId, pageScope);
8043
- const seenComponentScopes = /* @__PURE__ */ new Set();
8044
- const root = (document.children ?? [])[0] ?? document;
8045
- const templateRenderState = prepareTemplateRenderState(context.artifactSource, root, templatePath, context.project.miniprogramRootPath, getRuntimeWxsLoader(context.moduleLoader, context.artifactSource));
8046
- const renderedRoot = renderNodeTree(root, pageScope, context, path.resolve(context.project.miniprogramRootPath, `${resourcePath}.json`), `${resourcePath}.js`, pageScopeId, seenComponentScopes, templateRenderState);
8047
- const roots = [renderedRoot];
8048
- if (hasCustomTabBar(context.project.appConfig, route)) roots.push(renderNodeTree({
8049
- type: "tag",
8050
- name: "custom-tab-bar",
8051
- attribs: {},
8052
- children: []
8053
- }, customTabBarHostScope(), context, path.resolve(context.project.miniprogramRootPath, "app.json"), "app.js", pageScopeId, seenComponentScopes, templateRenderState));
8054
- const pageAttached = attachComponentPage(page);
8055
- const pageAttaching = isComponentPageAttaching(page);
8056
- const attached = !pageAttaching && flushComponentAttachments([...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId)), (instance) => runComponentLifecycle(instance, "attached"));
8057
- const removed = [...context.componentCache].filter(([scopeId]) => scopeId.startsWith(`${pageScopeId}/`) && !seenComponentScopes.has(scopeId));
8058
- for (const [scopeId, instance] of removed) if (isComponentAttached(instance)) runComponentLifecycle(instance, "detached");
8059
- else scheduleDiscardedComponentReady(context.componentCache, scopeId, instance);
8060
- const instances = [...seenComponentScopes].map((scopeId) => context.componentCache.get(scopeId));
8061
- const relationsChanged = !pageAttaching && !hasPendingComponentAttachments(instances) && syncComponentRelations(context.componentCache, seenComponentScopes, pageScopeId);
8062
- for (const [scopeId] of removed) {
8063
- context.componentCache.delete(scopeId);
8064
- context.componentScopes.delete(scopeId);
8065
- }
8066
- if (pageAttached || attached || relationsChanged) return renderRuntimePageTree(context, page);
8067
- if (!isPageBeforeReady(page)) flushDiscardedComponentReady(context.componentCache, pageScopeId, (instance) => runComponentLifecycle(instance, "ready"));
8068
- if (!isPageBeforeReady(page) && flushComponentReady(instances, (instance) => {
8069
- runComponentLifecycle(instance, "ready");
8070
- if (instance !== context.componentCache.get(customTabBarScopeId(route))) instance.__definition__?.pageLifetimes?.show?.call(instance);
8071
- })) return renderRuntimePageTree(context, page);
8072
- const treeRoot = roots.length > 1 ? {
8073
- type: "root",
8074
- children: roots
8075
- } : renderedRoot;
8076
- linkRenderedParents(treeRoot);
9279
+ const { root, roots } = reconcileRuntimePageTree(context, page);
8077
9280
  return {
8078
- root: treeRoot,
9281
+ root,
8079
9282
  wxml: roots.map(serializeDomNode).join("")
8080
9283
  };
8081
9284
  }
@@ -8180,9 +9383,9 @@ function transformEsmToCommonJs(source) {
8180
9383
  function createRequireNotFoundError(request, importer) {
8181
9384
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in headless runtime.`);
8182
9385
  }
8183
- function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, kernel, globals, onConsole) {
9386
+ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, kernel, globals, onConsole, workers) {
8184
9387
  const runtimeConsole = kernel.diagnostics.createConsole(console, onConsole);
8185
- const wx = createHeadlessWx(wxDriver, runtimeConsole);
9388
+ const wx = createHeadlessWx(wxDriver, runtimeConsole, workers);
8186
9389
  return createMiniProgramRuntimeGlobals({
8187
9390
  App(definition) {
8188
9391
  return registerAppDefinition(registries, definition);
@@ -8215,8 +9418,19 @@ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, k
8215
9418
  }, globals);
8216
9419
  }
8217
9420
  function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, options) {
9421
+ const workers = createWorkerHost({
9422
+ root: options.miniprogramRootPath,
9423
+ read: (file) => options.artifactSource.readText(file),
9424
+ console: options.kernel.diagnostics.createConsole(console, options.onConsole),
9425
+ createExecutor(globals) {
9426
+ const realm = vm.createContext(globals);
9427
+ return (source, file, module, require) => {
9428
+ new vm.Script(`(function(module, exports, require) {${source}\n})`, { filename: file }).runInContext(realm)(module, module.exports, require);
9429
+ };
9430
+ }
9431
+ });
8218
9432
  const moduleCache = /* @__PURE__ */ new Map();
8219
- const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {}, options.onConsole);
9433
+ const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {}, options.onConsole, workers.apis);
8220
9434
  executionContext.globalThis = executionContext;
8221
9435
  function executeModule(filePath, loadContext) {
8222
9436
  const resolvedPath = path.resolve(filePath);
@@ -8275,6 +9489,7 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, optio
8275
9489
  return callback(...args);
8276
9490
  },
8277
9491
  close() {
9492
+ workers.close();
8278
9493
  moduleCache.clear();
8279
9494
  closeRuntimeWxsLoader(loader);
8280
9495
  },
@@ -8378,6 +9593,7 @@ var HeadlessSession = class {
8378
9593
  appInstance = null;
8379
9594
  appLifecycle = new HeadlessAppLifecycle();
8380
9595
  moduleLoader;
9596
+ routeEvents = new HeadlessRouteEvents((callback) => this.requestRender(callback), (page) => this.currentPageInstance === page && !this.kernel.isClosed);
8381
9597
  eventListeners = /* @__PURE__ */ new Map();
8382
9598
  registries;
8383
9599
  currentPageInstance = null;
@@ -8405,7 +9621,10 @@ var HeadlessSession = class {
8405
9621
  constructor(options) {
8406
9622
  if (!options.project && !options.projectPath) throw new Error("Headless runtime requires projectPath or project.");
8407
9623
  this.project = options.project ?? loadProject(options.projectPath);
8408
- this.wxState = createHeadlessWxState(this.kernel.scheduler, { strictMocks: options.strictHostMocks });
9624
+ this.wxState = createHeadlessWxState(this.kernel.scheduler, {
9625
+ strictMocks: options.strictHostMocks,
9626
+ readPackageFile: createPackageAssetReader((relative) => this.project.artifactSource.readText(path.join(this.project.miniprogramRootPath, relative)))
9627
+ });
8409
9628
  this.registries = createHostRegistries();
8410
9629
  const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
8411
9630
  this.tabBarRoutes = /* @__PURE__ */ new Set();
@@ -8455,7 +9674,7 @@ var HeadlessSession = class {
8455
9674
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
8456
9675
  getNetworkType: () => this.wxState.getNetworkType(),
8457
9676
  navigateBack: (option) => this.navigateBack(option?.delta),
8458
- navigateTo: (option) => this.navigateTo(option.url),
9677
+ navigateTo: (option) => this.routeEvents.navigateTo(() => this.navigateTo(option.url), option),
8459
9678
  pageScrollTo: (option) => this.pageScrollTo(option),
8460
9679
  openDocument: (option) => this.wxState.openDocument(option),
8461
9680
  clearStorageSync: () => this.wxState.clearStorageSync(),
@@ -8472,6 +9691,14 @@ var HeadlessSession = class {
8472
9691
  saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
8473
9692
  saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
8474
9693
  nextTick: (callback) => this.kernel.scheduler.queueMicrotask(() => callback?.()),
9694
+ offBeforeAppRoute: (listener) => this.routeEvents.off("beforeAppRoute", listener),
9695
+ offBeforePageUnload: (listener) => this.routeEvents.off("beforePageUnload", listener),
9696
+ offAppRoute: (listener) => this.routeEvents.off("appRoute", listener),
9697
+ offAppRouteDone: (listener) => this.routeEvents.off("appRouteDone", listener),
9698
+ onBeforeAppRoute: (listener) => this.routeEvents.on("beforeAppRoute", listener),
9699
+ onBeforePageUnload: (listener) => this.routeEvents.on("beforePageUnload", listener),
9700
+ onAppRoute: (listener) => this.routeEvents.on("appRoute", listener),
9701
+ onAppRouteDone: (listener) => this.routeEvents.on("appRouteDone", listener),
8475
9702
  offAppHide: (callback) => this.appLifecycle.offAppHide(callback),
8476
9703
  offAppShow: (callback) => this.appLifecycle.offAppShow(callback),
8477
9704
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
@@ -8524,15 +9751,28 @@ var HeadlessSession = class {
8524
9751
  }
8525
9752
  close() {
8526
9753
  if (this.kernel.isClosed) return;
8527
- this.unloadAllPages();
9754
+ let failure;
9755
+ try {
9756
+ this.unloadAllPages(void 0, true);
9757
+ } catch (error) {
9758
+ failure = { error };
9759
+ }
8528
9760
  this.canvasContexts.clear();
8529
9761
  this.renderRequestCallbacks.length = 0;
8530
9762
  this.renderRequestPending = false;
8531
9763
  this.appLifecycle.close();
9764
+ this.routeEvents.close();
8532
9765
  this.wxState.close();
8533
9766
  this.moduleLoader.close();
8534
- this.eventListeners.clear();
8535
9767
  this.kernel.close();
9768
+ try {
9769
+ this.emit("close");
9770
+ } catch (error) {
9771
+ failure ??= { error };
9772
+ } finally {
9773
+ this.eventListeners.clear();
9774
+ }
9775
+ if (failure) throw failure.error;
8536
9776
  }
8537
9777
  getDiagnostics() {
8538
9778
  return this.kernel.diagnostics.getEntries();
@@ -8549,7 +9789,14 @@ var HeadlessSession = class {
8549
9789
  if (listeners?.size === 0) this.eventListeners.delete(eventName);
8550
9790
  }
8551
9791
  emit(eventName, ...args) {
8552
- for (const handler of [...this.eventListeners.get(eventName) ?? []]) handler(...args);
9792
+ let failure;
9793
+ for (const handler of [...this.eventListeners.get(eventName) ?? []]) try {
9794
+ handler(...args);
9795
+ } catch (error) {
9796
+ if (eventName !== "close") throw error;
9797
+ failure ??= { error };
9798
+ }
9799
+ if (failure) throw failure.error;
8553
9800
  }
8554
9801
  get isClosed() {
8555
9802
  return this.kernel.isClosed;
@@ -8631,6 +9878,11 @@ var HeadlessSession = class {
8631
9878
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
8632
9879
  }
8633
9880
  }, current);
9881
+ syncNativeScrollViews(current, rendered.root, (scopeId, method, event) => {
9882
+ this.kernel.scheduler.queueMicrotask(() => {
9883
+ if (this.currentPageInstance === current) this.callScopeMethod(scopeId, method, event);
9884
+ });
9885
+ });
8634
9886
  const componentScopePrefix = `page:${stripLeadingSlash(current.route)}`;
8635
9887
  for (const [scopeId, instance] of this.componentCache.entries()) if (scopeId.startsWith(componentScopePrefix)) this.selectorQueryScopeSnapshots.set(instance, {
8636
9888
  page: current,
@@ -8639,6 +9891,11 @@ var HeadlessSession = class {
8639
9891
  });
8640
9892
  return rendered;
8641
9893
  }
9894
+ dispatchNativeNodeEvent(node, eventName, event, onHandlerResult) {
9895
+ const current = this.requireCurrentPage("dispatchNativeNodeEvent()");
9896
+ if (eventName === "tap") this.renderCurrentPage();
9897
+ return dispatchNativeNodeEvent(current, node, eventName, event, this.moduleLoader.wx, (scopeId, method) => this.resolveScopeMethod(current, scopeId, method), onHandlerResult);
9898
+ }
8642
9899
  requestRender(callback) {
8643
9900
  this.assertActive();
8644
9901
  if (callback) this.renderRequestCallbacks.push(callback);
@@ -8686,21 +9943,27 @@ var HeadlessSession = class {
8686
9943
  callScopeMethod(scopeId, methodName, event) {
8687
9944
  const current = this.requireCurrentPage(`scope method "${methodName}"`);
8688
9945
  this.renderCurrentPage();
8689
- if (!scopeId || scopeId === `page:${stripLeadingSlash(current.route)}`) {
9946
+ return this.resolveScopeMethod(current, scopeId, methodName)(event);
9947
+ }
9948
+ /** 解析本次交互的实例,后续回调不随重渲染或导航切换所有者。 */
9949
+ resolveScopeMethod(current, scopeId, methodName) {
9950
+ if (!scopeId || scopeId === `page:${stripLeadingSlash(current.route)}`) return (event) => {
8690
9951
  const method = current[methodName];
8691
9952
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${current.route}.`);
8692
9953
  return method.call(current, event);
8693
- }
9954
+ };
8694
9955
  const instance = this.componentCache.get(scopeId);
8695
9956
  if (!instance) throw new Error(`Unknown scope "${scopeId}" in headless runtime.`);
8696
- instance.__lastInteractionEvent__ = {
8697
- currentTarget: event.currentTarget,
8698
- mark: event.mark,
8699
- target: event.target
9957
+ return (event) => {
9958
+ instance.__lastInteractionEvent__ = {
9959
+ currentTarget: event.currentTarget,
9960
+ mark: event.mark,
9961
+ target: event.target
9962
+ };
9963
+ const method = instance[methodName];
9964
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless component scope "${scopeId}".`);
9965
+ return method.call(instance, event);
8700
9966
  };
8701
- const method = instance[methodName];
8702
- if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless component scope "${scopeId}".`);
8703
- return method.call(instance, event);
8704
9967
  }
8705
9968
  callScopeMethodDirect(scopeId, methodName, ...args) {
8706
9969
  const normalizedScopeId = scopeId.trim();
@@ -8726,19 +9989,19 @@ var HeadlessSession = class {
8726
9989
  return this.wxState.getShareMenu();
8727
9990
  }
8728
9991
  selectComponent(selector) {
8729
- this.renderCurrentPage();
9992
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
8730
9993
  return this.selectComponentsWithin(null, selector)[0] ?? null;
8731
9994
  }
8732
9995
  selectAllComponents(selector) {
8733
- this.renderCurrentPage();
9996
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
8734
9997
  return this.selectComponentsWithin(null, selector);
8735
9998
  }
8736
9999
  selectComponentWithin(scopeId, selector) {
8737
- this.renderCurrentPage();
10000
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
8738
10001
  return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
8739
10002
  }
8740
10003
  selectAllComponentsWithin(scopeId, selector) {
8741
- this.renderCurrentPage();
10004
+ if (!hasPendingComponentConstruction(this.componentCache)) this.renderCurrentPage();
8742
10005
  return this.selectComponentsWithin(scopeId, selector);
8743
10006
  }
8744
10007
  selectOwnerComponent(scopeId) {
@@ -8981,11 +10244,13 @@ var HeadlessSession = class {
8981
10244
  const target = this.resolveNavigationTarget(url);
8982
10245
  const launchedPage = this.bootstrapNavigation(createAppLaunchOptions(target.normalizedRoute, target.query));
8983
10246
  if (launchedPage) return launchedPage;
8984
- this.unloadAllPages();
8985
- const pageInstance = this.createFreshPage(target);
10247
+ const event = this.beginRoute(target, "reLaunch");
10248
+ this.unloadAllPages(event);
10249
+ const pageInstance = this.createFreshPage(target, event);
8986
10250
  this.pages.push(pageInstance);
8987
10251
  this.currentPageInstance = pageInstance;
8988
10252
  this.runInitialPageLifecycles(pageInstance, target.query);
10253
+ this.routeEvents.commit(pageInstance, event);
8989
10254
  return pageInstance;
8990
10255
  }
8991
10256
  navigateTo(url) {
@@ -8994,12 +10259,14 @@ var HeadlessSession = class {
8994
10259
  if (launchedPage) return launchedPage;
8995
10260
  if (this.pages.length >= PAGE_STACK_LIMIT) throw new Error(`Cannot navigateTo() beyond a ${PAGE_STACK_LIMIT}-page stack in headless runtime.`);
8996
10261
  if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in headless runtime: ${url}`);
10262
+ const event = this.beginRoute(target, "navigateTo");
8997
10263
  this.currentPageInstance?.onHide?.();
8998
10264
  if (this.currentPageInstance) this.runPageComponentLifetime(this.currentPageInstance.route, "hide");
8999
- const pageInstance = this.createFreshPage(target);
10265
+ const pageInstance = this.createFreshPage(target, event);
9000
10266
  this.pages.push(pageInstance);
9001
10267
  this.currentPageInstance = pageInstance;
9002
10268
  this.runInitialPageLifecycles(pageInstance, target.query);
10269
+ this.routeEvents.commit(pageInstance, event);
9003
10270
  return pageInstance;
9004
10271
  }
9005
10272
  redirectTo(url) {
@@ -9007,15 +10274,17 @@ var HeadlessSession = class {
9007
10274
  const launchedPage = this.bootstrapNavigation(createAppLaunchOptions(target.normalizedRoute, target.query));
9008
10275
  if (launchedPage) return launchedPage;
9009
10276
  if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.redirectTo() cannot open a tabBar page in headless runtime: ${url}`);
10277
+ const event = this.beginRoute(target, "redirectTo");
9010
10278
  const current = this.currentPageInstance;
9011
10279
  if (current) {
10280
+ this.unloadPage(current, event);
9012
10281
  this.pages.pop();
9013
- this.unloadPage(current);
9014
10282
  }
9015
- const pageInstance = this.createFreshPage(target);
10283
+ const pageInstance = this.createFreshPage(target, event);
9016
10284
  this.pages.push(pageInstance);
9017
10285
  this.currentPageInstance = pageInstance;
9018
10286
  this.runInitialPageLifecycles(pageInstance, target.query);
10287
+ this.routeEvents.commit(pageInstance, event);
9019
10288
  return pageInstance;
9020
10289
  }
9021
10290
  navigateBack(delta = 1) {
@@ -9023,12 +10292,17 @@ var HeadlessSession = class {
9023
10292
  if (launchedPage) return launchedPage;
9024
10293
  if (this.pages.length <= 1) return this.currentPageInstance;
9025
10294
  const removableCount = Math.min(Number.isFinite(delta) ? Math.max(1, Math.trunc(delta)) : 1, this.pages.length - 1);
9026
- const removedPages = this.pages.splice(this.pages.length - removableCount, removableCount);
9027
- for (const page of removedPages.reverse()) this.unloadPage(page);
9028
- const nextPage = this.pages.at(-1) ?? null;
10295
+ const nextPage = this.pages[this.pages.length - removableCount - 1];
10296
+ const event = this.routeEvents.begin(nextPage.route, nextPage.options, "navigateBack", void 0, nextPage);
10297
+ this.routeEvents.attach(nextPage, event);
10298
+ for (let index = 0; index < removableCount; index++) {
10299
+ this.unloadPage(this.pages.at(-1), event);
10300
+ this.pages.pop();
10301
+ }
9029
10302
  this.currentPageInstance = nextPage;
9030
10303
  nextPage?.onShow?.();
9031
10304
  if (nextPage) this.runPageComponentLifetime(nextPage.route, "show");
10305
+ this.routeEvents.commit(nextPage, event);
9032
10306
  return nextPage;
9033
10307
  }
9034
10308
  switchTab(url) {
@@ -9046,6 +10320,8 @@ var HeadlessSession = class {
9046
10320
  const current = this.currentPageInstance;
9047
10321
  const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
9048
10322
  if (current === cachedTarget && current) return () => {};
10323
+ const event = this.beginRoute(target, "switchTab", cachedTarget ?? void 0);
10324
+ if (cachedTarget) this.routeEvents.attach(cachedTarget, event);
9049
10325
  if (current && current !== cachedTarget) {
9050
10326
  current.onHide?.();
9051
10327
  this.runPageComponentLifetime(current.route, "hide");
@@ -9055,7 +10331,7 @@ var HeadlessSession = class {
9055
10331
  let nextPage = cachedTarget;
9056
10332
  let shouldRunInitialLifecycles = false;
9057
10333
  if (!nextPage) {
9058
- nextPage = this.createFreshPage(target);
10334
+ nextPage = this.createFreshPage(target, event);
9059
10335
  this.tabPages.set(target.routeRecord.route, nextPage);
9060
10336
  shouldRunInitialLifecycles = true;
9061
10337
  }
@@ -9068,7 +10344,8 @@ var HeadlessSession = class {
9068
10344
  this.runPageComponentLifetime(nextPage.route, "show");
9069
10345
  }
9070
10346
  return () => {
9071
- for (const page of pagesToUnload) this.unloadPage(page);
10347
+ for (const page of pagesToUnload) this.unloadPage(page, event);
10348
+ this.routeEvents.commit(nextPage, event);
9072
10349
  };
9073
10350
  }
9074
10351
  pageScrollTo(option) {
@@ -9163,17 +10440,20 @@ var HeadlessSession = class {
9163
10440
  windowInfo: this.getWindowInfo()
9164
10441
  });
9165
10442
  }
9166
- createFreshPage(target) {
10443
+ beginRoute(target, openType, page) {
10444
+ return this.routeEvents.begin(target.normalizedRoute, target.query, openType, target.pageConfig?.renderer ?? this.project.appConfig.renderer, page);
10445
+ }
10446
+ createFreshPage(target, event) {
9167
10447
  const resourcePath = target.routeRecord.resourcePath ?? target.routeRecord.route;
9168
10448
  const pageModulePath = path.resolve(this.project.miniprogramRootPath, `${resourcePath}.js`);
9169
- const pageConfigPath = path.resolve(this.project.miniprogramRootPath, `${resourcePath}.json`);
9170
10449
  const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
9171
- const pageConfig = readJsonObject(this.project, pageConfigPath);
10450
+ const pageConfig = target.pageConfig;
9172
10451
  const pageInstance = createPageInstance(`/${target.routeRecord.route}`, pageDefinition, target.query, {
9173
10452
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
9174
10453
  navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig),
9175
10454
  requestRender: (callback) => this.requestRender(callback)
9176
10455
  });
10456
+ this.routeEvents.attach(pageInstance, event);
9177
10457
  pageInstance.createIntersectionObserver = (options) => this.createIntersectionObserver(pageInstance, options);
9178
10458
  pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
9179
10459
  pageInstance.selectComponent = (selector) => resolveNativeComponentSelection(this.selectComponent(selector));
@@ -9186,7 +10466,7 @@ var HeadlessSession = class {
9186
10466
  return pageInstance;
9187
10467
  }
9188
10468
  runInitialPageLifecycles(pageInstance, query) {
9189
- runInitialPageLifecycles(pageInstance, query, this.kernel.scheduler, () => this.pages.includes(pageInstance) || this.tabPages.get(pageInstance.route) === pageInstance, () => this.renderCurrentPage());
10469
+ runInitialPageLifecycles(pageInstance, query, this.kernel.scheduler, () => this.pages.includes(pageInstance) || this.tabPages.get(pageInstance.route) === pageInstance, () => this.renderCurrentPage(), () => this.routeEvents.ready(pageInstance));
9190
10470
  }
9191
10471
  isTabBarRoute(route) {
9192
10472
  return this.tabBarRoutes.has(stripLeadingSlash(route));
@@ -9215,24 +10495,45 @@ var HeadlessSession = class {
9215
10495
  return {
9216
10496
  normalizedRoute,
9217
10497
  query,
9218
- routeRecord
10498
+ routeRecord,
10499
+ pageConfig: readJsonObject(this.project, path.resolve(this.project.miniprogramRootPath, `${routeRecord.resourcePath ?? routeRecord.route}.json`))
9219
10500
  };
9220
10501
  }
9221
- unloadAllPages() {
10502
+ unloadAllPages(event, closing = false) {
9222
10503
  const pagesToUnload = /* @__PURE__ */ new Set([...this.pages, ...this.tabPages.values()]);
9223
- for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
10504
+ let failure;
10505
+ for (const page of [...pagesToUnload].reverse()) try {
10506
+ this.unloadPage(page, event, closing);
10507
+ } catch (error) {
10508
+ if (!closing) throw error;
10509
+ failure ??= { error };
10510
+ }
9224
10511
  this.pages.length = 0;
9225
10512
  this.tabPages.clear();
9226
10513
  this.componentCache.clear();
9227
10514
  this.componentScopes.clear();
9228
10515
  this.clearMediaQueryObservers();
9229
10516
  this.currentPageInstance = null;
10517
+ if (failure) throw failure.error;
9230
10518
  }
9231
- unloadPage(page) {
9232
- page.onUnload?.();
10519
+ unloadPage(page, event, closing = false) {
10520
+ let failure;
10521
+ try {
10522
+ this.routeEvents.beforeUnload(page, event);
10523
+ page.onUnload?.();
10524
+ } catch (error) {
10525
+ if (!closing) throw error;
10526
+ failure = { error };
10527
+ }
9233
10528
  this.clearMediaQueryObservers(page);
9234
- this.detachPageComponents(page.route);
10529
+ try {
10530
+ this.detachPageComponents(page.route, closing);
10531
+ } catch (error) {
10532
+ if (!closing) throw error;
10533
+ failure ??= { error };
10534
+ }
9235
10535
  this.tabPages.delete(stripLeadingSlash(page.route));
10536
+ if (failure) throw failure.error;
9236
10537
  }
9237
10538
  requireCurrentPage(action) {
9238
10539
  this.bootstrap();
@@ -9260,15 +10561,27 @@ var HeadlessSession = class {
9260
10561
  const directlyOwned = rootScopeId ? matches.filter(([, scope]) => scope.ownerScopeId === rootScopeId) : [];
9261
10562
  return (directlyOwned.length > 0 ? directlyOwned : matches).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
9262
10563
  }
9263
- detachPageComponents(route) {
10564
+ detachPageComponents(route, closing = false) {
9264
10565
  const prefix = `page:${stripLeadingSlash(route)}`;
9265
10566
  const removed = [...this.componentCache].filter(([scopeId]) => scopeId.startsWith(prefix));
9266
- for (const [, instance] of removed) runComponentLifecycle(instance, "detached");
9267
- detachComponentRelations(removed.map(([, instance]) => instance));
10567
+ let failure;
10568
+ for (const [, instance] of removed) try {
10569
+ runComponentLifecycle(instance, "detached");
10570
+ } catch (error) {
10571
+ if (!closing) throw error;
10572
+ failure ??= { error };
10573
+ }
10574
+ try {
10575
+ detachComponentRelations(removed.map(([, instance]) => instance));
10576
+ } catch (error) {
10577
+ if (!closing) throw error;
10578
+ failure ??= { error };
10579
+ }
9268
10580
  for (const [scopeId] of removed) {
9269
10581
  this.componentCache.delete(scopeId);
9270
10582
  this.componentScopes.delete(scopeId);
9271
10583
  }
10584
+ if (failure) throw failure.error;
9272
10585
  }
9273
10586
  notifyMediaQueryObservers() {
9274
10587
  for (const entry of [...this.mediaQueryObservers]) {
@@ -9428,6 +10741,8 @@ function createPageRootNodeHandle(options) {
9428
10741
  const tree = session?.getCurrentPages().includes(page) ? session.renderCurrentPage() : renderPageTree(project, page);
9429
10742
  return new HeadlessTestingNodeHandle(tree.root.type === "root" && !options.includeHostRoots ? tree.root.children?.[0] ?? tree.root : tree.root, {
9430
10743
  assertActive: options.assertActive,
10744
+ projectionOnly: options.projectionOnly,
10745
+ dispatchNativeEvent: (node, eventName, event, onHandlerResult) => session?.getCurrentPages().at(-1) === page ? session.dispatchNativeNodeEvent(node, eventName, event, onHandlerResult) : false,
9431
10746
  callMethod: (scopeId, methodName, event) => {
9432
10747
  if (session?.getCurrentPages().includes(page)) return session.callScopeMethod(scopeId, methodName, event);
9433
10748
  const method = page[methodName];
@@ -9789,7 +11104,18 @@ var HeadlessTestingPageHandle = class {
9789
11104
  renderedAccess() {
9790
11105
  return {
9791
11106
  assertActive: () => this.assertActive(),
9792
- findAll: async (selector) => await this.$$(selector),
11107
+ findAll: async (selector) => {
11108
+ this.assertActive();
11109
+ const root = createPageRootNodeHandle({
11110
+ assertActive: () => this.assertActive(),
11111
+ createPageHandle: () => this,
11112
+ page: this.page,
11113
+ project: this.project,
11114
+ projectionOnly: true,
11115
+ session: this.session
11116
+ });
11117
+ return selector === "page" ? [root] : await root.$$(selector);
11118
+ },
9793
11119
  waitFor: async (ms) => await this.waitFor(ms),
9794
11120
  wxml: async () => await this.wxml()
9795
11121
  };
@@ -9867,11 +11193,19 @@ var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
9867
11193
  var HeadlessTestingSessionHandle = class {
9868
11194
  project;
9869
11195
  session;
11196
+ pendingNavigations = /* @__PURE__ */ new Set();
9870
11197
  constructor(project, session) {
9871
11198
  this.project = project;
9872
11199
  this.session = session;
11200
+ this.session.on("close", () => {
11201
+ for (const reject of this.pendingNavigations) reject(/* @__PURE__ */ new Error("The headless testing session closed before navigation completed."));
11202
+ });
9873
11203
  }
9874
11204
  async close() {
11205
+ this.disconnect();
11206
+ }
11207
+ /** 无头会话独占本地 runtime;同步释放与 automator 的连接清理契约一致。 */
11208
+ disconnect() {
9875
11209
  this.session.close();
9876
11210
  }
9877
11211
  async toolInfo() {
@@ -9911,6 +11245,10 @@ var HeadlessTestingSessionHandle = class {
9911
11245
  const normalizedMethodName = normalizeNonEmptyInput(methodName, "wx method name");
9912
11246
  return await runWithTimeout(() => this.session.callWxMethod(normalizedMethodName, ...args), options.timeout, `Timed out calling wx.${normalizedMethodName} in headless testing runtime.`);
9913
11247
  }
11248
+ /** 返回与 DevTools automator 兼容的运行时系统信息。 */
11249
+ async systemInfo() {
11250
+ return await this.callWxMethod("getSystemInfoSync");
11251
+ }
9914
11252
  async scopeSnapshot(scopeId) {
9915
11253
  const normalizedScopeId = normalizeNonEmptyInput(scopeId, "Scope id");
9916
11254
  return this.session.getScopeSnapshot(normalizedScopeId);
@@ -9938,23 +11276,23 @@ var HeadlessTestingSessionHandle = class {
9938
11276
  }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
9939
11277
  }
9940
11278
  async reLaunch(route) {
9941
- this.invokeNavigation("reLaunch", { url: route });
11279
+ await this.invokeNavigation("reLaunch", { url: route });
9942
11280
  return await this.requireCurrentPage("reLaunch", route);
9943
11281
  }
9944
11282
  async navigateTo(route) {
9945
- this.invokeNavigation("navigateTo", { url: route });
11283
+ await this.invokeNavigation("navigateTo", { url: route });
9946
11284
  return await this.requireCurrentPage("navigateTo", route);
9947
11285
  }
9948
11286
  async redirectTo(route) {
9949
- this.invokeNavigation("redirectTo", { url: route });
11287
+ await this.invokeNavigation("redirectTo", { url: route });
9950
11288
  return await this.requireCurrentPage("redirectTo", route);
9951
11289
  }
9952
11290
  async navigateBack(delta = 1) {
9953
- this.invokeNavigation("navigateBack", { delta });
11291
+ await this.invokeNavigation("navigateBack", { delta });
9954
11292
  return await this.currentPage();
9955
11293
  }
9956
11294
  async switchTab(route) {
9957
- this.invokeNavigation("switchTab", { url: route });
11295
+ await this.invokeNavigation("switchTab", { url: route });
9958
11296
  return await this.requireCurrentPage("switchTab", route);
9959
11297
  }
9960
11298
  async waitForCurrentPage(route, options = {}) {
@@ -9991,21 +11329,30 @@ var HeadlessTestingSessionHandle = class {
9991
11329
  this.session.triggerRouteDone(options);
9992
11330
  }
9993
11331
  invokeNavigation(methodName, options) {
9994
- const failure = { received: false };
9995
- this.session.callWxMethod(methodName, {
9996
- ...options,
9997
- fail(error) {
9998
- failure.received = true;
9999
- failure.error = error;
11332
+ return new Promise((resolve, reject) => {
11333
+ const rejectNavigation = (error) => {
11334
+ this.pendingNavigations.delete(rejectNavigation);
11335
+ reject(error);
11336
+ };
11337
+ this.pendingNavigations.add(rejectNavigation);
11338
+ try {
11339
+ this.session.callWxMethod(methodName, {
11340
+ ...options,
11341
+ success: () => {
11342
+ this.pendingNavigations.delete(rejectNavigation);
11343
+ resolve();
11344
+ },
11345
+ fail: (error) => {
11346
+ const details = error && typeof error === "object" ? error : void 0;
11347
+ const reason = typeof details?.errMsg === "string" ? details.errMsg : typeof details?.message === "string" ? details.message : String(error);
11348
+ const target = options.url ? ` route "${options.url}"` : "";
11349
+ rejectNavigation(new Error(`Failed to ${methodName}${target} through the headless wx runtime: ${reason}`, { cause: error }));
11350
+ }
11351
+ });
11352
+ } catch (error) {
11353
+ rejectNavigation(error);
10000
11354
  }
10001
11355
  });
10002
- if (failure.received) {
10003
- const error = failure.error;
10004
- const details = error && typeof error === "object" ? error : void 0;
10005
- const reason = typeof details?.errMsg === "string" ? details.errMsg : typeof details?.message === "string" ? details.message : String(error);
10006
- const target = options.url ? ` route "${options.url}"` : "";
10007
- throw new Error(`Failed to ${methodName}${target} through the headless wx runtime: ${reason}`, { cause: error });
10008
- }
10009
11356
  }
10010
11357
  async requireCurrentPage(methodName, route) {
10011
11358
  const page = await this.currentPage();
@@ -10040,4 +11387,4 @@ async function launch(options) {
10040
11387
  }
10041
11388
  }
10042
11389
  //#endregion
10043
- 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, 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 };
11390
+ export { BrowserHeadlessSession, HEADLESS_PLUGIN_VIRTUAL_ROOT, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingScopeHandle, HeadlessTestingSessionHandle, RuntimeDiagnostics, RuntimeKernel, RuntimeScheduler, cloneValue, coerceComponentPropertyValue, collectMiniProgramEventBindings, createAppInstance, createArtifactProject, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createFileSystemArtifactSource, createHeadlessSession, createHeadlessUniEventBus, createHeadlessWx, createHeadlessWxState, createHostRegistries, createLogicalNode, createMemoryArtifactSource, createMiniProgramEventPayload, createMiniProgramHostConfig, createOverlayArtifactSource, createPageInstance, createPluginArtifactSource, createPluginVirtualRoot, createProjectDescriptor, executeSelectorQueryRequests, getPageInstanceId, hasBrowserVirtualFile, hasComponentPropertyValueChanged, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPageDefinition, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, readRenderedNodes, readRenderedSelectorNodes, registerAppDefinition, registerComponentDefinition, registerExportedComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, renderRuntimePageTree, resolveBrowserPageStyles, resolveMiniProgramEventBinding, resolvePluginRequest, resolveRoutesFromAppConfig, resolveSelectorQueryScopeRoot, resolveSelectorScrollTop, runComponentLifecycle, runComponentObservers, runComponentPageLifetime, waitForPageComponent, waitForPageComponents, waitForPageData, waitForPageSelector, waitForPageText, waitForPageTextGone, waitForRenderedPage, wechat };