@mpcore/simulator 0.1.3 → 0.2.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.
Files changed (3) hide show
  1. package/dist/index.d.mts +208 -167
  2. package/dist/index.mjs +488 -358
  3. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -8,6 +8,48 @@ import vm from "node:vm";
8
8
  function createDuplicateRegistrationError(kind, id) {
9
9
  return /* @__PURE__ */ new Error(`Duplicate ${kind} registration in headless runtime: ${id}`);
10
10
  }
11
+ function callDefinitionMethod(instance, method, args) {
12
+ if (typeof method === "function") return method.apply(instance, args);
13
+ }
14
+ function normalizeComponentPageDefinition(definition) {
15
+ const { lifetimes = {}, methods = {}, pageLifetimes = {}, ...rest } = definition;
16
+ const created = lifetimes.created ?? rest.created;
17
+ const attached = lifetimes.attached ?? rest.attached;
18
+ const ready = lifetimes.ready ?? rest.ready ?? methods.onReady ?? rest.onReady;
19
+ const detached = lifetimes.detached ?? rest.detached ?? methods.onUnload ?? rest.onUnload;
20
+ const load = methods.onLoad ?? rest.onLoad;
21
+ const show = pageLifetimes.show ?? methods.onShow ?? rest.onShow;
22
+ const hide = pageLifetimes.hide ?? methods.onHide ?? rest.onHide;
23
+ const resize = pageLifetimes.resize ?? methods.onResize ?? rest.onResize;
24
+ const routeDone = pageLifetimes.routeDone ?? methods.onRouteDone ?? rest.onRouteDone;
25
+ return {
26
+ ...rest,
27
+ ...methods,
28
+ onLoad(...args) {
29
+ callDefinitionMethod(this, created, []);
30
+ callDefinitionMethod(this, attached, []);
31
+ return callDefinitionMethod(this, load, args);
32
+ },
33
+ onShow(...args) {
34
+ return callDefinitionMethod(this, show, args);
35
+ },
36
+ onHide(...args) {
37
+ return callDefinitionMethod(this, hide, args);
38
+ },
39
+ onReady(...args) {
40
+ return callDefinitionMethod(this, ready, args);
41
+ },
42
+ onUnload(...args) {
43
+ return callDefinitionMethod(this, detached, args);
44
+ },
45
+ onResize(...args) {
46
+ return callDefinitionMethod(this, resize, args);
47
+ },
48
+ onRouteDone(...args) {
49
+ return callDefinitionMethod(this, routeDone, args);
50
+ }
51
+ };
52
+ }
11
53
  function createHostRegistries() {
12
54
  return {
13
55
  appDefinition: null,
@@ -29,13 +71,14 @@ function registerPageDefinition(registries, definition) {
29
71
  return definition;
30
72
  }
31
73
  function registerComponentDefinition(registries, definition) {
74
+ if (registries.currentLoadContext?.kind === "page") return registerPageDefinition(registries, normalizeComponentPageDefinition(definition));
32
75
  const id = registries.currentLoadContext?.route ?? `anonymous:${registries.components.size}`;
33
76
  if (registries.components.has(id)) throw createDuplicateRegistrationError("component", id);
34
77
  registries.components.set(id, definition);
35
78
  return definition;
36
79
  }
37
80
  //#endregion
38
- //#region src/host/wx.ts
81
+ //#region src/host/wx/index.ts
39
82
  function invokeWxApi(operation, option) {
40
83
  try {
41
84
  const result = operation();
@@ -278,10 +321,7 @@ function createHeadlessWx(driver) {
278
321
  chooseMedia: (option) => invokeWxApi(() => driver.chooseMedia(option ?? {}), option),
279
322
  chooseVideo: (option) => invokeWxApi(() => driver.chooseVideo(option ?? {}), option),
280
323
  compressImage: (option) => invokeWxApi(() => driver.compressImage(option), option),
281
- clearStorage: (option) => invokeWxApi(() => {
282
- driver.clearStorageSync();
283
- return { errMsg: "clearStorage:ok" };
284
- }, option),
324
+ clearStorage: (option) => invokeWxApi(() => ({ errMsg: (driver.clearStorageSync(), "clearStorage:ok") }), option),
285
325
  clearStorageSync: () => driver.clearStorageSync(),
286
326
  createAnimation: (option) => driver.createAnimation(option),
287
327
  createCanvasContext: (canvasId, component) => driver.createCanvasContext(canvasId, component),
@@ -645,9 +685,12 @@ function createBrowserProject(files, options = {}) {
645
685
  });
646
686
  }
647
687
  //#endregion
648
- //#region src/runtime/componentInstance.ts
688
+ //#region src/runtime/componentInstance/shared.ts
649
689
  const ARRAY_INDEX_PATH_RE$1 = /\[(\d+)\]/g;
650
690
  const ARRAY_INDEX_SEGMENT_RE$1 = /^\d+$/;
691
+ function cloneObject$1(value) {
692
+ return JSON.parse(JSON.stringify(value));
693
+ }
651
694
  function bindFunction$2(target, key, value) {
652
695
  if (typeof value !== "function") {
653
696
  target[key] = value;
@@ -655,14 +698,14 @@ function bindFunction$2(target, key, value) {
655
698
  }
656
699
  target[key] = (...args) => value.apply(target, args);
657
700
  }
658
- function cloneObject$1(value) {
659
- return JSON.parse(JSON.stringify(value));
660
- }
661
701
  function cloneValue(value) {
662
702
  if (Array.isArray(value)) return JSON.parse(JSON.stringify(value));
663
703
  if (value && typeof value === "object") return cloneObject$1(value);
664
704
  return value;
665
705
  }
706
+ function cloneRecord(value) {
707
+ return cloneObject$1(value);
708
+ }
666
709
  function parseDataPath$1(path) {
667
710
  return path.replace(ARRAY_INDEX_PATH_RE$1, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
668
711
  }
@@ -688,13 +731,70 @@ function assignByPath$1(target, path, value) {
688
731
  const normalizedLeafSegment = isArrayIndexSegment$1(leafSegment) ? Number(leafSegment) : leafSegment;
689
732
  current[normalizedLeafSegment] = value;
690
733
  }
734
+ function mergeRecord(...records) {
735
+ return Object.assign({}, ...records.filter(Boolean));
736
+ }
737
+ //#endregion
738
+ //#region src/runtime/componentInstance/observers.ts
739
+ function runPropertyObservers(definition, instance, changedKeys, previousProperties) {
740
+ const propOptions = definition.properties;
741
+ if (!propOptions || typeof propOptions !== "object" || Array.isArray(propOptions)) return;
742
+ for (const changedKey of changedKeys) {
743
+ const option = propOptions[changedKey];
744
+ if (!option || typeof option !== "object" || Array.isArray(option)) continue;
745
+ const observer = option.observer;
746
+ if (typeof observer !== "function") continue;
747
+ observer.call(instance, instance.properties[changedKey], previousProperties[changedKey]);
748
+ }
749
+ }
750
+ function normalizeObserverPattern(pattern) {
751
+ return pattern.split(",").map((item) => item.trim()).filter(Boolean);
752
+ }
753
+ function resolveObservedValue(instance, pattern) {
754
+ if (pattern === "**") return {
755
+ ...instance.properties,
756
+ ...instance.data
757
+ };
758
+ const segments = parseDataPath$1(pattern);
759
+ if (segments.length === 0) return;
760
+ const [rootSegment, ...restSegments] = segments;
761
+ let current = (Object.hasOwn(instance.properties, rootSegment) ? instance.properties : instance.data)?.[rootSegment];
762
+ for (const segment of restSegments) {
763
+ const normalizedSegment = isArrayIndexSegment$1(segment) ? Number(segment) : segment;
764
+ current = current?.[normalizedSegment];
765
+ }
766
+ return current;
767
+ }
768
+ function matchObserverPattern(pattern, changedKeys) {
769
+ if (pattern === "**") return changedKeys.length > 0;
770
+ const patterns = normalizeObserverPattern(pattern);
771
+ return changedKeys.some((changedKey) => {
772
+ return patterns.some((item) => {
773
+ if (item === "**") return true;
774
+ if (changedKey === item) return true;
775
+ return changedKey.startsWith(`${item}.`) || changedKey.startsWith(`${item}[`);
776
+ });
777
+ });
778
+ }
779
+ function runComponentObservers(definition, instance, changedKeys, previousProperties = {}) {
780
+ if (changedKeys.length === 0) return;
781
+ runPropertyObservers(definition, instance, changedKeys, previousProperties);
782
+ const observers = definition.observers;
783
+ if (observers && typeof observers === "object" && !Array.isArray(observers)) for (const [pattern, handler] of Object.entries(observers)) {
784
+ if (typeof handler !== "function" || !matchObserverPattern(pattern, changedKeys)) continue;
785
+ const args = normalizeObserverPattern(pattern).map((item) => resolveObservedValue(instance, item));
786
+ handler.call(instance, ...args);
787
+ }
788
+ }
789
+ //#endregion
790
+ //#region src/runtime/componentInstance/properties.ts
691
791
  function resolveInitialData$2(definition) {
692
792
  const rawData = definition.data;
693
793
  if (typeof rawData === "function") {
694
794
  const next = rawData.call(definition);
695
- return next && typeof next === "object" && !Array.isArray(next) ? cloneObject$1(next) : {};
795
+ return next && typeof next === "object" && !Array.isArray(next) ? cloneRecord(next) : {};
696
796
  }
697
- return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? cloneObject$1(rawData) : {};
797
+ return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? cloneRecord(rawData) : {};
698
798
  }
699
799
  function isBehaviorDefinition(value) {
700
800
  return !!value && typeof value === "object" && !Array.isArray(value) && value.__isHeadlessBehavior__ === true;
@@ -709,9 +809,6 @@ function flattenBehaviors(definition) {
709
809
  }
710
810
  return flattened;
711
811
  }
712
- function mergeRecord(...records) {
713
- return Object.assign({}, ...records.filter(Boolean));
714
- }
715
812
  function normalizeComponentDefinition(definition) {
716
813
  const behaviors = flattenBehaviors(definition);
717
814
  if (behaviors.length === 0) return definition;
@@ -818,61 +915,13 @@ function resolvePropertyDefaultValue(option) {
818
915
  if (!option || typeof option !== "object" || Array.isArray(option) || !("value" in option)) return;
819
916
  return cloneValue(option.value);
820
917
  }
821
- function runPropertyObservers(definition, instance, changedKeys, previousProperties) {
822
- const propOptions = definition.properties;
823
- if (!propOptions || typeof propOptions !== "object" || Array.isArray(propOptions)) return;
824
- for (const changedKey of changedKeys) {
825
- const option = propOptions[changedKey];
826
- if (!option || typeof option !== "object" || Array.isArray(option)) continue;
827
- const observer = option.observer;
828
- if (typeof observer !== "function") continue;
829
- observer.call(instance, instance.properties[changedKey], previousProperties[changedKey]);
830
- }
831
- }
832
- function normalizeObserverPattern(pattern) {
833
- return pattern.split(",").map((item) => item.trim()).filter(Boolean);
834
- }
835
- function resolveObservedValue(instance, pattern) {
836
- if (pattern === "**") return {
837
- ...instance.properties,
838
- ...instance.data
839
- };
840
- const segments = parseDataPath$1(pattern);
841
- if (segments.length === 0) return;
842
- const [rootSegment, ...restSegments] = segments;
843
- let current = (Object.hasOwn(instance.properties, rootSegment) ? instance.properties : instance.data)?.[rootSegment];
844
- for (const segment of restSegments) {
845
- const normalizedSegment = isArrayIndexSegment$1(segment) ? Number(segment) : segment;
846
- current = current?.[normalizedSegment];
847
- }
848
- return current;
849
- }
850
- function matchObserverPattern(pattern, changedKeys) {
851
- if (pattern === "**") return changedKeys.length > 0;
852
- const patterns = normalizeObserverPattern(pattern);
853
- return changedKeys.some((changedKey) => {
854
- return patterns.some((item) => {
855
- if (item === "**") return true;
856
- if (changedKey === item) return true;
857
- return changedKey.startsWith(`${item}.`) || changedKey.startsWith(`${item}[`);
858
- });
859
- });
860
- }
861
- function runComponentObservers(definition, instance, changedKeys, previousProperties = {}) {
862
- if (changedKeys.length === 0) return;
863
- runPropertyObservers(definition, instance, changedKeys, previousProperties);
864
- const observers = definition.observers;
865
- if (observers && typeof observers === "object" && !Array.isArray(observers)) for (const [pattern, handler] of Object.entries(observers)) {
866
- if (typeof handler !== "function" || !matchObserverPattern(pattern, changedKeys)) continue;
867
- const args = normalizeObserverPattern(pattern).map((item) => resolveObservedValue(instance, item));
868
- handler.call(instance, ...args);
869
- }
870
- }
871
918
  function normalizeComponentPropertyValue(definition, key, rawValue) {
872
919
  const option = definition.properties?.[key];
873
920
  if (rawValue == null) return resolvePropertyDefaultValue(option);
874
921
  return coerceComponentPropertyValue(rawValue, option);
875
922
  }
923
+ //#endregion
924
+ //#region src/runtime/componentInstance/index.ts
876
925
  function createComponentInstance(options) {
877
926
  const definition = normalizeComponentDefinition(options.definition);
878
927
  const instance = {
@@ -913,9 +962,11 @@ function runComponentPageLifetime(instance, lifetimeName, payload) {
913
962
  handler.call(instance, payload);
914
963
  }
915
964
  //#endregion
916
- //#region src/browser/render.ts
917
- const LEADING_SLASH_RE$5 = /^\/+/;
965
+ //#region src/browser/render/shared.ts
918
966
  const TEMPLATE_INTERPOLATION_RE$2 = /\{\{([^{}]+)\}\}/g;
967
+ const DATASET_NAME_RE$4 = /-([a-z])/g;
968
+ const BRACKET_INDEX_RE$1 = /\[(\d+)\]/g;
969
+ const LEADING_SLASH_RE$5 = /^\/+/;
919
970
  const EVENT_BINDING_ATTRS$1 = [
920
971
  "bindtap",
921
972
  "bind:tap",
@@ -937,9 +988,7 @@ const STRUCTURAL_ATTRS$1 = [
937
988
  "wx:for-index",
938
989
  "wx:key"
939
990
  ];
940
- const WX_ELSE_ATTRS$1 = new Set(["wx:elif", "wx:else"]);
941
- const DATASET_NAME_RE$4 = /-([a-z])/g;
942
- const BRACKET_INDEX_RE$1 = /\[(\d+)\]/g;
991
+ const WX_ELSE_ATTRS$1 = /* @__PURE__ */ new Set(["wx:elif", "wx:else"]);
943
992
  const CLASS_SPLIT_RE$1 = /\s+/;
944
993
  const JS_FILE_RE$1 = /\.js$/;
945
994
  function isMustacheOnly$1(value) {
@@ -1049,6 +1098,57 @@ function resolveComponentAttributeValue$1(value, scope) {
1049
1098
  }
1050
1099
  return interpolateTemplate$2(value, scope.data);
1051
1100
  }
1101
+ function applyNodeBindings$1(node, scope) {
1102
+ if (!isTagNode$1(node)) {
1103
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate$2(node.data, scope.data);
1104
+ return;
1105
+ }
1106
+ node.attribs ??= {};
1107
+ node.attribs["data-sim-scope"] = scope.getScopeId();
1108
+ for (const key of STRUCTURAL_ATTRS$1) delete node.attribs[key];
1109
+ for (const [key, value] of Object.entries({ ...node.attribs })) {
1110
+ if (EVENT_BINDING_ATTRS$1.includes(key)) {
1111
+ node.attribs["data-sim-tap"] = value;
1112
+ continue;
1113
+ }
1114
+ node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue$1(value, scope)) : String(value);
1115
+ }
1116
+ }
1117
+ function createMergedScopeData$1(pageData, componentProperties, componentData) {
1118
+ return {
1119
+ ...pageData,
1120
+ ...componentProperties,
1121
+ ...componentData
1122
+ };
1123
+ }
1124
+ function evaluateConditionalBranch$1(node, scope) {
1125
+ const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
1126
+ if (condition == null) return true;
1127
+ return Boolean(resolveRawValueByPath$1(scope.data, condition));
1128
+ }
1129
+ function createLoopScope$1(scope, itemName, indexName, item, index) {
1130
+ return {
1131
+ ...scope,
1132
+ data: {
1133
+ ...scope.data,
1134
+ [indexName]: index,
1135
+ [itemName]: item
1136
+ }
1137
+ };
1138
+ }
1139
+ //#endregion
1140
+ //#region src/browser/render/component.ts
1141
+ function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, alias) {
1142
+ const componentBasePath = resolveUsingComponents$1(context.files, ownerJsonPath, ownerFilePath).get(alias);
1143
+ if (!componentBasePath) return null;
1144
+ const filePath = `${componentBasePath}.js`;
1145
+ const templatePath = `${componentBasePath}.wxml`;
1146
+ return {
1147
+ definition: context.moduleLoader.executeComponentModule(filePath, componentBasePath),
1148
+ filePath,
1149
+ templatePath
1150
+ };
1151
+ }
1052
1152
  function resolveUsingComponents$1(files, ownerJsonPath, ownerFilePath) {
1053
1153
  const ownerJson = readBrowserVirtualFile(files, ownerJsonPath);
1054
1154
  if (typeof ownerJson !== "string") return /* @__PURE__ */ new Map();
@@ -1066,17 +1166,6 @@ function resolveUsingComponents$1(files, ownerJsonPath, ownerFilePath) {
1066
1166
  return /* @__PURE__ */ new Map();
1067
1167
  }
1068
1168
  }
1069
- function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, alias) {
1070
- const componentBasePath = resolveUsingComponents$1(context.files, ownerJsonPath, ownerFilePath).get(alias);
1071
- if (!componentBasePath) return null;
1072
- const filePath = `${componentBasePath}.js`;
1073
- const templatePath = `${componentBasePath}.wxml`;
1074
- return {
1075
- definition: context.moduleLoader.executeComponentModule(filePath, componentBasePath),
1076
- filePath,
1077
- templatePath
1078
- };
1079
- }
1080
1169
  function collectComponentEventBindings$1(hostNode) {
1081
1170
  const eventBindings = /* @__PURE__ */ new Map();
1082
1171
  for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
@@ -1127,22 +1216,6 @@ function buildComponentTrigger$1(componentScopeId, context, hostNode) {
1127
1216
  }
1128
1217
  };
1129
1218
  }
1130
- function applyNodeBindings$1(node, scope) {
1131
- if (!isTagNode$1(node)) {
1132
- if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate$2(node.data, scope.data);
1133
- return;
1134
- }
1135
- node.attribs ??= {};
1136
- node.attribs["data-sim-scope"] = scope.getScopeId();
1137
- for (const key of STRUCTURAL_ATTRS$1) delete node.attribs[key];
1138
- for (const [key, value] of Object.entries({ ...node.attribs })) {
1139
- if (EVENT_BINDING_ATTRS$1.includes(key)) {
1140
- node.attribs["data-sim-tap"] = value;
1141
- continue;
1142
- }
1143
- node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue$1(value, scope)) : String(value);
1144
- }
1145
- }
1146
1219
  function syncComponentProperties$1(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
1147
1220
  const changedRootKeys = [];
1148
1221
  const previousProperties = {};
@@ -1165,31 +1238,63 @@ function syncComponentProperties$1(instance, definition, nextProperties, binding
1165
1238
  if (changedRootKeys.length === 0) return;
1166
1239
  runComponentObservers(definition, instance, changedRootKeys, previousProperties);
1167
1240
  }
1168
- function createMergedScopeData$1(pageData, componentProperties, componentData) {
1241
+ function createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance) {
1242
+ const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
1169
1243
  return {
1170
- ...pageData,
1171
- ...componentProperties,
1172
- ...componentData
1244
+ alias: clonedNode.name,
1245
+ classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
1246
+ data: createMergedScopeData$1(scope.data, componentInstance.properties, componentInstance.data),
1247
+ dataset: collectDataset$4(clonedNode),
1248
+ eventBindings: collectComponentEventBindings$1(clonedNode),
1249
+ getMethod: (methodName) => {
1250
+ const method = componentInstance?.[methodName];
1251
+ return typeof method === "function" ? method : void 0;
1252
+ },
1253
+ getScopeId: () => componentScopeId,
1254
+ hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
1255
+ id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
1256
+ listenerScopeId: scope.getScopeId(),
1257
+ ownerScopeId
1173
1258
  };
1174
1259
  }
1175
- function isTruthy$1(value) {
1176
- return Boolean(value);
1177
- }
1178
- function createLoopScope$1(scope, itemName, indexName, item, index) {
1260
+ function resolveComponentProperties$1(clonedNode, scope) {
1261
+ const nextProperties = {};
1262
+ const bindingExpressions = {};
1263
+ for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
1264
+ if (key.startsWith("bind")) continue;
1265
+ if (isMustacheOnly$1(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
1266
+ nextProperties[key] = resolveComponentAttributeValue$1(String(value), scope);
1267
+ }
1179
1268
  return {
1180
- ...scope,
1181
- data: {
1182
- ...scope.data,
1183
- [indexName]: index,
1184
- [itemName]: item
1185
- }
1269
+ nextProperties,
1270
+ bindingExpressions
1186
1271
  };
1187
1272
  }
1188
- function evaluateConditionalBranch$1(node, scope) {
1189
- const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
1190
- if (condition == null) return true;
1191
- return isTruthy$1(resolveRawValueByPath$1(scope.data, condition));
1273
+ function createBrowserComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId) {
1274
+ const componentInstance = createComponentInstance({
1275
+ definition: componentEntry.definition,
1276
+ properties: nextProperties,
1277
+ triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
1278
+ });
1279
+ componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
1280
+ componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
1281
+ componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
1282
+ componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
1283
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
1284
+ runComponentLifecycle(componentInstance, "created");
1285
+ runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
1286
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
1287
+ runComponentLifecycle(componentInstance, "attached");
1288
+ runComponentPageLifetime(componentInstance, "show");
1289
+ context.componentCache.set(componentScopeId, componentInstance);
1290
+ return componentInstance;
1291
+ }
1292
+ function renderBrowserComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
1293
+ const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, componentEntry.templatePath));
1294
+ return renderNodeTree((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes);
1192
1295
  }
1296
+ //#endregion
1297
+ //#region src/browser/render/index.ts
1193
1298
  function expandNodeByFor$1(node, scope) {
1194
1299
  const forExpression = node.attribs?.["wx:for"];
1195
1300
  if (!forExpression) return [{
@@ -1259,52 +1364,14 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
1259
1364
  if (componentEntry) {
1260
1365
  const componentScopeId = `${instancePath}/${clonedNode.name}`;
1261
1366
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
1262
- const nextProperties = {};
1263
- const bindingExpressions = {};
1264
- for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
1265
- if (key.startsWith("bind")) continue;
1266
- if (isMustacheOnly$1(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
1267
- nextProperties[key] = resolveComponentAttributeValue$1(String(value), scope);
1268
- }
1367
+ const { nextProperties, bindingExpressions } = resolveComponentProperties$1(clonedNode, scope);
1269
1368
  let componentInstance = context.componentCache.get(componentScopeId);
1270
- if (!componentInstance) {
1271
- componentInstance = createComponentInstance({
1272
- definition: componentEntry.definition,
1273
- properties: nextProperties,
1274
- triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
1275
- });
1276
- componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
1277
- componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
1278
- componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
1279
- componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
1280
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
1281
- runComponentLifecycle(componentInstance, "created");
1282
- runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
1283
- componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
1284
- runComponentLifecycle(componentInstance, "attached");
1285
- runComponentPageLifetime(componentInstance, "show");
1286
- context.componentCache.set(componentScopeId, componentInstance);
1287
- } else syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
1369
+ if (!componentInstance) componentInstance = createBrowserComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId);
1370
+ else syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
1288
1371
  seenComponentScopes.add(componentScopeId);
1289
- const componentScope = {
1290
- alias: clonedNode.name,
1291
- classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
1292
- data: createMergedScopeData$1(scope.data, componentInstance.properties, componentInstance.data),
1293
- dataset: collectDataset$4(clonedNode),
1294
- eventBindings: collectComponentEventBindings$1(clonedNode),
1295
- getMethod: (methodName) => {
1296
- const method = componentInstance?.[methodName];
1297
- return typeof method === "function" ? method : void 0;
1298
- },
1299
- getScopeId: () => componentScopeId,
1300
- hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
1301
- id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
1302
- listenerScopeId: scope.getScopeId(),
1303
- ownerScopeId
1304
- };
1372
+ const componentScope = createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance);
1305
1373
  context.componentScopes.set(componentScopeId, componentScope);
1306
- const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, componentEntry.templatePath));
1307
- const renderedComponentRoot = renderNodeTree$1((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes);
1374
+ const renderedComponentRoot = renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, componentScope, componentScopeId, seenComponentScopes);
1308
1375
  if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
1309
1376
  if (!componentInstance.__ready__) {
1310
1377
  runComponentLifecycle(componentInstance, "ready");
@@ -1563,11 +1630,10 @@ function deriveMenuButtonBoundingClientRect(systemInfo) {
1563
1630
  const height = 32;
1564
1631
  const top = 32;
1565
1632
  const right = Math.max(systemInfo.windowWidth - 12, width);
1566
- const left = Math.max(0, right - width);
1567
1633
  return {
1568
- bottom: top + height,
1634
+ bottom: 64,
1569
1635
  height,
1570
- left,
1636
+ left: Math.max(0, right - width),
1571
1637
  right,
1572
1638
  top,
1573
1639
  width
@@ -1585,7 +1651,7 @@ const SAVED_FILE_PREFIXES = ["headless://saved/", "headless://wxfile/saved/"];
1585
1651
  const textEncoder = new TextEncoder();
1586
1652
  const IMAGE_EXTENSION_RE = /\.([^.?#/]+)(?:[?#].*)?$/;
1587
1653
  const LEADING_DOT_RE = /^\.+/;
1588
- const IMAGE_FILE_EXTENSIONS = new Set([
1654
+ const IMAGE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
1589
1655
  "bmp",
1590
1656
  "gif",
1591
1657
  "heic",
@@ -1594,7 +1660,7 @@ const IMAGE_FILE_EXTENSIONS = new Set([
1594
1660
  "png",
1595
1661
  "webp"
1596
1662
  ]);
1597
- const VIDEO_FILE_EXTENSIONS = new Set([
1663
+ const VIDEO_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
1598
1664
  "avi",
1599
1665
  "m4v",
1600
1666
  "mov",
@@ -1863,10 +1929,12 @@ function inferImageType(filePath, fileContent) {
1863
1929
  }
1864
1930
  function inferImageSize(fileContent) {
1865
1931
  try {
1866
- const payload = JSON.parse(fileContent);
1932
+ const config = JSON.parse(fileContent)?.config;
1933
+ const destHeight = config && "destHeight" in config ? config.destHeight : void 0;
1934
+ const destWidth = config && "destWidth" in config ? config.destWidth : void 0;
1867
1935
  return {
1868
- height: payload?.config?.destHeight ?? payload?.config?.height ?? 0,
1869
- width: payload?.config?.destWidth ?? payload?.config?.width ?? 0
1936
+ height: destHeight ?? config?.height ?? 0,
1937
+ width: destWidth ?? config?.width ?? 0
1870
1938
  };
1871
1939
  } catch {
1872
1940
  return {
@@ -2647,7 +2715,7 @@ function createHeadlessWxState() {
2647
2715
  width
2648
2716
  };
2649
2717
  }),
2650
- type: mediaTypes.length > 1 ? "mix" : mediaTypes[0]
2718
+ type: mediaTypes.length > 1 ? "mix" : mediaTypes[0] ?? "image"
2651
2719
  };
2652
2720
  },
2653
2721
  chooseVideo(option) {
@@ -3228,6 +3296,8 @@ function resolveComponentScopeId(scopeId) {
3228
3296
  return scopeId;
3229
3297
  }
3230
3298
  var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
3299
+ node;
3300
+ interactions;
3231
3301
  constructor(node, interactions) {
3232
3302
  this.node = node;
3233
3303
  this.interactions = interactions;
@@ -4910,6 +4980,7 @@ var BrowserHeadlessSession = class {
4910
4980
  const pageInstance = this.createFreshPage(target);
4911
4981
  this.pages.push(pageInstance);
4912
4982
  this.currentPageInstance = pageInstance;
4983
+ this.runInitialPageLifecycles(pageInstance, target.query);
4913
4984
  return pageInstance;
4914
4985
  }
4915
4986
  navigateTo(url) {
@@ -4922,6 +4993,7 @@ var BrowserHeadlessSession = class {
4922
4993
  const pageInstance = this.createFreshPage(target);
4923
4994
  this.pages.push(pageInstance);
4924
4995
  this.currentPageInstance = pageInstance;
4996
+ this.runInitialPageLifecycles(pageInstance, target.query);
4925
4997
  return pageInstance;
4926
4998
  }
4927
4999
  redirectTo(url) {
@@ -4936,6 +5008,7 @@ var BrowserHeadlessSession = class {
4936
5008
  const pageInstance = this.createFreshPage(target);
4937
5009
  this.pages.push(pageInstance);
4938
5010
  this.currentPageInstance = pageInstance;
5011
+ this.runInitialPageLifecycles(pageInstance, target.query);
4939
5012
  return pageInstance;
4940
5013
  }
4941
5014
  navigateBack(delta = 1) {
@@ -4972,17 +5045,21 @@ var BrowserHeadlessSession = class {
4972
5045
  this.unloadPage(page);
4973
5046
  }
4974
5047
  let nextPage = cachedTarget;
5048
+ let shouldRunInitialLifecycles = false;
4975
5049
  if (!nextPage) {
4976
5050
  nextPage = this.createFreshPage(target);
4977
5051
  this.tabPages.set(target.routeRecord.route, nextPage);
4978
- } else if (current !== nextPage) {
4979
- nextPage.onShow?.();
4980
- this.runPageComponentLifetime(nextPage.route, "show");
5052
+ shouldRunInitialLifecycles = true;
4981
5053
  }
4982
- nextPage.onTabItemTap?.(tabItem);
4983
5054
  this.pages.length = 0;
4984
5055
  this.pages.push(nextPage);
4985
5056
  this.currentPageInstance = nextPage;
5057
+ if (shouldRunInitialLifecycles) this.runInitialPageLifecycles(nextPage, target.query);
5058
+ else if (current !== nextPage) {
5059
+ nextPage.onShow?.();
5060
+ this.runPageComponentLifetime(nextPage.route, "show");
5061
+ }
5062
+ nextPage.onTabItemTap?.(tabItem);
4986
5063
  return nextPage;
4987
5064
  }
4988
5065
  pageScrollTo(option) {
@@ -5084,12 +5161,14 @@ var BrowserHeadlessSession = class {
5084
5161
  pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
5085
5162
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
5086
5163
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
5087
- pageInstance.onLoad?.(target.query);
5088
- pageInstance.onShow?.();
5089
- pageInstance.onReady?.();
5090
5164
  if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
5091
5165
  return pageInstance;
5092
5166
  }
5167
+ runInitialPageLifecycles(pageInstance, query) {
5168
+ pageInstance.onLoad?.(query);
5169
+ pageInstance.onShow?.();
5170
+ pageInstance.onReady?.();
5171
+ }
5093
5172
  isTabBarRoute(route) {
5094
5173
  return this.tabBarRoutes.has(stripLeadingSlash$1(route));
5095
5174
  }
@@ -5125,7 +5204,7 @@ var BrowserHeadlessSession = class {
5125
5204
  return item;
5126
5205
  }
5127
5206
  unloadAllPages() {
5128
- const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
5207
+ const pagesToUnload = /* @__PURE__ */ new Set([...this.pages, ...this.tabPages.values()]);
5129
5208
  for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
5130
5209
  this.pages.length = 0;
5131
5210
  this.tabPages.clear();
@@ -5336,9 +5415,11 @@ function loadProject(projectPath) {
5336
5415
  });
5337
5416
  }
5338
5417
  //#endregion
5339
- //#region src/runtime/render.ts
5340
- const LEADING_SLASH_RE$2 = /^\/+/;
5418
+ //#region src/runtime/render/shared.ts
5341
5419
  const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
5420
+ const DATASET_NAME_RE = /-([a-z])/g;
5421
+ const BRACKET_INDEX_RE = /\[(\d+)\]/g;
5422
+ const LEADING_SLASH_RE$2 = /^\/+/;
5342
5423
  const EVENT_BINDING_ATTRS = [
5343
5424
  "bindtap",
5344
5425
  "bind:tap",
@@ -5360,9 +5441,7 @@ const STRUCTURAL_ATTRS = [
5360
5441
  "wx:for-index",
5361
5442
  "wx:key"
5362
5443
  ];
5363
- const WX_ELSE_ATTRS = new Set(["wx:elif", "wx:else"]);
5364
- const DATASET_NAME_RE = /-([a-z])/g;
5365
- const BRACKET_INDEX_RE = /\[(\d+)\]/g;
5444
+ const WX_ELSE_ATTRS = /* @__PURE__ */ new Set(["wx:elif", "wx:else"]);
5366
5445
  const CLASS_SPLIT_RE = /\s+/;
5367
5446
  const JS_FILE_RE = /\.js$/;
5368
5447
  function isMustacheOnly(value) {
@@ -5470,21 +5549,46 @@ function resolveComponentAttributeValue(value, scope) {
5470
5549
  }
5471
5550
  return interpolateTemplate(value, scope.data);
5472
5551
  }
5473
- function resolveUsingComponents(ownerJsonPath, ownerFilePath) {
5474
- try {
5475
- const usingComponents = JSON.parse(fs.readFileSync(ownerJsonPath, "utf8")).usingComponents;
5476
- if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
5477
- const resolved = /* @__PURE__ */ new Map();
5478
- for (const [alias, rawPath] of Object.entries(usingComponents)) {
5479
- if (typeof rawPath !== "string") continue;
5480
- const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$2, "") : path.posix.normalize(path.posix.join(path.posix.dirname(ownerFilePath), rawPath));
5481
- resolved.set(alias, basePath.replace(LEADING_SLASH_RE$2, ""));
5552
+ function applyNodeBindings(node, scope) {
5553
+ if (!isTagNode(node)) {
5554
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate(node.data, scope.data);
5555
+ return;
5556
+ }
5557
+ node.attribs ??= {};
5558
+ node.attribs["data-sim-scope"] = scope.getScopeId();
5559
+ for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
5560
+ for (const [key, value] of Object.entries({ ...node.attribs })) {
5561
+ if (EVENT_BINDING_ATTRS.includes(key)) {
5562
+ node.attribs["data-sim-tap"] = value;
5563
+ continue;
5482
5564
  }
5483
- return resolved;
5484
- } catch {
5485
- return /* @__PURE__ */ new Map();
5565
+ node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
5486
5566
  }
5487
5567
  }
5568
+ function createMergedScopeData(pageData, componentProperties, componentData) {
5569
+ return {
5570
+ ...pageData,
5571
+ ...componentProperties,
5572
+ ...componentData
5573
+ };
5574
+ }
5575
+ function evaluateConditionalBranch(node, scope) {
5576
+ const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
5577
+ if (condition == null) return true;
5578
+ return Boolean(resolveRawValueByPath(scope.data, condition));
5579
+ }
5580
+ function createLoopScope(scope, itemName, indexName, item, index) {
5581
+ return {
5582
+ ...scope,
5583
+ data: {
5584
+ ...scope.data,
5585
+ [indexName]: index,
5586
+ [itemName]: item
5587
+ }
5588
+ };
5589
+ }
5590
+ //#endregion
5591
+ //#region src/runtime/render/component.ts
5488
5592
  function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias) {
5489
5593
  const componentBasePath = resolveUsingComponents(ownerJsonPath, ownerFilePath).get(alias);
5490
5594
  if (!componentBasePath) return null;
@@ -5499,6 +5603,21 @@ function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, al
5499
5603
  absoluteTemplatePath
5500
5604
  };
5501
5605
  }
5606
+ function resolveUsingComponents(ownerJsonPath, ownerFilePath) {
5607
+ try {
5608
+ const usingComponents = JSON.parse(fs.readFileSync(ownerJsonPath, "utf8")).usingComponents;
5609
+ if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
5610
+ const resolved = /* @__PURE__ */ new Map();
5611
+ for (const [alias, rawPath] of Object.entries(usingComponents)) {
5612
+ if (typeof rawPath !== "string") continue;
5613
+ const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$2, "") : path.posix.normalize(path.posix.join(path.posix.dirname(ownerFilePath), rawPath));
5614
+ resolved.set(alias, basePath.replace(LEADING_SLASH_RE$2, ""));
5615
+ }
5616
+ return resolved;
5617
+ } catch {
5618
+ return /* @__PURE__ */ new Map();
5619
+ }
5620
+ }
5502
5621
  function collectComponentEventBindings(hostNode) {
5503
5622
  const eventBindings = /* @__PURE__ */ new Map();
5504
5623
  for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
@@ -5549,22 +5668,6 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
5549
5668
  }
5550
5669
  };
5551
5670
  }
5552
- function applyNodeBindings(node, scope) {
5553
- if (!isTagNode(node)) {
5554
- if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate(node.data, scope.data);
5555
- return;
5556
- }
5557
- node.attribs ??= {};
5558
- node.attribs["data-sim-scope"] = scope.getScopeId();
5559
- for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
5560
- for (const [key, value] of Object.entries({ ...node.attribs })) {
5561
- if (EVENT_BINDING_ATTRS.includes(key)) {
5562
- node.attribs["data-sim-tap"] = value;
5563
- continue;
5564
- }
5565
- node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
5566
- }
5567
- }
5568
5671
  function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
5569
5672
  const changedRootKeys = [];
5570
5673
  const previousProperties = {};
@@ -5587,31 +5690,62 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
5587
5690
  if (changedRootKeys.length === 0) return;
5588
5691
  runComponentObservers(definition, instance, changedRootKeys, previousProperties);
5589
5692
  }
5590
- function createMergedScopeData(pageData, componentProperties, componentData) {
5693
+ function createComponentScope(clonedNode, scope, componentScopeId, componentInstance) {
5694
+ const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
5591
5695
  return {
5592
- ...pageData,
5593
- ...componentProperties,
5594
- ...componentData
5696
+ alias: clonedNode.name,
5697
+ classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
5698
+ data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
5699
+ dataset: collectDataset(clonedNode),
5700
+ eventBindings: collectComponentEventBindings(clonedNode),
5701
+ getMethod: (methodName) => {
5702
+ const method = componentInstance?.[methodName];
5703
+ return typeof method === "function" ? method : void 0;
5704
+ },
5705
+ getScopeId: () => componentScopeId,
5706
+ hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
5707
+ id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
5708
+ listenerScopeId: scope.getScopeId(),
5709
+ ownerScopeId
5595
5710
  };
5596
5711
  }
5597
- function isTruthy(value) {
5598
- return Boolean(value);
5599
- }
5600
- function createLoopScope(scope, itemName, indexName, item, index) {
5712
+ function resolveComponentProperties(clonedNode, scope) {
5713
+ const nextProperties = {};
5714
+ const bindingExpressions = {};
5715
+ for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
5716
+ if (key.startsWith("bind")) continue;
5717
+ if (isMustacheOnly(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
5718
+ nextProperties[key] = resolveComponentAttributeValue(String(value), scope);
5719
+ }
5601
5720
  return {
5602
- ...scope,
5603
- data: {
5604
- ...scope.data,
5605
- [indexName]: index,
5606
- [itemName]: item
5607
- }
5721
+ nextProperties,
5722
+ bindingExpressions
5608
5723
  };
5609
5724
  }
5610
- function evaluateConditionalBranch(node, scope) {
5611
- const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
5612
- if (condition == null) return true;
5613
- return isTruthy(resolveRawValueByPath(scope.data, condition));
5725
+ function createRuntimeComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId) {
5726
+ const componentInstance = createComponentInstance({
5727
+ definition: componentEntry.definition,
5728
+ properties: nextProperties,
5729
+ triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
5730
+ });
5731
+ componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
5732
+ componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
5733
+ componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
5734
+ componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
5735
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
5736
+ runComponentLifecycle(componentInstance, "created");
5737
+ runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
5738
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
5739
+ runComponentLifecycle(componentInstance, "attached");
5740
+ context.componentCache.set(componentScopeId, componentInstance);
5741
+ return componentInstance;
5742
+ }
5743
+ function renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
5744
+ const componentDocument = parseTemplateDocument(readTemplateSource(componentEntry.absoluteTemplatePath));
5745
+ return renderNodeTree((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, seenComponentScopes);
5614
5746
  }
5747
+ //#endregion
5748
+ //#region src/runtime/render/index.ts
5615
5749
  function expandNodeByFor(node, scope) {
5616
5750
  const forExpression = node.attribs?.["wx:for"];
5617
5751
  if (!forExpression) return [{
@@ -5681,51 +5815,14 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
5681
5815
  if (componentEntry) {
5682
5816
  const componentScopeId = `${instancePath}/${clonedNode.name}`;
5683
5817
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
5684
- const nextProperties = {};
5685
- const bindingExpressions = {};
5686
- for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
5687
- if (key.startsWith("bind")) continue;
5688
- if (isMustacheOnly(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
5689
- nextProperties[key] = resolveComponentAttributeValue(String(value), scope);
5690
- }
5818
+ const { nextProperties, bindingExpressions } = resolveComponentProperties(clonedNode, scope);
5691
5819
  let componentInstance = context.componentCache.get(componentScopeId);
5692
- if (!componentInstance) {
5693
- componentInstance = createComponentInstance({
5694
- definition: componentEntry.definition,
5695
- properties: nextProperties,
5696
- triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
5697
- });
5698
- componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
5699
- componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
5700
- componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
5701
- componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
5702
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
5703
- runComponentLifecycle(componentInstance, "created");
5704
- runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
5705
- componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
5706
- runComponentLifecycle(componentInstance, "attached");
5707
- context.componentCache.set(componentScopeId, componentInstance);
5708
- } else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
5820
+ if (!componentInstance) componentInstance = createRuntimeComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId);
5821
+ else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
5709
5822
  seenComponentScopes.add(componentScopeId);
5710
- const componentScope = {
5711
- alias: clonedNode.name,
5712
- classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
5713
- data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
5714
- dataset: collectDataset(clonedNode),
5715
- eventBindings: collectComponentEventBindings(clonedNode),
5716
- getMethod: (methodName) => {
5717
- const method = componentInstance?.[methodName];
5718
- return typeof method === "function" ? method : void 0;
5719
- },
5720
- getScopeId: () => componentScopeId,
5721
- hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
5722
- id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
5723
- listenerScopeId: scope.getScopeId(),
5724
- ownerScopeId
5725
- };
5823
+ const componentScope = createComponentScope(clonedNode, scope, componentScopeId, componentInstance);
5726
5824
  context.componentScopes.set(componentScopeId, componentScope);
5727
- const componentDocument = parseTemplateDocument(readTemplateSource(componentEntry.absoluteTemplatePath));
5728
- const renderedComponentRoot = renderNodeTree((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, seenComponentScopes);
5825
+ const renderedComponentRoot = renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes);
5729
5826
  if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
5730
5827
  if (!componentInstance.__ready__) {
5731
5828
  runComponentLifecycle(componentInstance, "ready");
@@ -5863,7 +5960,8 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
5863
5960
  const definition = registries.components.get(id);
5864
5961
  if (!definition) throw new Error(`Component() was not registered for id "${id}" while executing ${normalize(filePath)}.`);
5865
5962
  return definition;
5866
- }
5963
+ },
5964
+ wx: executionContext.wx
5867
5965
  };
5868
5966
  }
5869
5967
  //#endregion
@@ -6084,6 +6182,11 @@ var HeadlessSession = class {
6084
6182
  getCurrentPages() {
6085
6183
  return this.pages.slice();
6086
6184
  }
6185
+ callWxMethod(methodName, ...args) {
6186
+ const method = this.moduleLoader.wx[methodName];
6187
+ if (typeof method !== "function") throw new TypeError(`wx.${methodName} is not available in headless runtime.`);
6188
+ return Reflect.apply(method, this.moduleLoader.wx, args);
6189
+ }
6087
6190
  getCurrentPageNavigationBarTitle() {
6088
6191
  return this.currentPageInstance?.__navigationBarTitle__ ?? null;
6089
6192
  }
@@ -6452,6 +6555,7 @@ var HeadlessSession = class {
6452
6555
  const pageInstance = this.createFreshPage(target);
6453
6556
  this.pages.push(pageInstance);
6454
6557
  this.currentPageInstance = pageInstance;
6558
+ this.runInitialPageLifecycles(pageInstance, target.query);
6455
6559
  return pageInstance;
6456
6560
  }
6457
6561
  navigateTo(url) {
@@ -6464,6 +6568,7 @@ var HeadlessSession = class {
6464
6568
  const pageInstance = this.createFreshPage(target);
6465
6569
  this.pages.push(pageInstance);
6466
6570
  this.currentPageInstance = pageInstance;
6571
+ this.runInitialPageLifecycles(pageInstance, target.query);
6467
6572
  return pageInstance;
6468
6573
  }
6469
6574
  redirectTo(url) {
@@ -6478,6 +6583,7 @@ var HeadlessSession = class {
6478
6583
  const pageInstance = this.createFreshPage(target);
6479
6584
  this.pages.push(pageInstance);
6480
6585
  this.currentPageInstance = pageInstance;
6586
+ this.runInitialPageLifecycles(pageInstance, target.query);
6481
6587
  return pageInstance;
6482
6588
  }
6483
6589
  navigateBack(delta = 1) {
@@ -6514,17 +6620,21 @@ var HeadlessSession = class {
6514
6620
  this.unloadPage(page);
6515
6621
  }
6516
6622
  let nextPage = cachedTarget;
6623
+ let shouldRunInitialLifecycles = false;
6517
6624
  if (!nextPage) {
6518
6625
  nextPage = this.createFreshPage(target);
6519
6626
  this.tabPages.set(target.routeRecord.route, nextPage);
6520
- } else if (current !== nextPage) {
6521
- nextPage.onShow?.();
6522
- this.runPageComponentLifetime(nextPage.route, "show");
6627
+ shouldRunInitialLifecycles = true;
6523
6628
  }
6524
- nextPage.onTabItemTap?.(tabItem);
6525
6629
  this.pages.length = 0;
6526
6630
  this.pages.push(nextPage);
6527
6631
  this.currentPageInstance = nextPage;
6632
+ if (shouldRunInitialLifecycles) this.runInitialPageLifecycles(nextPage, target.query);
6633
+ else if (current !== nextPage) {
6634
+ nextPage.onShow?.();
6635
+ this.runPageComponentLifetime(nextPage.route, "show");
6636
+ }
6637
+ nextPage.onTabItemTap?.(tabItem);
6528
6638
  return nextPage;
6529
6639
  }
6530
6640
  pageScrollTo(option) {
@@ -6599,12 +6709,14 @@ var HeadlessSession = class {
6599
6709
  pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
6600
6710
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
6601
6711
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
6602
- pageInstance.onLoad?.(target.query);
6603
- pageInstance.onShow?.();
6604
- pageInstance.onReady?.();
6605
6712
  if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
6606
6713
  return pageInstance;
6607
6714
  }
6715
+ runInitialPageLifecycles(pageInstance, query) {
6716
+ pageInstance.onLoad?.(query);
6717
+ pageInstance.onShow?.();
6718
+ pageInstance.onReady?.();
6719
+ }
6608
6720
  isTabBarRoute(route) {
6609
6721
  return this.tabBarRoutes.has(stripLeadingSlash(route));
6610
6722
  }
@@ -6640,7 +6752,7 @@ var HeadlessSession = class {
6640
6752
  };
6641
6753
  }
6642
6754
  unloadAllPages() {
6643
- const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
6755
+ const pagesToUnload = /* @__PURE__ */ new Set([...this.pages, ...this.tabPages.values()]);
6644
6756
  for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
6645
6757
  this.pages.length = 0;
6646
6758
  this.tabPages.clear();
@@ -6810,15 +6922,67 @@ function createHeadlessSession(options) {
6810
6922
  return new HeadlessSession(options);
6811
6923
  }
6812
6924
  //#endregion
6813
- //#region src/testing/pageHandle.ts
6925
+ //#region src/testing/sessionHandle/shared.ts
6926
+ const LEADING_SLASH_RE = /^\/+/;
6814
6927
  const DEFAULT_WAIT_TIMEOUT$1 = 1e3;
6815
6928
  const DEFAULT_WAIT_INTERVAL$1 = 10;
6929
+ function normalizeRoute(route) {
6930
+ return route.replace(LEADING_SLASH_RE, "");
6931
+ }
6932
+ function resolvePageScopeId(scopeId) {
6933
+ const pagePathIndex = scopeId.indexOf("/page/");
6934
+ return pagePathIndex >= 0 ? scopeId.slice(0, pagePathIndex) : scopeId;
6935
+ }
6936
+ function normalizeNonEmptyInput(value, label) {
6937
+ const normalizedValue = value.trim();
6938
+ if (!normalizedValue) throw new Error(`${label} must be a non-empty string in headless testing runtime.`);
6939
+ return normalizedValue;
6940
+ }
6941
+ async function waitForDelay(ms = 0) {
6942
+ if (ms <= 0) return;
6943
+ await new Promise((resolve) => setTimeout(resolve, ms));
6944
+ }
6945
+ async function pollUntil(check, errorMessage, options = {}) {
6946
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT$1)) : DEFAULT_WAIT_TIMEOUT$1;
6947
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL$1)) : DEFAULT_WAIT_INTERVAL$1;
6948
+ const deadline = Date.now() + timeout;
6949
+ while (true) {
6950
+ const result = await check();
6951
+ if (result != null) return result;
6952
+ if (Date.now() >= deadline) throw new Error(errorMessage);
6953
+ await waitForDelay(interval);
6954
+ }
6955
+ }
6956
+ async function runWithTimeout(operation, timeout, message) {
6957
+ if (!Number.isFinite(timeout) || (timeout ?? 0) <= 0) return await operation();
6958
+ let timer;
6959
+ try {
6960
+ return await Promise.race([Promise.resolve().then(operation), new Promise((_resolve, reject) => {
6961
+ timer = setTimeout(() => reject(new Error(message)), Math.trunc(timeout));
6962
+ })]);
6963
+ } finally {
6964
+ if (timer) clearTimeout(timer);
6965
+ }
6966
+ }
6967
+ //#endregion
6968
+ //#region src/testing/pageHandle.ts
6969
+ const DEFAULT_WAIT_TIMEOUT = 1e3;
6970
+ const DEFAULT_WAIT_INTERVAL = 10;
6816
6971
  var HeadlessTestingPageHandle = class {
6972
+ project;
6973
+ page;
6974
+ session;
6817
6975
  constructor(project, page, session) {
6818
6976
  this.project = project;
6819
6977
  this.page = page;
6820
6978
  this.session = session;
6821
6979
  }
6980
+ get path() {
6981
+ return this.page.route;
6982
+ }
6983
+ get query() {
6984
+ return { ...this.page.options };
6985
+ }
6822
6986
  resolveDataByPath(path) {
6823
6987
  if (!path) return this.page.data;
6824
6988
  const segments = path.split(".").filter(Boolean);
@@ -6827,8 +6991,8 @@ var HeadlessTestingPageHandle = class {
6827
6991
  return current;
6828
6992
  }
6829
6993
  async pollUntil(check, errorMessage, options = {}) {
6830
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT$1)) : DEFAULT_WAIT_TIMEOUT$1;
6831
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL$1)) : DEFAULT_WAIT_INTERVAL$1;
6994
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT)) : DEFAULT_WAIT_TIMEOUT;
6995
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL)) : DEFAULT_WAIT_INTERVAL;
6832
6996
  const deadline = Date.now() + timeout;
6833
6997
  while (true) {
6834
6998
  const result = await check();
@@ -6842,9 +7006,15 @@ var HeadlessTestingPageHandle = class {
6842
7006
  return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
6843
7007
  }
6844
7008
  async callMethod(methodName, ...args) {
6845
- const method = this.page[methodName];
6846
- if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${this.page.route}.`);
6847
- return await method.apply(this.page, args);
7009
+ return await this.callMethodWithOptions(methodName, {}, ...args);
7010
+ }
7011
+ async callMethodWithOptions(methodName, options = {}, ...args) {
7012
+ const normalizedMethodName = normalizeNonEmptyInput(methodName, "Page method name");
7013
+ return await runWithTimeout(async () => {
7014
+ const method = this.page[normalizedMethodName];
7015
+ if (typeof method !== "function") throw new TypeError(`Method "${normalizedMethodName}" does not exist on headless page ${this.page.route}.`);
7016
+ return await method.apply(this.page, args);
7017
+ }, options.timeout, `Timed out calling page method "${normalizedMethodName}" in headless testing runtime.`);
6848
7018
  }
6849
7019
  async data(path) {
6850
7020
  return this.resolveDataByPath(path);
@@ -6946,18 +7116,11 @@ var HeadlessTestingPageHandle = class {
6946
7116
  }
6947
7117
  };
6948
7118
  //#endregion
6949
- //#region src/testing/sessionHandle.ts
6950
- const LEADING_SLASH_RE = /^\/+/;
6951
- const DEFAULT_WAIT_TIMEOUT = 1e3;
6952
- const DEFAULT_WAIT_INTERVAL = 10;
6953
- function normalizeRoute(route) {
6954
- return route.replace(LEADING_SLASH_RE, "");
6955
- }
6956
- function resolvePageScopeId(scopeId) {
6957
- const pagePathIndex = scopeId.indexOf("/page/");
6958
- return pagePathIndex >= 0 ? scopeId.slice(0, pagePathIndex) : scopeId;
6959
- }
7119
+ //#region src/testing/sessionHandle/scope.ts
6960
7120
  var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
7121
+ scopeId;
7122
+ project;
7123
+ session;
6961
7124
  constructor(scopeId, project, session) {
6962
7125
  this.scopeId = scopeId;
6963
7126
  this.project = project;
@@ -6968,8 +7131,7 @@ var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
6968
7131
  return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
6969
7132
  }
6970
7133
  async callMethod(methodName, ...args) {
6971
- const normalizedMethodName = methodName.trim();
6972
- if (!normalizedMethodName) throw new Error("Method name must be a non-empty string in headless testing runtime.");
7134
+ const normalizedMethodName = normalizeNonEmptyInput(methodName, "Method name");
6973
7135
  return this.session.callScopeMethodDirect(this.scopeId, normalizedMethodName, ...args);
6974
7136
  }
6975
7137
  async snapshot() {
@@ -6986,75 +7148,39 @@ var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
6986
7148
  return this.createScopeHandle(this.session.selectOwnerComponent(this.scopeId));
6987
7149
  }
6988
7150
  async waitForOwnerComponent(options = {}) {
6989
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
6990
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
6991
- const deadline = Date.now() + timeout;
6992
- while (true) {
6993
- const owner = await this.ownerComponent();
6994
- if (owner) return owner;
6995
- if (Date.now() >= deadline) throw new Error("Timed out waiting for owner component in headless testing runtime.");
6996
- await new Promise((resolve) => setTimeout(resolve, interval));
6997
- }
7151
+ return await pollUntil(async () => await this.ownerComponent(), "Timed out waiting for owner component in headless testing runtime.", options);
6998
7152
  }
6999
7153
  async selectComponent(selector) {
7000
- const normalizedSelector = selector.trim();
7001
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7154
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7002
7155
  const component = this.session.selectComponentWithin(this.scopeId, normalizedSelector);
7003
7156
  return this.createScopeHandle(component);
7004
7157
  }
7005
7158
  async selectAllComponents(selector) {
7006
- const normalizedSelector = selector.trim();
7007
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7159
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7008
7160
  return this.session.selectAllComponentsWithin(this.scopeId, normalizedSelector).map((component) => this.createScopeHandle(component)).filter((handle) => Boolean(handle));
7009
7161
  }
7010
7162
  async waitForComponent(selector, options = {}) {
7011
- const normalizedSelector = selector.trim();
7012
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7013
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
7014
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
7015
- const deadline = Date.now() + timeout;
7016
- while (true) {
7017
- const component = await this.selectComponent(normalizedSelector);
7018
- if (component) return component;
7019
- if (Date.now() >= deadline) throw new Error(`Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`);
7020
- await new Promise((resolve) => setTimeout(resolve, interval));
7021
- }
7163
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7164
+ return await pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
7022
7165
  }
7023
7166
  async waitForComponents(selector, count = 1, options = {}) {
7024
- const normalizedSelector = selector.trim();
7025
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7167
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7026
7168
  const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
7027
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
7028
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
7029
- const deadline = Date.now() + timeout;
7030
- while (true) {
7169
+ return await pollUntil(async () => {
7031
7170
  const components = await this.selectAllComponents(normalizedSelector);
7032
- if (components.length >= normalizedCount) return components;
7033
- if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`);
7034
- await new Promise((resolve) => setTimeout(resolve, interval));
7035
- }
7171
+ return components.length >= normalizedCount ? components : null;
7172
+ }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
7036
7173
  }
7037
7174
  };
7175
+ //#endregion
7176
+ //#region src/testing/sessionHandle/index.ts
7038
7177
  var HeadlessTestingSessionHandle = class {
7178
+ project;
7179
+ session;
7039
7180
  constructor(project, session) {
7040
7181
  this.project = project;
7041
7182
  this.session = session;
7042
7183
  }
7043
- async waitFor(ms = 0) {
7044
- if (ms <= 0) return;
7045
- await new Promise((resolve) => setTimeout(resolve, ms));
7046
- }
7047
- async pollUntil(check, errorMessage, options = {}) {
7048
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT)) : DEFAULT_WAIT_TIMEOUT;
7049
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL)) : DEFAULT_WAIT_INTERVAL;
7050
- const deadline = Date.now() + timeout;
7051
- while (true) {
7052
- const result = await check();
7053
- if (result != null) return result;
7054
- if (Date.now() >= deadline) throw new Error(errorMessage);
7055
- await this.waitFor(interval);
7056
- }
7057
- }
7058
7184
  async close() {}
7059
7185
  async currentPage() {
7060
7186
  const current = this.session.getCurrentPages().at(-1);
@@ -7063,45 +7189,49 @@ var HeadlessTestingSessionHandle = class {
7063
7189
  async getCurrentPages() {
7064
7190
  return this.session.getCurrentPages().map((page) => new HeadlessTestingPageHandle(this.project, page, this.session));
7065
7191
  }
7192
+ async callWxMethod(methodName, ...args) {
7193
+ return await this.callWxMethodWithOptions(methodName, {}, ...args);
7194
+ }
7195
+ async callWxMethodWithOptions(methodName, options = {}, ...args) {
7196
+ const normalizedMethodName = normalizeNonEmptyInput(methodName, "wx method name");
7197
+ return await runWithTimeout(() => this.session.callWxMethod(normalizedMethodName, ...args), options.timeout, `Timed out calling wx.${normalizedMethodName} in headless testing runtime.`);
7198
+ }
7066
7199
  async scopeSnapshot(scopeId) {
7067
- const normalizedScopeId = scopeId.trim();
7068
- if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in headless testing runtime.");
7200
+ const normalizedScopeId = normalizeNonEmptyInput(scopeId, "Scope id");
7069
7201
  return this.session.getScopeSnapshot(normalizedScopeId);
7070
7202
  }
7071
7203
  async selectComponent(selector) {
7072
- const normalizedSelector = selector.trim();
7073
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7204
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7074
7205
  const component = this.session.selectComponent(normalizedSelector);
7075
7206
  const scopeId = this.session.getScopeIdForComponent(component);
7076
7207
  return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
7077
7208
  }
7078
7209
  async selectAllComponents(selector) {
7079
- const normalizedSelector = selector.trim();
7080
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7210
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7081
7211
  return this.session.selectAllComponents(normalizedSelector).map((component) => this.session.getScopeIdForComponent(component)).filter((scopeId) => Boolean(scopeId)).map((scopeId) => new HeadlessTestingScopeHandle(scopeId, this.project, this.session));
7082
7212
  }
7083
7213
  async waitForComponent(selector, options = {}) {
7084
- const normalizedSelector = selector.trim();
7085
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7086
- return await this.pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
7214
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7215
+ return await pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
7087
7216
  }
7088
7217
  async waitForComponents(selector, count = 1, options = {}) {
7089
- const normalizedSelector = selector.trim();
7090
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7218
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7091
7219
  const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
7092
- return await this.pollUntil(async () => {
7220
+ return await pollUntil(async () => {
7093
7221
  const components = await this.selectAllComponents(normalizedSelector);
7094
7222
  return components.length >= normalizedCount ? components : null;
7095
7223
  }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
7096
7224
  }
7097
7225
  async reLaunch(route) {
7098
- const page = this.session.reLaunch(route);
7226
+ this.session.callWxMethod("reLaunch", { url: route });
7227
+ const page = this.session.getCurrentPages().at(-1);
7228
+ if (!page) throw new Error(`Failed to reLaunch route "${route}" through the headless wx runtime.`);
7099
7229
  return new HeadlessTestingPageHandle(this.project, page, this.session);
7100
7230
  }
7101
7231
  async waitForCurrentPage(route, options = {}) {
7102
7232
  const normalizedRoute = route?.trim();
7103
7233
  if (normalizedRoute != null && !normalizedRoute) throw new Error("Route must be a non-empty string in headless testing runtime.");
7104
- return await this.pollUntil(async () => {
7234
+ return await pollUntil(async () => {
7105
7235
  const currentPageInstance = this.session.getCurrentPages().at(-1);
7106
7236
  if (!currentPageInstance) return null;
7107
7237
  const current = new HeadlessTestingPageHandle(this.project, currentPageInstance, this.session);