@mpcore/simulator 0.0.2 → 0.0.3

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 +342 -79
  2. package/dist/index.mjs +1739 -623
  3. package/package.json +6 -3
package/dist/index.mjs CHANGED
@@ -1,6 +1,5 @@
1
1
  import { dirname, join, normalize, posix } from "pathe";
2
2
  import { parseDocument } from "htmlparser2";
3
- import { Buffer } from "node:buffer";
4
3
  import fs from "node:fs";
5
4
  import path from "node:path";
6
5
  import process from "node:process";
@@ -63,6 +62,7 @@ function createHeadlessWx(driver) {
63
62
  canIUse: true,
64
63
  clearStorage: true,
65
64
  clearStorageSync: true,
65
+ createSelectorQuery: true,
66
66
  getAppBaseInfo: { return: {
67
67
  SDKVersion: true,
68
68
  enableDebug: true,
@@ -206,6 +206,63 @@ function createHeadlessWx(driver) {
206
206
  return { errMsg: "clearStorage:ok" };
207
207
  }, option),
208
208
  clearStorageSync: () => driver.clearStorageSync(),
209
+ createSelectorQuery: () => {
210
+ const requests = [];
211
+ let scope;
212
+ const callbacks = [];
213
+ let query;
214
+ const createNode = (target, selector, single = true) => ({
215
+ boundingClientRect: (callback) => {
216
+ requests.push({
217
+ fields: {
218
+ rect: true,
219
+ size: true
220
+ },
221
+ selector,
222
+ single,
223
+ target
224
+ });
225
+ if (callback) callbacks.push(callback);
226
+ return query;
227
+ },
228
+ fields: (fields, callback) => {
229
+ requests.push({
230
+ fields: { ...fields },
231
+ selector,
232
+ single,
233
+ target
234
+ });
235
+ if (callback) callbacks.push(callback);
236
+ return query;
237
+ },
238
+ scrollOffset: (callback) => {
239
+ requests.push({
240
+ fields: { scrollOffset: true },
241
+ selector,
242
+ single,
243
+ target
244
+ });
245
+ if (callback) callbacks.push(callback);
246
+ return query;
247
+ }
248
+ });
249
+ query = {
250
+ exec: (callback) => {
251
+ const result = driver.executeSelectorQuery(requests, scope);
252
+ for (const [index, item] of result.entries()) callbacks[index]?.(item);
253
+ callback?.(result);
254
+ return result;
255
+ },
256
+ in: (component) => {
257
+ scope = component;
258
+ return query;
259
+ },
260
+ select: (selector) => createNode("selector", selector, true),
261
+ selectAll: (selector) => createNode("selector", selector, false),
262
+ selectViewport: () => createNode("viewport", void 0, true)
263
+ };
264
+ return query;
265
+ },
209
266
  getEnterOptionsSync: () => driver.getEnterOptionsSync(),
210
267
  getAppBaseInfo: (option) => invokeWxApi(() => driver.getAppBaseInfoSync(), option),
211
268
  getAppBaseInfoSync: () => driver.getAppBaseInfoSync(),
@@ -407,11 +464,11 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
407
464
  }
408
465
  //#endregion
409
466
  //#region src/project/resolveRoutes.ts
410
- const LEADING_SLASH_RE$5 = /^\/+/;
467
+ const LEADING_SLASH_RE$6 = /^\/+/;
411
468
  const TRAILING_SLASH_RE = /\/+$/;
412
469
  const DUPLICATE_SLASH_RE = /\/{2,}/g;
413
470
  function normalizeSegment(value) {
414
- return value.replace(LEADING_SLASH_RE$5, "").replace(TRAILING_SLASH_RE, "");
471
+ return value.replace(LEADING_SLASH_RE$6, "").replace(TRAILING_SLASH_RE, "");
415
472
  }
416
473
  function pushRoute(records, seen, record) {
417
474
  if (!record.route || seen.has(record.route)) return;
@@ -757,21 +814,21 @@ function runComponentPageLifetime(instance, lifetimeName, payload) {
757
814
  }
758
815
  //#endregion
759
816
  //#region src/browser/render.ts
760
- const LEADING_SLASH_RE$4 = /^\/+/;
761
- const TEMPLATE_INTERPOLATION_RE$1 = /\{\{([^{}]+)\}\}/g;
762
- const EVENT_BINDING_ATTRS = [
817
+ const LEADING_SLASH_RE$5 = /^\/+/;
818
+ const TEMPLATE_INTERPOLATION_RE$2 = /\{\{([^{}]+)\}\}/g;
819
+ const EVENT_BINDING_ATTRS$1 = [
763
820
  "bindtap",
764
821
  "bind:tap",
765
822
  "catchtap",
766
823
  "catch:tap"
767
824
  ];
768
- const COMPONENT_EVENT_PREFIXES = [
825
+ const COMPONENT_EVENT_PREFIXES$1 = [
769
826
  "bind:",
770
827
  "bind",
771
828
  "catch:",
772
829
  "catch"
773
830
  ];
774
- const STRUCTURAL_ATTRS = [
831
+ const STRUCTURAL_ATTRS$1 = [
775
832
  "wx:if",
776
833
  "wx:elif",
777
834
  "wx:else",
@@ -780,48 +837,48 @@ const STRUCTURAL_ATTRS = [
780
837
  "wx:for-index",
781
838
  "wx:key"
782
839
  ];
783
- const WX_ELSE_ATTRS = new Set(["wx:elif", "wx:else"]);
784
- const DATASET_NAME_RE$1 = /-([a-z])/g;
785
- const BRACKET_INDEX_RE = /\[(\d+)\]/g;
786
- const CLASS_SPLIT_RE = /\s+/;
787
- const JS_FILE_RE = /\.js$/;
788
- function isMustacheOnly(value) {
840
+ const WX_ELSE_ATTRS$1 = new Set(["wx:elif", "wx:else"]);
841
+ const DATASET_NAME_RE$3 = /-([a-z])/g;
842
+ const BRACKET_INDEX_RE$1 = /\[(\d+)\]/g;
843
+ const CLASS_SPLIT_RE$1 = /\s+/;
844
+ const JS_FILE_RE$1 = /\.js$/;
845
+ function isMustacheOnly$1(value) {
789
846
  const trimmed = value.trim();
790
847
  return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
791
848
  }
792
- function toDatasetKey$1(attributeName) {
793
- return attributeName.slice(5).replace(DATASET_NAME_RE$1, (_match, char) => char.toUpperCase());
849
+ function toDatasetKey$3(attributeName) {
850
+ return attributeName.slice(5).replace(DATASET_NAME_RE$3, (_match, char) => char.toUpperCase());
794
851
  }
795
- function collectDataset$1(node) {
852
+ function collectDataset$3(node) {
796
853
  const dataset = {};
797
854
  for (const [key, value] of Object.entries(node.attribs ?? {})) {
798
855
  if (!key.startsWith("data-") || key === "data-sim-scope" || key === "data-sim-tap" || key === "data-sim-component") continue;
799
- dataset[toDatasetKey$1(key)] = String(value);
856
+ dataset[toDatasetKey$3(key)] = String(value);
800
857
  }
801
858
  return dataset;
802
859
  }
803
- function escapeText$2(text) {
860
+ function escapeText$3(text) {
804
861
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
805
862
  }
806
- function escapeAttribute$2(value) {
807
- return escapeText$2(value).replaceAll("\"", "&quot;");
863
+ function escapeAttribute$3(value) {
864
+ return escapeText$3(value).replaceAll("\"", "&quot;");
808
865
  }
809
- function cloneNode(node) {
866
+ function cloneNode$1(node) {
810
867
  return {
811
868
  ...node,
812
869
  attribs: node.attribs ? { ...node.attribs } : void 0,
813
- children: node.children?.map((child) => cloneNode(child))
870
+ children: node.children?.map((child) => cloneNode$1(child))
814
871
  };
815
872
  }
816
- function parseExpressionSegments(expression) {
817
- return expression.replace(BRACKET_INDEX_RE, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
873
+ function parseExpressionSegments$1(expression) {
874
+ return expression.replace(BRACKET_INDEX_RE$1, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
818
875
  }
819
- function unwrapMustacheExpression(expression) {
876
+ function unwrapMustacheExpression$1(expression) {
820
877
  const normalized = expression.trim();
821
- if (isMustacheOnly(normalized)) return normalized.slice(2, -2).trim();
878
+ if (isMustacheOnly$1(normalized)) return normalized.slice(2, -2).trim();
822
879
  return normalized;
823
880
  }
824
- function resolveLiteralValue(expression) {
881
+ function resolveLiteralValue$1(expression) {
825
882
  if (expression === "true") return true;
826
883
  if (expression === "false") return false;
827
884
  if (expression === "null") return null;
@@ -830,69 +887,69 @@ function resolveLiteralValue(expression) {
830
887
  const numericValue = Number(expression);
831
888
  if (!Number.isNaN(numericValue) && expression !== "") return numericValue;
832
889
  }
833
- function resolveValueByExpression(source, expression) {
834
- const normalized = unwrapMustacheExpression(expression);
890
+ function resolveValueByExpression$1(source, expression) {
891
+ const normalized = unwrapMustacheExpression$1(expression);
835
892
  if (!normalized) return;
836
- if (normalized.startsWith("!")) return !resolveValueByExpression(source, normalized.slice(1));
837
- const literalValue = resolveLiteralValue(normalized);
893
+ if (normalized.startsWith("!")) return !resolveValueByExpression$1(source, normalized.slice(1));
894
+ const literalValue = resolveLiteralValue$1(normalized);
838
895
  if (literalValue !== void 0 || normalized === "undefined") return literalValue;
839
- const segments = parseExpressionSegments(normalized);
896
+ const segments = parseExpressionSegments$1(normalized);
840
897
  let current = source;
841
898
  for (const segment of segments) current = current?.[segment];
842
899
  return current;
843
900
  }
844
- function resolveValueByPath$1(source, expression) {
845
- return resolveValueByExpression(source, expression) ?? "";
901
+ function resolveValueByPath$2(source, expression) {
902
+ return resolveValueByExpression$1(source, expression) ?? "";
846
903
  }
847
- function resolveRawValueByPath(source, expression) {
848
- return resolveValueByExpression(source, expression);
904
+ function resolveRawValueByPath$1(source, expression) {
905
+ return resolveValueByExpression$1(source, expression);
849
906
  }
850
- function interpolateTemplate$1(input, data) {
851
- return input.replace(TEMPLATE_INTERPOLATION_RE$1, (_match, expression) => {
852
- const value = resolveValueByPath$1(data, expression);
907
+ function interpolateTemplate$2(input, data) {
908
+ return input.replace(TEMPLATE_INTERPOLATION_RE$2, (_match, expression) => {
909
+ const value = resolveValueByPath$2(data, expression);
853
910
  return typeof value === "string" ? value : String(value);
854
911
  });
855
912
  }
856
- function readTemplateSource(files, filePath) {
913
+ function readTemplateSource$1(files, filePath) {
857
914
  const templateSource = readBrowserVirtualFile(files, filePath);
858
915
  if (typeof templateSource !== "string") throw new TypeError(`Missing template in browser simulator runtime: ${filePath}`);
859
916
  return templateSource;
860
917
  }
861
- function parseTemplateDocument(templateSource) {
918
+ function parseTemplateDocument$1(templateSource) {
862
919
  return parseDocument(`<page>${templateSource}</page>`, {
863
920
  xmlMode: false,
864
921
  decodeEntities: false,
865
922
  recognizeSelfClosing: true
866
923
  });
867
924
  }
868
- function serializeDomNode$1(node) {
869
- if (node.type === "text") return escapeText$2(node.data ?? "");
870
- if (node.type === "root") return (node.children ?? []).map(serializeDomNode$1).join("");
925
+ function serializeDomNode$2(node) {
926
+ if (node.type === "text") return escapeText$3(node.data ?? "");
927
+ if (node.type === "root") return (node.children ?? []).map(serializeDomNode$2).join("");
871
928
  const tagName = node.name ?? "";
872
- if (!tagName) return (node.children ?? []).map(serializeDomNode$1).join("");
873
- return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$2(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$1).join("")}</${tagName}>`;
929
+ if (!tagName) return (node.children ?? []).map(serializeDomNode$2).join("");
930
+ return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$3(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$2).join("")}</${tagName}>`;
874
931
  }
875
- function isTagNode(node) {
932
+ function isTagNode$1(node) {
876
933
  return node.type === "tag" && typeof node.name === "string";
877
934
  }
878
- function isIgnorableTextNode(node) {
935
+ function isIgnorableTextNode$1(node) {
879
936
  return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
880
937
  }
881
- function resolveAttributeValue(value, scope) {
882
- if (isMustacheOnly(value)) {
938
+ function resolveAttributeValue$1(value, scope) {
939
+ if (isMustacheOnly$1(value)) {
883
940
  const expression = value.trim().slice(2, -2);
884
- return resolveValueByPath$1(scope.data, expression);
941
+ return resolveValueByPath$2(scope.data, expression);
885
942
  }
886
- return interpolateTemplate$1(value, scope.data);
943
+ return interpolateTemplate$2(value, scope.data);
887
944
  }
888
- function resolveComponentAttributeValue(value, scope) {
889
- if (isMustacheOnly(value)) {
945
+ function resolveComponentAttributeValue$1(value, scope) {
946
+ if (isMustacheOnly$1(value)) {
890
947
  const expression = value.trim().slice(2, -2);
891
- return resolveRawValueByPath(scope.data, expression);
948
+ return resolveRawValueByPath$1(scope.data, expression);
892
949
  }
893
- return interpolateTemplate$1(value, scope.data);
950
+ return interpolateTemplate$2(value, scope.data);
894
951
  }
895
- function resolveUsingComponents(files, ownerJsonPath, ownerFilePath) {
952
+ function resolveUsingComponents$1(files, ownerJsonPath, ownerFilePath) {
896
953
  const ownerJson = readBrowserVirtualFile(files, ownerJsonPath);
897
954
  if (typeof ownerJson !== "string") return /* @__PURE__ */ new Map();
898
955
  try {
@@ -901,16 +958,16 @@ function resolveUsingComponents(files, ownerJsonPath, ownerFilePath) {
901
958
  const resolved = /* @__PURE__ */ new Map();
902
959
  for (const [alias, rawPath] of Object.entries(usingComponents)) {
903
960
  if (typeof rawPath !== "string") continue;
904
- const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$4, "") : normalize(join(dirname(ownerFilePath), rawPath));
905
- resolved.set(alias, basePath.replace(LEADING_SLASH_RE$4, ""));
961
+ const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$5, "") : normalize(join(dirname(ownerFilePath), rawPath));
962
+ resolved.set(alias, basePath.replace(LEADING_SLASH_RE$5, ""));
906
963
  }
907
964
  return resolved;
908
965
  } catch {
909
966
  return /* @__PURE__ */ new Map();
910
967
  }
911
968
  }
912
- function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias) {
913
- const componentBasePath = resolveUsingComponents(context.files, ownerJsonPath, ownerFilePath).get(alias);
969
+ function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, alias) {
970
+ const componentBasePath = resolveUsingComponents$1(context.files, ownerJsonPath, ownerFilePath).get(alias);
914
971
  if (!componentBasePath) return null;
915
972
  const filePath = `${componentBasePath}.js`;
916
973
  const templatePath = `${componentBasePath}.wxml`;
@@ -920,10 +977,10 @@ function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, al
920
977
  templatePath
921
978
  };
922
979
  }
923
- function collectComponentEventBindings(hostNode) {
980
+ function collectComponentEventBindings$1(hostNode) {
924
981
  const eventBindings = /* @__PURE__ */ new Map();
925
982
  for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
926
- const matchedPrefix = COMPONENT_EVENT_PREFIXES.find((prefix) => key.startsWith(prefix));
983
+ const matchedPrefix = COMPONENT_EVENT_PREFIXES$1.find((prefix) => key.startsWith(prefix));
927
984
  if (!matchedPrefix) continue;
928
985
  const eventName = key.slice(matchedPrefix.length);
929
986
  if (!eventName) continue;
@@ -934,12 +991,13 @@ function collectComponentEventBindings(hostNode) {
934
991
  }
935
992
  return eventBindings;
936
993
  }
937
- function buildComponentTrigger(componentScopeId, context, hostNode) {
938
- const hostDataset = collectDataset$1(hostNode);
994
+ function buildComponentTrigger$1(componentScopeId, context, hostNode) {
995
+ const hostDataset = collectDataset$3(hostNode);
939
996
  const hostId = hostNode.attribs?.id ?? "";
940
997
  return (instance, eventName, detail, triggerOptions) => {
941
998
  const interactionTarget = instance.__lastInteractionEvent__?.target;
942
999
  const interactionCurrentTarget = instance.__lastInteractionEvent__?.currentTarget;
1000
+ const interactionMark = instance.__lastInteractionEvent__?.mark;
943
1001
  const target = {
944
1002
  dataset: interactionTarget?.dataset ?? hostDataset,
945
1003
  id: interactionTarget?.id ?? hostId
@@ -955,7 +1013,7 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
955
1013
  capturePhase: false,
956
1014
  composed: triggerOptions?.composed ?? false,
957
1015
  detail,
958
- mark: void 0,
1016
+ mark: interactionMark,
959
1017
  target,
960
1018
  type: eventName,
961
1019
  currentTarget: {
@@ -969,23 +1027,23 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
969
1027
  }
970
1028
  };
971
1029
  }
972
- function applyNodeBindings(node, scope) {
973
- if (!isTagNode(node)) {
974
- if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate$1(node.data, scope.data);
1030
+ function applyNodeBindings$1(node, scope) {
1031
+ if (!isTagNode$1(node)) {
1032
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate$2(node.data, scope.data);
975
1033
  return;
976
1034
  }
977
1035
  node.attribs ??= {};
978
1036
  node.attribs["data-sim-scope"] = scope.getScopeId();
979
- for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
1037
+ for (const key of STRUCTURAL_ATTRS$1) delete node.attribs[key];
980
1038
  for (const [key, value] of Object.entries({ ...node.attribs })) {
981
- if (EVENT_BINDING_ATTRS.includes(key)) {
1039
+ if (EVENT_BINDING_ATTRS$1.includes(key)) {
982
1040
  node.attribs["data-sim-tap"] = value;
983
1041
  continue;
984
1042
  }
985
- node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
1043
+ node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue$1(value, scope)) : String(value);
986
1044
  }
987
1045
  }
988
- function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
1046
+ function syncComponentProperties$1(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
989
1047
  const changedRootKeys = [];
990
1048
  const previousProperties = {};
991
1049
  for (const [key, value] of Object.entries(nextProperties)) {
@@ -1007,17 +1065,17 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
1007
1065
  if (changedRootKeys.length === 0) return;
1008
1066
  runComponentObservers(definition, instance, changedRootKeys, previousProperties);
1009
1067
  }
1010
- function createMergedScopeData(pageData, componentProperties, componentData) {
1068
+ function createMergedScopeData$1(pageData, componentProperties, componentData) {
1011
1069
  return {
1012
1070
  ...pageData,
1013
1071
  ...componentProperties,
1014
1072
  ...componentData
1015
1073
  };
1016
1074
  }
1017
- function isTruthy(value) {
1075
+ function isTruthy$1(value) {
1018
1076
  return Boolean(value);
1019
1077
  }
1020
- function createLoopScope(scope, itemName, indexName, item, index) {
1078
+ function createLoopScope$1(scope, itemName, indexName, item, index) {
1021
1079
  return {
1022
1080
  ...scope,
1023
1081
  data: {
@@ -1027,37 +1085,37 @@ function createLoopScope(scope, itemName, indexName, item, index) {
1027
1085
  }
1028
1086
  };
1029
1087
  }
1030
- function evaluateConditionalBranch(node, scope) {
1088
+ function evaluateConditionalBranch$1(node, scope) {
1031
1089
  const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
1032
1090
  if (condition == null) return true;
1033
- return isTruthy(resolveRawValueByPath(scope.data, condition));
1091
+ return isTruthy$1(resolveRawValueByPath$1(scope.data, condition));
1034
1092
  }
1035
- function expandNodeByFor(node, scope) {
1093
+ function expandNodeByFor$1(node, scope) {
1036
1094
  const forExpression = node.attribs?.["wx:for"];
1037
1095
  if (!forExpression) return [{
1038
1096
  node,
1039
1097
  scope,
1040
1098
  instanceSuffix: ""
1041
1099
  }];
1042
- const list = resolveRawValueByPath(scope.data, forExpression);
1100
+ const list = resolveRawValueByPath$1(scope.data, forExpression);
1043
1101
  const items = Array.isArray(list) ? list : [];
1044
1102
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
1045
1103
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
1046
1104
  return items.map((item, index) => ({
1047
- node: cloneNode(node),
1048
- scope: createLoopScope(scope, itemName, indexName, item, index),
1105
+ node: cloneNode$1(node),
1106
+ scope: createLoopScope$1(scope, itemName, indexName, item, index),
1049
1107
  instanceSuffix: `:for-${index}`
1050
1108
  }));
1051
1109
  }
1052
- function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1053
- return expandNodeByFor(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes));
1110
+ function renderNodeVariants$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1111
+ return expandNodeByFor$1(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree$1(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes));
1054
1112
  }
1055
- function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1113
+ function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1056
1114
  const renderedChildren = [];
1057
1115
  for (let index = 0; index < children.length; index += 1) {
1058
1116
  const child = children[index];
1059
- if (!isTagNode(child)) {
1060
- renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
1117
+ if (!isTagNode$1(child)) {
1118
+ renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
1061
1119
  continue;
1062
1120
  }
1063
1121
  const hasConditional = child.attribs?.["wx:if"] != null;
@@ -1067,37 +1125,37 @@ function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath,
1067
1125
  let cursor = index;
1068
1126
  while (cursor < children.length) {
1069
1127
  const branch = children[cursor];
1070
- if (cursor !== index && isIgnorableTextNode(branch)) {
1128
+ if (cursor !== index && isIgnorableTextNode$1(branch)) {
1071
1129
  cursor += 1;
1072
1130
  continue;
1073
1131
  }
1074
- if (!isTagNode(branch)) break;
1075
- if (cursor !== index && !WX_ELSE_ATTRS.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
1076
- if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch(branch, scope)) {
1077
- renderedChildren.push(...renderNodeVariants(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes));
1132
+ if (!isTagNode$1(branch)) break;
1133
+ if (cursor !== index && !WX_ELSE_ATTRS$1.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
1134
+ if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch$1(branch, scope)) {
1135
+ renderedChildren.push(...renderNodeVariants$1(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes));
1078
1136
  branchMatched = true;
1079
1137
  }
1080
1138
  let nextBranchIndex = cursor + 1;
1081
- while (nextBranchIndex < children.length && isIgnorableTextNode(children[nextBranchIndex])) nextBranchIndex += 1;
1139
+ while (nextBranchIndex < children.length && isIgnorableTextNode$1(children[nextBranchIndex])) nextBranchIndex += 1;
1082
1140
  const nextBranch = children[nextBranchIndex];
1083
- if (!(!!nextBranch && isTagNode(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
1141
+ if (!(!!nextBranch && isTagNode$1(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
1084
1142
  cursor = nextBranchIndex;
1085
1143
  }
1086
1144
  index = cursor;
1087
1145
  continue;
1088
1146
  }
1089
1147
  if (isElseBranch) continue;
1090
- renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
1148
+ renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
1091
1149
  }
1092
1150
  return renderedChildren;
1093
1151
  }
1094
- function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1095
- const clonedNode = cloneNode(node);
1096
- if (!isTagNode(clonedNode)) {
1097
- applyNodeBindings(clonedNode, scope);
1152
+ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1153
+ const clonedNode = cloneNode$1(node);
1154
+ if (!isTagNode$1(clonedNode)) {
1155
+ applyNodeBindings$1(clonedNode, scope);
1098
1156
  return clonedNode;
1099
1157
  }
1100
- const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name);
1158
+ const componentEntry = resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, clonedNode.name);
1101
1159
  if (componentEntry) {
1102
1160
  const componentScopeId = `${instancePath}/${clonedNode.name}`;
1103
1161
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
@@ -1105,15 +1163,15 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
1105
1163
  const bindingExpressions = {};
1106
1164
  for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
1107
1165
  if (key.startsWith("bind")) continue;
1108
- if (isMustacheOnly(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
1109
- nextProperties[key] = resolveComponentAttributeValue(String(value), scope);
1166
+ if (isMustacheOnly$1(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
1167
+ nextProperties[key] = resolveComponentAttributeValue$1(String(value), scope);
1110
1168
  }
1111
1169
  let componentInstance = context.componentCache.get(componentScopeId);
1112
1170
  if (!componentInstance) {
1113
1171
  componentInstance = createComponentInstance({
1114
1172
  definition: componentEntry.definition,
1115
1173
  properties: nextProperties,
1116
- triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
1174
+ triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
1117
1175
  });
1118
1176
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
1119
1177
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
@@ -1124,14 +1182,14 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
1124
1182
  runComponentLifecycle(componentInstance, "attached");
1125
1183
  runComponentPageLifetime(componentInstance, "show");
1126
1184
  context.componentCache.set(componentScopeId, componentInstance);
1127
- } else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
1185
+ } else syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
1128
1186
  seenComponentScopes.add(componentScopeId);
1129
1187
  const componentScope = {
1130
1188
  alias: clonedNode.name,
1131
- classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
1132
- data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
1133
- dataset: collectDataset$1(clonedNode),
1134
- eventBindings: collectComponentEventBindings(clonedNode),
1189
+ classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
1190
+ data: createMergedScopeData$1(scope.data, componentInstance.properties, componentInstance.data),
1191
+ dataset: collectDataset$3(clonedNode),
1192
+ eventBindings: collectComponentEventBindings$1(clonedNode),
1135
1193
  getMethod: (methodName) => {
1136
1194
  const method = componentInstance?.[methodName];
1137
1195
  return typeof method === "function" ? method : void 0;
@@ -1143,8 +1201,8 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
1143
1201
  ownerScopeId
1144
1202
  };
1145
1203
  context.componentScopes.set(componentScopeId, componentScope);
1146
- const componentDocument = parseTemplateDocument(readTemplateSource(context.files, componentEntry.templatePath));
1147
- const renderedComponentRoot = renderNodeTree((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes);
1204
+ const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, componentEntry.templatePath));
1205
+ const renderedComponentRoot = renderNodeTree$1((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes);
1148
1206
  if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
1149
1207
  if (!componentInstance.__ready__) {
1150
1208
  runComponentLifecycle(componentInstance, "ready");
@@ -1152,14 +1210,14 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
1152
1210
  }
1153
1211
  return renderedComponentRoot;
1154
1212
  }
1155
- applyNodeBindings(clonedNode, scope);
1156
- clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
1213
+ applyNodeBindings$1(clonedNode, scope);
1214
+ clonedNode.children = renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
1157
1215
  return clonedNode;
1158
1216
  }
1159
1217
  function renderBrowserPageTree(context, page) {
1160
- const route = page.route.replace(LEADING_SLASH_RE$4, "");
1218
+ const route = page.route.replace(LEADING_SLASH_RE$5, "");
1161
1219
  const templatePath = join(context.project.miniprogramRootPath, `${route}.wxml`);
1162
- const document = parseTemplateDocument(readTemplateSource(context.files, templatePath));
1220
+ const document = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
1163
1221
  const pageScopeId = `page:${route}`;
1164
1222
  const pageScope = {
1165
1223
  data: page.data,
@@ -1173,7 +1231,7 @@ function renderBrowserPageTree(context, page) {
1173
1231
  context.componentScopes.clear();
1174
1232
  context.componentScopes.set(pageScopeId, pageScope);
1175
1233
  const seenComponentScopes = /* @__PURE__ */ new Set();
1176
- const renderedRoot = renderNodeTree((document.children ?? [])[0] ?? document, pageScope, context, `${route}.json`, `${route}.js`, pageScopeId, seenComponentScopes);
1234
+ const renderedRoot = renderNodeTree$1((document.children ?? [])[0] ?? document, pageScope, context, `${route}.json`, `${route}.js`, pageScopeId, seenComponentScopes);
1177
1235
  for (const [scopeId, instance] of [...context.componentCache.entries()]) if (!seenComponentScopes.has(scopeId)) {
1178
1236
  runComponentLifecycle(instance, "detached");
1179
1237
  context.componentCache.delete(scopeId);
@@ -1181,7 +1239,7 @@ function renderBrowserPageTree(context, page) {
1181
1239
  }
1182
1240
  return {
1183
1241
  root: renderedRoot,
1184
- wxml: serializeDomNode$1(renderedRoot)
1242
+ wxml: serializeDomNode$2(renderedRoot)
1185
1243
  };
1186
1244
  }
1187
1245
  //#endregion
@@ -1420,6 +1478,10 @@ const DEFAULT_MODAL_CANCEL_COLOR = "#000000";
1420
1478
  const DEFAULT_MODAL_CANCEL_TEXT = "取消";
1421
1479
  const DEFAULT_MODAL_CONFIRM_COLOR = "#576B95";
1422
1480
  const DEFAULT_MODAL_CONFIRM_TEXT = "确定";
1481
+ const textEncoder = new TextEncoder();
1482
+ function byteLength(input) {
1483
+ return textEncoder.encode(input).byteLength;
1484
+ }
1423
1485
  function cloneShareMenuSnapshot(snapshot) {
1424
1486
  return {
1425
1487
  isUpdatableMessage: snapshot.isUpdatableMessage,
@@ -1526,7 +1588,7 @@ function createHeadlessWxState() {
1526
1588
  getStorageInfoSync() {
1527
1589
  const keys = Array.from(storage.keys()).sort((a, b) => a.localeCompare(b));
1528
1590
  const totalBytes = Array.from(storage.entries()).reduce((sum, [key, value]) => {
1529
- return sum + Buffer.byteLength(JSON.stringify([key, value]));
1591
+ return sum + byteLength(JSON.stringify([key, value]));
1530
1592
  }, 0);
1531
1593
  return {
1532
1594
  currentSize: Math.ceil(totalBytes / 1024),
@@ -1742,81 +1804,494 @@ function createHeadlessWxState() {
1742
1804
  };
1743
1805
  }
1744
1806
  //#endregion
1745
- //#region src/browser/session.ts
1746
- const LEADING_SLASH_RE$3 = /^\/+/;
1747
- const PAGE_STACK_LIMIT$1 = 10;
1748
- const DATA_ATTR_SELECTOR_RE$1 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
1749
- const DATASET_KEY_RE = /-([a-z])/g;
1750
- function stripLeadingSlash$1(route) {
1751
- return route.replace(LEADING_SLASH_RE$3, "");
1807
+ //#region src/view/selectors.ts
1808
+ const WHITESPACE_RE = /\s+/;
1809
+ const DATA_ATTR_SELECTOR_RE$2 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
1810
+ function getClassList(node) {
1811
+ return String(node.attribs?.class ?? "").split(WHITESPACE_RE).map((item) => item.trim()).filter(Boolean);
1752
1812
  }
1753
- function normalizeQuery$1(queryString) {
1754
- const query = new URLSearchParams(queryString);
1755
- const result = {};
1756
- for (const [key, value] of query.entries()) result[key] = value;
1757
- return result;
1813
+ function matchesSimpleSelector(node, selector) {
1814
+ if (node.type !== "tag") return false;
1815
+ if (selector === "page") return node.name === "page";
1816
+ if (selector.startsWith("#")) return node.attribs?.id === selector.slice(1);
1817
+ if (selector.startsWith(".")) return getClassList(node).includes(selector.slice(1));
1818
+ const dataAttrMatch = selector.match(DATA_ATTR_SELECTOR_RE$2);
1819
+ if (dataAttrMatch) {
1820
+ const [, key, value] = dataAttrMatch;
1821
+ return node.attribs?.[`data-${key}`] === value;
1822
+ }
1823
+ return node.name === selector;
1758
1824
  }
1759
- function parseNavigationUrl$1(url) {
1760
- const trimmedUrl = url.trim();
1761
- if (!trimmedUrl) throw new Error("Navigation url must be a non-empty string in browser simulator runtime.");
1762
- const [pathWithHash, queryString = ""] = trimmedUrl.split("?");
1763
- const [pathname] = pathWithHash.split("#");
1825
+ function collectDescendants(node, into) {
1826
+ for (const child of node.children ?? []) {
1827
+ into.push(child);
1828
+ collectDescendants(child, into);
1829
+ }
1830
+ }
1831
+ function querySelectorAll(root, selector) {
1832
+ const parts = selector.trim().split(WHITESPACE_RE).filter(Boolean);
1833
+ if (parts.length === 0) return [];
1834
+ let current = [root];
1835
+ for (const part of parts) {
1836
+ const next = [];
1837
+ for (const node of current) {
1838
+ const candidates = [];
1839
+ if (part === "page" && node.type === "tag" && node.name === "page") candidates.push(node);
1840
+ collectDescendants(node, candidates);
1841
+ for (const candidate of candidates) if (matchesSimpleSelector(candidate, part)) next.push(candidate);
1842
+ }
1843
+ current = next;
1844
+ }
1845
+ return current;
1846
+ }
1847
+ //#endregion
1848
+ //#region src/view/nodeHandle.ts
1849
+ const DATASET_NAME_RE$2 = /-([a-z])/g;
1850
+ function escapeText$2(text) {
1851
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1852
+ }
1853
+ function toDatasetKey$2(attributeName) {
1854
+ return attributeName.slice(5).replace(DATASET_NAME_RE$2, (_match, char) => char.toUpperCase());
1855
+ }
1856
+ function collectDataset$2(node) {
1857
+ const dataset = {};
1858
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
1859
+ if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
1860
+ dataset[toDatasetKey$2(key)] = value;
1861
+ }
1862
+ return dataset;
1863
+ }
1864
+ function resolveEventBinding(node, eventName) {
1865
+ const normalizedEventName = eventName.trim();
1866
+ if (!normalizedEventName) return null;
1867
+ const bindingAttrs = [
1868
+ `bind${normalizedEventName}`,
1869
+ `bind:${normalizedEventName}`,
1870
+ `catch${normalizedEventName}`,
1871
+ `catch:${normalizedEventName}`
1872
+ ];
1873
+ for (const attributeName of bindingAttrs) {
1874
+ const methodName = node.attribs?.[attributeName]?.trim();
1875
+ if (methodName) return methodName;
1876
+ }
1877
+ return null;
1878
+ }
1879
+ function createEventPayload(node, eventName, event) {
1880
+ const dataset = collectDataset$2(node);
1881
+ const nodeId = node.attribs?.id ?? "";
1764
1882
  return {
1765
- pathname: pathname || "",
1766
- query: normalizeQuery$1(queryString)
1883
+ bubbles: false,
1884
+ capturePhase: false,
1885
+ composed: false,
1886
+ currentTarget: {
1887
+ dataset: event.currentTarget?.dataset ?? event.dataset ?? dataset,
1888
+ id: event.currentTarget?.id ?? event.id ?? nodeId
1889
+ },
1890
+ detail: event.detail,
1891
+ mark: event.mark,
1892
+ target: {
1893
+ dataset: event.target?.dataset ?? event.dataset ?? dataset,
1894
+ id: event.target?.id ?? event.id ?? nodeId
1895
+ },
1896
+ type: eventName
1767
1897
  };
1768
1898
  }
1769
- function createAppLaunchOptions$1(pathname, query) {
1899
+ function createValueEventDetail(value, detail) {
1770
1900
  return {
1771
- path: stripLeadingSlash$1(pathname),
1772
- query: { ...query },
1773
- referrerInfo: {
1774
- appId: "",
1775
- extraData: {}
1776
- },
1777
- scene: 1001
1901
+ value,
1902
+ ...detail ?? {}
1778
1903
  };
1779
1904
  }
1780
- function readJsonObject$2(files, filePath) {
1781
- const content = readBrowserVirtualFile(files, filePath);
1782
- if (!content) return;
1783
- try {
1784
- const value = JSON.parse(content);
1785
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1786
- } catch {
1787
- return;
1788
- }
1905
+ function escapeAttribute$2(value) {
1906
+ return escapeText$2(value).replaceAll("\"", "&quot;");
1789
1907
  }
1790
- function resolveNavigationPath$1(targetPath, baseRoute) {
1791
- if (!targetPath) throw new Error("Navigation url must include a pathname in browser simulator runtime.");
1792
- if (targetPath.startsWith("/")) return posix.normalize(targetPath).replace(LEADING_SLASH_RE$3, "");
1793
- if (!baseRoute) throw new Error(`Cannot resolve relative navigation url "${targetPath}" without an active page.`);
1794
- return posix.resolve(`/${posix.dirname(baseRoute)}`, targetPath).replace(LEADING_SLASH_RE$3, "");
1908
+ function serializeNode(node) {
1909
+ if (node.type === "text") return escapeText$2(node.data ?? "");
1910
+ if (node.type !== "tag") return (node.children ?? []).map(serializeNode).join("");
1911
+ if (node.name === "page") return (node.children ?? []).filter((child) => !(child.type === "tag" && (child.name === "import" || child.name === "wxs"))).map(serializeNode).join("");
1912
+ const attrs = Object.entries(node.attribs ?? {}).filter(([key]) => !key.startsWith("data-sim-")).map(([key, value]) => ` ${key}="${escapeAttribute$2(value)}"`).join("");
1913
+ const children = (node.children ?? []).map(serializeNode).join("");
1914
+ return `<${node.name ?? ""}${attrs}>${children}</${node.name ?? ""}>`;
1795
1915
  }
1796
- var BrowserHeadlessSession = class {
1797
- files;
1798
- project;
1799
- appDefinition = null;
1800
- appInstance = null;
1801
- moduleLoader;
1802
- registries;
1803
- currentPageInstance = null;
1804
- pages = [];
1805
- componentCache = /* @__PURE__ */ new Map();
1806
- componentScopes = /* @__PURE__ */ new Map();
1807
- tabBarRoutes;
1808
- tabPages = /* @__PURE__ */ new Map();
1809
- tabBarItems = /* @__PURE__ */ new Map();
1810
- tabBarState = /* @__PURE__ */ new Map();
1811
- tabBarVisible = false;
1812
- systemInfo = createDefaultSystemInfo();
1813
- enterOptions = createAppLaunchOptions$1("", {});
1814
- launchOptions = createAppLaunchOptions$1("", {});
1815
- wxState = createHeadlessWxState();
1816
- constructor(options) {
1817
- this.files = options.files;
1818
- this.project = options.project ?? createBrowserProject(options.files);
1819
- this.registries = createHostRegistries();
1916
+ function collectText(node) {
1917
+ if (node.type === "text") return node.data ?? "";
1918
+ return (node.children ?? []).map(collectText).join("");
1919
+ }
1920
+ function resolvePageScopeId$1(scopeId) {
1921
+ if (!scopeId) return null;
1922
+ const pagePathIndex = scopeId.indexOf("/page/");
1923
+ return pagePathIndex >= 0 ? scopeId.slice(0, pagePathIndex) : scopeId;
1924
+ }
1925
+ function resolveComponentScopeId(scopeId) {
1926
+ if (!scopeId || !scopeId.includes("/")) return null;
1927
+ return scopeId;
1928
+ }
1929
+ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
1930
+ constructor(node, interactions) {
1931
+ this.node = node;
1932
+ this.interactions = interactions;
1933
+ }
1934
+ async $(selector) {
1935
+ const match = querySelectorAll(this.node, selector)[0];
1936
+ return match ? new HeadlessTestingNodeHandle(match, this.interactions) : null;
1937
+ }
1938
+ async $$(selector) {
1939
+ return querySelectorAll(this.node, selector).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
1940
+ }
1941
+ async attr(name) {
1942
+ return this.node.attribs?.[name];
1943
+ }
1944
+ async dataset() {
1945
+ return collectDataset$2(this.node);
1946
+ }
1947
+ async scope() {
1948
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
1949
+ return this.interactions.createScopeHandle(this.node.attribs?.["data-sim-scope"] ?? null);
1950
+ }
1951
+ async componentScope() {
1952
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
1953
+ return this.interactions.createScopeHandle(resolveComponentScopeId(this.node.attribs?.["data-sim-scope"] ?? null));
1954
+ }
1955
+ async pageScope() {
1956
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
1957
+ return this.interactions.createScopeHandle(resolvePageScopeId$1(this.node.attribs?.["data-sim-scope"] ?? null));
1958
+ }
1959
+ async page() {
1960
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
1961
+ return this.interactions.createPageHandle();
1962
+ }
1963
+ async ownerComponentScope() {
1964
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
1965
+ const scopeId = resolveComponentScopeId(this.node.attribs?.["data-sim-scope"] ?? null);
1966
+ return this.interactions.createScopeHandle(this.interactions.ownerScopeId(scopeId));
1967
+ }
1968
+ async text() {
1969
+ return collectText(this.node);
1970
+ }
1971
+ async trigger(eventName, event = {}) {
1972
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
1973
+ const normalizedEventName = eventName.trim();
1974
+ if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
1975
+ const methodName = resolveEventBinding(this.node, normalizedEventName);
1976
+ if (!methodName) throw new Error(`No ${normalizedEventName} binding was found on <${this.node.name ?? "unknown"}> in headless testing runtime.`);
1977
+ return await this.interactions.callMethod(this.node.attribs?.["data-sim-scope"] ?? null, methodName, createEventPayload(this.node, normalizedEventName, event));
1978
+ }
1979
+ async tap(event = {}) {
1980
+ return await this.trigger("tap", event);
1981
+ }
1982
+ async input(value, event = {}) {
1983
+ return await this.trigger("input", {
1984
+ ...event,
1985
+ detail: createValueEventDetail(value, event.detail)
1986
+ });
1987
+ }
1988
+ async change(value, event = {}) {
1989
+ return await this.trigger("change", {
1990
+ ...event,
1991
+ detail: createValueEventDetail(value, event.detail)
1992
+ });
1993
+ }
1994
+ async blur(value, event = {}) {
1995
+ return await this.trigger("blur", {
1996
+ ...event,
1997
+ detail: value == null ? event.detail : createValueEventDetail(value, event.detail)
1998
+ });
1999
+ }
2000
+ async wxml() {
2001
+ return serializeNode(this.node);
2002
+ }
2003
+ };
2004
+ //#endregion
2005
+ //#region src/view/render.ts
2006
+ const LEADING_SLASH_RE$4 = /^\/+/;
2007
+ const TEMPLATE_INTERPOLATION_RE$1 = /\{\{([^{}]+)\}\}/g;
2008
+ function resolveValueByPath$1(source, expression) {
2009
+ const normalized = expression.trim();
2010
+ if (!normalized) return "";
2011
+ const segments = normalized.split(".").filter(Boolean);
2012
+ let current = source;
2013
+ for (const segment of segments) current = current?.[segment];
2014
+ return current ?? "";
2015
+ }
2016
+ function interpolateTemplate$1(input, data) {
2017
+ return input.replace(TEMPLATE_INTERPOLATION_RE$1, (_match, expression) => {
2018
+ const value = resolveValueByPath$1(data, expression);
2019
+ return typeof value === "string" ? value : String(value);
2020
+ });
2021
+ }
2022
+ function visitDom(node, visitor) {
2023
+ visitor(node);
2024
+ for (const child of node.children ?? []) visitDom(child, visitor);
2025
+ }
2026
+ function interpolateDomTree(root, data) {
2027
+ visitDom(root, (node) => {
2028
+ if (typeof node.data === "string") node.data = interpolateTemplate$1(node.data, data);
2029
+ if (node.attribs) for (const [key, value] of Object.entries(node.attribs)) node.attribs[key] = interpolateTemplate$1(value, data);
2030
+ });
2031
+ }
2032
+ function escapeText$1(text) {
2033
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
2034
+ }
2035
+ function escapeAttribute$1(value) {
2036
+ return escapeText$1(value).replaceAll("\"", "&quot;");
2037
+ }
2038
+ function serializeDomNode$1(node) {
2039
+ if (node.type === "text") return escapeText$1(node.data ?? "");
2040
+ if (node.type === "root") return (node.children ?? []).map(serializeDomNode$1).join("");
2041
+ const tagName = node.name ?? "";
2042
+ if (!tagName) return (node.children ?? []).map(serializeDomNode$1).join("");
2043
+ return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$1(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$1).join("")}</${tagName}>`;
2044
+ }
2045
+ function renderPageTree(project, page) {
2046
+ const route = page.route.replace(LEADING_SLASH_RE$4, "");
2047
+ const templatePath = path.resolve(project.miniprogramRootPath, `${route}.wxml`);
2048
+ const document = parseDocument(`<page>${fs.readFileSync(templatePath, "utf8")}</page>`, {
2049
+ xmlMode: false,
2050
+ decodeEntities: false,
2051
+ recognizeSelfClosing: true
2052
+ });
2053
+ interpolateDomTree(document, page.data);
2054
+ return {
2055
+ root: document,
2056
+ wxml: serializeDomNode$1((document.children ?? [])[0] ?? document)
2057
+ };
2058
+ }
2059
+ //#endregion
2060
+ //#region src/view/selectorQuery.ts
2061
+ const DATASET_NAME_RE$1 = /-([a-z])/g;
2062
+ const LEADING_MARK_PREFIX_RE = /^mark[:\-]?/;
2063
+ const MARK_NAME_RE = /[:\-]([a-z])/g;
2064
+ const NUMERIC_LIKE_VALUE_RE = /-?\d+(?:\.\d+)?/;
2065
+ function toDatasetKey$1(attributeName) {
2066
+ return attributeName.slice(5).replace(DATASET_NAME_RE$1, (_match, char) => char.toUpperCase());
2067
+ }
2068
+ function collectDataset$1(node) {
2069
+ const dataset = {};
2070
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
2071
+ if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
2072
+ dataset[toDatasetKey$1(key)] = value;
2073
+ }
2074
+ return dataset;
2075
+ }
2076
+ function toMarkKey(attributeName) {
2077
+ return attributeName.replace(LEADING_MARK_PREFIX_RE, "").replace(MARK_NAME_RE, (_match, char) => char.toUpperCase());
2078
+ }
2079
+ function collectMark(node) {
2080
+ const mark = {};
2081
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
2082
+ if (!(key.startsWith("mark:") || key.startsWith("mark-"))) continue;
2083
+ mark[toMarkKey(key)] = value;
2084
+ }
2085
+ return mark;
2086
+ }
2087
+ function createScopedRoot(node) {
2088
+ return {
2089
+ children: [node],
2090
+ type: "root"
2091
+ };
2092
+ }
2093
+ function findNodeByScopeId(root, scopeId) {
2094
+ if (root.attribs?.["data-sim-scope"] === scopeId) return root;
2095
+ for (const child of root.children ?? []) {
2096
+ const match = findNodeByScopeId(child, scopeId);
2097
+ if (match) return match;
2098
+ }
2099
+ return null;
2100
+ }
2101
+ function parseStyleDeclarations(styleValue) {
2102
+ const declarations = {};
2103
+ if (!styleValue) return declarations;
2104
+ for (const declaration of styleValue.split(";")) {
2105
+ const [rawProperty, ...rawValueParts] = declaration.split(":");
2106
+ const property = rawProperty?.trim();
2107
+ if (!property) continue;
2108
+ declarations[property] = rawValueParts.join(":").trim();
2109
+ }
2110
+ return declarations;
2111
+ }
2112
+ function parseNumericLikeValue(value) {
2113
+ if (!value) return 0;
2114
+ const match = value.match(NUMERIC_LIKE_VALUE_RE);
2115
+ return match ? Number(match[0]) : 0;
2116
+ }
2117
+ function resolveRect(node) {
2118
+ const style = parseStyleDeclarations(node.attribs?.style);
2119
+ const left = parseNumericLikeValue(node.attribs?.["data-sim-left"] ?? style.left);
2120
+ const top = parseNumericLikeValue(node.attribs?.["data-sim-top"] ?? style.top);
2121
+ const width = parseNumericLikeValue(node.attribs?.["data-sim-width"] ?? style.width);
2122
+ const height = parseNumericLikeValue(node.attribs?.["data-sim-height"] ?? style.height);
2123
+ return {
2124
+ bottom: top + height,
2125
+ height,
2126
+ left,
2127
+ right: left + width,
2128
+ top,
2129
+ width
2130
+ };
2131
+ }
2132
+ function resolveScrollOffset(node) {
2133
+ return {
2134
+ scrollLeft: parseNumericLikeValue(node.attribs?.["data-sim-scroll-left"]),
2135
+ scrollTop: parseNumericLikeValue(node.attribs?.["data-sim-scroll-top"])
2136
+ };
2137
+ }
2138
+ function resolvePropertyValue(node, propertyName) {
2139
+ const normalizedPropertyName = propertyName.trim();
2140
+ if (!normalizedPropertyName) return;
2141
+ if (normalizedPropertyName === "id") return node.attribs?.id ?? "";
2142
+ if (normalizedPropertyName === "class") return node.attribs?.class ?? "";
2143
+ if (normalizedPropertyName === "dataset") return collectDataset$1(node);
2144
+ return node.attribs?.[normalizedPropertyName];
2145
+ }
2146
+ function pickProperties(node, propertyNames) {
2147
+ const result = {};
2148
+ for (const propertyName of propertyNames) result[propertyName] = resolvePropertyValue(node, propertyName);
2149
+ return result;
2150
+ }
2151
+ function pickComputedStyle(node, propertyNames) {
2152
+ const style = parseStyleDeclarations(node.attribs?.style);
2153
+ const result = {};
2154
+ for (const propertyName of propertyNames) result[propertyName] = style[propertyName] ?? "";
2155
+ return result;
2156
+ }
2157
+ function resolveFieldsResult(node, fields, _options) {
2158
+ const result = {};
2159
+ if (fields.id) result.id = node.attribs?.id ?? "";
2160
+ if (fields.dataset) result.dataset = collectDataset$1(node);
2161
+ if (fields.mark) result.mark = collectMark(node);
2162
+ if (fields.rect || fields.size) {
2163
+ const rect = resolveRect(node);
2164
+ if (fields.rect) Object.assign(result, rect);
2165
+ if (fields.size) {
2166
+ result.width = rect.width;
2167
+ result.height = rect.height;
2168
+ }
2169
+ }
2170
+ if (fields.scrollOffset) Object.assign(result, resolveScrollOffset(node));
2171
+ if (Array.isArray(fields.properties) && fields.properties.length > 0) Object.assign(result, pickProperties(node, fields.properties));
2172
+ if (Array.isArray(fields.computedStyle) && fields.computedStyle.length > 0) Object.assign(result, pickComputedStyle(node, fields.computedStyle));
2173
+ if (fields.context) result.context = { type: "unsupported-context" };
2174
+ if (fields.node) result.node = { type: node.name ?? "unknown" };
2175
+ return result;
2176
+ }
2177
+ function resolveViewportResult(fields, options) {
2178
+ const result = {};
2179
+ if (fields.rect || fields.size) {
2180
+ const rect = {
2181
+ bottom: options.windowInfo.windowHeight,
2182
+ height: options.windowInfo.windowHeight,
2183
+ left: 0,
2184
+ right: options.windowInfo.windowWidth,
2185
+ top: 0,
2186
+ width: options.windowInfo.windowWidth
2187
+ };
2188
+ if (fields.rect) Object.assign(result, rect);
2189
+ if (fields.size) {
2190
+ result.width = rect.width;
2191
+ result.height = rect.height;
2192
+ }
2193
+ }
2194
+ if (fields.scrollOffset) {
2195
+ result.scrollLeft = 0;
2196
+ result.scrollTop = options.page.__scrollTop__ ?? 0;
2197
+ }
2198
+ return result;
2199
+ }
2200
+ function resolveRequestResult(request, options) {
2201
+ if (request.target === "viewport") return resolveViewportResult(request.fields, options);
2202
+ const matches = querySelectorAll(options.root, request.selector ?? "");
2203
+ if (!request.single) return matches.map((node) => resolveFieldsResult(node, request.fields, options));
2204
+ const match = matches[0];
2205
+ return match ? resolveFieldsResult(match, request.fields, options) : null;
2206
+ }
2207
+ function executeSelectorQueryRequests(requests, options) {
2208
+ return requests.map((request) => resolveRequestResult(request, options));
2209
+ }
2210
+ function resolveSelectorQueryScopeRoot(root, scopeId) {
2211
+ if (!scopeId) return root;
2212
+ const scopedNode = findNodeByScopeId(root, scopeId);
2213
+ return scopedNode ? createScopedRoot(scopedNode) : root;
2214
+ }
2215
+ //#endregion
2216
+ //#region src/browser/session.ts
2217
+ const LEADING_SLASH_RE$3 = /^\/+/;
2218
+ const PAGE_STACK_LIMIT$1 = 10;
2219
+ const DATA_ATTR_SELECTOR_RE$1 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
2220
+ const DATASET_KEY_RE$1 = /-([a-z])/g;
2221
+ function stripLeadingSlash$1(route) {
2222
+ return route.replace(LEADING_SLASH_RE$3, "");
2223
+ }
2224
+ function normalizeQuery$1(queryString) {
2225
+ const query = new URLSearchParams(queryString);
2226
+ const result = {};
2227
+ for (const [key, value] of query.entries()) result[key] = value;
2228
+ return result;
2229
+ }
2230
+ function parseNavigationUrl$1(url) {
2231
+ const trimmedUrl = url.trim();
2232
+ if (!trimmedUrl) throw new Error("Navigation url must be a non-empty string in browser simulator runtime.");
2233
+ const [pathWithHash, queryString = ""] = trimmedUrl.split("?");
2234
+ const [pathname] = pathWithHash.split("#");
2235
+ return {
2236
+ pathname: pathname || "",
2237
+ query: normalizeQuery$1(queryString)
2238
+ };
2239
+ }
2240
+ function createAppLaunchOptions$1(pathname, query) {
2241
+ return {
2242
+ path: stripLeadingSlash$1(pathname),
2243
+ query: { ...query },
2244
+ referrerInfo: {
2245
+ appId: "",
2246
+ extraData: {}
2247
+ },
2248
+ scene: 1001
2249
+ };
2250
+ }
2251
+ function readJsonObject$2(files, filePath) {
2252
+ const content = readBrowserVirtualFile(files, filePath);
2253
+ if (!content) return;
2254
+ try {
2255
+ const value = JSON.parse(content);
2256
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2257
+ } catch {
2258
+ return;
2259
+ }
2260
+ }
2261
+ function resolveNavigationPath$1(targetPath, baseRoute) {
2262
+ if (!targetPath) throw new Error("Navigation url must include a pathname in browser simulator runtime.");
2263
+ if (targetPath.startsWith("/")) return posix.normalize(targetPath).replace(LEADING_SLASH_RE$3, "");
2264
+ if (!baseRoute) throw new Error(`Cannot resolve relative navigation url "${targetPath}" without an active page.`);
2265
+ return posix.resolve(`/${posix.dirname(baseRoute)}`, targetPath).replace(LEADING_SLASH_RE$3, "");
2266
+ }
2267
+ var BrowserHeadlessSession = class {
2268
+ files;
2269
+ project;
2270
+ appDefinition = null;
2271
+ appInstance = null;
2272
+ moduleLoader;
2273
+ registries;
2274
+ currentPageInstance = null;
2275
+ pages = [];
2276
+ componentCache = /* @__PURE__ */ new Map();
2277
+ componentScopes = /* @__PURE__ */ new Map();
2278
+ tabBarRoutes;
2279
+ tabPages = /* @__PURE__ */ new Map();
2280
+ tabBarItems = /* @__PURE__ */ new Map();
2281
+ tabBarState = /* @__PURE__ */ new Map();
2282
+ tabBarVisible = false;
2283
+ systemInfo = createDefaultSystemInfo();
2284
+ enterOptions = createAppLaunchOptions$1("", {});
2285
+ launchOptions = createAppLaunchOptions$1("", {});
2286
+ wxState = createHeadlessWxState();
2287
+ pullDownRefreshState = {
2288
+ active: false,
2289
+ stopCalls: 0
2290
+ };
2291
+ constructor(options) {
2292
+ this.files = options.files;
2293
+ this.project = options.project ?? createBrowserProject(options.files);
2294
+ this.registries = createHostRegistries();
1820
2295
  const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
1821
2296
  this.tabBarRoutes = /* @__PURE__ */ new Set();
1822
2297
  rawTabBarList.forEach((item, index) => {
@@ -1839,6 +2314,7 @@ var BrowserHeadlessSession = class {
1839
2314
  });
1840
2315
  this.tabBarVisible = this.tabBarRoutes.size > 0;
1841
2316
  this.moduleLoader = createBrowserModuleLoader(this.files, this.registries, () => this.pages.slice(), () => this.getApp(), {
2317
+ executeSelectorQuery: (requests, scope) => this.executeSelectorQuery(requests, scope),
1842
2318
  getEnterOptionsSync: () => ({
1843
2319
  ...this.enterOptions,
1844
2320
  query: { ...this.enterOptions.query },
@@ -1946,6 +2422,9 @@ var BrowserHeadlessSession = class {
1946
2422
  getStorageInfo() {
1947
2423
  return this.wxState.getStorageInfoSync();
1948
2424
  }
2425
+ getPullDownRefreshState() {
2426
+ return { ...this.pullDownRefreshState };
2427
+ }
1949
2428
  getSystemInfo() {
1950
2429
  return { ...this.systemInfo };
1951
2430
  }
@@ -2139,6 +2618,10 @@ var BrowserHeadlessSession = class {
2139
2618
  type: "scope"
2140
2619
  };
2141
2620
  }
2621
+ getScopeIdForComponent(component) {
2622
+ if (!component) return null;
2623
+ return this.getComponentScopeId(component);
2624
+ }
2142
2625
  selectComponent(selector) {
2143
2626
  return this.selectComponentsWithin(null, selector)[0] ?? null;
2144
2627
  }
@@ -2168,7 +2651,7 @@ var BrowserHeadlessSession = class {
2168
2651
  const dataAttrMatch = normalizedSelector.match(DATA_ATTR_SELECTOR_RE$1);
2169
2652
  if (dataAttrMatch) {
2170
2653
  const [, key, value] = dataAttrMatch;
2171
- const datasetKey = key.replace(DATASET_KEY_RE, (_match, char) => char.toUpperCase());
2654
+ const datasetKey = key.replace(DATASET_KEY_RE$1, (_match, char) => char.toUpperCase());
2172
2655
  return scope.dataset?.[datasetKey] === value;
2173
2656
  }
2174
2657
  return scope.alias === normalizedSelector;
@@ -2192,10 +2675,44 @@ var BrowserHeadlessSession = class {
2192
2675
  current.__lastChangedKeys__ = [];
2193
2676
  return rendered;
2194
2677
  }
2195
- callTapBinding(scopeId, methodName) {
2196
- const scope = this.componentScopes.get(scopeId);
2197
- if (!scope) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
2198
- const method = scope.getMethod(methodName);
2678
+ callScopeMethod(scopeId, methodName, event) {
2679
+ const current = this.requireCurrentPage(`scope method "${methodName}"`);
2680
+ this.renderCurrentPage();
2681
+ if (!scopeId || scopeId === `page:${stripLeadingSlash$1(current.route)}`) {
2682
+ const method = current[methodName];
2683
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator page ${current.route}.`);
2684
+ return method.call(current, event);
2685
+ }
2686
+ const instance = this.componentCache.get(scopeId);
2687
+ if (!instance) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
2688
+ instance.__lastInteractionEvent__ = {
2689
+ currentTarget: event.currentTarget,
2690
+ mark: event.mark,
2691
+ target: event.target
2692
+ };
2693
+ const method = instance[methodName];
2694
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator component scope "${scopeId}".`);
2695
+ return method.call(instance, event);
2696
+ }
2697
+ callScopeMethodDirect(scopeId, methodName, ...args) {
2698
+ const normalizedScopeId = scopeId.trim();
2699
+ if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in browser simulator runtime.");
2700
+ const current = this.requireCurrentPage(`scope method "${methodName}"`);
2701
+ if (normalizedScopeId === `page:${stripLeadingSlash$1(current.route)}`) {
2702
+ const method = current[methodName];
2703
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator page ${current.route}.`);
2704
+ return method.apply(current, args);
2705
+ }
2706
+ const instance = this.componentCache.get(normalizedScopeId);
2707
+ if (!instance) throw new Error(`Unknown scope "${normalizedScopeId}" in browser simulator runtime.`);
2708
+ const method = instance[methodName];
2709
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator component scope "${normalizedScopeId}".`);
2710
+ return method.apply(instance, args);
2711
+ }
2712
+ callTapBinding(scopeId, methodName) {
2713
+ const scope = this.componentScopes.get(scopeId);
2714
+ if (!scope) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
2715
+ const method = scope.getMethod(methodName);
2199
2716
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on scope "${scopeId}" in browser simulator runtime.`);
2200
2717
  return method();
2201
2718
  }
@@ -2210,6 +2727,7 @@ var BrowserHeadlessSession = class {
2210
2727
  dataset: event.currentTarget?.dataset ?? event.dataset ?? {},
2211
2728
  id: event.currentTarget?.id ?? event.id ?? ""
2212
2729
  },
2730
+ mark: event.mark,
2213
2731
  target: {
2214
2732
  dataset: event.target?.dataset ?? event.dataset ?? {},
2215
2733
  id: event.target?.id ?? event.id ?? ""
@@ -2224,7 +2742,7 @@ var BrowserHeadlessSession = class {
2224
2742
  id: event.currentTarget?.id ?? event.id ?? ""
2225
2743
  },
2226
2744
  detail: void 0,
2227
- mark: void 0,
2745
+ mark: event.mark,
2228
2746
  target: {
2229
2747
  dataset: event.target?.dataset ?? event.dataset ?? {},
2230
2748
  id: event.target?.id ?? event.id ?? ""
@@ -2326,10 +2844,16 @@ var BrowserHeadlessSession = class {
2326
2844
  return nextPage;
2327
2845
  }
2328
2846
  pageScrollTo(option) {
2329
- this.requireCurrentPage("wx.pageScrollTo()").onPageScroll?.({ scrollTop: Number(option.scrollTop ?? 0) });
2847
+ const current = this.requireCurrentPage("wx.pageScrollTo()");
2848
+ current.__scrollTop__ = Number(option.scrollTop ?? 0);
2849
+ current.onPageScroll?.({ scrollTop: current.__scrollTop__ });
2330
2850
  }
2331
2851
  triggerPullDownRefresh() {
2332
2852
  const current = this.requireCurrentPage("triggerPullDownRefresh()");
2853
+ this.pullDownRefreshState = {
2854
+ ...this.pullDownRefreshState,
2855
+ active: true
2856
+ };
2333
2857
  current.onPullDownRefresh?.();
2334
2858
  return current;
2335
2859
  }
@@ -2350,7 +2874,34 @@ var BrowserHeadlessSession = class {
2350
2874
  current.onRouteDone?.(options);
2351
2875
  return current;
2352
2876
  }
2353
- stopPullDownRefresh() {}
2877
+ stopPullDownRefresh() {
2878
+ this.pullDownRefreshState = {
2879
+ active: false,
2880
+ stopCalls: this.pullDownRefreshState.stopCalls + 1
2881
+ };
2882
+ }
2883
+ executeSelectorQuery(requests, scope) {
2884
+ const current = this.requireCurrentPage("wx.createSelectorQuery().exec()");
2885
+ if (scope && scope !== current && !Array.from(this.componentCache.values()).includes(scope)) throw new Error("wx.createSelectorQuery().in(component) received an unknown scope in browser simulator runtime.");
2886
+ const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
2887
+ return executeSelectorQueryRequests(requests, {
2888
+ page: current,
2889
+ root: resolveSelectorQueryScopeRoot(renderBrowserPageTree({
2890
+ changedPageKeys: current.__lastChangedKeys__ ?? [],
2891
+ componentCache: this.componentCache,
2892
+ componentScopes: this.componentScopes,
2893
+ files: this.files,
2894
+ moduleLoader: this.moduleLoader,
2895
+ project: this.project,
2896
+ session: {
2897
+ selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
2898
+ selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
2899
+ selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
2900
+ }
2901
+ }, current).root, scopeId),
2902
+ windowInfo: this.getWindowInfo()
2903
+ });
2904
+ }
2354
2905
  createFreshPage(target) {
2355
2906
  const pageModulePath = join(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
2356
2907
  const pageConfigPath = join(this.project.miniprogramRootPath, `${target.routeRecord.route}.json`);
@@ -2438,6 +2989,10 @@ var BrowserHeadlessSession = class {
2438
2989
  runComponentPageLifetime(instance, lifetimeName, payload);
2439
2990
  }
2440
2991
  }
2992
+ getComponentScopeId(component) {
2993
+ for (const [scopeId, instance] of this.componentCache.entries()) if (instance === component) return scopeId;
2994
+ return null;
2995
+ }
2441
2996
  };
2442
2997
  function createBrowserHeadlessSession(options) {
2443
2998
  return new BrowserHeadlessSession(options);
@@ -2502,153 +3057,594 @@ function loadProject(projectPath) {
2502
3057
  });
2503
3058
  }
2504
3059
  //#endregion
2505
- //#region src/runtime/moduleLoader.ts
2506
- function createRequireNotFoundError(request, importer) {
2507
- return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in headless runtime.`);
2508
- }
2509
- function resolveRequiredModulePath(importer, request) {
2510
- if (!request.startsWith(".")) throw createRequireNotFoundError(request, importer);
2511
- const basePath = path.resolve(path.dirname(importer), request);
2512
- const candidates = [
2513
- basePath,
2514
- `${basePath}.js`,
2515
- `${basePath}.json`,
2516
- path.join(basePath, "index.js")
2517
- ];
2518
- for (const candidate of candidates) if (fs.existsSync(candidate)) return candidate;
2519
- throw createRequireNotFoundError(request, importer);
3060
+ //#region src/runtime/render.ts
3061
+ const LEADING_SLASH_RE$2 = /^\/+/;
3062
+ const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
3063
+ const EVENT_BINDING_ATTRS = [
3064
+ "bindtap",
3065
+ "bind:tap",
3066
+ "catchtap",
3067
+ "catch:tap"
3068
+ ];
3069
+ const COMPONENT_EVENT_PREFIXES = [
3070
+ "bind:",
3071
+ "bind",
3072
+ "catch:",
3073
+ "catch"
3074
+ ];
3075
+ const STRUCTURAL_ATTRS = [
3076
+ "wx:if",
3077
+ "wx:elif",
3078
+ "wx:else",
3079
+ "wx:for",
3080
+ "wx:for-item",
3081
+ "wx:for-index",
3082
+ "wx:key"
3083
+ ];
3084
+ const WX_ELSE_ATTRS = new Set(["wx:elif", "wx:else"]);
3085
+ const DATASET_NAME_RE = /-([a-z])/g;
3086
+ const BRACKET_INDEX_RE = /\[(\d+)\]/g;
3087
+ const CLASS_SPLIT_RE = /\s+/;
3088
+ const JS_FILE_RE = /\.js$/;
3089
+ function isMustacheOnly(value) {
3090
+ const trimmed = value.trim();
3091
+ return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
2520
3092
  }
2521
- function createExecutionContext(registries, getCurrentPages, getApp, wxDriver) {
2522
- const wx = createHeadlessWx(wxDriver);
2523
- return {
2524
- App(definition) {
2525
- return registerAppDefinition(registries, definition);
2526
- },
2527
- Behavior(definition) {
2528
- return {
2529
- ...definition,
2530
- __isHeadlessBehavior__: true
2531
- };
2532
- },
2533
- Component(definition) {
2534
- return registerComponentDefinition(registries, definition);
2535
- },
2536
- Page(definition) {
2537
- return registerPageDefinition(registries, definition);
2538
- },
2539
- console,
2540
- clearTimeout,
2541
- getApp,
2542
- getCurrentPages,
2543
- globalThis: void 0,
2544
- process,
2545
- require: void 0,
2546
- setInterval,
2547
- setTimeout,
2548
- wx
2549
- };
3093
+ function toDatasetKey(attributeName) {
3094
+ return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
2550
3095
  }
2551
- function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
2552
- const moduleCache = /* @__PURE__ */ new Map();
2553
- const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver);
2554
- executionContext.globalThis = executionContext;
2555
- function executeModule(filePath, loadContext) {
2556
- const resolvedPath = path.resolve(filePath);
2557
- const cached = moduleCache.get(resolvedPath);
2558
- if (cached) return cached.exports;
2559
- const source = fs.readFileSync(resolvedPath, "utf8");
2560
- const module = { exports: {} };
2561
- moduleCache.set(resolvedPath, module);
2562
- const previousLoadContext = registries.currentLoadContext;
2563
- registries.currentLoadContext = loadContext;
2564
- const localRequire = (request) => {
2565
- const requiredPath = resolveRequiredModulePath(resolvedPath, request);
2566
- if (requiredPath.endsWith(".json")) {
2567
- const content = fs.readFileSync(requiredPath, "utf8");
2568
- return JSON.parse(content);
2569
- }
2570
- return executeModule(requiredPath, null);
2571
- };
2572
- try {
2573
- new vm.Script(`(function (exports, module, require, __filename, __dirname) { ${source}\n})`, { filename: resolvedPath }).runInNewContext(executionContext)(module.exports, module, localRequire, resolvedPath, path.dirname(resolvedPath));
2574
- return module.exports;
2575
- } finally {
2576
- registries.currentLoadContext = previousLoadContext;
2577
- }
3096
+ function collectDataset(node) {
3097
+ const dataset = {};
3098
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
3099
+ if (!key.startsWith("data-") || key === "data-sim-scope" || key === "data-sim-tap" || key === "data-sim-component") continue;
3100
+ dataset[toDatasetKey(key)] = String(value);
2578
3101
  }
2579
- return {
2580
- executeAppModule(filePath) {
2581
- executeModule(filePath, { kind: "app" });
2582
- if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in headless runtime.`);
2583
- return registries.appDefinition;
2584
- },
2585
- executePageModule(filePath, route) {
2586
- executeModule(filePath, {
2587
- kind: "page",
2588
- route
2589
- });
2590
- const definition = registries.pages.get(route);
2591
- if (!definition) throw new Error(`Page() was not registered for route "${route}" while executing ${normalize(filePath)}.`);
2592
- return definition;
2593
- }
2594
- };
3102
+ return dataset;
2595
3103
  }
2596
- //#endregion
2597
- //#region src/runtime/session.ts
2598
- const LEADING_SLASH_RE$2 = /^\/+/;
2599
- const PAGE_STACK_LIMIT = 10;
2600
- function stripLeadingSlash(route) {
2601
- return route.replace(LEADING_SLASH_RE$2, "");
3104
+ function escapeText(text) {
3105
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
2602
3106
  }
2603
- function normalizeQuery(queryString) {
2604
- const query = new URLSearchParams(queryString);
2605
- const result = {};
2606
- for (const [key, value] of query.entries()) result[key] = value;
2607
- return result;
3107
+ function escapeAttribute(value) {
3108
+ return escapeText(value).replaceAll("\"", "&quot;");
2608
3109
  }
2609
- function parseNavigationUrl(url) {
2610
- const trimmedUrl = url.trim();
2611
- if (!trimmedUrl) throw new Error("Navigation url must be a non-empty string in headless runtime.");
2612
- const [pathWithHash, queryString = ""] = trimmedUrl.split("?");
2613
- const [pathname] = pathWithHash.split("#");
3110
+ function cloneNode(node) {
2614
3111
  return {
2615
- pathname: pathname || "",
2616
- query: normalizeQuery(queryString)
3112
+ ...node,
3113
+ attribs: node.attribs ? { ...node.attribs } : void 0,
3114
+ children: node.children?.map((child) => cloneNode(child))
2617
3115
  };
2618
3116
  }
2619
- function createAppLaunchOptions(pathname, query) {
2620
- return {
2621
- path: stripLeadingSlash(pathname),
2622
- query: { ...query },
2623
- referrerInfo: {
2624
- appId: "",
2625
- extraData: {}
2626
- },
2627
- scene: 1001
2628
- };
3117
+ function parseExpressionSegments(expression) {
3118
+ return expression.replace(BRACKET_INDEX_RE, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
2629
3119
  }
2630
- function readJsonObject(filePath) {
2631
- try {
2632
- const value = JSON.parse(fs.readFileSync(filePath, "utf8"));
2633
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2634
- } catch {
2635
- return;
3120
+ function unwrapMustacheExpression(expression) {
3121
+ const normalized = expression.trim();
3122
+ if (isMustacheOnly(normalized)) return normalized.slice(2, -2).trim();
3123
+ return normalized;
3124
+ }
3125
+ function resolveLiteralValue(expression) {
3126
+ if (expression === "true") return true;
3127
+ if (expression === "false") return false;
3128
+ if (expression === "null") return null;
3129
+ if (expression === "undefined") return;
3130
+ if (expression.startsWith("\"") && expression.endsWith("\"") || expression.startsWith("'") && expression.endsWith("'")) return expression.slice(1, -1);
3131
+ const numericValue = Number(expression);
3132
+ if (!Number.isNaN(numericValue) && expression !== "") return numericValue;
3133
+ }
3134
+ function resolveValueByExpression(source, expression) {
3135
+ const normalized = unwrapMustacheExpression(expression);
3136
+ if (!normalized) return;
3137
+ if (normalized.startsWith("!")) return !resolveValueByExpression(source, normalized.slice(1));
3138
+ const literalValue = resolveLiteralValue(normalized);
3139
+ if (literalValue !== void 0 || normalized === "undefined") return literalValue;
3140
+ const segments = parseExpressionSegments(normalized);
3141
+ let current = source;
3142
+ for (const segment of segments) current = current?.[segment];
3143
+ return current;
3144
+ }
3145
+ function resolveValueByPath(source, expression) {
3146
+ return resolveValueByExpression(source, expression) ?? "";
3147
+ }
3148
+ function resolveRawValueByPath(source, expression) {
3149
+ return resolveValueByExpression(source, expression);
3150
+ }
3151
+ function interpolateTemplate(input, data) {
3152
+ return input.replace(TEMPLATE_INTERPOLATION_RE, (_match, expression) => {
3153
+ const value = resolveValueByPath(data, expression);
3154
+ return typeof value === "string" ? value : String(value);
3155
+ });
3156
+ }
3157
+ function readTemplateSource(filePath) {
3158
+ return fs.readFileSync(filePath, "utf8");
3159
+ }
3160
+ function parseTemplateDocument(templateSource) {
3161
+ return parseDocument(`<page>${templateSource}</page>`, {
3162
+ xmlMode: false,
3163
+ decodeEntities: false,
3164
+ recognizeSelfClosing: true
3165
+ });
3166
+ }
3167
+ function serializeDomNode(node) {
3168
+ if (node.type === "text") return escapeText(node.data ?? "");
3169
+ if (node.type === "root") return (node.children ?? []).map(serializeDomNode).join("");
3170
+ const tagName = node.name ?? "";
3171
+ if (!tagName) return (node.children ?? []).map(serializeDomNode).join("");
3172
+ return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode).join("")}</${tagName}>`;
3173
+ }
3174
+ function isTagNode(node) {
3175
+ return node.type === "tag" && typeof node.name === "string";
3176
+ }
3177
+ function isIgnorableTextNode(node) {
3178
+ return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
3179
+ }
3180
+ function resolveAttributeValue(value, scope) {
3181
+ if (isMustacheOnly(value)) {
3182
+ const expression = value.trim().slice(2, -2);
3183
+ return resolveValueByPath(scope.data, expression);
2636
3184
  }
3185
+ return interpolateTemplate(value, scope.data);
2637
3186
  }
2638
- function resolveNavigationPath(targetPath, baseRoute) {
2639
- if (!targetPath) throw new Error("Navigation url must include a pathname in headless runtime.");
2640
- if (targetPath.startsWith("/")) return path.posix.normalize(targetPath).replace(LEADING_SLASH_RE$2, "");
2641
- if (!baseRoute) throw new Error(`Cannot resolve relative navigation url "${targetPath}" without an active page.`);
2642
- return path.posix.resolve(`/${path.posix.dirname(baseRoute)}`, targetPath).replace(LEADING_SLASH_RE$2, "");
3187
+ function resolveComponentAttributeValue(value, scope) {
3188
+ if (isMustacheOnly(value)) {
3189
+ const expression = value.trim().slice(2, -2);
3190
+ return resolveRawValueByPath(scope.data, expression);
3191
+ }
3192
+ return interpolateTemplate(value, scope.data);
2643
3193
  }
2644
- var HeadlessSession = class {
2645
- project;
2646
- appDefinition = null;
3194
+ function resolveUsingComponents(ownerJsonPath, ownerFilePath) {
3195
+ try {
3196
+ const usingComponents = JSON.parse(fs.readFileSync(ownerJsonPath, "utf8")).usingComponents;
3197
+ if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
3198
+ const resolved = /* @__PURE__ */ new Map();
3199
+ for (const [alias, rawPath] of Object.entries(usingComponents)) {
3200
+ if (typeof rawPath !== "string") continue;
3201
+ const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$2, "") : path.posix.normalize(path.posix.join(path.posix.dirname(ownerFilePath), rawPath));
3202
+ resolved.set(alias, basePath.replace(LEADING_SLASH_RE$2, ""));
3203
+ }
3204
+ return resolved;
3205
+ } catch {
3206
+ return /* @__PURE__ */ new Map();
3207
+ }
3208
+ }
3209
+ function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias) {
3210
+ const componentBasePath = resolveUsingComponents(ownerJsonPath, ownerFilePath).get(alias);
3211
+ if (!componentBasePath) return null;
3212
+ const filePath = `${componentBasePath}.js`;
3213
+ const templatePath = `${componentBasePath}.wxml`;
3214
+ const absoluteFilePath = path.resolve(context.project.miniprogramRootPath, filePath);
3215
+ const absoluteTemplatePath = path.resolve(context.project.miniprogramRootPath, templatePath);
3216
+ return {
3217
+ definition: context.moduleLoader.executeComponentModule(absoluteFilePath, componentBasePath),
3218
+ filePath,
3219
+ templatePath,
3220
+ absoluteTemplatePath
3221
+ };
3222
+ }
3223
+ function collectComponentEventBindings(hostNode) {
3224
+ const eventBindings = /* @__PURE__ */ new Map();
3225
+ for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
3226
+ const matchedPrefix = COMPONENT_EVENT_PREFIXES.find((prefix) => key.startsWith(prefix));
3227
+ if (!matchedPrefix) continue;
3228
+ const eventName = key.slice(matchedPrefix.length);
3229
+ if (!eventName) continue;
3230
+ eventBindings.set(eventName, {
3231
+ method: value,
3232
+ stopAfter: matchedPrefix.startsWith("catch")
3233
+ });
3234
+ }
3235
+ return eventBindings;
3236
+ }
3237
+ function buildComponentTrigger(componentScopeId, context, hostNode) {
3238
+ const hostDataset = collectDataset(hostNode);
3239
+ const hostId = hostNode.attribs?.id ?? "";
3240
+ return (instance, eventName, detail, triggerOptions) => {
3241
+ const interactionTarget = instance.__lastInteractionEvent__?.target;
3242
+ const interactionCurrentTarget = instance.__lastInteractionEvent__?.currentTarget;
3243
+ const interactionMark = instance.__lastInteractionEvent__?.mark;
3244
+ const target = {
3245
+ dataset: interactionTarget?.dataset ?? hostDataset,
3246
+ id: interactionTarget?.id ?? hostId
3247
+ };
3248
+ let currentScopeId = componentScopeId;
3249
+ while (currentScopeId) {
3250
+ const currentScope = context.componentScopes.get(currentScopeId);
3251
+ const binding = currentScope?.eventBindings?.get(eventName);
3252
+ const listenerScope = currentScope?.listenerScopeId ? context.componentScopes.get(currentScope.listenerScopeId) : null;
3253
+ const handler = binding && listenerScope ? listenerScope.getMethod(binding.method) : void 0;
3254
+ if (handler) handler({
3255
+ bubbles: triggerOptions?.bubbles ?? false,
3256
+ capturePhase: false,
3257
+ composed: triggerOptions?.composed ?? false,
3258
+ currentTarget: {
3259
+ dataset: currentScope?.dataset ?? interactionCurrentTarget?.dataset ?? hostDataset,
3260
+ id: currentScope?.hostId ?? interactionCurrentTarget?.id ?? hostId
3261
+ },
3262
+ detail,
3263
+ mark: interactionMark,
3264
+ target,
3265
+ type: eventName
3266
+ });
3267
+ if (binding?.stopAfter) break;
3268
+ if (!triggerOptions?.bubbles || !triggerOptions?.composed) break;
3269
+ currentScopeId = currentScope?.ownerScopeId;
3270
+ }
3271
+ };
3272
+ }
3273
+ function applyNodeBindings(node, scope) {
3274
+ if (!isTagNode(node)) {
3275
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate(node.data, scope.data);
3276
+ return;
3277
+ }
3278
+ node.attribs ??= {};
3279
+ node.attribs["data-sim-scope"] = scope.getScopeId();
3280
+ for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
3281
+ for (const [key, value] of Object.entries({ ...node.attribs })) {
3282
+ if (EVENT_BINDING_ATTRS.includes(key)) {
3283
+ node.attribs["data-sim-tap"] = value;
3284
+ continue;
3285
+ }
3286
+ node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
3287
+ }
3288
+ }
3289
+ function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
3290
+ const changedRootKeys = [];
3291
+ const previousProperties = {};
3292
+ for (const [key, value] of Object.entries(nextProperties)) {
3293
+ const nextValue = normalizeComponentPropertyValue(definition, key, value);
3294
+ const bindingExpression = bindingExpressions[key];
3295
+ const bindingAffected = !!bindingExpression && changedPageKeys.some((changedKey) => {
3296
+ return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
3297
+ });
3298
+ const previousSnapshot = instance.__propertySnapshots?.[key];
3299
+ const deepChanged = bindingAffected && JSON.stringify(previousSnapshot) !== JSON.stringify(nextValue);
3300
+ if (instance.properties[key] !== nextValue || deepChanged) {
3301
+ previousProperties[key] = instance.properties[key];
3302
+ instance.properties[key] = nextValue;
3303
+ changedRootKeys.push(key);
3304
+ }
3305
+ instance.__propertySnapshots ??= {};
3306
+ instance.__propertySnapshots[key] = cloneValue(nextValue);
3307
+ }
3308
+ if (changedRootKeys.length === 0) return;
3309
+ runComponentObservers(definition, instance, changedRootKeys, previousProperties);
3310
+ }
3311
+ function createMergedScopeData(pageData, componentProperties, componentData) {
3312
+ return {
3313
+ ...pageData,
3314
+ ...componentProperties,
3315
+ ...componentData
3316
+ };
3317
+ }
3318
+ function isTruthy(value) {
3319
+ return Boolean(value);
3320
+ }
3321
+ function createLoopScope(scope, itemName, indexName, item, index) {
3322
+ return {
3323
+ ...scope,
3324
+ data: {
3325
+ ...scope.data,
3326
+ [indexName]: index,
3327
+ [itemName]: item
3328
+ }
3329
+ };
3330
+ }
3331
+ function evaluateConditionalBranch(node, scope) {
3332
+ const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
3333
+ if (condition == null) return true;
3334
+ return isTruthy(resolveRawValueByPath(scope.data, condition));
3335
+ }
3336
+ function expandNodeByFor(node, scope) {
3337
+ const forExpression = node.attribs?.["wx:for"];
3338
+ if (!forExpression) return [{
3339
+ node,
3340
+ scope,
3341
+ instanceSuffix: ""
3342
+ }];
3343
+ const list = resolveRawValueByPath(scope.data, forExpression);
3344
+ const items = Array.isArray(list) ? list : [];
3345
+ const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
3346
+ const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
3347
+ return items.map((item, index) => ({
3348
+ node: cloneNode(node),
3349
+ scope: createLoopScope(scope, itemName, indexName, item, index),
3350
+ instanceSuffix: `:for-${index}`
3351
+ }));
3352
+ }
3353
+ function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
3354
+ return expandNodeByFor(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes));
3355
+ }
3356
+ function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
3357
+ const renderedChildren = [];
3358
+ for (let index = 0; index < children.length; index += 1) {
3359
+ const child = children[index];
3360
+ if (!isTagNode(child)) {
3361
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
3362
+ continue;
3363
+ }
3364
+ const hasConditional = child.attribs?.["wx:if"] != null;
3365
+ const isElseBranch = child.attribs?.["wx:elif"] != null || child.attribs?.["wx:else"] != null;
3366
+ if (hasConditional) {
3367
+ let branchMatched = false;
3368
+ let cursor = index;
3369
+ while (cursor < children.length) {
3370
+ const branch = children[cursor];
3371
+ if (cursor !== index && isIgnorableTextNode(branch)) {
3372
+ cursor += 1;
3373
+ continue;
3374
+ }
3375
+ if (!isTagNode(branch)) break;
3376
+ if (cursor !== index && !WX_ELSE_ATTRS.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
3377
+ if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch(branch, scope)) {
3378
+ renderedChildren.push(...renderNodeVariants(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes));
3379
+ branchMatched = true;
3380
+ }
3381
+ let nextBranchIndex = cursor + 1;
3382
+ while (nextBranchIndex < children.length && isIgnorableTextNode(children[nextBranchIndex])) nextBranchIndex += 1;
3383
+ const nextBranch = children[nextBranchIndex];
3384
+ if (!(!!nextBranch && isTagNode(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
3385
+ cursor = nextBranchIndex;
3386
+ }
3387
+ index = cursor;
3388
+ continue;
3389
+ }
3390
+ if (isElseBranch) continue;
3391
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
3392
+ }
3393
+ return renderedChildren;
3394
+ }
3395
+ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
3396
+ const clonedNode = cloneNode(node);
3397
+ if (!isTagNode(clonedNode)) {
3398
+ applyNodeBindings(clonedNode, scope);
3399
+ return clonedNode;
3400
+ }
3401
+ const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name);
3402
+ if (componentEntry) {
3403
+ const componentScopeId = `${instancePath}/${clonedNode.name}`;
3404
+ const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
3405
+ const nextProperties = {};
3406
+ const bindingExpressions = {};
3407
+ for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
3408
+ if (key.startsWith("bind")) continue;
3409
+ if (isMustacheOnly(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
3410
+ nextProperties[key] = resolveComponentAttributeValue(String(value), scope);
3411
+ }
3412
+ let componentInstance = context.componentCache.get(componentScopeId);
3413
+ if (!componentInstance) {
3414
+ componentInstance = createComponentInstance({
3415
+ definition: componentEntry.definition,
3416
+ properties: nextProperties,
3417
+ triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
3418
+ });
3419
+ componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
3420
+ componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
3421
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
3422
+ runComponentLifecycle(componentInstance, "created");
3423
+ runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
3424
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
3425
+ runComponentLifecycle(componentInstance, "attached");
3426
+ context.componentCache.set(componentScopeId, componentInstance);
3427
+ } else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
3428
+ seenComponentScopes.add(componentScopeId);
3429
+ const componentScope = {
3430
+ alias: clonedNode.name,
3431
+ classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
3432
+ data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
3433
+ dataset: collectDataset(clonedNode),
3434
+ eventBindings: collectComponentEventBindings(clonedNode),
3435
+ getMethod: (methodName) => {
3436
+ const method = componentInstance?.[methodName];
3437
+ return typeof method === "function" ? method : void 0;
3438
+ },
3439
+ getScopeId: () => componentScopeId,
3440
+ hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
3441
+ id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
3442
+ listenerScopeId: scope.getScopeId(),
3443
+ ownerScopeId
3444
+ };
3445
+ context.componentScopes.set(componentScopeId, componentScope);
3446
+ const componentDocument = parseTemplateDocument(readTemplateSource(componentEntry.absoluteTemplatePath));
3447
+ 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);
3448
+ if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
3449
+ if (!componentInstance.__ready__) {
3450
+ runComponentLifecycle(componentInstance, "ready");
3451
+ componentInstance.__ready__ = true;
3452
+ componentInstance.__definition__?.pageLifetimes?.show?.call(componentInstance);
3453
+ }
3454
+ return renderedComponentRoot;
3455
+ }
3456
+ applyNodeBindings(clonedNode, scope);
3457
+ clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
3458
+ return clonedNode;
3459
+ }
3460
+ function renderRuntimePageTree(context, page) {
3461
+ const route = page.route.replace(LEADING_SLASH_RE$2, "");
3462
+ const document = parseTemplateDocument(readTemplateSource(path.resolve(context.project.miniprogramRootPath, `${route}.wxml`)));
3463
+ const pageScopeId = `page:${route}`;
3464
+ const pageScope = {
3465
+ data: page.data,
3466
+ getMethod: (methodName) => {
3467
+ const method = page[methodName];
3468
+ return typeof method === "function" ? method : void 0;
3469
+ },
3470
+ getScopeId: () => pageScopeId,
3471
+ id: "page-root"
3472
+ };
3473
+ context.componentScopes.clear();
3474
+ context.componentScopes.set(pageScopeId, pageScope);
3475
+ const seenComponentScopes = /* @__PURE__ */ new Set();
3476
+ const renderedRoot = renderNodeTree((document.children ?? [])[0] ?? document, pageScope, context, path.resolve(context.project.miniprogramRootPath, `${route}.json`), `${route}.js`, pageScopeId, seenComponentScopes);
3477
+ for (const [scopeId, instance] of [...context.componentCache.entries()]) if (!seenComponentScopes.has(scopeId)) {
3478
+ runComponentLifecycle(instance, "detached");
3479
+ context.componentCache.delete(scopeId);
3480
+ context.componentScopes.delete(scopeId);
3481
+ }
3482
+ return {
3483
+ root: renderedRoot,
3484
+ wxml: serializeDomNode(renderedRoot)
3485
+ };
3486
+ }
3487
+ //#endregion
3488
+ //#region src/runtime/moduleLoader.ts
3489
+ function createRequireNotFoundError(request, importer) {
3490
+ return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in headless runtime.`);
3491
+ }
3492
+ function resolveRequiredModulePath(importer, request) {
3493
+ if (!request.startsWith(".")) throw createRequireNotFoundError(request, importer);
3494
+ const basePath = path.resolve(path.dirname(importer), request);
3495
+ const candidates = [
3496
+ basePath,
3497
+ `${basePath}.js`,
3498
+ `${basePath}.json`,
3499
+ path.join(basePath, "index.js")
3500
+ ];
3501
+ for (const candidate of candidates) if (fs.existsSync(candidate)) return candidate;
3502
+ throw createRequireNotFoundError(request, importer);
3503
+ }
3504
+ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver) {
3505
+ const wx = createHeadlessWx(wxDriver);
3506
+ return {
3507
+ App(definition) {
3508
+ return registerAppDefinition(registries, definition);
3509
+ },
3510
+ Behavior(definition) {
3511
+ return {
3512
+ ...definition,
3513
+ __isHeadlessBehavior__: true
3514
+ };
3515
+ },
3516
+ Component(definition) {
3517
+ return registerComponentDefinition(registries, definition);
3518
+ },
3519
+ Page(definition) {
3520
+ return registerPageDefinition(registries, definition);
3521
+ },
3522
+ console,
3523
+ clearTimeout,
3524
+ getApp,
3525
+ getCurrentPages,
3526
+ globalThis: void 0,
3527
+ process,
3528
+ require: void 0,
3529
+ setInterval,
3530
+ setTimeout,
3531
+ wx
3532
+ };
3533
+ }
3534
+ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
3535
+ const moduleCache = /* @__PURE__ */ new Map();
3536
+ const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver);
3537
+ executionContext.globalThis = executionContext;
3538
+ function executeModule(filePath, loadContext) {
3539
+ const resolvedPath = path.resolve(filePath);
3540
+ const cached = moduleCache.get(resolvedPath);
3541
+ if (cached) return cached.exports;
3542
+ const source = fs.readFileSync(resolvedPath, "utf8");
3543
+ const module = { exports: {} };
3544
+ moduleCache.set(resolvedPath, module);
3545
+ const previousLoadContext = registries.currentLoadContext;
3546
+ registries.currentLoadContext = loadContext;
3547
+ const localRequire = (request) => {
3548
+ const requiredPath = resolveRequiredModulePath(resolvedPath, request);
3549
+ if (requiredPath.endsWith(".json")) {
3550
+ const content = fs.readFileSync(requiredPath, "utf8");
3551
+ return JSON.parse(content);
3552
+ }
3553
+ return executeModule(requiredPath, null);
3554
+ };
3555
+ try {
3556
+ new vm.Script(`(function (exports, module, require, __filename, __dirname) { ${source}\n})`, { filename: resolvedPath }).runInNewContext(executionContext)(module.exports, module, localRequire, resolvedPath, path.dirname(resolvedPath));
3557
+ return module.exports;
3558
+ } finally {
3559
+ registries.currentLoadContext = previousLoadContext;
3560
+ }
3561
+ }
3562
+ return {
3563
+ executeAppModule(filePath) {
3564
+ executeModule(filePath, { kind: "app" });
3565
+ if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in headless runtime.`);
3566
+ return registries.appDefinition;
3567
+ },
3568
+ executePageModule(filePath, route) {
3569
+ executeModule(filePath, {
3570
+ kind: "page",
3571
+ route
3572
+ });
3573
+ const definition = registries.pages.get(route);
3574
+ if (!definition) throw new Error(`Page() was not registered for route "${route}" while executing ${normalize(filePath)}.`);
3575
+ return definition;
3576
+ },
3577
+ executeComponentModule(filePath, id) {
3578
+ executeModule(filePath, {
3579
+ kind: "component",
3580
+ route: id
3581
+ });
3582
+ const definition = registries.components.get(id);
3583
+ if (!definition) throw new Error(`Component() was not registered for id "${id}" while executing ${normalize(filePath)}.`);
3584
+ return definition;
3585
+ }
3586
+ };
3587
+ }
3588
+ //#endregion
3589
+ //#region src/runtime/session.ts
3590
+ const LEADING_SLASH_RE$1 = /^\/+/;
3591
+ const PAGE_STACK_LIMIT = 10;
3592
+ const DATA_ATTR_SELECTOR_RE = /^\[data-([^=\]]+)="([^"]*)"\]$/;
3593
+ const DATASET_KEY_RE = /-([a-z])/g;
3594
+ function stripLeadingSlash(route) {
3595
+ return route.replace(LEADING_SLASH_RE$1, "");
3596
+ }
3597
+ function normalizeQuery(queryString) {
3598
+ const query = new URLSearchParams(queryString);
3599
+ const result = {};
3600
+ for (const [key, value] of query.entries()) result[key] = value;
3601
+ return result;
3602
+ }
3603
+ function parseNavigationUrl(url) {
3604
+ const trimmedUrl = url.trim();
3605
+ if (!trimmedUrl) throw new Error("Navigation url must be a non-empty string in headless runtime.");
3606
+ const [pathWithHash, queryString = ""] = trimmedUrl.split("?");
3607
+ const [pathname] = pathWithHash.split("#");
3608
+ return {
3609
+ pathname: pathname || "",
3610
+ query: normalizeQuery(queryString)
3611
+ };
3612
+ }
3613
+ function createAppLaunchOptions(pathname, query) {
3614
+ return {
3615
+ path: stripLeadingSlash(pathname),
3616
+ query: { ...query },
3617
+ referrerInfo: {
3618
+ appId: "",
3619
+ extraData: {}
3620
+ },
3621
+ scene: 1001
3622
+ };
3623
+ }
3624
+ function readJsonObject(filePath) {
3625
+ try {
3626
+ const value = JSON.parse(fs.readFileSync(filePath, "utf8"));
3627
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3628
+ } catch {
3629
+ return;
3630
+ }
3631
+ }
3632
+ function resolveNavigationPath(targetPath, baseRoute) {
3633
+ if (!targetPath) throw new Error("Navigation url must include a pathname in headless runtime.");
3634
+ if (targetPath.startsWith("/")) return path.posix.normalize(targetPath).replace(LEADING_SLASH_RE$1, "");
3635
+ if (!baseRoute) throw new Error(`Cannot resolve relative navigation url "${targetPath}" without an active page.`);
3636
+ return path.posix.resolve(`/${path.posix.dirname(baseRoute)}`, targetPath).replace(LEADING_SLASH_RE$1, "");
3637
+ }
3638
+ var HeadlessSession = class {
3639
+ project;
3640
+ appDefinition = null;
2647
3641
  appInstance = null;
2648
3642
  moduleLoader;
2649
3643
  registries;
2650
3644
  currentPageInstance = null;
2651
3645
  pages = [];
3646
+ componentCache = /* @__PURE__ */ new Map();
3647
+ componentScopes = /* @__PURE__ */ new Map();
2652
3648
  tabBarRoutes;
2653
3649
  tabPages = /* @__PURE__ */ new Map();
2654
3650
  tabBarItems = /* @__PURE__ */ new Map();
@@ -2658,6 +3654,10 @@ var HeadlessSession = class {
2658
3654
  enterOptions = createAppLaunchOptions("", {});
2659
3655
  launchOptions = createAppLaunchOptions("", {});
2660
3656
  wxState = createHeadlessWxState();
3657
+ pullDownRefreshState = {
3658
+ active: false,
3659
+ stopCalls: 0
3660
+ };
2661
3661
  constructor(options) {
2662
3662
  this.project = loadProject(options.projectPath);
2663
3663
  this.registries = createHostRegistries();
@@ -2683,6 +3683,7 @@ var HeadlessSession = class {
2683
3683
  });
2684
3684
  this.tabBarVisible = this.tabBarRoutes.size > 0;
2685
3685
  this.moduleLoader = createModuleLoader(this.registries, () => this.pages.slice(), () => this.getApp(), {
3686
+ executeSelectorQuery: (requests, scope) => this.executeSelectorQuery(requests, scope),
2686
3687
  getEnterOptionsSync: () => ({
2687
3688
  ...this.enterOptions,
2688
3689
  query: { ...this.enterOptions.query },
@@ -2760,11 +3761,91 @@ var HeadlessSession = class {
2760
3761
  const snapshot = this.currentPageInstance?.__background__;
2761
3762
  return snapshot ? cloneBackgroundSnapshot(snapshot) : null;
2762
3763
  }
2763
- getActionSheetLogs() {
2764
- return this.wxState.getActionSheetLogs();
3764
+ getActionSheetLogs() {
3765
+ return this.wxState.getActionSheetLogs();
3766
+ }
3767
+ getRequestLogs() {
3768
+ return this.wxState.getRequestLogs();
3769
+ }
3770
+ renderCurrentPage() {
3771
+ const current = this.requireCurrentPage("renderCurrentPage()");
3772
+ return renderRuntimePageTree({
3773
+ changedPageKeys: current.__lastChangedKeys__ ?? [],
3774
+ componentCache: this.componentCache,
3775
+ componentScopes: this.componentScopes,
3776
+ moduleLoader: this.moduleLoader,
3777
+ project: this.project,
3778
+ session: {
3779
+ selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
3780
+ selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
3781
+ selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
3782
+ }
3783
+ }, current);
3784
+ }
3785
+ getScopeSnapshot(scopeId) {
3786
+ const scope = this.componentScopes.get(scopeId);
3787
+ if (!scope) return null;
3788
+ const instance = this.componentCache.get(scopeId);
3789
+ if (instance) return {
3790
+ data: instance.data ?? {},
3791
+ methods: Object.keys(instance).filter((key) => typeof instance[key] === "function").sort((a, b) => a.localeCompare(b)),
3792
+ properties: instance.properties ?? {},
3793
+ scopeId,
3794
+ type: "component"
3795
+ };
3796
+ const currentPage = this.currentPageInstance;
3797
+ if (currentPage && scopeId === `page:${currentPage.route}`) return {
3798
+ data: currentPage.data ?? {},
3799
+ methods: Object.keys(currentPage).filter((key) => typeof currentPage[key] === "function").sort((a, b) => a.localeCompare(b)),
3800
+ properties: currentPage.options ?? {},
3801
+ scopeId,
3802
+ type: "page"
3803
+ };
3804
+ return {
3805
+ data: scope.data ?? {},
3806
+ methods: [],
3807
+ properties: {},
3808
+ scopeId,
3809
+ type: "scope"
3810
+ };
2765
3811
  }
2766
- getRequestLogs() {
2767
- return this.wxState.getRequestLogs();
3812
+ getScopeIdForComponent(component) {
3813
+ if (!component) return null;
3814
+ return this.getComponentScopeId(component);
3815
+ }
3816
+ callScopeMethod(scopeId, methodName, event) {
3817
+ const current = this.requireCurrentPage(`scope method "${methodName}"`);
3818
+ this.renderCurrentPage();
3819
+ if (!scopeId || scopeId === `page:${stripLeadingSlash(current.route)}`) {
3820
+ const method = current[methodName];
3821
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${current.route}.`);
3822
+ return method.call(current, event);
3823
+ }
3824
+ const instance = this.componentCache.get(scopeId);
3825
+ if (!instance) throw new Error(`Unknown scope "${scopeId}" in headless runtime.`);
3826
+ instance.__lastInteractionEvent__ = {
3827
+ currentTarget: event.currentTarget,
3828
+ mark: event.mark,
3829
+ target: event.target
3830
+ };
3831
+ const method = instance[methodName];
3832
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless component scope "${scopeId}".`);
3833
+ return method.call(instance, event);
3834
+ }
3835
+ callScopeMethodDirect(scopeId, methodName, ...args) {
3836
+ const normalizedScopeId = scopeId.trim();
3837
+ if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in headless runtime.");
3838
+ const current = this.requireCurrentPage(`scope method "${methodName}"`);
3839
+ if (normalizedScopeId === `page:${stripLeadingSlash(current.route)}`) {
3840
+ const method = current[methodName];
3841
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${current.route}.`);
3842
+ return method.apply(current, args);
3843
+ }
3844
+ const instance = this.componentCache.get(normalizedScopeId);
3845
+ if (!instance) throw new Error(`Unknown scope "${normalizedScopeId}" in headless runtime.`);
3846
+ const method = instance[methodName];
3847
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless component scope "${normalizedScopeId}".`);
3848
+ return method.apply(instance, args);
2768
3849
  }
2769
3850
  getStorageSnapshot() {
2770
3851
  return this.wxState.getStorageSnapshot();
@@ -2772,6 +3853,27 @@ var HeadlessSession = class {
2772
3853
  getShareMenu() {
2773
3854
  return this.wxState.getShareMenu();
2774
3855
  }
3856
+ selectComponent(selector) {
3857
+ this.renderCurrentPage();
3858
+ return this.selectComponentsWithin(null, selector)[0] ?? null;
3859
+ }
3860
+ selectAllComponents(selector) {
3861
+ this.renderCurrentPage();
3862
+ return this.selectComponentsWithin(null, selector);
3863
+ }
3864
+ selectComponentWithin(scopeId, selector) {
3865
+ this.renderCurrentPage();
3866
+ return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
3867
+ }
3868
+ selectAllComponentsWithin(scopeId, selector) {
3869
+ this.renderCurrentPage();
3870
+ return this.selectComponentsWithin(scopeId, selector);
3871
+ }
3872
+ selectOwnerComponent(scopeId) {
3873
+ const scope = this.componentScopes.get(scopeId);
3874
+ if (!scope?.ownerScopeId) return null;
3875
+ return this.componentCache.get(scope.ownerScopeId) ?? null;
3876
+ }
2775
3877
  getTabBar() {
2776
3878
  return { visible: this.tabBarVisible };
2777
3879
  }
@@ -2790,6 +3892,9 @@ var HeadlessSession = class {
2790
3892
  getStorageInfo() {
2791
3893
  return this.wxState.getStorageInfoSync();
2792
3894
  }
3895
+ getPullDownRefreshState() {
3896
+ return { ...this.pullDownRefreshState };
3897
+ }
2793
3898
  getSystemInfo() {
2794
3899
  return { ...this.systemInfo };
2795
3900
  }
@@ -2982,6 +4087,7 @@ var HeadlessSession = class {
2982
4087
  if (this.pages.length >= PAGE_STACK_LIMIT) throw new Error(`Cannot navigateTo() beyond a ${PAGE_STACK_LIMIT}-page stack in headless runtime.`);
2983
4088
  if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in headless runtime: ${url}`);
2984
4089
  this.currentPageInstance?.onHide?.();
4090
+ if (this.currentPageInstance) this.runPageComponentLifetime(this.currentPageInstance.route, "hide");
2985
4091
  const pageInstance = this.createFreshPage(target);
2986
4092
  this.pages.push(pageInstance);
2987
4093
  this.currentPageInstance = pageInstance;
@@ -3010,6 +4116,7 @@ var HeadlessSession = class {
3010
4116
  const nextPage = this.pages.at(-1) ?? null;
3011
4117
  this.currentPageInstance = nextPage;
3012
4118
  nextPage?.onShow?.();
4119
+ if (nextPage) this.runPageComponentLifetime(nextPage.route, "show");
3013
4120
  return nextPage;
3014
4121
  }
3015
4122
  switchTab(url) {
@@ -3024,7 +4131,10 @@ var HeadlessSession = class {
3024
4131
  current.onTabItemTap?.(tabItem);
3025
4132
  return current;
3026
4133
  }
3027
- if (current && current !== cachedTarget) current.onHide?.();
4134
+ if (current && current !== cachedTarget) {
4135
+ current.onHide?.();
4136
+ this.runPageComponentLifetime(current.route, "hide");
4137
+ }
3028
4138
  for (const page of [...this.pages].reverse()) {
3029
4139
  if (this.isTabBarRoute(stripLeadingSlash(page.route))) continue;
3030
4140
  this.removePageInstance(page);
@@ -3034,7 +4144,10 @@ var HeadlessSession = class {
3034
4144
  if (!nextPage) {
3035
4145
  nextPage = this.createFreshPage(target);
3036
4146
  this.tabPages.set(target.routeRecord.route, nextPage);
3037
- } else if (current !== nextPage) nextPage.onShow?.();
4147
+ } else if (current !== nextPage) {
4148
+ nextPage.onShow?.();
4149
+ this.runPageComponentLifetime(nextPage.route, "show");
4150
+ }
3038
4151
  nextPage.onTabItemTap?.(tabItem);
3039
4152
  this.pages.length = 0;
3040
4153
  this.pages.push(nextPage);
@@ -3042,10 +4155,16 @@ var HeadlessSession = class {
3042
4155
  return nextPage;
3043
4156
  }
3044
4157
  pageScrollTo(option) {
3045
- this.requireCurrentPage("wx.pageScrollTo()").onPageScroll?.({ scrollTop: Number(option.scrollTop ?? 0) });
4158
+ const current = this.requireCurrentPage("wx.pageScrollTo()");
4159
+ current.__scrollTop__ = Number(option.scrollTop ?? 0);
4160
+ current.onPageScroll?.({ scrollTop: current.__scrollTop__ });
3046
4161
  }
3047
4162
  triggerPullDownRefresh() {
3048
4163
  const current = this.requireCurrentPage("triggerPullDownRefresh()");
4164
+ this.pullDownRefreshState = {
4165
+ ...this.pullDownRefreshState,
4166
+ active: true
4167
+ };
3049
4168
  current.onPullDownRefresh?.();
3050
4169
  return current;
3051
4170
  }
@@ -3058,315 +4177,153 @@ var HeadlessSession = class {
3058
4177
  const current = this.requireCurrentPage("triggerResize()");
3059
4178
  applyResizeToSystemInfo(this.systemInfo, options);
3060
4179
  current.onResize?.(options);
3061
- return current;
3062
- }
3063
- triggerRouteDone(options = {}) {
3064
- const current = this.requireCurrentPage("triggerRouteDone()");
3065
- current.onRouteDone?.(options);
3066
- return current;
3067
- }
3068
- stopPullDownRefresh() {}
3069
- createFreshPage(target) {
3070
- const pageModulePath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
3071
- const pageConfigPath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.json`);
3072
- const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
3073
- const pageConfig = readJsonObject(pageConfigPath);
3074
- const pageInstance = createPageInstance(`/${target.routeRecord.route}`, pageDefinition, target.query, {
3075
- background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
3076
- navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
3077
- });
3078
- pageInstance.onLoad?.(target.query);
3079
- pageInstance.onShow?.();
3080
- pageInstance.onReady?.();
3081
- if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
3082
- return pageInstance;
3083
- }
3084
- isTabBarRoute(route) {
3085
- return this.tabBarRoutes.has(stripLeadingSlash(route));
3086
- }
3087
- resolveTabBarItem(route) {
3088
- const pagePath = stripLeadingSlash(route);
3089
- const item = this.tabBarItems.get(pagePath);
3090
- if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in headless runtime.`);
3091
- return { ...item };
3092
- }
3093
- requireTabBarItem(index, action) {
3094
- const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
3095
- const item = this.tabBarState.get(normalizedIndex);
3096
- if (!item) throw new Error(`Cannot call ${action} with unknown tabBar index ${index} in headless runtime.`);
3097
- return item;
3098
- }
3099
- removePageInstance(page) {
3100
- const index = this.pages.indexOf(page);
3101
- if (index >= 0) this.pages.splice(index, 1);
3102
- }
3103
- resolveNavigationTarget(url) {
3104
- const { pathname, query } = parseNavigationUrl(url);
3105
- const normalizedRoute = resolveNavigationPath(pathname, this.currentPageInstance ? stripLeadingSlash(this.currentPageInstance.route) : void 0);
3106
- const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
3107
- if (!routeRecord) {
3108
- this.bootstrap(createAppLaunchOptions(normalizedRoute, query));
3109
- this.appInstance?.onPageNotFound?.(createAppLaunchOptions(normalizedRoute, query));
3110
- throw new Error(`Unknown route for headless runtime navigation: ${url}`);
3111
- }
3112
- return {
3113
- normalizedRoute,
3114
- query,
3115
- routeRecord
3116
- };
3117
- }
3118
- unloadAllPages() {
3119
- const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
3120
- for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
3121
- this.pages.length = 0;
3122
- this.tabPages.clear();
3123
- this.currentPageInstance = null;
3124
- }
3125
- unloadPage(page) {
3126
- page.onUnload?.();
3127
- this.tabPages.delete(stripLeadingSlash(page.route));
3128
- }
3129
- requireCurrentPage(action) {
3130
- this.bootstrap();
3131
- const current = this.currentPageInstance;
3132
- if (!current) throw new Error(`Cannot call ${action} without an active page in headless runtime.`);
3133
- return current;
3134
- }
3135
- };
3136
- function createHeadlessSession(options) {
3137
- return new HeadlessSession(options);
3138
- }
3139
- //#endregion
3140
- //#region src/view/selectors.ts
3141
- const WHITESPACE_RE = /\s+/;
3142
- const DATA_ATTR_SELECTOR_RE = /^\[data-([^=\]]+)="([^"]*)"\]$/;
3143
- function getClassList(node) {
3144
- return String(node.attribs?.class ?? "").split(WHITESPACE_RE).map((item) => item.trim()).filter(Boolean);
3145
- }
3146
- function matchesSimpleSelector(node, selector) {
3147
- if (node.type !== "tag") return false;
3148
- if (selector === "page") return node.name === "page";
3149
- if (selector.startsWith("#")) return node.attribs?.id === selector.slice(1);
3150
- if (selector.startsWith(".")) return getClassList(node).includes(selector.slice(1));
3151
- const dataAttrMatch = selector.match(DATA_ATTR_SELECTOR_RE);
3152
- if (dataAttrMatch) {
3153
- const [, key, value] = dataAttrMatch;
3154
- return node.attribs?.[`data-${key}`] === value;
3155
- }
3156
- return node.name === selector;
3157
- }
3158
- function collectDescendants(node, into) {
3159
- for (const child of node.children ?? []) {
3160
- into.push(child);
3161
- collectDescendants(child, into);
3162
- }
3163
- }
3164
- function querySelectorAll(root, selector) {
3165
- const parts = selector.trim().split(WHITESPACE_RE).filter(Boolean);
3166
- if (parts.length === 0) return [];
3167
- let current = [root];
3168
- for (const part of parts) {
3169
- const next = [];
3170
- for (const node of current) {
3171
- const candidates = [];
3172
- if (part === "page" && node.type === "tag" && node.name === "page") candidates.push(node);
3173
- collectDescendants(node, candidates);
3174
- for (const candidate of candidates) if (matchesSimpleSelector(candidate, part)) next.push(candidate);
3175
- }
3176
- current = next;
3177
- }
3178
- return current;
3179
- }
3180
- //#endregion
3181
- //#region src/view/nodeHandle.ts
3182
- const DATASET_NAME_RE = /-([a-z])/g;
3183
- function escapeText$1(text) {
3184
- return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
3185
- }
3186
- function toDatasetKey(attributeName) {
3187
- return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
3188
- }
3189
- function collectDataset(node) {
3190
- const dataset = {};
3191
- for (const [key, value] of Object.entries(node.attribs ?? {})) {
3192
- if (!key.startsWith("data-")) continue;
3193
- dataset[toDatasetKey(key)] = value;
3194
- }
3195
- return dataset;
3196
- }
3197
- function resolveEventBinding(node, eventName) {
3198
- const normalizedEventName = eventName.trim();
3199
- if (!normalizedEventName) return null;
3200
- const bindingAttrs = [
3201
- `bind${normalizedEventName}`,
3202
- `bind:${normalizedEventName}`,
3203
- `catch${normalizedEventName}`,
3204
- `catch:${normalizedEventName}`
3205
- ];
3206
- for (const attributeName of bindingAttrs) {
3207
- const methodName = node.attribs?.[attributeName]?.trim();
3208
- if (methodName) return methodName;
3209
- }
3210
- return null;
3211
- }
3212
- function createEventPayload(node, eventName, event) {
3213
- const dataset = collectDataset(node);
3214
- const nodeId = node.attribs?.id ?? "";
3215
- return {
3216
- bubbles: false,
3217
- capturePhase: false,
3218
- composed: false,
3219
- currentTarget: {
3220
- dataset: event.currentTarget?.dataset ?? event.dataset ?? dataset,
3221
- id: event.currentTarget?.id ?? event.id ?? nodeId
3222
- },
3223
- detail: event.detail,
3224
- mark: event.mark,
3225
- target: {
3226
- dataset: event.target?.dataset ?? event.dataset ?? dataset,
3227
- id: event.target?.id ?? event.id ?? nodeId
3228
- },
3229
- type: eventName
3230
- };
3231
- }
3232
- function createValueEventDetail(value, detail) {
3233
- return {
3234
- value,
3235
- ...detail ?? {}
3236
- };
3237
- }
3238
- function escapeAttribute$1(value) {
3239
- return escapeText$1(value).replaceAll("\"", "&quot;");
3240
- }
3241
- function serializeNode(node) {
3242
- if (node.type === "text") return escapeText$1(node.data ?? "");
3243
- if (node.type !== "tag") return (node.children ?? []).map(serializeNode).join("");
3244
- if (node.name === "page") return (node.children ?? []).filter((child) => !(child.type === "tag" && (child.name === "import" || child.name === "wxs"))).map(serializeNode).join("");
3245
- const attrs = Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$1(value)}"`).join("");
3246
- const children = (node.children ?? []).map(serializeNode).join("");
3247
- return `<${node.name ?? ""}${attrs}>${children}</${node.name ?? ""}>`;
3248
- }
3249
- function collectText(node) {
3250
- if (node.type === "text") return node.data ?? "";
3251
- return (node.children ?? []).map(collectText).join("");
3252
- }
3253
- var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
3254
- constructor(node, interactions) {
3255
- this.node = node;
3256
- this.interactions = interactions;
4180
+ this.runPageComponentLifetime(current.route, "resize", options);
4181
+ return current;
3257
4182
  }
3258
- async $(selector) {
3259
- const match = querySelectorAll(this.node, selector)[0];
3260
- return match ? new HeadlessTestingNodeHandle(match, this.interactions) : null;
4183
+ triggerRouteDone(options = {}) {
4184
+ const current = this.requireCurrentPage("triggerRouteDone()");
4185
+ current.onRouteDone?.(options);
4186
+ return current;
3261
4187
  }
3262
- async $$(selector) {
3263
- return querySelectorAll(this.node, selector).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
4188
+ stopPullDownRefresh() {
4189
+ this.pullDownRefreshState = {
4190
+ active: false,
4191
+ stopCalls: this.pullDownRefreshState.stopCalls + 1
4192
+ };
3264
4193
  }
3265
- async attr(name) {
3266
- return this.node.attribs?.[name];
4194
+ executeSelectorQuery(requests, scope) {
4195
+ const current = this.requireCurrentPage("wx.createSelectorQuery().exec()");
4196
+ if (scope && scope !== current && !Array.from(this.componentCache.values()).includes(scope)) throw new Error("wx.createSelectorQuery().in(component) received an unknown scope in headless runtime.");
4197
+ const rendered = this.renderCurrentPage();
4198
+ const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
4199
+ return executeSelectorQueryRequests(requests, {
4200
+ page: current,
4201
+ root: resolveSelectorQueryScopeRoot(rendered.root, scopeId),
4202
+ windowInfo: this.getWindowInfo()
4203
+ });
3267
4204
  }
3268
- async dataset() {
3269
- return collectDataset(this.node);
4205
+ createFreshPage(target) {
4206
+ const pageModulePath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
4207
+ const pageConfigPath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.json`);
4208
+ const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
4209
+ const pageConfig = readJsonObject(pageConfigPath);
4210
+ const pageInstance = createPageInstance(`/${target.routeRecord.route}`, pageDefinition, target.query, {
4211
+ background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
4212
+ navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
4213
+ });
4214
+ pageInstance.selectComponent = (selector) => this.selectComponent(selector);
4215
+ pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
4216
+ pageInstance.onLoad?.(target.query);
4217
+ pageInstance.onShow?.();
4218
+ pageInstance.onReady?.();
4219
+ if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
4220
+ return pageInstance;
3270
4221
  }
3271
- async text() {
3272
- return collectText(this.node);
4222
+ isTabBarRoute(route) {
4223
+ return this.tabBarRoutes.has(stripLeadingSlash(route));
3273
4224
  }
3274
- async trigger(eventName, event = {}) {
3275
- if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3276
- const normalizedEventName = eventName.trim();
3277
- if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
3278
- const methodName = resolveEventBinding(this.node, normalizedEventName);
3279
- if (!methodName) throw new Error(`No ${normalizedEventName} binding was found on <${this.node.name ?? "unknown"}> in headless testing runtime.`);
3280
- return await this.interactions.callMethod(methodName, createEventPayload(this.node, normalizedEventName, event));
4225
+ resolveTabBarItem(route) {
4226
+ const pagePath = stripLeadingSlash(route);
4227
+ const item = this.tabBarItems.get(pagePath);
4228
+ if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in headless runtime.`);
4229
+ return { ...item };
3281
4230
  }
3282
- async tap(event = {}) {
3283
- return await this.trigger("tap", event);
4231
+ requireTabBarItem(index, action) {
4232
+ const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
4233
+ const item = this.tabBarState.get(normalizedIndex);
4234
+ if (!item) throw new Error(`Cannot call ${action} with unknown tabBar index ${index} in headless runtime.`);
4235
+ return item;
3284
4236
  }
3285
- async input(value, event = {}) {
3286
- return await this.trigger("input", {
3287
- ...event,
3288
- detail: createValueEventDetail(value, event.detail)
3289
- });
4237
+ removePageInstance(page) {
4238
+ const index = this.pages.indexOf(page);
4239
+ if (index >= 0) this.pages.splice(index, 1);
3290
4240
  }
3291
- async change(value, event = {}) {
3292
- return await this.trigger("change", {
3293
- ...event,
3294
- detail: createValueEventDetail(value, event.detail)
3295
- });
4241
+ resolveNavigationTarget(url) {
4242
+ const { pathname, query } = parseNavigationUrl(url);
4243
+ const normalizedRoute = resolveNavigationPath(pathname, this.currentPageInstance ? stripLeadingSlash(this.currentPageInstance.route) : void 0);
4244
+ const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
4245
+ if (!routeRecord) {
4246
+ this.bootstrap(createAppLaunchOptions(normalizedRoute, query));
4247
+ this.appInstance?.onPageNotFound?.(createAppLaunchOptions(normalizedRoute, query));
4248
+ throw new Error(`Unknown route for headless runtime navigation: ${url}`);
4249
+ }
4250
+ return {
4251
+ normalizedRoute,
4252
+ query,
4253
+ routeRecord
4254
+ };
3296
4255
  }
3297
- async blur(value, event = {}) {
3298
- return await this.trigger("blur", {
3299
- ...event,
3300
- detail: value == null ? event.detail : createValueEventDetail(value, event.detail)
3301
- });
4256
+ unloadAllPages() {
4257
+ const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
4258
+ for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
4259
+ this.pages.length = 0;
4260
+ this.tabPages.clear();
4261
+ this.componentCache.clear();
4262
+ this.componentScopes.clear();
4263
+ this.currentPageInstance = null;
3302
4264
  }
3303
- async wxml() {
3304
- return serializeNode(this.node);
4265
+ unloadPage(page) {
4266
+ page.onUnload?.();
4267
+ this.detachPageComponents(page.route);
4268
+ this.tabPages.delete(stripLeadingSlash(page.route));
4269
+ }
4270
+ requireCurrentPage(action) {
4271
+ this.bootstrap();
4272
+ const current = this.currentPageInstance;
4273
+ if (!current) throw new Error(`Cannot call ${action} without an active page in headless runtime.`);
4274
+ return current;
4275
+ }
4276
+ selectComponentsWithin(rootScopeId, selector) {
4277
+ const normalizedSelector = selector.trim();
4278
+ if (!normalizedSelector) return [];
4279
+ return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
4280
+ if (!candidateScopeId.includes("/")) return false;
4281
+ if (rootScopeId && candidateScopeId === rootScopeId) return false;
4282
+ if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
4283
+ if (normalizedSelector.startsWith("#")) return scope.id === normalizedSelector.slice(1);
4284
+ if (normalizedSelector.startsWith(".")) return scope.classList?.includes(normalizedSelector.slice(1)) ?? false;
4285
+ const dataAttrMatch = normalizedSelector.match(DATA_ATTR_SELECTOR_RE);
4286
+ if (dataAttrMatch) {
4287
+ const [, key, value] = dataAttrMatch;
4288
+ const datasetKey = key.replace(DATASET_KEY_RE, (_match, char) => char.toUpperCase());
4289
+ return scope.dataset?.[datasetKey] === value;
4290
+ }
4291
+ return scope.alias === normalizedSelector;
4292
+ }).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
4293
+ }
4294
+ detachPageComponents(route) {
4295
+ const prefix = `page:${stripLeadingSlash(route)}`;
4296
+ for (const [scopeId, instance] of [...this.componentCache.entries()]) {
4297
+ if (!scopeId.startsWith(prefix)) continue;
4298
+ instance.__definition__?.lifetimes?.detached?.call(instance);
4299
+ this.componentCache.delete(scopeId);
4300
+ this.componentScopes.delete(scopeId);
4301
+ }
4302
+ }
4303
+ runPageComponentLifetime(route, lifetimeName, payload) {
4304
+ const prefix = `page:${stripLeadingSlash(route)}`;
4305
+ for (const [scopeId, instance] of this.componentCache.entries()) {
4306
+ if (!scopeId.startsWith(prefix)) continue;
4307
+ instance.__definition__?.pageLifetimes?.[lifetimeName]?.call(instance, payload);
4308
+ }
4309
+ }
4310
+ getComponentScopeId(component) {
4311
+ for (const [scopeId, instance] of this.componentCache.entries()) if (instance === component) return scopeId;
4312
+ return null;
3305
4313
  }
3306
4314
  };
3307
- //#endregion
3308
- //#region src/view/render.ts
3309
- const LEADING_SLASH_RE$1 = /^\/+/;
3310
- const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
3311
- function resolveValueByPath(source, expression) {
3312
- const normalized = expression.trim();
3313
- if (!normalized) return "";
3314
- const segments = normalized.split(".").filter(Boolean);
3315
- let current = source;
3316
- for (const segment of segments) current = current?.[segment];
3317
- return current ?? "";
3318
- }
3319
- function interpolateTemplate(input, data) {
3320
- return input.replace(TEMPLATE_INTERPOLATION_RE, (_match, expression) => {
3321
- const value = resolveValueByPath(data, expression);
3322
- return typeof value === "string" ? value : String(value);
3323
- });
3324
- }
3325
- function visitDom(node, visitor) {
3326
- visitor(node);
3327
- for (const child of node.children ?? []) visitDom(child, visitor);
3328
- }
3329
- function interpolateDomTree(root, data) {
3330
- visitDom(root, (node) => {
3331
- if (typeof node.data === "string") node.data = interpolateTemplate(node.data, data);
3332
- if (node.attribs) for (const [key, value] of Object.entries(node.attribs)) node.attribs[key] = interpolateTemplate(value, data);
3333
- });
3334
- }
3335
- function escapeText(text) {
3336
- return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
3337
- }
3338
- function escapeAttribute(value) {
3339
- return escapeText(value).replaceAll("\"", "&quot;");
3340
- }
3341
- function serializeDomNode(node) {
3342
- if (node.type === "text") return escapeText(node.data ?? "");
3343
- if (node.type === "root") return (node.children ?? []).map(serializeDomNode).join("");
3344
- const tagName = node.name ?? "";
3345
- if (!tagName) return (node.children ?? []).map(serializeDomNode).join("");
3346
- return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode).join("")}</${tagName}>`;
3347
- }
3348
- function renderPageTree(project, page) {
3349
- const route = page.route.replace(LEADING_SLASH_RE$1, "");
3350
- const templatePath = path.resolve(project.miniprogramRootPath, `${route}.wxml`);
3351
- const document = parseDocument(`<page>${fs.readFileSync(templatePath, "utf8")}</page>`, {
3352
- xmlMode: false,
3353
- decodeEntities: false,
3354
- recognizeSelfClosing: true
3355
- });
3356
- interpolateDomTree(document, page.data);
3357
- return {
3358
- root: document,
3359
- wxml: serializeDomNode((document.children ?? [])[0] ?? document)
3360
- };
4315
+ function createHeadlessSession(options) {
4316
+ return new HeadlessSession(options);
3361
4317
  }
3362
4318
  //#endregion
3363
4319
  //#region src/testing/pageHandle.ts
3364
4320
  const DEFAULT_WAIT_TIMEOUT$1 = 1e3;
3365
4321
  const DEFAULT_WAIT_INTERVAL$1 = 10;
3366
4322
  var HeadlessTestingPageHandle = class {
3367
- constructor(project, page) {
4323
+ constructor(project, page, session) {
3368
4324
  this.project = project;
3369
4325
  this.page = page;
4326
+ this.session = session;
3370
4327
  }
3371
4328
  resolveDataByPath(path) {
3372
4329
  if (!path) return this.page.data;
@@ -3386,6 +4343,10 @@ var HeadlessTestingPageHandle = class {
3386
4343
  await this.waitFor(interval);
3387
4344
  }
3388
4345
  }
4346
+ createScopeHandle(component) {
4347
+ const scopeId = this.session?.getScopeIdForComponent(component);
4348
+ return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
4349
+ }
3389
4350
  async callMethod(methodName, ...args) {
3390
4351
  const method = this.page[methodName];
3391
4352
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${this.page.route}.`);
@@ -3394,13 +4355,41 @@ var HeadlessTestingPageHandle = class {
3394
4355
  async data(path) {
3395
4356
  return this.resolveDataByPath(path);
3396
4357
  }
4358
+ async selectComponent(selector) {
4359
+ const normalizedSelector = selector.trim();
4360
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4361
+ const component = this.page.selectComponent?.(normalizedSelector) ?? null;
4362
+ return this.createScopeHandle(component);
4363
+ }
4364
+ async selectAllComponents(selector) {
4365
+ const normalizedSelector = selector.trim();
4366
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4367
+ return (this.page.selectAllComponents?.(normalizedSelector) ?? []).map((component) => this.createScopeHandle(component)).filter((handle) => Boolean(handle));
4368
+ }
3397
4369
  async waitFor(ms = 0) {
3398
4370
  if (ms <= 0) return;
3399
4371
  await new Promise((resolve) => setTimeout(resolve, ms));
3400
4372
  }
3401
4373
  async $(selector) {
3402
- const tree = renderPageTree(this.project, this.page);
3403
- const root = new HeadlessTestingNodeHandle(tree.root.children?.[0] ?? tree.root, { callMethod: (methodName, event) => this.callMethod(methodName, event) });
4374
+ const tree = this.session?.getCurrentPages().includes(this.page) ? this.session.renderCurrentPage() : renderPageTree(this.project, this.page);
4375
+ const root = new HeadlessTestingNodeHandle(tree.root.type === "root" ? tree.root.children?.[0] ?? tree.root : tree.root, {
4376
+ callMethod: (scopeId, methodName, event) => {
4377
+ if (this.session?.getCurrentPages().includes(this.page)) return this.session.callScopeMethod(scopeId, methodName, event);
4378
+ return this.callMethod(methodName, event);
4379
+ },
4380
+ createPageHandle: () => this,
4381
+ createScopeHandle: (scopeId) => {
4382
+ if (!this.session) throw new Error("Scope handles are not available without an active headless testing session.");
4383
+ if (!scopeId) return null;
4384
+ return new HeadlessTestingScopeHandle(scopeId, this.project, this.session);
4385
+ },
4386
+ ownerScopeId: (scopeId) => {
4387
+ if (!this.session || !scopeId) return null;
4388
+ if (this.session.getScopeSnapshot(scopeId)?.type !== "component") return null;
4389
+ const owner = this.session.selectOwnerComponent(scopeId);
4390
+ return this.session.getScopeIdForComponent(owner);
4391
+ }
4392
+ });
3404
4393
  if (selector === "page") return root;
3405
4394
  return await root.$(selector);
3406
4395
  }
@@ -3419,6 +4408,20 @@ var HeadlessTestingPageHandle = class {
3419
4408
  }
3420
4409
  return await this.pollUntil(async () => await this.$(normalizedSelector), `Timed out waiting for selector "${normalizedSelector}" to appear in headless testing runtime.`, options);
3421
4410
  }
4411
+ async waitForComponent(selector, options = {}) {
4412
+ const normalizedSelector = selector.trim();
4413
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4414
+ return await this.pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
4415
+ }
4416
+ async waitForComponents(selector, count = 1, options = {}) {
4417
+ const normalizedSelector = selector.trim();
4418
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4419
+ const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
4420
+ return await this.pollUntil(async () => {
4421
+ const components = await this.selectAllComponents(normalizedSelector);
4422
+ return components.length >= normalizedCount ? components : null;
4423
+ }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
4424
+ }
3422
4425
  async waitForText(text, options = {}) {
3423
4426
  const normalizedText = text.trim();
3424
4427
  if (!normalizedText) throw new Error("Text must be a non-empty string in headless testing runtime.");
@@ -3445,7 +4448,7 @@ var HeadlessTestingPageHandle = class {
3445
4448
  }, `Timed out waiting for data "${normalizedPath}" in headless testing runtime.`, options);
3446
4449
  }
3447
4450
  async wxml() {
3448
- return renderPageTree(this.project, this.page).wxml;
4451
+ return this.session?.getCurrentPages().includes(this.page) ? this.session.renderCurrentPage().wxml : renderPageTree(this.project, this.page).wxml;
3449
4452
  }
3450
4453
  };
3451
4454
  //#endregion
@@ -3456,6 +4459,88 @@ const DEFAULT_WAIT_INTERVAL = 10;
3456
4459
  function normalizeRoute(route) {
3457
4460
  return route.replace(LEADING_SLASH_RE, "");
3458
4461
  }
4462
+ function resolvePageScopeId(scopeId) {
4463
+ const pagePathIndex = scopeId.indexOf("/page/");
4464
+ return pagePathIndex >= 0 ? scopeId.slice(0, pagePathIndex) : scopeId;
4465
+ }
4466
+ var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
4467
+ constructor(scopeId, project, session) {
4468
+ this.scopeId = scopeId;
4469
+ this.project = project;
4470
+ this.session = session;
4471
+ }
4472
+ createScopeHandle(component) {
4473
+ const scopeId = this.session.getScopeIdForComponent(component);
4474
+ return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
4475
+ }
4476
+ async callMethod(methodName, ...args) {
4477
+ const normalizedMethodName = methodName.trim();
4478
+ if (!normalizedMethodName) throw new Error("Method name must be a non-empty string in headless testing runtime.");
4479
+ return this.session.callScopeMethodDirect(this.scopeId, normalizedMethodName, ...args);
4480
+ }
4481
+ async snapshot() {
4482
+ return this.session.getScopeSnapshot(this.scopeId);
4483
+ }
4484
+ async page() {
4485
+ const currentPage = this.session.getCurrentPages().at(-1);
4486
+ return currentPage ? new HeadlessTestingPageHandle(this.project, currentPage, this.session) : null;
4487
+ }
4488
+ async pageScope() {
4489
+ return new HeadlessTestingScopeHandle(resolvePageScopeId(this.scopeId), this.project, this.session);
4490
+ }
4491
+ async ownerComponent() {
4492
+ return this.createScopeHandle(this.session.selectOwnerComponent(this.scopeId));
4493
+ }
4494
+ async waitForOwnerComponent(options = {}) {
4495
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
4496
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
4497
+ const deadline = Date.now() + timeout;
4498
+ while (true) {
4499
+ const owner = await this.ownerComponent();
4500
+ if (owner) return owner;
4501
+ if (Date.now() >= deadline) throw new Error("Timed out waiting for owner component in headless testing runtime.");
4502
+ await new Promise((resolve) => setTimeout(resolve, interval));
4503
+ }
4504
+ }
4505
+ async selectComponent(selector) {
4506
+ const normalizedSelector = selector.trim();
4507
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4508
+ const component = this.session.selectComponentWithin(this.scopeId, normalizedSelector);
4509
+ return this.createScopeHandle(component);
4510
+ }
4511
+ async selectAllComponents(selector) {
4512
+ const normalizedSelector = selector.trim();
4513
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4514
+ return this.session.selectAllComponentsWithin(this.scopeId, normalizedSelector).map((component) => this.createScopeHandle(component)).filter((handle) => Boolean(handle));
4515
+ }
4516
+ async waitForComponent(selector, options = {}) {
4517
+ const normalizedSelector = selector.trim();
4518
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4519
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
4520
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
4521
+ const deadline = Date.now() + timeout;
4522
+ while (true) {
4523
+ const component = await this.selectComponent(normalizedSelector);
4524
+ if (component) return component;
4525
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`);
4526
+ await new Promise((resolve) => setTimeout(resolve, interval));
4527
+ }
4528
+ }
4529
+ async waitForComponents(selector, count = 1, options = {}) {
4530
+ const normalizedSelector = selector.trim();
4531
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4532
+ const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
4533
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
4534
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
4535
+ const deadline = Date.now() + timeout;
4536
+ while (true) {
4537
+ const components = await this.selectAllComponents(normalizedSelector);
4538
+ if (components.length >= normalizedCount) return components;
4539
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`);
4540
+ await new Promise((resolve) => setTimeout(resolve, interval));
4541
+ }
4542
+ }
4543
+ };
3459
4544
  var HeadlessTestingSessionHandle = class {
3460
4545
  constructor(project, session) {
3461
4546
  this.project = project;
@@ -3479,14 +4564,45 @@ var HeadlessTestingSessionHandle = class {
3479
4564
  async close() {}
3480
4565
  async currentPage() {
3481
4566
  const current = this.session.getCurrentPages().at(-1);
3482
- return current ? new HeadlessTestingPageHandle(this.project, current) : null;
4567
+ return current ? new HeadlessTestingPageHandle(this.project, current, this.session) : null;
3483
4568
  }
3484
4569
  async getCurrentPages() {
3485
- return this.session.getCurrentPages().map((page) => new HeadlessTestingPageHandle(this.project, page));
4570
+ return this.session.getCurrentPages().map((page) => new HeadlessTestingPageHandle(this.project, page, this.session));
4571
+ }
4572
+ async scopeSnapshot(scopeId) {
4573
+ const normalizedScopeId = scopeId.trim();
4574
+ if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in headless testing runtime.");
4575
+ return this.session.getScopeSnapshot(normalizedScopeId);
4576
+ }
4577
+ async selectComponent(selector) {
4578
+ const normalizedSelector = selector.trim();
4579
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4580
+ const component = this.session.selectComponent(normalizedSelector);
4581
+ const scopeId = this.session.getScopeIdForComponent(component);
4582
+ return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
4583
+ }
4584
+ async selectAllComponents(selector) {
4585
+ const normalizedSelector = selector.trim();
4586
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4587
+ return this.session.selectAllComponents(normalizedSelector).map((component) => this.session.getScopeIdForComponent(component)).filter((scopeId) => Boolean(scopeId)).map((scopeId) => new HeadlessTestingScopeHandle(scopeId, this.project, this.session));
4588
+ }
4589
+ async waitForComponent(selector, options = {}) {
4590
+ const normalizedSelector = selector.trim();
4591
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4592
+ return await this.pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
4593
+ }
4594
+ async waitForComponents(selector, count = 1, options = {}) {
4595
+ const normalizedSelector = selector.trim();
4596
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4597
+ const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
4598
+ return await this.pollUntil(async () => {
4599
+ const components = await this.selectAllComponents(normalizedSelector);
4600
+ return components.length >= normalizedCount ? components : null;
4601
+ }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
3486
4602
  }
3487
4603
  async reLaunch(route) {
3488
4604
  const page = this.session.reLaunch(route);
3489
- return new HeadlessTestingPageHandle(this.project, page);
4605
+ return new HeadlessTestingPageHandle(this.project, page, this.session);
3490
4606
  }
3491
4607
  async waitForCurrentPage(route, options = {}) {
3492
4608
  const normalizedRoute = route?.trim();
@@ -3494,7 +4610,7 @@ var HeadlessTestingSessionHandle = class {
3494
4610
  return await this.pollUntil(async () => {
3495
4611
  const currentPageInstance = this.session.getCurrentPages().at(-1);
3496
4612
  if (!currentPageInstance) return null;
3497
- const current = new HeadlessTestingPageHandle(this.project, currentPageInstance);
4613
+ const current = new HeadlessTestingPageHandle(this.project, currentPageInstance, this.session);
3498
4614
  if (!normalizedRoute) return current;
3499
4615
  if (normalizeRoute(currentPageInstance.route) === normalizeRoute(normalizedRoute)) return current;
3500
4616
  return null;
@@ -3524,4 +4640,4 @@ async function launch(options) {
3524
4640
  return new HeadlessTestingSessionHandle(session.project, session);
3525
4641
  }
3526
4642
  //#endregion
3527
- export { BrowserHeadlessSession, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingSessionHandle, cloneValue, coerceComponentPropertyValue, createAppInstance, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createHeadlessSession, createHeadlessWx, createHeadlessWxState, createHostRegistries, createPageInstance, createProjectDescriptor, hasBrowserVirtualFile, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, registerAppDefinition, registerComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, resolveRoutesFromAppConfig, runComponentLifecycle, runComponentObservers, runComponentPageLifetime };
4643
+ export { BrowserHeadlessSession, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingScopeHandle, HeadlessTestingSessionHandle, cloneValue, coerceComponentPropertyValue, createAppInstance, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createHeadlessSession, createHeadlessWx, createHeadlessWxState, createHostRegistries, createPageInstance, createProjectDescriptor, executeSelectorQueryRequests, hasBrowserVirtualFile, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, registerAppDefinition, registerComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, renderRuntimePageTree, resolveRoutesFromAppConfig, resolveSelectorQueryScopeRoot, runComponentLifecycle, runComponentObservers, runComponentPageLifetime };