@mpcore/simulator 0.1.4 → 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 +207 -166
  2. package/dist/index.mjs +482 -354
  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",
@@ -3230,6 +3296,8 @@ function resolveComponentScopeId(scopeId) {
3230
3296
  return scopeId;
3231
3297
  }
3232
3298
  var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
3299
+ node;
3300
+ interactions;
3233
3301
  constructor(node, interactions) {
3234
3302
  this.node = node;
3235
3303
  this.interactions = interactions;
@@ -4912,6 +4980,7 @@ var BrowserHeadlessSession = class {
4912
4980
  const pageInstance = this.createFreshPage(target);
4913
4981
  this.pages.push(pageInstance);
4914
4982
  this.currentPageInstance = pageInstance;
4983
+ this.runInitialPageLifecycles(pageInstance, target.query);
4915
4984
  return pageInstance;
4916
4985
  }
4917
4986
  navigateTo(url) {
@@ -4924,6 +4993,7 @@ var BrowserHeadlessSession = class {
4924
4993
  const pageInstance = this.createFreshPage(target);
4925
4994
  this.pages.push(pageInstance);
4926
4995
  this.currentPageInstance = pageInstance;
4996
+ this.runInitialPageLifecycles(pageInstance, target.query);
4927
4997
  return pageInstance;
4928
4998
  }
4929
4999
  redirectTo(url) {
@@ -4938,6 +5008,7 @@ var BrowserHeadlessSession = class {
4938
5008
  const pageInstance = this.createFreshPage(target);
4939
5009
  this.pages.push(pageInstance);
4940
5010
  this.currentPageInstance = pageInstance;
5011
+ this.runInitialPageLifecycles(pageInstance, target.query);
4941
5012
  return pageInstance;
4942
5013
  }
4943
5014
  navigateBack(delta = 1) {
@@ -4974,17 +5045,21 @@ var BrowserHeadlessSession = class {
4974
5045
  this.unloadPage(page);
4975
5046
  }
4976
5047
  let nextPage = cachedTarget;
5048
+ let shouldRunInitialLifecycles = false;
4977
5049
  if (!nextPage) {
4978
5050
  nextPage = this.createFreshPage(target);
4979
5051
  this.tabPages.set(target.routeRecord.route, nextPage);
4980
- } else if (current !== nextPage) {
4981
- nextPage.onShow?.();
4982
- this.runPageComponentLifetime(nextPage.route, "show");
5052
+ shouldRunInitialLifecycles = true;
4983
5053
  }
4984
- nextPage.onTabItemTap?.(tabItem);
4985
5054
  this.pages.length = 0;
4986
5055
  this.pages.push(nextPage);
4987
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);
4988
5063
  return nextPage;
4989
5064
  }
4990
5065
  pageScrollTo(option) {
@@ -5086,12 +5161,14 @@ var BrowserHeadlessSession = class {
5086
5161
  pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
5087
5162
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
5088
5163
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
5089
- pageInstance.onLoad?.(target.query);
5090
- pageInstance.onShow?.();
5091
- pageInstance.onReady?.();
5092
5164
  if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
5093
5165
  return pageInstance;
5094
5166
  }
5167
+ runInitialPageLifecycles(pageInstance, query) {
5168
+ pageInstance.onLoad?.(query);
5169
+ pageInstance.onShow?.();
5170
+ pageInstance.onReady?.();
5171
+ }
5095
5172
  isTabBarRoute(route) {
5096
5173
  return this.tabBarRoutes.has(stripLeadingSlash$1(route));
5097
5174
  }
@@ -5127,7 +5204,7 @@ var BrowserHeadlessSession = class {
5127
5204
  return item;
5128
5205
  }
5129
5206
  unloadAllPages() {
5130
- const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
5207
+ const pagesToUnload = /* @__PURE__ */ new Set([...this.pages, ...this.tabPages.values()]);
5131
5208
  for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
5132
5209
  this.pages.length = 0;
5133
5210
  this.tabPages.clear();
@@ -5338,9 +5415,11 @@ function loadProject(projectPath) {
5338
5415
  });
5339
5416
  }
5340
5417
  //#endregion
5341
- //#region src/runtime/render.ts
5342
- const LEADING_SLASH_RE$2 = /^\/+/;
5418
+ //#region src/runtime/render/shared.ts
5343
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 = /^\/+/;
5344
5423
  const EVENT_BINDING_ATTRS = [
5345
5424
  "bindtap",
5346
5425
  "bind:tap",
@@ -5362,9 +5441,7 @@ const STRUCTURAL_ATTRS = [
5362
5441
  "wx:for-index",
5363
5442
  "wx:key"
5364
5443
  ];
5365
- const WX_ELSE_ATTRS = new Set(["wx:elif", "wx:else"]);
5366
- const DATASET_NAME_RE = /-([a-z])/g;
5367
- const BRACKET_INDEX_RE = /\[(\d+)\]/g;
5444
+ const WX_ELSE_ATTRS = /* @__PURE__ */ new Set(["wx:elif", "wx:else"]);
5368
5445
  const CLASS_SPLIT_RE = /\s+/;
5369
5446
  const JS_FILE_RE = /\.js$/;
5370
5447
  function isMustacheOnly(value) {
@@ -5472,21 +5549,46 @@ function resolveComponentAttributeValue(value, scope) {
5472
5549
  }
5473
5550
  return interpolateTemplate(value, scope.data);
5474
5551
  }
5475
- function resolveUsingComponents(ownerJsonPath, ownerFilePath) {
5476
- try {
5477
- const usingComponents = JSON.parse(fs.readFileSync(ownerJsonPath, "utf8")).usingComponents;
5478
- if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
5479
- const resolved = /* @__PURE__ */ new Map();
5480
- for (const [alias, rawPath] of Object.entries(usingComponents)) {
5481
- if (typeof rawPath !== "string") continue;
5482
- const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$2, "") : path.posix.normalize(path.posix.join(path.posix.dirname(ownerFilePath), rawPath));
5483
- 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;
5484
5564
  }
5485
- return resolved;
5486
- } catch {
5487
- return /* @__PURE__ */ new Map();
5565
+ node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
5488
5566
  }
5489
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
5490
5592
  function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias) {
5491
5593
  const componentBasePath = resolveUsingComponents(ownerJsonPath, ownerFilePath).get(alias);
5492
5594
  if (!componentBasePath) return null;
@@ -5501,6 +5603,21 @@ function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, al
5501
5603
  absoluteTemplatePath
5502
5604
  };
5503
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
+ }
5504
5621
  function collectComponentEventBindings(hostNode) {
5505
5622
  const eventBindings = /* @__PURE__ */ new Map();
5506
5623
  for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
@@ -5551,22 +5668,6 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
5551
5668
  }
5552
5669
  };
5553
5670
  }
5554
- function applyNodeBindings(node, scope) {
5555
- if (!isTagNode(node)) {
5556
- if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate(node.data, scope.data);
5557
- return;
5558
- }
5559
- node.attribs ??= {};
5560
- node.attribs["data-sim-scope"] = scope.getScopeId();
5561
- for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
5562
- for (const [key, value] of Object.entries({ ...node.attribs })) {
5563
- if (EVENT_BINDING_ATTRS.includes(key)) {
5564
- node.attribs["data-sim-tap"] = value;
5565
- continue;
5566
- }
5567
- node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
5568
- }
5569
- }
5570
5671
  function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
5571
5672
  const changedRootKeys = [];
5572
5673
  const previousProperties = {};
@@ -5589,31 +5690,62 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
5589
5690
  if (changedRootKeys.length === 0) return;
5590
5691
  runComponentObservers(definition, instance, changedRootKeys, previousProperties);
5591
5692
  }
5592
- function createMergedScopeData(pageData, componentProperties, componentData) {
5693
+ function createComponentScope(clonedNode, scope, componentScopeId, componentInstance) {
5694
+ const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
5593
5695
  return {
5594
- ...pageData,
5595
- ...componentProperties,
5596
- ...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
5597
5710
  };
5598
5711
  }
5599
- function isTruthy(value) {
5600
- return Boolean(value);
5601
- }
5602
- 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
+ }
5603
5720
  return {
5604
- ...scope,
5605
- data: {
5606
- ...scope.data,
5607
- [indexName]: index,
5608
- [itemName]: item
5609
- }
5721
+ nextProperties,
5722
+ bindingExpressions
5610
5723
  };
5611
5724
  }
5612
- function evaluateConditionalBranch(node, scope) {
5613
- const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
5614
- if (condition == null) return true;
5615
- 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);
5616
5746
  }
5747
+ //#endregion
5748
+ //#region src/runtime/render/index.ts
5617
5749
  function expandNodeByFor(node, scope) {
5618
5750
  const forExpression = node.attribs?.["wx:for"];
5619
5751
  if (!forExpression) return [{
@@ -5683,51 +5815,14 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
5683
5815
  if (componentEntry) {
5684
5816
  const componentScopeId = `${instancePath}/${clonedNode.name}`;
5685
5817
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
5686
- const nextProperties = {};
5687
- const bindingExpressions = {};
5688
- for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
5689
- if (key.startsWith("bind")) continue;
5690
- if (isMustacheOnly(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
5691
- nextProperties[key] = resolveComponentAttributeValue(String(value), scope);
5692
- }
5818
+ const { nextProperties, bindingExpressions } = resolveComponentProperties(clonedNode, scope);
5693
5819
  let componentInstance = context.componentCache.get(componentScopeId);
5694
- if (!componentInstance) {
5695
- componentInstance = createComponentInstance({
5696
- definition: componentEntry.definition,
5697
- properties: nextProperties,
5698
- triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
5699
- });
5700
- componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
5701
- componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
5702
- componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
5703
- componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
5704
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
5705
- runComponentLifecycle(componentInstance, "created");
5706
- runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
5707
- componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
5708
- runComponentLifecycle(componentInstance, "attached");
5709
- context.componentCache.set(componentScopeId, componentInstance);
5710
- } 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);
5711
5822
  seenComponentScopes.add(componentScopeId);
5712
- const componentScope = {
5713
- alias: clonedNode.name,
5714
- classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
5715
- data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
5716
- dataset: collectDataset(clonedNode),
5717
- eventBindings: collectComponentEventBindings(clonedNode),
5718
- getMethod: (methodName) => {
5719
- const method = componentInstance?.[methodName];
5720
- return typeof method === "function" ? method : void 0;
5721
- },
5722
- getScopeId: () => componentScopeId,
5723
- hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
5724
- id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
5725
- listenerScopeId: scope.getScopeId(),
5726
- ownerScopeId
5727
- };
5823
+ const componentScope = createComponentScope(clonedNode, scope, componentScopeId, componentInstance);
5728
5824
  context.componentScopes.set(componentScopeId, componentScope);
5729
- const componentDocument = parseTemplateDocument(readTemplateSource(componentEntry.absoluteTemplatePath));
5730
- 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);
5731
5826
  if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
5732
5827
  if (!componentInstance.__ready__) {
5733
5828
  runComponentLifecycle(componentInstance, "ready");
@@ -5865,7 +5960,8 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
5865
5960
  const definition = registries.components.get(id);
5866
5961
  if (!definition) throw new Error(`Component() was not registered for id "${id}" while executing ${normalize(filePath)}.`);
5867
5962
  return definition;
5868
- }
5963
+ },
5964
+ wx: executionContext.wx
5869
5965
  };
5870
5966
  }
5871
5967
  //#endregion
@@ -6086,6 +6182,11 @@ var HeadlessSession = class {
6086
6182
  getCurrentPages() {
6087
6183
  return this.pages.slice();
6088
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
+ }
6089
6190
  getCurrentPageNavigationBarTitle() {
6090
6191
  return this.currentPageInstance?.__navigationBarTitle__ ?? null;
6091
6192
  }
@@ -6454,6 +6555,7 @@ var HeadlessSession = class {
6454
6555
  const pageInstance = this.createFreshPage(target);
6455
6556
  this.pages.push(pageInstance);
6456
6557
  this.currentPageInstance = pageInstance;
6558
+ this.runInitialPageLifecycles(pageInstance, target.query);
6457
6559
  return pageInstance;
6458
6560
  }
6459
6561
  navigateTo(url) {
@@ -6466,6 +6568,7 @@ var HeadlessSession = class {
6466
6568
  const pageInstance = this.createFreshPage(target);
6467
6569
  this.pages.push(pageInstance);
6468
6570
  this.currentPageInstance = pageInstance;
6571
+ this.runInitialPageLifecycles(pageInstance, target.query);
6469
6572
  return pageInstance;
6470
6573
  }
6471
6574
  redirectTo(url) {
@@ -6480,6 +6583,7 @@ var HeadlessSession = class {
6480
6583
  const pageInstance = this.createFreshPage(target);
6481
6584
  this.pages.push(pageInstance);
6482
6585
  this.currentPageInstance = pageInstance;
6586
+ this.runInitialPageLifecycles(pageInstance, target.query);
6483
6587
  return pageInstance;
6484
6588
  }
6485
6589
  navigateBack(delta = 1) {
@@ -6516,17 +6620,21 @@ var HeadlessSession = class {
6516
6620
  this.unloadPage(page);
6517
6621
  }
6518
6622
  let nextPage = cachedTarget;
6623
+ let shouldRunInitialLifecycles = false;
6519
6624
  if (!nextPage) {
6520
6625
  nextPage = this.createFreshPage(target);
6521
6626
  this.tabPages.set(target.routeRecord.route, nextPage);
6522
- } else if (current !== nextPage) {
6523
- nextPage.onShow?.();
6524
- this.runPageComponentLifetime(nextPage.route, "show");
6627
+ shouldRunInitialLifecycles = true;
6525
6628
  }
6526
- nextPage.onTabItemTap?.(tabItem);
6527
6629
  this.pages.length = 0;
6528
6630
  this.pages.push(nextPage);
6529
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);
6530
6638
  return nextPage;
6531
6639
  }
6532
6640
  pageScrollTo(option) {
@@ -6601,12 +6709,14 @@ var HeadlessSession = class {
6601
6709
  pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
6602
6710
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
6603
6711
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
6604
- pageInstance.onLoad?.(target.query);
6605
- pageInstance.onShow?.();
6606
- pageInstance.onReady?.();
6607
6712
  if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
6608
6713
  return pageInstance;
6609
6714
  }
6715
+ runInitialPageLifecycles(pageInstance, query) {
6716
+ pageInstance.onLoad?.(query);
6717
+ pageInstance.onShow?.();
6718
+ pageInstance.onReady?.();
6719
+ }
6610
6720
  isTabBarRoute(route) {
6611
6721
  return this.tabBarRoutes.has(stripLeadingSlash(route));
6612
6722
  }
@@ -6642,7 +6752,7 @@ var HeadlessSession = class {
6642
6752
  };
6643
6753
  }
6644
6754
  unloadAllPages() {
6645
- const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
6755
+ const pagesToUnload = /* @__PURE__ */ new Set([...this.pages, ...this.tabPages.values()]);
6646
6756
  for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
6647
6757
  this.pages.length = 0;
6648
6758
  this.tabPages.clear();
@@ -6812,15 +6922,67 @@ function createHeadlessSession(options) {
6812
6922
  return new HeadlessSession(options);
6813
6923
  }
6814
6924
  //#endregion
6815
- //#region src/testing/pageHandle.ts
6925
+ //#region src/testing/sessionHandle/shared.ts
6926
+ const LEADING_SLASH_RE = /^\/+/;
6816
6927
  const DEFAULT_WAIT_TIMEOUT$1 = 1e3;
6817
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;
6818
6971
  var HeadlessTestingPageHandle = class {
6972
+ project;
6973
+ page;
6974
+ session;
6819
6975
  constructor(project, page, session) {
6820
6976
  this.project = project;
6821
6977
  this.page = page;
6822
6978
  this.session = session;
6823
6979
  }
6980
+ get path() {
6981
+ return this.page.route;
6982
+ }
6983
+ get query() {
6984
+ return { ...this.page.options };
6985
+ }
6824
6986
  resolveDataByPath(path) {
6825
6987
  if (!path) return this.page.data;
6826
6988
  const segments = path.split(".").filter(Boolean);
@@ -6829,8 +6991,8 @@ var HeadlessTestingPageHandle = class {
6829
6991
  return current;
6830
6992
  }
6831
6993
  async pollUntil(check, errorMessage, options = {}) {
6832
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT$1)) : DEFAULT_WAIT_TIMEOUT$1;
6833
- 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;
6834
6996
  const deadline = Date.now() + timeout;
6835
6997
  while (true) {
6836
6998
  const result = await check();
@@ -6844,9 +7006,15 @@ var HeadlessTestingPageHandle = class {
6844
7006
  return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
6845
7007
  }
6846
7008
  async callMethod(methodName, ...args) {
6847
- const method = this.page[methodName];
6848
- if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${this.page.route}.`);
6849
- 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.`);
6850
7018
  }
6851
7019
  async data(path) {
6852
7020
  return this.resolveDataByPath(path);
@@ -6948,18 +7116,11 @@ var HeadlessTestingPageHandle = class {
6948
7116
  }
6949
7117
  };
6950
7118
  //#endregion
6951
- //#region src/testing/sessionHandle.ts
6952
- const LEADING_SLASH_RE = /^\/+/;
6953
- const DEFAULT_WAIT_TIMEOUT = 1e3;
6954
- const DEFAULT_WAIT_INTERVAL = 10;
6955
- function normalizeRoute(route) {
6956
- return route.replace(LEADING_SLASH_RE, "");
6957
- }
6958
- function resolvePageScopeId(scopeId) {
6959
- const pagePathIndex = scopeId.indexOf("/page/");
6960
- return pagePathIndex >= 0 ? scopeId.slice(0, pagePathIndex) : scopeId;
6961
- }
7119
+ //#region src/testing/sessionHandle/scope.ts
6962
7120
  var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
7121
+ scopeId;
7122
+ project;
7123
+ session;
6963
7124
  constructor(scopeId, project, session) {
6964
7125
  this.scopeId = scopeId;
6965
7126
  this.project = project;
@@ -6970,8 +7131,7 @@ var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
6970
7131
  return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
6971
7132
  }
6972
7133
  async callMethod(methodName, ...args) {
6973
- const normalizedMethodName = methodName.trim();
6974
- if (!normalizedMethodName) throw new Error("Method name must be a non-empty string in headless testing runtime.");
7134
+ const normalizedMethodName = normalizeNonEmptyInput(methodName, "Method name");
6975
7135
  return this.session.callScopeMethodDirect(this.scopeId, normalizedMethodName, ...args);
6976
7136
  }
6977
7137
  async snapshot() {
@@ -6988,75 +7148,39 @@ var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
6988
7148
  return this.createScopeHandle(this.session.selectOwnerComponent(this.scopeId));
6989
7149
  }
6990
7150
  async waitForOwnerComponent(options = {}) {
6991
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
6992
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
6993
- const deadline = Date.now() + timeout;
6994
- while (true) {
6995
- const owner = await this.ownerComponent();
6996
- if (owner) return owner;
6997
- if (Date.now() >= deadline) throw new Error("Timed out waiting for owner component in headless testing runtime.");
6998
- await new Promise((resolve) => setTimeout(resolve, interval));
6999
- }
7151
+ return await pollUntil(async () => await this.ownerComponent(), "Timed out waiting for owner component in headless testing runtime.", options);
7000
7152
  }
7001
7153
  async selectComponent(selector) {
7002
- const normalizedSelector = selector.trim();
7003
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7154
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7004
7155
  const component = this.session.selectComponentWithin(this.scopeId, normalizedSelector);
7005
7156
  return this.createScopeHandle(component);
7006
7157
  }
7007
7158
  async selectAllComponents(selector) {
7008
- const normalizedSelector = selector.trim();
7009
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7159
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7010
7160
  return this.session.selectAllComponentsWithin(this.scopeId, normalizedSelector).map((component) => this.createScopeHandle(component)).filter((handle) => Boolean(handle));
7011
7161
  }
7012
7162
  async waitForComponent(selector, options = {}) {
7013
- const normalizedSelector = selector.trim();
7014
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7015
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
7016
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
7017
- const deadline = Date.now() + timeout;
7018
- while (true) {
7019
- const component = await this.selectComponent(normalizedSelector);
7020
- if (component) return component;
7021
- if (Date.now() >= deadline) throw new Error(`Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`);
7022
- await new Promise((resolve) => setTimeout(resolve, interval));
7023
- }
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);
7024
7165
  }
7025
7166
  async waitForComponents(selector, count = 1, options = {}) {
7026
- const normalizedSelector = selector.trim();
7027
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7167
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7028
7168
  const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
7029
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
7030
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
7031
- const deadline = Date.now() + timeout;
7032
- while (true) {
7169
+ return await pollUntil(async () => {
7033
7170
  const components = await this.selectAllComponents(normalizedSelector);
7034
- if (components.length >= normalizedCount) return components;
7035
- if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`);
7036
- await new Promise((resolve) => setTimeout(resolve, interval));
7037
- }
7171
+ return components.length >= normalizedCount ? components : null;
7172
+ }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
7038
7173
  }
7039
7174
  };
7175
+ //#endregion
7176
+ //#region src/testing/sessionHandle/index.ts
7040
7177
  var HeadlessTestingSessionHandle = class {
7178
+ project;
7179
+ session;
7041
7180
  constructor(project, session) {
7042
7181
  this.project = project;
7043
7182
  this.session = session;
7044
7183
  }
7045
- async waitFor(ms = 0) {
7046
- if (ms <= 0) return;
7047
- await new Promise((resolve) => setTimeout(resolve, ms));
7048
- }
7049
- async pollUntil(check, errorMessage, options = {}) {
7050
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT)) : DEFAULT_WAIT_TIMEOUT;
7051
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL)) : DEFAULT_WAIT_INTERVAL;
7052
- const deadline = Date.now() + timeout;
7053
- while (true) {
7054
- const result = await check();
7055
- if (result != null) return result;
7056
- if (Date.now() >= deadline) throw new Error(errorMessage);
7057
- await this.waitFor(interval);
7058
- }
7059
- }
7060
7184
  async close() {}
7061
7185
  async currentPage() {
7062
7186
  const current = this.session.getCurrentPages().at(-1);
@@ -7065,45 +7189,49 @@ var HeadlessTestingSessionHandle = class {
7065
7189
  async getCurrentPages() {
7066
7190
  return this.session.getCurrentPages().map((page) => new HeadlessTestingPageHandle(this.project, page, this.session));
7067
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
+ }
7068
7199
  async scopeSnapshot(scopeId) {
7069
- const normalizedScopeId = scopeId.trim();
7070
- if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in headless testing runtime.");
7200
+ const normalizedScopeId = normalizeNonEmptyInput(scopeId, "Scope id");
7071
7201
  return this.session.getScopeSnapshot(normalizedScopeId);
7072
7202
  }
7073
7203
  async selectComponent(selector) {
7074
- const normalizedSelector = selector.trim();
7075
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7204
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7076
7205
  const component = this.session.selectComponent(normalizedSelector);
7077
7206
  const scopeId = this.session.getScopeIdForComponent(component);
7078
7207
  return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
7079
7208
  }
7080
7209
  async selectAllComponents(selector) {
7081
- const normalizedSelector = selector.trim();
7082
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7210
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7083
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));
7084
7212
  }
7085
7213
  async waitForComponent(selector, options = {}) {
7086
- const normalizedSelector = selector.trim();
7087
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7088
- 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);
7089
7216
  }
7090
7217
  async waitForComponents(selector, count = 1, options = {}) {
7091
- const normalizedSelector = selector.trim();
7092
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7218
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7093
7219
  const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
7094
- return await this.pollUntil(async () => {
7220
+ return await pollUntil(async () => {
7095
7221
  const components = await this.selectAllComponents(normalizedSelector);
7096
7222
  return components.length >= normalizedCount ? components : null;
7097
7223
  }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
7098
7224
  }
7099
7225
  async reLaunch(route) {
7100
- 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.`);
7101
7229
  return new HeadlessTestingPageHandle(this.project, page, this.session);
7102
7230
  }
7103
7231
  async waitForCurrentPage(route, options = {}) {
7104
7232
  const normalizedRoute = route?.trim();
7105
7233
  if (normalizedRoute != null && !normalizedRoute) throw new Error("Route must be a non-empty string in headless testing runtime.");
7106
- return await this.pollUntil(async () => {
7234
+ return await pollUntil(async () => {
7107
7235
  const currentPageInstance = this.session.getCurrentPages().at(-1);
7108
7236
  if (!currentPageInstance) return null;
7109
7237
  const current = new HeadlessTestingPageHandle(this.project, currentPageInstance, this.session);