@mpcore/simulator 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -48,25 +48,292 @@ function invokeWxApi(operation, option) {
48
48
  return;
49
49
  }
50
50
  }
51
+ function resolveCapabilityValue(source, schema) {
52
+ const segments = schema.split(".").map((segment) => segment.trim()).filter(Boolean);
53
+ let current = source;
54
+ for (const segment of segments) {
55
+ if (current == null || !(segment in current)) return;
56
+ current = current[segment];
57
+ }
58
+ return current;
59
+ }
51
60
  function createHeadlessWx(driver) {
61
+ const capabilityTree = {
62
+ canIUse: true,
63
+ clearStorage: true,
64
+ clearStorageSync: true,
65
+ createSelectorQuery: true,
66
+ getAppBaseInfo: { return: {
67
+ SDKVersion: true,
68
+ enableDebug: true,
69
+ host: { env: true },
70
+ language: true,
71
+ platform: true,
72
+ version: true
73
+ } },
74
+ getAppBaseInfoSync: { return: {
75
+ SDKVersion: true,
76
+ enableDebug: true,
77
+ host: { env: true },
78
+ language: true,
79
+ platform: true,
80
+ version: true
81
+ } },
82
+ getEnterOptionsSync: { return: {
83
+ path: true,
84
+ query: true,
85
+ referrerInfo: {
86
+ appId: true,
87
+ extraData: true
88
+ },
89
+ scene: true
90
+ } },
91
+ getLaunchOptionsSync: { return: {
92
+ path: true,
93
+ query: true,
94
+ referrerInfo: {
95
+ appId: true,
96
+ extraData: true
97
+ },
98
+ scene: true
99
+ } },
100
+ getMenuButtonBoundingClientRect: { return: {
101
+ bottom: true,
102
+ height: true,
103
+ left: true,
104
+ right: true,
105
+ top: true,
106
+ width: true
107
+ } },
108
+ getNetworkType: { return: { networkType: true } },
109
+ getStorage: true,
110
+ getStorageInfo: { return: {
111
+ currentSize: true,
112
+ keys: true,
113
+ limitSize: true
114
+ } },
115
+ getStorageInfoSync: { return: {
116
+ currentSize: true,
117
+ keys: true,
118
+ limitSize: true
119
+ } },
120
+ getStorageSync: true,
121
+ getSystemInfo: { return: {
122
+ SDKVersion: true,
123
+ brand: true,
124
+ language: true,
125
+ model: true,
126
+ pixelRatio: true,
127
+ platform: true,
128
+ screenHeight: true,
129
+ screenWidth: true,
130
+ system: true,
131
+ version: true,
132
+ windowHeight: true,
133
+ windowWidth: true
134
+ } },
135
+ getSystemInfoSync: { return: {
136
+ SDKVersion: true,
137
+ brand: true,
138
+ language: true,
139
+ model: true,
140
+ pixelRatio: true,
141
+ platform: true,
142
+ screenHeight: true,
143
+ screenWidth: true,
144
+ system: true,
145
+ version: true,
146
+ windowHeight: true,
147
+ windowWidth: true
148
+ } },
149
+ getWindowInfo: { return: {
150
+ pixelRatio: true,
151
+ screenHeight: true,
152
+ screenWidth: true,
153
+ statusBarHeight: true,
154
+ windowHeight: true,
155
+ windowWidth: true
156
+ } },
157
+ getWindowInfoSync: { return: {
158
+ pixelRatio: true,
159
+ screenHeight: true,
160
+ screenWidth: true,
161
+ statusBarHeight: true,
162
+ windowHeight: true,
163
+ windowWidth: true
164
+ } },
165
+ hideLoading: true,
166
+ hideToast: true,
167
+ navigateBack: true,
168
+ navigateTo: true,
169
+ nextTick: true,
170
+ offNetworkStatusChange: true,
171
+ onNetworkStatusChange: true,
172
+ pageScrollTo: true,
173
+ reLaunch: true,
174
+ redirectTo: true,
175
+ removeStorage: true,
176
+ removeStorageSync: true,
177
+ request: true,
178
+ setBackgroundColor: true,
179
+ setBackgroundTextStyle: true,
180
+ setStorage: true,
181
+ setStorageSync: true,
182
+ setNavigationBarColor: true,
183
+ setNavigationBarTitle: true,
184
+ hideShareMenu: true,
185
+ hideNavigationBarLoading: true,
186
+ hideTabBar: true,
187
+ hideTabBarRedDot: true,
188
+ showShareMenu: true,
189
+ showNavigationBarLoading: true,
190
+ showTabBar: true,
191
+ showTabBarRedDot: true,
192
+ showActionSheet: true,
193
+ showLoading: true,
194
+ showModal: true,
195
+ showToast: true,
196
+ stopPullDownRefresh: true,
197
+ switchTab: true,
198
+ removeTabBarBadge: true,
199
+ setTabBarBadge: true,
200
+ updateShareMenu: true
201
+ };
52
202
  return {
203
+ canIUse: (schema) => typeof schema === "string" && schema.trim() !== "" && resolveCapabilityValue(capabilityTree, schema.trim()) != null,
204
+ clearStorage: (option) => invokeWxApi(() => {
205
+ driver.clearStorageSync();
206
+ return { errMsg: "clearStorage:ok" };
207
+ }, option),
53
208
  clearStorageSync: () => driver.clearStorageSync(),
209
+ createSelectorQuery: () => {
210
+ const requests = [];
211
+ let scope;
212
+ const callbacks = [];
213
+ let query;
214
+ const createNode = (target, selector, single = true) => ({
215
+ boundingClientRect: (callback) => {
216
+ requests.push({
217
+ fields: {
218
+ rect: true,
219
+ size: true
220
+ },
221
+ selector,
222
+ single,
223
+ target
224
+ });
225
+ if (callback) callbacks.push(callback);
226
+ return query;
227
+ },
228
+ fields: (fields, callback) => {
229
+ requests.push({
230
+ fields: { ...fields },
231
+ selector,
232
+ single,
233
+ target
234
+ });
235
+ if (callback) callbacks.push(callback);
236
+ return query;
237
+ },
238
+ scrollOffset: (callback) => {
239
+ requests.push({
240
+ fields: { scrollOffset: true },
241
+ selector,
242
+ single,
243
+ target
244
+ });
245
+ if (callback) callbacks.push(callback);
246
+ return query;
247
+ }
248
+ });
249
+ query = {
250
+ exec: (callback) => {
251
+ const result = driver.executeSelectorQuery(requests, scope);
252
+ for (const [index, item] of result.entries()) callbacks[index]?.(item);
253
+ callback?.(result);
254
+ return result;
255
+ },
256
+ in: (component) => {
257
+ scope = component;
258
+ return query;
259
+ },
260
+ select: (selector) => createNode("selector", selector, true),
261
+ selectAll: (selector) => createNode("selector", selector, false),
262
+ selectViewport: () => createNode("viewport", void 0, true)
263
+ };
264
+ return query;
265
+ },
266
+ getEnterOptionsSync: () => driver.getEnterOptionsSync(),
267
+ getAppBaseInfo: (option) => invokeWxApi(() => driver.getAppBaseInfoSync(), option),
268
+ getAppBaseInfoSync: () => driver.getAppBaseInfoSync(),
269
+ getLaunchOptionsSync: () => driver.getLaunchOptionsSync(),
270
+ getMenuButtonBoundingClientRect: () => driver.getMenuButtonBoundingClientRect(),
271
+ getNetworkType: (option) => invokeWxApi(() => driver.getNetworkType(), option),
272
+ getStorageInfo: (option) => invokeWxApi(() => driver.getStorageInfoSync(), option),
273
+ getStorageInfoSync: () => driver.getStorageInfoSync(),
274
+ getStorage: (option) => invokeWxApi(() => ({
275
+ data: driver.getStorageSync(option.key),
276
+ errMsg: "getStorage:ok"
277
+ }), option),
54
278
  getStorageSync: (key) => driver.getStorageSync(key),
279
+ getSystemInfo: (option) => invokeWxApi(() => driver.getSystemInfoSync(), option),
280
+ getSystemInfoSync: () => driver.getSystemInfoSync(),
281
+ getWindowInfo: (option) => invokeWxApi(() => driver.getWindowInfoSync(), option),
282
+ getWindowInfoSync: () => driver.getWindowInfoSync(),
283
+ hideLoading: (option) => invokeWxApi(() => driver.hideLoading(), option),
55
284
  hideToast: () => driver.hideToast(),
56
- navigateBack: (option) => invokeWxApi(() => driver.navigateBack(option), option),
57
- navigateTo: (option) => invokeWxApi(() => driver.navigateTo(option), option),
58
- pageScrollTo: (option) => invokeWxApi(() => driver.pageScrollTo(option), option),
59
- reLaunch: (option) => invokeWxApi(() => driver.reLaunch(option), option),
60
- redirectTo: (option) => invokeWxApi(() => driver.redirectTo(option), option),
285
+ navigateBack: (option) => invokeWxApi(() => {
286
+ driver.navigateBack(option);
287
+ }, option),
288
+ navigateTo: (option) => invokeWxApi(() => {
289
+ driver.navigateTo(option);
290
+ }, option),
291
+ nextTick: (callback) => driver.nextTick(callback),
292
+ offNetworkStatusChange: (callback) => driver.offNetworkStatusChange(callback),
293
+ onNetworkStatusChange: (callback) => driver.onNetworkStatusChange(callback),
294
+ pageScrollTo: (option) => invokeWxApi(() => {
295
+ driver.pageScrollTo(option);
296
+ }, option),
297
+ reLaunch: (option) => invokeWxApi(() => {
298
+ driver.reLaunch(option);
299
+ }, option),
300
+ redirectTo: (option) => invokeWxApi(() => {
301
+ driver.redirectTo(option);
302
+ }, option),
303
+ removeStorage: (option) => invokeWxApi(() => {
304
+ driver.removeStorageSync(option.key);
305
+ return { errMsg: "removeStorage:ok" };
306
+ }, option),
61
307
  removeStorageSync: (key) => driver.removeStorageSync(key),
62
- request: (option) => {
63
- invokeWxApi(() => driver.request(option), option);
64
- return { abort() {} };
65
- },
308
+ request: (option) => driver.request(option),
309
+ setBackgroundColor: (option) => invokeWxApi(() => driver.setBackgroundColor(option), option),
310
+ setBackgroundTextStyle: (option) => invokeWxApi(() => driver.setBackgroundTextStyle(option), option),
311
+ setStorage: (option) => invokeWxApi(() => {
312
+ driver.setStorageSync(option.key, option.data);
313
+ return { errMsg: "setStorage:ok" };
314
+ }, option),
66
315
  setStorageSync: (key, value) => driver.setStorageSync(key, value),
316
+ setNavigationBarColor: (option) => invokeWxApi(() => driver.setNavigationBarColor(option), option),
317
+ setNavigationBarTitle: (option) => invokeWxApi(() => driver.setNavigationBarTitle(option), option),
318
+ hideShareMenu: (option) => invokeWxApi(() => driver.hideShareMenu(), option),
319
+ hideNavigationBarLoading: (option) => invokeWxApi(() => driver.hideNavigationBarLoading(), option),
320
+ hideTabBar: (option) => invokeWxApi(() => driver.hideTabBar(), option),
321
+ hideTabBarRedDot: (option) => invokeWxApi(() => driver.hideTabBarRedDot(option), option),
322
+ showShareMenu: (option) => invokeWxApi(() => driver.showShareMenu(option ?? {}), option),
323
+ showNavigationBarLoading: (option) => invokeWxApi(() => driver.showNavigationBarLoading(), option),
324
+ showTabBar: (option) => invokeWxApi(() => driver.showTabBar(), option),
325
+ showTabBarRedDot: (option) => invokeWxApi(() => driver.showTabBarRedDot(option), option),
326
+ showActionSheet: (option) => invokeWxApi(() => driver.showActionSheet(option), option),
327
+ showLoading: (option) => invokeWxApi(() => driver.showLoading(option), option),
328
+ showModal: (option) => invokeWxApi(() => driver.showModal(option), option),
67
329
  showToast: (option) => invokeWxApi(() => driver.showToast(option), option),
68
330
  stopPullDownRefresh: () => driver.stopPullDownRefresh(),
69
- switchTab: (option) => invokeWxApi(() => driver.switchTab(option), option)
331
+ switchTab: (option) => invokeWxApi(() => {
332
+ driver.switchTab(option);
333
+ }, option),
334
+ removeTabBarBadge: (option) => invokeWxApi(() => driver.removeTabBarBadge(option), option),
335
+ setTabBarBadge: (option) => invokeWxApi(() => driver.setTabBarBadge(option), option),
336
+ updateShareMenu: (option) => invokeWxApi(() => driver.updateShareMenu(option ?? {}), option)
70
337
  };
71
338
  }
72
339
  //#endregion
@@ -197,11 +464,11 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
197
464
  }
198
465
  //#endregion
199
466
  //#region src/project/resolveRoutes.ts
200
- const LEADING_SLASH_RE$4 = /^\/+/;
467
+ const LEADING_SLASH_RE$6 = /^\/+/;
201
468
  const TRAILING_SLASH_RE = /\/+$/;
202
469
  const DUPLICATE_SLASH_RE = /\/{2,}/g;
203
470
  function normalizeSegment(value) {
204
- return value.replace(LEADING_SLASH_RE$4, "").replace(TRAILING_SLASH_RE, "");
471
+ return value.replace(LEADING_SLASH_RE$6, "").replace(TRAILING_SLASH_RE, "");
205
472
  }
206
473
  function pushRoute(records, seen, record) {
207
474
  if (!record.route || seen.has(record.route)) return;
@@ -255,7 +522,7 @@ function createProjectDescriptor(options) {
255
522
  }
256
523
  //#endregion
257
524
  //#region src/browser/project.ts
258
- function readJsonObject$1(files, filePath) {
525
+ function readJsonObject$3(files, filePath) {
259
526
  const content = readBrowserVirtualFile(files, filePath);
260
527
  if (!content) return;
261
528
  try {
@@ -268,7 +535,7 @@ function readJsonObject$1(files, filePath) {
268
535
  function createBrowserProject(files, options = {}) {
269
536
  const appConfigPath = options.appConfigPath ?? "app.json";
270
537
  if (!hasBrowserVirtualFile(files, appConfigPath)) throw new Error(`Missing built app.json for browser simulator project: ${appConfigPath}`);
271
- const appConfig = readJsonObject$1(files, appConfigPath);
538
+ const appConfig = readJsonObject$3(files, appConfigPath);
272
539
  if (!appConfig) throw new Error(`Failed to read built app.json for browser simulator project: ${appConfigPath}`);
273
540
  return createProjectDescriptor({
274
541
  appConfig,
@@ -547,21 +814,21 @@ function runComponentPageLifetime(instance, lifetimeName, payload) {
547
814
  }
548
815
  //#endregion
549
816
  //#region src/browser/render.ts
550
- const LEADING_SLASH_RE$3 = /^\/+/;
551
- const TEMPLATE_INTERPOLATION_RE$1 = /\{\{([^{}]+)\}\}/g;
552
- const EVENT_BINDING_ATTRS = [
817
+ const LEADING_SLASH_RE$5 = /^\/+/;
818
+ const TEMPLATE_INTERPOLATION_RE$2 = /\{\{([^{}]+)\}\}/g;
819
+ const EVENT_BINDING_ATTRS$1 = [
553
820
  "bindtap",
554
821
  "bind:tap",
555
822
  "catchtap",
556
823
  "catch:tap"
557
824
  ];
558
- const COMPONENT_EVENT_PREFIXES = [
825
+ const COMPONENT_EVENT_PREFIXES$1 = [
559
826
  "bind:",
560
827
  "bind",
561
828
  "catch:",
562
829
  "catch"
563
830
  ];
564
- const STRUCTURAL_ATTRS = [
831
+ const STRUCTURAL_ATTRS$1 = [
565
832
  "wx:if",
566
833
  "wx:elif",
567
834
  "wx:else",
@@ -570,48 +837,48 @@ const STRUCTURAL_ATTRS = [
570
837
  "wx:for-index",
571
838
  "wx:key"
572
839
  ];
573
- const WX_ELSE_ATTRS = new Set(["wx:elif", "wx:else"]);
574
- const DATASET_NAME_RE = /-([a-z])/g;
575
- const BRACKET_INDEX_RE = /\[(\d+)\]/g;
576
- const CLASS_SPLIT_RE = /\s+/;
577
- const JS_FILE_RE = /\.js$/;
578
- function isMustacheOnly(value) {
840
+ const WX_ELSE_ATTRS$1 = new Set(["wx:elif", "wx:else"]);
841
+ const DATASET_NAME_RE$3 = /-([a-z])/g;
842
+ const BRACKET_INDEX_RE$1 = /\[(\d+)\]/g;
843
+ const CLASS_SPLIT_RE$1 = /\s+/;
844
+ const JS_FILE_RE$1 = /\.js$/;
845
+ function isMustacheOnly$1(value) {
579
846
  const trimmed = value.trim();
580
847
  return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
581
848
  }
582
- function toDatasetKey(attributeName) {
583
- return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
849
+ function toDatasetKey$3(attributeName) {
850
+ return attributeName.slice(5).replace(DATASET_NAME_RE$3, (_match, char) => char.toUpperCase());
584
851
  }
585
- function collectDataset(node) {
852
+ function collectDataset$3(node) {
586
853
  const dataset = {};
587
854
  for (const [key, value] of Object.entries(node.attribs ?? {})) {
588
855
  if (!key.startsWith("data-") || key === "data-sim-scope" || key === "data-sim-tap" || key === "data-sim-component") continue;
589
- dataset[toDatasetKey(key)] = String(value);
856
+ dataset[toDatasetKey$3(key)] = String(value);
590
857
  }
591
858
  return dataset;
592
859
  }
593
- function escapeText$2(text) {
860
+ function escapeText$3(text) {
594
861
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
595
862
  }
596
- function escapeAttribute$2(value) {
597
- return escapeText$2(value).replaceAll("\"", "&quot;");
863
+ function escapeAttribute$3(value) {
864
+ return escapeText$3(value).replaceAll("\"", "&quot;");
598
865
  }
599
- function cloneNode(node) {
866
+ function cloneNode$1(node) {
600
867
  return {
601
868
  ...node,
602
869
  attribs: node.attribs ? { ...node.attribs } : void 0,
603
- children: node.children?.map((child) => cloneNode(child))
870
+ children: node.children?.map((child) => cloneNode$1(child))
604
871
  };
605
872
  }
606
- function parseExpressionSegments(expression) {
607
- return expression.replace(BRACKET_INDEX_RE, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
873
+ function parseExpressionSegments$1(expression) {
874
+ return expression.replace(BRACKET_INDEX_RE$1, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
608
875
  }
609
- function unwrapMustacheExpression(expression) {
876
+ function unwrapMustacheExpression$1(expression) {
610
877
  const normalized = expression.trim();
611
- if (isMustacheOnly(normalized)) return normalized.slice(2, -2).trim();
878
+ if (isMustacheOnly$1(normalized)) return normalized.slice(2, -2).trim();
612
879
  return normalized;
613
880
  }
614
- function resolveLiteralValue(expression) {
881
+ function resolveLiteralValue$1(expression) {
615
882
  if (expression === "true") return true;
616
883
  if (expression === "false") return false;
617
884
  if (expression === "null") return null;
@@ -620,69 +887,69 @@ function resolveLiteralValue(expression) {
620
887
  const numericValue = Number(expression);
621
888
  if (!Number.isNaN(numericValue) && expression !== "") return numericValue;
622
889
  }
623
- function resolveValueByExpression(source, expression) {
624
- const normalized = unwrapMustacheExpression(expression);
890
+ function resolveValueByExpression$1(source, expression) {
891
+ const normalized = unwrapMustacheExpression$1(expression);
625
892
  if (!normalized) return;
626
- if (normalized.startsWith("!")) return !resolveValueByExpression(source, normalized.slice(1));
627
- const literalValue = resolveLiteralValue(normalized);
893
+ if (normalized.startsWith("!")) return !resolveValueByExpression$1(source, normalized.slice(1));
894
+ const literalValue = resolveLiteralValue$1(normalized);
628
895
  if (literalValue !== void 0 || normalized === "undefined") return literalValue;
629
- const segments = parseExpressionSegments(normalized);
896
+ const segments = parseExpressionSegments$1(normalized);
630
897
  let current = source;
631
898
  for (const segment of segments) current = current?.[segment];
632
899
  return current;
633
900
  }
634
- function resolveValueByPath$1(source, expression) {
635
- return resolveValueByExpression(source, expression) ?? "";
901
+ function resolveValueByPath$2(source, expression) {
902
+ return resolveValueByExpression$1(source, expression) ?? "";
636
903
  }
637
- function resolveRawValueByPath(source, expression) {
638
- return resolveValueByExpression(source, expression);
904
+ function resolveRawValueByPath$1(source, expression) {
905
+ return resolveValueByExpression$1(source, expression);
639
906
  }
640
- function interpolateTemplate$1(input, data) {
641
- return input.replace(TEMPLATE_INTERPOLATION_RE$1, (_match, expression) => {
642
- const value = resolveValueByPath$1(data, expression);
907
+ function interpolateTemplate$2(input, data) {
908
+ return input.replace(TEMPLATE_INTERPOLATION_RE$2, (_match, expression) => {
909
+ const value = resolveValueByPath$2(data, expression);
643
910
  return typeof value === "string" ? value : String(value);
644
911
  });
645
912
  }
646
- function readTemplateSource(files, filePath) {
913
+ function readTemplateSource$1(files, filePath) {
647
914
  const templateSource = readBrowserVirtualFile(files, filePath);
648
915
  if (typeof templateSource !== "string") throw new TypeError(`Missing template in browser simulator runtime: ${filePath}`);
649
916
  return templateSource;
650
917
  }
651
- function parseTemplateDocument(templateSource) {
918
+ function parseTemplateDocument$1(templateSource) {
652
919
  return parseDocument(`<page>${templateSource}</page>`, {
653
920
  xmlMode: false,
654
921
  decodeEntities: false,
655
922
  recognizeSelfClosing: true
656
923
  });
657
924
  }
658
- function serializeDomNode$1(node) {
659
- if (node.type === "text") return escapeText$2(node.data ?? "");
660
- if (node.type === "root") return (node.children ?? []).map(serializeDomNode$1).join("");
925
+ function serializeDomNode$2(node) {
926
+ if (node.type === "text") return escapeText$3(node.data ?? "");
927
+ if (node.type === "root") return (node.children ?? []).map(serializeDomNode$2).join("");
661
928
  const tagName = node.name ?? "";
662
- if (!tagName) return (node.children ?? []).map(serializeDomNode$1).join("");
663
- return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$2(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$1).join("")}</${tagName}>`;
929
+ if (!tagName) return (node.children ?? []).map(serializeDomNode$2).join("");
930
+ return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$3(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$2).join("")}</${tagName}>`;
664
931
  }
665
- function isTagNode(node) {
932
+ function isTagNode$1(node) {
666
933
  return node.type === "tag" && typeof node.name === "string";
667
934
  }
668
- function isIgnorableTextNode(node) {
935
+ function isIgnorableTextNode$1(node) {
669
936
  return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
670
937
  }
671
- function resolveAttributeValue(value, scope) {
672
- if (isMustacheOnly(value)) {
938
+ function resolveAttributeValue$1(value, scope) {
939
+ if (isMustacheOnly$1(value)) {
673
940
  const expression = value.trim().slice(2, -2);
674
- return resolveValueByPath$1(scope.data, expression);
941
+ return resolveValueByPath$2(scope.data, expression);
675
942
  }
676
- return interpolateTemplate$1(value, scope.data);
943
+ return interpolateTemplate$2(value, scope.data);
677
944
  }
678
- function resolveComponentAttributeValue(value, scope) {
679
- if (isMustacheOnly(value)) {
945
+ function resolveComponentAttributeValue$1(value, scope) {
946
+ if (isMustacheOnly$1(value)) {
680
947
  const expression = value.trim().slice(2, -2);
681
- return resolveRawValueByPath(scope.data, expression);
948
+ return resolveRawValueByPath$1(scope.data, expression);
682
949
  }
683
- return interpolateTemplate$1(value, scope.data);
950
+ return interpolateTemplate$2(value, scope.data);
684
951
  }
685
- function resolveUsingComponents(files, ownerJsonPath, ownerFilePath) {
952
+ function resolveUsingComponents$1(files, ownerJsonPath, ownerFilePath) {
686
953
  const ownerJson = readBrowserVirtualFile(files, ownerJsonPath);
687
954
  if (typeof ownerJson !== "string") return /* @__PURE__ */ new Map();
688
955
  try {
@@ -691,16 +958,16 @@ function resolveUsingComponents(files, ownerJsonPath, ownerFilePath) {
691
958
  const resolved = /* @__PURE__ */ new Map();
692
959
  for (const [alias, rawPath] of Object.entries(usingComponents)) {
693
960
  if (typeof rawPath !== "string") continue;
694
- const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$3, "") : normalize(join(dirname(ownerFilePath), rawPath));
695
- resolved.set(alias, basePath.replace(LEADING_SLASH_RE$3, ""));
961
+ const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$5, "") : normalize(join(dirname(ownerFilePath), rawPath));
962
+ resolved.set(alias, basePath.replace(LEADING_SLASH_RE$5, ""));
696
963
  }
697
964
  return resolved;
698
965
  } catch {
699
966
  return /* @__PURE__ */ new Map();
700
967
  }
701
968
  }
702
- function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias) {
703
- const componentBasePath = resolveUsingComponents(context.files, ownerJsonPath, ownerFilePath).get(alias);
969
+ function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, alias) {
970
+ const componentBasePath = resolveUsingComponents$1(context.files, ownerJsonPath, ownerFilePath).get(alias);
704
971
  if (!componentBasePath) return null;
705
972
  const filePath = `${componentBasePath}.js`;
706
973
  const templatePath = `${componentBasePath}.wxml`;
@@ -710,10 +977,10 @@ function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, al
710
977
  templatePath
711
978
  };
712
979
  }
713
- function collectComponentEventBindings(hostNode) {
980
+ function collectComponentEventBindings$1(hostNode) {
714
981
  const eventBindings = /* @__PURE__ */ new Map();
715
982
  for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
716
- const matchedPrefix = COMPONENT_EVENT_PREFIXES.find((prefix) => key.startsWith(prefix));
983
+ const matchedPrefix = COMPONENT_EVENT_PREFIXES$1.find((prefix) => key.startsWith(prefix));
717
984
  if (!matchedPrefix) continue;
718
985
  const eventName = key.slice(matchedPrefix.length);
719
986
  if (!eventName) continue;
@@ -724,12 +991,13 @@ function collectComponentEventBindings(hostNode) {
724
991
  }
725
992
  return eventBindings;
726
993
  }
727
- function buildComponentTrigger(componentScopeId, context, hostNode) {
728
- const hostDataset = collectDataset(hostNode);
994
+ function buildComponentTrigger$1(componentScopeId, context, hostNode) {
995
+ const hostDataset = collectDataset$3(hostNode);
729
996
  const hostId = hostNode.attribs?.id ?? "";
730
997
  return (instance, eventName, detail, triggerOptions) => {
731
998
  const interactionTarget = instance.__lastInteractionEvent__?.target;
732
999
  const interactionCurrentTarget = instance.__lastInteractionEvent__?.currentTarget;
1000
+ const interactionMark = instance.__lastInteractionEvent__?.mark;
733
1001
  const target = {
734
1002
  dataset: interactionTarget?.dataset ?? hostDataset,
735
1003
  id: interactionTarget?.id ?? hostId
@@ -745,7 +1013,7 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
745
1013
  capturePhase: false,
746
1014
  composed: triggerOptions?.composed ?? false,
747
1015
  detail,
748
- mark: void 0,
1016
+ mark: interactionMark,
749
1017
  target,
750
1018
  type: eventName,
751
1019
  currentTarget: {
@@ -759,23 +1027,23 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
759
1027
  }
760
1028
  };
761
1029
  }
762
- function applyNodeBindings(node, scope) {
763
- if (!isTagNode(node)) {
764
- if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate$1(node.data, scope.data);
1030
+ function applyNodeBindings$1(node, scope) {
1031
+ if (!isTagNode$1(node)) {
1032
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate$2(node.data, scope.data);
765
1033
  return;
766
1034
  }
767
1035
  node.attribs ??= {};
768
1036
  node.attribs["data-sim-scope"] = scope.getScopeId();
769
- for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
1037
+ for (const key of STRUCTURAL_ATTRS$1) delete node.attribs[key];
770
1038
  for (const [key, value] of Object.entries({ ...node.attribs })) {
771
- if (EVENT_BINDING_ATTRS.includes(key)) {
1039
+ if (EVENT_BINDING_ATTRS$1.includes(key)) {
772
1040
  node.attribs["data-sim-tap"] = value;
773
1041
  continue;
774
1042
  }
775
- node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
1043
+ node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue$1(value, scope)) : String(value);
776
1044
  }
777
1045
  }
778
- function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
1046
+ function syncComponentProperties$1(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
779
1047
  const changedRootKeys = [];
780
1048
  const previousProperties = {};
781
1049
  for (const [key, value] of Object.entries(nextProperties)) {
@@ -797,17 +1065,17 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
797
1065
  if (changedRootKeys.length === 0) return;
798
1066
  runComponentObservers(definition, instance, changedRootKeys, previousProperties);
799
1067
  }
800
- function createMergedScopeData(pageData, componentProperties, componentData) {
1068
+ function createMergedScopeData$1(pageData, componentProperties, componentData) {
801
1069
  return {
802
1070
  ...pageData,
803
1071
  ...componentProperties,
804
1072
  ...componentData
805
1073
  };
806
1074
  }
807
- function isTruthy(value) {
1075
+ function isTruthy$1(value) {
808
1076
  return Boolean(value);
809
1077
  }
810
- function createLoopScope(scope, itemName, indexName, item, index) {
1078
+ function createLoopScope$1(scope, itemName, indexName, item, index) {
811
1079
  return {
812
1080
  ...scope,
813
1081
  data: {
@@ -817,37 +1085,37 @@ function createLoopScope(scope, itemName, indexName, item, index) {
817
1085
  }
818
1086
  };
819
1087
  }
820
- function evaluateConditionalBranch(node, scope) {
1088
+ function evaluateConditionalBranch$1(node, scope) {
821
1089
  const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
822
1090
  if (condition == null) return true;
823
- return isTruthy(resolveRawValueByPath(scope.data, condition));
1091
+ return isTruthy$1(resolveRawValueByPath$1(scope.data, condition));
824
1092
  }
825
- function expandNodeByFor(node, scope) {
1093
+ function expandNodeByFor$1(node, scope) {
826
1094
  const forExpression = node.attribs?.["wx:for"];
827
1095
  if (!forExpression) return [{
828
1096
  node,
829
1097
  scope,
830
1098
  instanceSuffix: ""
831
1099
  }];
832
- const list = resolveRawValueByPath(scope.data, forExpression);
1100
+ const list = resolveRawValueByPath$1(scope.data, forExpression);
833
1101
  const items = Array.isArray(list) ? list : [];
834
1102
  const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
835
1103
  const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
836
1104
  return items.map((item, index) => ({
837
- node: cloneNode(node),
838
- scope: createLoopScope(scope, itemName, indexName, item, index),
1105
+ node: cloneNode$1(node),
1106
+ scope: createLoopScope$1(scope, itemName, indexName, item, index),
839
1107
  instanceSuffix: `:for-${index}`
840
1108
  }));
841
1109
  }
842
- function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
843
- return expandNodeByFor(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes));
1110
+ function renderNodeVariants$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1111
+ return expandNodeByFor$1(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree$1(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes));
844
1112
  }
845
- function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1113
+ function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
846
1114
  const renderedChildren = [];
847
1115
  for (let index = 0; index < children.length; index += 1) {
848
1116
  const child = children[index];
849
- if (!isTagNode(child)) {
850
- renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
1117
+ if (!isTagNode$1(child)) {
1118
+ renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
851
1119
  continue;
852
1120
  }
853
1121
  const hasConditional = child.attribs?.["wx:if"] != null;
@@ -857,37 +1125,37 @@ function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath,
857
1125
  let cursor = index;
858
1126
  while (cursor < children.length) {
859
1127
  const branch = children[cursor];
860
- if (cursor !== index && isIgnorableTextNode(branch)) {
1128
+ if (cursor !== index && isIgnorableTextNode$1(branch)) {
861
1129
  cursor += 1;
862
1130
  continue;
863
1131
  }
864
- if (!isTagNode(branch)) break;
865
- if (cursor !== index && !WX_ELSE_ATTRS.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
866
- if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch(branch, scope)) {
867
- renderedChildren.push(...renderNodeVariants(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes));
1132
+ if (!isTagNode$1(branch)) break;
1133
+ if (cursor !== index && !WX_ELSE_ATTRS$1.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
1134
+ if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch$1(branch, scope)) {
1135
+ renderedChildren.push(...renderNodeVariants$1(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes));
868
1136
  branchMatched = true;
869
1137
  }
870
1138
  let nextBranchIndex = cursor + 1;
871
- while (nextBranchIndex < children.length && isIgnorableTextNode(children[nextBranchIndex])) nextBranchIndex += 1;
1139
+ while (nextBranchIndex < children.length && isIgnorableTextNode$1(children[nextBranchIndex])) nextBranchIndex += 1;
872
1140
  const nextBranch = children[nextBranchIndex];
873
- if (!(!!nextBranch && isTagNode(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
1141
+ if (!(!!nextBranch && isTagNode$1(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
874
1142
  cursor = nextBranchIndex;
875
1143
  }
876
1144
  index = cursor;
877
1145
  continue;
878
1146
  }
879
1147
  if (isElseBranch) continue;
880
- renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
1148
+ renderedChildren.push(...renderNodeVariants$1(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
881
1149
  }
882
1150
  return renderedChildren;
883
1151
  }
884
- function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
885
- const clonedNode = cloneNode(node);
886
- if (!isTagNode(clonedNode)) {
887
- applyNodeBindings(clonedNode, scope);
1152
+ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1153
+ const clonedNode = cloneNode$1(node);
1154
+ if (!isTagNode$1(clonedNode)) {
1155
+ applyNodeBindings$1(clonedNode, scope);
888
1156
  return clonedNode;
889
1157
  }
890
- const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name);
1158
+ const componentEntry = resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, clonedNode.name);
891
1159
  if (componentEntry) {
892
1160
  const componentScopeId = `${instancePath}/${clonedNode.name}`;
893
1161
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
@@ -895,15 +1163,15 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
895
1163
  const bindingExpressions = {};
896
1164
  for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
897
1165
  if (key.startsWith("bind")) continue;
898
- if (isMustacheOnly(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
899
- nextProperties[key] = resolveComponentAttributeValue(String(value), scope);
1166
+ if (isMustacheOnly$1(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
1167
+ nextProperties[key] = resolveComponentAttributeValue$1(String(value), scope);
900
1168
  }
901
1169
  let componentInstance = context.componentCache.get(componentScopeId);
902
1170
  if (!componentInstance) {
903
1171
  componentInstance = createComponentInstance({
904
1172
  definition: componentEntry.definition,
905
1173
  properties: nextProperties,
906
- triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
1174
+ triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
907
1175
  });
908
1176
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
909
1177
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
@@ -914,14 +1182,14 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
914
1182
  runComponentLifecycle(componentInstance, "attached");
915
1183
  runComponentPageLifetime(componentInstance, "show");
916
1184
  context.componentCache.set(componentScopeId, componentInstance);
917
- } else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
1185
+ } else syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
918
1186
  seenComponentScopes.add(componentScopeId);
919
1187
  const componentScope = {
920
1188
  alias: clonedNode.name,
921
- classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
922
- data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
923
- dataset: collectDataset(clonedNode),
924
- eventBindings: collectComponentEventBindings(clonedNode),
1189
+ classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
1190
+ data: createMergedScopeData$1(scope.data, componentInstance.properties, componentInstance.data),
1191
+ dataset: collectDataset$3(clonedNode),
1192
+ eventBindings: collectComponentEventBindings$1(clonedNode),
925
1193
  getMethod: (methodName) => {
926
1194
  const method = componentInstance?.[methodName];
927
1195
  return typeof method === "function" ? method : void 0;
@@ -933,8 +1201,8 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
933
1201
  ownerScopeId
934
1202
  };
935
1203
  context.componentScopes.set(componentScopeId, componentScope);
936
- const componentDocument = parseTemplateDocument(readTemplateSource(context.files, componentEntry.templatePath));
937
- const renderedComponentRoot = renderNodeTree((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes);
1204
+ const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, componentEntry.templatePath));
1205
+ const renderedComponentRoot = renderNodeTree$1((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes);
938
1206
  if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
939
1207
  if (!componentInstance.__ready__) {
940
1208
  runComponentLifecycle(componentInstance, "ready");
@@ -942,14 +1210,14 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
942
1210
  }
943
1211
  return renderedComponentRoot;
944
1212
  }
945
- applyNodeBindings(clonedNode, scope);
946
- clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
1213
+ applyNodeBindings$1(clonedNode, scope);
1214
+ clonedNode.children = renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
947
1215
  return clonedNode;
948
1216
  }
949
1217
  function renderBrowserPageTree(context, page) {
950
- const route = page.route.replace(LEADING_SLASH_RE$3, "");
1218
+ const route = page.route.replace(LEADING_SLASH_RE$5, "");
951
1219
  const templatePath = join(context.project.miniprogramRootPath, `${route}.wxml`);
952
- const document = parseTemplateDocument(readTemplateSource(context.files, templatePath));
1220
+ const document = parseTemplateDocument$1(readTemplateSource$1(context.files, templatePath));
953
1221
  const pageScopeId = `page:${route}`;
954
1222
  const pageScope = {
955
1223
  data: page.data,
@@ -963,7 +1231,7 @@ function renderBrowserPageTree(context, page) {
963
1231
  context.componentScopes.clear();
964
1232
  context.componentScopes.set(pageScopeId, pageScope);
965
1233
  const seenComponentScopes = /* @__PURE__ */ new Set();
966
- const renderedRoot = renderNodeTree((document.children ?? [])[0] ?? document, pageScope, context, `${route}.json`, `${route}.js`, pageScopeId, seenComponentScopes);
1234
+ const renderedRoot = renderNodeTree$1((document.children ?? [])[0] ?? document, pageScope, context, `${route}.json`, `${route}.js`, pageScopeId, seenComponentScopes);
967
1235
  for (const [scopeId, instance] of [...context.componentCache.entries()]) if (!seenComponentScopes.has(scopeId)) {
968
1236
  runComponentLifecycle(instance, "detached");
969
1237
  context.componentCache.delete(scopeId);
@@ -971,7 +1239,70 @@ function renderBrowserPageTree(context, page) {
971
1239
  }
972
1240
  return {
973
1241
  root: renderedRoot,
974
- wxml: serializeDomNode$1(renderedRoot)
1242
+ wxml: serializeDomNode$2(renderedRoot)
1243
+ };
1244
+ }
1245
+ //#endregion
1246
+ //#region src/project/pageConfig.ts
1247
+ const DEFAULT_NAVIGATION_BAR_BACKGROUND_COLOR = "#ffffff";
1248
+ const DEFAULT_NAVIGATION_BAR_FRONT_COLOR = "#000000";
1249
+ const DEFAULT_NAVIGATION_BAR_FRONT_COLOR_WHITE = "#ffffff";
1250
+ const DEFAULT_BACKGROUND_TEXT_STYLE = "dark";
1251
+ const DEFAULT_BACKGROUND_COLOR = "#ffffff";
1252
+ function resolveNavigationBarTitle(appConfig, pageConfig) {
1253
+ if (typeof pageConfig?.navigationBarTitleText === "string") return pageConfig.navigationBarTitleText;
1254
+ if (typeof appConfig.window?.navigationBarTitleText === "string") return appConfig.window.navigationBarTitleText;
1255
+ return "";
1256
+ }
1257
+ function resolveNavigationBarBackgroundColor(appConfig, pageConfig) {
1258
+ if (typeof pageConfig?.navigationBarBackgroundColor === "string") return pageConfig.navigationBarBackgroundColor;
1259
+ if (typeof appConfig.window?.navigationBarBackgroundColor === "string") return appConfig.window.navigationBarBackgroundColor;
1260
+ return DEFAULT_NAVIGATION_BAR_BACKGROUND_COLOR;
1261
+ }
1262
+ function resolveNavigationBarFrontColor(appConfig, pageConfig) {
1263
+ if ((typeof pageConfig?.navigationBarTextStyle === "string" ? pageConfig.navigationBarTextStyle : typeof appConfig.window?.navigationBarTextStyle === "string" ? appConfig.window.navigationBarTextStyle : void 0) === "white") return DEFAULT_NAVIGATION_BAR_FRONT_COLOR_WHITE;
1264
+ return DEFAULT_NAVIGATION_BAR_FRONT_COLOR;
1265
+ }
1266
+ function cloneNavigationBarSnapshot(snapshot) {
1267
+ return {
1268
+ animation: snapshot.animation ? { ...snapshot.animation } : null,
1269
+ backgroundColor: snapshot.backgroundColor,
1270
+ frontColor: snapshot.frontColor,
1271
+ loading: snapshot.loading,
1272
+ title: snapshot.title
1273
+ };
1274
+ }
1275
+ function resolveNavigationBarSnapshot(appConfig, pageConfig) {
1276
+ return {
1277
+ animation: null,
1278
+ backgroundColor: resolveNavigationBarBackgroundColor(appConfig, pageConfig),
1279
+ frontColor: resolveNavigationBarFrontColor(appConfig, pageConfig),
1280
+ loading: false,
1281
+ title: resolveNavigationBarTitle(appConfig, pageConfig)
1282
+ };
1283
+ }
1284
+ function resolveBackgroundTextStyle(appConfig, pageConfig) {
1285
+ return (typeof pageConfig?.backgroundTextStyle === "string" ? pageConfig.backgroundTextStyle : typeof appConfig.window?.backgroundTextStyle === "string" ? appConfig.window.backgroundTextStyle : void 0) === "light" ? "light" : DEFAULT_BACKGROUND_TEXT_STYLE;
1286
+ }
1287
+ function resolveBackgroundColorValue(appConfig, pageConfig, key) {
1288
+ if (typeof pageConfig?.[key] === "string") return pageConfig[key];
1289
+ if (typeof appConfig.window?.[key] === "string") return appConfig.window[key];
1290
+ return DEFAULT_BACKGROUND_COLOR;
1291
+ }
1292
+ function cloneBackgroundSnapshot(snapshot) {
1293
+ return {
1294
+ backgroundColor: snapshot.backgroundColor,
1295
+ backgroundColorBottom: snapshot.backgroundColorBottom,
1296
+ backgroundColorTop: snapshot.backgroundColorTop,
1297
+ textStyle: snapshot.textStyle
1298
+ };
1299
+ }
1300
+ function resolveBackgroundSnapshot(appConfig, pageConfig) {
1301
+ return {
1302
+ backgroundColor: resolveBackgroundColorValue(appConfig, pageConfig, "backgroundColor"),
1303
+ backgroundColorBottom: resolveBackgroundColorValue(appConfig, pageConfig, "backgroundColorBottom"),
1304
+ backgroundColorTop: resolveBackgroundColorValue(appConfig, pageConfig, "backgroundColorTop"),
1305
+ textStyle: resolveBackgroundTextStyle(appConfig, pageConfig)
975
1306
  };
976
1307
  }
977
1308
  //#endregion
@@ -1001,6 +1332,9 @@ function createAppInstance(definition) {
1001
1332
  }
1002
1333
  //#endregion
1003
1334
  //#region src/runtime/pageInstance.ts
1335
+ const ARRAY_INDEX_PATH_RE = /\[(\d+)\]/g;
1336
+ const ARRAY_INDEX_SEGMENT_RE = /^\d+$/;
1337
+ const LEADING_ROUTE_SLASH_RE = /^\/+/;
1004
1338
  function bindFunction(target, key, value) {
1005
1339
  if (typeof value !== "function") {
1006
1340
  target[key] = value;
@@ -1020,10 +1354,10 @@ function resolveInitialData(definition) {
1020
1354
  return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? cloneObject(rawData) : {};
1021
1355
  }
1022
1356
  function parseDataPath(path) {
1023
- return path.replace(/\[(\d+)\]/g, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
1357
+ return path.replace(ARRAY_INDEX_PATH_RE, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
1024
1358
  }
1025
1359
  function isArrayIndexSegment(segment) {
1026
- return /^\d+$/.test(segment);
1360
+ return ARRAY_INDEX_SEGMENT_RE.test(segment);
1027
1361
  }
1028
1362
  function createContainerByNextSegment(nextSegment) {
1029
1363
  return isArrayIndexSegment(nextSegment ?? "") ? [] : {};
@@ -1040,17 +1374,21 @@ function assignByPath(target, path, value) {
1040
1374
  if (!next || typeof next !== "object") current[normalizedSegment] = createContainerByNextSegment(nextSegment);
1041
1375
  current = current[normalizedSegment];
1042
1376
  }
1043
- const leafSegment = segments[segments.length - 1];
1377
+ const leafSegment = segments.at(-1);
1044
1378
  const normalizedLeafSegment = isArrayIndexSegment(leafSegment) ? Number(leafSegment) : leafSegment;
1045
1379
  current[normalizedLeafSegment] = value;
1046
1380
  }
1047
- function normalizeRoute(route) {
1048
- return route.replace(/^\/+/, "");
1381
+ function normalizeRoute$1(route) {
1382
+ return route.replace(LEADING_ROUTE_SLASH_RE, "");
1049
1383
  }
1050
- function createPageInstance(route, definition, options = {}) {
1051
- const normalizedRoute = normalizeRoute(route);
1384
+ function createPageInstance(route, definition, options = {}, pageState = {}) {
1385
+ const normalizedRoute = normalizeRoute$1(route);
1052
1386
  const instance = {
1387
+ __background__: pageState.background ? cloneBackgroundSnapshot(pageState.background) : void 0,
1388
+ __backgroundTextStyle__: pageState.background?.textStyle ?? pageState.backgroundTextStyle,
1053
1389
  __route__: normalizedRoute,
1390
+ __navigationBar__: pageState.navigationBar ? cloneNavigationBarSnapshot(pageState.navigationBar) : void 0,
1391
+ __navigationBarTitle__: pageState.navigationBar?.title,
1054
1392
  data: resolveInitialData(definition),
1055
1393
  options: { ...options },
1056
1394
  route: normalizedRoute,
@@ -1067,7 +1405,97 @@ function createPageInstance(route, definition, options = {}) {
1067
1405
  return instance;
1068
1406
  }
1069
1407
  //#endregion
1408
+ //#region src/runtime/systemInfo.ts
1409
+ function createDefaultSystemInfo() {
1410
+ return {
1411
+ SDKVersion: "0.0.0",
1412
+ brand: "devtools",
1413
+ language: "zh_CN",
1414
+ model: "headless-simulator",
1415
+ pixelRatio: 2,
1416
+ platform: "devtools",
1417
+ screenHeight: 667,
1418
+ screenWidth: 375,
1419
+ system: "iOS 0.0.0",
1420
+ version: "0.0.0",
1421
+ windowHeight: 667,
1422
+ windowWidth: 375
1423
+ };
1424
+ }
1425
+ function applyResizeToSystemInfo(systemInfo, options) {
1426
+ const size = options?.size;
1427
+ const nextWindowWidth = Number(size?.windowWidth);
1428
+ const nextWindowHeight = Number(size?.windowHeight);
1429
+ if (Number.isFinite(nextWindowWidth) && nextWindowWidth > 0) {
1430
+ systemInfo.windowWidth = nextWindowWidth;
1431
+ systemInfo.screenWidth = nextWindowWidth;
1432
+ }
1433
+ if (Number.isFinite(nextWindowHeight) && nextWindowHeight > 0) {
1434
+ systemInfo.windowHeight = nextWindowHeight;
1435
+ systemInfo.screenHeight = nextWindowHeight;
1436
+ }
1437
+ return systemInfo;
1438
+ }
1439
+ function deriveWindowInfo(systemInfo) {
1440
+ return {
1441
+ pixelRatio: systemInfo.pixelRatio,
1442
+ screenHeight: systemInfo.screenHeight,
1443
+ screenWidth: systemInfo.screenWidth,
1444
+ statusBarHeight: 20,
1445
+ windowHeight: systemInfo.windowHeight,
1446
+ windowWidth: systemInfo.windowWidth
1447
+ };
1448
+ }
1449
+ function deriveAppBaseInfo(systemInfo) {
1450
+ return {
1451
+ SDKVersion: systemInfo.SDKVersion,
1452
+ enableDebug: false,
1453
+ host: { env: systemInfo.platform },
1454
+ language: systemInfo.language,
1455
+ platform: systemInfo.platform,
1456
+ version: systemInfo.version
1457
+ };
1458
+ }
1459
+ function deriveMenuButtonBoundingClientRect(systemInfo) {
1460
+ const width = 87;
1461
+ const height = 32;
1462
+ const top = 32;
1463
+ const right = Math.max(systemInfo.windowWidth - 12, width);
1464
+ const left = Math.max(0, right - width);
1465
+ return {
1466
+ bottom: top + height,
1467
+ height,
1468
+ left,
1469
+ right,
1470
+ top,
1471
+ width
1472
+ };
1473
+ }
1474
+ //#endregion
1070
1475
  //#region src/runtime/wxState.ts
1476
+ const STORAGE_LIMIT_SIZE = 10 * 1024;
1477
+ const DEFAULT_MODAL_CANCEL_COLOR = "#000000";
1478
+ const DEFAULT_MODAL_CANCEL_TEXT = "取消";
1479
+ const DEFAULT_MODAL_CONFIRM_COLOR = "#576B95";
1480
+ const DEFAULT_MODAL_CONFIRM_TEXT = "确定";
1481
+ const textEncoder = new TextEncoder();
1482
+ function byteLength(input) {
1483
+ return textEncoder.encode(input).byteLength;
1484
+ }
1485
+ function cloneShareMenuSnapshot(snapshot) {
1486
+ return {
1487
+ isUpdatableMessage: snapshot.isUpdatableMessage,
1488
+ menus: [...snapshot.menus],
1489
+ visible: snapshot.visible,
1490
+ withShareTicket: snapshot.withShareTicket
1491
+ };
1492
+ }
1493
+ function createNetworkSnapshot(networkType) {
1494
+ return {
1495
+ isConnected: networkType !== "none",
1496
+ networkType
1497
+ };
1498
+ }
1071
1499
  function cloneValue$1(value) {
1072
1500
  if (value == null || typeof value !== "object") return value;
1073
1501
  return JSON.parse(JSON.stringify(value));
@@ -1104,14 +1532,46 @@ function resolveRequestResponse(mock, option) {
1104
1532
  };
1105
1533
  }
1106
1534
  function createHeadlessWxState() {
1535
+ const actionSheetLogs = [];
1536
+ const actionSheetMocks = [];
1537
+ const modalLogs = [];
1538
+ const networkStatusChangeCallbacks = /* @__PURE__ */ new Set();
1539
+ const modalMocks = [];
1107
1540
  const requestLogs = [];
1108
1541
  const requestMocks = [];
1109
1542
  const storage = /* @__PURE__ */ new Map();
1543
+ let loading = null;
1544
+ let networkType = "wifi";
1545
+ let shareMenu = {
1546
+ isUpdatableMessage: false,
1547
+ menus: [],
1548
+ visible: false,
1549
+ withShareTicket: false
1550
+ };
1110
1551
  let toast = null;
1111
1552
  return {
1112
1553
  clearStorageSync() {
1113
1554
  storage.clear();
1114
1555
  },
1556
+ getActionSheetLogs() {
1557
+ return actionSheetLogs.map((entry) => ({
1558
+ ...entry,
1559
+ itemList: [...entry.itemList],
1560
+ result: entry.result ? { ...entry.result } : void 0
1561
+ }));
1562
+ },
1563
+ getNetworkType() {
1564
+ return {
1565
+ errMsg: "getNetworkType:ok",
1566
+ networkType
1567
+ };
1568
+ },
1569
+ getModalLogs() {
1570
+ return modalLogs.map((entry) => ({
1571
+ ...entry,
1572
+ result: { ...entry.result }
1573
+ }));
1574
+ },
1115
1575
  getRequestLogs() {
1116
1576
  return requestLogs.map((entry) => ({
1117
1577
  ...entry,
@@ -1125,25 +1585,77 @@ function createHeadlessWxState() {
1125
1585
  } : void 0
1126
1586
  }));
1127
1587
  },
1588
+ getStorageInfoSync() {
1589
+ const keys = Array.from(storage.keys()).sort((a, b) => a.localeCompare(b));
1590
+ const totalBytes = Array.from(storage.entries()).reduce((sum, [key, value]) => {
1591
+ return sum + byteLength(JSON.stringify([key, value]));
1592
+ }, 0);
1593
+ return {
1594
+ currentSize: Math.ceil(totalBytes / 1024),
1595
+ errMsg: "getStorageInfo:ok",
1596
+ keys,
1597
+ limitSize: STORAGE_LIMIT_SIZE
1598
+ };
1599
+ },
1128
1600
  getStorageSnapshot() {
1129
1601
  return Object.fromEntries(Array.from(storage.entries(), ([key, value]) => [key, cloneValue$1(value)]));
1130
1602
  },
1131
1603
  getStorageSync(key) {
1132
1604
  return cloneValue$1(storage.get(key));
1133
1605
  },
1606
+ getShareMenu() {
1607
+ return cloneShareMenuSnapshot(shareMenu);
1608
+ },
1609
+ getLoading() {
1610
+ return loading ? { ...loading } : null;
1611
+ },
1612
+ hideShareMenu() {
1613
+ shareMenu = {
1614
+ ...shareMenu,
1615
+ visible: false
1616
+ };
1617
+ return { errMsg: "hideShareMenu:ok" };
1618
+ },
1134
1619
  getToast() {
1135
1620
  return toast ? { ...toast } : null;
1136
1621
  },
1622
+ hideLoading() {
1623
+ loading = null;
1624
+ return { errMsg: "hideLoading:ok" };
1625
+ },
1137
1626
  hideToast() {
1138
1627
  toast = null;
1139
1628
  return { errMsg: "hideToast:ok" };
1140
1629
  },
1630
+ offNetworkStatusChange(callback) {
1631
+ if (!callback) {
1632
+ networkStatusChangeCallbacks.clear();
1633
+ return;
1634
+ }
1635
+ networkStatusChangeCallbacks.delete(callback);
1636
+ },
1141
1637
  mockRequest(definition) {
1142
1638
  requestMocks.push({
1143
1639
  ...definition,
1640
+ delay: definition.delay,
1144
1641
  header: definition.header ? { ...definition.header } : void 0
1145
1642
  });
1146
1643
  },
1644
+ mockModal(definition = {}) {
1645
+ modalMocks.push({
1646
+ cancel: definition.cancel,
1647
+ confirm: definition.confirm
1648
+ });
1649
+ },
1650
+ mockActionSheet(definition = {}) {
1651
+ actionSheetMocks.push({
1652
+ cancel: definition.cancel,
1653
+ tapIndex: definition.tapIndex
1654
+ });
1655
+ },
1656
+ onNetworkStatusChange(callback) {
1657
+ networkStatusChangeCallbacks.add(callback);
1658
+ },
1147
1659
  removeStorageSync(key) {
1148
1660
  storage.delete(key);
1149
1661
  },
@@ -1158,22 +1670,119 @@ function createHeadlessWxState() {
1158
1670
  url: option.url
1159
1671
  };
1160
1672
  requestLogs.push(logEntry);
1161
- throw new Error(`No request mock matched in headless runtime: ${normalizeMethod(option.method)} ${option.url}`);
1673
+ const error = /* @__PURE__ */ new Error(`No request mock matched in headless runtime: ${normalizeMethod(option.method)} ${option.url}`);
1674
+ option.fail?.(error);
1675
+ option.complete?.();
1676
+ return { abort() {} };
1162
1677
  }
1163
1678
  const response = resolveRequestResponse(matchedMock, option);
1164
- requestLogs.push({
1679
+ const requestLogEntry = {
1165
1680
  data: cloneValue$1(option.data),
1166
1681
  header: { ...option.header ?? {} },
1167
1682
  matched: true,
1168
1683
  method: normalizeMethod(option.method),
1169
1684
  response,
1170
1685
  url: option.url
1171
- });
1172
- return response;
1686
+ };
1687
+ const delay = Number.isFinite(matchedMock.delay) ? Math.max(0, Math.trunc(matchedMock.delay ?? 0)) : 0;
1688
+ if (delay <= 0) {
1689
+ requestLogs.push(requestLogEntry);
1690
+ option.success?.(response);
1691
+ option.complete?.(response);
1692
+ return { abort() {} };
1693
+ }
1694
+ let completed = false;
1695
+ const timer = setTimeout(() => {
1696
+ if (completed) return;
1697
+ completed = true;
1698
+ requestLogs.push(requestLogEntry);
1699
+ option.success?.(response);
1700
+ option.complete?.(response);
1701
+ }, delay);
1702
+ return { abort() {
1703
+ if (completed) return;
1704
+ completed = true;
1705
+ clearTimeout(timer);
1706
+ const error = /* @__PURE__ */ new Error("request:fail abort");
1707
+ option.fail?.(error);
1708
+ option.complete?.();
1709
+ } };
1173
1710
  },
1174
1711
  setStorageSync(key, value) {
1175
1712
  storage.set(key, cloneValue$1(value));
1176
1713
  },
1714
+ setNetworkType(nextNetworkType) {
1715
+ networkType = nextNetworkType;
1716
+ const snapshot = createNetworkSnapshot(networkType);
1717
+ networkStatusChangeCallbacks.forEach((callback) => callback({ ...snapshot }));
1718
+ return {
1719
+ errMsg: "getNetworkType:ok",
1720
+ networkType
1721
+ };
1722
+ },
1723
+ showActionSheet(option) {
1724
+ const itemList = Array.isArray(option.itemList) ? option.itemList.filter((item) => typeof item === "string") : [];
1725
+ if (itemList.length === 0) throw new Error("showActionSheet:fail invalid itemList");
1726
+ const nextMock = actionSheetMocks.shift();
1727
+ if (nextMock?.cancel) {
1728
+ actionSheetLogs.push({ itemList: [...itemList] });
1729
+ throw new Error("showActionSheet:fail cancel");
1730
+ }
1731
+ const tapIndex = Number.isInteger(nextMock?.tapIndex) ? Number(nextMock?.tapIndex) : 0;
1732
+ if (tapIndex < 0 || tapIndex >= itemList.length) throw new Error("showActionSheet:fail invalid tapIndex");
1733
+ const result = {
1734
+ errMsg: "showActionSheet:ok",
1735
+ tapIndex
1736
+ };
1737
+ actionSheetLogs.push({
1738
+ itemList: [...itemList],
1739
+ result: { ...result }
1740
+ });
1741
+ return result;
1742
+ },
1743
+ showShareMenu(option = {}) {
1744
+ shareMenu = {
1745
+ isUpdatableMessage: Boolean(option.isUpdatableMessage),
1746
+ menus: Array.isArray(option.menus) ? option.menus.filter((item) => typeof item === "string") : shareMenu.menus,
1747
+ visible: true,
1748
+ withShareTicket: Boolean(option.withShareTicket)
1749
+ };
1750
+ return { errMsg: "showShareMenu:ok" };
1751
+ },
1752
+ showLoading(option) {
1753
+ loading = {
1754
+ mask: Boolean(option.mask),
1755
+ title: option.title
1756
+ };
1757
+ return { errMsg: "showLoading:ok" };
1758
+ },
1759
+ showModal(option) {
1760
+ const showCancel = option.showCancel !== false;
1761
+ const nextMock = modalMocks.shift();
1762
+ let confirm = nextMock?.confirm ?? true;
1763
+ let cancel = nextMock?.cancel ?? !confirm;
1764
+ if (!showCancel) {
1765
+ confirm = true;
1766
+ cancel = false;
1767
+ } else if (confirm) cancel = false;
1768
+ else cancel = true;
1769
+ const result = {
1770
+ cancel,
1771
+ confirm,
1772
+ errMsg: "showModal:ok"
1773
+ };
1774
+ modalLogs.push({
1775
+ cancelColor: option.cancelColor ?? DEFAULT_MODAL_CANCEL_COLOR,
1776
+ cancelText: option.cancelText ?? DEFAULT_MODAL_CANCEL_TEXT,
1777
+ confirmColor: option.confirmColor ?? DEFAULT_MODAL_CONFIRM_COLOR,
1778
+ confirmText: option.confirmText ?? DEFAULT_MODAL_CONFIRM_TEXT,
1779
+ content: option.content,
1780
+ result: { ...result },
1781
+ showCancel,
1782
+ title: option.title ?? ""
1783
+ });
1784
+ return result;
1785
+ },
1177
1786
  showToast(option) {
1178
1787
  toast = {
1179
1788
  duration: Number(option.duration ?? 1500),
@@ -1182,56 +1791,484 @@ function createHeadlessWxState() {
1182
1791
  title: option.title
1183
1792
  };
1184
1793
  return { errMsg: "showToast:ok" };
1794
+ },
1795
+ updateShareMenu(option = {}) {
1796
+ shareMenu = {
1797
+ isUpdatableMessage: option.isUpdatableMessage == null ? shareMenu.isUpdatableMessage : Boolean(option.isUpdatableMessage),
1798
+ menus: Array.isArray(option.menus) ? option.menus.filter((item) => typeof item === "string") : shareMenu.menus,
1799
+ visible: true,
1800
+ withShareTicket: option.withShareTicket == null ? shareMenu.withShareTicket : Boolean(option.withShareTicket)
1801
+ };
1802
+ return { errMsg: "updateShareMenu:ok" };
1185
1803
  }
1186
1804
  };
1187
1805
  }
1188
1806
  //#endregion
1189
- //#region src/browser/session.ts
1190
- const LEADING_SLASH_RE$2 = /^\/+/;
1191
- const PAGE_STACK_LIMIT$1 = 10;
1192
- const DATA_ATTR_SELECTOR_RE$1 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
1193
- const DATASET_KEY_RE = /-([a-z])/g;
1194
- function stripLeadingSlash$1(route) {
1195
- return route.replace(LEADING_SLASH_RE$2, "");
1196
- }
1197
- function normalizeQuery$1(queryString) {
1198
- const query = new URLSearchParams(queryString);
1199
- const result = {};
1200
- for (const [key, value] of query.entries()) result[key] = value;
1201
- return result;
1202
- }
1203
- function parseNavigationUrl$1(url) {
1204
- const trimmedUrl = url.trim();
1205
- if (!trimmedUrl) throw new Error("Navigation url must be a non-empty string in browser simulator runtime.");
1206
- const [pathWithHash, queryString = ""] = trimmedUrl.split("?");
1207
- const [pathname] = pathWithHash.split("#");
1208
- return {
1209
- pathname: pathname || "",
1210
- query: normalizeQuery$1(queryString)
1211
- };
1807
+ //#region src/view/selectors.ts
1808
+ const WHITESPACE_RE = /\s+/;
1809
+ const DATA_ATTR_SELECTOR_RE$2 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
1810
+ function getClassList(node) {
1811
+ return String(node.attribs?.class ?? "").split(WHITESPACE_RE).map((item) => item.trim()).filter(Boolean);
1212
1812
  }
1213
- function createAppLaunchOptions$1(pathname, query) {
1214
- return {
1215
- path: stripLeadingSlash$1(pathname),
1216
- query: { ...query },
1217
- referrerInfo: {
1218
- appId: "",
1219
- extraData: {}
1220
- },
1221
- scene: 1001
1222
- };
1813
+ function matchesSimpleSelector(node, selector) {
1814
+ if (node.type !== "tag") return false;
1815
+ if (selector === "page") return node.name === "page";
1816
+ if (selector.startsWith("#")) return node.attribs?.id === selector.slice(1);
1817
+ if (selector.startsWith(".")) return getClassList(node).includes(selector.slice(1));
1818
+ const dataAttrMatch = selector.match(DATA_ATTR_SELECTOR_RE$2);
1819
+ if (dataAttrMatch) {
1820
+ const [, key, value] = dataAttrMatch;
1821
+ return node.attribs?.[`data-${key}`] === value;
1822
+ }
1823
+ return node.name === selector;
1223
1824
  }
1224
- function resolveNavigationPath$1(targetPath, baseRoute) {
1225
- if (!targetPath) throw new Error("Navigation url must include a pathname in browser simulator runtime.");
1226
- if (targetPath.startsWith("/")) return posix.normalize(targetPath).replace(LEADING_SLASH_RE$2, "");
1227
- if (!baseRoute) throw new Error(`Cannot resolve relative navigation url "${targetPath}" without an active page.`);
1228
- return posix.resolve(`/${posix.dirname(baseRoute)}`, targetPath).replace(LEADING_SLASH_RE$2, "");
1825
+ function collectDescendants(node, into) {
1826
+ for (const child of node.children ?? []) {
1827
+ into.push(child);
1828
+ collectDescendants(child, into);
1829
+ }
1229
1830
  }
1230
- var BrowserHeadlessSession = class {
1231
- files;
1232
- project;
1233
- appDefinition = null;
1234
- appInstance = null;
1831
+ function querySelectorAll(root, selector) {
1832
+ const parts = selector.trim().split(WHITESPACE_RE).filter(Boolean);
1833
+ if (parts.length === 0) return [];
1834
+ let current = [root];
1835
+ for (const part of parts) {
1836
+ const next = [];
1837
+ for (const node of current) {
1838
+ const candidates = [];
1839
+ if (part === "page" && node.type === "tag" && node.name === "page") candidates.push(node);
1840
+ collectDescendants(node, candidates);
1841
+ for (const candidate of candidates) if (matchesSimpleSelector(candidate, part)) next.push(candidate);
1842
+ }
1843
+ current = next;
1844
+ }
1845
+ return current;
1846
+ }
1847
+ //#endregion
1848
+ //#region src/view/nodeHandle.ts
1849
+ const DATASET_NAME_RE$2 = /-([a-z])/g;
1850
+ function escapeText$2(text) {
1851
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1852
+ }
1853
+ function toDatasetKey$2(attributeName) {
1854
+ return attributeName.slice(5).replace(DATASET_NAME_RE$2, (_match, char) => char.toUpperCase());
1855
+ }
1856
+ function collectDataset$2(node) {
1857
+ const dataset = {};
1858
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
1859
+ if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
1860
+ dataset[toDatasetKey$2(key)] = value;
1861
+ }
1862
+ return dataset;
1863
+ }
1864
+ function resolveEventBinding(node, eventName) {
1865
+ const normalizedEventName = eventName.trim();
1866
+ if (!normalizedEventName) return null;
1867
+ const bindingAttrs = [
1868
+ `bind${normalizedEventName}`,
1869
+ `bind:${normalizedEventName}`,
1870
+ `catch${normalizedEventName}`,
1871
+ `catch:${normalizedEventName}`
1872
+ ];
1873
+ for (const attributeName of bindingAttrs) {
1874
+ const methodName = node.attribs?.[attributeName]?.trim();
1875
+ if (methodName) return methodName;
1876
+ }
1877
+ return null;
1878
+ }
1879
+ function createEventPayload(node, eventName, event) {
1880
+ const dataset = collectDataset$2(node);
1881
+ const nodeId = node.attribs?.id ?? "";
1882
+ return {
1883
+ bubbles: false,
1884
+ capturePhase: false,
1885
+ composed: false,
1886
+ currentTarget: {
1887
+ dataset: event.currentTarget?.dataset ?? event.dataset ?? dataset,
1888
+ id: event.currentTarget?.id ?? event.id ?? nodeId
1889
+ },
1890
+ detail: event.detail,
1891
+ mark: event.mark,
1892
+ target: {
1893
+ dataset: event.target?.dataset ?? event.dataset ?? dataset,
1894
+ id: event.target?.id ?? event.id ?? nodeId
1895
+ },
1896
+ type: eventName
1897
+ };
1898
+ }
1899
+ function createValueEventDetail(value, detail) {
1900
+ return {
1901
+ value,
1902
+ ...detail ?? {}
1903
+ };
1904
+ }
1905
+ function escapeAttribute$2(value) {
1906
+ return escapeText$2(value).replaceAll("\"", "&quot;");
1907
+ }
1908
+ function serializeNode(node) {
1909
+ if (node.type === "text") return escapeText$2(node.data ?? "");
1910
+ if (node.type !== "tag") return (node.children ?? []).map(serializeNode).join("");
1911
+ if (node.name === "page") return (node.children ?? []).filter((child) => !(child.type === "tag" && (child.name === "import" || child.name === "wxs"))).map(serializeNode).join("");
1912
+ const attrs = Object.entries(node.attribs ?? {}).filter(([key]) => !key.startsWith("data-sim-")).map(([key, value]) => ` ${key}="${escapeAttribute$2(value)}"`).join("");
1913
+ const children = (node.children ?? []).map(serializeNode).join("");
1914
+ return `<${node.name ?? ""}${attrs}>${children}</${node.name ?? ""}>`;
1915
+ }
1916
+ function collectText(node) {
1917
+ if (node.type === "text") return node.data ?? "";
1918
+ return (node.children ?? []).map(collectText).join("");
1919
+ }
1920
+ function resolvePageScopeId$1(scopeId) {
1921
+ if (!scopeId) return null;
1922
+ const pagePathIndex = scopeId.indexOf("/page/");
1923
+ return pagePathIndex >= 0 ? scopeId.slice(0, pagePathIndex) : scopeId;
1924
+ }
1925
+ function resolveComponentScopeId(scopeId) {
1926
+ if (!scopeId || !scopeId.includes("/")) return null;
1927
+ return scopeId;
1928
+ }
1929
+ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
1930
+ constructor(node, interactions) {
1931
+ this.node = node;
1932
+ this.interactions = interactions;
1933
+ }
1934
+ async $(selector) {
1935
+ const match = querySelectorAll(this.node, selector)[0];
1936
+ return match ? new HeadlessTestingNodeHandle(match, this.interactions) : null;
1937
+ }
1938
+ async $$(selector) {
1939
+ return querySelectorAll(this.node, selector).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
1940
+ }
1941
+ async attr(name) {
1942
+ return this.node.attribs?.[name];
1943
+ }
1944
+ async dataset() {
1945
+ return collectDataset$2(this.node);
1946
+ }
1947
+ async scope() {
1948
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
1949
+ return this.interactions.createScopeHandle(this.node.attribs?.["data-sim-scope"] ?? null);
1950
+ }
1951
+ async componentScope() {
1952
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
1953
+ return this.interactions.createScopeHandle(resolveComponentScopeId(this.node.attribs?.["data-sim-scope"] ?? null));
1954
+ }
1955
+ async pageScope() {
1956
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
1957
+ return this.interactions.createScopeHandle(resolvePageScopeId$1(this.node.attribs?.["data-sim-scope"] ?? null));
1958
+ }
1959
+ async page() {
1960
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
1961
+ return this.interactions.createPageHandle();
1962
+ }
1963
+ async ownerComponentScope() {
1964
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
1965
+ const scopeId = resolveComponentScopeId(this.node.attribs?.["data-sim-scope"] ?? null);
1966
+ return this.interactions.createScopeHandle(this.interactions.ownerScopeId(scopeId));
1967
+ }
1968
+ async text() {
1969
+ return collectText(this.node);
1970
+ }
1971
+ async trigger(eventName, event = {}) {
1972
+ if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
1973
+ const normalizedEventName = eventName.trim();
1974
+ if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
1975
+ const methodName = resolveEventBinding(this.node, normalizedEventName);
1976
+ if (!methodName) throw new Error(`No ${normalizedEventName} binding was found on <${this.node.name ?? "unknown"}> in headless testing runtime.`);
1977
+ return await this.interactions.callMethod(this.node.attribs?.["data-sim-scope"] ?? null, methodName, createEventPayload(this.node, normalizedEventName, event));
1978
+ }
1979
+ async tap(event = {}) {
1980
+ return await this.trigger("tap", event);
1981
+ }
1982
+ async input(value, event = {}) {
1983
+ return await this.trigger("input", {
1984
+ ...event,
1985
+ detail: createValueEventDetail(value, event.detail)
1986
+ });
1987
+ }
1988
+ async change(value, event = {}) {
1989
+ return await this.trigger("change", {
1990
+ ...event,
1991
+ detail: createValueEventDetail(value, event.detail)
1992
+ });
1993
+ }
1994
+ async blur(value, event = {}) {
1995
+ return await this.trigger("blur", {
1996
+ ...event,
1997
+ detail: value == null ? event.detail : createValueEventDetail(value, event.detail)
1998
+ });
1999
+ }
2000
+ async wxml() {
2001
+ return serializeNode(this.node);
2002
+ }
2003
+ };
2004
+ //#endregion
2005
+ //#region src/view/render.ts
2006
+ const LEADING_SLASH_RE$4 = /^\/+/;
2007
+ const TEMPLATE_INTERPOLATION_RE$1 = /\{\{([^{}]+)\}\}/g;
2008
+ function resolveValueByPath$1(source, expression) {
2009
+ const normalized = expression.trim();
2010
+ if (!normalized) return "";
2011
+ const segments = normalized.split(".").filter(Boolean);
2012
+ let current = source;
2013
+ for (const segment of segments) current = current?.[segment];
2014
+ return current ?? "";
2015
+ }
2016
+ function interpolateTemplate$1(input, data) {
2017
+ return input.replace(TEMPLATE_INTERPOLATION_RE$1, (_match, expression) => {
2018
+ const value = resolveValueByPath$1(data, expression);
2019
+ return typeof value === "string" ? value : String(value);
2020
+ });
2021
+ }
2022
+ function visitDom(node, visitor) {
2023
+ visitor(node);
2024
+ for (const child of node.children ?? []) visitDom(child, visitor);
2025
+ }
2026
+ function interpolateDomTree(root, data) {
2027
+ visitDom(root, (node) => {
2028
+ if (typeof node.data === "string") node.data = interpolateTemplate$1(node.data, data);
2029
+ if (node.attribs) for (const [key, value] of Object.entries(node.attribs)) node.attribs[key] = interpolateTemplate$1(value, data);
2030
+ });
2031
+ }
2032
+ function escapeText$1(text) {
2033
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
2034
+ }
2035
+ function escapeAttribute$1(value) {
2036
+ return escapeText$1(value).replaceAll("\"", "&quot;");
2037
+ }
2038
+ function serializeDomNode$1(node) {
2039
+ if (node.type === "text") return escapeText$1(node.data ?? "");
2040
+ if (node.type === "root") return (node.children ?? []).map(serializeDomNode$1).join("");
2041
+ const tagName = node.name ?? "";
2042
+ if (!tagName) return (node.children ?? []).map(serializeDomNode$1).join("");
2043
+ return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$1(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$1).join("")}</${tagName}>`;
2044
+ }
2045
+ function renderPageTree(project, page) {
2046
+ const route = page.route.replace(LEADING_SLASH_RE$4, "");
2047
+ const templatePath = path.resolve(project.miniprogramRootPath, `${route}.wxml`);
2048
+ const document = parseDocument(`<page>${fs.readFileSync(templatePath, "utf8")}</page>`, {
2049
+ xmlMode: false,
2050
+ decodeEntities: false,
2051
+ recognizeSelfClosing: true
2052
+ });
2053
+ interpolateDomTree(document, page.data);
2054
+ return {
2055
+ root: document,
2056
+ wxml: serializeDomNode$1((document.children ?? [])[0] ?? document)
2057
+ };
2058
+ }
2059
+ //#endregion
2060
+ //#region src/view/selectorQuery.ts
2061
+ const DATASET_NAME_RE$1 = /-([a-z])/g;
2062
+ const LEADING_MARK_PREFIX_RE = /^mark[:\-]?/;
2063
+ const MARK_NAME_RE = /[:\-]([a-z])/g;
2064
+ const NUMERIC_LIKE_VALUE_RE = /-?\d+(?:\.\d+)?/;
2065
+ function toDatasetKey$1(attributeName) {
2066
+ return attributeName.slice(5).replace(DATASET_NAME_RE$1, (_match, char) => char.toUpperCase());
2067
+ }
2068
+ function collectDataset$1(node) {
2069
+ const dataset = {};
2070
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
2071
+ if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
2072
+ dataset[toDatasetKey$1(key)] = value;
2073
+ }
2074
+ return dataset;
2075
+ }
2076
+ function toMarkKey(attributeName) {
2077
+ return attributeName.replace(LEADING_MARK_PREFIX_RE, "").replace(MARK_NAME_RE, (_match, char) => char.toUpperCase());
2078
+ }
2079
+ function collectMark(node) {
2080
+ const mark = {};
2081
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
2082
+ if (!(key.startsWith("mark:") || key.startsWith("mark-"))) continue;
2083
+ mark[toMarkKey(key)] = value;
2084
+ }
2085
+ return mark;
2086
+ }
2087
+ function createScopedRoot(node) {
2088
+ return {
2089
+ children: [node],
2090
+ type: "root"
2091
+ };
2092
+ }
2093
+ function findNodeByScopeId(root, scopeId) {
2094
+ if (root.attribs?.["data-sim-scope"] === scopeId) return root;
2095
+ for (const child of root.children ?? []) {
2096
+ const match = findNodeByScopeId(child, scopeId);
2097
+ if (match) return match;
2098
+ }
2099
+ return null;
2100
+ }
2101
+ function parseStyleDeclarations(styleValue) {
2102
+ const declarations = {};
2103
+ if (!styleValue) return declarations;
2104
+ for (const declaration of styleValue.split(";")) {
2105
+ const [rawProperty, ...rawValueParts] = declaration.split(":");
2106
+ const property = rawProperty?.trim();
2107
+ if (!property) continue;
2108
+ declarations[property] = rawValueParts.join(":").trim();
2109
+ }
2110
+ return declarations;
2111
+ }
2112
+ function parseNumericLikeValue(value) {
2113
+ if (!value) return 0;
2114
+ const match = value.match(NUMERIC_LIKE_VALUE_RE);
2115
+ return match ? Number(match[0]) : 0;
2116
+ }
2117
+ function resolveRect(node) {
2118
+ const style = parseStyleDeclarations(node.attribs?.style);
2119
+ const left = parseNumericLikeValue(node.attribs?.["data-sim-left"] ?? style.left);
2120
+ const top = parseNumericLikeValue(node.attribs?.["data-sim-top"] ?? style.top);
2121
+ const width = parseNumericLikeValue(node.attribs?.["data-sim-width"] ?? style.width);
2122
+ const height = parseNumericLikeValue(node.attribs?.["data-sim-height"] ?? style.height);
2123
+ return {
2124
+ bottom: top + height,
2125
+ height,
2126
+ left,
2127
+ right: left + width,
2128
+ top,
2129
+ width
2130
+ };
2131
+ }
2132
+ function resolveScrollOffset(node) {
2133
+ return {
2134
+ scrollLeft: parseNumericLikeValue(node.attribs?.["data-sim-scroll-left"]),
2135
+ scrollTop: parseNumericLikeValue(node.attribs?.["data-sim-scroll-top"])
2136
+ };
2137
+ }
2138
+ function resolvePropertyValue(node, propertyName) {
2139
+ const normalizedPropertyName = propertyName.trim();
2140
+ if (!normalizedPropertyName) return;
2141
+ if (normalizedPropertyName === "id") return node.attribs?.id ?? "";
2142
+ if (normalizedPropertyName === "class") return node.attribs?.class ?? "";
2143
+ if (normalizedPropertyName === "dataset") return collectDataset$1(node);
2144
+ return node.attribs?.[normalizedPropertyName];
2145
+ }
2146
+ function pickProperties(node, propertyNames) {
2147
+ const result = {};
2148
+ for (const propertyName of propertyNames) result[propertyName] = resolvePropertyValue(node, propertyName);
2149
+ return result;
2150
+ }
2151
+ function pickComputedStyle(node, propertyNames) {
2152
+ const style = parseStyleDeclarations(node.attribs?.style);
2153
+ const result = {};
2154
+ for (const propertyName of propertyNames) result[propertyName] = style[propertyName] ?? "";
2155
+ return result;
2156
+ }
2157
+ function resolveFieldsResult(node, fields, _options) {
2158
+ const result = {};
2159
+ if (fields.id) result.id = node.attribs?.id ?? "";
2160
+ if (fields.dataset) result.dataset = collectDataset$1(node);
2161
+ if (fields.mark) result.mark = collectMark(node);
2162
+ if (fields.rect || fields.size) {
2163
+ const rect = resolveRect(node);
2164
+ if (fields.rect) Object.assign(result, rect);
2165
+ if (fields.size) {
2166
+ result.width = rect.width;
2167
+ result.height = rect.height;
2168
+ }
2169
+ }
2170
+ if (fields.scrollOffset) Object.assign(result, resolveScrollOffset(node));
2171
+ if (Array.isArray(fields.properties) && fields.properties.length > 0) Object.assign(result, pickProperties(node, fields.properties));
2172
+ if (Array.isArray(fields.computedStyle) && fields.computedStyle.length > 0) Object.assign(result, pickComputedStyle(node, fields.computedStyle));
2173
+ if (fields.context) result.context = { type: "unsupported-context" };
2174
+ if (fields.node) result.node = { type: node.name ?? "unknown" };
2175
+ return result;
2176
+ }
2177
+ function resolveViewportResult(fields, options) {
2178
+ const result = {};
2179
+ if (fields.rect || fields.size) {
2180
+ const rect = {
2181
+ bottom: options.windowInfo.windowHeight,
2182
+ height: options.windowInfo.windowHeight,
2183
+ left: 0,
2184
+ right: options.windowInfo.windowWidth,
2185
+ top: 0,
2186
+ width: options.windowInfo.windowWidth
2187
+ };
2188
+ if (fields.rect) Object.assign(result, rect);
2189
+ if (fields.size) {
2190
+ result.width = rect.width;
2191
+ result.height = rect.height;
2192
+ }
2193
+ }
2194
+ if (fields.scrollOffset) {
2195
+ result.scrollLeft = 0;
2196
+ result.scrollTop = options.page.__scrollTop__ ?? 0;
2197
+ }
2198
+ return result;
2199
+ }
2200
+ function resolveRequestResult(request, options) {
2201
+ if (request.target === "viewport") return resolveViewportResult(request.fields, options);
2202
+ const matches = querySelectorAll(options.root, request.selector ?? "");
2203
+ if (!request.single) return matches.map((node) => resolveFieldsResult(node, request.fields, options));
2204
+ const match = matches[0];
2205
+ return match ? resolveFieldsResult(match, request.fields, options) : null;
2206
+ }
2207
+ function executeSelectorQueryRequests(requests, options) {
2208
+ return requests.map((request) => resolveRequestResult(request, options));
2209
+ }
2210
+ function resolveSelectorQueryScopeRoot(root, scopeId) {
2211
+ if (!scopeId) return root;
2212
+ const scopedNode = findNodeByScopeId(root, scopeId);
2213
+ return scopedNode ? createScopedRoot(scopedNode) : root;
2214
+ }
2215
+ //#endregion
2216
+ //#region src/browser/session.ts
2217
+ const LEADING_SLASH_RE$3 = /^\/+/;
2218
+ const PAGE_STACK_LIMIT$1 = 10;
2219
+ const DATA_ATTR_SELECTOR_RE$1 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
2220
+ const DATASET_KEY_RE$1 = /-([a-z])/g;
2221
+ function stripLeadingSlash$1(route) {
2222
+ return route.replace(LEADING_SLASH_RE$3, "");
2223
+ }
2224
+ function normalizeQuery$1(queryString) {
2225
+ const query = new URLSearchParams(queryString);
2226
+ const result = {};
2227
+ for (const [key, value] of query.entries()) result[key] = value;
2228
+ return result;
2229
+ }
2230
+ function parseNavigationUrl$1(url) {
2231
+ const trimmedUrl = url.trim();
2232
+ if (!trimmedUrl) throw new Error("Navigation url must be a non-empty string in browser simulator runtime.");
2233
+ const [pathWithHash, queryString = ""] = trimmedUrl.split("?");
2234
+ const [pathname] = pathWithHash.split("#");
2235
+ return {
2236
+ pathname: pathname || "",
2237
+ query: normalizeQuery$1(queryString)
2238
+ };
2239
+ }
2240
+ function createAppLaunchOptions$1(pathname, query) {
2241
+ return {
2242
+ path: stripLeadingSlash$1(pathname),
2243
+ query: { ...query },
2244
+ referrerInfo: {
2245
+ appId: "",
2246
+ extraData: {}
2247
+ },
2248
+ scene: 1001
2249
+ };
2250
+ }
2251
+ function readJsonObject$2(files, filePath) {
2252
+ const content = readBrowserVirtualFile(files, filePath);
2253
+ if (!content) return;
2254
+ try {
2255
+ const value = JSON.parse(content);
2256
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2257
+ } catch {
2258
+ return;
2259
+ }
2260
+ }
2261
+ function resolveNavigationPath$1(targetPath, baseRoute) {
2262
+ if (!targetPath) throw new Error("Navigation url must include a pathname in browser simulator runtime.");
2263
+ if (targetPath.startsWith("/")) return posix.normalize(targetPath).replace(LEADING_SLASH_RE$3, "");
2264
+ if (!baseRoute) throw new Error(`Cannot resolve relative navigation url "${targetPath}" without an active page.`);
2265
+ return posix.resolve(`/${posix.dirname(baseRoute)}`, targetPath).replace(LEADING_SLASH_RE$3, "");
2266
+ }
2267
+ var BrowserHeadlessSession = class {
2268
+ files;
2269
+ project;
2270
+ appDefinition = null;
2271
+ appInstance = null;
1235
2272
  moduleLoader;
1236
2273
  registries;
1237
2274
  currentPageInstance = null;
@@ -1241,7 +2278,16 @@ var BrowserHeadlessSession = class {
1241
2278
  tabBarRoutes;
1242
2279
  tabPages = /* @__PURE__ */ new Map();
1243
2280
  tabBarItems = /* @__PURE__ */ new Map();
2281
+ tabBarState = /* @__PURE__ */ new Map();
2282
+ tabBarVisible = false;
2283
+ systemInfo = createDefaultSystemInfo();
2284
+ enterOptions = createAppLaunchOptions$1("", {});
2285
+ launchOptions = createAppLaunchOptions$1("", {});
1244
2286
  wxState = createHeadlessWxState();
2287
+ pullDownRefreshState = {
2288
+ active: false,
2289
+ stopCalls: 0
2290
+ };
1245
2291
  constructor(options) {
1246
2292
  this.files = options.files;
1247
2293
  this.project = options.project ?? createBrowserProject(options.files);
@@ -1258,22 +2304,75 @@ var BrowserHeadlessSession = class {
1258
2304
  pagePath,
1259
2305
  text: typeof item.text === "string" ? item.text : void 0
1260
2306
  });
2307
+ this.tabBarState.set(index, {
2308
+ badge: null,
2309
+ index,
2310
+ pagePath,
2311
+ redDot: false,
2312
+ text: typeof item.text === "string" ? item.text : void 0
2313
+ });
1261
2314
  });
2315
+ this.tabBarVisible = this.tabBarRoutes.size > 0;
1262
2316
  this.moduleLoader = createBrowserModuleLoader(this.files, this.registries, () => this.pages.slice(), () => this.getApp(), {
2317
+ executeSelectorQuery: (requests, scope) => this.executeSelectorQuery(requests, scope),
2318
+ getEnterOptionsSync: () => ({
2319
+ ...this.enterOptions,
2320
+ query: { ...this.enterOptions.query },
2321
+ referrerInfo: {
2322
+ ...this.enterOptions.referrerInfo,
2323
+ extraData: { ...this.enterOptions.referrerInfo.extraData }
2324
+ }
2325
+ }),
2326
+ getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
2327
+ getLaunchOptionsSync: () => ({
2328
+ ...this.launchOptions,
2329
+ query: { ...this.launchOptions.query },
2330
+ referrerInfo: {
2331
+ ...this.launchOptions.referrerInfo,
2332
+ extraData: { ...this.launchOptions.referrerInfo.extraData }
2333
+ }
2334
+ }),
2335
+ getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
2336
+ getNetworkType: () => this.wxState.getNetworkType(),
1263
2337
  navigateBack: (option) => this.navigateBack(option?.delta),
1264
2338
  navigateTo: (option) => this.navigateTo(option.url),
1265
2339
  pageScrollTo: (option) => this.pageScrollTo(option),
1266
2340
  clearStorageSync: () => this.wxState.clearStorageSync(),
2341
+ getStorageInfoSync: () => this.wxState.getStorageInfoSync(),
1267
2342
  getStorageSync: (key) => this.wxState.getStorageSync(key),
2343
+ getSystemInfoSync: () => ({ ...this.systemInfo }),
2344
+ getWindowInfoSync: () => deriveWindowInfo(this.systemInfo),
2345
+ hideLoading: () => this.wxState.hideLoading(),
1268
2346
  hideToast: () => this.wxState.hideToast(),
1269
2347
  reLaunch: (option) => this.reLaunch(option.url),
1270
2348
  redirectTo: (option) => this.redirectTo(option.url),
2349
+ nextTick: (callback) => queueMicrotask(() => callback?.()),
2350
+ offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
2351
+ onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
1271
2352
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
1272
2353
  request: (option) => this.wxState.request(option),
2354
+ setBackgroundColor: (option) => this.setBackgroundColor(option),
2355
+ setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
1273
2356
  setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
2357
+ setNavigationBarColor: (option) => this.setNavigationBarColor(option),
2358
+ setNavigationBarTitle: (option) => this.setNavigationBarTitle(option.title),
2359
+ hideShareMenu: () => this.wxState.hideShareMenu(),
2360
+ hideNavigationBarLoading: () => this.hideNavigationBarLoading(),
2361
+ hideTabBar: () => this.hideTabBar(),
2362
+ hideTabBarRedDot: (option) => this.hideTabBarRedDot(option.index),
2363
+ showShareMenu: (option) => this.wxState.showShareMenu(option),
2364
+ showNavigationBarLoading: () => this.showNavigationBarLoading(),
2365
+ showTabBar: () => this.showTabBar(),
2366
+ showTabBarRedDot: (option) => this.showTabBarRedDot(option.index),
2367
+ showActionSheet: (option) => this.wxState.showActionSheet(option),
2368
+ showLoading: (option) => this.wxState.showLoading(option),
2369
+ showModal: (option) => this.wxState.showModal(option),
1274
2370
  showToast: (option) => this.wxState.showToast(option),
1275
2371
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
1276
- switchTab: (option) => this.switchTab(option.url)
2372
+ switchTab: (option) => this.switchTab(option.url),
2373
+ removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
2374
+ setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
2375
+ updateShareMenu: (option) => this.wxState.updateShareMenu(option)
1277
2376
  });
1278
2377
  }
1279
2378
  getApp() {
@@ -1282,31 +2381,229 @@ var BrowserHeadlessSession = class {
1282
2381
  getCurrentPages() {
1283
2382
  return this.pages.slice();
1284
2383
  }
2384
+ getCurrentPageNavigationBarTitle() {
2385
+ return this.currentPageInstance?.__navigationBarTitle__ ?? null;
2386
+ }
2387
+ getCurrentPageNavigationBar() {
2388
+ const snapshot = this.currentPageInstance?.__navigationBar__;
2389
+ return snapshot ? cloneNavigationBarSnapshot(snapshot) : null;
2390
+ }
2391
+ getCurrentPageBackground() {
2392
+ const snapshot = this.currentPageInstance?.__background__;
2393
+ return snapshot ? cloneBackgroundSnapshot(snapshot) : null;
2394
+ }
2395
+ getActionSheetLogs() {
2396
+ return this.wxState.getActionSheetLogs();
2397
+ }
1285
2398
  getRequestLogs() {
1286
2399
  return this.wxState.getRequestLogs();
1287
2400
  }
1288
2401
  getStorageSnapshot() {
1289
2402
  return this.wxState.getStorageSnapshot();
1290
2403
  }
1291
- getToast() {
1292
- return this.wxState.getToast();
2404
+ getShareMenu() {
2405
+ return this.wxState.getShareMenu();
1293
2406
  }
1294
- mockRequest(definition) {
1295
- this.wxState.mockRequest(definition);
2407
+ getTabBar() {
2408
+ return { visible: this.tabBarVisible };
1296
2409
  }
1297
- getScopeSnapshot(scopeId) {
1298
- const scope = this.componentScopes.get(scopeId);
1299
- if (!scope) return null;
1300
- const instance = this.componentCache.get(scopeId);
1301
- if (instance) return {
1302
- data: instance.data ?? {},
1303
- methods: Object.keys(instance).filter((key) => typeof instance[key] === "function").sort((a, b) => a.localeCompare(b)),
1304
- properties: instance.properties ?? {},
1305
- scopeId,
1306
- type: "component"
2410
+ getTabBarSnapshot() {
2411
+ return {
2412
+ items: Array.from(this.tabBarState.values(), (item) => ({
2413
+ badge: item.badge,
2414
+ index: item.index,
2415
+ pagePath: item.pagePath,
2416
+ redDot: item.redDot,
2417
+ text: item.text
2418
+ })),
2419
+ visible: this.tabBarVisible
1307
2420
  };
1308
- const currentPage = this.currentPageInstance;
1309
- if (currentPage && scopeId === `page:${currentPage.route}`) return {
2421
+ }
2422
+ getStorageInfo() {
2423
+ return this.wxState.getStorageInfoSync();
2424
+ }
2425
+ getPullDownRefreshState() {
2426
+ return { ...this.pullDownRefreshState };
2427
+ }
2428
+ getSystemInfo() {
2429
+ return { ...this.systemInfo };
2430
+ }
2431
+ getWindowInfo() {
2432
+ return deriveWindowInfo(this.systemInfo);
2433
+ }
2434
+ getAppBaseInfo() {
2435
+ return deriveAppBaseInfo(this.systemInfo);
2436
+ }
2437
+ getLaunchOptions() {
2438
+ return {
2439
+ ...this.launchOptions,
2440
+ query: { ...this.launchOptions.query },
2441
+ referrerInfo: {
2442
+ ...this.launchOptions.referrerInfo,
2443
+ extraData: { ...this.launchOptions.referrerInfo.extraData }
2444
+ }
2445
+ };
2446
+ }
2447
+ getEnterOptions() {
2448
+ return {
2449
+ ...this.enterOptions,
2450
+ query: { ...this.enterOptions.query },
2451
+ referrerInfo: {
2452
+ ...this.enterOptions.referrerInfo,
2453
+ extraData: { ...this.enterOptions.referrerInfo.extraData }
2454
+ }
2455
+ };
2456
+ }
2457
+ getMenuButtonBoundingClientRect() {
2458
+ return deriveMenuButtonBoundingClientRect(this.systemInfo);
2459
+ }
2460
+ getNetworkType() {
2461
+ return this.wxState.getNetworkType();
2462
+ }
2463
+ getLoading() {
2464
+ return this.wxState.getLoading();
2465
+ }
2466
+ getModalLogs() {
2467
+ return this.wxState.getModalLogs();
2468
+ }
2469
+ getToast() {
2470
+ return this.wxState.getToast();
2471
+ }
2472
+ mockModal(definition = {}) {
2473
+ this.wxState.mockModal(definition);
2474
+ }
2475
+ mockActionSheet(definition = {}) {
2476
+ this.wxState.mockActionSheet(definition);
2477
+ }
2478
+ mockRequest(definition) {
2479
+ this.wxState.mockRequest(definition);
2480
+ }
2481
+ setNetworkType(networkType) {
2482
+ return this.wxState.setNetworkType(networkType);
2483
+ }
2484
+ setBackgroundTextStyle(textStyle) {
2485
+ if (textStyle !== "dark" && textStyle !== "light") throw new Error("setBackgroundTextStyle:fail invalid textStyle");
2486
+ const current = this.requireCurrentPage("wx.setBackgroundTextStyle()");
2487
+ current.__background__ ??= {
2488
+ backgroundColor: "#ffffff",
2489
+ backgroundColorBottom: "#ffffff",
2490
+ backgroundColorTop: "#ffffff",
2491
+ textStyle: "dark"
2492
+ };
2493
+ current.__background__.textStyle = textStyle;
2494
+ current.__backgroundTextStyle__ = textStyle;
2495
+ return { errMsg: "setBackgroundTextStyle:ok" };
2496
+ }
2497
+ setBackgroundColor(option) {
2498
+ const current = this.requireCurrentPage("wx.setBackgroundColor()");
2499
+ current.__background__ ??= {
2500
+ backgroundColor: "#ffffff",
2501
+ backgroundColorBottom: "#ffffff",
2502
+ backgroundColorTop: "#ffffff",
2503
+ textStyle: current.__backgroundTextStyle__ ?? "dark"
2504
+ };
2505
+ if (typeof option.backgroundColor === "string") current.__background__.backgroundColor = option.backgroundColor;
2506
+ if (typeof option.backgroundColorTop === "string") current.__background__.backgroundColorTop = option.backgroundColorTop;
2507
+ if (typeof option.backgroundColorBottom === "string") current.__background__.backgroundColorBottom = option.backgroundColorBottom;
2508
+ return { errMsg: "setBackgroundColor:ok" };
2509
+ }
2510
+ setNavigationBarTitle(title) {
2511
+ const current = this.requireCurrentPage("wx.setNavigationBarTitle()");
2512
+ current.__navigationBar__ ??= {
2513
+ animation: null,
2514
+ backgroundColor: "#ffffff",
2515
+ frontColor: "#000000",
2516
+ loading: false,
2517
+ title: ""
2518
+ };
2519
+ current.__navigationBar__.title = title;
2520
+ current.__navigationBarTitle__ = title;
2521
+ return { errMsg: "setNavigationBarTitle:ok" };
2522
+ }
2523
+ setNavigationBarColor(option) {
2524
+ const current = this.requireCurrentPage("wx.setNavigationBarColor()");
2525
+ current.__navigationBar__ ??= {
2526
+ animation: null,
2527
+ backgroundColor: "#ffffff",
2528
+ frontColor: "#000000",
2529
+ loading: false,
2530
+ title: current.__navigationBarTitle__ ?? ""
2531
+ };
2532
+ if (typeof option.backgroundColor === "string") current.__navigationBar__.backgroundColor = option.backgroundColor;
2533
+ if (typeof option.frontColor === "string") current.__navigationBar__.frontColor = option.frontColor;
2534
+ current.__navigationBar__.animation = option.animation ? {
2535
+ duration: option.animation.duration,
2536
+ timingFunction: option.animation.timingFunction
2537
+ } : null;
2538
+ return { errMsg: "setNavigationBarColor:ok" };
2539
+ }
2540
+ showNavigationBarLoading() {
2541
+ const current = this.requireCurrentPage("wx.showNavigationBarLoading()");
2542
+ current.__navigationBar__ ??= {
2543
+ animation: null,
2544
+ backgroundColor: "#ffffff",
2545
+ frontColor: "#000000",
2546
+ loading: false,
2547
+ title: current.__navigationBarTitle__ ?? ""
2548
+ };
2549
+ current.__navigationBar__.loading = true;
2550
+ return { errMsg: "showNavigationBarLoading:ok" };
2551
+ }
2552
+ hideNavigationBarLoading() {
2553
+ const current = this.requireCurrentPage("wx.hideNavigationBarLoading()");
2554
+ current.__navigationBar__ ??= {
2555
+ animation: null,
2556
+ backgroundColor: "#ffffff",
2557
+ frontColor: "#000000",
2558
+ loading: false,
2559
+ title: current.__navigationBarTitle__ ?? ""
2560
+ };
2561
+ current.__navigationBar__.loading = false;
2562
+ return { errMsg: "hideNavigationBarLoading:ok" };
2563
+ }
2564
+ hideTabBar() {
2565
+ this.tabBarVisible = false;
2566
+ return { errMsg: "hideTabBar:ok" };
2567
+ }
2568
+ hideTabBarRedDot(index) {
2569
+ const item = this.requireTabBarItem(index, "wx.hideTabBarRedDot()");
2570
+ item.redDot = false;
2571
+ return { errMsg: "hideTabBarRedDot:ok" };
2572
+ }
2573
+ showTabBar() {
2574
+ this.tabBarVisible = this.tabBarRoutes.size > 0;
2575
+ return { errMsg: "showTabBar:ok" };
2576
+ }
2577
+ showTabBarRedDot(index) {
2578
+ const item = this.requireTabBarItem(index, "wx.showTabBarRedDot()");
2579
+ item.badge = null;
2580
+ item.redDot = true;
2581
+ return { errMsg: "showTabBarRedDot:ok" };
2582
+ }
2583
+ removeTabBarBadge(index) {
2584
+ const item = this.requireTabBarItem(index, "wx.removeTabBarBadge()");
2585
+ item.badge = null;
2586
+ return { errMsg: "removeTabBarBadge:ok" };
2587
+ }
2588
+ setTabBarBadge(index, text) {
2589
+ const item = this.requireTabBarItem(index, "wx.setTabBarBadge()");
2590
+ item.badge = text;
2591
+ item.redDot = false;
2592
+ return { errMsg: "setTabBarBadge:ok" };
2593
+ }
2594
+ getScopeSnapshot(scopeId) {
2595
+ const scope = this.componentScopes.get(scopeId);
2596
+ if (!scope) return null;
2597
+ const instance = this.componentCache.get(scopeId);
2598
+ if (instance) return {
2599
+ data: instance.data ?? {},
2600
+ methods: Object.keys(instance).filter((key) => typeof instance[key] === "function").sort((a, b) => a.localeCompare(b)),
2601
+ properties: instance.properties ?? {},
2602
+ scopeId,
2603
+ type: "component"
2604
+ };
2605
+ const currentPage = this.currentPageInstance;
2606
+ if (currentPage && scopeId === `page:${currentPage.route}`) return {
1310
2607
  data: currentPage.data ?? {},
1311
2608
  methods: Object.keys(currentPage).filter((key) => typeof currentPage[key] === "function").sort((a, b) => a.localeCompare(b)),
1312
2609
  properties: currentPage.options ?? {},
@@ -1321,6 +2618,10 @@ var BrowserHeadlessSession = class {
1321
2618
  type: "scope"
1322
2619
  };
1323
2620
  }
2621
+ getScopeIdForComponent(component) {
2622
+ if (!component) return null;
2623
+ return this.getComponentScopeId(component);
2624
+ }
1324
2625
  selectComponent(selector) {
1325
2626
  return this.selectComponentsWithin(null, selector)[0] ?? null;
1326
2627
  }
@@ -1350,7 +2651,7 @@ var BrowserHeadlessSession = class {
1350
2651
  const dataAttrMatch = normalizedSelector.match(DATA_ATTR_SELECTOR_RE$1);
1351
2652
  if (dataAttrMatch) {
1352
2653
  const [, key, value] = dataAttrMatch;
1353
- const datasetKey = key.replace(DATASET_KEY_RE, (_match, char) => char.toUpperCase());
2654
+ const datasetKey = key.replace(DATASET_KEY_RE$1, (_match, char) => char.toUpperCase());
1354
2655
  return scope.dataset?.[datasetKey] === value;
1355
2656
  }
1356
2657
  return scope.alias === normalizedSelector;
@@ -1374,6 +2675,40 @@ var BrowserHeadlessSession = class {
1374
2675
  current.__lastChangedKeys__ = [];
1375
2676
  return rendered;
1376
2677
  }
2678
+ callScopeMethod(scopeId, methodName, event) {
2679
+ const current = this.requireCurrentPage(`scope method "${methodName}"`);
2680
+ this.renderCurrentPage();
2681
+ if (!scopeId || scopeId === `page:${stripLeadingSlash$1(current.route)}`) {
2682
+ const method = current[methodName];
2683
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator page ${current.route}.`);
2684
+ return method.call(current, event);
2685
+ }
2686
+ const instance = this.componentCache.get(scopeId);
2687
+ if (!instance) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
2688
+ instance.__lastInteractionEvent__ = {
2689
+ currentTarget: event.currentTarget,
2690
+ mark: event.mark,
2691
+ target: event.target
2692
+ };
2693
+ const method = instance[methodName];
2694
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator component scope "${scopeId}".`);
2695
+ return method.call(instance, event);
2696
+ }
2697
+ callScopeMethodDirect(scopeId, methodName, ...args) {
2698
+ const normalizedScopeId = scopeId.trim();
2699
+ if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in browser simulator runtime.");
2700
+ const current = this.requireCurrentPage(`scope method "${methodName}"`);
2701
+ if (normalizedScopeId === `page:${stripLeadingSlash$1(current.route)}`) {
2702
+ const method = current[methodName];
2703
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator page ${current.route}.`);
2704
+ return method.apply(current, args);
2705
+ }
2706
+ const instance = this.componentCache.get(normalizedScopeId);
2707
+ if (!instance) throw new Error(`Unknown scope "${normalizedScopeId}" in browser simulator runtime.`);
2708
+ const method = instance[methodName];
2709
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator component scope "${normalizedScopeId}".`);
2710
+ return method.apply(instance, args);
2711
+ }
1377
2712
  callTapBinding(scopeId, methodName) {
1378
2713
  const scope = this.componentScopes.get(scopeId);
1379
2714
  if (!scope) throw new Error(`Unknown scope "${scopeId}" in browser simulator runtime.`);
@@ -1392,6 +2727,7 @@ var BrowserHeadlessSession = class {
1392
2727
  dataset: event.currentTarget?.dataset ?? event.dataset ?? {},
1393
2728
  id: event.currentTarget?.id ?? event.id ?? ""
1394
2729
  },
2730
+ mark: event.mark,
1395
2731
  target: {
1396
2732
  dataset: event.target?.dataset ?? event.dataset ?? {},
1397
2733
  id: event.target?.id ?? event.id ?? ""
@@ -1406,7 +2742,7 @@ var BrowserHeadlessSession = class {
1406
2742
  id: event.currentTarget?.id ?? event.id ?? ""
1407
2743
  },
1408
2744
  detail: void 0,
1409
- mark: void 0,
2745
+ mark: event.mark,
1410
2746
  target: {
1411
2747
  dataset: event.target?.dataset ?? event.dataset ?? {},
1412
2748
  id: event.target?.id ?? event.id ?? ""
@@ -1416,6 +2752,8 @@ var BrowserHeadlessSession = class {
1416
2752
  }
1417
2753
  bootstrap(launchOptions = createAppLaunchOptions$1("", {})) {
1418
2754
  if (this.appInstance) return this.appInstance;
2755
+ this.launchOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
2756
+ this.enterOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
1419
2757
  const appModulePath = join(this.project.miniprogramRootPath, "app.js");
1420
2758
  this.appDefinition = this.moduleLoader.executeAppModule(appModulePath);
1421
2759
  this.appInstance = createAppInstance(this.appDefinition);
@@ -1506,10 +2844,16 @@ var BrowserHeadlessSession = class {
1506
2844
  return nextPage;
1507
2845
  }
1508
2846
  pageScrollTo(option) {
1509
- this.requireCurrentPage("wx.pageScrollTo()").onPageScroll?.({ scrollTop: Number(option.scrollTop ?? 0) });
2847
+ const current = this.requireCurrentPage("wx.pageScrollTo()");
2848
+ current.__scrollTop__ = Number(option.scrollTop ?? 0);
2849
+ current.onPageScroll?.({ scrollTop: current.__scrollTop__ });
1510
2850
  }
1511
2851
  triggerPullDownRefresh() {
1512
2852
  const current = this.requireCurrentPage("triggerPullDownRefresh()");
2853
+ this.pullDownRefreshState = {
2854
+ ...this.pullDownRefreshState,
2855
+ active: true
2856
+ };
1513
2857
  current.onPullDownRefresh?.();
1514
2858
  return current;
1515
2859
  }
@@ -1520,6 +2864,7 @@ var BrowserHeadlessSession = class {
1520
2864
  }
1521
2865
  triggerResize(options) {
1522
2866
  const current = this.requireCurrentPage("triggerResize()");
2867
+ applyResizeToSystemInfo(this.systemInfo, options);
1523
2868
  current.onResize?.(options);
1524
2869
  this.runPageComponentLifetime(current.route, "resize", options);
1525
2870
  return current;
@@ -1529,11 +2874,43 @@ var BrowserHeadlessSession = class {
1529
2874
  current.onRouteDone?.(options);
1530
2875
  return current;
1531
2876
  }
1532
- stopPullDownRefresh() {}
2877
+ stopPullDownRefresh() {
2878
+ this.pullDownRefreshState = {
2879
+ active: false,
2880
+ stopCalls: this.pullDownRefreshState.stopCalls + 1
2881
+ };
2882
+ }
2883
+ executeSelectorQuery(requests, scope) {
2884
+ const current = this.requireCurrentPage("wx.createSelectorQuery().exec()");
2885
+ if (scope && scope !== current && !Array.from(this.componentCache.values()).includes(scope)) throw new Error("wx.createSelectorQuery().in(component) received an unknown scope in browser simulator runtime.");
2886
+ const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
2887
+ return executeSelectorQueryRequests(requests, {
2888
+ page: current,
2889
+ root: resolveSelectorQueryScopeRoot(renderBrowserPageTree({
2890
+ changedPageKeys: current.__lastChangedKeys__ ?? [],
2891
+ componentCache: this.componentCache,
2892
+ componentScopes: this.componentScopes,
2893
+ files: this.files,
2894
+ moduleLoader: this.moduleLoader,
2895
+ project: this.project,
2896
+ session: {
2897
+ selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
2898
+ selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
2899
+ selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
2900
+ }
2901
+ }, current).root, scopeId),
2902
+ windowInfo: this.getWindowInfo()
2903
+ });
2904
+ }
1533
2905
  createFreshPage(target) {
1534
2906
  const pageModulePath = join(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
2907
+ const pageConfigPath = join(this.project.miniprogramRootPath, `${target.routeRecord.route}.json`);
1535
2908
  const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
1536
- const pageInstance = createPageInstance(target.routeRecord.route, pageDefinition, target.query);
2909
+ const pageConfig = readJsonObject$2(this.files, pageConfigPath);
2910
+ const pageInstance = createPageInstance(target.routeRecord.route, pageDefinition, target.query, {
2911
+ background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
2912
+ navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
2913
+ });
1537
2914
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
1538
2915
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
1539
2916
  pageInstance.onLoad?.(target.query);
@@ -1570,6 +2947,12 @@ var BrowserHeadlessSession = class {
1570
2947
  if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in browser simulator runtime.`);
1571
2948
  return { ...item };
1572
2949
  }
2950
+ requireTabBarItem(index, action) {
2951
+ const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
2952
+ const item = this.tabBarState.get(normalizedIndex);
2953
+ if (!item) throw new Error(`Cannot call ${action} with unknown tabBar index ${index} in browser simulator runtime.`);
2954
+ return item;
2955
+ }
1573
2956
  unloadAllPages() {
1574
2957
  const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
1575
2958
  for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
@@ -1606,68 +2989,500 @@ var BrowserHeadlessSession = class {
1606
2989
  runComponentPageLifetime(instance, lifetimeName, payload);
1607
2990
  }
1608
2991
  }
1609
- };
1610
- function createBrowserHeadlessSession(options) {
1611
- return new BrowserHeadlessSession(options);
2992
+ getComponentScopeId(component) {
2993
+ for (const [scopeId, instance] of this.componentCache.entries()) if (instance === component) return scopeId;
2994
+ return null;
2995
+ }
2996
+ };
2997
+ function createBrowserHeadlessSession(options) {
2998
+ return new BrowserHeadlessSession(options);
2999
+ }
3000
+ //#endregion
3001
+ //#region src/project/loadProject.ts
3002
+ function readJsonObject$1(filePath) {
3003
+ try {
3004
+ const content = fs.readFileSync(filePath, "utf8");
3005
+ const value = JSON.parse(content);
3006
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3007
+ } catch {
3008
+ return;
3009
+ }
3010
+ }
3011
+ function resolveProjectConfigFiles(projectPath) {
3012
+ const entries = [];
3013
+ for (const fileName of ["project.config.json", "project.private.config.json"]) {
3014
+ const filePath = path.resolve(projectPath, fileName);
3015
+ const value = readJsonObject$1(filePath);
3016
+ if (!value) continue;
3017
+ entries.push({
3018
+ filePath,
3019
+ value
3020
+ });
3021
+ }
3022
+ return entries;
3023
+ }
3024
+ function resolveMiniprogramRoot(projectPath, configFiles) {
3025
+ for (const configFile of [...configFiles].reverse()) {
3026
+ const rawRoot = configFile.value.miniprogramRoot;
3027
+ if (typeof rawRoot !== "string" || !rawRoot.trim()) continue;
3028
+ return rawRoot.trim();
3029
+ }
3030
+ throw new Error(`Failed to resolve miniprogramRoot for headless runtime project: ${projectPath}. Expected project.config.json or project.private.config.json to define miniprogramRoot.`);
3031
+ }
3032
+ function ensureFileExists(filePath, label) {
3033
+ if (fs.existsSync(filePath)) return;
3034
+ throw new Error(`Missing ${label} for headless runtime project: ${normalize(filePath)}`);
3035
+ }
3036
+ function loadAppConfig(appConfigPath) {
3037
+ const appConfig = readJsonObject$1(appConfigPath);
3038
+ if (!appConfig) throw new Error(`Failed to read built app.json for headless runtime project: ${normalize(appConfigPath)}`);
3039
+ return appConfig;
3040
+ }
3041
+ function loadProject(projectPath) {
3042
+ const normalizedProjectPath = path.resolve(projectPath);
3043
+ const projectConfigFiles = resolveProjectConfigFiles(normalizedProjectPath);
3044
+ if (projectConfigFiles.length === 0) throw new Error(`Missing project config for headless runtime project: ${normalizedProjectPath}. Expected project.config.json or project.private.config.json.`);
3045
+ const miniprogramRoot = resolveMiniprogramRoot(normalizedProjectPath, projectConfigFiles);
3046
+ const miniprogramRootPath = path.resolve(normalizedProjectPath, miniprogramRoot);
3047
+ ensureFileExists(miniprogramRootPath, "miniprogramRoot directory");
3048
+ const appConfigPath = path.resolve(miniprogramRootPath, "app.json");
3049
+ ensureFileExists(appConfigPath, "built app.json");
3050
+ return createProjectDescriptor({
3051
+ appConfig: loadAppConfig(appConfigPath),
3052
+ appConfigPath,
3053
+ miniprogramRoot,
3054
+ miniprogramRootPath,
3055
+ projectPath: normalizedProjectPath,
3056
+ projectConfigFiles
3057
+ });
3058
+ }
3059
+ //#endregion
3060
+ //#region src/runtime/render.ts
3061
+ const LEADING_SLASH_RE$2 = /^\/+/;
3062
+ const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
3063
+ const EVENT_BINDING_ATTRS = [
3064
+ "bindtap",
3065
+ "bind:tap",
3066
+ "catchtap",
3067
+ "catch:tap"
3068
+ ];
3069
+ const COMPONENT_EVENT_PREFIXES = [
3070
+ "bind:",
3071
+ "bind",
3072
+ "catch:",
3073
+ "catch"
3074
+ ];
3075
+ const STRUCTURAL_ATTRS = [
3076
+ "wx:if",
3077
+ "wx:elif",
3078
+ "wx:else",
3079
+ "wx:for",
3080
+ "wx:for-item",
3081
+ "wx:for-index",
3082
+ "wx:key"
3083
+ ];
3084
+ const WX_ELSE_ATTRS = new Set(["wx:elif", "wx:else"]);
3085
+ const DATASET_NAME_RE = /-([a-z])/g;
3086
+ const BRACKET_INDEX_RE = /\[(\d+)\]/g;
3087
+ const CLASS_SPLIT_RE = /\s+/;
3088
+ const JS_FILE_RE = /\.js$/;
3089
+ function isMustacheOnly(value) {
3090
+ const trimmed = value.trim();
3091
+ return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
3092
+ }
3093
+ function toDatasetKey(attributeName) {
3094
+ return attributeName.slice(5).replace(DATASET_NAME_RE, (_match, char) => char.toUpperCase());
3095
+ }
3096
+ function collectDataset(node) {
3097
+ const dataset = {};
3098
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
3099
+ if (!key.startsWith("data-") || key === "data-sim-scope" || key === "data-sim-tap" || key === "data-sim-component") continue;
3100
+ dataset[toDatasetKey(key)] = String(value);
3101
+ }
3102
+ return dataset;
3103
+ }
3104
+ function escapeText(text) {
3105
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
3106
+ }
3107
+ function escapeAttribute(value) {
3108
+ return escapeText(value).replaceAll("\"", "&quot;");
3109
+ }
3110
+ function cloneNode(node) {
3111
+ return {
3112
+ ...node,
3113
+ attribs: node.attribs ? { ...node.attribs } : void 0,
3114
+ children: node.children?.map((child) => cloneNode(child))
3115
+ };
3116
+ }
3117
+ function parseExpressionSegments(expression) {
3118
+ return expression.replace(BRACKET_INDEX_RE, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
3119
+ }
3120
+ function unwrapMustacheExpression(expression) {
3121
+ const normalized = expression.trim();
3122
+ if (isMustacheOnly(normalized)) return normalized.slice(2, -2).trim();
3123
+ return normalized;
3124
+ }
3125
+ function resolveLiteralValue(expression) {
3126
+ if (expression === "true") return true;
3127
+ if (expression === "false") return false;
3128
+ if (expression === "null") return null;
3129
+ if (expression === "undefined") return;
3130
+ if (expression.startsWith("\"") && expression.endsWith("\"") || expression.startsWith("'") && expression.endsWith("'")) return expression.slice(1, -1);
3131
+ const numericValue = Number(expression);
3132
+ if (!Number.isNaN(numericValue) && expression !== "") return numericValue;
3133
+ }
3134
+ function resolveValueByExpression(source, expression) {
3135
+ const normalized = unwrapMustacheExpression(expression);
3136
+ if (!normalized) return;
3137
+ if (normalized.startsWith("!")) return !resolveValueByExpression(source, normalized.slice(1));
3138
+ const literalValue = resolveLiteralValue(normalized);
3139
+ if (literalValue !== void 0 || normalized === "undefined") return literalValue;
3140
+ const segments = parseExpressionSegments(normalized);
3141
+ let current = source;
3142
+ for (const segment of segments) current = current?.[segment];
3143
+ return current;
3144
+ }
3145
+ function resolveValueByPath(source, expression) {
3146
+ return resolveValueByExpression(source, expression) ?? "";
3147
+ }
3148
+ function resolveRawValueByPath(source, expression) {
3149
+ return resolveValueByExpression(source, expression);
3150
+ }
3151
+ function interpolateTemplate(input, data) {
3152
+ return input.replace(TEMPLATE_INTERPOLATION_RE, (_match, expression) => {
3153
+ const value = resolveValueByPath(data, expression);
3154
+ return typeof value === "string" ? value : String(value);
3155
+ });
3156
+ }
3157
+ function readTemplateSource(filePath) {
3158
+ return fs.readFileSync(filePath, "utf8");
3159
+ }
3160
+ function parseTemplateDocument(templateSource) {
3161
+ return parseDocument(`<page>${templateSource}</page>`, {
3162
+ xmlMode: false,
3163
+ decodeEntities: false,
3164
+ recognizeSelfClosing: true
3165
+ });
3166
+ }
3167
+ function serializeDomNode(node) {
3168
+ if (node.type === "text") return escapeText(node.data ?? "");
3169
+ if (node.type === "root") return (node.children ?? []).map(serializeDomNode).join("");
3170
+ const tagName = node.name ?? "";
3171
+ if (!tagName) return (node.children ?? []).map(serializeDomNode).join("");
3172
+ return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode).join("")}</${tagName}>`;
3173
+ }
3174
+ function isTagNode(node) {
3175
+ return node.type === "tag" && typeof node.name === "string";
3176
+ }
3177
+ function isIgnorableTextNode(node) {
3178
+ return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
3179
+ }
3180
+ function resolveAttributeValue(value, scope) {
3181
+ if (isMustacheOnly(value)) {
3182
+ const expression = value.trim().slice(2, -2);
3183
+ return resolveValueByPath(scope.data, expression);
3184
+ }
3185
+ return interpolateTemplate(value, scope.data);
3186
+ }
3187
+ function resolveComponentAttributeValue(value, scope) {
3188
+ if (isMustacheOnly(value)) {
3189
+ const expression = value.trim().slice(2, -2);
3190
+ return resolveRawValueByPath(scope.data, expression);
3191
+ }
3192
+ return interpolateTemplate(value, scope.data);
3193
+ }
3194
+ function resolveUsingComponents(ownerJsonPath, ownerFilePath) {
3195
+ try {
3196
+ const usingComponents = JSON.parse(fs.readFileSync(ownerJsonPath, "utf8")).usingComponents;
3197
+ if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
3198
+ const resolved = /* @__PURE__ */ new Map();
3199
+ for (const [alias, rawPath] of Object.entries(usingComponents)) {
3200
+ if (typeof rawPath !== "string") continue;
3201
+ const basePath = rawPath.startsWith("/") ? rawPath.replace(LEADING_SLASH_RE$2, "") : path.posix.normalize(path.posix.join(path.posix.dirname(ownerFilePath), rawPath));
3202
+ resolved.set(alias, basePath.replace(LEADING_SLASH_RE$2, ""));
3203
+ }
3204
+ return resolved;
3205
+ } catch {
3206
+ return /* @__PURE__ */ new Map();
3207
+ }
3208
+ }
3209
+ function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias) {
3210
+ const componentBasePath = resolveUsingComponents(ownerJsonPath, ownerFilePath).get(alias);
3211
+ if (!componentBasePath) return null;
3212
+ const filePath = `${componentBasePath}.js`;
3213
+ const templatePath = `${componentBasePath}.wxml`;
3214
+ const absoluteFilePath = path.resolve(context.project.miniprogramRootPath, filePath);
3215
+ const absoluteTemplatePath = path.resolve(context.project.miniprogramRootPath, templatePath);
3216
+ return {
3217
+ definition: context.moduleLoader.executeComponentModule(absoluteFilePath, componentBasePath),
3218
+ filePath,
3219
+ templatePath,
3220
+ absoluteTemplatePath
3221
+ };
3222
+ }
3223
+ function collectComponentEventBindings(hostNode) {
3224
+ const eventBindings = /* @__PURE__ */ new Map();
3225
+ for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
3226
+ const matchedPrefix = COMPONENT_EVENT_PREFIXES.find((prefix) => key.startsWith(prefix));
3227
+ if (!matchedPrefix) continue;
3228
+ const eventName = key.slice(matchedPrefix.length);
3229
+ if (!eventName) continue;
3230
+ eventBindings.set(eventName, {
3231
+ method: value,
3232
+ stopAfter: matchedPrefix.startsWith("catch")
3233
+ });
3234
+ }
3235
+ return eventBindings;
3236
+ }
3237
+ function buildComponentTrigger(componentScopeId, context, hostNode) {
3238
+ const hostDataset = collectDataset(hostNode);
3239
+ const hostId = hostNode.attribs?.id ?? "";
3240
+ return (instance, eventName, detail, triggerOptions) => {
3241
+ const interactionTarget = instance.__lastInteractionEvent__?.target;
3242
+ const interactionCurrentTarget = instance.__lastInteractionEvent__?.currentTarget;
3243
+ const interactionMark = instance.__lastInteractionEvent__?.mark;
3244
+ const target = {
3245
+ dataset: interactionTarget?.dataset ?? hostDataset,
3246
+ id: interactionTarget?.id ?? hostId
3247
+ };
3248
+ let currentScopeId = componentScopeId;
3249
+ while (currentScopeId) {
3250
+ const currentScope = context.componentScopes.get(currentScopeId);
3251
+ const binding = currentScope?.eventBindings?.get(eventName);
3252
+ const listenerScope = currentScope?.listenerScopeId ? context.componentScopes.get(currentScope.listenerScopeId) : null;
3253
+ const handler = binding && listenerScope ? listenerScope.getMethod(binding.method) : void 0;
3254
+ if (handler) handler({
3255
+ bubbles: triggerOptions?.bubbles ?? false,
3256
+ capturePhase: false,
3257
+ composed: triggerOptions?.composed ?? false,
3258
+ currentTarget: {
3259
+ dataset: currentScope?.dataset ?? interactionCurrentTarget?.dataset ?? hostDataset,
3260
+ id: currentScope?.hostId ?? interactionCurrentTarget?.id ?? hostId
3261
+ },
3262
+ detail,
3263
+ mark: interactionMark,
3264
+ target,
3265
+ type: eventName
3266
+ });
3267
+ if (binding?.stopAfter) break;
3268
+ if (!triggerOptions?.bubbles || !triggerOptions?.composed) break;
3269
+ currentScopeId = currentScope?.ownerScopeId;
3270
+ }
3271
+ };
3272
+ }
3273
+ function applyNodeBindings(node, scope) {
3274
+ if (!isTagNode(node)) {
3275
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate(node.data, scope.data);
3276
+ return;
3277
+ }
3278
+ node.attribs ??= {};
3279
+ node.attribs["data-sim-scope"] = scope.getScopeId();
3280
+ for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
3281
+ for (const [key, value] of Object.entries({ ...node.attribs })) {
3282
+ if (EVENT_BINDING_ATTRS.includes(key)) {
3283
+ node.attribs["data-sim-tap"] = value;
3284
+ continue;
3285
+ }
3286
+ node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
3287
+ }
3288
+ }
3289
+ function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
3290
+ const changedRootKeys = [];
3291
+ const previousProperties = {};
3292
+ for (const [key, value] of Object.entries(nextProperties)) {
3293
+ const nextValue = normalizeComponentPropertyValue(definition, key, value);
3294
+ const bindingExpression = bindingExpressions[key];
3295
+ const bindingAffected = !!bindingExpression && changedPageKeys.some((changedKey) => {
3296
+ return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
3297
+ });
3298
+ const previousSnapshot = instance.__propertySnapshots?.[key];
3299
+ const deepChanged = bindingAffected && JSON.stringify(previousSnapshot) !== JSON.stringify(nextValue);
3300
+ if (instance.properties[key] !== nextValue || deepChanged) {
3301
+ previousProperties[key] = instance.properties[key];
3302
+ instance.properties[key] = nextValue;
3303
+ changedRootKeys.push(key);
3304
+ }
3305
+ instance.__propertySnapshots ??= {};
3306
+ instance.__propertySnapshots[key] = cloneValue(nextValue);
3307
+ }
3308
+ if (changedRootKeys.length === 0) return;
3309
+ runComponentObservers(definition, instance, changedRootKeys, previousProperties);
3310
+ }
3311
+ function createMergedScopeData(pageData, componentProperties, componentData) {
3312
+ return {
3313
+ ...pageData,
3314
+ ...componentProperties,
3315
+ ...componentData
3316
+ };
3317
+ }
3318
+ function isTruthy(value) {
3319
+ return Boolean(value);
3320
+ }
3321
+ function createLoopScope(scope, itemName, indexName, item, index) {
3322
+ return {
3323
+ ...scope,
3324
+ data: {
3325
+ ...scope.data,
3326
+ [indexName]: index,
3327
+ [itemName]: item
3328
+ }
3329
+ };
3330
+ }
3331
+ function evaluateConditionalBranch(node, scope) {
3332
+ const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
3333
+ if (condition == null) return true;
3334
+ return isTruthy(resolveRawValueByPath(scope.data, condition));
3335
+ }
3336
+ function expandNodeByFor(node, scope) {
3337
+ const forExpression = node.attribs?.["wx:for"];
3338
+ if (!forExpression) return [{
3339
+ node,
3340
+ scope,
3341
+ instanceSuffix: ""
3342
+ }];
3343
+ const list = resolveRawValueByPath(scope.data, forExpression);
3344
+ const items = Array.isArray(list) ? list : [];
3345
+ const itemName = node.attribs?.["wx:for-item"]?.trim() || "item";
3346
+ const indexName = node.attribs?.["wx:for-index"]?.trim() || "index";
3347
+ return items.map((item, index) => ({
3348
+ node: cloneNode(node),
3349
+ scope: createLoopScope(scope, itemName, indexName, item, index),
3350
+ instanceSuffix: `:for-${index}`
3351
+ }));
3352
+ }
3353
+ function renderNodeVariants(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
3354
+ return expandNodeByFor(node, scope).map(({ node: expandedNode, scope: expandedScope, instanceSuffix }) => renderNodeTree(expandedNode, expandedScope, context, ownerJsonPath, ownerFilePath, `${instancePath}${instanceSuffix}`, seenComponentScopes));
3355
+ }
3356
+ function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
3357
+ const renderedChildren = [];
3358
+ for (let index = 0; index < children.length; index += 1) {
3359
+ const child = children[index];
3360
+ if (!isTagNode(child)) {
3361
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
3362
+ continue;
3363
+ }
3364
+ const hasConditional = child.attribs?.["wx:if"] != null;
3365
+ const isElseBranch = child.attribs?.["wx:elif"] != null || child.attribs?.["wx:else"] != null;
3366
+ if (hasConditional) {
3367
+ let branchMatched = false;
3368
+ let cursor = index;
3369
+ while (cursor < children.length) {
3370
+ const branch = children[cursor];
3371
+ if (cursor !== index && isIgnorableTextNode(branch)) {
3372
+ cursor += 1;
3373
+ continue;
3374
+ }
3375
+ if (!isTagNode(branch)) break;
3376
+ if (cursor !== index && !WX_ELSE_ATTRS.has(Object.keys(branch.attribs ?? {}).find((key) => key.startsWith("wx:")) ?? "")) break;
3377
+ if (branch.attribs?.["wx:else"] != null ? !branchMatched : !branchMatched && evaluateConditionalBranch(branch, scope)) {
3378
+ renderedChildren.push(...renderNodeVariants(branch, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${cursor}`, seenComponentScopes));
3379
+ branchMatched = true;
3380
+ }
3381
+ let nextBranchIndex = cursor + 1;
3382
+ while (nextBranchIndex < children.length && isIgnorableTextNode(children[nextBranchIndex])) nextBranchIndex += 1;
3383
+ const nextBranch = children[nextBranchIndex];
3384
+ if (!(!!nextBranch && isTagNode(nextBranch) && (nextBranch.attribs?.["wx:elif"] != null || nextBranch.attribs?.["wx:else"] != null))) break;
3385
+ cursor = nextBranchIndex;
3386
+ }
3387
+ index = cursor;
3388
+ continue;
3389
+ }
3390
+ if (isElseBranch) continue;
3391
+ renderedChildren.push(...renderNodeVariants(child, scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/node-${index}`, seenComponentScopes));
3392
+ }
3393
+ return renderedChildren;
1612
3394
  }
1613
- //#endregion
1614
- //#region src/project/loadProject.ts
1615
- function readJsonObject(filePath) {
1616
- try {
1617
- const content = fs.readFileSync(filePath, "utf8");
1618
- const value = JSON.parse(content);
1619
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1620
- } catch {
1621
- return;
3395
+ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
3396
+ const clonedNode = cloneNode(node);
3397
+ if (!isTagNode(clonedNode)) {
3398
+ applyNodeBindings(clonedNode, scope);
3399
+ return clonedNode;
1622
3400
  }
1623
- }
1624
- function resolveProjectConfigFiles(projectPath) {
1625
- const entries = [];
1626
- for (const fileName of ["project.config.json", "project.private.config.json"]) {
1627
- const filePath = path.resolve(projectPath, fileName);
1628
- const value = readJsonObject(filePath);
1629
- if (!value) continue;
1630
- entries.push({
1631
- filePath,
1632
- value
1633
- });
3401
+ const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name);
3402
+ if (componentEntry) {
3403
+ const componentScopeId = `${instancePath}/${clonedNode.name}`;
3404
+ const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
3405
+ const nextProperties = {};
3406
+ const bindingExpressions = {};
3407
+ for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
3408
+ if (key.startsWith("bind")) continue;
3409
+ if (isMustacheOnly(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
3410
+ nextProperties[key] = resolveComponentAttributeValue(String(value), scope);
3411
+ }
3412
+ let componentInstance = context.componentCache.get(componentScopeId);
3413
+ if (!componentInstance) {
3414
+ componentInstance = createComponentInstance({
3415
+ definition: componentEntry.definition,
3416
+ properties: nextProperties,
3417
+ triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
3418
+ });
3419
+ componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
3420
+ componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
3421
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
3422
+ runComponentLifecycle(componentInstance, "created");
3423
+ runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
3424
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
3425
+ runComponentLifecycle(componentInstance, "attached");
3426
+ context.componentCache.set(componentScopeId, componentInstance);
3427
+ } else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
3428
+ seenComponentScopes.add(componentScopeId);
3429
+ const componentScope = {
3430
+ alias: clonedNode.name,
3431
+ classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
3432
+ data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
3433
+ dataset: collectDataset(clonedNode),
3434
+ eventBindings: collectComponentEventBindings(clonedNode),
3435
+ getMethod: (methodName) => {
3436
+ const method = componentInstance?.[methodName];
3437
+ return typeof method === "function" ? method : void 0;
3438
+ },
3439
+ getScopeId: () => componentScopeId,
3440
+ hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
3441
+ id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
3442
+ listenerScopeId: scope.getScopeId(),
3443
+ ownerScopeId
3444
+ };
3445
+ context.componentScopes.set(componentScopeId, componentScope);
3446
+ const componentDocument = parseTemplateDocument(readTemplateSource(componentEntry.absoluteTemplatePath));
3447
+ const renderedComponentRoot = renderNodeTree((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, seenComponentScopes);
3448
+ if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
3449
+ if (!componentInstance.__ready__) {
3450
+ runComponentLifecycle(componentInstance, "ready");
3451
+ componentInstance.__ready__ = true;
3452
+ componentInstance.__definition__?.pageLifetimes?.show?.call(componentInstance);
3453
+ }
3454
+ return renderedComponentRoot;
1634
3455
  }
1635
- return entries;
3456
+ applyNodeBindings(clonedNode, scope);
3457
+ clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
3458
+ return clonedNode;
1636
3459
  }
1637
- function resolveMiniprogramRoot(projectPath, configFiles) {
1638
- for (const configFile of [...configFiles].reverse()) {
1639
- const rawRoot = configFile.value.miniprogramRoot;
1640
- if (typeof rawRoot !== "string" || !rawRoot.trim()) continue;
1641
- return rawRoot.trim();
3460
+ function renderRuntimePageTree(context, page) {
3461
+ const route = page.route.replace(LEADING_SLASH_RE$2, "");
3462
+ const document = parseTemplateDocument(readTemplateSource(path.resolve(context.project.miniprogramRootPath, `${route}.wxml`)));
3463
+ const pageScopeId = `page:${route}`;
3464
+ const pageScope = {
3465
+ data: page.data,
3466
+ getMethod: (methodName) => {
3467
+ const method = page[methodName];
3468
+ return typeof method === "function" ? method : void 0;
3469
+ },
3470
+ getScopeId: () => pageScopeId,
3471
+ id: "page-root"
3472
+ };
3473
+ context.componentScopes.clear();
3474
+ context.componentScopes.set(pageScopeId, pageScope);
3475
+ const seenComponentScopes = /* @__PURE__ */ new Set();
3476
+ const renderedRoot = renderNodeTree((document.children ?? [])[0] ?? document, pageScope, context, path.resolve(context.project.miniprogramRootPath, `${route}.json`), `${route}.js`, pageScopeId, seenComponentScopes);
3477
+ for (const [scopeId, instance] of [...context.componentCache.entries()]) if (!seenComponentScopes.has(scopeId)) {
3478
+ runComponentLifecycle(instance, "detached");
3479
+ context.componentCache.delete(scopeId);
3480
+ context.componentScopes.delete(scopeId);
1642
3481
  }
1643
- throw new Error(`Failed to resolve miniprogramRoot for headless runtime project: ${projectPath}. Expected project.config.json or project.private.config.json to define miniprogramRoot.`);
1644
- }
1645
- function ensureFileExists(filePath, label) {
1646
- if (fs.existsSync(filePath)) return;
1647
- throw new Error(`Missing ${label} for headless runtime project: ${normalize(filePath)}`);
1648
- }
1649
- function loadAppConfig(appConfigPath) {
1650
- const appConfig = readJsonObject(appConfigPath);
1651
- if (!appConfig) throw new Error(`Failed to read built app.json for headless runtime project: ${normalize(appConfigPath)}`);
1652
- return appConfig;
1653
- }
1654
- function loadProject(projectPath) {
1655
- const normalizedProjectPath = path.resolve(projectPath);
1656
- const projectConfigFiles = resolveProjectConfigFiles(normalizedProjectPath);
1657
- if (projectConfigFiles.length === 0) throw new Error(`Missing project config for headless runtime project: ${normalizedProjectPath}. Expected project.config.json or project.private.config.json.`);
1658
- const miniprogramRoot = resolveMiniprogramRoot(normalizedProjectPath, projectConfigFiles);
1659
- const miniprogramRootPath = path.resolve(normalizedProjectPath, miniprogramRoot);
1660
- ensureFileExists(miniprogramRootPath, "miniprogramRoot directory");
1661
- const appConfigPath = path.resolve(miniprogramRootPath, "app.json");
1662
- ensureFileExists(appConfigPath, "built app.json");
1663
- return createProjectDescriptor({
1664
- appConfig: loadAppConfig(appConfigPath),
1665
- appConfigPath,
1666
- miniprogramRoot,
1667
- miniprogramRootPath,
1668
- projectPath: normalizedProjectPath,
1669
- projectConfigFiles
1670
- });
3482
+ return {
3483
+ root: renderedRoot,
3484
+ wxml: serializeDomNode(renderedRoot)
3485
+ };
1671
3486
  }
1672
3487
  //#endregion
1673
3488
  //#region src/runtime/moduleLoader.ts
@@ -1758,6 +3573,15 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
1758
3573
  const definition = registries.pages.get(route);
1759
3574
  if (!definition) throw new Error(`Page() was not registered for route "${route}" while executing ${normalize(filePath)}.`);
1760
3575
  return definition;
3576
+ },
3577
+ executeComponentModule(filePath, id) {
3578
+ executeModule(filePath, {
3579
+ kind: "component",
3580
+ route: id
3581
+ });
3582
+ const definition = registries.components.get(id);
3583
+ if (!definition) throw new Error(`Component() was not registered for id "${id}" while executing ${normalize(filePath)}.`);
3584
+ return definition;
1761
3585
  }
1762
3586
  };
1763
3587
  }
@@ -1765,6 +3589,8 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
1765
3589
  //#region src/runtime/session.ts
1766
3590
  const LEADING_SLASH_RE$1 = /^\/+/;
1767
3591
  const PAGE_STACK_LIMIT = 10;
3592
+ const DATA_ATTR_SELECTOR_RE = /^\[data-([^=\]]+)="([^"]*)"\]$/;
3593
+ const DATASET_KEY_RE = /-([a-z])/g;
1768
3594
  function stripLeadingSlash(route) {
1769
3595
  return route.replace(LEADING_SLASH_RE$1, "");
1770
3596
  }
@@ -1795,6 +3621,14 @@ function createAppLaunchOptions(pathname, query) {
1795
3621
  scene: 1001
1796
3622
  };
1797
3623
  }
3624
+ function readJsonObject(filePath) {
3625
+ try {
3626
+ const value = JSON.parse(fs.readFileSync(filePath, "utf8"));
3627
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3628
+ } catch {
3629
+ return;
3630
+ }
3631
+ }
1798
3632
  function resolveNavigationPath(targetPath, baseRoute) {
1799
3633
  if (!targetPath) throw new Error("Navigation url must include a pathname in headless runtime.");
1800
3634
  if (targetPath.startsWith("/")) return path.posix.normalize(targetPath).replace(LEADING_SLASH_RE$1, "");
@@ -1809,10 +3643,21 @@ var HeadlessSession = class {
1809
3643
  registries;
1810
3644
  currentPageInstance = null;
1811
3645
  pages = [];
3646
+ componentCache = /* @__PURE__ */ new Map();
3647
+ componentScopes = /* @__PURE__ */ new Map();
1812
3648
  tabBarRoutes;
1813
3649
  tabPages = /* @__PURE__ */ new Map();
1814
3650
  tabBarItems = /* @__PURE__ */ new Map();
3651
+ tabBarState = /* @__PURE__ */ new Map();
3652
+ tabBarVisible = false;
3653
+ systemInfo = createDefaultSystemInfo();
3654
+ enterOptions = createAppLaunchOptions("", {});
3655
+ launchOptions = createAppLaunchOptions("", {});
1815
3656
  wxState = createHeadlessWxState();
3657
+ pullDownRefreshState = {
3658
+ active: false,
3659
+ stopCalls: 0
3660
+ };
1816
3661
  constructor(options) {
1817
3662
  this.project = loadProject(options.projectPath);
1818
3663
  this.registries = createHostRegistries();
@@ -1828,22 +3673,75 @@ var HeadlessSession = class {
1828
3673
  pagePath,
1829
3674
  text: typeof item.text === "string" ? item.text : void 0
1830
3675
  });
3676
+ this.tabBarState.set(index, {
3677
+ badge: null,
3678
+ index,
3679
+ pagePath,
3680
+ redDot: false,
3681
+ text: typeof item.text === "string" ? item.text : void 0
3682
+ });
1831
3683
  });
3684
+ this.tabBarVisible = this.tabBarRoutes.size > 0;
1832
3685
  this.moduleLoader = createModuleLoader(this.registries, () => this.pages.slice(), () => this.getApp(), {
3686
+ executeSelectorQuery: (requests, scope) => this.executeSelectorQuery(requests, scope),
3687
+ getEnterOptionsSync: () => ({
3688
+ ...this.enterOptions,
3689
+ query: { ...this.enterOptions.query },
3690
+ referrerInfo: {
3691
+ ...this.enterOptions.referrerInfo,
3692
+ extraData: { ...this.enterOptions.referrerInfo.extraData }
3693
+ }
3694
+ }),
3695
+ getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
3696
+ getLaunchOptionsSync: () => ({
3697
+ ...this.launchOptions,
3698
+ query: { ...this.launchOptions.query },
3699
+ referrerInfo: {
3700
+ ...this.launchOptions.referrerInfo,
3701
+ extraData: { ...this.launchOptions.referrerInfo.extraData }
3702
+ }
3703
+ }),
3704
+ getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
3705
+ getNetworkType: () => this.wxState.getNetworkType(),
1833
3706
  navigateBack: (option) => this.navigateBack(option?.delta),
1834
3707
  navigateTo: (option) => this.navigateTo(option.url),
1835
3708
  pageScrollTo: (option) => this.pageScrollTo(option),
1836
3709
  clearStorageSync: () => this.wxState.clearStorageSync(),
3710
+ getStorageInfoSync: () => this.wxState.getStorageInfoSync(),
1837
3711
  getStorageSync: (key) => this.wxState.getStorageSync(key),
3712
+ getSystemInfoSync: () => ({ ...this.systemInfo }),
3713
+ getWindowInfoSync: () => deriveWindowInfo(this.systemInfo),
3714
+ hideLoading: () => this.wxState.hideLoading(),
1838
3715
  hideToast: () => this.wxState.hideToast(),
1839
3716
  reLaunch: (option) => this.reLaunch(option.url),
1840
3717
  redirectTo: (option) => this.redirectTo(option.url),
3718
+ nextTick: (callback) => queueMicrotask(() => callback?.()),
3719
+ offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
3720
+ onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
1841
3721
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
1842
3722
  request: (option) => this.wxState.request(option),
3723
+ setBackgroundColor: (option) => this.setBackgroundColor(option),
3724
+ setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
1843
3725
  setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
3726
+ setNavigationBarColor: (option) => this.setNavigationBarColor(option),
3727
+ setNavigationBarTitle: (option) => this.setNavigationBarTitle(option.title),
3728
+ hideShareMenu: () => this.wxState.hideShareMenu(),
3729
+ hideNavigationBarLoading: () => this.hideNavigationBarLoading(),
3730
+ hideTabBar: () => this.hideTabBar(),
3731
+ hideTabBarRedDot: (option) => this.hideTabBarRedDot(option.index),
3732
+ showShareMenu: (option) => this.wxState.showShareMenu(option),
3733
+ showNavigationBarLoading: () => this.showNavigationBarLoading(),
3734
+ showTabBar: () => this.showTabBar(),
3735
+ showTabBarRedDot: (option) => this.showTabBarRedDot(option.index),
3736
+ showActionSheet: (option) => this.wxState.showActionSheet(option),
3737
+ showLoading: (option) => this.wxState.showLoading(option),
3738
+ showModal: (option) => this.wxState.showModal(option),
1844
3739
  showToast: (option) => this.wxState.showToast(option),
1845
3740
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
1846
- switchTab: (option) => this.switchTab(option.url)
3741
+ switchTab: (option) => this.switchTab(option.url),
3742
+ removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
3743
+ setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
3744
+ updateShareMenu: (option) => this.wxState.updateShareMenu(option)
1847
3745
  });
1848
3746
  }
1849
3747
  getApp() {
@@ -1852,20 +3750,321 @@ var HeadlessSession = class {
1852
3750
  getCurrentPages() {
1853
3751
  return this.pages.slice();
1854
3752
  }
3753
+ getCurrentPageNavigationBarTitle() {
3754
+ return this.currentPageInstance?.__navigationBarTitle__ ?? null;
3755
+ }
3756
+ getCurrentPageNavigationBar() {
3757
+ const snapshot = this.currentPageInstance?.__navigationBar__;
3758
+ return snapshot ? cloneNavigationBarSnapshot(snapshot) : null;
3759
+ }
3760
+ getCurrentPageBackground() {
3761
+ const snapshot = this.currentPageInstance?.__background__;
3762
+ return snapshot ? cloneBackgroundSnapshot(snapshot) : null;
3763
+ }
3764
+ getActionSheetLogs() {
3765
+ return this.wxState.getActionSheetLogs();
3766
+ }
1855
3767
  getRequestLogs() {
1856
3768
  return this.wxState.getRequestLogs();
1857
3769
  }
1858
- getStorageSnapshot() {
1859
- return this.wxState.getStorageSnapshot();
3770
+ renderCurrentPage() {
3771
+ const current = this.requireCurrentPage("renderCurrentPage()");
3772
+ return renderRuntimePageTree({
3773
+ changedPageKeys: current.__lastChangedKeys__ ?? [],
3774
+ componentCache: this.componentCache,
3775
+ componentScopes: this.componentScopes,
3776
+ moduleLoader: this.moduleLoader,
3777
+ project: this.project,
3778
+ session: {
3779
+ selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
3780
+ selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
3781
+ selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
3782
+ }
3783
+ }, current);
3784
+ }
3785
+ getScopeSnapshot(scopeId) {
3786
+ const scope = this.componentScopes.get(scopeId);
3787
+ if (!scope) return null;
3788
+ const instance = this.componentCache.get(scopeId);
3789
+ if (instance) return {
3790
+ data: instance.data ?? {},
3791
+ methods: Object.keys(instance).filter((key) => typeof instance[key] === "function").sort((a, b) => a.localeCompare(b)),
3792
+ properties: instance.properties ?? {},
3793
+ scopeId,
3794
+ type: "component"
3795
+ };
3796
+ const currentPage = this.currentPageInstance;
3797
+ if (currentPage && scopeId === `page:${currentPage.route}`) return {
3798
+ data: currentPage.data ?? {},
3799
+ methods: Object.keys(currentPage).filter((key) => typeof currentPage[key] === "function").sort((a, b) => a.localeCompare(b)),
3800
+ properties: currentPage.options ?? {},
3801
+ scopeId,
3802
+ type: "page"
3803
+ };
3804
+ return {
3805
+ data: scope.data ?? {},
3806
+ methods: [],
3807
+ properties: {},
3808
+ scopeId,
3809
+ type: "scope"
3810
+ };
3811
+ }
3812
+ getScopeIdForComponent(component) {
3813
+ if (!component) return null;
3814
+ return this.getComponentScopeId(component);
3815
+ }
3816
+ callScopeMethod(scopeId, methodName, event) {
3817
+ const current = this.requireCurrentPage(`scope method "${methodName}"`);
3818
+ this.renderCurrentPage();
3819
+ if (!scopeId || scopeId === `page:${stripLeadingSlash(current.route)}`) {
3820
+ const method = current[methodName];
3821
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${current.route}.`);
3822
+ return method.call(current, event);
3823
+ }
3824
+ const instance = this.componentCache.get(scopeId);
3825
+ if (!instance) throw new Error(`Unknown scope "${scopeId}" in headless runtime.`);
3826
+ instance.__lastInteractionEvent__ = {
3827
+ currentTarget: event.currentTarget,
3828
+ mark: event.mark,
3829
+ target: event.target
3830
+ };
3831
+ const method = instance[methodName];
3832
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless component scope "${scopeId}".`);
3833
+ return method.call(instance, event);
3834
+ }
3835
+ callScopeMethodDirect(scopeId, methodName, ...args) {
3836
+ const normalizedScopeId = scopeId.trim();
3837
+ if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in headless runtime.");
3838
+ const current = this.requireCurrentPage(`scope method "${methodName}"`);
3839
+ if (normalizedScopeId === `page:${stripLeadingSlash(current.route)}`) {
3840
+ const method = current[methodName];
3841
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${current.route}.`);
3842
+ return method.apply(current, args);
3843
+ }
3844
+ const instance = this.componentCache.get(normalizedScopeId);
3845
+ if (!instance) throw new Error(`Unknown scope "${normalizedScopeId}" in headless runtime.`);
3846
+ const method = instance[methodName];
3847
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless component scope "${normalizedScopeId}".`);
3848
+ return method.apply(instance, args);
3849
+ }
3850
+ getStorageSnapshot() {
3851
+ return this.wxState.getStorageSnapshot();
3852
+ }
3853
+ getShareMenu() {
3854
+ return this.wxState.getShareMenu();
3855
+ }
3856
+ selectComponent(selector) {
3857
+ this.renderCurrentPage();
3858
+ return this.selectComponentsWithin(null, selector)[0] ?? null;
3859
+ }
3860
+ selectAllComponents(selector) {
3861
+ this.renderCurrentPage();
3862
+ return this.selectComponentsWithin(null, selector);
3863
+ }
3864
+ selectComponentWithin(scopeId, selector) {
3865
+ this.renderCurrentPage();
3866
+ return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
3867
+ }
3868
+ selectAllComponentsWithin(scopeId, selector) {
3869
+ this.renderCurrentPage();
3870
+ return this.selectComponentsWithin(scopeId, selector);
3871
+ }
3872
+ selectOwnerComponent(scopeId) {
3873
+ const scope = this.componentScopes.get(scopeId);
3874
+ if (!scope?.ownerScopeId) return null;
3875
+ return this.componentCache.get(scope.ownerScopeId) ?? null;
3876
+ }
3877
+ getTabBar() {
3878
+ return { visible: this.tabBarVisible };
3879
+ }
3880
+ getTabBarSnapshot() {
3881
+ return {
3882
+ items: Array.from(this.tabBarState.values(), (item) => ({
3883
+ badge: item.badge,
3884
+ index: item.index,
3885
+ pagePath: item.pagePath,
3886
+ redDot: item.redDot,
3887
+ text: item.text
3888
+ })),
3889
+ visible: this.tabBarVisible
3890
+ };
3891
+ }
3892
+ getStorageInfo() {
3893
+ return this.wxState.getStorageInfoSync();
3894
+ }
3895
+ getPullDownRefreshState() {
3896
+ return { ...this.pullDownRefreshState };
3897
+ }
3898
+ getSystemInfo() {
3899
+ return { ...this.systemInfo };
3900
+ }
3901
+ getWindowInfo() {
3902
+ return deriveWindowInfo(this.systemInfo);
3903
+ }
3904
+ getAppBaseInfo() {
3905
+ return deriveAppBaseInfo(this.systemInfo);
3906
+ }
3907
+ getLaunchOptions() {
3908
+ return {
3909
+ ...this.launchOptions,
3910
+ query: { ...this.launchOptions.query },
3911
+ referrerInfo: {
3912
+ ...this.launchOptions.referrerInfo,
3913
+ extraData: { ...this.launchOptions.referrerInfo.extraData }
3914
+ }
3915
+ };
3916
+ }
3917
+ getEnterOptions() {
3918
+ return {
3919
+ ...this.enterOptions,
3920
+ query: { ...this.enterOptions.query },
3921
+ referrerInfo: {
3922
+ ...this.enterOptions.referrerInfo,
3923
+ extraData: { ...this.enterOptions.referrerInfo.extraData }
3924
+ }
3925
+ };
3926
+ }
3927
+ getMenuButtonBoundingClientRect() {
3928
+ return deriveMenuButtonBoundingClientRect(this.systemInfo);
3929
+ }
3930
+ getNetworkType() {
3931
+ return this.wxState.getNetworkType();
3932
+ }
3933
+ getLoading() {
3934
+ return this.wxState.getLoading();
3935
+ }
3936
+ getModalLogs() {
3937
+ return this.wxState.getModalLogs();
1860
3938
  }
1861
3939
  getToast() {
1862
3940
  return this.wxState.getToast();
1863
3941
  }
3942
+ mockModal(definition = {}) {
3943
+ this.wxState.mockModal(definition);
3944
+ }
3945
+ mockActionSheet(definition = {}) {
3946
+ this.wxState.mockActionSheet(definition);
3947
+ }
1864
3948
  mockRequest(definition) {
1865
3949
  this.wxState.mockRequest(definition);
1866
3950
  }
3951
+ setNetworkType(networkType) {
3952
+ return this.wxState.setNetworkType(networkType);
3953
+ }
3954
+ setBackgroundTextStyle(textStyle) {
3955
+ if (textStyle !== "dark" && textStyle !== "light") throw new Error("setBackgroundTextStyle:fail invalid textStyle");
3956
+ const current = this.requireCurrentPage("wx.setBackgroundTextStyle()");
3957
+ current.__background__ ??= {
3958
+ backgroundColor: "#ffffff",
3959
+ backgroundColorBottom: "#ffffff",
3960
+ backgroundColorTop: "#ffffff",
3961
+ textStyle: "dark"
3962
+ };
3963
+ current.__background__.textStyle = textStyle;
3964
+ current.__backgroundTextStyle__ = textStyle;
3965
+ return { errMsg: "setBackgroundTextStyle:ok" };
3966
+ }
3967
+ setBackgroundColor(option) {
3968
+ const current = this.requireCurrentPage("wx.setBackgroundColor()");
3969
+ current.__background__ ??= {
3970
+ backgroundColor: "#ffffff",
3971
+ backgroundColorBottom: "#ffffff",
3972
+ backgroundColorTop: "#ffffff",
3973
+ textStyle: current.__backgroundTextStyle__ ?? "dark"
3974
+ };
3975
+ if (typeof option.backgroundColor === "string") current.__background__.backgroundColor = option.backgroundColor;
3976
+ if (typeof option.backgroundColorTop === "string") current.__background__.backgroundColorTop = option.backgroundColorTop;
3977
+ if (typeof option.backgroundColorBottom === "string") current.__background__.backgroundColorBottom = option.backgroundColorBottom;
3978
+ return { errMsg: "setBackgroundColor:ok" };
3979
+ }
3980
+ setNavigationBarTitle(title) {
3981
+ const current = this.requireCurrentPage("wx.setNavigationBarTitle()");
3982
+ current.__navigationBar__ ??= {
3983
+ animation: null,
3984
+ backgroundColor: "#ffffff",
3985
+ frontColor: "#000000",
3986
+ loading: false,
3987
+ title: ""
3988
+ };
3989
+ current.__navigationBar__.title = title;
3990
+ current.__navigationBarTitle__ = title;
3991
+ return { errMsg: "setNavigationBarTitle:ok" };
3992
+ }
3993
+ setNavigationBarColor(option) {
3994
+ const current = this.requireCurrentPage("wx.setNavigationBarColor()");
3995
+ current.__navigationBar__ ??= {
3996
+ animation: null,
3997
+ backgroundColor: "#ffffff",
3998
+ frontColor: "#000000",
3999
+ loading: false,
4000
+ title: current.__navigationBarTitle__ ?? ""
4001
+ };
4002
+ if (typeof option.backgroundColor === "string") current.__navigationBar__.backgroundColor = option.backgroundColor;
4003
+ if (typeof option.frontColor === "string") current.__navigationBar__.frontColor = option.frontColor;
4004
+ current.__navigationBar__.animation = option.animation ? {
4005
+ duration: option.animation.duration,
4006
+ timingFunction: option.animation.timingFunction
4007
+ } : null;
4008
+ return { errMsg: "setNavigationBarColor:ok" };
4009
+ }
4010
+ showNavigationBarLoading() {
4011
+ const current = this.requireCurrentPage("wx.showNavigationBarLoading()");
4012
+ current.__navigationBar__ ??= {
4013
+ animation: null,
4014
+ backgroundColor: "#ffffff",
4015
+ frontColor: "#000000",
4016
+ loading: false,
4017
+ title: current.__navigationBarTitle__ ?? ""
4018
+ };
4019
+ current.__navigationBar__.loading = true;
4020
+ return { errMsg: "showNavigationBarLoading:ok" };
4021
+ }
4022
+ hideNavigationBarLoading() {
4023
+ const current = this.requireCurrentPage("wx.hideNavigationBarLoading()");
4024
+ current.__navigationBar__ ??= {
4025
+ animation: null,
4026
+ backgroundColor: "#ffffff",
4027
+ frontColor: "#000000",
4028
+ loading: false,
4029
+ title: current.__navigationBarTitle__ ?? ""
4030
+ };
4031
+ current.__navigationBar__.loading = false;
4032
+ return { errMsg: "hideNavigationBarLoading:ok" };
4033
+ }
4034
+ hideTabBar() {
4035
+ this.tabBarVisible = false;
4036
+ return { errMsg: "hideTabBar:ok" };
4037
+ }
4038
+ hideTabBarRedDot(index) {
4039
+ const item = this.requireTabBarItem(index, "wx.hideTabBarRedDot()");
4040
+ item.redDot = false;
4041
+ return { errMsg: "hideTabBarRedDot:ok" };
4042
+ }
4043
+ showTabBar() {
4044
+ this.tabBarVisible = this.tabBarRoutes.size > 0;
4045
+ return { errMsg: "showTabBar:ok" };
4046
+ }
4047
+ showTabBarRedDot(index) {
4048
+ const item = this.requireTabBarItem(index, "wx.showTabBarRedDot()");
4049
+ item.badge = null;
4050
+ item.redDot = true;
4051
+ return { errMsg: "showTabBarRedDot:ok" };
4052
+ }
4053
+ removeTabBarBadge(index) {
4054
+ const item = this.requireTabBarItem(index, "wx.removeTabBarBadge()");
4055
+ item.badge = null;
4056
+ return { errMsg: "removeTabBarBadge:ok" };
4057
+ }
4058
+ setTabBarBadge(index, text) {
4059
+ const item = this.requireTabBarItem(index, "wx.setTabBarBadge()");
4060
+ item.badge = text;
4061
+ item.redDot = false;
4062
+ return { errMsg: "setTabBarBadge:ok" };
4063
+ }
1867
4064
  bootstrap(launchOptions = createAppLaunchOptions("", {})) {
1868
4065
  if (this.appInstance) return this.appInstance;
4066
+ this.launchOptions = createAppLaunchOptions(launchOptions.path, launchOptions.query);
4067
+ this.enterOptions = createAppLaunchOptions(launchOptions.path, launchOptions.query);
1869
4068
  const appModulePath = path.resolve(this.project.miniprogramRootPath, "app.js");
1870
4069
  this.appDefinition = this.moduleLoader.executeAppModule(appModulePath);
1871
4070
  this.appInstance = createAppInstance(this.appDefinition);
@@ -1888,6 +4087,7 @@ var HeadlessSession = class {
1888
4087
  if (this.pages.length >= PAGE_STACK_LIMIT) throw new Error(`Cannot navigateTo() beyond a ${PAGE_STACK_LIMIT}-page stack in headless runtime.`);
1889
4088
  if (this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.navigateTo() cannot open a tabBar page in headless runtime: ${url}`);
1890
4089
  this.currentPageInstance?.onHide?.();
4090
+ if (this.currentPageInstance) this.runPageComponentLifetime(this.currentPageInstance.route, "hide");
1891
4091
  const pageInstance = this.createFreshPage(target);
1892
4092
  this.pages.push(pageInstance);
1893
4093
  this.currentPageInstance = pageInstance;
@@ -1916,6 +4116,7 @@ var HeadlessSession = class {
1916
4116
  const nextPage = this.pages.at(-1) ?? null;
1917
4117
  this.currentPageInstance = nextPage;
1918
4118
  nextPage?.onShow?.();
4119
+ if (nextPage) this.runPageComponentLifetime(nextPage.route, "show");
1919
4120
  return nextPage;
1920
4121
  }
1921
4122
  switchTab(url) {
@@ -1930,7 +4131,10 @@ var HeadlessSession = class {
1930
4131
  current.onTabItemTap?.(tabItem);
1931
4132
  return current;
1932
4133
  }
1933
- if (current && current !== cachedTarget) current.onHide?.();
4134
+ if (current && current !== cachedTarget) {
4135
+ current.onHide?.();
4136
+ this.runPageComponentLifetime(current.route, "hide");
4137
+ }
1934
4138
  for (const page of [...this.pages].reverse()) {
1935
4139
  if (this.isTabBarRoute(stripLeadingSlash(page.route))) continue;
1936
4140
  this.removePageInstance(page);
@@ -1940,7 +4144,10 @@ var HeadlessSession = class {
1940
4144
  if (!nextPage) {
1941
4145
  nextPage = this.createFreshPage(target);
1942
4146
  this.tabPages.set(target.routeRecord.route, nextPage);
1943
- } else if (current !== nextPage) nextPage.onShow?.();
4147
+ } else if (current !== nextPage) {
4148
+ nextPage.onShow?.();
4149
+ this.runPageComponentLifetime(nextPage.route, "show");
4150
+ }
1944
4151
  nextPage.onTabItemTap?.(tabItem);
1945
4152
  this.pages.length = 0;
1946
4153
  this.pages.push(nextPage);
@@ -1948,10 +4155,16 @@ var HeadlessSession = class {
1948
4155
  return nextPage;
1949
4156
  }
1950
4157
  pageScrollTo(option) {
1951
- this.requireCurrentPage("wx.pageScrollTo()").onPageScroll?.({ scrollTop: Number(option.scrollTop ?? 0) });
4158
+ const current = this.requireCurrentPage("wx.pageScrollTo()");
4159
+ current.__scrollTop__ = Number(option.scrollTop ?? 0);
4160
+ current.onPageScroll?.({ scrollTop: current.__scrollTop__ });
1952
4161
  }
1953
4162
  triggerPullDownRefresh() {
1954
4163
  const current = this.requireCurrentPage("triggerPullDownRefresh()");
4164
+ this.pullDownRefreshState = {
4165
+ ...this.pullDownRefreshState,
4166
+ active: true
4167
+ };
1955
4168
  current.onPullDownRefresh?.();
1956
4169
  return current;
1957
4170
  }
@@ -1962,7 +4175,9 @@ var HeadlessSession = class {
1962
4175
  }
1963
4176
  triggerResize(options) {
1964
4177
  const current = this.requireCurrentPage("triggerResize()");
4178
+ applyResizeToSystemInfo(this.systemInfo, options);
1965
4179
  current.onResize?.(options);
4180
+ this.runPageComponentLifetime(current.route, "resize", options);
1966
4181
  return current;
1967
4182
  }
1968
4183
  triggerRouteDone(options = {}) {
@@ -1970,11 +4185,34 @@ var HeadlessSession = class {
1970
4185
  current.onRouteDone?.(options);
1971
4186
  return current;
1972
4187
  }
1973
- stopPullDownRefresh() {}
4188
+ stopPullDownRefresh() {
4189
+ this.pullDownRefreshState = {
4190
+ active: false,
4191
+ stopCalls: this.pullDownRefreshState.stopCalls + 1
4192
+ };
4193
+ }
4194
+ executeSelectorQuery(requests, scope) {
4195
+ const current = this.requireCurrentPage("wx.createSelectorQuery().exec()");
4196
+ if (scope && scope !== current && !Array.from(this.componentCache.values()).includes(scope)) throw new Error("wx.createSelectorQuery().in(component) received an unknown scope in headless runtime.");
4197
+ const rendered = this.renderCurrentPage();
4198
+ const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
4199
+ return executeSelectorQueryRequests(requests, {
4200
+ page: current,
4201
+ root: resolveSelectorQueryScopeRoot(rendered.root, scopeId),
4202
+ windowInfo: this.getWindowInfo()
4203
+ });
4204
+ }
1974
4205
  createFreshPage(target) {
1975
4206
  const pageModulePath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
4207
+ const pageConfigPath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.json`);
1976
4208
  const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
1977
- const pageInstance = createPageInstance(`/${target.routeRecord.route}`, pageDefinition, target.query);
4209
+ const pageConfig = readJsonObject(pageConfigPath);
4210
+ const pageInstance = createPageInstance(`/${target.routeRecord.route}`, pageDefinition, target.query, {
4211
+ background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
4212
+ navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
4213
+ });
4214
+ pageInstance.selectComponent = (selector) => this.selectComponent(selector);
4215
+ pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
1978
4216
  pageInstance.onLoad?.(target.query);
1979
4217
  pageInstance.onShow?.();
1980
4218
  pageInstance.onReady?.();
@@ -1990,6 +4228,12 @@ var HeadlessSession = class {
1990
4228
  if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in headless runtime.`);
1991
4229
  return { ...item };
1992
4230
  }
4231
+ requireTabBarItem(index, action) {
4232
+ const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
4233
+ const item = this.tabBarState.get(normalizedIndex);
4234
+ if (!item) throw new Error(`Cannot call ${action} with unknown tabBar index ${index} in headless runtime.`);
4235
+ return item;
4236
+ }
1993
4237
  removePageInstance(page) {
1994
4238
  const index = this.pages.indexOf(page);
1995
4239
  if (index >= 0) this.pages.splice(index, 1);
@@ -2014,10 +4258,13 @@ var HeadlessSession = class {
2014
4258
  for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
2015
4259
  this.pages.length = 0;
2016
4260
  this.tabPages.clear();
4261
+ this.componentCache.clear();
4262
+ this.componentScopes.clear();
2017
4263
  this.currentPageInstance = null;
2018
4264
  }
2019
4265
  unloadPage(page) {
2020
4266
  page.onUnload?.();
4267
+ this.detachPageComponents(page.route);
2021
4268
  this.tabPages.delete(stripLeadingSlash(page.route));
2022
4269
  }
2023
4270
  requireCurrentPage(action) {
@@ -2026,178 +4273,123 @@ var HeadlessSession = class {
2026
4273
  if (!current) throw new Error(`Cannot call ${action} without an active page in headless runtime.`);
2027
4274
  return current;
2028
4275
  }
2029
- };
2030
- function createHeadlessSession(options) {
2031
- return new HeadlessSession(options);
2032
- }
2033
- //#endregion
2034
- //#region src/view/selectors.ts
2035
- const WHITESPACE_RE = /\s+/;
2036
- const DATA_ATTR_SELECTOR_RE = /^\[data-([^=\]]+)="([^"]*)"\]$/;
2037
- function getClassList(node) {
2038
- return String(node.attribs?.class ?? "").split(WHITESPACE_RE).map((item) => item.trim()).filter(Boolean);
2039
- }
2040
- function matchesSimpleSelector(node, selector) {
2041
- if (node.type !== "tag") return false;
2042
- if (selector === "page") return node.name === "page";
2043
- if (selector.startsWith("#")) return node.attribs?.id === selector.slice(1);
2044
- if (selector.startsWith(".")) return getClassList(node).includes(selector.slice(1));
2045
- const dataAttrMatch = selector.match(DATA_ATTR_SELECTOR_RE);
2046
- if (dataAttrMatch) {
2047
- const [, key, value] = dataAttrMatch;
2048
- return node.attribs?.[`data-${key}`] === value;
2049
- }
2050
- return node.name === selector;
2051
- }
2052
- function collectDescendants(node, into) {
2053
- for (const child of node.children ?? []) {
2054
- into.push(child);
2055
- collectDescendants(child, into);
4276
+ selectComponentsWithin(rootScopeId, selector) {
4277
+ const normalizedSelector = selector.trim();
4278
+ if (!normalizedSelector) return [];
4279
+ return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
4280
+ if (!candidateScopeId.includes("/")) return false;
4281
+ if (rootScopeId && candidateScopeId === rootScopeId) return false;
4282
+ if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
4283
+ if (normalizedSelector.startsWith("#")) return scope.id === normalizedSelector.slice(1);
4284
+ if (normalizedSelector.startsWith(".")) return scope.classList?.includes(normalizedSelector.slice(1)) ?? false;
4285
+ const dataAttrMatch = normalizedSelector.match(DATA_ATTR_SELECTOR_RE);
4286
+ if (dataAttrMatch) {
4287
+ const [, key, value] = dataAttrMatch;
4288
+ const datasetKey = key.replace(DATASET_KEY_RE, (_match, char) => char.toUpperCase());
4289
+ return scope.dataset?.[datasetKey] === value;
4290
+ }
4291
+ return scope.alias === normalizedSelector;
4292
+ }).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
2056
4293
  }
2057
- }
2058
- function querySelectorAll(root, selector) {
2059
- const parts = selector.trim().split(WHITESPACE_RE).filter(Boolean);
2060
- if (parts.length === 0) return [];
2061
- let current = [root];
2062
- for (const part of parts) {
2063
- const next = [];
2064
- for (const node of current) {
2065
- const candidates = [];
2066
- if (part === "page" && node.type === "tag" && node.name === "page") candidates.push(node);
2067
- collectDescendants(node, candidates);
2068
- for (const candidate of candidates) if (matchesSimpleSelector(candidate, part)) next.push(candidate);
4294
+ detachPageComponents(route) {
4295
+ const prefix = `page:${stripLeadingSlash(route)}`;
4296
+ for (const [scopeId, instance] of [...this.componentCache.entries()]) {
4297
+ if (!scopeId.startsWith(prefix)) continue;
4298
+ instance.__definition__?.lifetimes?.detached?.call(instance);
4299
+ this.componentCache.delete(scopeId);
4300
+ this.componentScopes.delete(scopeId);
2069
4301
  }
2070
- current = next;
2071
- }
2072
- return current;
2073
- }
2074
- //#endregion
2075
- //#region src/view/nodeHandle.ts
2076
- function escapeText$1(text) {
2077
- return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
2078
- }
2079
- function escapeAttribute$1(value) {
2080
- return escapeText$1(value).replaceAll("\"", "&quot;");
2081
- }
2082
- function serializeNode(node) {
2083
- if (node.type === "text") return escapeText$1(node.data ?? "");
2084
- if (node.type !== "tag") return (node.children ?? []).map(serializeNode).join("");
2085
- if (node.name === "page") return (node.children ?? []).filter((child) => !(child.type === "tag" && (child.name === "import" || child.name === "wxs"))).map(serializeNode).join("");
2086
- const attrs = Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$1(value)}"`).join("");
2087
- const children = (node.children ?? []).map(serializeNode).join("");
2088
- return `<${node.name ?? ""}${attrs}>${children}</${node.name ?? ""}>`;
2089
- }
2090
- function collectText(node) {
2091
- if (node.type === "text") return node.data ?? "";
2092
- return (node.children ?? []).map(collectText).join("");
2093
- }
2094
- var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
2095
- constructor(node) {
2096
- this.node = node;
2097
- }
2098
- async $(selector) {
2099
- const match = querySelectorAll(this.node, selector)[0];
2100
- return match ? new HeadlessTestingNodeHandle(match) : null;
2101
- }
2102
- async $$(selector) {
2103
- return querySelectorAll(this.node, selector).map((node) => new HeadlessTestingNodeHandle(node));
2104
- }
2105
- async attr(name) {
2106
- return this.node.attribs?.[name];
2107
- }
2108
- async dataset() {
2109
- const dataset = {};
2110
- for (const [key, value] of Object.entries(this.node.attribs ?? {})) if (key.startsWith("data-")) dataset[key.slice(5)] = value;
2111
- return dataset;
2112
4302
  }
2113
- async text() {
2114
- return collectText(this.node);
4303
+ runPageComponentLifetime(route, lifetimeName, payload) {
4304
+ const prefix = `page:${stripLeadingSlash(route)}`;
4305
+ for (const [scopeId, instance] of this.componentCache.entries()) {
4306
+ if (!scopeId.startsWith(prefix)) continue;
4307
+ instance.__definition__?.pageLifetimes?.[lifetimeName]?.call(instance, payload);
4308
+ }
2115
4309
  }
2116
- async wxml() {
2117
- return serializeNode(this.node);
4310
+ getComponentScopeId(component) {
4311
+ for (const [scopeId, instance] of this.componentCache.entries()) if (instance === component) return scopeId;
4312
+ return null;
2118
4313
  }
2119
4314
  };
2120
- //#endregion
2121
- //#region src/view/render.ts
2122
- const LEADING_SLASH_RE = /^\/+/;
2123
- const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
2124
- function resolveValueByPath(source, expression) {
2125
- const normalized = expression.trim();
2126
- if (!normalized) return "";
2127
- const segments = normalized.split(".").filter(Boolean);
2128
- let current = source;
2129
- for (const segment of segments) current = current?.[segment];
2130
- return current ?? "";
2131
- }
2132
- function interpolateTemplate(input, data) {
2133
- return input.replace(TEMPLATE_INTERPOLATION_RE, (_match, expression) => {
2134
- const value = resolveValueByPath(data, expression);
2135
- return typeof value === "string" ? value : String(value);
2136
- });
2137
- }
2138
- function visitDom(node, visitor) {
2139
- visitor(node);
2140
- for (const child of node.children ?? []) visitDom(child, visitor);
2141
- }
2142
- function interpolateDomTree(root, data) {
2143
- visitDom(root, (node) => {
2144
- if (typeof node.data === "string") node.data = interpolateTemplate(node.data, data);
2145
- if (node.attribs) for (const [key, value] of Object.entries(node.attribs)) node.attribs[key] = interpolateTemplate(value, data);
2146
- });
2147
- }
2148
- function escapeText(text) {
2149
- return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
2150
- }
2151
- function escapeAttribute(value) {
2152
- return escapeText(value).replaceAll("\"", "&quot;");
2153
- }
2154
- function serializeDomNode(node) {
2155
- if (node.type === "text") return escapeText(node.data ?? "");
2156
- if (node.type === "root") return (node.children ?? []).map(serializeDomNode).join("");
2157
- const tagName = node.name ?? "";
2158
- if (!tagName) return (node.children ?? []).map(serializeDomNode).join("");
2159
- return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode).join("")}</${tagName}>`;
2160
- }
2161
- function renderPageTree(project, page) {
2162
- const route = page.route.replace(LEADING_SLASH_RE, "");
2163
- const templatePath = path.resolve(project.miniprogramRootPath, `${route}.wxml`);
2164
- const document = parseDocument(`<page>${fs.readFileSync(templatePath, "utf8")}</page>`, {
2165
- xmlMode: false,
2166
- decodeEntities: false,
2167
- recognizeSelfClosing: true
2168
- });
2169
- interpolateDomTree(document, page.data);
2170
- return {
2171
- root: document,
2172
- wxml: serializeDomNode((document.children ?? [])[0] ?? document)
2173
- };
4315
+ function createHeadlessSession(options) {
4316
+ return new HeadlessSession(options);
2174
4317
  }
2175
4318
  //#endregion
2176
4319
  //#region src/testing/pageHandle.ts
4320
+ const DEFAULT_WAIT_TIMEOUT$1 = 1e3;
4321
+ const DEFAULT_WAIT_INTERVAL$1 = 10;
2177
4322
  var HeadlessTestingPageHandle = class {
2178
- constructor(project, page) {
4323
+ constructor(project, page, session) {
2179
4324
  this.project = project;
2180
4325
  this.page = page;
4326
+ this.session = session;
2181
4327
  }
2182
- async callMethod(methodName, ...args) {
2183
- const method = this.page[methodName];
2184
- if (typeof method !== "function") throw new Error(`Method "${methodName}" does not exist on headless page ${this.page.route}.`);
2185
- return await method.apply(this.page, args);
2186
- }
2187
- async data(path) {
4328
+ resolveDataByPath(path) {
2188
4329
  if (!path) return this.page.data;
2189
4330
  const segments = path.split(".").filter(Boolean);
2190
4331
  let current = this.page.data;
2191
4332
  for (const segment of segments) current = current?.[segment];
2192
4333
  return current;
2193
4334
  }
4335
+ async pollUntil(check, errorMessage, options = {}) {
4336
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT$1)) : DEFAULT_WAIT_TIMEOUT$1;
4337
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL$1)) : DEFAULT_WAIT_INTERVAL$1;
4338
+ const deadline = Date.now() + timeout;
4339
+ while (true) {
4340
+ const result = await check();
4341
+ if (result != null) return result;
4342
+ if (Date.now() >= deadline) throw new Error(errorMessage);
4343
+ await this.waitFor(interval);
4344
+ }
4345
+ }
4346
+ createScopeHandle(component) {
4347
+ const scopeId = this.session?.getScopeIdForComponent(component);
4348
+ return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
4349
+ }
4350
+ async callMethod(methodName, ...args) {
4351
+ const method = this.page[methodName];
4352
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${this.page.route}.`);
4353
+ return await method.apply(this.page, args);
4354
+ }
4355
+ async data(path) {
4356
+ return this.resolveDataByPath(path);
4357
+ }
4358
+ async selectComponent(selector) {
4359
+ const normalizedSelector = selector.trim();
4360
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4361
+ const component = this.page.selectComponent?.(normalizedSelector) ?? null;
4362
+ return this.createScopeHandle(component);
4363
+ }
4364
+ async selectAllComponents(selector) {
4365
+ const normalizedSelector = selector.trim();
4366
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4367
+ return (this.page.selectAllComponents?.(normalizedSelector) ?? []).map((component) => this.createScopeHandle(component)).filter((handle) => Boolean(handle));
4368
+ }
2194
4369
  async waitFor(ms = 0) {
2195
4370
  if (ms <= 0) return;
2196
4371
  await new Promise((resolve) => setTimeout(resolve, ms));
2197
4372
  }
2198
4373
  async $(selector) {
2199
- const tree = renderPageTree(this.project, this.page);
2200
- const root = new HeadlessTestingNodeHandle(tree.root.children?.[0] ?? tree.root);
4374
+ const tree = this.session?.getCurrentPages().includes(this.page) ? this.session.renderCurrentPage() : renderPageTree(this.project, this.page);
4375
+ const root = new HeadlessTestingNodeHandle(tree.root.type === "root" ? tree.root.children?.[0] ?? tree.root : tree.root, {
4376
+ callMethod: (scopeId, methodName, event) => {
4377
+ if (this.session?.getCurrentPages().includes(this.page)) return this.session.callScopeMethod(scopeId, methodName, event);
4378
+ return this.callMethod(methodName, event);
4379
+ },
4380
+ createPageHandle: () => this,
4381
+ createScopeHandle: (scopeId) => {
4382
+ if (!this.session) throw new Error("Scope handles are not available without an active headless testing session.");
4383
+ if (!scopeId) return null;
4384
+ return new HeadlessTestingScopeHandle(scopeId, this.project, this.session);
4385
+ },
4386
+ ownerScopeId: (scopeId) => {
4387
+ if (!this.session || !scopeId) return null;
4388
+ if (this.session.getScopeSnapshot(scopeId)?.type !== "component") return null;
4389
+ const owner = this.session.selectOwnerComponent(scopeId);
4390
+ return this.session.getScopeIdForComponent(owner);
4391
+ }
4392
+ });
2201
4393
  if (selector === "page") return root;
2202
4394
  return await root.$(selector);
2203
4395
  }
@@ -2207,28 +4399,222 @@ var HeadlessTestingPageHandle = class {
2207
4399
  if (selector === "page") return [root];
2208
4400
  return await root.$$(selector);
2209
4401
  }
4402
+ async waitForSelector(selector, options = {}) {
4403
+ const normalizedSelector = selector.trim();
4404
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4405
+ if ((options.state ?? "attached") === "detached") {
4406
+ await this.pollUntil(async () => await this.$(normalizedSelector) ? null : true, `Timed out waiting for selector "${normalizedSelector}" to become detached in headless testing runtime.`, options);
4407
+ return null;
4408
+ }
4409
+ return await this.pollUntil(async () => await this.$(normalizedSelector), `Timed out waiting for selector "${normalizedSelector}" to appear in headless testing runtime.`, options);
4410
+ }
4411
+ async waitForComponent(selector, options = {}) {
4412
+ const normalizedSelector = selector.trim();
4413
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4414
+ return await this.pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
4415
+ }
4416
+ async waitForComponents(selector, count = 1, options = {}) {
4417
+ const normalizedSelector = selector.trim();
4418
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4419
+ const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
4420
+ return await this.pollUntil(async () => {
4421
+ const components = await this.selectAllComponents(normalizedSelector);
4422
+ return components.length >= normalizedCount ? components : null;
4423
+ }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
4424
+ }
4425
+ async waitForText(text, options = {}) {
4426
+ const normalizedText = text.trim();
4427
+ if (!normalizedText) throw new Error("Text must be a non-empty string in headless testing runtime.");
4428
+ return await this.pollUntil(async () => {
4429
+ return (await this.wxml()).includes(normalizedText) ? normalizedText : null;
4430
+ }, `Timed out waiting for text "${normalizedText}" in headless testing runtime.`, options);
4431
+ }
4432
+ async waitForTextGone(text, options = {}) {
4433
+ const normalizedText = text.trim();
4434
+ if (!normalizedText) throw new Error("Text must be a non-empty string in headless testing runtime.");
4435
+ await this.pollUntil(async () => {
4436
+ return (await this.wxml()).includes(normalizedText) ? null : true;
4437
+ }, `Timed out waiting for text "${normalizedText}" to disappear in headless testing runtime.`, options);
4438
+ }
4439
+ async waitForData(path, matcher, options = {}) {
4440
+ const normalizedPath = path.trim();
4441
+ if (!normalizedPath) throw new Error("Data path must be a non-empty string in headless testing runtime.");
4442
+ const hasMatcher = arguments.length >= 2;
4443
+ return await this.pollUntil(async () => {
4444
+ const value = this.resolveDataByPath(normalizedPath);
4445
+ if (typeof matcher === "function") return matcher(value) ? value : null;
4446
+ if (hasMatcher) return Object.is(value, matcher) ? value : null;
4447
+ return value === void 0 ? null : value;
4448
+ }, `Timed out waiting for data "${normalizedPath}" in headless testing runtime.`, options);
4449
+ }
2210
4450
  async wxml() {
2211
- return renderPageTree(this.project, this.page).wxml;
4451
+ return this.session?.getCurrentPages().includes(this.page) ? this.session.renderCurrentPage().wxml : renderPageTree(this.project, this.page).wxml;
2212
4452
  }
2213
4453
  };
2214
4454
  //#endregion
2215
4455
  //#region src/testing/sessionHandle.ts
4456
+ const LEADING_SLASH_RE = /^\/+/;
4457
+ const DEFAULT_WAIT_TIMEOUT = 1e3;
4458
+ const DEFAULT_WAIT_INTERVAL = 10;
4459
+ function normalizeRoute(route) {
4460
+ return route.replace(LEADING_SLASH_RE, "");
4461
+ }
4462
+ function resolvePageScopeId(scopeId) {
4463
+ const pagePathIndex = scopeId.indexOf("/page/");
4464
+ return pagePathIndex >= 0 ? scopeId.slice(0, pagePathIndex) : scopeId;
4465
+ }
4466
+ var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
4467
+ constructor(scopeId, project, session) {
4468
+ this.scopeId = scopeId;
4469
+ this.project = project;
4470
+ this.session = session;
4471
+ }
4472
+ createScopeHandle(component) {
4473
+ const scopeId = this.session.getScopeIdForComponent(component);
4474
+ return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
4475
+ }
4476
+ async callMethod(methodName, ...args) {
4477
+ const normalizedMethodName = methodName.trim();
4478
+ if (!normalizedMethodName) throw new Error("Method name must be a non-empty string in headless testing runtime.");
4479
+ return this.session.callScopeMethodDirect(this.scopeId, normalizedMethodName, ...args);
4480
+ }
4481
+ async snapshot() {
4482
+ return this.session.getScopeSnapshot(this.scopeId);
4483
+ }
4484
+ async page() {
4485
+ const currentPage = this.session.getCurrentPages().at(-1);
4486
+ return currentPage ? new HeadlessTestingPageHandle(this.project, currentPage, this.session) : null;
4487
+ }
4488
+ async pageScope() {
4489
+ return new HeadlessTestingScopeHandle(resolvePageScopeId(this.scopeId), this.project, this.session);
4490
+ }
4491
+ async ownerComponent() {
4492
+ return this.createScopeHandle(this.session.selectOwnerComponent(this.scopeId));
4493
+ }
4494
+ async waitForOwnerComponent(options = {}) {
4495
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
4496
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
4497
+ const deadline = Date.now() + timeout;
4498
+ while (true) {
4499
+ const owner = await this.ownerComponent();
4500
+ if (owner) return owner;
4501
+ if (Date.now() >= deadline) throw new Error("Timed out waiting for owner component in headless testing runtime.");
4502
+ await new Promise((resolve) => setTimeout(resolve, interval));
4503
+ }
4504
+ }
4505
+ async selectComponent(selector) {
4506
+ const normalizedSelector = selector.trim();
4507
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4508
+ const component = this.session.selectComponentWithin(this.scopeId, normalizedSelector);
4509
+ return this.createScopeHandle(component);
4510
+ }
4511
+ async selectAllComponents(selector) {
4512
+ const normalizedSelector = selector.trim();
4513
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4514
+ return this.session.selectAllComponentsWithin(this.scopeId, normalizedSelector).map((component) => this.createScopeHandle(component)).filter((handle) => Boolean(handle));
4515
+ }
4516
+ async waitForComponent(selector, options = {}) {
4517
+ const normalizedSelector = selector.trim();
4518
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4519
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
4520
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
4521
+ const deadline = Date.now() + timeout;
4522
+ while (true) {
4523
+ const component = await this.selectComponent(normalizedSelector);
4524
+ if (component) return component;
4525
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`);
4526
+ await new Promise((resolve) => setTimeout(resolve, interval));
4527
+ }
4528
+ }
4529
+ async waitForComponents(selector, count = 1, options = {}) {
4530
+ const normalizedSelector = selector.trim();
4531
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4532
+ const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
4533
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
4534
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
4535
+ const deadline = Date.now() + timeout;
4536
+ while (true) {
4537
+ const components = await this.selectAllComponents(normalizedSelector);
4538
+ if (components.length >= normalizedCount) return components;
4539
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`);
4540
+ await new Promise((resolve) => setTimeout(resolve, interval));
4541
+ }
4542
+ }
4543
+ };
2216
4544
  var HeadlessTestingSessionHandle = class {
2217
4545
  constructor(project, session) {
2218
4546
  this.project = project;
2219
4547
  this.session = session;
2220
4548
  }
4549
+ async waitFor(ms = 0) {
4550
+ if (ms <= 0) return;
4551
+ await new Promise((resolve) => setTimeout(resolve, ms));
4552
+ }
4553
+ async pollUntil(check, errorMessage, options = {}) {
4554
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT)) : DEFAULT_WAIT_TIMEOUT;
4555
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL)) : DEFAULT_WAIT_INTERVAL;
4556
+ const deadline = Date.now() + timeout;
4557
+ while (true) {
4558
+ const result = await check();
4559
+ if (result != null) return result;
4560
+ if (Date.now() >= deadline) throw new Error(errorMessage);
4561
+ await this.waitFor(interval);
4562
+ }
4563
+ }
2221
4564
  async close() {}
2222
4565
  async currentPage() {
2223
4566
  const current = this.session.getCurrentPages().at(-1);
2224
- return current ? new HeadlessTestingPageHandle(this.project, current) : null;
4567
+ return current ? new HeadlessTestingPageHandle(this.project, current, this.session) : null;
2225
4568
  }
2226
4569
  async getCurrentPages() {
2227
- return this.session.getCurrentPages().map((page) => new HeadlessTestingPageHandle(this.project, page));
4570
+ return this.session.getCurrentPages().map((page) => new HeadlessTestingPageHandle(this.project, page, this.session));
4571
+ }
4572
+ async scopeSnapshot(scopeId) {
4573
+ const normalizedScopeId = scopeId.trim();
4574
+ if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in headless testing runtime.");
4575
+ return this.session.getScopeSnapshot(normalizedScopeId);
4576
+ }
4577
+ async selectComponent(selector) {
4578
+ const normalizedSelector = selector.trim();
4579
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4580
+ const component = this.session.selectComponent(normalizedSelector);
4581
+ const scopeId = this.session.getScopeIdForComponent(component);
4582
+ return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
4583
+ }
4584
+ async selectAllComponents(selector) {
4585
+ const normalizedSelector = selector.trim();
4586
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4587
+ return this.session.selectAllComponents(normalizedSelector).map((component) => this.session.getScopeIdForComponent(component)).filter((scopeId) => Boolean(scopeId)).map((scopeId) => new HeadlessTestingScopeHandle(scopeId, this.project, this.session));
4588
+ }
4589
+ async waitForComponent(selector, options = {}) {
4590
+ const normalizedSelector = selector.trim();
4591
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4592
+ return await this.pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
4593
+ }
4594
+ async waitForComponents(selector, count = 1, options = {}) {
4595
+ const normalizedSelector = selector.trim();
4596
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
4597
+ const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
4598
+ return await this.pollUntil(async () => {
4599
+ const components = await this.selectAllComponents(normalizedSelector);
4600
+ return components.length >= normalizedCount ? components : null;
4601
+ }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
2228
4602
  }
2229
4603
  async reLaunch(route) {
2230
4604
  const page = this.session.reLaunch(route);
2231
- return new HeadlessTestingPageHandle(this.project, page);
4605
+ return new HeadlessTestingPageHandle(this.project, page, this.session);
4606
+ }
4607
+ async waitForCurrentPage(route, options = {}) {
4608
+ const normalizedRoute = route?.trim();
4609
+ if (normalizedRoute != null && !normalizedRoute) throw new Error("Route must be a non-empty string in headless testing runtime.");
4610
+ return await this.pollUntil(async () => {
4611
+ const currentPageInstance = this.session.getCurrentPages().at(-1);
4612
+ if (!currentPageInstance) return null;
4613
+ const current = new HeadlessTestingPageHandle(this.project, currentPageInstance, this.session);
4614
+ if (!normalizedRoute) return current;
4615
+ if (normalizeRoute(currentPageInstance.route) === normalizeRoute(normalizedRoute)) return current;
4616
+ return null;
4617
+ }, normalizedRoute ? `Timed out waiting for current page "${normalizeRoute(normalizedRoute)}" in headless testing runtime.` : "Timed out waiting for a current page in headless testing runtime.", options);
2232
4618
  }
2233
4619
  async pageScrollTo(scrollTop) {
2234
4620
  this.session.pageScrollTo({ scrollTop });
@@ -2254,4 +4640,4 @@ async function launch(options) {
2254
4640
  return new HeadlessTestingSessionHandle(session.project, session);
2255
4641
  }
2256
4642
  //#endregion
2257
- export { BrowserHeadlessSession, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingSessionHandle, cloneValue, coerceComponentPropertyValue, createAppInstance, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createHeadlessSession, createHeadlessWx, createHeadlessWxState, createHostRegistries, createPageInstance, createProjectDescriptor, hasBrowserVirtualFile, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, registerAppDefinition, registerComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, resolveRoutesFromAppConfig, runComponentLifecycle, runComponentObservers, runComponentPageLifetime };
4643
+ export { BrowserHeadlessSession, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingScopeHandle, HeadlessTestingSessionHandle, cloneValue, coerceComponentPropertyValue, createAppInstance, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createHeadlessSession, createHeadlessWx, createHeadlessWxState, createHostRegistries, createPageInstance, createProjectDescriptor, executeSelectorQueryRequests, hasBrowserVirtualFile, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, registerAppDefinition, registerComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, renderRuntimePageTree, resolveRoutesFromAppConfig, resolveSelectorQueryScopeRoot, runComponentLifecycle, runComponentObservers, runComponentPageLifetime };