@mpcore/simulator 0.0.2 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.mts +660 -79
  2. package/dist/index.mjs +2995 -1181
  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,10 @@ function createHeadlessWx(driver) {
63
62
  canIUse: true,
64
63
  clearStorage: true,
65
64
  clearStorageSync: true,
65
+ createSelectorQuery: true,
66
+ getFileSystemManager: true,
67
+ getSavedFileInfo: true,
68
+ getSavedFileList: true,
66
69
  getAppBaseInfo: { return: {
67
70
  SDKVersion: true,
68
71
  enableDebug: true,
@@ -164,6 +167,7 @@ function createHeadlessWx(driver) {
164
167
  } },
165
168
  hideLoading: true,
166
169
  hideToast: true,
170
+ downloadFile: true,
167
171
  navigateBack: true,
168
172
  navigateTo: true,
169
173
  nextTick: true,
@@ -175,6 +179,7 @@ function createHeadlessWx(driver) {
175
179
  removeStorage: true,
176
180
  removeStorageSync: true,
177
181
  request: true,
182
+ saveFile: true,
178
183
  setBackgroundColor: true,
179
184
  setBackgroundTextStyle: true,
180
185
  setStorage: true,
@@ -195,6 +200,7 @@ function createHeadlessWx(driver) {
195
200
  showToast: true,
196
201
  stopPullDownRefresh: true,
197
202
  switchTab: true,
203
+ uploadFile: true,
198
204
  removeTabBarBadge: true,
199
205
  setTabBarBadge: true,
200
206
  updateShareMenu: true
@@ -206,7 +212,67 @@ function createHeadlessWx(driver) {
206
212
  return { errMsg: "clearStorage:ok" };
207
213
  }, option),
208
214
  clearStorageSync: () => driver.clearStorageSync(),
215
+ createSelectorQuery: () => {
216
+ const requests = [];
217
+ let scope;
218
+ const callbacks = [];
219
+ let query;
220
+ const createNode = (target, selector, single = true) => ({
221
+ boundingClientRect: (callback) => {
222
+ requests.push({
223
+ fields: {
224
+ rect: true,
225
+ size: true
226
+ },
227
+ selector,
228
+ single,
229
+ target
230
+ });
231
+ if (callback) callbacks.push(callback);
232
+ return query;
233
+ },
234
+ fields: (fields, callback) => {
235
+ requests.push({
236
+ fields: { ...fields },
237
+ selector,
238
+ single,
239
+ target
240
+ });
241
+ if (callback) callbacks.push(callback);
242
+ return query;
243
+ },
244
+ scrollOffset: (callback) => {
245
+ requests.push({
246
+ fields: { scrollOffset: true },
247
+ selector,
248
+ single,
249
+ target
250
+ });
251
+ if (callback) callbacks.push(callback);
252
+ return query;
253
+ }
254
+ });
255
+ query = {
256
+ exec: (callback) => {
257
+ const result = driver.executeSelectorQuery(requests, scope);
258
+ for (const [index, item] of result.entries()) callbacks[index]?.(item);
259
+ callback?.(result);
260
+ return result;
261
+ },
262
+ in: (component) => {
263
+ scope = component;
264
+ return query;
265
+ },
266
+ select: (selector) => createNode("selector", selector, true),
267
+ selectAll: (selector) => createNode("selector", selector, false),
268
+ selectViewport: () => createNode("viewport", void 0, true)
269
+ };
270
+ return query;
271
+ },
209
272
  getEnterOptionsSync: () => driver.getEnterOptionsSync(),
273
+ getFileSystemManager: () => driver.getFileSystemManager(),
274
+ getSavedFileInfo: (option) => invokeWxApi(() => driver.getSavedFileInfo(option), option),
275
+ getSavedFileList: (option) => invokeWxApi(() => driver.getSavedFileList(option), option),
210
276
  getAppBaseInfo: (option) => invokeWxApi(() => driver.getAppBaseInfoSync(), option),
211
277
  getAppBaseInfoSync: () => driver.getAppBaseInfoSync(),
212
278
  getLaunchOptionsSync: () => driver.getLaunchOptionsSync(),
@@ -225,6 +291,7 @@ function createHeadlessWx(driver) {
225
291
  getWindowInfoSync: () => driver.getWindowInfoSync(),
226
292
  hideLoading: (option) => invokeWxApi(() => driver.hideLoading(), option),
227
293
  hideToast: () => driver.hideToast(),
294
+ downloadFile: (option) => driver.downloadFile(option),
228
295
  navigateBack: (option) => invokeWxApi(() => {
229
296
  driver.navigateBack(option);
230
297
  }, option),
@@ -243,12 +310,14 @@ function createHeadlessWx(driver) {
243
310
  redirectTo: (option) => invokeWxApi(() => {
244
311
  driver.redirectTo(option);
245
312
  }, option),
313
+ removeSavedFile: (option) => invokeWxApi(() => driver.removeSavedFile(option), option),
246
314
  removeStorage: (option) => invokeWxApi(() => {
247
315
  driver.removeStorageSync(option.key);
248
316
  return { errMsg: "removeStorage:ok" };
249
317
  }, option),
250
318
  removeStorageSync: (key) => driver.removeStorageSync(key),
251
319
  request: (option) => driver.request(option),
320
+ saveFile: (option) => invokeWxApi(() => driver.saveFile(option), option),
252
321
  setBackgroundColor: (option) => invokeWxApi(() => driver.setBackgroundColor(option), option),
253
322
  setBackgroundTextStyle: (option) => invokeWxApi(() => driver.setBackgroundTextStyle(option), option),
254
323
  setStorage: (option) => invokeWxApi(() => {
@@ -274,6 +343,7 @@ function createHeadlessWx(driver) {
274
343
  switchTab: (option) => invokeWxApi(() => {
275
344
  driver.switchTab(option);
276
345
  }, option),
346
+ uploadFile: (option) => driver.uploadFile(option),
277
347
  removeTabBarBadge: (option) => invokeWxApi(() => driver.removeTabBarBadge(option), option),
278
348
  setTabBarBadge: (option) => invokeWxApi(() => driver.setTabBarBadge(option), option),
279
349
  updateShareMenu: (option) => invokeWxApi(() => driver.updateShareMenu(option ?? {}), option)
@@ -407,11 +477,11 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
407
477
  }
408
478
  //#endregion
409
479
  //#region src/project/resolveRoutes.ts
410
- const LEADING_SLASH_RE$5 = /^\/+/;
411
- const TRAILING_SLASH_RE = /\/+$/;
480
+ const LEADING_SLASH_RE$6 = /^\/+/;
481
+ const TRAILING_SLASH_RE$1 = /\/+$/;
412
482
  const DUPLICATE_SLASH_RE = /\/{2,}/g;
413
483
  function normalizeSegment(value) {
414
- return value.replace(LEADING_SLASH_RE$5, "").replace(TRAILING_SLASH_RE, "");
484
+ return value.replace(LEADING_SLASH_RE$6, "").replace(TRAILING_SLASH_RE$1, "");
415
485
  }
416
486
  function pushRoute(records, seen, record) {
417
487
  if (!record.route || seen.has(record.route)) return;
@@ -757,21 +827,21 @@ function runComponentPageLifetime(instance, lifetimeName, payload) {
757
827
  }
758
828
  //#endregion
759
829
  //#region src/browser/render.ts
760
- const LEADING_SLASH_RE$4 = /^\/+/;
761
- const TEMPLATE_INTERPOLATION_RE$1 = /\{\{([^{}]+)\}\}/g;
762
- const EVENT_BINDING_ATTRS = [
830
+ const LEADING_SLASH_RE$5 = /^\/+/;
831
+ const TEMPLATE_INTERPOLATION_RE$2 = /\{\{([^{}]+)\}\}/g;
832
+ const EVENT_BINDING_ATTRS$1 = [
763
833
  "bindtap",
764
834
  "bind:tap",
765
835
  "catchtap",
766
836
  "catch:tap"
767
837
  ];
768
- const COMPONENT_EVENT_PREFIXES = [
838
+ const COMPONENT_EVENT_PREFIXES$1 = [
769
839
  "bind:",
770
840
  "bind",
771
841
  "catch:",
772
842
  "catch"
773
843
  ];
774
- const STRUCTURAL_ATTRS = [
844
+ const STRUCTURAL_ATTRS$1 = [
775
845
  "wx:if",
776
846
  "wx:elif",
777
847
  "wx:else",
@@ -780,48 +850,48 @@ const STRUCTURAL_ATTRS = [
780
850
  "wx:for-index",
781
851
  "wx:key"
782
852
  ];
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) {
853
+ const WX_ELSE_ATTRS$1 = new Set(["wx:elif", "wx:else"]);
854
+ const DATASET_NAME_RE$3 = /-([a-z])/g;
855
+ const BRACKET_INDEX_RE$1 = /\[(\d+)\]/g;
856
+ const CLASS_SPLIT_RE$1 = /\s+/;
857
+ const JS_FILE_RE$1 = /\.js$/;
858
+ function isMustacheOnly$1(value) {
789
859
  const trimmed = value.trim();
790
860
  return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
791
861
  }
792
- function toDatasetKey$1(attributeName) {
793
- return attributeName.slice(5).replace(DATASET_NAME_RE$1, (_match, char) => char.toUpperCase());
862
+ function toDatasetKey$3(attributeName) {
863
+ return attributeName.slice(5).replace(DATASET_NAME_RE$3, (_match, char) => char.toUpperCase());
794
864
  }
795
- function collectDataset$1(node) {
865
+ function collectDataset$3(node) {
796
866
  const dataset = {};
797
867
  for (const [key, value] of Object.entries(node.attribs ?? {})) {
798
868
  if (!key.startsWith("data-") || key === "data-sim-scope" || key === "data-sim-tap" || key === "data-sim-component") continue;
799
- dataset[toDatasetKey$1(key)] = String(value);
869
+ dataset[toDatasetKey$3(key)] = String(value);
800
870
  }
801
871
  return dataset;
802
872
  }
803
- function escapeText$2(text) {
873
+ function escapeText$3(text) {
804
874
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
805
875
  }
806
- function escapeAttribute$2(value) {
807
- return escapeText$2(value).replaceAll("\"", "&quot;");
876
+ function escapeAttribute$3(value) {
877
+ return escapeText$3(value).replaceAll("\"", "&quot;");
808
878
  }
809
- function cloneNode(node) {
879
+ function cloneNode$1(node) {
810
880
  return {
811
881
  ...node,
812
882
  attribs: node.attribs ? { ...node.attribs } : void 0,
813
- children: node.children?.map((child) => cloneNode(child))
883
+ children: node.children?.map((child) => cloneNode$1(child))
814
884
  };
815
885
  }
816
- function parseExpressionSegments(expression) {
817
- return expression.replace(BRACKET_INDEX_RE, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
886
+ function parseExpressionSegments$1(expression) {
887
+ return expression.replace(BRACKET_INDEX_RE$1, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
818
888
  }
819
- function unwrapMustacheExpression(expression) {
889
+ function unwrapMustacheExpression$1(expression) {
820
890
  const normalized = expression.trim();
821
- if (isMustacheOnly(normalized)) return normalized.slice(2, -2).trim();
891
+ if (isMustacheOnly$1(normalized)) return normalized.slice(2, -2).trim();
822
892
  return normalized;
823
893
  }
824
- function resolveLiteralValue(expression) {
894
+ function resolveLiteralValue$1(expression) {
825
895
  if (expression === "true") return true;
826
896
  if (expression === "false") return false;
827
897
  if (expression === "null") return null;
@@ -830,69 +900,69 @@ function resolveLiteralValue(expression) {
830
900
  const numericValue = Number(expression);
831
901
  if (!Number.isNaN(numericValue) && expression !== "") return numericValue;
832
902
  }
833
- function resolveValueByExpression(source, expression) {
834
- const normalized = unwrapMustacheExpression(expression);
903
+ function resolveValueByExpression$1(source, expression) {
904
+ const normalized = unwrapMustacheExpression$1(expression);
835
905
  if (!normalized) return;
836
- if (normalized.startsWith("!")) return !resolveValueByExpression(source, normalized.slice(1));
837
- const literalValue = resolveLiteralValue(normalized);
906
+ if (normalized.startsWith("!")) return !resolveValueByExpression$1(source, normalized.slice(1));
907
+ const literalValue = resolveLiteralValue$1(normalized);
838
908
  if (literalValue !== void 0 || normalized === "undefined") return literalValue;
839
- const segments = parseExpressionSegments(normalized);
909
+ const segments = parseExpressionSegments$1(normalized);
840
910
  let current = source;
841
911
  for (const segment of segments) current = current?.[segment];
842
912
  return current;
843
913
  }
844
- function resolveValueByPath$1(source, expression) {
845
- return resolveValueByExpression(source, expression) ?? "";
914
+ function resolveValueByPath$2(source, expression) {
915
+ return resolveValueByExpression$1(source, expression) ?? "";
846
916
  }
847
- function resolveRawValueByPath(source, expression) {
848
- return resolveValueByExpression(source, expression);
917
+ function resolveRawValueByPath$1(source, expression) {
918
+ return resolveValueByExpression$1(source, expression);
849
919
  }
850
- function interpolateTemplate$1(input, data) {
851
- return input.replace(TEMPLATE_INTERPOLATION_RE$1, (_match, expression) => {
852
- const value = resolveValueByPath$1(data, expression);
920
+ function interpolateTemplate$2(input, data) {
921
+ return input.replace(TEMPLATE_INTERPOLATION_RE$2, (_match, expression) => {
922
+ const value = resolveValueByPath$2(data, expression);
853
923
  return typeof value === "string" ? value : String(value);
854
924
  });
855
925
  }
856
- function readTemplateSource(files, filePath) {
926
+ function readTemplateSource$1(files, filePath) {
857
927
  const templateSource = readBrowserVirtualFile(files, filePath);
858
928
  if (typeof templateSource !== "string") throw new TypeError(`Missing template in browser simulator runtime: ${filePath}`);
859
929
  return templateSource;
860
930
  }
861
- function parseTemplateDocument(templateSource) {
931
+ function parseTemplateDocument$1(templateSource) {
862
932
  return parseDocument(`<page>${templateSource}</page>`, {
863
933
  xmlMode: false,
864
934
  decodeEntities: false,
865
935
  recognizeSelfClosing: true
866
936
  });
867
937
  }
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("");
938
+ function serializeDomNode$2(node) {
939
+ if (node.type === "text") return escapeText$3(node.data ?? "");
940
+ if (node.type === "root") return (node.children ?? []).map(serializeDomNode$2).join("");
871
941
  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}>`;
942
+ if (!tagName) return (node.children ?? []).map(serializeDomNode$2).join("");
943
+ return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$3(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$2).join("")}</${tagName}>`;
874
944
  }
875
- function isTagNode(node) {
945
+ function isTagNode$1(node) {
876
946
  return node.type === "tag" && typeof node.name === "string";
877
947
  }
878
- function isIgnorableTextNode(node) {
948
+ function isIgnorableTextNode$1(node) {
879
949
  return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
880
950
  }
881
- function resolveAttributeValue(value, scope) {
882
- if (isMustacheOnly(value)) {
951
+ function resolveAttributeValue$1(value, scope) {
952
+ if (isMustacheOnly$1(value)) {
883
953
  const expression = value.trim().slice(2, -2);
884
- return resolveValueByPath$1(scope.data, expression);
954
+ return resolveValueByPath$2(scope.data, expression);
885
955
  }
886
- return interpolateTemplate$1(value, scope.data);
956
+ return interpolateTemplate$2(value, scope.data);
887
957
  }
888
- function resolveComponentAttributeValue(value, scope) {
889
- if (isMustacheOnly(value)) {
958
+ function resolveComponentAttributeValue$1(value, scope) {
959
+ if (isMustacheOnly$1(value)) {
890
960
  const expression = value.trim().slice(2, -2);
891
- return resolveRawValueByPath(scope.data, expression);
961
+ return resolveRawValueByPath$1(scope.data, expression);
892
962
  }
893
- return interpolateTemplate$1(value, scope.data);
963
+ return interpolateTemplate$2(value, scope.data);
894
964
  }
895
- function resolveUsingComponents(files, ownerJsonPath, ownerFilePath) {
965
+ function resolveUsingComponents$1(files, ownerJsonPath, ownerFilePath) {
896
966
  const ownerJson = readBrowserVirtualFile(files, ownerJsonPath);
897
967
  if (typeof ownerJson !== "string") return /* @__PURE__ */ new Map();
898
968
  try {
@@ -901,16 +971,16 @@ function resolveUsingComponents(files, ownerJsonPath, ownerFilePath) {
901
971
  const resolved = /* @__PURE__ */ new Map();
902
972
  for (const [alias, rawPath] of Object.entries(usingComponents)) {
903
973
  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, ""));
974
+ const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$5, "") : normalize(join(dirname(ownerFilePath), rawPath));
975
+ resolved.set(alias, basePath.replace(LEADING_SLASH_RE$5, ""));
906
976
  }
907
977
  return resolved;
908
978
  } catch {
909
979
  return /* @__PURE__ */ new Map();
910
980
  }
911
981
  }
912
- function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias) {
913
- const componentBasePath = resolveUsingComponents(context.files, ownerJsonPath, ownerFilePath).get(alias);
982
+ function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, alias) {
983
+ const componentBasePath = resolveUsingComponents$1(context.files, ownerJsonPath, ownerFilePath).get(alias);
914
984
  if (!componentBasePath) return null;
915
985
  const filePath = `${componentBasePath}.js`;
916
986
  const templatePath = `${componentBasePath}.wxml`;
@@ -920,10 +990,10 @@ function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, al
920
990
  templatePath
921
991
  };
922
992
  }
923
- function collectComponentEventBindings(hostNode) {
993
+ function collectComponentEventBindings$1(hostNode) {
924
994
  const eventBindings = /* @__PURE__ */ new Map();
925
995
  for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
926
- const matchedPrefix = COMPONENT_EVENT_PREFIXES.find((prefix) => key.startsWith(prefix));
996
+ const matchedPrefix = COMPONENT_EVENT_PREFIXES$1.find((prefix) => key.startsWith(prefix));
927
997
  if (!matchedPrefix) continue;
928
998
  const eventName = key.slice(matchedPrefix.length);
929
999
  if (!eventName) continue;
@@ -934,12 +1004,13 @@ function collectComponentEventBindings(hostNode) {
934
1004
  }
935
1005
  return eventBindings;
936
1006
  }
937
- function buildComponentTrigger(componentScopeId, context, hostNode) {
938
- const hostDataset = collectDataset$1(hostNode);
1007
+ function buildComponentTrigger$1(componentScopeId, context, hostNode) {
1008
+ const hostDataset = collectDataset$3(hostNode);
939
1009
  const hostId = hostNode.attribs?.id ?? "";
940
1010
  return (instance, eventName, detail, triggerOptions) => {
941
1011
  const interactionTarget = instance.__lastInteractionEvent__?.target;
942
1012
  const interactionCurrentTarget = instance.__lastInteractionEvent__?.currentTarget;
1013
+ const interactionMark = instance.__lastInteractionEvent__?.mark;
943
1014
  const target = {
944
1015
  dataset: interactionTarget?.dataset ?? hostDataset,
945
1016
  id: interactionTarget?.id ?? hostId
@@ -955,7 +1026,7 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
955
1026
  capturePhase: false,
956
1027
  composed: triggerOptions?.composed ?? false,
957
1028
  detail,
958
- mark: void 0,
1029
+ mark: interactionMark,
959
1030
  target,
960
1031
  type: eventName,
961
1032
  currentTarget: {
@@ -969,23 +1040,23 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
969
1040
  }
970
1041
  };
971
1042
  }
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);
1043
+ function applyNodeBindings$1(node, scope) {
1044
+ if (!isTagNode$1(node)) {
1045
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate$2(node.data, scope.data);
975
1046
  return;
976
1047
  }
977
1048
  node.attribs ??= {};
978
1049
  node.attribs["data-sim-scope"] = scope.getScopeId();
979
- for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
1050
+ for (const key of STRUCTURAL_ATTRS$1) delete node.attribs[key];
980
1051
  for (const [key, value] of Object.entries({ ...node.attribs })) {
981
- if (EVENT_BINDING_ATTRS.includes(key)) {
1052
+ if (EVENT_BINDING_ATTRS$1.includes(key)) {
982
1053
  node.attribs["data-sim-tap"] = value;
983
1054
  continue;
984
1055
  }
985
- node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
1056
+ node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue$1(value, scope)) : String(value);
986
1057
  }
987
1058
  }
988
- function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
1059
+ function syncComponentProperties$1(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
989
1060
  const changedRootKeys = [];
990
1061
  const previousProperties = {};
991
1062
  for (const [key, value] of Object.entries(nextProperties)) {
@@ -1007,17 +1078,17 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
1007
1078
  if (changedRootKeys.length === 0) return;
1008
1079
  runComponentObservers(definition, instance, changedRootKeys, previousProperties);
1009
1080
  }
1010
- function createMergedScopeData(pageData, componentProperties, componentData) {
1081
+ function createMergedScopeData$1(pageData, componentProperties, componentData) {
1011
1082
  return {
1012
1083
  ...pageData,
1013
1084
  ...componentProperties,
1014
1085
  ...componentData
1015
1086
  };
1016
1087
  }
1017
- function isTruthy(value) {
1088
+ function isTruthy$1(value) {
1018
1089
  return Boolean(value);
1019
1090
  }
1020
- function createLoopScope(scope, itemName, indexName, item, index) {
1091
+ function createLoopScope$1(scope, itemName, indexName, item, index) {
1021
1092
  return {
1022
1093
  ...scope,
1023
1094
  data: {
@@ -1027,37 +1098,37 @@ function createLoopScope(scope, itemName, indexName, item, index) {
1027
1098
  }
1028
1099
  };
1029
1100
  }
1030
- function evaluateConditionalBranch(node, scope) {
1101
+ function evaluateConditionalBranch$1(node, scope) {
1031
1102
  const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
1032
1103
  if (condition == null) return true;
1033
- return isTruthy(resolveRawValueByPath(scope.data, condition));
1104
+ return isTruthy$1(resolveRawValueByPath$1(scope.data, condition));
1034
1105
  }
1035
- function expandNodeByFor(node, scope) {
1106
+ function expandNodeByFor$1(node, scope) {
1036
1107
  const forExpression = node.attribs?.["wx:for"];
1037
1108
  if (!forExpression) return [{
1038
1109
  node,
1039
1110
  scope,
1040
1111
  instanceSuffix: ""
1041
1112
  }];
1042
- const list = resolveRawValueByPath(scope.data, forExpression);
1113
+ const list = resolveRawValueByPath$1(scope.data, forExpression);
1043
1114
  const items = Array.isArray(list) ? list : [];
1044
1115
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
1045
1116
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
1046
1117
  return items.map((item, index) => ({
1047
- node: cloneNode(node),
1048
- scope: createLoopScope(scope, itemName, indexName, item, index),
1118
+ node: cloneNode$1(node),
1119
+ scope: createLoopScope$1(scope, itemName, indexName, item, index),
1049
1120
  instanceSuffix: `:for-${index}`
1050
1121
  }));
1051
1122
  }
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));
1123
+ function renderNodeVariants$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1124
+ return expandNodeByFor$1(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree$1(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes));
1054
1125
  }
1055
- function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1126
+ function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1056
1127
  const renderedChildren = [];
1057
1128
  for (let index = 0; index < children.length; index += 1) {
1058
1129
  const child = children[index];
1059
- if (!isTagNode(child)) {
1060
- renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
1130
+ if (!isTagNode$1(child)) {
1131
+ renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
1061
1132
  continue;
1062
1133
  }
1063
1134
  const hasConditional = child.attribs?.["wx:if"] != null;
@@ -1067,37 +1138,37 @@ function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath,
1067
1138
  let cursor = index;
1068
1139
  while (cursor < children.length) {
1069
1140
  const branch = children[cursor];
1070
- if (cursor !== index && isIgnorableTextNode(branch)) {
1141
+ if (cursor !== index && isIgnorableTextNode$1(branch)) {
1071
1142
  cursor += 1;
1072
1143
  continue;
1073
1144
  }
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));
1145
+ if (!isTagNode$1(branch)) break;
1146
+ if (cursor !== index && !WX_ELSE_ATTRS$1.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
1147
+ if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch$1(branch, scope)) {
1148
+ renderedChildren.push(...renderNodeVariants$1(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes));
1078
1149
  branchMatched = true;
1079
1150
  }
1080
1151
  let nextBranchIndex = cursor + 1;
1081
- while (nextBranchIndex < children.length && isIgnorableTextNode(children[nextBranchIndex])) nextBranchIndex += 1;
1152
+ while (nextBranchIndex < children.length && isIgnorableTextNode$1(children[nextBranchIndex])) nextBranchIndex += 1;
1082
1153
  const nextBranch = children[nextBranchIndex];
1083
- if (!(!!nextBranch && isTagNode(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
1154
+ if (!(!!nextBranch && isTagNode$1(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
1084
1155
  cursor = nextBranchIndex;
1085
1156
  }
1086
1157
  index = cursor;
1087
1158
  continue;
1088
1159
  }
1089
1160
  if (isElseBranch) continue;
1090
- renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
1161
+ renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
1091
1162
  }
1092
1163
  return renderedChildren;
1093
1164
  }
1094
- function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1095
- const clonedNode = cloneNode(node);
1096
- if (!isTagNode(clonedNode)) {
1097
- applyNodeBindings(clonedNode, scope);
1165
+ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1166
+ const clonedNode = cloneNode$1(node);
1167
+ if (!isTagNode$1(clonedNode)) {
1168
+ applyNodeBindings$1(clonedNode, scope);
1098
1169
  return clonedNode;
1099
1170
  }
1100
- const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name);
1171
+ const componentEntry = resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, clonedNode.name);
1101
1172
  if (componentEntry) {
1102
1173
  const componentScopeId = `${instancePath}/${clonedNode.name}`;
1103
1174
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
@@ -1105,15 +1176,15 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
1105
1176
  const bindingExpressions = {};
1106
1177
  for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
1107
1178
  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);
1179
+ if (isMustacheOnly$1(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
1180
+ nextProperties[key] = resolveComponentAttributeValue$1(String(value), scope);
1110
1181
  }
1111
1182
  let componentInstance = context.componentCache.get(componentScopeId);
1112
1183
  if (!componentInstance) {
1113
1184
  componentInstance = createComponentInstance({
1114
1185
  definition: componentEntry.definition,
1115
1186
  properties: nextProperties,
1116
- triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
1187
+ triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
1117
1188
  });
1118
1189
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
1119
1190
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
@@ -1124,14 +1195,14 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
1124
1195
  runComponentLifecycle(componentInstance, "attached");
1125
1196
  runComponentPageLifetime(componentInstance, "show");
1126
1197
  context.componentCache.set(componentScopeId, componentInstance);
1127
- } else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
1198
+ } else syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
1128
1199
  seenComponentScopes.add(componentScopeId);
1129
1200
  const componentScope = {
1130
1201
  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),
1202
+ classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
1203
+ data: createMergedScopeData$1(scope.data, componentInstance.properties, componentInstance.data),
1204
+ dataset: collectDataset$3(clonedNode),
1205
+ eventBindings: collectComponentEventBindings$1(clonedNode),
1135
1206
  getMethod: (methodName) => {
1136
1207
  const method = componentInstance?.[methodName];
1137
1208
  return typeof method === "function" ? method : void 0;
@@ -1143,8 +1214,8 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
1143
1214
  ownerScopeId
1144
1215
  };
1145
1216
  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);
1217
+ const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, componentEntry.templatePath));
1218
+ const renderedComponentRoot = renderNodeTree$1((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes);
1148
1219
  if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
1149
1220
  if (!componentInstance.__ready__) {
1150
1221
  runComponentLifecycle(componentInstance, "ready");
@@ -1152,14 +1223,14 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
1152
1223
  }
1153
1224
  return renderedComponentRoot;
1154
1225
  }
1155
- applyNodeBindings(clonedNode, scope);
1156
- clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
1226
+ applyNodeBindings$1(clonedNode, scope);
1227
+ clonedNode.children = renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
1157
1228
  return clonedNode;
1158
1229
  }
1159
1230
  function renderBrowserPageTree(context, page) {
1160
- const route = page.route.replace(LEADING_SLASH_RE$4, "");
1231
+ const route = page.route.replace(LEADING_SLASH_RE$5, "");
1161
1232
  const templatePath = join(context.project.miniprogramRootPath, `${route}.wxml`);
1162
- const document = parseTemplateDocument(readTemplateSource(context.files, templatePath));
1233
+ const document = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
1163
1234
  const pageScopeId = `page:${route}`;
1164
1235
  const pageScope = {
1165
1236
  data: page.data,
@@ -1173,7 +1244,7 @@ function renderBrowserPageTree(context, page) {
1173
1244
  context.componentScopes.clear();
1174
1245
  context.componentScopes.set(pageScopeId, pageScope);
1175
1246
  const seenComponentScopes = /* @__PURE__ */ new Set();
1176
- const renderedRoot = renderNodeTree((document.children ?? [])[0] ?? document, pageScope, context, `${route}.json`, `${route}.js`, pageScopeId, seenComponentScopes);
1247
+ const renderedRoot = renderNodeTree$1((document.children ?? [])[0] ?? document, pageScope, context, `${route}.json`, `${route}.js`, pageScopeId, seenComponentScopes);
1177
1248
  for (const [scopeId, instance] of [...context.componentCache.entries()]) if (!seenComponentScopes.has(scopeId)) {
1178
1249
  runComponentLifecycle(instance, "detached");
1179
1250
  context.componentCache.delete(scopeId);
@@ -1181,7 +1252,7 @@ function renderBrowserPageTree(context, page) {
1181
1252
  }
1182
1253
  return {
1183
1254
  root: renderedRoot,
1184
- wxml: serializeDomNode$1(renderedRoot)
1255
+ wxml: serializeDomNode$2(renderedRoot)
1185
1256
  };
1186
1257
  }
1187
1258
  //#endregion
@@ -1420,6 +1491,12 @@ const DEFAULT_MODAL_CANCEL_COLOR = "#000000";
1420
1491
  const DEFAULT_MODAL_CANCEL_TEXT = "取消";
1421
1492
  const DEFAULT_MODAL_CONFIRM_COLOR = "#576B95";
1422
1493
  const DEFAULT_MODAL_CONFIRM_TEXT = "确定";
1494
+ const TRAILING_SLASH_RE = /\/+$/;
1495
+ const SAVED_FILE_PREFIXES = ["headless://saved/", "headless://wxfile/saved/"];
1496
+ const textEncoder = new TextEncoder();
1497
+ function byteLength(input) {
1498
+ return textEncoder.encode(input).byteLength;
1499
+ }
1423
1500
  function cloneShareMenuSnapshot(snapshot) {
1424
1501
  return {
1425
1502
  isUpdatableMessage: snapshot.isUpdatableMessage,
@@ -1469,15 +1546,113 @@ function resolveRequestResponse(mock, option) {
1469
1546
  statusCode: mock.statusCode ?? 200
1470
1547
  };
1471
1548
  }
1549
+ function matchesSimpleUrlMock(mock, url) {
1550
+ if (typeof mock.url === "string") return mock.url === url;
1551
+ mock.url.lastIndex = 0;
1552
+ return mock.url.test(url);
1553
+ }
1554
+ function resolveDownloadFileResponse(mock, option, tempFilePath) {
1555
+ return {
1556
+ fileContent: typeof mock.fileContent === "function" ? mock.fileContent(option) : mock.fileContent,
1557
+ result: {
1558
+ errMsg: "downloadFile:ok",
1559
+ statusCode: mock.statusCode ?? 200,
1560
+ tempFilePath
1561
+ }
1562
+ };
1563
+ }
1564
+ function resolveUploadFileResponse(mock, option, fileContent) {
1565
+ const rawResponse = typeof mock.response === "function" ? mock.response({
1566
+ ...option,
1567
+ fileContent
1568
+ }) : mock.response;
1569
+ if (typeof rawResponse === "string") return {
1570
+ data: rawResponse,
1571
+ errMsg: "uploadFile:ok",
1572
+ statusCode: mock.statusCode ?? 200
1573
+ };
1574
+ return {
1575
+ data: rawResponse.data == null ? "" : String(rawResponse.data),
1576
+ errMsg: rawResponse.errMsg ?? "uploadFile:ok",
1577
+ statusCode: rawResponse.statusCode ?? mock.statusCode ?? 200
1578
+ };
1579
+ }
1580
+ function normalizeDelay(delay) {
1581
+ return Number.isFinite(delay) ? Math.max(0, Math.trunc(delay ?? 0)) : 0;
1582
+ }
1583
+ function createNoopTask() {
1584
+ return { abort() {} };
1585
+ }
1586
+ function normalizeEncoding(encoding) {
1587
+ const normalized = (encoding ?? "utf8").trim().toLowerCase();
1588
+ if (normalized === "utf8" || normalized === "utf-8") return "utf8";
1589
+ throw new Error(`Unsupported file encoding in headless runtime: ${encoding}`);
1590
+ }
1591
+ function isSavedFilePath(path) {
1592
+ return SAVED_FILE_PREFIXES.some((prefix) => path === prefix.slice(0, -1) || path.startsWith(prefix));
1593
+ }
1594
+ function normalizeFsPath(input) {
1595
+ const trimmed = input.trim();
1596
+ if (!trimmed) throw new Error("File path must be a non-empty string in headless runtime.");
1597
+ if (trimmed.length > 1 && trimmed.endsWith("/")) return trimmed.replace(TRAILING_SLASH_RE, "");
1598
+ return trimmed;
1599
+ }
1600
+ function splitFsPath(input) {
1601
+ const normalized = normalizeFsPath(input);
1602
+ const schemeIndex = normalized.indexOf("://");
1603
+ if (schemeIndex >= 0) {
1604
+ const afterScheme = schemeIndex + 3;
1605
+ const firstSlash = normalized.indexOf("/", afterScheme);
1606
+ if (firstSlash < 0) return {
1607
+ prefix: normalized,
1608
+ segments: []
1609
+ };
1610
+ return {
1611
+ prefix: normalized.slice(0, firstSlash),
1612
+ segments: normalized.slice(firstSlash + 1).split("/").filter(Boolean)
1613
+ };
1614
+ }
1615
+ return {
1616
+ prefix: normalized.startsWith("/") ? "/" : "",
1617
+ segments: normalized.split("/").filter(Boolean)
1618
+ };
1619
+ }
1620
+ function joinFsPath(prefix, segments) {
1621
+ if (segments.length === 0) return prefix || ".";
1622
+ if (!prefix) return segments.join("/");
1623
+ if (prefix === "/") return `/${segments.join("/")}`;
1624
+ return `${prefix}/${segments.join("/")}`;
1625
+ }
1626
+ function listParentDirectories(input) {
1627
+ const { prefix, segments } = splitFsPath(input);
1628
+ const parents = [];
1629
+ if (segments.length === 0) {
1630
+ if (prefix && prefix !== "/") parents.push(prefix);
1631
+ return parents;
1632
+ }
1633
+ for (let index = 0; index < segments.length; index += 1) {
1634
+ const parentPath = joinFsPath(prefix, segments.slice(0, index));
1635
+ if (parentPath !== "." && parentPath !== "/") parents.push(parentPath);
1636
+ }
1637
+ return parents;
1638
+ }
1472
1639
  function createHeadlessWxState() {
1473
1640
  const actionSheetLogs = [];
1474
1641
  const actionSheetMocks = [];
1642
+ const downloadFileLogs = [];
1643
+ const downloadFileMocks = [];
1475
1644
  const modalLogs = [];
1476
1645
  const networkStatusChangeCallbacks = /* @__PURE__ */ new Set();
1477
1646
  const modalMocks = [];
1478
1647
  const requestLogs = [];
1479
1648
  const requestMocks = [];
1480
1649
  const storage = /* @__PURE__ */ new Map();
1650
+ const uploadFileLogs = [];
1651
+ const uploadFileMocks = [];
1652
+ const files = /* @__PURE__ */ new Map();
1653
+ const savedFiles = /* @__PURE__ */ new Map();
1654
+ const directories = /* @__PURE__ */ new Set();
1655
+ let fileId = 0;
1481
1656
  let loading = null;
1482
1657
  let networkType = "wifi";
1483
1658
  let shareMenu = {
@@ -1487,81 +1662,528 @@ function createHeadlessWxState() {
1487
1662
  withShareTicket: false
1488
1663
  };
1489
1664
  let toast = null;
1490
- return {
1491
- clearStorageSync() {
1492
- storage.clear();
1665
+ const allocateFilePath = (bucket, preferredPath) => {
1666
+ if (typeof preferredPath === "string" && preferredPath.trim()) return preferredPath.trim();
1667
+ fileId += 1;
1668
+ return `headless://wxfile/${bucket}/${String(fileId).padStart(4, "0")}`;
1669
+ };
1670
+ const runDelayedTask = (delay, onSuccess, onFail, abortMessage) => {
1671
+ if (delay <= 0) {
1672
+ onSuccess(void 0);
1673
+ return createNoopTask();
1674
+ }
1675
+ let completed = false;
1676
+ const timer = setTimeout(() => {
1677
+ if (completed) return;
1678
+ completed = true;
1679
+ onSuccess(void 0);
1680
+ }, delay);
1681
+ return { abort() {
1682
+ if (completed) return;
1683
+ completed = true;
1684
+ clearTimeout(timer);
1685
+ onFail(new Error(abortMessage));
1686
+ } };
1687
+ };
1688
+ const ensureDirectoryTree = (targetPath) => {
1689
+ for (const directoryPath of listParentDirectories(targetPath)) directories.add(directoryPath);
1690
+ };
1691
+ const createStats = (isDirectory, size) => ({
1692
+ isDirectory: () => isDirectory,
1693
+ isFile: () => !isDirectory,
1694
+ size
1695
+ });
1696
+ const updateSavedFileMetadata = (normalizedPath, fileContent) => {
1697
+ const savedFile = savedFiles.get(normalizedPath);
1698
+ if (!savedFile) return;
1699
+ savedFiles.set(normalizedPath, {
1700
+ ...savedFile,
1701
+ size: fileContent.length
1702
+ });
1703
+ };
1704
+ const setSavedFileMetadata = (normalizedPath, fileContent, createTime = Date.now()) => {
1705
+ savedFiles.set(normalizedPath, {
1706
+ createTime,
1707
+ filePath: normalizedPath,
1708
+ size: fileContent.length
1709
+ });
1710
+ };
1711
+ const accessFile = (filePath) => {
1712
+ const normalizedPath = normalizeFsPath(filePath);
1713
+ if (!files.has(normalizedPath) && !directories.has(normalizedPath)) throw new Error(`access:fail no such file or directory, access '${normalizedPath}'`);
1714
+ return { errMsg: "access:ok" };
1715
+ };
1716
+ const readFile = (filePath, encoding) => {
1717
+ normalizeEncoding(encoding);
1718
+ const normalizedPath = normalizeFsPath(filePath);
1719
+ const fileContent = files.get(normalizedPath);
1720
+ if (fileContent == null) throw new Error(`readFile:fail no such file or directory, open '${normalizedPath}'`);
1721
+ return {
1722
+ data: fileContent,
1723
+ errMsg: "readFile:ok"
1724
+ };
1725
+ };
1726
+ const writeFile = (filePath, data, encoding) => {
1727
+ const normalizedPath = normalizeFsPath(filePath);
1728
+ normalizeEncoding(encoding);
1729
+ ensureDirectoryTree(normalizedPath);
1730
+ const fileContent = String(data);
1731
+ files.set(normalizedPath, fileContent);
1732
+ updateSavedFileMetadata(normalizedPath, fileContent);
1733
+ return { errMsg: "writeFile:ok" };
1734
+ };
1735
+ const appendFile = (filePath, data, encoding) => {
1736
+ const normalizedPath = normalizeFsPath(filePath);
1737
+ normalizeEncoding(encoding);
1738
+ ensureDirectoryTree(normalizedPath);
1739
+ const nextFileContent = `${files.get(normalizedPath) ?? ""}${String(data)}`;
1740
+ files.set(normalizedPath, nextFileContent);
1741
+ updateSavedFileMetadata(normalizedPath, nextFileContent);
1742
+ return { errMsg: "appendFile:ok" };
1743
+ };
1744
+ const copyFile = (srcPath, destPath) => {
1745
+ const normalizedSrcPath = normalizeFsPath(srcPath);
1746
+ const normalizedDestPath = normalizeFsPath(destPath);
1747
+ const fileContent = files.get(normalizedSrcPath);
1748
+ if (fileContent == null) throw new Error(`copyFile:fail no such file or directory, copyfile '${normalizedSrcPath}'`);
1749
+ ensureDirectoryTree(normalizedDestPath);
1750
+ files.set(normalizedDestPath, fileContent);
1751
+ if (savedFiles.has(normalizedDestPath)) setSavedFileMetadata(normalizedDestPath, fileContent, savedFiles.get(normalizedDestPath)?.createTime ?? Date.now());
1752
+ return { errMsg: "copyFile:ok" };
1753
+ };
1754
+ const renameFile = (oldPath, newPath) => {
1755
+ const normalizedOldPath = normalizeFsPath(oldPath);
1756
+ const normalizedNewPath = normalizeFsPath(newPath);
1757
+ const fileContent = files.get(normalizedOldPath);
1758
+ if (fileContent == null) throw new Error(`rename:fail no such file or directory, rename '${normalizedOldPath}'`);
1759
+ const targetSavedFile = savedFiles.get(normalizedNewPath);
1760
+ files.delete(normalizedOldPath);
1761
+ const savedFile = savedFiles.get(normalizedOldPath);
1762
+ if (savedFile) savedFiles.delete(normalizedOldPath);
1763
+ ensureDirectoryTree(normalizedNewPath);
1764
+ files.set(normalizedNewPath, fileContent);
1765
+ if (savedFile && isSavedFilePath(normalizedNewPath)) savedFiles.set(normalizedNewPath, {
1766
+ ...savedFile,
1767
+ filePath: normalizedNewPath,
1768
+ size: fileContent.length
1769
+ });
1770
+ else if (targetSavedFile) savedFiles.set(normalizedNewPath, {
1771
+ ...targetSavedFile,
1772
+ size: fileContent.length
1773
+ });
1774
+ return { errMsg: "rename:ok" };
1775
+ };
1776
+ const unlinkFile = (filePath) => {
1777
+ const normalizedPath = normalizeFsPath(filePath);
1778
+ if (!files.has(normalizedPath)) throw new Error(`unlink:fail no such file or directory, unlink '${normalizedPath}'`);
1779
+ files.delete(normalizedPath);
1780
+ savedFiles.delete(normalizedPath);
1781
+ return { errMsg: "unlink:ok" };
1782
+ };
1783
+ const mkdir = (dirPath, recursive = false) => {
1784
+ const normalizedPath = normalizeFsPath(dirPath);
1785
+ if (!recursive) {
1786
+ const directParent = listParentDirectories(normalizedPath).at(-1);
1787
+ if (directParent && !directories.has(directParent)) throw new Error(`mkdir:fail no such file or directory, mkdir '${normalizedPath}'`);
1788
+ }
1789
+ for (const directoryPath of [...listParentDirectories(normalizedPath), normalizedPath]) directories.add(directoryPath);
1790
+ return { errMsg: "mkdir:ok" };
1791
+ };
1792
+ const readdir = (dirPath) => {
1793
+ const normalizedPath = normalizeFsPath(dirPath);
1794
+ if (!directories.has(normalizedPath)) throw new Error(`readdir:fail no such file or directory, scandir '${normalizedPath}'`);
1795
+ const { prefix, segments } = splitFsPath(normalizedPath);
1796
+ const baseDepth = segments.length;
1797
+ const entries = /* @__PURE__ */ new Set();
1798
+ for (const directoryPath of directories) {
1799
+ if (directoryPath === normalizedPath) continue;
1800
+ const current = splitFsPath(directoryPath);
1801
+ if (current.prefix !== prefix || current.segments.length <= baseDepth) continue;
1802
+ if (current.segments.slice(0, baseDepth).join("/") !== segments.join("/")) continue;
1803
+ entries.add(current.segments[baseDepth]);
1804
+ }
1805
+ for (const filePath of files.keys()) {
1806
+ const current = splitFsPath(filePath);
1807
+ if (current.prefix !== prefix || current.segments.length <= baseDepth) continue;
1808
+ if (current.segments.slice(0, baseDepth).join("/") !== segments.join("/")) continue;
1809
+ entries.add(current.segments[baseDepth]);
1810
+ }
1811
+ return {
1812
+ errMsg: "readdir:ok",
1813
+ files: Array.from(entries).sort((a, b) => a.localeCompare(b))
1814
+ };
1815
+ };
1816
+ const rmdir = (dirPath, recursive = false) => {
1817
+ const normalizedPath = normalizeFsPath(dirPath);
1818
+ if (files.has(normalizedPath)) throw new Error(`rmdir:fail not a directory, rmdir '${normalizedPath}'`);
1819
+ if (!directories.has(normalizedPath)) throw new Error(`rmdir:fail no such file or directory, rmdir '${normalizedPath}'`);
1820
+ const childDirectoryPaths = Array.from(directories).filter((currentPath) => currentPath !== normalizedPath && currentPath.startsWith(`${normalizedPath}/`));
1821
+ const childFilePaths = Array.from(files.keys()).filter((currentPath) => currentPath.startsWith(`${normalizedPath}/`));
1822
+ if (!recursive && (childDirectoryPaths.length > 0 || childFilePaths.length > 0)) throw new Error(`rmdir:fail directory not empty, rmdir '${normalizedPath}'`);
1823
+ directories.delete(normalizedPath);
1824
+ childDirectoryPaths.forEach((currentPath) => directories.delete(currentPath));
1825
+ childFilePaths.forEach((currentPath) => {
1826
+ files.delete(currentPath);
1827
+ savedFiles.delete(currentPath);
1828
+ });
1829
+ return { errMsg: "rmdir:ok" };
1830
+ };
1831
+ const stat = (inputPath) => {
1832
+ const normalizedPath = normalizeFsPath(inputPath);
1833
+ if (files.has(normalizedPath)) return {
1834
+ errMsg: "stat:ok",
1835
+ stats: createStats(false, files.get(normalizedPath)?.length ?? 0)
1836
+ };
1837
+ if (directories.has(normalizedPath)) return {
1838
+ errMsg: "stat:ok",
1839
+ stats: createStats(true, 0)
1840
+ };
1841
+ throw new Error(`stat:fail no such file or directory, stat '${normalizedPath}'`);
1842
+ };
1843
+ const getSavedFileList = () => {
1844
+ return {
1845
+ errMsg: "getSavedFileList:ok",
1846
+ fileList: Array.from(savedFiles.values()).map((item) => ({ ...item })).sort((a, b) => a.filePath.localeCompare(b.filePath))
1847
+ };
1848
+ };
1849
+ const getSavedFileInfo = (filePath) => {
1850
+ const normalizedPath = normalizeFsPath(filePath);
1851
+ const savedFile = savedFiles.get(normalizedPath);
1852
+ if (!savedFile) throw new Error(`getSavedFileInfo:fail no such file or directory, stat '${normalizedPath}'`);
1853
+ return {
1854
+ createTime: savedFile.createTime,
1855
+ errMsg: "getSavedFileInfo:ok",
1856
+ size: savedFile.size
1857
+ };
1858
+ };
1859
+ const removeSavedFile = (filePath) => {
1860
+ const normalizedPath = normalizeFsPath(filePath);
1861
+ if (!savedFiles.has(normalizedPath)) throw new Error(`removeSavedFile:fail no such file or directory, unlink '${normalizedPath}'`);
1862
+ savedFiles.delete(normalizedPath);
1863
+ files.delete(normalizedPath);
1864
+ return { errMsg: "removeSavedFile:ok" };
1865
+ };
1866
+ const fileSystemManager = {
1867
+ access(option) {
1868
+ try {
1869
+ const result = accessFile(option.path);
1870
+ option.success?.(result);
1871
+ option.complete?.(result);
1872
+ return result;
1873
+ } catch (error) {
1874
+ option.fail?.(error);
1875
+ option.complete?.();
1876
+ return;
1877
+ }
1493
1878
  },
1494
- getActionSheetLogs() {
1495
- return actionSheetLogs.map((entry) => ({
1496
- ...entry,
1497
- itemList: [...entry.itemList],
1498
- result: entry.result ? { ...entry.result } : void 0
1499
- }));
1879
+ accessSync(path) {
1880
+ accessFile(path);
1500
1881
  },
1501
- getNetworkType() {
1502
- return {
1503
- errMsg: "getNetworkType:ok",
1504
- networkType
1505
- };
1882
+ appendFile(option) {
1883
+ try {
1884
+ const result = appendFile(option.filePath, option.data, option.encoding);
1885
+ option.success?.(result);
1886
+ option.complete?.(result);
1887
+ return result;
1888
+ } catch (error) {
1889
+ option.fail?.(error);
1890
+ option.complete?.();
1891
+ return;
1892
+ }
1506
1893
  },
1507
- getModalLogs() {
1508
- return modalLogs.map((entry) => ({
1509
- ...entry,
1510
- result: { ...entry.result }
1511
- }));
1894
+ appendFileSync(filePath, data, encoding) {
1895
+ appendFile(filePath, data, encoding);
1512
1896
  },
1513
- getRequestLogs() {
1514
- return requestLogs.map((entry) => ({
1515
- ...entry,
1516
- data: cloneValue$1(entry.data),
1517
- header: { ...entry.header },
1518
- response: entry.response ? {
1519
- ...entry.response,
1520
- cookies: [...entry.response.cookies],
1521
- data: cloneValue$1(entry.response.data),
1522
- header: { ...entry.response.header }
1523
- } : void 0
1524
- }));
1897
+ copyFile(option) {
1898
+ try {
1899
+ const result = copyFile(option.srcPath, option.destPath);
1900
+ option.success?.(result);
1901
+ option.complete?.(result);
1902
+ return result;
1903
+ } catch (error) {
1904
+ option.fail?.(error);
1905
+ option.complete?.();
1906
+ return;
1907
+ }
1525
1908
  },
1526
- getStorageInfoSync() {
1527
- const keys = Array.from(storage.keys()).sort((a, b) => a.localeCompare(b));
1528
- const totalBytes = Array.from(storage.entries()).reduce((sum, [key, value]) => {
1529
- return sum + Buffer.byteLength(JSON.stringify([key, value]));
1530
- }, 0);
1531
- return {
1532
- currentSize: Math.ceil(totalBytes / 1024),
1533
- errMsg: "getStorageInfo:ok",
1534
- keys,
1535
- limitSize: STORAGE_LIMIT_SIZE
1536
- };
1909
+ copyFileSync(srcPath, destPath) {
1910
+ copyFile(srcPath, destPath);
1537
1911
  },
1538
- getStorageSnapshot() {
1539
- return Object.fromEntries(Array.from(storage.entries(), ([key, value]) => [key, cloneValue$1(value)]));
1912
+ mkdir(option) {
1913
+ try {
1914
+ const result = mkdir(option.dirPath, option.recursive);
1915
+ option.success?.(result);
1916
+ option.complete?.(result);
1917
+ return result;
1918
+ } catch (error) {
1919
+ option.fail?.(error);
1920
+ option.complete?.();
1921
+ return;
1922
+ }
1540
1923
  },
1541
- getStorageSync(key) {
1542
- return cloneValue$1(storage.get(key));
1924
+ mkdirSync(dirPath, recursive) {
1925
+ mkdir(dirPath, recursive);
1543
1926
  },
1544
- getShareMenu() {
1545
- return cloneShareMenuSnapshot(shareMenu);
1927
+ readFile(option) {
1928
+ try {
1929
+ const result = readFile(option.filePath, option.encoding);
1930
+ option.success?.(result);
1931
+ option.complete?.(result);
1932
+ return result;
1933
+ } catch (error) {
1934
+ option.fail?.(error);
1935
+ option.complete?.();
1936
+ return;
1937
+ }
1546
1938
  },
1547
- getLoading() {
1548
- return loading ? { ...loading } : null;
1939
+ readFileSync(filePath, encoding) {
1940
+ return readFile(filePath, encoding).data;
1549
1941
  },
1550
- hideShareMenu() {
1551
- shareMenu = {
1552
- ...shareMenu,
1553
- visible: false
1554
- };
1555
- return { errMsg: "hideShareMenu:ok" };
1942
+ readdir(option) {
1943
+ try {
1944
+ const result = readdir(option.dirPath);
1945
+ option.success?.(result);
1946
+ option.complete?.(result);
1947
+ return result;
1948
+ } catch (error) {
1949
+ option.fail?.(error);
1950
+ option.complete?.();
1951
+ return;
1952
+ }
1556
1953
  },
1557
- getToast() {
1558
- return toast ? { ...toast } : null;
1954
+ readdirSync(dirPath) {
1955
+ return readdir(dirPath).files;
1559
1956
  },
1560
- hideLoading() {
1561
- loading = null;
1562
- return { errMsg: "hideLoading:ok" };
1957
+ rmdir(option) {
1958
+ try {
1959
+ const result = rmdir(option.dirPath, option.recursive);
1960
+ option.success?.(result);
1961
+ option.complete?.(result);
1962
+ return result;
1963
+ } catch (error) {
1964
+ option.fail?.(error);
1965
+ option.complete?.();
1966
+ return;
1967
+ }
1563
1968
  },
1564
- hideToast() {
1969
+ rmdirSync(dirPath, recursive) {
1970
+ rmdir(dirPath, recursive);
1971
+ },
1972
+ rename(option) {
1973
+ try {
1974
+ const result = renameFile(option.oldPath, option.newPath);
1975
+ option.success?.(result);
1976
+ option.complete?.(result);
1977
+ return result;
1978
+ } catch (error) {
1979
+ option.fail?.(error);
1980
+ option.complete?.();
1981
+ return;
1982
+ }
1983
+ },
1984
+ renameSync(oldPath, newPath) {
1985
+ renameFile(oldPath, newPath);
1986
+ },
1987
+ stat(option) {
1988
+ try {
1989
+ const result = stat(option.path);
1990
+ option.success?.(result);
1991
+ option.complete?.(result);
1992
+ return result;
1993
+ } catch (error) {
1994
+ option.fail?.(error);
1995
+ option.complete?.();
1996
+ return;
1997
+ }
1998
+ },
1999
+ statSync(path) {
2000
+ return stat(path).stats;
2001
+ },
2002
+ unlink(option) {
2003
+ try {
2004
+ const result = unlinkFile(option.filePath);
2005
+ option.success?.(result);
2006
+ option.complete?.(result);
2007
+ return result;
2008
+ } catch (error) {
2009
+ option.fail?.(error);
2010
+ option.complete?.();
2011
+ return;
2012
+ }
2013
+ },
2014
+ unlinkSync(filePath) {
2015
+ unlinkFile(filePath);
2016
+ },
2017
+ writeFile(option) {
2018
+ try {
2019
+ const result = writeFile(option.filePath, option.data, option.encoding);
2020
+ option.success?.(result);
2021
+ option.complete?.(result);
2022
+ return result;
2023
+ } catch (error) {
2024
+ option.fail?.(error);
2025
+ option.complete?.();
2026
+ return;
2027
+ }
2028
+ },
2029
+ writeFileSync(filePath, data, encoding) {
2030
+ writeFile(filePath, data, encoding);
2031
+ }
2032
+ };
2033
+ return {
2034
+ clearStorageSync() {
2035
+ storage.clear();
2036
+ },
2037
+ downloadFile(option) {
2038
+ const matchedMock = downloadFileMocks.find((mock) => matchesSimpleUrlMock(mock, option.url));
2039
+ if (!matchedMock) {
2040
+ const logEntry = {
2041
+ header: { ...option.header ?? {} },
2042
+ matched: false,
2043
+ url: option.url
2044
+ };
2045
+ downloadFileLogs.push(logEntry);
2046
+ const error = /* @__PURE__ */ new Error(`No downloadFile mock matched in headless runtime: ${option.url}`);
2047
+ option.fail?.(error);
2048
+ option.complete?.();
2049
+ return createNoopTask();
2050
+ }
2051
+ const tempFilePath = allocateFilePath("temp", option.filePath);
2052
+ const delay = normalizeDelay(matchedMock.delay);
2053
+ const logEntry = {
2054
+ header: { ...option.header ?? {} },
2055
+ matched: true,
2056
+ response: {
2057
+ errMsg: "downloadFile:ok",
2058
+ statusCode: matchedMock.statusCode ?? 200,
2059
+ tempFilePath
2060
+ },
2061
+ tempFilePath,
2062
+ url: option.url
2063
+ };
2064
+ const commit = () => {
2065
+ const { fileContent, result } = resolveDownloadFileResponse(matchedMock, option, tempFilePath);
2066
+ ensureDirectoryTree(tempFilePath);
2067
+ files.set(tempFilePath, fileContent);
2068
+ logEntry.response = { ...result };
2069
+ downloadFileLogs.push(logEntry);
2070
+ option.success?.(result);
2071
+ option.complete?.(result);
2072
+ };
2073
+ const fail = (error) => {
2074
+ option.fail?.(error);
2075
+ option.complete?.();
2076
+ };
2077
+ if (delay <= 0) {
2078
+ commit();
2079
+ return createNoopTask();
2080
+ }
2081
+ return runDelayedTask(delay, commit, fail, "downloadFile:fail abort");
2082
+ },
2083
+ getActionSheetLogs() {
2084
+ return actionSheetLogs.map((entry) => ({
2085
+ ...entry,
2086
+ itemList: [...entry.itemList],
2087
+ result: entry.result ? { ...entry.result } : void 0
2088
+ }));
2089
+ },
2090
+ getDownloadFileLogs() {
2091
+ return downloadFileLogs.map((entry) => ({
2092
+ ...entry,
2093
+ header: { ...entry.header },
2094
+ response: entry.response ? { ...entry.response } : void 0
2095
+ }));
2096
+ },
2097
+ getFileSnapshot() {
2098
+ return Object.fromEntries(files.entries());
2099
+ },
2100
+ getDirectorySnapshot() {
2101
+ return Array.from(directories.values()).sort((a, b) => a.localeCompare(b));
2102
+ },
2103
+ getFileSystemManager() {
2104
+ return fileSystemManager;
2105
+ },
2106
+ getSavedFileInfo(option) {
2107
+ return getSavedFileInfo(option.filePath);
2108
+ },
2109
+ getSavedFileList() {
2110
+ return getSavedFileList();
2111
+ },
2112
+ getFileText(filePath) {
2113
+ return files.get(filePath) ?? null;
2114
+ },
2115
+ getNetworkType() {
2116
+ return {
2117
+ errMsg: "getNetworkType:ok",
2118
+ networkType
2119
+ };
2120
+ },
2121
+ getModalLogs() {
2122
+ return modalLogs.map((entry) => ({
2123
+ ...entry,
2124
+ result: { ...entry.result }
2125
+ }));
2126
+ },
2127
+ getRequestLogs() {
2128
+ return requestLogs.map((entry) => ({
2129
+ ...entry,
2130
+ data: cloneValue$1(entry.data),
2131
+ header: { ...entry.header },
2132
+ response: entry.response ? {
2133
+ ...entry.response,
2134
+ cookies: [...entry.response.cookies],
2135
+ data: cloneValue$1(entry.response.data),
2136
+ header: { ...entry.response.header }
2137
+ } : void 0
2138
+ }));
2139
+ },
2140
+ getStorageInfoSync() {
2141
+ const keys = Array.from(storage.keys()).sort((a, b) => a.localeCompare(b));
2142
+ const totalBytes = Array.from(storage.entries()).reduce((sum, [key, value]) => {
2143
+ return sum + byteLength(JSON.stringify([key, value]));
2144
+ }, 0);
2145
+ return {
2146
+ currentSize: Math.ceil(totalBytes / 1024),
2147
+ errMsg: "getStorageInfo:ok",
2148
+ keys,
2149
+ limitSize: STORAGE_LIMIT_SIZE
2150
+ };
2151
+ },
2152
+ getStorageSnapshot() {
2153
+ return Object.fromEntries(Array.from(storage.entries(), ([key, value]) => [key, cloneValue$1(value)]));
2154
+ },
2155
+ getStorageSync(key) {
2156
+ return cloneValue$1(storage.get(key));
2157
+ },
2158
+ getShareMenu() {
2159
+ return cloneShareMenuSnapshot(shareMenu);
2160
+ },
2161
+ getLoading() {
2162
+ return loading ? { ...loading } : null;
2163
+ },
2164
+ hideShareMenu() {
2165
+ shareMenu = {
2166
+ ...shareMenu,
2167
+ visible: false
2168
+ };
2169
+ return { errMsg: "hideShareMenu:ok" };
2170
+ },
2171
+ getToast() {
2172
+ return toast ? { ...toast } : null;
2173
+ },
2174
+ getUploadFileLogs() {
2175
+ return uploadFileLogs.map((entry) => ({
2176
+ ...entry,
2177
+ formData: cloneValue$1(entry.formData),
2178
+ header: { ...entry.header },
2179
+ response: entry.response ? { ...entry.response } : void 0
2180
+ }));
2181
+ },
2182
+ hideLoading() {
2183
+ loading = null;
2184
+ return { errMsg: "hideLoading:ok" };
2185
+ },
2186
+ hideToast() {
1565
2187
  toast = null;
1566
2188
  return { errMsg: "hideToast:ok" };
1567
2189
  },
@@ -1579,12 +2201,26 @@ function createHeadlessWxState() {
1579
2201
  header: definition.header ? { ...definition.header } : void 0
1580
2202
  });
1581
2203
  },
2204
+ mockDownloadFile(definition) {
2205
+ downloadFileMocks.push({
2206
+ ...definition,
2207
+ delay: definition.delay,
2208
+ header: definition.header ? { ...definition.header } : void 0
2209
+ });
2210
+ },
1582
2211
  mockModal(definition = {}) {
1583
2212
  modalMocks.push({
1584
2213
  cancel: definition.cancel,
1585
2214
  confirm: definition.confirm
1586
2215
  });
1587
2216
  },
2217
+ mockUploadFile(definition) {
2218
+ uploadFileMocks.push({
2219
+ ...definition,
2220
+ delay: definition.delay,
2221
+ header: definition.header ? { ...definition.header } : void 0
2222
+ });
2223
+ },
1588
2224
  mockActionSheet(definition = {}) {
1589
2225
  actionSheetMocks.push({
1590
2226
  cancel: definition.cancel,
@@ -1611,7 +2247,7 @@ function createHeadlessWxState() {
1611
2247
  const error = /* @__PURE__ */ new Error(`No request mock matched in headless runtime: ${normalizeMethod(option.method)} ${option.url}`);
1612
2248
  option.fail?.(error);
1613
2249
  option.complete?.();
1614
- return { abort() {} };
2250
+ return createNoopTask();
1615
2251
  }
1616
2252
  const response = resolveRequestResponse(matchedMock, option);
1617
2253
  const requestLogEntry = {
@@ -1627,28 +2263,40 @@ function createHeadlessWxState() {
1627
2263
  requestLogs.push(requestLogEntry);
1628
2264
  option.success?.(response);
1629
2265
  option.complete?.(response);
1630
- return { abort() {} };
2266
+ return createNoopTask();
1631
2267
  }
1632
- let completed = false;
1633
- const timer = setTimeout(() => {
1634
- if (completed) return;
1635
- completed = true;
2268
+ return runDelayedTask(delay, () => {
1636
2269
  requestLogs.push(requestLogEntry);
1637
2270
  option.success?.(response);
1638
2271
  option.complete?.(response);
1639
- }, delay);
1640
- return { abort() {
1641
- if (completed) return;
1642
- completed = true;
1643
- clearTimeout(timer);
1644
- const error = /* @__PURE__ */ new Error("request:fail abort");
2272
+ }, (error) => {
1645
2273
  option.fail?.(error);
1646
2274
  option.complete?.();
1647
- } };
2275
+ }, "request:fail abort");
2276
+ },
2277
+ removeSavedFile(option) {
2278
+ return removeSavedFile(option.filePath);
2279
+ },
2280
+ saveFile(option) {
2281
+ const fileContent = files.get(option.tempFilePath);
2282
+ if (fileContent == null) throw new Error(`saveFile:fail tempFilePath not found: ${option.tempFilePath}`);
2283
+ const savedFilePath = allocateFilePath("saved", option.filePath);
2284
+ ensureDirectoryTree(savedFilePath);
2285
+ files.set(savedFilePath, fileContent);
2286
+ setSavedFileMetadata(savedFilePath, fileContent, savedFiles.get(savedFilePath)?.createTime ?? Date.now());
2287
+ return {
2288
+ errMsg: "saveFile:ok",
2289
+ savedFilePath
2290
+ };
1648
2291
  },
1649
2292
  setStorageSync(key, value) {
1650
2293
  storage.set(key, cloneValue$1(value));
1651
2294
  },
2295
+ setFile(filePath, fileContent) {
2296
+ const normalizedPath = normalizeFsPath(filePath);
2297
+ ensureDirectoryTree(normalizedPath);
2298
+ files.set(normalizedPath, fileContent);
2299
+ },
1652
2300
  setNetworkType(nextNetworkType) {
1653
2301
  networkType = nextNetworkType;
1654
2302
  const snapshot = createNetworkSnapshot(networkType);
@@ -1730,6 +2378,50 @@ function createHeadlessWxState() {
1730
2378
  };
1731
2379
  return { errMsg: "showToast:ok" };
1732
2380
  },
2381
+ uploadFile(option) {
2382
+ const fileContent = files.get(option.filePath);
2383
+ if (fileContent == null) {
2384
+ const error = /* @__PURE__ */ new Error(`uploadFile:fail file not found: ${option.filePath}`);
2385
+ option.fail?.(error);
2386
+ option.complete?.();
2387
+ return createNoopTask();
2388
+ }
2389
+ const matchedMock = uploadFileMocks.find((mock) => matchesSimpleUrlMock(mock, option.url));
2390
+ const logEntry = {
2391
+ fileContent,
2392
+ fileName: option.fileName,
2393
+ filePath: option.filePath,
2394
+ formData: cloneValue$1(option.formData ?? {}),
2395
+ header: { ...option.header ?? {} },
2396
+ matched: Boolean(matchedMock),
2397
+ name: option.name,
2398
+ url: option.url
2399
+ };
2400
+ if (!matchedMock) {
2401
+ uploadFileLogs.push(logEntry);
2402
+ const error = /* @__PURE__ */ new Error(`No uploadFile mock matched in headless runtime: ${option.url}`);
2403
+ option.fail?.(error);
2404
+ option.complete?.();
2405
+ return createNoopTask();
2406
+ }
2407
+ const response = resolveUploadFileResponse(matchedMock, option, fileContent);
2408
+ const delay = normalizeDelay(matchedMock.delay);
2409
+ const commit = () => {
2410
+ logEntry.response = { ...response };
2411
+ uploadFileLogs.push(logEntry);
2412
+ option.success?.(response);
2413
+ option.complete?.(response);
2414
+ };
2415
+ const fail = (error) => {
2416
+ option.fail?.(error);
2417
+ option.complete?.();
2418
+ };
2419
+ if (delay <= 0) {
2420
+ commit();
2421
+ return createNoopTask();
2422
+ }
2423
+ return runDelayedTask(delay, commit, fail, "uploadFile:fail abort");
2424
+ },
1733
2425
  updateShareMenu(option = {}) {
1734
2426
  shareMenu = {
1735
2427
  isUpdatableMessage: option.isUpdatableMessage == null ? shareMenu.isUpdatableMessage : Boolean(option.isUpdatableMessage),
@@ -1742,500 +2434,990 @@ function createHeadlessWxState() {
1742
2434
  };
1743
2435
  }
1744
2436
  //#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, "");
1752
- }
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;
2437
+ //#region src/view/selectors.ts
2438
+ const WHITESPACE_RE = /\s+/;
2439
+ const DATA_ATTR_SELECTOR_RE$2 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
2440
+ function getClassList(node) {
2441
+ return String(node.attribs?.class ?? "").split(WHITESPACE_RE).map((item) => item.trim()).filter(Boolean);
1758
2442
  }
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("#");
1764
- return {
1765
- pathname: pathname || "",
1766
- query: normalizeQuery$1(queryString)
1767
- };
2443
+ function matchesSimpleSelector(node, selector) {
2444
+ if (node.type !== "tag") return false;
2445
+ if (selector === "page") return node.name === "page";
2446
+ if (selector.startsWith("#")) return node.attribs?.id === selector.slice(1);
2447
+ if (selector.startsWith(".")) return getClassList(node).includes(selector.slice(1));
2448
+ const dataAttrMatch = selector.match(DATA_ATTR_SELECTOR_RE$2);
2449
+ if (dataAttrMatch) {
2450
+ const [, key, value] = dataAttrMatch;
2451
+ return node.attribs?.[`data-${key}`] === value;
2452
+ }
2453
+ return node.name === selector;
1768
2454
  }
1769
- function createAppLaunchOptions$1(pathname, query) {
1770
- return {
1771
- path: stripLeadingSlash$1(pathname),
1772
- query: { ...query },
1773
- referrerInfo: {
1774
- appId: "",
1775
- extraData: {}
1776
- },
1777
- scene: 1001
1778
- };
2455
+ function collectDescendants(node, into) {
2456
+ for (const child of node.children ?? []) {
2457
+ into.push(child);
2458
+ collectDescendants(child, into);
2459
+ }
1779
2460
  }
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;
2461
+ function querySelectorAll(root, selector) {
2462
+ const parts = selector.trim().split(WHITESPACE_RE).filter(Boolean);
2463
+ if (parts.length === 0) return [];
2464
+ let current = [root];
2465
+ for (const part of parts) {
2466
+ const next = [];
2467
+ for (const node of current) {
2468
+ const candidates = [];
2469
+ if (part === "page" && node.type === "tag" && node.name === "page") candidates.push(node);
2470
+ collectDescendants(node, candidates);
2471
+ for (const candidate of candidates) if (matchesSimpleSelector(candidate, part)) next.push(candidate);
2472
+ }
2473
+ current = next;
1788
2474
  }
2475
+ return current;
1789
2476
  }
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, "");
2477
+ //#endregion
2478
+ //#region src/view/nodeHandle.ts
2479
+ const DATASET_NAME_RE$2 = /-([a-z])/g;
2480
+ function escapeText$2(text) {
2481
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1795
2482
  }
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();
1820
- const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
1821
- this.tabBarRoutes = /* @__PURE__ */ new Set();
1822
- rawTabBarList.forEach((item, index) => {
1823
- if (typeof item?.pagePath !== "string") return;
1824
- const pagePath = stripLeadingSlash$1(item.pagePath);
1825
- if (!pagePath) return;
1826
- this.tabBarRoutes.add(pagePath);
1827
- this.tabBarItems.set(pagePath, {
1828
- index,
1829
- pagePath,
1830
- text: typeof item.text === "string" ? item.text : void 0
1831
- });
1832
- this.tabBarState.set(index, {
1833
- badge: null,
1834
- index,
1835
- pagePath,
1836
- redDot: false,
1837
- text: typeof item.text === "string" ? item.text : void 0
1838
- });
1839
- });
1840
- this.tabBarVisible = this.tabBarRoutes.size > 0;
1841
- this.moduleLoader = createBrowserModuleLoader(this.files, this.registries, () => this.pages.slice(), () => this.getApp(), {
1842
- getEnterOptionsSync: () => ({
1843
- ...this.enterOptions,
1844
- query: { ...this.enterOptions.query },
1845
- referrerInfo: {
1846
- ...this.enterOptions.referrerInfo,
1847
- extraData: { ...this.enterOptions.referrerInfo.extraData }
1848
- }
1849
- }),
1850
- getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
1851
- getLaunchOptionsSync: () => ({
1852
- ...this.launchOptions,
1853
- query: { ...this.launchOptions.query },
1854
- referrerInfo: {
1855
- ...this.launchOptions.referrerInfo,
1856
- extraData: { ...this.launchOptions.referrerInfo.extraData }
1857
- }
1858
- }),
1859
- getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
1860
- getNetworkType: () => this.wxState.getNetworkType(),
1861
- navigateBack: (option) => this.navigateBack(option?.delta),
1862
- navigateTo: (option) => this.navigateTo(option.url),
1863
- pageScrollTo: (option) => this.pageScrollTo(option),
1864
- clearStorageSync: () => this.wxState.clearStorageSync(),
1865
- getStorageInfoSync: () => this.wxState.getStorageInfoSync(),
1866
- getStorageSync: (key) => this.wxState.getStorageSync(key),
1867
- getSystemInfoSync: () => ({ ...this.systemInfo }),
1868
- getWindowInfoSync: () => deriveWindowInfo(this.systemInfo),
1869
- hideLoading: () => this.wxState.hideLoading(),
1870
- hideToast: () => this.wxState.hideToast(),
1871
- reLaunch: (option) => this.reLaunch(option.url),
1872
- redirectTo: (option) => this.redirectTo(option.url),
1873
- nextTick: (callback) => queueMicrotask(() => callback?.()),
1874
- offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
1875
- onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
1876
- removeStorageSync: (key) => this.wxState.removeStorageSync(key),
1877
- request: (option) => this.wxState.request(option),
1878
- setBackgroundColor: (option) => this.setBackgroundColor(option),
1879
- setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
1880
- setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
1881
- setNavigationBarColor: (option) => this.setNavigationBarColor(option),
1882
- setNavigationBarTitle: (option) => this.setNavigationBarTitle(option.title),
1883
- hideShareMenu: () => this.wxState.hideShareMenu(),
1884
- hideNavigationBarLoading: () => this.hideNavigationBarLoading(),
1885
- hideTabBar: () => this.hideTabBar(),
1886
- hideTabBarRedDot: (option) => this.hideTabBarRedDot(option.index),
1887
- showShareMenu: (option) => this.wxState.showShareMenu(option),
1888
- showNavigationBarLoading: () => this.showNavigationBarLoading(),
1889
- showTabBar: () => this.showTabBar(),
1890
- showTabBarRedDot: (option) => this.showTabBarRedDot(option.index),
1891
- showActionSheet: (option) => this.wxState.showActionSheet(option),
1892
- showLoading: (option) => this.wxState.showLoading(option),
1893
- showModal: (option) => this.wxState.showModal(option),
1894
- showToast: (option) => this.wxState.showToast(option),
1895
- stopPullDownRefresh: () => this.stopPullDownRefresh(),
1896
- switchTab: (option) => this.switchTab(option.url),
1897
- removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
1898
- setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
1899
- updateShareMenu: (option) => this.wxState.updateShareMenu(option)
1900
- });
1901
- }
1902
- getApp() {
1903
- return this.appInstance;
2483
+ function toDatasetKey$2(attributeName) {
2484
+ return attributeName.slice(5).replace(DATASET_NAME_RE$2, (_match, char) => char.toUpperCase());
2485
+ }
2486
+ function collectDataset$2(node) {
2487
+ const dataset = {};
2488
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
2489
+ if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
2490
+ dataset[toDatasetKey$2(key)] = value;
1904
2491
  }
1905
- getCurrentPages() {
1906
- return this.pages.slice();
2492
+ return dataset;
2493
+ }
2494
+ function resolveEventBinding(node, eventName) {
2495
+ const normalizedEventName = eventName.trim();
2496
+ if (!normalizedEventName) return null;
2497
+ const bindingAttrs = [
2498
+ `bind${normalizedEventName}`,
2499
+ `bind:${normalizedEventName}`,
2500
+ `catch${normalizedEventName}`,
2501
+ `catch:${normalizedEventName}`
2502
+ ];
2503
+ for (const attributeName of bindingAttrs) {
2504
+ const methodName = node.attribs?.[attributeName]?.trim();
2505
+ if (methodName) return methodName;
1907
2506
  }
1908
- getCurrentPageNavigationBarTitle() {
1909
- return this.currentPageInstance?.__navigationBarTitle__ ?? null;
2507
+ return null;
2508
+ }
2509
+ function createEventPayload(node, eventName, event) {
2510
+ const dataset = collectDataset$2(node);
2511
+ const nodeId = node.attribs?.id ?? "";
2512
+ return {
2513
+ bubbles: false,
2514
+ capturePhase: false,
2515
+ composed: false,
2516
+ currentTarget: {
2517
+ dataset: event.currentTarget?.dataset ?? event.dataset ?? dataset,
2518
+ id: event.currentTarget?.id ?? event.id ?? nodeId
2519
+ },
2520
+ detail: event.detail,
2521
+ mark: event.mark,
2522
+ target: {
2523
+ dataset: event.target?.dataset ?? event.dataset ?? dataset,
2524
+ id: event.target?.id ?? event.id ?? nodeId
2525
+ },
2526
+ type: eventName
2527
+ };
2528
+ }
2529
+ function createValueEventDetail(value, detail) {
2530
+ return {
2531
+ value,
2532
+ ...detail ?? {}
2533
+ };
2534
+ }
2535
+ function escapeAttribute$2(value) {
2536
+ return escapeText$2(value).replaceAll("\"", "&quot;");
2537
+ }
2538
+ function serializeNode(node) {
2539
+ if (node.type === "text") return escapeText$2(node.data ?? "");
2540
+ if (node.type !== "tag") return (node.children ?? []).map(serializeNode).join("");
2541
+ if (node.name === "page") return (node.children ?? []).filter((child) => !(child.type === "tag" && (child.name === "import" || child.name === "wxs"))).map(serializeNode).join("");
2542
+ const attrs = Object.entries(node.attribs ?? {}).filter(([key]) => !key.startsWith("data-sim-")).map(([key, value]) => ` ${key}="${escapeAttribute$2(value)}"`).join("");
2543
+ const children = (node.children ?? []).map(serializeNode).join("");
2544
+ return `<${node.name ?? ""}${attrs}>${children}</${node.name ?? ""}>`;
2545
+ }
2546
+ function collectText(node) {
2547
+ if (node.type === "text") return node.data ?? "";
2548
+ return (node.children ?? []).map(collectText).join("");
2549
+ }
2550
+ function resolvePageScopeId$1(scopeId) {
2551
+ if (!scopeId) return null;
2552
+ const pagePathIndex = scopeId.indexOf("/page/");
2553
+ return pagePathIndex >= 0 ? scopeId.slice(0, pagePathIndex) : scopeId;
2554
+ }
2555
+ function resolveComponentScopeId(scopeId) {
2556
+ if (!scopeId || !scopeId.includes("/")) return null;
2557
+ return scopeId;
2558
+ }
2559
+ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
2560
+ constructor(node, interactions) {
2561
+ this.node = node;
2562
+ this.interactions = interactions;
1910
2563
  }
1911
- getCurrentPageNavigationBar() {
1912
- const snapshot = this.currentPageInstance?.__navigationBar__;
1913
- return snapshot ? cloneNavigationBarSnapshot(snapshot) : null;
2564
+ async $(selector) {
2565
+ const match = querySelectorAll(this.node, selector)[0];
2566
+ return match ? new HeadlessTestingNodeHandle(match, this.interactions) : null;
1914
2567
  }
1915
- getCurrentPageBackground() {
1916
- const snapshot = this.currentPageInstance?.__background__;
1917
- return snapshot ? cloneBackgroundSnapshot(snapshot) : null;
2568
+ async $$(selector) {
2569
+ return querySelectorAll(this.node, selector).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
1918
2570
  }
1919
- getActionSheetLogs() {
1920
- return this.wxState.getActionSheetLogs();
2571
+ async attr(name) {
2572
+ return this.node.attribs?.[name];
1921
2573
  }
1922
- getRequestLogs() {
1923
- return this.wxState.getRequestLogs();
2574
+ async dataset() {
2575
+ return collectDataset$2(this.node);
1924
2576
  }
1925
- getStorageSnapshot() {
1926
- return this.wxState.getStorageSnapshot();
2577
+ async scope() {
2578
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
2579
+ return this.interactions.createScopeHandle(this.node.attribs?.["data-sim-scope"] ?? null);
1927
2580
  }
1928
- getShareMenu() {
1929
- return this.wxState.getShareMenu();
2581
+ async componentScope() {
2582
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
2583
+ return this.interactions.createScopeHandle(resolveComponentScopeId(this.node.attribs?.["data-sim-scope"] ?? null));
1930
2584
  }
1931
- getTabBar() {
1932
- return { visible: this.tabBarVisible };
2585
+ async pageScope() {
2586
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
2587
+ return this.interactions.createScopeHandle(resolvePageScopeId$1(this.node.attribs?.["data-sim-scope"] ?? null));
1933
2588
  }
1934
- getTabBarSnapshot() {
1935
- return {
1936
- items: Array.from(this.tabBarState.values(), (item) => ({
1937
- badge: item.badge,
1938
- index: item.index,
1939
- pagePath: item.pagePath,
1940
- redDot: item.redDot,
1941
- text: item.text
1942
- })),
1943
- visible: this.tabBarVisible
1944
- };
2589
+ async page() {
2590
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
2591
+ return this.interactions.createPageHandle();
1945
2592
  }
1946
- getStorageInfo() {
1947
- return this.wxState.getStorageInfoSync();
2593
+ async ownerComponentScope() {
2594
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
2595
+ const scopeId = resolveComponentScopeId(this.node.attribs?.["data-sim-scope"] ?? null);
2596
+ return this.interactions.createScopeHandle(this.interactions.ownerScopeId(scopeId));
1948
2597
  }
1949
- getSystemInfo() {
1950
- return { ...this.systemInfo };
2598
+ async text() {
2599
+ return collectText(this.node);
1951
2600
  }
1952
- getWindowInfo() {
1953
- return deriveWindowInfo(this.systemInfo);
2601
+ async trigger(eventName, event = {}) {
2602
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
2603
+ const normalizedEventName = eventName.trim();
2604
+ if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
2605
+ const methodName = resolveEventBinding(this.node, normalizedEventName);
2606
+ if (!methodName) throw new Error(`No ${normalizedEventName} binding was found on <${this.node.name ?? "unknown"}> in headless testing runtime.`);
2607
+ return await this.interactions.callMethod(this.node.attribs?.["data-sim-scope"] ?? null, methodName, createEventPayload(this.node, normalizedEventName, event));
1954
2608
  }
1955
- getAppBaseInfo() {
1956
- return deriveAppBaseInfo(this.systemInfo);
2609
+ async tap(event = {}) {
2610
+ return await this.trigger("tap", event);
1957
2611
  }
1958
- getLaunchOptions() {
1959
- return {
1960
- ...this.launchOptions,
1961
- query: { ...this.launchOptions.query },
1962
- referrerInfo: {
1963
- ...this.launchOptions.referrerInfo,
1964
- extraData: { ...this.launchOptions.referrerInfo.extraData }
1965
- }
1966
- };
2612
+ async input(value, event = {}) {
2613
+ return await this.trigger("input", {
2614
+ ...event,
2615
+ detail: createValueEventDetail(value, event.detail)
2616
+ });
1967
2617
  }
1968
- getEnterOptions() {
1969
- return {
1970
- ...this.enterOptions,
1971
- query: { ...this.enterOptions.query },
1972
- referrerInfo: {
1973
- ...this.enterOptions.referrerInfo,
1974
- extraData: { ...this.enterOptions.referrerInfo.extraData }
1975
- }
1976
- };
2618
+ async change(value, event = {}) {
2619
+ return await this.trigger("change", {
2620
+ ...event,
2621
+ detail: createValueEventDetail(value, event.detail)
2622
+ });
1977
2623
  }
1978
- getMenuButtonBoundingClientRect() {
1979
- return deriveMenuButtonBoundingClientRect(this.systemInfo);
1980
- }
1981
- getNetworkType() {
1982
- return this.wxState.getNetworkType();
1983
- }
1984
- getLoading() {
1985
- return this.wxState.getLoading();
1986
- }
1987
- getModalLogs() {
1988
- return this.wxState.getModalLogs();
1989
- }
1990
- getToast() {
1991
- return this.wxState.getToast();
1992
- }
1993
- mockModal(definition = {}) {
1994
- this.wxState.mockModal(definition);
1995
- }
1996
- mockActionSheet(definition = {}) {
1997
- this.wxState.mockActionSheet(definition);
1998
- }
1999
- mockRequest(definition) {
2000
- this.wxState.mockRequest(definition);
2001
- }
2002
- setNetworkType(networkType) {
2003
- return this.wxState.setNetworkType(networkType);
2624
+ async blur(value, event = {}) {
2625
+ return await this.trigger("blur", {
2626
+ ...event,
2627
+ detail: value == null ? event.detail : createValueEventDetail(value, event.detail)
2628
+ });
2004
2629
  }
2005
- setBackgroundTextStyle(textStyle) {
2006
- if (textStyle !== "dark" && textStyle !== "light") throw new Error("setBackgroundTextStyle:fail invalid textStyle");
2007
- const current = this.requireCurrentPage("wx.setBackgroundTextStyle()");
2008
- current.__background__ ??= {
2009
- backgroundColor: "#ffffff",
2010
- backgroundColorBottom: "#ffffff",
2011
- backgroundColorTop: "#ffffff",
2012
- textStyle: "dark"
2013
- };
2014
- current.__background__.textStyle = textStyle;
2015
- current.__backgroundTextStyle__ = textStyle;
2016
- return { errMsg: "setBackgroundTextStyle:ok" };
2630
+ async wxml() {
2631
+ return serializeNode(this.node);
2017
2632
  }
2018
- setBackgroundColor(option) {
2019
- const current = this.requireCurrentPage("wx.setBackgroundColor()");
2020
- current.__background__ ??= {
2021
- backgroundColor: "#ffffff",
2022
- backgroundColorBottom: "#ffffff",
2023
- backgroundColorTop: "#ffffff",
2024
- textStyle: current.__backgroundTextStyle__ ?? "dark"
2025
- };
2026
- if (typeof option.backgroundColor === "string") current.__background__.backgroundColor = option.backgroundColor;
2027
- if (typeof option.backgroundColorTop === "string") current.__background__.backgroundColorTop = option.backgroundColorTop;
2028
- if (typeof option.backgroundColorBottom === "string") current.__background__.backgroundColorBottom = option.backgroundColorBottom;
2029
- return { errMsg: "setBackgroundColor:ok" };
2633
+ };
2634
+ //#endregion
2635
+ //#region src/view/render.ts
2636
+ const LEADING_SLASH_RE$4 = /^\/+/;
2637
+ const TEMPLATE_INTERPOLATION_RE$1 = /\{\{([^{}]+)\}\}/g;
2638
+ function resolveValueByPath$1(source, expression) {
2639
+ const normalized = expression.trim();
2640
+ if (!normalized) return "";
2641
+ const segments = normalized.split(".").filter(Boolean);
2642
+ let current = source;
2643
+ for (const segment of segments) current = current?.[segment];
2644
+ return current ?? "";
2645
+ }
2646
+ function interpolateTemplate$1(input, data) {
2647
+ return input.replace(TEMPLATE_INTERPOLATION_RE$1, (_match, expression) => {
2648
+ const value = resolveValueByPath$1(data, expression);
2649
+ return typeof value === "string" ? value : String(value);
2650
+ });
2651
+ }
2652
+ function visitDom(node, visitor) {
2653
+ visitor(node);
2654
+ for (const child of node.children ?? []) visitDom(child, visitor);
2655
+ }
2656
+ function interpolateDomTree(root, data) {
2657
+ visitDom(root, (node) => {
2658
+ if (typeof node.data === "string") node.data = interpolateTemplate$1(node.data, data);
2659
+ if (node.attribs) for (const [key, value] of Object.entries(node.attribs)) node.attribs[key] = interpolateTemplate$1(value, data);
2660
+ });
2661
+ }
2662
+ function escapeText$1(text) {
2663
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
2664
+ }
2665
+ function escapeAttribute$1(value) {
2666
+ return escapeText$1(value).replaceAll("\"", "&quot;");
2667
+ }
2668
+ function serializeDomNode$1(node) {
2669
+ if (node.type === "text") return escapeText$1(node.data ?? "");
2670
+ if (node.type === "root") return (node.children ?? []).map(serializeDomNode$1).join("");
2671
+ const tagName = node.name ?? "";
2672
+ if (!tagName) return (node.children ?? []).map(serializeDomNode$1).join("");
2673
+ return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$1(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$1).join("")}</${tagName}>`;
2674
+ }
2675
+ function renderPageTree(project, page) {
2676
+ const route = page.route.replace(LEADING_SLASH_RE$4, "");
2677
+ const templatePath = path.resolve(project.miniprogramRootPath, `${route}.wxml`);
2678
+ const document = parseDocument(`<page>${fs.readFileSync(templatePath, "utf8")}</page>`, {
2679
+ xmlMode: false,
2680
+ decodeEntities: false,
2681
+ recognizeSelfClosing: true
2682
+ });
2683
+ interpolateDomTree(document, page.data);
2684
+ return {
2685
+ root: document,
2686
+ wxml: serializeDomNode$1((document.children ?? [])[0] ?? document)
2687
+ };
2688
+ }
2689
+ //#endregion
2690
+ //#region src/view/selectorQuery.ts
2691
+ const DATASET_NAME_RE$1 = /-([a-z])/g;
2692
+ const LEADING_MARK_PREFIX_RE = /^mark[:\-]?/;
2693
+ const MARK_NAME_RE = /[:\-]([a-z])/g;
2694
+ const NUMERIC_LIKE_VALUE_RE = /-?\d+(?:\.\d+)?/;
2695
+ function toDatasetKey$1(attributeName) {
2696
+ return attributeName.slice(5).replace(DATASET_NAME_RE$1, (_match, char) => char.toUpperCase());
2697
+ }
2698
+ function collectDataset$1(node) {
2699
+ const dataset = {};
2700
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
2701
+ if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
2702
+ dataset[toDatasetKey$1(key)] = value;
2030
2703
  }
2031
- setNavigationBarTitle(title) {
2032
- const current = this.requireCurrentPage("wx.setNavigationBarTitle()");
2033
- current.__navigationBar__ ??= {
2034
- animation: null,
2035
- backgroundColor: "#ffffff",
2036
- frontColor: "#000000",
2037
- loading: false,
2038
- title: ""
2039
- };
2040
- current.__navigationBar__.title = title;
2041
- current.__navigationBarTitle__ = title;
2042
- return { errMsg: "setNavigationBarTitle:ok" };
2704
+ return dataset;
2705
+ }
2706
+ function toMarkKey(attributeName) {
2707
+ return attributeName.replace(LEADING_MARK_PREFIX_RE, "").replace(MARK_NAME_RE, (_match, char) => char.toUpperCase());
2708
+ }
2709
+ function collectMark(node) {
2710
+ const mark = {};
2711
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
2712
+ if (!(key.startsWith("mark:") || key.startsWith("mark-"))) continue;
2713
+ mark[toMarkKey(key)] = value;
2043
2714
  }
2044
- setNavigationBarColor(option) {
2045
- const current = this.requireCurrentPage("wx.setNavigationBarColor()");
2046
- current.__navigationBar__ ??= {
2047
- animation: null,
2048
- backgroundColor: "#ffffff",
2049
- frontColor: "#000000",
2050
- loading: false,
2051
- title: current.__navigationBarTitle__ ?? ""
2052
- };
2053
- if (typeof option.backgroundColor === "string") current.__navigationBar__.backgroundColor = option.backgroundColor;
2054
- if (typeof option.frontColor === "string") current.__navigationBar__.frontColor = option.frontColor;
2055
- current.__navigationBar__.animation = option.animation ? {
2056
- duration: option.animation.duration,
2057
- timingFunction: option.animation.timingFunction
2058
- } : null;
2059
- return { errMsg: "setNavigationBarColor:ok" };
2715
+ return mark;
2716
+ }
2717
+ function createScopedRoot(node) {
2718
+ return {
2719
+ children: [node],
2720
+ type: "root"
2721
+ };
2722
+ }
2723
+ function findNodeByScopeId(root, scopeId) {
2724
+ if (root.attribs?.["data-sim-scope"] === scopeId) return root;
2725
+ for (const child of root.children ?? []) {
2726
+ const match = findNodeByScopeId(child, scopeId);
2727
+ if (match) return match;
2060
2728
  }
2061
- showNavigationBarLoading() {
2062
- const current = this.requireCurrentPage("wx.showNavigationBarLoading()");
2063
- current.__navigationBar__ ??= {
2064
- animation: null,
2065
- backgroundColor: "#ffffff",
2066
- frontColor: "#000000",
2067
- loading: false,
2068
- title: current.__navigationBarTitle__ ?? ""
2069
- };
2070
- current.__navigationBar__.loading = true;
2071
- return { errMsg: "showNavigationBarLoading:ok" };
2729
+ return null;
2730
+ }
2731
+ function parseStyleDeclarations(styleValue) {
2732
+ const declarations = {};
2733
+ if (!styleValue) return declarations;
2734
+ for (const declaration of styleValue.split(";")) {
2735
+ const [rawProperty, ...rawValueParts] = declaration.split(":");
2736
+ const property = rawProperty?.trim();
2737
+ if (!property) continue;
2738
+ declarations[property] = rawValueParts.join(":").trim();
2739
+ }
2740
+ return declarations;
2741
+ }
2742
+ function parseNumericLikeValue(value) {
2743
+ if (!value) return 0;
2744
+ const match = value.match(NUMERIC_LIKE_VALUE_RE);
2745
+ return match ? Number(match[0]) : 0;
2746
+ }
2747
+ function resolveRect(node) {
2748
+ const style = parseStyleDeclarations(node.attribs?.style);
2749
+ const left = parseNumericLikeValue(node.attribs?.["data-sim-left"] ?? style.left);
2750
+ const top = parseNumericLikeValue(node.attribs?.["data-sim-top"] ?? style.top);
2751
+ const width = parseNumericLikeValue(node.attribs?.["data-sim-width"] ?? style.width);
2752
+ const height = parseNumericLikeValue(node.attribs?.["data-sim-height"] ?? style.height);
2753
+ return {
2754
+ bottom: top + height,
2755
+ height,
2756
+ left,
2757
+ right: left + width,
2758
+ top,
2759
+ width
2760
+ };
2761
+ }
2762
+ function resolveScrollOffset(node) {
2763
+ return {
2764
+ scrollLeft: parseNumericLikeValue(node.attribs?.["data-sim-scroll-left"]),
2765
+ scrollTop: parseNumericLikeValue(node.attribs?.["data-sim-scroll-top"])
2766
+ };
2767
+ }
2768
+ function resolvePropertyValue(node, propertyName) {
2769
+ const normalizedPropertyName = propertyName.trim();
2770
+ if (!normalizedPropertyName) return;
2771
+ if (normalizedPropertyName === "id") return node.attribs?.id ?? "";
2772
+ if (normalizedPropertyName === "class") return node.attribs?.class ?? "";
2773
+ if (normalizedPropertyName === "dataset") return collectDataset$1(node);
2774
+ return node.attribs?.[normalizedPropertyName];
2775
+ }
2776
+ function pickProperties(node, propertyNames) {
2777
+ const result = {};
2778
+ for (const propertyName of propertyNames) result[propertyName] = resolvePropertyValue(node, propertyName);
2779
+ return result;
2780
+ }
2781
+ function pickComputedStyle(node, propertyNames) {
2782
+ const style = parseStyleDeclarations(node.attribs?.style);
2783
+ const result = {};
2784
+ for (const propertyName of propertyNames) result[propertyName] = style[propertyName] ?? "";
2785
+ return result;
2786
+ }
2787
+ function resolveFieldsResult(node, fields, _options) {
2788
+ const result = {};
2789
+ if (fields.id) result.id = node.attribs?.id ?? "";
2790
+ if (fields.dataset) result.dataset = collectDataset$1(node);
2791
+ if (fields.mark) result.mark = collectMark(node);
2792
+ if (fields.rect || fields.size) {
2793
+ const rect = resolveRect(node);
2794
+ if (fields.rect) Object.assign(result, rect);
2795
+ if (fields.size) {
2796
+ result.width = rect.width;
2797
+ result.height = rect.height;
2798
+ }
2072
2799
  }
2073
- hideNavigationBarLoading() {
2074
- const current = this.requireCurrentPage("wx.hideNavigationBarLoading()");
2075
- current.__navigationBar__ ??= {
2076
- animation: null,
2077
- backgroundColor: "#ffffff",
2078
- frontColor: "#000000",
2079
- loading: false,
2080
- title: current.__navigationBarTitle__ ?? ""
2800
+ if (fields.scrollOffset) Object.assign(result, resolveScrollOffset(node));
2801
+ if (Array.isArray(fields.properties) && fields.properties.length > 0) Object.assign(result, pickProperties(node, fields.properties));
2802
+ if (Array.isArray(fields.computedStyle) && fields.computedStyle.length > 0) Object.assign(result, pickComputedStyle(node, fields.computedStyle));
2803
+ if (fields.context) result.context = { type: "unsupported-context" };
2804
+ if (fields.node) result.node = { type: node.name ?? "unknown" };
2805
+ return result;
2806
+ }
2807
+ function resolveViewportResult(fields, options) {
2808
+ const result = {};
2809
+ if (fields.rect || fields.size) {
2810
+ const rect = {
2811
+ bottom: options.windowInfo.windowHeight,
2812
+ height: options.windowInfo.windowHeight,
2813
+ left: 0,
2814
+ right: options.windowInfo.windowWidth,
2815
+ top: 0,
2816
+ width: options.windowInfo.windowWidth
2081
2817
  };
2082
- current.__navigationBar__.loading = false;
2083
- return { errMsg: "hideNavigationBarLoading:ok" };
2818
+ if (fields.rect) Object.assign(result, rect);
2819
+ if (fields.size) {
2820
+ result.width = rect.width;
2821
+ result.height = rect.height;
2822
+ }
2084
2823
  }
2085
- hideTabBar() {
2086
- this.tabBarVisible = false;
2087
- return { errMsg: "hideTabBar:ok" };
2824
+ if (fields.scrollOffset) {
2825
+ result.scrollLeft = 0;
2826
+ result.scrollTop = options.page.__scrollTop__ ?? 0;
2088
2827
  }
2089
- hideTabBarRedDot(index) {
2090
- const item = this.requireTabBarItem(index, "wx.hideTabBarRedDot()");
2091
- item.redDot = false;
2092
- return { errMsg: "hideTabBarRedDot:ok" };
2828
+ return result;
2829
+ }
2830
+ function resolveRequestResult(request, options) {
2831
+ if (request.target === "viewport") return resolveViewportResult(request.fields, options);
2832
+ const matches = querySelectorAll(options.root, request.selector ?? "");
2833
+ if (!request.single) return matches.map((node) => resolveFieldsResult(node, request.fields, options));
2834
+ const match = matches[0];
2835
+ return match ? resolveFieldsResult(match, request.fields, options) : null;
2836
+ }
2837
+ function executeSelectorQueryRequests(requests, options) {
2838
+ return requests.map((request) => resolveRequestResult(request, options));
2839
+ }
2840
+ function resolveSelectorQueryScopeRoot(root, scopeId) {
2841
+ if (!scopeId) return root;
2842
+ const scopedNode = findNodeByScopeId(root, scopeId);
2843
+ return scopedNode ? createScopedRoot(scopedNode) : root;
2844
+ }
2845
+ //#endregion
2846
+ //#region src/browser/session.ts
2847
+ const LEADING_SLASH_RE$3 = /^\/+/;
2848
+ const PAGE_STACK_LIMIT$1 = 10;
2849
+ const DATA_ATTR_SELECTOR_RE$1 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
2850
+ const DATASET_KEY_RE$1 = /-([a-z])/g;
2851
+ function stripLeadingSlash$1(route) {
2852
+ return route.replace(LEADING_SLASH_RE$3, "");
2853
+ }
2854
+ function normalizeQuery$1(queryString) {
2855
+ const query = new URLSearchParams(queryString);
2856
+ const result = {};
2857
+ for (const [key, value] of query.entries()) result[key] = value;
2858
+ return result;
2859
+ }
2860
+ function parseNavigationUrl$1(url) {
2861
+ const trimmedUrl = url.trim();
2862
+ if (!trimmedUrl) throw new Error("Navigation url must be a non-empty string in browser simulator runtime.");
2863
+ const [pathWithHash, queryString = ""] = trimmedUrl.split("?");
2864
+ const [pathname] = pathWithHash.split("#");
2865
+ return {
2866
+ pathname: pathname || "",
2867
+ query: normalizeQuery$1(queryString)
2868
+ };
2869
+ }
2870
+ function createAppLaunchOptions$1(pathname, query) {
2871
+ return {
2872
+ path: stripLeadingSlash$1(pathname),
2873
+ query: { ...query },
2874
+ referrerInfo: {
2875
+ appId: "",
2876
+ extraData: {}
2877
+ },
2878
+ scene: 1001
2879
+ };
2880
+ }
2881
+ function readJsonObject$2(files, filePath) {
2882
+ const content = readBrowserVirtualFile(files, filePath);
2883
+ if (!content) return;
2884
+ try {
2885
+ const value = JSON.parse(content);
2886
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2887
+ } catch {
2888
+ return;
2093
2889
  }
2094
- showTabBar() {
2890
+ }
2891
+ function resolveNavigationPath$1(targetPath, baseRoute) {
2892
+ if (!targetPath) throw new Error("Navigation url must include a pathname in browser simulator runtime.");
2893
+ if (targetPath.startsWith("/")) return posix.normalize(targetPath).replace(LEADING_SLASH_RE$3, "");
2894
+ if (!baseRoute) throw new Error(`Cannot resolve relative navigation url "${targetPath}" without an active page.`);
2895
+ return posix.resolve(`/${posix.dirname(baseRoute)}`, targetPath).replace(LEADING_SLASH_RE$3, "");
2896
+ }
2897
+ var BrowserHeadlessSession = class {
2898
+ files;
2899
+ project;
2900
+ appDefinition = null;
2901
+ appInstance = null;
2902
+ moduleLoader;
2903
+ registries;
2904
+ currentPageInstance = null;
2905
+ pages = [];
2906
+ componentCache = /* @__PURE__ */ new Map();
2907
+ componentScopes = /* @__PURE__ */ new Map();
2908
+ tabBarRoutes;
2909
+ tabPages = /* @__PURE__ */ new Map();
2910
+ tabBarItems = /* @__PURE__ */ new Map();
2911
+ tabBarState = /* @__PURE__ */ new Map();
2912
+ tabBarVisible = false;
2913
+ systemInfo = createDefaultSystemInfo();
2914
+ enterOptions = createAppLaunchOptions$1("", {});
2915
+ launchOptions = createAppLaunchOptions$1("", {});
2916
+ wxState = createHeadlessWxState();
2917
+ pullDownRefreshState = {
2918
+ active: false,
2919
+ stopCalls: 0
2920
+ };
2921
+ constructor(options) {
2922
+ this.files = options.files;
2923
+ this.project = options.project ?? createBrowserProject(options.files);
2924
+ this.registries = createHostRegistries();
2925
+ const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
2926
+ this.tabBarRoutes = /* @__PURE__ */ new Set();
2927
+ rawTabBarList.forEach((item, index) => {
2928
+ if (typeof item?.pagePath !== "string") return;
2929
+ const pagePath = stripLeadingSlash$1(item.pagePath);
2930
+ if (!pagePath) return;
2931
+ this.tabBarRoutes.add(pagePath);
2932
+ this.tabBarItems.set(pagePath, {
2933
+ index,
2934
+ pagePath,
2935
+ text: typeof item.text === "string" ? item.text : void 0
2936
+ });
2937
+ this.tabBarState.set(index, {
2938
+ badge: null,
2939
+ index,
2940
+ pagePath,
2941
+ redDot: false,
2942
+ text: typeof item.text === "string" ? item.text : void 0
2943
+ });
2944
+ });
2095
2945
  this.tabBarVisible = this.tabBarRoutes.size > 0;
2096
- return { errMsg: "showTabBar:ok" };
2946
+ this.moduleLoader = createBrowserModuleLoader(this.files, this.registries, () => this.pages.slice(), () => this.getApp(), {
2947
+ executeSelectorQuery: (requests, scope) => this.executeSelectorQuery(requests, scope),
2948
+ getFileSystemManager: () => this.wxState.getFileSystemManager(),
2949
+ getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
2950
+ getSavedFileList: () => this.wxState.getSavedFileList(),
2951
+ getEnterOptionsSync: () => ({
2952
+ ...this.enterOptions,
2953
+ query: { ...this.enterOptions.query },
2954
+ referrerInfo: {
2955
+ ...this.enterOptions.referrerInfo,
2956
+ extraData: { ...this.enterOptions.referrerInfo.extraData }
2957
+ }
2958
+ }),
2959
+ getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
2960
+ getLaunchOptionsSync: () => ({
2961
+ ...this.launchOptions,
2962
+ query: { ...this.launchOptions.query },
2963
+ referrerInfo: {
2964
+ ...this.launchOptions.referrerInfo,
2965
+ extraData: { ...this.launchOptions.referrerInfo.extraData }
2966
+ }
2967
+ }),
2968
+ getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
2969
+ getNetworkType: () => this.wxState.getNetworkType(),
2970
+ navigateBack: (option) => this.navigateBack(option?.delta),
2971
+ navigateTo: (option) => this.navigateTo(option.url),
2972
+ pageScrollTo: (option) => this.pageScrollTo(option),
2973
+ clearStorageSync: () => this.wxState.clearStorageSync(),
2974
+ getStorageInfoSync: () => this.wxState.getStorageInfoSync(),
2975
+ getStorageSync: (key) => this.wxState.getStorageSync(key),
2976
+ getSystemInfoSync: () => ({ ...this.systemInfo }),
2977
+ getWindowInfoSync: () => deriveWindowInfo(this.systemInfo),
2978
+ hideLoading: () => this.wxState.hideLoading(),
2979
+ hideToast: () => this.wxState.hideToast(),
2980
+ downloadFile: (option) => this.wxState.downloadFile(option),
2981
+ reLaunch: (option) => this.reLaunch(option.url),
2982
+ redirectTo: (option) => this.redirectTo(option.url),
2983
+ removeSavedFile: (option) => this.wxState.removeSavedFile(option),
2984
+ nextTick: (callback) => queueMicrotask(() => callback?.()),
2985
+ offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
2986
+ onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
2987
+ removeStorageSync: (key) => this.wxState.removeStorageSync(key),
2988
+ request: (option) => this.wxState.request(option),
2989
+ saveFile: (option) => this.wxState.saveFile(option),
2990
+ setBackgroundColor: (option) => this.setBackgroundColor(option),
2991
+ setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
2992
+ setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
2993
+ setNavigationBarColor: (option) => this.setNavigationBarColor(option),
2994
+ setNavigationBarTitle: (option) => this.setNavigationBarTitle(option.title),
2995
+ hideShareMenu: () => this.wxState.hideShareMenu(),
2996
+ hideNavigationBarLoading: () => this.hideNavigationBarLoading(),
2997
+ hideTabBar: () => this.hideTabBar(),
2998
+ hideTabBarRedDot: (option) => this.hideTabBarRedDot(option.index),
2999
+ showShareMenu: (option) => this.wxState.showShareMenu(option),
3000
+ showNavigationBarLoading: () => this.showNavigationBarLoading(),
3001
+ showTabBar: () => this.showTabBar(),
3002
+ showTabBarRedDot: (option) => this.showTabBarRedDot(option.index),
3003
+ showActionSheet: (option) => this.wxState.showActionSheet(option),
3004
+ showLoading: (option) => this.wxState.showLoading(option),
3005
+ showModal: (option) => this.wxState.showModal(option),
3006
+ showToast: (option) => this.wxState.showToast(option),
3007
+ stopPullDownRefresh: () => this.stopPullDownRefresh(),
3008
+ switchTab: (option) => this.switchTab(option.url),
3009
+ uploadFile: (option) => this.wxState.uploadFile(option),
3010
+ removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
3011
+ setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
3012
+ updateShareMenu: (option) => this.wxState.updateShareMenu(option)
3013
+ });
2097
3014
  }
2098
- showTabBarRedDot(index) {
2099
- const item = this.requireTabBarItem(index, "wx.showTabBarRedDot()");
2100
- item.badge = null;
2101
- item.redDot = true;
2102
- return { errMsg: "showTabBarRedDot:ok" };
3015
+ getApp() {
3016
+ return this.appInstance;
2103
3017
  }
2104
- removeTabBarBadge(index) {
2105
- const item = this.requireTabBarItem(index, "wx.removeTabBarBadge()");
2106
- item.badge = null;
2107
- return { errMsg: "removeTabBarBadge:ok" };
3018
+ getCurrentPages() {
3019
+ return this.pages.slice();
2108
3020
  }
2109
- setTabBarBadge(index, text) {
2110
- const item = this.requireTabBarItem(index, "wx.setTabBarBadge()");
2111
- item.badge = text;
2112
- item.redDot = false;
2113
- return { errMsg: "setTabBarBadge:ok" };
3021
+ getCurrentPageNavigationBarTitle() {
3022
+ return this.currentPageInstance?.__navigationBarTitle__ ?? null;
2114
3023
  }
2115
- getScopeSnapshot(scopeId) {
2116
- const scope = this.componentScopes.get(scopeId);
2117
- if (!scope) return null;
2118
- const instance = this.componentCache.get(scopeId);
2119
- if (instance) return {
2120
- data: instance.data ?? {},
2121
- methods: Object.keys(instance).filter((key) => typeof instance[key] === "function").sort((a, b) => a.localeCompare(b)),
2122
- properties: instance.properties ?? {},
2123
- scopeId,
2124
- type: "component"
2125
- };
2126
- const currentPage = this.currentPageInstance;
2127
- if (currentPage && scopeId === `page:${currentPage.route}`) return {
2128
- data: currentPage.data ?? {},
2129
- methods: Object.keys(currentPage).filter((key) => typeof currentPage[key] === "function").sort((a, b) => a.localeCompare(b)),
2130
- properties: currentPage.options ?? {},
2131
- scopeId,
2132
- type: "page"
2133
- };
2134
- return {
2135
- data: scope.data ?? {},
2136
- methods: [],
2137
- properties: {},
2138
- scopeId,
2139
- type: "scope"
2140
- };
3024
+ getCurrentPageNavigationBar() {
3025
+ const snapshot = this.currentPageInstance?.__navigationBar__;
3026
+ return snapshot ? cloneNavigationBarSnapshot(snapshot) : null;
2141
3027
  }
2142
- selectComponent(selector) {
2143
- return this.selectComponentsWithin(null, selector)[0] ?? null;
3028
+ getCurrentPageBackground() {
3029
+ const snapshot = this.currentPageInstance?.__background__;
3030
+ return snapshot ? cloneBackgroundSnapshot(snapshot) : null;
2144
3031
  }
2145
- selectAllComponents(selector) {
2146
- return this.selectComponentsWithin(null, selector);
3032
+ getActionSheetLogs() {
3033
+ return this.wxState.getActionSheetLogs();
2147
3034
  }
2148
- selectComponentWithin(scopeId, selector) {
2149
- return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
3035
+ getRequestLogs() {
3036
+ return this.wxState.getRequestLogs();
2150
3037
  }
2151
- selectAllComponentsWithin(scopeId, selector) {
2152
- return this.selectComponentsWithin(scopeId, selector);
3038
+ getDownloadFileLogs() {
3039
+ return this.wxState.getDownloadFileLogs();
2153
3040
  }
2154
- selectOwnerComponent(scopeId) {
2155
- const scope = this.componentScopes.get(scopeId);
2156
- if (!scope?.ownerScopeId) return null;
2157
- return this.componentCache.get(scope.ownerScopeId) ?? null;
3041
+ getUploadFileLogs() {
3042
+ return this.wxState.getUploadFileLogs();
2158
3043
  }
2159
- selectComponentsWithin(rootScopeId, selector) {
2160
- const normalizedSelector = selector.trim();
2161
- if (!normalizedSelector) return [];
2162
- return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
2163
- if (!candidateScopeId.includes("/")) return false;
2164
- if (rootScopeId && candidateScopeId === rootScopeId) return false;
2165
- if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
2166
- if (normalizedSelector.startsWith("#")) return scope.id === normalizedSelector.slice(1);
2167
- if (normalizedSelector.startsWith(".")) return scope.classList?.includes(normalizedSelector.slice(1)) ?? false;
2168
- const dataAttrMatch = normalizedSelector.match(DATA_ATTR_SELECTOR_RE$1);
2169
- if (dataAttrMatch) {
2170
- const [, key, value] = dataAttrMatch;
2171
- const datasetKey = key.replace(DATASET_KEY_RE, (_match, char) => char.toUpperCase());
2172
- return scope.dataset?.[datasetKey] === value;
2173
- }
2174
- return scope.alias === normalizedSelector;
2175
- }).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
3044
+ getFileSnapshot() {
3045
+ return this.wxState.getFileSnapshot();
2176
3046
  }
2177
- renderCurrentPage() {
2178
- const current = this.requireCurrentPage("renderCurrentPage()");
2179
- const rendered = renderBrowserPageTree({
2180
- changedPageKeys: current.__lastChangedKeys__ ?? [],
2181
- componentCache: this.componentCache,
2182
- componentScopes: this.componentScopes,
2183
- files: this.files,
2184
- moduleLoader: this.moduleLoader,
2185
- project: this.project,
2186
- session: {
2187
- selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
2188
- selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
2189
- selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
2190
- }
2191
- }, current);
2192
- current.__lastChangedKeys__ = [];
2193
- return rendered;
3047
+ getDirectorySnapshot() {
3048
+ return this.wxState.getDirectorySnapshot();
2194
3049
  }
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);
2199
- if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on scope "${scopeId}" in browser simulator runtime.`);
2200
- return method();
3050
+ getFileText(filePath) {
3051
+ return this.wxState.getFileText(filePath);
2201
3052
  }
2202
- callTapBindingWithEvent(scopeId, methodName, event = {}) {
2203
- const scope = this.componentScopes.get(scopeId);
2204
- if (!scope) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
2205
- const method = scope.getMethod(methodName);
2206
- if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on scope "${scopeId}" in browser simulator runtime.`);
2207
- const instance = this.componentCache.get(scopeId);
2208
- if (instance) instance.__lastInteractionEvent__ = {
2209
- currentTarget: {
2210
- dataset: event.currentTarget?.dataset ?? event.dataset ?? {},
2211
- id: event.currentTarget?.id ?? event.id ?? ""
2212
- },
2213
- target: {
2214
- dataset: event.target?.dataset ?? event.dataset ?? {},
2215
- id: event.target?.id ?? event.id ?? ""
2216
- }
2217
- };
2218
- return method({
2219
- bubbles: false,
2220
- capturePhase: false,
2221
- composed: false,
2222
- currentTarget: {
2223
- dataset: event.currentTarget?.dataset ?? event.dataset ?? {},
2224
- id: event.currentTarget?.id ?? event.id ?? ""
2225
- },
2226
- detail: void 0,
2227
- mark: void 0,
2228
- target: {
2229
- dataset: event.target?.dataset ?? event.dataset ?? {},
2230
- id: event.target?.id ?? event.id ?? ""
2231
- },
2232
- type: "tap"
2233
- });
3053
+ getSavedFileListSnapshot() {
3054
+ return this.wxState.getSavedFileList().fileList;
2234
3055
  }
2235
- bootstrap(launchOptions = createAppLaunchOptions$1("", {})) {
2236
- if (this.appInstance) return this.appInstance;
2237
- this.launchOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
2238
- this.enterOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
3056
+ getStorageSnapshot() {
3057
+ return this.wxState.getStorageSnapshot();
3058
+ }
3059
+ getShareMenu() {
3060
+ return this.wxState.getShareMenu();
3061
+ }
3062
+ getTabBar() {
3063
+ return { visible: this.tabBarVisible };
3064
+ }
3065
+ getTabBarSnapshot() {
3066
+ return {
3067
+ items: Array.from(this.tabBarState.values(), (item) => ({
3068
+ badge: item.badge,
3069
+ index: item.index,
3070
+ pagePath: item.pagePath,
3071
+ redDot: item.redDot,
3072
+ text: item.text
3073
+ })),
3074
+ visible: this.tabBarVisible
3075
+ };
3076
+ }
3077
+ getStorageInfo() {
3078
+ return this.wxState.getStorageInfoSync();
3079
+ }
3080
+ getPullDownRefreshState() {
3081
+ return { ...this.pullDownRefreshState };
3082
+ }
3083
+ getSystemInfo() {
3084
+ return { ...this.systemInfo };
3085
+ }
3086
+ getWindowInfo() {
3087
+ return deriveWindowInfo(this.systemInfo);
3088
+ }
3089
+ getAppBaseInfo() {
3090
+ return deriveAppBaseInfo(this.systemInfo);
3091
+ }
3092
+ getLaunchOptions() {
3093
+ return {
3094
+ ...this.launchOptions,
3095
+ query: { ...this.launchOptions.query },
3096
+ referrerInfo: {
3097
+ ...this.launchOptions.referrerInfo,
3098
+ extraData: { ...this.launchOptions.referrerInfo.extraData }
3099
+ }
3100
+ };
3101
+ }
3102
+ getEnterOptions() {
3103
+ return {
3104
+ ...this.enterOptions,
3105
+ query: { ...this.enterOptions.query },
3106
+ referrerInfo: {
3107
+ ...this.enterOptions.referrerInfo,
3108
+ extraData: { ...this.enterOptions.referrerInfo.extraData }
3109
+ }
3110
+ };
3111
+ }
3112
+ getMenuButtonBoundingClientRect() {
3113
+ return deriveMenuButtonBoundingClientRect(this.systemInfo);
3114
+ }
3115
+ getNetworkType() {
3116
+ return this.wxState.getNetworkType();
3117
+ }
3118
+ getLoading() {
3119
+ return this.wxState.getLoading();
3120
+ }
3121
+ getModalLogs() {
3122
+ return this.wxState.getModalLogs();
3123
+ }
3124
+ getToast() {
3125
+ return this.wxState.getToast();
3126
+ }
3127
+ mockModal(definition = {}) {
3128
+ this.wxState.mockModal(definition);
3129
+ }
3130
+ mockActionSheet(definition = {}) {
3131
+ this.wxState.mockActionSheet(definition);
3132
+ }
3133
+ mockRequest(definition) {
3134
+ this.wxState.mockRequest(definition);
3135
+ }
3136
+ mockDownloadFile(definition) {
3137
+ this.wxState.mockDownloadFile(definition);
3138
+ }
3139
+ mockUploadFile(definition) {
3140
+ this.wxState.mockUploadFile(definition);
3141
+ }
3142
+ setFile(filePath, fileContent) {
3143
+ this.wxState.setFile(filePath, fileContent);
3144
+ }
3145
+ setNetworkType(networkType) {
3146
+ return this.wxState.setNetworkType(networkType);
3147
+ }
3148
+ setBackgroundTextStyle(textStyle) {
3149
+ if (textStyle !== "dark" && textStyle !== "light") throw new Error("setBackgroundTextStyle:fail invalid textStyle");
3150
+ const current = this.requireCurrentPage("wx.setBackgroundTextStyle()");
3151
+ current.__background__ ??= {
3152
+ backgroundColor: "#ffffff",
3153
+ backgroundColorBottom: "#ffffff",
3154
+ backgroundColorTop: "#ffffff",
3155
+ textStyle: "dark"
3156
+ };
3157
+ current.__background__.textStyle = textStyle;
3158
+ current.__backgroundTextStyle__ = textStyle;
3159
+ return { errMsg: "setBackgroundTextStyle:ok" };
3160
+ }
3161
+ setBackgroundColor(option) {
3162
+ const current = this.requireCurrentPage("wx.setBackgroundColor()");
3163
+ current.__background__ ??= {
3164
+ backgroundColor: "#ffffff",
3165
+ backgroundColorBottom: "#ffffff",
3166
+ backgroundColorTop: "#ffffff",
3167
+ textStyle: current.__backgroundTextStyle__ ?? "dark"
3168
+ };
3169
+ if (typeof option.backgroundColor === "string") current.__background__.backgroundColor = option.backgroundColor;
3170
+ if (typeof option.backgroundColorTop === "string") current.__background__.backgroundColorTop = option.backgroundColorTop;
3171
+ if (typeof option.backgroundColorBottom === "string") current.__background__.backgroundColorBottom = option.backgroundColorBottom;
3172
+ return { errMsg: "setBackgroundColor:ok" };
3173
+ }
3174
+ setNavigationBarTitle(title) {
3175
+ const current = this.requireCurrentPage("wx.setNavigationBarTitle()");
3176
+ current.__navigationBar__ ??= {
3177
+ animation: null,
3178
+ backgroundColor: "#ffffff",
3179
+ frontColor: "#000000",
3180
+ loading: false,
3181
+ title: ""
3182
+ };
3183
+ current.__navigationBar__.title = title;
3184
+ current.__navigationBarTitle__ = title;
3185
+ return { errMsg: "setNavigationBarTitle:ok" };
3186
+ }
3187
+ setNavigationBarColor(option) {
3188
+ const current = this.requireCurrentPage("wx.setNavigationBarColor()");
3189
+ current.__navigationBar__ ??= {
3190
+ animation: null,
3191
+ backgroundColor: "#ffffff",
3192
+ frontColor: "#000000",
3193
+ loading: false,
3194
+ title: current.__navigationBarTitle__ ?? ""
3195
+ };
3196
+ if (typeof option.backgroundColor === "string") current.__navigationBar__.backgroundColor = option.backgroundColor;
3197
+ if (typeof option.frontColor === "string") current.__navigationBar__.frontColor = option.frontColor;
3198
+ current.__navigationBar__.animation = option.animation ? {
3199
+ duration: option.animation.duration,
3200
+ timingFunction: option.animation.timingFunction
3201
+ } : null;
3202
+ return { errMsg: "setNavigationBarColor:ok" };
3203
+ }
3204
+ showNavigationBarLoading() {
3205
+ const current = this.requireCurrentPage("wx.showNavigationBarLoading()");
3206
+ current.__navigationBar__ ??= {
3207
+ animation: null,
3208
+ backgroundColor: "#ffffff",
3209
+ frontColor: "#000000",
3210
+ loading: false,
3211
+ title: current.__navigationBarTitle__ ?? ""
3212
+ };
3213
+ current.__navigationBar__.loading = true;
3214
+ return { errMsg: "showNavigationBarLoading:ok" };
3215
+ }
3216
+ hideNavigationBarLoading() {
3217
+ const current = this.requireCurrentPage("wx.hideNavigationBarLoading()");
3218
+ current.__navigationBar__ ??= {
3219
+ animation: null,
3220
+ backgroundColor: "#ffffff",
3221
+ frontColor: "#000000",
3222
+ loading: false,
3223
+ title: current.__navigationBarTitle__ ?? ""
3224
+ };
3225
+ current.__navigationBar__.loading = false;
3226
+ return { errMsg: "hideNavigationBarLoading:ok" };
3227
+ }
3228
+ hideTabBar() {
3229
+ this.tabBarVisible = false;
3230
+ return { errMsg: "hideTabBar:ok" };
3231
+ }
3232
+ hideTabBarRedDot(index) {
3233
+ const item = this.requireTabBarItem(index, "wx.hideTabBarRedDot()");
3234
+ item.redDot = false;
3235
+ return { errMsg: "hideTabBarRedDot:ok" };
3236
+ }
3237
+ showTabBar() {
3238
+ this.tabBarVisible = this.tabBarRoutes.size > 0;
3239
+ return { errMsg: "showTabBar:ok" };
3240
+ }
3241
+ showTabBarRedDot(index) {
3242
+ const item = this.requireTabBarItem(index, "wx.showTabBarRedDot()");
3243
+ item.badge = null;
3244
+ item.redDot = true;
3245
+ return { errMsg: "showTabBarRedDot:ok" };
3246
+ }
3247
+ removeTabBarBadge(index) {
3248
+ const item = this.requireTabBarItem(index, "wx.removeTabBarBadge()");
3249
+ item.badge = null;
3250
+ return { errMsg: "removeTabBarBadge:ok" };
3251
+ }
3252
+ setTabBarBadge(index, text) {
3253
+ const item = this.requireTabBarItem(index, "wx.setTabBarBadge()");
3254
+ item.badge = text;
3255
+ item.redDot = false;
3256
+ return { errMsg: "setTabBarBadge:ok" };
3257
+ }
3258
+ getScopeSnapshot(scopeId) {
3259
+ const scope = this.componentScopes.get(scopeId);
3260
+ if (!scope) return null;
3261
+ const instance = this.componentCache.get(scopeId);
3262
+ if (instance) return {
3263
+ data: instance.data ?? {},
3264
+ methods: Object.keys(instance).filter((key) => typeof instance[key] === "function").sort((a, b) => a.localeCompare(b)),
3265
+ properties: instance.properties ?? {},
3266
+ scopeId,
3267
+ type: "component"
3268
+ };
3269
+ const currentPage = this.currentPageInstance;
3270
+ if (currentPage && scopeId === `page:${currentPage.route}`) return {
3271
+ data: currentPage.data ?? {},
3272
+ methods: Object.keys(currentPage).filter((key) => typeof currentPage[key] === "function").sort((a, b) => a.localeCompare(b)),
3273
+ properties: currentPage.options ?? {},
3274
+ scopeId,
3275
+ type: "page"
3276
+ };
3277
+ return {
3278
+ data: scope.data ?? {},
3279
+ methods: [],
3280
+ properties: {},
3281
+ scopeId,
3282
+ type: "scope"
3283
+ };
3284
+ }
3285
+ getScopeIdForComponent(component) {
3286
+ if (!component) return null;
3287
+ return this.getComponentScopeId(component);
3288
+ }
3289
+ selectComponent(selector) {
3290
+ return this.selectComponentsWithin(null, selector)[0] ?? null;
3291
+ }
3292
+ selectAllComponents(selector) {
3293
+ return this.selectComponentsWithin(null, selector);
3294
+ }
3295
+ selectComponentWithin(scopeId, selector) {
3296
+ return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
3297
+ }
3298
+ selectAllComponentsWithin(scopeId, selector) {
3299
+ return this.selectComponentsWithin(scopeId, selector);
3300
+ }
3301
+ selectOwnerComponent(scopeId) {
3302
+ const scope = this.componentScopes.get(scopeId);
3303
+ if (!scope?.ownerScopeId) return null;
3304
+ return this.componentCache.get(scope.ownerScopeId) ?? null;
3305
+ }
3306
+ selectComponentsWithin(rootScopeId, selector) {
3307
+ const normalizedSelector = selector.trim();
3308
+ if (!normalizedSelector) return [];
3309
+ return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
3310
+ if (!candidateScopeId.includes("/")) return false;
3311
+ if (rootScopeId && candidateScopeId === rootScopeId) return false;
3312
+ if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
3313
+ if (normalizedSelector.startsWith("#")) return scope.id === normalizedSelector.slice(1);
3314
+ if (normalizedSelector.startsWith(".")) return scope.classList?.includes(normalizedSelector.slice(1)) ?? false;
3315
+ const dataAttrMatch = normalizedSelector.match(DATA_ATTR_SELECTOR_RE$1);
3316
+ if (dataAttrMatch) {
3317
+ const [, key, value] = dataAttrMatch;
3318
+ const datasetKey = key.replace(DATASET_KEY_RE$1, (_match, char) => char.toUpperCase());
3319
+ return scope.dataset?.[datasetKey] === value;
3320
+ }
3321
+ return scope.alias === normalizedSelector;
3322
+ }).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
3323
+ }
3324
+ renderCurrentPage() {
3325
+ const current = this.requireCurrentPage("renderCurrentPage()");
3326
+ const rendered = renderBrowserPageTree({
3327
+ changedPageKeys: current.__lastChangedKeys__ ?? [],
3328
+ componentCache: this.componentCache,
3329
+ componentScopes: this.componentScopes,
3330
+ files: this.files,
3331
+ moduleLoader: this.moduleLoader,
3332
+ project: this.project,
3333
+ session: {
3334
+ selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
3335
+ selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
3336
+ selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
3337
+ }
3338
+ }, current);
3339
+ current.__lastChangedKeys__ = [];
3340
+ return rendered;
3341
+ }
3342
+ callScopeMethod(scopeId, methodName, event) {
3343
+ const current = this.requireCurrentPage(`scope method "${methodName}"`);
3344
+ this.renderCurrentPage();
3345
+ if (!scopeId || scopeId === `page:${stripLeadingSlash$1(current.route)}`) {
3346
+ const method = current[methodName];
3347
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator page ${current.route}.`);
3348
+ return method.call(current, event);
3349
+ }
3350
+ const instance = this.componentCache.get(scopeId);
3351
+ if (!instance) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
3352
+ instance.__lastInteractionEvent__ = {
3353
+ currentTarget: event.currentTarget,
3354
+ mark: event.mark,
3355
+ target: event.target
3356
+ };
3357
+ const method = instance[methodName];
3358
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator component scope "${scopeId}".`);
3359
+ return method.call(instance, event);
3360
+ }
3361
+ callScopeMethodDirect(scopeId, methodName, ...args) {
3362
+ const normalizedScopeId = scopeId.trim();
3363
+ if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in browser simulator runtime.");
3364
+ const current = this.requireCurrentPage(`scope method "${methodName}"`);
3365
+ if (normalizedScopeId === `page:${stripLeadingSlash$1(current.route)}`) {
3366
+ const method = current[methodName];
3367
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator page ${current.route}.`);
3368
+ return method.apply(current, args);
3369
+ }
3370
+ const instance = this.componentCache.get(normalizedScopeId);
3371
+ if (!instance) throw new Error(`Unknown scope "${normalizedScopeId}" in browser simulator runtime.`);
3372
+ const method = instance[methodName];
3373
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator component scope "${normalizedScopeId}".`);
3374
+ return method.apply(instance, args);
3375
+ }
3376
+ callTapBinding(scopeId, methodName) {
3377
+ const scope = this.componentScopes.get(scopeId);
3378
+ if (!scope) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
3379
+ const method = scope.getMethod(methodName);
3380
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on scope "${scopeId}" in browser simulator runtime.`);
3381
+ return method();
3382
+ }
3383
+ callTapBindingWithEvent(scopeId, methodName, event = {}) {
3384
+ const scope = this.componentScopes.get(scopeId);
3385
+ if (!scope) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
3386
+ const method = scope.getMethod(methodName);
3387
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on scope "${scopeId}" in browser simulator runtime.`);
3388
+ const instance = this.componentCache.get(scopeId);
3389
+ if (instance) instance.__lastInteractionEvent__ = {
3390
+ currentTarget: {
3391
+ dataset: event.currentTarget?.dataset ?? event.dataset ?? {},
3392
+ id: event.currentTarget?.id ?? event.id ?? ""
3393
+ },
3394
+ mark: event.mark,
3395
+ target: {
3396
+ dataset: event.target?.dataset ?? event.dataset ?? {},
3397
+ id: event.target?.id ?? event.id ?? ""
3398
+ }
3399
+ };
3400
+ return method({
3401
+ bubbles: false,
3402
+ capturePhase: false,
3403
+ composed: false,
3404
+ currentTarget: {
3405
+ dataset: event.currentTarget?.dataset ?? event.dataset ?? {},
3406
+ id: event.currentTarget?.id ?? event.id ?? ""
3407
+ },
3408
+ detail: void 0,
3409
+ mark: event.mark,
3410
+ target: {
3411
+ dataset: event.target?.dataset ?? event.dataset ?? {},
3412
+ id: event.target?.id ?? event.id ?? ""
3413
+ },
3414
+ type: "tap"
3415
+ });
3416
+ }
3417
+ bootstrap(launchOptions = createAppLaunchOptions$1("", {})) {
3418
+ if (this.appInstance) return this.appInstance;
3419
+ this.launchOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
3420
+ this.enterOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
2239
3421
  const appModulePath = join(this.project.miniprogramRootPath, "app.js");
2240
3422
  this.appDefinition = this.moduleLoader.executeAppModule(appModulePath);
2241
3423
  this.appInstance = createAppInstance(this.appDefinition);
@@ -2243,263 +3425,728 @@ var BrowserHeadlessSession = class {
2243
3425
  this.appInstance.onShow?.(launchOptions);
2244
3426
  return this.appInstance;
2245
3427
  }
2246
- reLaunch(url) {
2247
- const target = this.resolveNavigationTarget(url);
2248
- this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
2249
- this.unloadAllPages();
2250
- const pageInstance = this.createFreshPage(target);
2251
- this.pages.push(pageInstance);
2252
- this.currentPageInstance = pageInstance;
2253
- return pageInstance;
3428
+ reLaunch(url) {
3429
+ const target = this.resolveNavigationTarget(url);
3430
+ this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
3431
+ this.unloadAllPages();
3432
+ const pageInstance = this.createFreshPage(target);
3433
+ this.pages.push(pageInstance);
3434
+ this.currentPageInstance = pageInstance;
3435
+ return pageInstance;
3436
+ }
3437
+ navigateTo(url) {
3438
+ const target = this.resolveNavigationTarget(url);
3439
+ this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
3440
+ if (this.pages.length >= PAGE_STACK_LIMIT$1) throw new Error(`Cannot navigateTo() beyond a ${PAGE_STACK_LIMIT$1}-page stack in browser simulator runtime.`);
3441
+ if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
3442
+ this.currentPageInstance?.onHide?.();
3443
+ if (this.currentPageInstance) this.runPageComponentLifetime(this.currentPageInstance.route, "hide");
3444
+ const pageInstance = this.createFreshPage(target);
3445
+ this.pages.push(pageInstance);
3446
+ this.currentPageInstance = pageInstance;
3447
+ return pageInstance;
3448
+ }
3449
+ redirectTo(url) {
3450
+ const target = this.resolveNavigationTarget(url);
3451
+ this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
3452
+ if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.redirectTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
3453
+ const current = this.currentPageInstance;
3454
+ if (current) {
3455
+ this.pages.pop();
3456
+ this.unloadPage(current);
3457
+ }
3458
+ const pageInstance = this.createFreshPage(target);
3459
+ this.pages.push(pageInstance);
3460
+ this.currentPageInstance = pageInstance;
3461
+ return pageInstance;
3462
+ }
3463
+ navigateBack(delta = 1) {
3464
+ this.bootstrap();
3465
+ if (this.pages.length <= 1) return this.currentPageInstance;
3466
+ const removableCount = Math.min(Number.isFinite(delta) ? Math.max(1, Math.trunc(delta)) : 1, this.pages.length - 1);
3467
+ const removedPages = this.pages.splice(this.pages.length - removableCount, removableCount);
3468
+ for (const page of removedPages.reverse()) this.unloadPage(page);
3469
+ const nextPage = this.pages.at(-1) ?? null;
3470
+ this.currentPageInstance = nextPage;
3471
+ nextPage?.onShow?.();
3472
+ if (nextPage) this.runPageComponentLifetime(nextPage.route, "show");
3473
+ return nextPage;
3474
+ }
3475
+ switchTab(url) {
3476
+ const target = this.resolveNavigationTarget(url);
3477
+ this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
3478
+ if (Object.keys(target.query).length > 0) throw new Error(`wx.switchTab() url cannot contain query in browser simulator runtime: ${url}`);
3479
+ if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in browser simulator runtime: ${url}`);
3480
+ const current = this.currentPageInstance;
3481
+ const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
3482
+ const tabItem = this.resolveTabBarItem(target.routeRecord.route);
3483
+ if (current === cachedTarget && current) {
3484
+ current.onTabItemTap?.(tabItem);
3485
+ return current;
3486
+ }
3487
+ if (current && current !== cachedTarget) {
3488
+ current.onHide?.();
3489
+ this.runPageComponentLifetime(current.route, "hide");
3490
+ }
3491
+ for (const page of [...this.pages].reverse()) {
3492
+ if (this.isTabBarRoute(stripLeadingSlash$1(page.route))) continue;
3493
+ this.removePageInstance(page);
3494
+ this.unloadPage(page);
3495
+ }
3496
+ let nextPage = cachedTarget;
3497
+ if (!nextPage) {
3498
+ nextPage = this.createFreshPage(target);
3499
+ this.tabPages.set(target.routeRecord.route, nextPage);
3500
+ } else if (current !== nextPage) {
3501
+ nextPage.onShow?.();
3502
+ this.runPageComponentLifetime(nextPage.route, "show");
3503
+ }
3504
+ nextPage.onTabItemTap?.(tabItem);
3505
+ this.pages.length = 0;
3506
+ this.pages.push(nextPage);
3507
+ this.currentPageInstance = nextPage;
3508
+ return nextPage;
3509
+ }
3510
+ pageScrollTo(option) {
3511
+ const current = this.requireCurrentPage("wx.pageScrollTo()");
3512
+ current.__scrollTop__ = Number(option.scrollTop ?? 0);
3513
+ current.onPageScroll?.({ scrollTop: current.__scrollTop__ });
3514
+ }
3515
+ triggerPullDownRefresh() {
3516
+ const current = this.requireCurrentPage("triggerPullDownRefresh()");
3517
+ this.pullDownRefreshState = {
3518
+ ...this.pullDownRefreshState,
3519
+ active: true
3520
+ };
3521
+ current.onPullDownRefresh?.();
3522
+ return current;
3523
+ }
3524
+ triggerReachBottom() {
3525
+ const current = this.requireCurrentPage("triggerReachBottom()");
3526
+ current.onReachBottom?.();
3527
+ return current;
3528
+ }
3529
+ triggerResize(options) {
3530
+ const current = this.requireCurrentPage("triggerResize()");
3531
+ applyResizeToSystemInfo(this.systemInfo, options);
3532
+ current.onResize?.(options);
3533
+ this.runPageComponentLifetime(current.route, "resize", options);
3534
+ return current;
3535
+ }
3536
+ triggerRouteDone(options = {}) {
3537
+ const current = this.requireCurrentPage("triggerRouteDone()");
3538
+ current.onRouteDone?.(options);
3539
+ return current;
3540
+ }
3541
+ stopPullDownRefresh() {
3542
+ this.pullDownRefreshState = {
3543
+ active: false,
3544
+ stopCalls: this.pullDownRefreshState.stopCalls + 1
3545
+ };
3546
+ }
3547
+ executeSelectorQuery(requests, scope) {
3548
+ const current = this.requireCurrentPage("wx.createSelectorQuery().exec()");
3549
+ 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.");
3550
+ const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
3551
+ return executeSelectorQueryRequests(requests, {
3552
+ page: current,
3553
+ root: resolveSelectorQueryScopeRoot(renderBrowserPageTree({
3554
+ changedPageKeys: current.__lastChangedKeys__ ?? [],
3555
+ componentCache: this.componentCache,
3556
+ componentScopes: this.componentScopes,
3557
+ files: this.files,
3558
+ moduleLoader: this.moduleLoader,
3559
+ project: this.project,
3560
+ session: {
3561
+ selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
3562
+ selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
3563
+ selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
3564
+ }
3565
+ }, current).root, scopeId),
3566
+ windowInfo: this.getWindowInfo()
3567
+ });
3568
+ }
3569
+ createFreshPage(target) {
3570
+ const pageModulePath = join(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
3571
+ const pageConfigPath = join(this.project.miniprogramRootPath, `${target.routeRecord.route}.json`);
3572
+ const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
3573
+ const pageConfig = readJsonObject$2(this.files, pageConfigPath);
3574
+ const pageInstance = createPageInstance(target.routeRecord.route, pageDefinition, target.query, {
3575
+ background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
3576
+ navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
3577
+ });
3578
+ pageInstance.selectComponent = (selector) => this.selectComponent(selector);
3579
+ pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
3580
+ pageInstance.onLoad?.(target.query);
3581
+ pageInstance.onShow?.();
3582
+ pageInstance.onReady?.();
3583
+ if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
3584
+ return pageInstance;
3585
+ }
3586
+ isTabBarRoute(route) {
3587
+ return this.tabBarRoutes.has(stripLeadingSlash$1(route));
3588
+ }
3589
+ removePageInstance(page) {
3590
+ const index = this.pages.indexOf(page);
3591
+ if (index >= 0) this.pages.splice(index, 1);
3592
+ }
3593
+ resolveNavigationTarget(url) {
3594
+ const { pathname, query } = parseNavigationUrl$1(url);
3595
+ const normalizedRoute = resolveNavigationPath$1(pathname, this.currentPageInstance ? stripLeadingSlash$1(this.currentPageInstance.route) : void 0);
3596
+ const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
3597
+ if (!routeRecord) {
3598
+ this.bootstrap(createAppLaunchOptions$1(normalizedRoute, query));
3599
+ this.appInstance?.onPageNotFound?.(createAppLaunchOptions$1(normalizedRoute, query));
3600
+ throw new Error(`Unknown route for browser simulator navigation: ${url}`);
3601
+ }
3602
+ return {
3603
+ normalizedRoute,
3604
+ query,
3605
+ routeRecord
3606
+ };
3607
+ }
3608
+ resolveTabBarItem(route) {
3609
+ const pagePath = stripLeadingSlash$1(route);
3610
+ const item = this.tabBarItems.get(pagePath);
3611
+ if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in browser simulator runtime.`);
3612
+ return { ...item };
2254
3613
  }
2255
- navigateTo(url) {
2256
- const target = this.resolveNavigationTarget(url);
2257
- this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
2258
- if (this.pages.length >= PAGE_STACK_LIMIT$1) throw new Error(`Cannot navigateTo() beyond a ${PAGE_STACK_LIMIT$1}-page stack in browser simulator runtime.`);
2259
- if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
2260
- this.currentPageInstance?.onHide?.();
2261
- if (this.currentPageInstance) this.runPageComponentLifetime(this.currentPageInstance.route, "hide");
2262
- const pageInstance = this.createFreshPage(target);
2263
- this.pages.push(pageInstance);
2264
- this.currentPageInstance = pageInstance;
2265
- return pageInstance;
3614
+ requireTabBarItem(index, action) {
3615
+ const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
3616
+ const item = this.tabBarState.get(normalizedIndex);
3617
+ if (!item) throw new Error(`Cannot call ${action} with unknown tabBar index ${index} in browser simulator runtime.`);
3618
+ return item;
2266
3619
  }
2267
- redirectTo(url) {
2268
- const target = this.resolveNavigationTarget(url);
2269
- this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
2270
- if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.redirectTo() cannot open a tabBar page in browser simulator runtime: ${url}`);
3620
+ unloadAllPages() {
3621
+ const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
3622
+ for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
3623
+ this.pages.length = 0;
3624
+ this.tabPages.clear();
3625
+ this.componentCache.clear();
3626
+ this.componentScopes.clear();
3627
+ this.currentPageInstance = null;
3628
+ }
3629
+ unloadPage(page) {
3630
+ page.onUnload?.();
3631
+ this.detachPageComponents(page.route);
3632
+ this.tabPages.delete(stripLeadingSlash$1(page.route));
3633
+ }
3634
+ requireCurrentPage(action) {
3635
+ this.bootstrap();
2271
3636
  const current = this.currentPageInstance;
2272
- if (current) {
2273
- this.pages.pop();
2274
- this.unloadPage(current);
3637
+ if (!current) throw new Error(`Cannot call ${action} without an active page in browser simulator runtime.`);
3638
+ return current;
3639
+ }
3640
+ detachPageComponents(route) {
3641
+ const prefix = `page:${stripLeadingSlash$1(route)}`;
3642
+ for (const [scopeId, instance] of [...this.componentCache.entries()]) {
3643
+ if (!scopeId.startsWith(prefix)) continue;
3644
+ instance.__definition__?.lifetimes?.detached?.call(instance);
3645
+ this.componentCache.delete(scopeId);
3646
+ this.componentScopes.delete(scopeId);
2275
3647
  }
2276
- const pageInstance = this.createFreshPage(target);
2277
- this.pages.push(pageInstance);
2278
- this.currentPageInstance = pageInstance;
2279
- return pageInstance;
2280
3648
  }
2281
- navigateBack(delta = 1) {
2282
- this.bootstrap();
2283
- if (this.pages.length <= 1) return this.currentPageInstance;
2284
- const removableCount = Math.min(Number.isFinite(delta) ? Math.max(1, Math.trunc(delta)) : 1, this.pages.length - 1);
2285
- const removedPages = this.pages.splice(this.pages.length - removableCount, removableCount);
2286
- for (const page of removedPages.reverse()) this.unloadPage(page);
2287
- const nextPage = this.pages.at(-1) ?? null;
2288
- this.currentPageInstance = nextPage;
2289
- nextPage?.onShow?.();
2290
- if (nextPage) this.runPageComponentLifetime(nextPage.route, "show");
2291
- return nextPage;
3649
+ runPageComponentLifetime(route, lifetimeName, payload) {
3650
+ const prefix = `page:${stripLeadingSlash$1(route)}`;
3651
+ for (const [scopeId, instance] of this.componentCache.entries()) {
3652
+ if (!scopeId.startsWith(prefix)) continue;
3653
+ runComponentPageLifetime(instance, lifetimeName, payload);
3654
+ }
3655
+ }
3656
+ getComponentScopeId(component) {
3657
+ for (const [scopeId, instance] of this.componentCache.entries()) if (instance === component) return scopeId;
3658
+ return null;
3659
+ }
3660
+ };
3661
+ function createBrowserHeadlessSession(options) {
3662
+ return new BrowserHeadlessSession(options);
3663
+ }
3664
+ //#endregion
3665
+ //#region src/project/loadProject.ts
3666
+ function readJsonObject$1(filePath) {
3667
+ try {
3668
+ const content = fs.readFileSync(filePath, "utf8");
3669
+ const value = JSON.parse(content);
3670
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3671
+ } catch {
3672
+ return;
3673
+ }
3674
+ }
3675
+ function resolveProjectConfigFiles(projectPath) {
3676
+ const entries = [];
3677
+ for (const fileName of ["project.config.json", "project.private.config.json"]) {
3678
+ const filePath = path.resolve(projectPath, fileName);
3679
+ const value = readJsonObject$1(filePath);
3680
+ if (!value) continue;
3681
+ entries.push({
3682
+ filePath,
3683
+ value
3684
+ });
3685
+ }
3686
+ return entries;
3687
+ }
3688
+ function resolveMiniprogramRoot(projectPath, configFiles) {
3689
+ for (const configFile of [...configFiles].reverse()) {
3690
+ const rawRoot = configFile.value.miniprogramRoot;
3691
+ if (typeof rawRoot !== "string" || !rawRoot.trim()) continue;
3692
+ return rawRoot.trim();
3693
+ }
3694
+ throw new Error(`Failed to resolve miniprogramRoot for headless runtime project: ${projectPath}. Expected project.config.json or project.private.config.json to define miniprogramRoot.`);
3695
+ }
3696
+ function ensureFileExists(filePath, label) {
3697
+ if (fs.existsSync(filePath)) return;
3698
+ throw new Error(`Missing ${label} for headless runtime project: ${normalize(filePath)}`);
3699
+ }
3700
+ function loadAppConfig(appConfigPath) {
3701
+ const appConfig = readJsonObject$1(appConfigPath);
3702
+ if (!appConfig) throw new Error(`Failed to read built app.json for headless runtime project: ${normalize(appConfigPath)}`);
3703
+ return appConfig;
3704
+ }
3705
+ function loadProject(projectPath) {
3706
+ const normalizedProjectPath = path.resolve(projectPath);
3707
+ const projectConfigFiles = resolveProjectConfigFiles(normalizedProjectPath);
3708
+ if (projectConfigFiles.length === 0) throw new Error(`Missing project config for headless runtime project: ${normalizedProjectPath}. Expected project.config.json or project.private.config.json.`);
3709
+ const miniprogramRoot = resolveMiniprogramRoot(normalizedProjectPath, projectConfigFiles);
3710
+ const miniprogramRootPath = path.resolve(normalizedProjectPath, miniprogramRoot);
3711
+ ensureFileExists(miniprogramRootPath, "miniprogramRoot directory");
3712
+ const appConfigPath = path.resolve(miniprogramRootPath, "app.json");
3713
+ ensureFileExists(appConfigPath, "built app.json");
3714
+ return createProjectDescriptor({
3715
+ appConfig: loadAppConfig(appConfigPath),
3716
+ appConfigPath,
3717
+ miniprogramRoot,
3718
+ miniprogramRootPath,
3719
+ projectPath: normalizedProjectPath,
3720
+ projectConfigFiles
3721
+ });
3722
+ }
3723
+ //#endregion
3724
+ //#region src/runtime/render.ts
3725
+ const LEADING_SLASH_RE$2 = /^\/+/;
3726
+ const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
3727
+ const EVENT_BINDING_ATTRS = [
3728
+ "bindtap",
3729
+ "bind:tap",
3730
+ "catchtap",
3731
+ "catch:tap"
3732
+ ];
3733
+ const COMPONENT_EVENT_PREFIXES = [
3734
+ "bind:",
3735
+ "bind",
3736
+ "catch:",
3737
+ "catch"
3738
+ ];
3739
+ const STRUCTURAL_ATTRS = [
3740
+ "wx:if",
3741
+ "wx:elif",
3742
+ "wx:else",
3743
+ "wx:for",
3744
+ "wx:for-item",
3745
+ "wx:for-index",
3746
+ "wx:key"
3747
+ ];
3748
+ const WX_ELSE_ATTRS = new Set(["wx:elif", "wx:else"]);
3749
+ const DATASET_NAME_RE = /-([a-z])/g;
3750
+ const BRACKET_INDEX_RE = /\[(\d+)\]/g;
3751
+ const CLASS_SPLIT_RE = /\s+/;
3752
+ const JS_FILE_RE = /\.js$/;
3753
+ function isMustacheOnly(value) {
3754
+ const trimmed = value.trim();
3755
+ return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
3756
+ }
3757
+ function toDatasetKey(attributeName) {
3758
+ return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
3759
+ }
3760
+ function collectDataset(node) {
3761
+ const dataset = {};
3762
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
3763
+ if (!key.startsWith("data-") || key === "data-sim-scope" || key === "data-sim-tap" || key === "data-sim-component") continue;
3764
+ dataset[toDatasetKey(key)] = String(value);
3765
+ }
3766
+ return dataset;
3767
+ }
3768
+ function escapeText(text) {
3769
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
3770
+ }
3771
+ function escapeAttribute(value) {
3772
+ return escapeText(value).replaceAll("\"", "&quot;");
3773
+ }
3774
+ function cloneNode(node) {
3775
+ return {
3776
+ ...node,
3777
+ attribs: node.attribs ? { ...node.attribs } : void 0,
3778
+ children: node.children?.map((child) => cloneNode(child))
3779
+ };
3780
+ }
3781
+ function parseExpressionSegments(expression) {
3782
+ return expression.replace(BRACKET_INDEX_RE, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
3783
+ }
3784
+ function unwrapMustacheExpression(expression) {
3785
+ const normalized = expression.trim();
3786
+ if (isMustacheOnly(normalized)) return normalized.slice(2, -2).trim();
3787
+ return normalized;
3788
+ }
3789
+ function resolveLiteralValue(expression) {
3790
+ if (expression === "true") return true;
3791
+ if (expression === "false") return false;
3792
+ if (expression === "null") return null;
3793
+ if (expression === "undefined") return;
3794
+ if (expression.startsWith("\"") && expression.endsWith("\"") || expression.startsWith("'") && expression.endsWith("'")) return expression.slice(1, -1);
3795
+ const numericValue = Number(expression);
3796
+ if (!Number.isNaN(numericValue) && expression !== "") return numericValue;
3797
+ }
3798
+ function resolveValueByExpression(source, expression) {
3799
+ const normalized = unwrapMustacheExpression(expression);
3800
+ if (!normalized) return;
3801
+ if (normalized.startsWith("!")) return !resolveValueByExpression(source, normalized.slice(1));
3802
+ const literalValue = resolveLiteralValue(normalized);
3803
+ if (literalValue !== void 0 || normalized === "undefined") return literalValue;
3804
+ const segments = parseExpressionSegments(normalized);
3805
+ let current = source;
3806
+ for (const segment of segments) current = current?.[segment];
3807
+ return current;
3808
+ }
3809
+ function resolveValueByPath(source, expression) {
3810
+ return resolveValueByExpression(source, expression) ?? "";
3811
+ }
3812
+ function resolveRawValueByPath(source, expression) {
3813
+ return resolveValueByExpression(source, expression);
3814
+ }
3815
+ function interpolateTemplate(input, data) {
3816
+ return input.replace(TEMPLATE_INTERPOLATION_RE, (_match, expression) => {
3817
+ const value = resolveValueByPath(data, expression);
3818
+ return typeof value === "string" ? value : String(value);
3819
+ });
3820
+ }
3821
+ function readTemplateSource(filePath) {
3822
+ return fs.readFileSync(filePath, "utf8");
3823
+ }
3824
+ function parseTemplateDocument(templateSource) {
3825
+ return parseDocument(`<page>${templateSource}</page>`, {
3826
+ xmlMode: false,
3827
+ decodeEntities: false,
3828
+ recognizeSelfClosing: true
3829
+ });
3830
+ }
3831
+ function serializeDomNode(node) {
3832
+ if (node.type === "text") return escapeText(node.data ?? "");
3833
+ if (node.type === "root") return (node.children ?? []).map(serializeDomNode).join("");
3834
+ const tagName = node.name ?? "";
3835
+ if (!tagName) return (node.children ?? []).map(serializeDomNode).join("");
3836
+ return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode).join("")}</${tagName}>`;
3837
+ }
3838
+ function isTagNode(node) {
3839
+ return node.type === "tag" && typeof node.name === "string";
3840
+ }
3841
+ function isIgnorableTextNode(node) {
3842
+ return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
3843
+ }
3844
+ function resolveAttributeValue(value, scope) {
3845
+ if (isMustacheOnly(value)) {
3846
+ const expression = value.trim().slice(2, -2);
3847
+ return resolveValueByPath(scope.data, expression);
3848
+ }
3849
+ return interpolateTemplate(value, scope.data);
3850
+ }
3851
+ function resolveComponentAttributeValue(value, scope) {
3852
+ if (isMustacheOnly(value)) {
3853
+ const expression = value.trim().slice(2, -2);
3854
+ return resolveRawValueByPath(scope.data, expression);
2292
3855
  }
2293
- switchTab(url) {
2294
- const target = this.resolveNavigationTarget(url);
2295
- this.bootstrap(createAppLaunchOptions$1(target.normalizedRoute, target.query));
2296
- if (Object.keys(target.query).length > 0) throw new Error(`wx.switchTab() url cannot contain query in browser simulator runtime: ${url}`);
2297
- if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in browser simulator runtime: ${url}`);
2298
- const current = this.currentPageInstance;
2299
- const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
2300
- const tabItem = this.resolveTabBarItem(target.routeRecord.route);
2301
- if (current === cachedTarget && current) {
2302
- current.onTabItemTap?.(tabItem);
2303
- return current;
2304
- }
2305
- if (current && current !== cachedTarget) {
2306
- current.onHide?.();
2307
- this.runPageComponentLifetime(current.route, "hide");
2308
- }
2309
- for (const page of [...this.pages].reverse()) {
2310
- if (this.isTabBarRoute(stripLeadingSlash$1(page.route))) continue;
2311
- this.removePageInstance(page);
2312
- this.unloadPage(page);
2313
- }
2314
- let nextPage = cachedTarget;
2315
- if (!nextPage) {
2316
- nextPage = this.createFreshPage(target);
2317
- this.tabPages.set(target.routeRecord.route, nextPage);
2318
- } else if (current !== nextPage) {
2319
- nextPage.onShow?.();
2320
- this.runPageComponentLifetime(nextPage.route, "show");
3856
+ return interpolateTemplate(value, scope.data);
3857
+ }
3858
+ function resolveUsingComponents(ownerJsonPath, ownerFilePath) {
3859
+ try {
3860
+ const usingComponents = JSON.parse(fs.readFileSync(ownerJsonPath, "utf8")).usingComponents;
3861
+ if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
3862
+ const resolved = /* @__PURE__ */ new Map();
3863
+ for (const [alias, rawPath] of Object.entries(usingComponents)) {
3864
+ if (typeof rawPath !== "string") continue;
3865
+ const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$2, "") : path.posix.normalize(path.posix.join(path.posix.dirname(ownerFilePath), rawPath));
3866
+ resolved.set(alias, basePath.replace(LEADING_SLASH_RE$2, ""));
2321
3867
  }
2322
- nextPage.onTabItemTap?.(tabItem);
2323
- this.pages.length = 0;
2324
- this.pages.push(nextPage);
2325
- this.currentPageInstance = nextPage;
2326
- return nextPage;
2327
- }
2328
- pageScrollTo(option) {
2329
- this.requireCurrentPage("wx.pageScrollTo()").onPageScroll?.({ scrollTop: Number(option.scrollTop ?? 0) });
2330
- }
2331
- triggerPullDownRefresh() {
2332
- const current = this.requireCurrentPage("triggerPullDownRefresh()");
2333
- current.onPullDownRefresh?.();
2334
- return current;
2335
- }
2336
- triggerReachBottom() {
2337
- const current = this.requireCurrentPage("triggerReachBottom()");
2338
- current.onReachBottom?.();
2339
- return current;
2340
- }
2341
- triggerResize(options) {
2342
- const current = this.requireCurrentPage("triggerResize()");
2343
- applyResizeToSystemInfo(this.systemInfo, options);
2344
- current.onResize?.(options);
2345
- this.runPageComponentLifetime(current.route, "resize", options);
2346
- return current;
2347
- }
2348
- triggerRouteDone(options = {}) {
2349
- const current = this.requireCurrentPage("triggerRouteDone()");
2350
- current.onRouteDone?.(options);
2351
- return current;
3868
+ return resolved;
3869
+ } catch {
3870
+ return /* @__PURE__ */ new Map();
2352
3871
  }
2353
- stopPullDownRefresh() {}
2354
- createFreshPage(target) {
2355
- const pageModulePath = join(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
2356
- const pageConfigPath = join(this.project.miniprogramRootPath, `${target.routeRecord.route}.json`);
2357
- const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
2358
- const pageConfig = readJsonObject$2(this.files, pageConfigPath);
2359
- const pageInstance = createPageInstance(target.routeRecord.route, pageDefinition, target.query, {
2360
- background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
2361
- navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
3872
+ }
3873
+ function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias) {
3874
+ const componentBasePath = resolveUsingComponents(ownerJsonPath, ownerFilePath).get(alias);
3875
+ if (!componentBasePath) return null;
3876
+ const filePath = `${componentBasePath}.js`;
3877
+ const templatePath = `${componentBasePath}.wxml`;
3878
+ const absoluteFilePath = path.resolve(context.project.miniprogramRootPath, filePath);
3879
+ const absoluteTemplatePath = path.resolve(context.project.miniprogramRootPath, templatePath);
3880
+ return {
3881
+ definition: context.moduleLoader.executeComponentModule(absoluteFilePath, componentBasePath),
3882
+ filePath,
3883
+ templatePath,
3884
+ absoluteTemplatePath
3885
+ };
3886
+ }
3887
+ function collectComponentEventBindings(hostNode) {
3888
+ const eventBindings = /* @__PURE__ */ new Map();
3889
+ for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
3890
+ const matchedPrefix = COMPONENT_EVENT_PREFIXES.find((prefix) => key.startsWith(prefix));
3891
+ if (!matchedPrefix) continue;
3892
+ const eventName = key.slice(matchedPrefix.length);
3893
+ if (!eventName) continue;
3894
+ eventBindings.set(eventName, {
3895
+ method: value,
3896
+ stopAfter: matchedPrefix.startsWith("catch")
2362
3897
  });
2363
- pageInstance.selectComponent = (selector) => this.selectComponent(selector);
2364
- pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
2365
- pageInstance.onLoad?.(target.query);
2366
- pageInstance.onShow?.();
2367
- pageInstance.onReady?.();
2368
- if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
2369
- return pageInstance;
2370
- }
2371
- isTabBarRoute(route) {
2372
- return this.tabBarRoutes.has(stripLeadingSlash$1(route));
2373
- }
2374
- removePageInstance(page) {
2375
- const index = this.pages.indexOf(page);
2376
- if (index >= 0) this.pages.splice(index, 1);
2377
3898
  }
2378
- resolveNavigationTarget(url) {
2379
- const { pathname, query } = parseNavigationUrl$1(url);
2380
- const normalizedRoute = resolveNavigationPath$1(pathname, this.currentPageInstance ? stripLeadingSlash$1(this.currentPageInstance.route) : void 0);
2381
- const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
2382
- if (!routeRecord) {
2383
- this.bootstrap(createAppLaunchOptions$1(normalizedRoute, query));
2384
- this.appInstance?.onPageNotFound?.(createAppLaunchOptions$1(normalizedRoute, query));
2385
- throw new Error(`Unknown route for browser simulator navigation: ${url}`);
2386
- }
2387
- return {
2388
- normalizedRoute,
2389
- query,
2390
- routeRecord
3899
+ return eventBindings;
3900
+ }
3901
+ function buildComponentTrigger(componentScopeId, context, hostNode) {
3902
+ const hostDataset = collectDataset(hostNode);
3903
+ const hostId = hostNode.attribs?.id ?? "";
3904
+ return (instance, eventName, detail, triggerOptions) => {
3905
+ const interactionTarget = instance.__lastInteractionEvent__?.target;
3906
+ const interactionCurrentTarget = instance.__lastInteractionEvent__?.currentTarget;
3907
+ const interactionMark = instance.__lastInteractionEvent__?.mark;
3908
+ const target = {
3909
+ dataset: interactionTarget?.dataset ?? hostDataset,
3910
+ id: interactionTarget?.id ?? hostId
2391
3911
  };
3912
+ let currentScopeId = componentScopeId;
3913
+ while (currentScopeId) {
3914
+ const currentScope = context.componentScopes.get(currentScopeId);
3915
+ const binding = currentScope?.eventBindings?.get(eventName);
3916
+ const listenerScope = currentScope?.listenerScopeId ? context.componentScopes.get(currentScope.listenerScopeId) : null;
3917
+ const handler = binding && listenerScope ? listenerScope.getMethod(binding.method) : void 0;
3918
+ if (handler) handler({
3919
+ bubbles: triggerOptions?.bubbles ?? false,
3920
+ capturePhase: false,
3921
+ composed: triggerOptions?.composed ?? false,
3922
+ currentTarget: {
3923
+ dataset: currentScope?.dataset ?? interactionCurrentTarget?.dataset ?? hostDataset,
3924
+ id: currentScope?.hostId ?? interactionCurrentTarget?.id ?? hostId
3925
+ },
3926
+ detail,
3927
+ mark: interactionMark,
3928
+ target,
3929
+ type: eventName
3930
+ });
3931
+ if (binding?.stopAfter) break;
3932
+ if (!triggerOptions?.bubbles || !triggerOptions?.composed) break;
3933
+ currentScopeId = currentScope?.ownerScopeId;
3934
+ }
3935
+ };
3936
+ }
3937
+ function applyNodeBindings(node, scope) {
3938
+ if (!isTagNode(node)) {
3939
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate(node.data, scope.data);
3940
+ return;
2392
3941
  }
2393
- resolveTabBarItem(route) {
2394
- const pagePath = stripLeadingSlash$1(route);
2395
- const item = this.tabBarItems.get(pagePath);
2396
- if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in browser simulator runtime.`);
2397
- return { ...item };
2398
- }
2399
- requireTabBarItem(index, action) {
2400
- const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
2401
- const item = this.tabBarState.get(normalizedIndex);
2402
- if (!item) throw new Error(`Cannot call ${action} with unknown tabBar index ${index} in browser simulator runtime.`);
2403
- return item;
2404
- }
2405
- unloadAllPages() {
2406
- const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
2407
- for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
2408
- this.pages.length = 0;
2409
- this.tabPages.clear();
2410
- this.componentCache.clear();
2411
- this.componentScopes.clear();
2412
- this.currentPageInstance = null;
2413
- }
2414
- unloadPage(page) {
2415
- page.onUnload?.();
2416
- this.detachPageComponents(page.route);
2417
- this.tabPages.delete(stripLeadingSlash$1(page.route));
3942
+ node.attribs ??= {};
3943
+ node.attribs["data-sim-scope"] = scope.getScopeId();
3944
+ for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
3945
+ for (const [key, value] of Object.entries({ ...node.attribs })) {
3946
+ if (EVENT_BINDING_ATTRS.includes(key)) {
3947
+ node.attribs["data-sim-tap"] = value;
3948
+ continue;
3949
+ }
3950
+ node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
2418
3951
  }
2419
- requireCurrentPage(action) {
2420
- this.bootstrap();
2421
- const current = this.currentPageInstance;
2422
- if (!current) throw new Error(`Cannot call ${action} without an active page in browser simulator runtime.`);
2423
- return current;
3952
+ }
3953
+ function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
3954
+ const changedRootKeys = [];
3955
+ const previousProperties = {};
3956
+ for (const [key, value] of Object.entries(nextProperties)) {
3957
+ const nextValue = normalizeComponentPropertyValue(definition, key, value);
3958
+ const bindingExpression = bindingExpressions[key];
3959
+ const bindingAffected = !!bindingExpression && changedPageKeys.some((changedKey) => {
3960
+ return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
3961
+ });
3962
+ const previousSnapshot = instance.__propertySnapshots?.[key];
3963
+ const deepChanged = bindingAffected && JSON.stringify(previousSnapshot) !== JSON.stringify(nextValue);
3964
+ if (instance.properties[key] !== nextValue || deepChanged) {
3965
+ previousProperties[key] = instance.properties[key];
3966
+ instance.properties[key] = nextValue;
3967
+ changedRootKeys.push(key);
3968
+ }
3969
+ instance.__propertySnapshots ??= {};
3970
+ instance.__propertySnapshots[key] = cloneValue(nextValue);
2424
3971
  }
2425
- detachPageComponents(route) {
2426
- const prefix = `page:${stripLeadingSlash$1(route)}`;
2427
- for (const [scopeId, instance] of [...this.componentCache.entries()]) {
2428
- if (!scopeId.startsWith(prefix)) continue;
2429
- instance.__definition__?.lifetimes?.detached?.call(instance);
2430
- this.componentCache.delete(scopeId);
2431
- this.componentScopes.delete(scopeId);
3972
+ if (changedRootKeys.length === 0) return;
3973
+ runComponentObservers(definition, instance, changedRootKeys, previousProperties);
3974
+ }
3975
+ function createMergedScopeData(pageData, componentProperties, componentData) {
3976
+ return {
3977
+ ...pageData,
3978
+ ...componentProperties,
3979
+ ...componentData
3980
+ };
3981
+ }
3982
+ function isTruthy(value) {
3983
+ return Boolean(value);
3984
+ }
3985
+ function createLoopScope(scope, itemName, indexName, item, index) {
3986
+ return {
3987
+ ...scope,
3988
+ data: {
3989
+ ...scope.data,
3990
+ [indexName]: index,
3991
+ [itemName]: item
2432
3992
  }
2433
- }
2434
- runPageComponentLifetime(route, lifetimeName, payload) {
2435
- const prefix = `page:${stripLeadingSlash$1(route)}`;
2436
- for (const [scopeId, instance] of this.componentCache.entries()) {
2437
- if (!scopeId.startsWith(prefix)) continue;
2438
- runComponentPageLifetime(instance, lifetimeName, payload);
3993
+ };
3994
+ }
3995
+ function evaluateConditionalBranch(node, scope) {
3996
+ const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
3997
+ if (condition == null) return true;
3998
+ return isTruthy(resolveRawValueByPath(scope.data, condition));
3999
+ }
4000
+ function expandNodeByFor(node, scope) {
4001
+ const forExpression = node.attribs?.["wx:for"];
4002
+ if (!forExpression) return [{
4003
+ node,
4004
+ scope,
4005
+ instanceSuffix: ""
4006
+ }];
4007
+ const list = resolveRawValueByPath(scope.data, forExpression);
4008
+ const items = Array.isArray(list) ? list : [];
4009
+ const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
4010
+ const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
4011
+ return items.map((item, index) => ({
4012
+ node: cloneNode(node),
4013
+ scope: createLoopScope(scope, itemName, indexName, item, index),
4014
+ instanceSuffix: `:for-${index}`
4015
+ }));
4016
+ }
4017
+ function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
4018
+ return expandNodeByFor(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes));
4019
+ }
4020
+ function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
4021
+ const renderedChildren = [];
4022
+ for (let index = 0; index < children.length; index += 1) {
4023
+ const child = children[index];
4024
+ if (!isTagNode(child)) {
4025
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
4026
+ continue;
4027
+ }
4028
+ const hasConditional = child.attribs?.["wx:if"] != null;
4029
+ const isElseBranch = child.attribs?.["wx:elif"] != null || child.attribs?.["wx:else"] != null;
4030
+ if (hasConditional) {
4031
+ let branchMatched = false;
4032
+ let cursor = index;
4033
+ while (cursor < children.length) {
4034
+ const branch = children[cursor];
4035
+ if (cursor !== index && isIgnorableTextNode(branch)) {
4036
+ cursor += 1;
4037
+ continue;
4038
+ }
4039
+ if (!isTagNode(branch)) break;
4040
+ if (cursor !== index && !WX_ELSE_ATTRS.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
4041
+ if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch(branch, scope)) {
4042
+ renderedChildren.push(...renderNodeVariants(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes));
4043
+ branchMatched = true;
4044
+ }
4045
+ let nextBranchIndex = cursor + 1;
4046
+ while (nextBranchIndex < children.length && isIgnorableTextNode(children[nextBranchIndex])) nextBranchIndex += 1;
4047
+ const nextBranch = children[nextBranchIndex];
4048
+ if (!(!!nextBranch && isTagNode(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
4049
+ cursor = nextBranchIndex;
4050
+ }
4051
+ index = cursor;
4052
+ continue;
2439
4053
  }
4054
+ if (isElseBranch) continue;
4055
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
2440
4056
  }
2441
- };
2442
- function createBrowserHeadlessSession(options) {
2443
- return new BrowserHeadlessSession(options);
4057
+ return renderedChildren;
2444
4058
  }
2445
- //#endregion
2446
- //#region src/project/loadProject.ts
2447
- function readJsonObject$1(filePath) {
2448
- try {
2449
- const content = fs.readFileSync(filePath, "utf8");
2450
- const value = JSON.parse(content);
2451
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2452
- } catch {
2453
- return;
4059
+ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
4060
+ const clonedNode = cloneNode(node);
4061
+ if (!isTagNode(clonedNode)) {
4062
+ applyNodeBindings(clonedNode, scope);
4063
+ return clonedNode;
2454
4064
  }
2455
- }
2456
- function resolveProjectConfigFiles(projectPath) {
2457
- const entries = [];
2458
- for (const fileName of ["project.config.json", "project.private.config.json"]) {
2459
- const filePath = path.resolve(projectPath, fileName);
2460
- const value = readJsonObject$1(filePath);
2461
- if (!value) continue;
2462
- entries.push({
2463
- filePath,
2464
- value
2465
- });
4065
+ const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name);
4066
+ if (componentEntry) {
4067
+ const componentScopeId = `${instancePath}/${clonedNode.name}`;
4068
+ const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
4069
+ const nextProperties = {};
4070
+ const bindingExpressions = {};
4071
+ for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
4072
+ if (key.startsWith("bind")) continue;
4073
+ if (isMustacheOnly(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
4074
+ nextProperties[key] = resolveComponentAttributeValue(String(value), scope);
4075
+ }
4076
+ let componentInstance = context.componentCache.get(componentScopeId);
4077
+ if (!componentInstance) {
4078
+ componentInstance = createComponentInstance({
4079
+ definition: componentEntry.definition,
4080
+ properties: nextProperties,
4081
+ triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
4082
+ });
4083
+ componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
4084
+ componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
4085
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
4086
+ runComponentLifecycle(componentInstance, "created");
4087
+ runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
4088
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
4089
+ runComponentLifecycle(componentInstance, "attached");
4090
+ context.componentCache.set(componentScopeId, componentInstance);
4091
+ } else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
4092
+ seenComponentScopes.add(componentScopeId);
4093
+ const componentScope = {
4094
+ alias: clonedNode.name,
4095
+ classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
4096
+ data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
4097
+ dataset: collectDataset(clonedNode),
4098
+ eventBindings: collectComponentEventBindings(clonedNode),
4099
+ getMethod: (methodName) => {
4100
+ const method = componentInstance?.[methodName];
4101
+ return typeof method === "function" ? method : void 0;
4102
+ },
4103
+ getScopeId: () => componentScopeId,
4104
+ hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
4105
+ id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
4106
+ listenerScopeId: scope.getScopeId(),
4107
+ ownerScopeId
4108
+ };
4109
+ context.componentScopes.set(componentScopeId, componentScope);
4110
+ const componentDocument = parseTemplateDocument(readTemplateSource(componentEntry.absoluteTemplatePath));
4111
+ 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);
4112
+ if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
4113
+ if (!componentInstance.__ready__) {
4114
+ runComponentLifecycle(componentInstance, "ready");
4115
+ componentInstance.__ready__ = true;
4116
+ componentInstance.__definition__?.pageLifetimes?.show?.call(componentInstance);
4117
+ }
4118
+ return renderedComponentRoot;
2466
4119
  }
2467
- return entries;
4120
+ applyNodeBindings(clonedNode, scope);
4121
+ clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
4122
+ return clonedNode;
2468
4123
  }
2469
- function resolveMiniprogramRoot(projectPath, configFiles) {
2470
- for (const configFile of [...configFiles].reverse()) {
2471
- const rawRoot = configFile.value.miniprogramRoot;
2472
- if (typeof rawRoot !== "string" || !rawRoot.trim()) continue;
2473
- return rawRoot.trim();
4124
+ function renderRuntimePageTree(context, page) {
4125
+ const route = page.route.replace(LEADING_SLASH_RE$2, "");
4126
+ const document = parseTemplateDocument(readTemplateSource(path.resolve(context.project.miniprogramRootPath, `${route}.wxml`)));
4127
+ const pageScopeId = `page:${route}`;
4128
+ const pageScope = {
4129
+ data: page.data,
4130
+ getMethod: (methodName) => {
4131
+ const method = page[methodName];
4132
+ return typeof method === "function" ? method : void 0;
4133
+ },
4134
+ getScopeId: () => pageScopeId,
4135
+ id: "page-root"
4136
+ };
4137
+ context.componentScopes.clear();
4138
+ context.componentScopes.set(pageScopeId, pageScope);
4139
+ const seenComponentScopes = /* @__PURE__ */ new Set();
4140
+ const renderedRoot = renderNodeTree((document.children ?? [])[0] ?? document, pageScope, context, path.resolve(context.project.miniprogramRootPath, `${route}.json`), `${route}.js`, pageScopeId, seenComponentScopes);
4141
+ for (const [scopeId, instance] of [...context.componentCache.entries()]) if (!seenComponentScopes.has(scopeId)) {
4142
+ runComponentLifecycle(instance, "detached");
4143
+ context.componentCache.delete(scopeId);
4144
+ context.componentScopes.delete(scopeId);
2474
4145
  }
2475
- throw new Error(`Failed to resolve miniprogramRoot for headless runtime project: ${projectPath}. Expected project.config.json or project.private.config.json to define miniprogramRoot.`);
2476
- }
2477
- function ensureFileExists(filePath, label) {
2478
- if (fs.existsSync(filePath)) return;
2479
- throw new Error(`Missing ${label} for headless runtime project: ${normalize(filePath)}`);
2480
- }
2481
- function loadAppConfig(appConfigPath) {
2482
- const appConfig = readJsonObject$1(appConfigPath);
2483
- if (!appConfig) throw new Error(`Failed to read built app.json for headless runtime project: ${normalize(appConfigPath)}`);
2484
- return appConfig;
2485
- }
2486
- function loadProject(projectPath) {
2487
- const normalizedProjectPath = path.resolve(projectPath);
2488
- const projectConfigFiles = resolveProjectConfigFiles(normalizedProjectPath);
2489
- if (projectConfigFiles.length === 0) throw new Error(`Missing project config for headless runtime project: ${normalizedProjectPath}. Expected project.config.json or project.private.config.json.`);
2490
- const miniprogramRoot = resolveMiniprogramRoot(normalizedProjectPath, projectConfigFiles);
2491
- const miniprogramRootPath = path.resolve(normalizedProjectPath, miniprogramRoot);
2492
- ensureFileExists(miniprogramRootPath, "miniprogramRoot directory");
2493
- const appConfigPath = path.resolve(miniprogramRootPath, "app.json");
2494
- ensureFileExists(appConfigPath, "built app.json");
2495
- return createProjectDescriptor({
2496
- appConfig: loadAppConfig(appConfigPath),
2497
- appConfigPath,
2498
- miniprogramRoot,
2499
- miniprogramRootPath,
2500
- projectPath: normalizedProjectPath,
2501
- projectConfigFiles
2502
- });
4146
+ return {
4147
+ root: renderedRoot,
4148
+ wxml: serializeDomNode(renderedRoot)
4149
+ };
2503
4150
  }
2504
4151
  //#endregion
2505
4152
  //#region src/runtime/moduleLoader.ts
@@ -2590,15 +4237,26 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
2590
4237
  const definition = registries.pages.get(route);
2591
4238
  if (!definition) throw new Error(`Page() was not registered for route "${route}" while executing ${normalize(filePath)}.`);
2592
4239
  return definition;
4240
+ },
4241
+ executeComponentModule(filePath, id) {
4242
+ executeModule(filePath, {
4243
+ kind: "component",
4244
+ route: id
4245
+ });
4246
+ const definition = registries.components.get(id);
4247
+ if (!definition) throw new Error(`Component() was not registered for id "${id}" while executing ${normalize(filePath)}.`);
4248
+ return definition;
2593
4249
  }
2594
4250
  };
2595
4251
  }
2596
4252
  //#endregion
2597
4253
  //#region src/runtime/session.ts
2598
- const LEADING_SLASH_RE$2 = /^\/+/;
4254
+ const LEADING_SLASH_RE$1 = /^\/+/;
2599
4255
  const PAGE_STACK_LIMIT = 10;
4256
+ const DATA_ATTR_SELECTOR_RE = /^\[data-([^=\]]+)="([^"]*)"\]$/;
4257
+ const DATASET_KEY_RE = /-([a-z])/g;
2600
4258
  function stripLeadingSlash(route) {
2601
- return route.replace(LEADING_SLASH_RE$2, "");
4259
+ return route.replace(LEADING_SLASH_RE$1, "");
2602
4260
  }
2603
4261
  function normalizeQuery(queryString) {
2604
4262
  const query = new URLSearchParams(queryString);
@@ -2637,9 +4295,9 @@ function readJsonObject(filePath) {
2637
4295
  }
2638
4296
  function resolveNavigationPath(targetPath, baseRoute) {
2639
4297
  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, "");
4298
+ if (targetPath.startsWith("/")) return path.posix.normalize(targetPath).replace(LEADING_SLASH_RE$1, "");
2641
4299
  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, "");
4300
+ return path.posix.resolve(`/${path.posix.dirname(baseRoute)}`, targetPath).replace(LEADING_SLASH_RE$1, "");
2643
4301
  }
2644
4302
  var HeadlessSession = class {
2645
4303
  project;
@@ -2649,6 +4307,8 @@ var HeadlessSession = class {
2649
4307
  registries;
2650
4308
  currentPageInstance = null;
2651
4309
  pages = [];
4310
+ componentCache = /* @__PURE__ */ new Map();
4311
+ componentScopes = /* @__PURE__ */ new Map();
2652
4312
  tabBarRoutes;
2653
4313
  tabPages = /* @__PURE__ */ new Map();
2654
4314
  tabBarItems = /* @__PURE__ */ new Map();
@@ -2658,6 +4318,10 @@ var HeadlessSession = class {
2658
4318
  enterOptions = createAppLaunchOptions("", {});
2659
4319
  launchOptions = createAppLaunchOptions("", {});
2660
4320
  wxState = createHeadlessWxState();
4321
+ pullDownRefreshState = {
4322
+ active: false,
4323
+ stopCalls: 0
4324
+ };
2661
4325
  constructor(options) {
2662
4326
  this.project = loadProject(options.projectPath);
2663
4327
  this.registries = createHostRegistries();
@@ -2683,6 +4347,10 @@ var HeadlessSession = class {
2683
4347
  });
2684
4348
  this.tabBarVisible = this.tabBarRoutes.size > 0;
2685
4349
  this.moduleLoader = createModuleLoader(this.registries, () => this.pages.slice(), () => this.getApp(), {
4350
+ executeSelectorQuery: (requests, scope) => this.executeSelectorQuery(requests, scope),
4351
+ getFileSystemManager: () => this.wxState.getFileSystemManager(),
4352
+ getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
4353
+ getSavedFileList: () => this.wxState.getSavedFileList(),
2686
4354
  getEnterOptionsSync: () => ({
2687
4355
  ...this.enterOptions,
2688
4356
  query: { ...this.enterOptions.query },
@@ -2712,13 +4380,16 @@ var HeadlessSession = class {
2712
4380
  getWindowInfoSync: () => deriveWindowInfo(this.systemInfo),
2713
4381
  hideLoading: () => this.wxState.hideLoading(),
2714
4382
  hideToast: () => this.wxState.hideToast(),
4383
+ downloadFile: (option) => this.wxState.downloadFile(option),
2715
4384
  reLaunch: (option) => this.reLaunch(option.url),
2716
4385
  redirectTo: (option) => this.redirectTo(option.url),
4386
+ removeSavedFile: (option) => this.wxState.removeSavedFile(option),
2717
4387
  nextTick: (callback) => queueMicrotask(() => callback?.()),
2718
4388
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
2719
4389
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
2720
4390
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
2721
4391
  request: (option) => this.wxState.request(option),
4392
+ saveFile: (option) => this.wxState.saveFile(option),
2722
4393
  setBackgroundColor: (option) => this.setBackgroundColor(option),
2723
4394
  setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
2724
4395
  setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
@@ -2738,6 +4409,7 @@ var HeadlessSession = class {
2738
4409
  showToast: (option) => this.wxState.showToast(option),
2739
4410
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
2740
4411
  switchTab: (option) => this.switchTab(option.url),
4412
+ uploadFile: (option) => this.wxState.uploadFile(option),
2741
4413
  removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
2742
4414
  setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
2743
4415
  updateShareMenu: (option) => this.wxState.updateShareMenu(option)
@@ -2760,11 +4432,109 @@ var HeadlessSession = class {
2760
4432
  const snapshot = this.currentPageInstance?.__background__;
2761
4433
  return snapshot ? cloneBackgroundSnapshot(snapshot) : null;
2762
4434
  }
2763
- getActionSheetLogs() {
2764
- return this.wxState.getActionSheetLogs();
4435
+ getActionSheetLogs() {
4436
+ return this.wxState.getActionSheetLogs();
4437
+ }
4438
+ getRequestLogs() {
4439
+ return this.wxState.getRequestLogs();
4440
+ }
4441
+ getDownloadFileLogs() {
4442
+ return this.wxState.getDownloadFileLogs();
4443
+ }
4444
+ getUploadFileLogs() {
4445
+ return this.wxState.getUploadFileLogs();
4446
+ }
4447
+ getFileSnapshot() {
4448
+ return this.wxState.getFileSnapshot();
4449
+ }
4450
+ getDirectorySnapshot() {
4451
+ return this.wxState.getDirectorySnapshot();
4452
+ }
4453
+ getFileText(filePath) {
4454
+ return this.wxState.getFileText(filePath);
4455
+ }
4456
+ getSavedFileListSnapshot() {
4457
+ return this.wxState.getSavedFileList().fileList;
4458
+ }
4459
+ renderCurrentPage() {
4460
+ const current = this.requireCurrentPage("renderCurrentPage()");
4461
+ return renderRuntimePageTree({
4462
+ changedPageKeys: current.__lastChangedKeys__ ?? [],
4463
+ componentCache: this.componentCache,
4464
+ componentScopes: this.componentScopes,
4465
+ moduleLoader: this.moduleLoader,
4466
+ project: this.project,
4467
+ session: {
4468
+ selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
4469
+ selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
4470
+ selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
4471
+ }
4472
+ }, current);
4473
+ }
4474
+ getScopeSnapshot(scopeId) {
4475
+ const scope = this.componentScopes.get(scopeId);
4476
+ if (!scope) return null;
4477
+ const instance = this.componentCache.get(scopeId);
4478
+ if (instance) return {
4479
+ data: instance.data ?? {},
4480
+ methods: Object.keys(instance).filter((key) => typeof instance[key] === "function").sort((a, b) => a.localeCompare(b)),
4481
+ properties: instance.properties ?? {},
4482
+ scopeId,
4483
+ type: "component"
4484
+ };
4485
+ const currentPage = this.currentPageInstance;
4486
+ if (currentPage && scopeId === `page:${currentPage.route}`) return {
4487
+ data: currentPage.data ?? {},
4488
+ methods: Object.keys(currentPage).filter((key) => typeof currentPage[key] === "function").sort((a, b) => a.localeCompare(b)),
4489
+ properties: currentPage.options ?? {},
4490
+ scopeId,
4491
+ type: "page"
4492
+ };
4493
+ return {
4494
+ data: scope.data ?? {},
4495
+ methods: [],
4496
+ properties: {},
4497
+ scopeId,
4498
+ type: "scope"
4499
+ };
2765
4500
  }
2766
- getRequestLogs() {
2767
- return this.wxState.getRequestLogs();
4501
+ getScopeIdForComponent(component) {
4502
+ if (!component) return null;
4503
+ return this.getComponentScopeId(component);
4504
+ }
4505
+ callScopeMethod(scopeId, methodName, event) {
4506
+ const current = this.requireCurrentPage(`scope method "${methodName}"`);
4507
+ this.renderCurrentPage();
4508
+ if (!scopeId || scopeId === `page:${stripLeadingSlash(current.route)}`) {
4509
+ const method = current[methodName];
4510
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${current.route}.`);
4511
+ return method.call(current, event);
4512
+ }
4513
+ const instance = this.componentCache.get(scopeId);
4514
+ if (!instance) throw new Error(`Unknown scope "${scopeId}" in headless runtime.`);
4515
+ instance.__lastInteractionEvent__ = {
4516
+ currentTarget: event.currentTarget,
4517
+ mark: event.mark,
4518
+ target: event.target
4519
+ };
4520
+ const method = instance[methodName];
4521
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless component scope "${scopeId}".`);
4522
+ return method.call(instance, event);
4523
+ }
4524
+ callScopeMethodDirect(scopeId, methodName, ...args) {
4525
+ const normalizedScopeId = scopeId.trim();
4526
+ if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in headless runtime.");
4527
+ const current = this.requireCurrentPage(`scope method "${methodName}"`);
4528
+ if (normalizedScopeId === `page:${stripLeadingSlash(current.route)}`) {
4529
+ const method = current[methodName];
4530
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${current.route}.`);
4531
+ return method.apply(current, args);
4532
+ }
4533
+ const instance = this.componentCache.get(normalizedScopeId);
4534
+ if (!instance) throw new Error(`Unknown scope "${normalizedScopeId}" in headless runtime.`);
4535
+ const method = instance[methodName];
4536
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless component scope "${normalizedScopeId}".`);
4537
+ return method.apply(instance, args);
2768
4538
  }
2769
4539
  getStorageSnapshot() {
2770
4540
  return this.wxState.getStorageSnapshot();
@@ -2772,6 +4542,27 @@ var HeadlessSession = class {
2772
4542
  getShareMenu() {
2773
4543
  return this.wxState.getShareMenu();
2774
4544
  }
4545
+ selectComponent(selector) {
4546
+ this.renderCurrentPage();
4547
+ return this.selectComponentsWithin(null, selector)[0] ?? null;
4548
+ }
4549
+ selectAllComponents(selector) {
4550
+ this.renderCurrentPage();
4551
+ return this.selectComponentsWithin(null, selector);
4552
+ }
4553
+ selectComponentWithin(scopeId, selector) {
4554
+ this.renderCurrentPage();
4555
+ return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
4556
+ }
4557
+ selectAllComponentsWithin(scopeId, selector) {
4558
+ this.renderCurrentPage();
4559
+ return this.selectComponentsWithin(scopeId, selector);
4560
+ }
4561
+ selectOwnerComponent(scopeId) {
4562
+ const scope = this.componentScopes.get(scopeId);
4563
+ if (!scope?.ownerScopeId) return null;
4564
+ return this.componentCache.get(scope.ownerScopeId) ?? null;
4565
+ }
2775
4566
  getTabBar() {
2776
4567
  return { visible: this.tabBarVisible };
2777
4568
  }
@@ -2790,6 +4581,9 @@ var HeadlessSession = class {
2790
4581
  getStorageInfo() {
2791
4582
  return this.wxState.getStorageInfoSync();
2792
4583
  }
4584
+ getPullDownRefreshState() {
4585
+ return { ...this.pullDownRefreshState };
4586
+ }
2793
4587
  getSystemInfo() {
2794
4588
  return { ...this.systemInfo };
2795
4589
  }
@@ -2843,6 +4637,15 @@ var HeadlessSession = class {
2843
4637
  mockRequest(definition) {
2844
4638
  this.wxState.mockRequest(definition);
2845
4639
  }
4640
+ mockDownloadFile(definition) {
4641
+ this.wxState.mockDownloadFile(definition);
4642
+ }
4643
+ mockUploadFile(definition) {
4644
+ this.wxState.mockUploadFile(definition);
4645
+ }
4646
+ setFile(filePath, fileContent) {
4647
+ this.wxState.setFile(filePath, fileContent);
4648
+ }
2846
4649
  setNetworkType(networkType) {
2847
4650
  return this.wxState.setNetworkType(networkType);
2848
4651
  }
@@ -2982,6 +4785,7 @@ var HeadlessSession = class {
2982
4785
  if (this.pages.length >= PAGE_STACK_LIMIT) throw new Error(`Cannot navigateTo() beyond a ${PAGE_STACK_LIMIT}-page stack in headless runtime.`);
2983
4786
  if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in headless runtime: ${url}`);
2984
4787
  this.currentPageInstance?.onHide?.();
4788
+ if (this.currentPageInstance) this.runPageComponentLifetime(this.currentPageInstance.route, "hide");
2985
4789
  const pageInstance = this.createFreshPage(target);
2986
4790
  this.pages.push(pageInstance);
2987
4791
  this.currentPageInstance = pageInstance;
@@ -3010,6 +4814,7 @@ var HeadlessSession = class {
3010
4814
  const nextPage = this.pages.at(-1) ?? null;
3011
4815
  this.currentPageInstance = nextPage;
3012
4816
  nextPage?.onShow?.();
4817
+ if (nextPage) this.runPageComponentLifetime(nextPage.route, "show");
3013
4818
  return nextPage;
3014
4819
  }
3015
4820
  switchTab(url) {
@@ -3024,7 +4829,10 @@ var HeadlessSession = class {
3024
4829
  current.onTabItemTap?.(tabItem);
3025
4830
  return current;
3026
4831
  }
3027
- if (current && current !== cachedTarget) current.onHide?.();
4832
+ if (current && current !== cachedTarget) {
4833
+ current.onHide?.();
4834
+ this.runPageComponentLifetime(current.route, "hide");
4835
+ }
3028
4836
  for (const page of [...this.pages].reverse()) {
3029
4837
  if (this.isTabBarRoute(stripLeadingSlash(page.route))) continue;
3030
4838
  this.removePageInstance(page);
@@ -3034,7 +4842,10 @@ var HeadlessSession = class {
3034
4842
  if (!nextPage) {
3035
4843
  nextPage = this.createFreshPage(target);
3036
4844
  this.tabPages.set(target.routeRecord.route, nextPage);
3037
- } else if (current !== nextPage) nextPage.onShow?.();
4845
+ } else if (current !== nextPage) {
4846
+ nextPage.onShow?.();
4847
+ this.runPageComponentLifetime(nextPage.route, "show");
4848
+ }
3038
4849
  nextPage.onTabItemTap?.(tabItem);
3039
4850
  this.pages.length = 0;
3040
4851
  this.pages.push(nextPage);
@@ -3042,10 +4853,16 @@ var HeadlessSession = class {
3042
4853
  return nextPage;
3043
4854
  }
3044
4855
  pageScrollTo(option) {
3045
- this.requireCurrentPage("wx.pageScrollTo()").onPageScroll?.({ scrollTop: Number(option.scrollTop ?? 0) });
4856
+ const current = this.requireCurrentPage("wx.pageScrollTo()");
4857
+ current.__scrollTop__ = Number(option.scrollTop ?? 0);
4858
+ current.onPageScroll?.({ scrollTop: current.__scrollTop__ });
3046
4859
  }
3047
4860
  triggerPullDownRefresh() {
3048
4861
  const current = this.requireCurrentPage("triggerPullDownRefresh()");
4862
+ this.pullDownRefreshState = {
4863
+ ...this.pullDownRefreshState,
4864
+ active: true
4865
+ };
3049
4866
  current.onPullDownRefresh?.();
3050
4867
  return current;
3051
4868
  }
@@ -3058,315 +4875,153 @@ var HeadlessSession = class {
3058
4875
  const current = this.requireCurrentPage("triggerResize()");
3059
4876
  applyResizeToSystemInfo(this.systemInfo, options);
3060
4877
  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;
4878
+ this.runPageComponentLifetime(current.route, "resize", options);
4879
+ return current;
3257
4880
  }
3258
- async $(selector) {
3259
- const match = querySelectorAll(this.node, selector)[0];
3260
- return match ? new HeadlessTestingNodeHandle(match, this.interactions) : null;
4881
+ triggerRouteDone(options = {}) {
4882
+ const current = this.requireCurrentPage("triggerRouteDone()");
4883
+ current.onRouteDone?.(options);
4884
+ return current;
3261
4885
  }
3262
- async $$(selector) {
3263
- return querySelectorAll(this.node, selector).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
4886
+ stopPullDownRefresh() {
4887
+ this.pullDownRefreshState = {
4888
+ active: false,
4889
+ stopCalls: this.pullDownRefreshState.stopCalls + 1
4890
+ };
3264
4891
  }
3265
- async attr(name) {
3266
- return this.node.attribs?.[name];
4892
+ executeSelectorQuery(requests, scope) {
4893
+ const current = this.requireCurrentPage("wx.createSelectorQuery().exec()");
4894
+ 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.");
4895
+ const rendered = this.renderCurrentPage();
4896
+ const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
4897
+ return executeSelectorQueryRequests(requests, {
4898
+ page: current,
4899
+ root: resolveSelectorQueryScopeRoot(rendered.root, scopeId),
4900
+ windowInfo: this.getWindowInfo()
4901
+ });
3267
4902
  }
3268
- async dataset() {
3269
- return collectDataset(this.node);
4903
+ createFreshPage(target) {
4904
+ const pageModulePath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
4905
+ const pageConfigPath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.json`);
4906
+ const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
4907
+ const pageConfig = readJsonObject(pageConfigPath);
4908
+ const pageInstance = createPageInstance(`/${target.routeRecord.route}`, pageDefinition, target.query, {
4909
+ background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
4910
+ navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
4911
+ });
4912
+ pageInstance.selectComponent = (selector) => this.selectComponent(selector);
4913
+ pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
4914
+ pageInstance.onLoad?.(target.query);
4915
+ pageInstance.onShow?.();
4916
+ pageInstance.onReady?.();
4917
+ if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
4918
+ return pageInstance;
3270
4919
  }
3271
- async text() {
3272
- return collectText(this.node);
4920
+ isTabBarRoute(route) {
4921
+ return this.tabBarRoutes.has(stripLeadingSlash(route));
3273
4922
  }
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));
4923
+ resolveTabBarItem(route) {
4924
+ const pagePath = stripLeadingSlash(route);
4925
+ const item = this.tabBarItems.get(pagePath);
4926
+ if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in headless runtime.`);
4927
+ return { ...item };
3281
4928
  }
3282
- async tap(event = {}) {
3283
- return await this.trigger("tap", event);
4929
+ requireTabBarItem(index, action) {
4930
+ const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
4931
+ const item = this.tabBarState.get(normalizedIndex);
4932
+ if (!item) throw new Error(`Cannot call ${action} with unknown tabBar index ${index} in headless runtime.`);
4933
+ return item;
3284
4934
  }
3285
- async input(value, event = {}) {
3286
- return await this.trigger("input", {
3287
- ...event,
3288
- detail: createValueEventDetail(value, event.detail)
3289
- });
4935
+ removePageInstance(page) {
4936
+ const index = this.pages.indexOf(page);
4937
+ if (index >= 0) this.pages.splice(index, 1);
3290
4938
  }
3291
- async change(value, event = {}) {
3292
- return await this.trigger("change", {
3293
- ...event,
3294
- detail: createValueEventDetail(value, event.detail)
3295
- });
4939
+ resolveNavigationTarget(url) {
4940
+ const { pathname, query } = parseNavigationUrl(url);
4941
+ const normalizedRoute = resolveNavigationPath(pathname, this.currentPageInstance ? stripLeadingSlash(this.currentPageInstance.route) : void 0);
4942
+ const routeRecord = this.project.routes.find((item) => item.route === normalizedRoute);
4943
+ if (!routeRecord) {
4944
+ this.bootstrap(createAppLaunchOptions(normalizedRoute, query));
4945
+ this.appInstance?.onPageNotFound?.(createAppLaunchOptions(normalizedRoute, query));
4946
+ throw new Error(`Unknown route for headless runtime navigation: ${url}`);
4947
+ }
4948
+ return {
4949
+ normalizedRoute,
4950
+ query,
4951
+ routeRecord
4952
+ };
3296
4953
  }
3297
- async blur(value, event = {}) {
3298
- return await this.trigger("blur", {
3299
- ...event,
3300
- detail: value == null ? event.detail : createValueEventDetail(value, event.detail)
3301
- });
4954
+ unloadAllPages() {
4955
+ const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
4956
+ for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
4957
+ this.pages.length = 0;
4958
+ this.tabPages.clear();
4959
+ this.componentCache.clear();
4960
+ this.componentScopes.clear();
4961
+ this.currentPageInstance = null;
3302
4962
  }
3303
- async wxml() {
3304
- return serializeNode(this.node);
4963
+ unloadPage(page) {
4964
+ page.onUnload?.();
4965
+ this.detachPageComponents(page.route);
4966
+ this.tabPages.delete(stripLeadingSlash(page.route));
4967
+ }
4968
+ requireCurrentPage(action) {
4969
+ this.bootstrap();
4970
+ const current = this.currentPageInstance;
4971
+ if (!current) throw new Error(`Cannot call ${action} without an active page in headless runtime.`);
4972
+ return current;
4973
+ }
4974
+ selectComponentsWithin(rootScopeId, selector) {
4975
+ const normalizedSelector = selector.trim();
4976
+ if (!normalizedSelector) return [];
4977
+ return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
4978
+ if (!candidateScopeId.includes("/")) return false;
4979
+ if (rootScopeId && candidateScopeId === rootScopeId) return false;
4980
+ if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
4981
+ if (normalizedSelector.startsWith("#")) return scope.id === normalizedSelector.slice(1);
4982
+ if (normalizedSelector.startsWith(".")) return scope.classList?.includes(normalizedSelector.slice(1)) ?? false;
4983
+ const dataAttrMatch = normalizedSelector.match(DATA_ATTR_SELECTOR_RE);
4984
+ if (dataAttrMatch) {
4985
+ const [, key, value] = dataAttrMatch;
4986
+ const datasetKey = key.replace(DATASET_KEY_RE, (_match, char) => char.toUpperCase());
4987
+ return scope.dataset?.[datasetKey] === value;
4988
+ }
4989
+ return scope.alias === normalizedSelector;
4990
+ }).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
4991
+ }
4992
+ detachPageComponents(route) {
4993
+ const prefix = `page:${stripLeadingSlash(route)}`;
4994
+ for (const [scopeId, instance] of [...this.componentCache.entries()]) {
4995
+ if (!scopeId.startsWith(prefix)) continue;
4996
+ instance.__definition__?.lifetimes?.detached?.call(instance);
4997
+ this.componentCache.delete(scopeId);
4998
+ this.componentScopes.delete(scopeId);
4999
+ }
5000
+ }
5001
+ runPageComponentLifetime(route, lifetimeName, payload) {
5002
+ const prefix = `page:${stripLeadingSlash(route)}`;
5003
+ for (const [scopeId, instance] of this.componentCache.entries()) {
5004
+ if (!scopeId.startsWith(prefix)) continue;
5005
+ instance.__definition__?.pageLifetimes?.[lifetimeName]?.call(instance, payload);
5006
+ }
5007
+ }
5008
+ getComponentScopeId(component) {
5009
+ for (const [scopeId, instance] of this.componentCache.entries()) if (instance === component) return scopeId;
5010
+ return null;
3305
5011
  }
3306
5012
  };
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
- };
5013
+ function createHeadlessSession(options) {
5014
+ return new HeadlessSession(options);
3361
5015
  }
3362
5016
  //#endregion
3363
5017
  //#region src/testing/pageHandle.ts
3364
5018
  const DEFAULT_WAIT_TIMEOUT$1 = 1e3;
3365
5019
  const DEFAULT_WAIT_INTERVAL$1 = 10;
3366
5020
  var HeadlessTestingPageHandle = class {
3367
- constructor(project, page) {
5021
+ constructor(project, page, session) {
3368
5022
  this.project = project;
3369
5023
  this.page = page;
5024
+ this.session = session;
3370
5025
  }
3371
5026
  resolveDataByPath(path) {
3372
5027
  if (!path) return this.page.data;
@@ -3386,6 +5041,10 @@ var HeadlessTestingPageHandle = class {
3386
5041
  await this.waitFor(interval);
3387
5042
  }
3388
5043
  }
5044
+ createScopeHandle(component) {
5045
+ const scopeId = this.session?.getScopeIdForComponent(component);
5046
+ return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
5047
+ }
3389
5048
  async callMethod(methodName, ...args) {
3390
5049
  const method = this.page[methodName];
3391
5050
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${this.page.route}.`);
@@ -3394,13 +5053,41 @@ var HeadlessTestingPageHandle = class {
3394
5053
  async data(path) {
3395
5054
  return this.resolveDataByPath(path);
3396
5055
  }
5056
+ async selectComponent(selector) {
5057
+ const normalizedSelector = selector.trim();
5058
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
5059
+ const component = this.page.selectComponent?.(normalizedSelector) ?? null;
5060
+ return this.createScopeHandle(component);
5061
+ }
5062
+ async selectAllComponents(selector) {
5063
+ const normalizedSelector = selector.trim();
5064
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
5065
+ return (this.page.selectAllComponents?.(normalizedSelector) ?? []).map((component) => this.createScopeHandle(component)).filter((handle) => Boolean(handle));
5066
+ }
3397
5067
  async waitFor(ms = 0) {
3398
5068
  if (ms <= 0) return;
3399
5069
  await new Promise((resolve) => setTimeout(resolve, ms));
3400
5070
  }
3401
5071
  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) });
5072
+ const tree = this.session?.getCurrentPages().includes(this.page) ? this.session.renderCurrentPage() : renderPageTree(this.project, this.page);
5073
+ const root = new HeadlessTestingNodeHandle(tree.root.type === "root" ? tree.root.children?.[0] ?? tree.root : tree.root, {
5074
+ callMethod: (scopeId, methodName, event) => {
5075
+ if (this.session?.getCurrentPages().includes(this.page)) return this.session.callScopeMethod(scopeId, methodName, event);
5076
+ return this.callMethod(methodName, event);
5077
+ },
5078
+ createPageHandle: () => this,
5079
+ createScopeHandle: (scopeId) => {
5080
+ if (!this.session) throw new Error("Scope handles are not available without an active headless testing session.");
5081
+ if (!scopeId) return null;
5082
+ return new HeadlessTestingScopeHandle(scopeId, this.project, this.session);
5083
+ },
5084
+ ownerScopeId: (scopeId) => {
5085
+ if (!this.session || !scopeId) return null;
5086
+ if (this.session.getScopeSnapshot(scopeId)?.type !== "component") return null;
5087
+ const owner = this.session.selectOwnerComponent(scopeId);
5088
+ return this.session.getScopeIdForComponent(owner);
5089
+ }
5090
+ });
3404
5091
  if (selector === "page") return root;
3405
5092
  return await root.$(selector);
3406
5093
  }
@@ -3419,6 +5106,20 @@ var HeadlessTestingPageHandle = class {
3419
5106
  }
3420
5107
  return await this.pollUntil(async () => await this.$(normalizedSelector), `Timed out waiting for selector "${normalizedSelector}" to appear in headless testing runtime.`, options);
3421
5108
  }
5109
+ async waitForComponent(selector, options = {}) {
5110
+ const normalizedSelector = selector.trim();
5111
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
5112
+ return await this.pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
5113
+ }
5114
+ async waitForComponents(selector, count = 1, options = {}) {
5115
+ const normalizedSelector = selector.trim();
5116
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
5117
+ const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
5118
+ return await this.pollUntil(async () => {
5119
+ const components = await this.selectAllComponents(normalizedSelector);
5120
+ return components.length >= normalizedCount ? components : null;
5121
+ }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
5122
+ }
3422
5123
  async waitForText(text, options = {}) {
3423
5124
  const normalizedText = text.trim();
3424
5125
  if (!normalizedText) throw new Error("Text must be a non-empty string in headless testing runtime.");
@@ -3445,7 +5146,7 @@ var HeadlessTestingPageHandle = class {
3445
5146
  }, `Timed out waiting for data "${normalizedPath}" in headless testing runtime.`, options);
3446
5147
  }
3447
5148
  async wxml() {
3448
- return renderPageTree(this.project, this.page).wxml;
5149
+ return this.session?.getCurrentPages().includes(this.page) ? this.session.renderCurrentPage().wxml : renderPageTree(this.project, this.page).wxml;
3449
5150
  }
3450
5151
  };
3451
5152
  //#endregion
@@ -3456,6 +5157,88 @@ const DEFAULT_WAIT_INTERVAL = 10;
3456
5157
  function normalizeRoute(route) {
3457
5158
  return route.replace(LEADING_SLASH_RE, "");
3458
5159
  }
5160
+ function resolvePageScopeId(scopeId) {
5161
+ const pagePathIndex = scopeId.indexOf("/page/");
5162
+ return pagePathIndex >= 0 ? scopeId.slice(0, pagePathIndex) : scopeId;
5163
+ }
5164
+ var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
5165
+ constructor(scopeId, project, session) {
5166
+ this.scopeId = scopeId;
5167
+ this.project = project;
5168
+ this.session = session;
5169
+ }
5170
+ createScopeHandle(component) {
5171
+ const scopeId = this.session.getScopeIdForComponent(component);
5172
+ return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
5173
+ }
5174
+ async callMethod(methodName, ...args) {
5175
+ const normalizedMethodName = methodName.trim();
5176
+ if (!normalizedMethodName) throw new Error("Method name must be a non-empty string in headless testing runtime.");
5177
+ return this.session.callScopeMethodDirect(this.scopeId, normalizedMethodName, ...args);
5178
+ }
5179
+ async snapshot() {
5180
+ return this.session.getScopeSnapshot(this.scopeId);
5181
+ }
5182
+ async page() {
5183
+ const currentPage = this.session.getCurrentPages().at(-1);
5184
+ return currentPage ? new HeadlessTestingPageHandle(this.project, currentPage, this.session) : null;
5185
+ }
5186
+ async pageScope() {
5187
+ return new HeadlessTestingScopeHandle(resolvePageScopeId(this.scopeId), this.project, this.session);
5188
+ }
5189
+ async ownerComponent() {
5190
+ return this.createScopeHandle(this.session.selectOwnerComponent(this.scopeId));
5191
+ }
5192
+ async waitForOwnerComponent(options = {}) {
5193
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
5194
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
5195
+ const deadline = Date.now() + timeout;
5196
+ while (true) {
5197
+ const owner = await this.ownerComponent();
5198
+ if (owner) return owner;
5199
+ if (Date.now() >= deadline) throw new Error("Timed out waiting for owner component in headless testing runtime.");
5200
+ await new Promise((resolve) => setTimeout(resolve, interval));
5201
+ }
5202
+ }
5203
+ async selectComponent(selector) {
5204
+ const normalizedSelector = selector.trim();
5205
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
5206
+ const component = this.session.selectComponentWithin(this.scopeId, normalizedSelector);
5207
+ return this.createScopeHandle(component);
5208
+ }
5209
+ async selectAllComponents(selector) {
5210
+ const normalizedSelector = selector.trim();
5211
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
5212
+ return this.session.selectAllComponentsWithin(this.scopeId, normalizedSelector).map((component) => this.createScopeHandle(component)).filter((handle) => Boolean(handle));
5213
+ }
5214
+ async waitForComponent(selector, options = {}) {
5215
+ const normalizedSelector = selector.trim();
5216
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
5217
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
5218
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
5219
+ const deadline = Date.now() + timeout;
5220
+ while (true) {
5221
+ const component = await this.selectComponent(normalizedSelector);
5222
+ if (component) return component;
5223
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`);
5224
+ await new Promise((resolve) => setTimeout(resolve, interval));
5225
+ }
5226
+ }
5227
+ async waitForComponents(selector, count = 1, options = {}) {
5228
+ const normalizedSelector = selector.trim();
5229
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
5230
+ const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
5231
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
5232
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
5233
+ const deadline = Date.now() + timeout;
5234
+ while (true) {
5235
+ const components = await this.selectAllComponents(normalizedSelector);
5236
+ if (components.length >= normalizedCount) return components;
5237
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`);
5238
+ await new Promise((resolve) => setTimeout(resolve, interval));
5239
+ }
5240
+ }
5241
+ };
3459
5242
  var HeadlessTestingSessionHandle = class {
3460
5243
  constructor(project, session) {
3461
5244
  this.project = project;
@@ -3479,14 +5262,45 @@ var HeadlessTestingSessionHandle = class {
3479
5262
  async close() {}
3480
5263
  async currentPage() {
3481
5264
  const current = this.session.getCurrentPages().at(-1);
3482
- return current ? new HeadlessTestingPageHandle(this.project, current) : null;
5265
+ return current ? new HeadlessTestingPageHandle(this.project, current, this.session) : null;
3483
5266
  }
3484
5267
  async getCurrentPages() {
3485
- return this.session.getCurrentPages().map((page) => new HeadlessTestingPageHandle(this.project, page));
5268
+ return this.session.getCurrentPages().map((page) => new HeadlessTestingPageHandle(this.project, page, this.session));
5269
+ }
5270
+ async scopeSnapshot(scopeId) {
5271
+ const normalizedScopeId = scopeId.trim();
5272
+ if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in headless testing runtime.");
5273
+ return this.session.getScopeSnapshot(normalizedScopeId);
5274
+ }
5275
+ async selectComponent(selector) {
5276
+ const normalizedSelector = selector.trim();
5277
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
5278
+ const component = this.session.selectComponent(normalizedSelector);
5279
+ const scopeId = this.session.getScopeIdForComponent(component);
5280
+ return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
5281
+ }
5282
+ async selectAllComponents(selector) {
5283
+ const normalizedSelector = selector.trim();
5284
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
5285
+ return this.session.selectAllComponents(normalizedSelector).map((component) => this.session.getScopeIdForComponent(component)).filter((scopeId) => Boolean(scopeId)).map((scopeId) => new HeadlessTestingScopeHandle(scopeId, this.project, this.session));
5286
+ }
5287
+ async waitForComponent(selector, options = {}) {
5288
+ const normalizedSelector = selector.trim();
5289
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
5290
+ return await this.pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
5291
+ }
5292
+ async waitForComponents(selector, count = 1, options = {}) {
5293
+ const normalizedSelector = selector.trim();
5294
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
5295
+ const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
5296
+ return await this.pollUntil(async () => {
5297
+ const components = await this.selectAllComponents(normalizedSelector);
5298
+ return components.length >= normalizedCount ? components : null;
5299
+ }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
3486
5300
  }
3487
5301
  async reLaunch(route) {
3488
5302
  const page = this.session.reLaunch(route);
3489
- return new HeadlessTestingPageHandle(this.project, page);
5303
+ return new HeadlessTestingPageHandle(this.project, page, this.session);
3490
5304
  }
3491
5305
  async waitForCurrentPage(route, options = {}) {
3492
5306
  const normalizedRoute = route?.trim();
@@ -3494,7 +5308,7 @@ var HeadlessTestingSessionHandle = class {
3494
5308
  return await this.pollUntil(async () => {
3495
5309
  const currentPageInstance = this.session.getCurrentPages().at(-1);
3496
5310
  if (!currentPageInstance) return null;
3497
- const current = new HeadlessTestingPageHandle(this.project, currentPageInstance);
5311
+ const current = new HeadlessTestingPageHandle(this.project, currentPageInstance, this.session);
3498
5312
  if (!normalizedRoute) return current;
3499
5313
  if (normalizeRoute(currentPageInstance.route) === normalizeRoute(normalizedRoute)) return current;
3500
5314
  return null;
@@ -3524,4 +5338,4 @@ async function launch(options) {
3524
5338
  return new HeadlessTestingSessionHandle(session.project, session);
3525
5339
  }
3526
5340
  //#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 };
5341
+ 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 };