@mpcore/simulator 0.1.1 → 0.1.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
@@ -60,9 +60,65 @@ function resolveCapabilityValue(source, schema) {
60
60
  function createHeadlessWx(driver) {
61
61
  const capabilityTree = {
62
62
  canIUse: true,
63
+ canvasToTempFilePath: true,
64
+ chooseImage: { return: {
65
+ errMsg: true,
66
+ tempFilePaths: true,
67
+ tempFiles: true
68
+ } },
69
+ chooseMessageFile: { return: {
70
+ errMsg: true,
71
+ tempFiles: true
72
+ } },
73
+ chooseMedia: { return: {
74
+ errMsg: true,
75
+ tempFiles: true,
76
+ type: true
77
+ } },
78
+ chooseVideo: { return: {
79
+ duration: true,
80
+ errMsg: true,
81
+ height: true,
82
+ size: true,
83
+ tempFilePath: true,
84
+ width: true
85
+ } },
86
+ compressImage: { return: {
87
+ errMsg: true,
88
+ tempFilePath: true
89
+ } },
63
90
  clearStorage: true,
64
91
  clearStorageSync: true,
92
+ createAnimation: true,
93
+ createCanvasContext: true,
94
+ createIntersectionObserver: true,
95
+ createVideoContext: true,
65
96
  createSelectorQuery: true,
97
+ getImageInfo: { return: {
98
+ errMsg: true,
99
+ height: true,
100
+ orientation: true,
101
+ path: true,
102
+ type: true,
103
+ width: true
104
+ } },
105
+ getFileInfo: { return: {
106
+ digest: true,
107
+ errMsg: true,
108
+ size: true
109
+ } },
110
+ openDocument: { return: { errMsg: true } },
111
+ getVideoInfo: { return: {
112
+ bitrate: true,
113
+ duration: true,
114
+ errMsg: true,
115
+ fps: true,
116
+ height: true,
117
+ orientation: true,
118
+ size: true,
119
+ type: true,
120
+ width: true
121
+ } },
66
122
  getFileSystemManager: true,
67
123
  getSavedFileInfo: true,
68
124
  getSavedFileList: true,
@@ -100,6 +156,10 @@ function createHeadlessWx(driver) {
100
156
  },
101
157
  scene: true
102
158
  } },
159
+ getClipboardData: { return: {
160
+ data: true,
161
+ errMsg: true
162
+ } },
103
163
  getMenuButtonBoundingClientRect: { return: {
104
164
  bottom: true,
105
165
  height: true,
@@ -174,14 +234,18 @@ function createHeadlessWx(driver) {
174
234
  offNetworkStatusChange: true,
175
235
  onNetworkStatusChange: true,
176
236
  pageScrollTo: true,
237
+ previewImage: true,
177
238
  reLaunch: true,
178
239
  redirectTo: true,
240
+ saveImageToPhotosAlbum: true,
241
+ saveVideoToPhotosAlbum: true,
179
242
  removeStorage: true,
180
243
  removeStorageSync: true,
181
244
  request: true,
182
245
  saveFile: true,
183
246
  setBackgroundColor: true,
184
247
  setBackgroundTextStyle: true,
248
+ setClipboardData: true,
185
249
  setStorage: true,
186
250
  setStorageSync: true,
187
251
  setNavigationBarColor: true,
@@ -198,6 +262,7 @@ function createHeadlessWx(driver) {
198
262
  showLoading: true,
199
263
  showModal: true,
200
264
  showToast: true,
265
+ startPullDownRefresh: true,
201
266
  stopPullDownRefresh: true,
202
267
  switchTab: true,
203
268
  uploadFile: true,
@@ -207,11 +272,21 @@ function createHeadlessWx(driver) {
207
272
  };
208
273
  return {
209
274
  canIUse: (schema) => typeof schema === "string" && schema.trim() !== "" && resolveCapabilityValue(capabilityTree, schema.trim()) != null,
275
+ canvasToTempFilePath: (option) => invokeWxApi(() => driver.canvasToTempFilePath(option), option),
276
+ chooseImage: (option) => invokeWxApi(() => driver.chooseImage(option ?? {}), option),
277
+ chooseMessageFile: (option) => invokeWxApi(() => driver.chooseMessageFile(option ?? {}), option),
278
+ chooseMedia: (option) => invokeWxApi(() => driver.chooseMedia(option ?? {}), option),
279
+ chooseVideo: (option) => invokeWxApi(() => driver.chooseVideo(option ?? {}), option),
280
+ compressImage: (option) => invokeWxApi(() => driver.compressImage(option), option),
210
281
  clearStorage: (option) => invokeWxApi(() => {
211
282
  driver.clearStorageSync();
212
283
  return { errMsg: "clearStorage:ok" };
213
284
  }, option),
214
285
  clearStorageSync: () => driver.clearStorageSync(),
286
+ createAnimation: (option) => driver.createAnimation(option),
287
+ createCanvasContext: (canvasId, component) => driver.createCanvasContext(canvasId, component),
288
+ createIntersectionObserver: (component, options) => driver.createIntersectionObserver(component, options),
289
+ createVideoContext: (videoId, component) => driver.createVideoContext(videoId, component),
215
290
  createSelectorQuery: () => {
216
291
  const requests = [];
217
292
  let scope;
@@ -270,12 +345,16 @@ function createHeadlessWx(driver) {
270
345
  return query;
271
346
  },
272
347
  getEnterOptionsSync: () => driver.getEnterOptionsSync(),
348
+ getFileInfo: (option) => invokeWxApi(() => driver.getFileInfo(option), option),
349
+ getImageInfo: (option) => invokeWxApi(() => driver.getImageInfo(option), option),
350
+ getVideoInfo: (option) => invokeWxApi(() => driver.getVideoInfo(option), option),
273
351
  getFileSystemManager: () => driver.getFileSystemManager(),
274
352
  getSavedFileInfo: (option) => invokeWxApi(() => driver.getSavedFileInfo(option), option),
275
353
  getSavedFileList: (option) => invokeWxApi(() => driver.getSavedFileList(option), option),
276
354
  getAppBaseInfo: (option) => invokeWxApi(() => driver.getAppBaseInfoSync(), option),
277
355
  getAppBaseInfoSync: () => driver.getAppBaseInfoSync(),
278
356
  getLaunchOptionsSync: () => driver.getLaunchOptionsSync(),
357
+ getClipboardData: (option) => invokeWxApi(() => driver.getClipboardData(), option),
279
358
  getMenuButtonBoundingClientRect: () => driver.getMenuButtonBoundingClientRect(),
280
359
  getNetworkType: (option) => invokeWxApi(() => driver.getNetworkType(), option),
281
360
  getStorageInfo: (option) => invokeWxApi(() => driver.getStorageInfoSync(), option),
@@ -301,9 +380,11 @@ function createHeadlessWx(driver) {
301
380
  nextTick: (callback) => driver.nextTick(callback),
302
381
  offNetworkStatusChange: (callback) => driver.offNetworkStatusChange(callback),
303
382
  onNetworkStatusChange: (callback) => driver.onNetworkStatusChange(callback),
383
+ openDocument: (option) => invokeWxApi(() => driver.openDocument(option), option),
304
384
  pageScrollTo: (option) => invokeWxApi(() => {
305
385
  driver.pageScrollTo(option);
306
386
  }, option),
387
+ previewImage: (option) => invokeWxApi(() => driver.previewImage(option), option),
307
388
  reLaunch: (option) => invokeWxApi(() => {
308
389
  driver.reLaunch(option);
309
390
  }, option),
@@ -311,6 +392,8 @@ function createHeadlessWx(driver) {
311
392
  driver.redirectTo(option);
312
393
  }, option),
313
394
  removeSavedFile: (option) => invokeWxApi(() => driver.removeSavedFile(option), option),
395
+ saveImageToPhotosAlbum: (option) => invokeWxApi(() => driver.saveImageToPhotosAlbum(option), option),
396
+ saveVideoToPhotosAlbum: (option) => invokeWxApi(() => driver.saveVideoToPhotosAlbum(option), option),
314
397
  removeStorage: (option) => invokeWxApi(() => {
315
398
  driver.removeStorageSync(option.key);
316
399
  return { errMsg: "removeStorage:ok" };
@@ -320,6 +403,7 @@ function createHeadlessWx(driver) {
320
403
  saveFile: (option) => invokeWxApi(() => driver.saveFile(option), option),
321
404
  setBackgroundColor: (option) => invokeWxApi(() => driver.setBackgroundColor(option), option),
322
405
  setBackgroundTextStyle: (option) => invokeWxApi(() => driver.setBackgroundTextStyle(option), option),
406
+ setClipboardData: (option) => invokeWxApi(() => driver.setClipboardData(option), option),
323
407
  setStorage: (option) => invokeWxApi(() => {
324
408
  driver.setStorageSync(option.key, option.data);
325
409
  return { errMsg: "setStorage:ok" };
@@ -339,6 +423,7 @@ function createHeadlessWx(driver) {
339
423
  showLoading: (option) => invokeWxApi(() => driver.showLoading(option), option),
340
424
  showModal: (option) => invokeWxApi(() => driver.showModal(option), option),
341
425
  showToast: (option) => invokeWxApi(() => driver.showToast(option), option),
426
+ startPullDownRefresh: (option) => invokeWxApi(() => driver.startPullDownRefresh(), option),
342
427
  stopPullDownRefresh: () => driver.stopPullDownRefresh(),
343
428
  switchTab: (option) => invokeWxApi(() => {
344
429
  driver.switchTab(option);
@@ -561,6 +646,8 @@ function createBrowserProject(files, options = {}) {
561
646
  }
562
647
  //#endregion
563
648
  //#region src/runtime/componentInstance.ts
649
+ const ARRAY_INDEX_PATH_RE$1 = /\[(\d+)\]/g;
650
+ const ARRAY_INDEX_SEGMENT_RE$1 = /^\d+$/;
564
651
  function bindFunction$2(target, key, value) {
565
652
  if (typeof value !== "function") {
566
653
  target[key] = value;
@@ -577,10 +664,10 @@ function cloneValue(value) {
577
664
  return value;
578
665
  }
579
666
  function parseDataPath$1(path) {
580
- return path.replace(/\[(\d+)\]/g, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
667
+ return path.replace(ARRAY_INDEX_PATH_RE$1, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
581
668
  }
582
669
  function isArrayIndexSegment$1(segment) {
583
- return /^\d+$/.test(segment);
670
+ return ARRAY_INDEX_SEGMENT_RE$1.test(segment);
584
671
  }
585
672
  function createContainerByNextSegment$1(nextSegment) {
586
673
  return isArrayIndexSegment$1(nextSegment ?? "") ? [] : {};
@@ -597,7 +684,7 @@ function assignByPath$1(target, path, value) {
597
684
  if (!next || typeof next !== "object") current[normalizedSegment] = createContainerByNextSegment$1(nextSegment);
598
685
  current = current[normalizedSegment];
599
686
  }
600
- const leafSegment = segments[segments.length - 1];
687
+ const leafSegment = segments.at(-1);
601
688
  const normalizedLeafSegment = isArrayIndexSegment$1(leafSegment) ? Number(leafSegment) : leafSegment;
602
689
  current[normalizedLeafSegment] = value;
603
690
  }
@@ -717,7 +804,7 @@ function resolveInitialProperties(definition, properties) {
717
804
  const resolved = {};
718
805
  const propOptions = definition.properties;
719
806
  if (propOptions && typeof propOptions === "object" && !Array.isArray(propOptions)) for (const [key, option] of Object.entries(propOptions)) {
720
- if (Object.prototype.hasOwnProperty.call(properties, key)) {
807
+ if (Object.hasOwn(properties, key)) {
721
808
  resolved[key] = coerceComponentPropertyValue(properties[key], option);
722
809
  continue;
723
810
  }
@@ -753,7 +840,7 @@ function resolveObservedValue(instance, pattern) {
753
840
  const segments = parseDataPath$1(pattern);
754
841
  if (segments.length === 0) return;
755
842
  const [rootSegment, ...restSegments] = segments;
756
- let current = (Object.prototype.hasOwnProperty.call(instance.properties, rootSegment) ? instance.properties : instance.data)?.[rootSegment];
843
+ let current = (Object.hasOwn(instance.properties, rootSegment) ? instance.properties : instance.data)?.[rootSegment];
757
844
  for (const segment of restSegments) {
758
845
  const normalizedSegment = isArrayIndexSegment$1(segment) ? Number(segment) : segment;
759
846
  current = current?.[normalizedSegment];
@@ -851,7 +938,7 @@ const STRUCTURAL_ATTRS$1 = [
851
938
  "wx:key"
852
939
  ];
853
940
  const WX_ELSE_ATTRS$1 = new Set(["wx:elif", "wx:else"]);
854
- const DATASET_NAME_RE$3 = /-([a-z])/g;
941
+ const DATASET_NAME_RE$4 = /-([a-z])/g;
855
942
  const BRACKET_INDEX_RE$1 = /\[(\d+)\]/g;
856
943
  const CLASS_SPLIT_RE$1 = /\s+/;
857
944
  const JS_FILE_RE$1 = /\.js$/;
@@ -859,14 +946,14 @@ function isMustacheOnly$1(value) {
859
946
  const trimmed = value.trim();
860
947
  return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
861
948
  }
862
- function toDatasetKey$3(attributeName) {
863
- return attributeName.slice(5).replace(DATASET_NAME_RE$3, (_match, char) => char.toUpperCase());
949
+ function toDatasetKey$4(attributeName) {
950
+ return attributeName.slice(5).replace(DATASET_NAME_RE$4, (_match, char) => char.toUpperCase());
864
951
  }
865
- function collectDataset$3(node) {
952
+ function collectDataset$4(node) {
866
953
  const dataset = {};
867
954
  for (const [key, value] of Object.entries(node.attribs ?? {})) {
868
955
  if (!key.startsWith("data-") || key === "data-sim-scope" || key === "data-sim-tap" || key === "data-sim-component") continue;
869
- dataset[toDatasetKey$3(key)] = String(value);
956
+ dataset[toDatasetKey$4(key)] = String(value);
870
957
  }
871
958
  return dataset;
872
959
  }
@@ -1005,7 +1092,7 @@ function collectComponentEventBindings$1(hostNode) {
1005
1092
  return eventBindings;
1006
1093
  }
1007
1094
  function buildComponentTrigger$1(componentScopeId, context, hostNode) {
1008
- const hostDataset = collectDataset$3(hostNode);
1095
+ const hostDataset = collectDataset$4(hostNode);
1009
1096
  const hostId = hostNode.attribs?.id ?? "";
1010
1097
  return (instance, eventName, detail, triggerOptions) => {
1011
1098
  const interactionTarget = instance.__lastInteractionEvent__?.target;
@@ -1186,6 +1273,8 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
1186
1273
  properties: nextProperties,
1187
1274
  triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
1188
1275
  });
1276
+ componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
1277
+ componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
1189
1278
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
1190
1279
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
1191
1280
  componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
@@ -1201,7 +1290,7 @@ function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, in
1201
1290
  alias: clonedNode.name,
1202
1291
  classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
1203
1292
  data: createMergedScopeData$1(scope.data, componentInstance.properties, componentInstance.data),
1204
- dataset: collectDataset$3(clonedNode),
1293
+ dataset: collectDataset$4(clonedNode),
1205
1294
  eventBindings: collectComponentEventBindings$1(clonedNode),
1206
1295
  getMethod: (methodName) => {
1207
1296
  const method = componentInstance?.[methodName];
@@ -1494,9 +1583,228 @@ const DEFAULT_MODAL_CONFIRM_TEXT = "确定";
1494
1583
  const TRAILING_SLASH_RE = /\/+$/;
1495
1584
  const SAVED_FILE_PREFIXES = ["headless://saved/", "headless://wxfile/saved/"];
1496
1585
  const textEncoder = new TextEncoder();
1586
+ const IMAGE_EXTENSION_RE = /\.([^.?#/]+)(?:[?#].*)?$/;
1587
+ const LEADING_DOT_RE = /^\.+/;
1588
+ const IMAGE_FILE_EXTENSIONS = new Set([
1589
+ "bmp",
1590
+ "gif",
1591
+ "heic",
1592
+ "jpeg",
1593
+ "jpg",
1594
+ "png",
1595
+ "webp"
1596
+ ]);
1597
+ const VIDEO_FILE_EXTENSIONS = new Set([
1598
+ "avi",
1599
+ "m4v",
1600
+ "mov",
1601
+ "mp4",
1602
+ "mpeg",
1603
+ "mpg",
1604
+ "webm"
1605
+ ]);
1497
1606
  function byteLength(input) {
1498
1607
  return textEncoder.encode(input).byteLength;
1499
1608
  }
1609
+ function rotateLeft(value, bits) {
1610
+ return (value << bits | value >>> 32 - bits) >>> 0;
1611
+ }
1612
+ function toHexWordLittleEndian(value) {
1613
+ let output = "";
1614
+ for (let index = 0; index < 4; index += 1) output += (value >>> index * 8 & 255).toString(16).padStart(2, "0");
1615
+ return output;
1616
+ }
1617
+ function toHexWordBigEndian(value) {
1618
+ return value.toString(16).padStart(8, "0");
1619
+ }
1620
+ function computeMd5Digest(input) {
1621
+ const bytes = Array.from(textEncoder.encode(input));
1622
+ const bitLength = bytes.length * 8;
1623
+ const lowBits = bitLength >>> 0;
1624
+ const highBits = Math.floor(bitLength / 4294967296) >>> 0;
1625
+ bytes.push(128);
1626
+ while (bytes.length % 64 !== 56) bytes.push(0);
1627
+ for (let index = 0; index < 4; index += 1) bytes.push(lowBits >>> index * 8 & 255);
1628
+ for (let index = 0; index < 4; index += 1) bytes.push(highBits >>> index * 8 & 255);
1629
+ const shifts = [
1630
+ 7,
1631
+ 12,
1632
+ 17,
1633
+ 22,
1634
+ 7,
1635
+ 12,
1636
+ 17,
1637
+ 22,
1638
+ 7,
1639
+ 12,
1640
+ 17,
1641
+ 22,
1642
+ 7,
1643
+ 12,
1644
+ 17,
1645
+ 22,
1646
+ 5,
1647
+ 9,
1648
+ 14,
1649
+ 20,
1650
+ 5,
1651
+ 9,
1652
+ 14,
1653
+ 20,
1654
+ 5,
1655
+ 9,
1656
+ 14,
1657
+ 20,
1658
+ 5,
1659
+ 9,
1660
+ 14,
1661
+ 20,
1662
+ 4,
1663
+ 11,
1664
+ 16,
1665
+ 23,
1666
+ 4,
1667
+ 11,
1668
+ 16,
1669
+ 23,
1670
+ 4,
1671
+ 11,
1672
+ 16,
1673
+ 23,
1674
+ 4,
1675
+ 11,
1676
+ 16,
1677
+ 23,
1678
+ 6,
1679
+ 10,
1680
+ 15,
1681
+ 21,
1682
+ 6,
1683
+ 10,
1684
+ 15,
1685
+ 21,
1686
+ 6,
1687
+ 10,
1688
+ 15,
1689
+ 21,
1690
+ 6,
1691
+ 10,
1692
+ 15,
1693
+ 21
1694
+ ];
1695
+ const table = Array.from({ length: 64 }, (_, index) => Math.floor(Math.abs(Math.sin(index + 1)) * 4294967296) >>> 0);
1696
+ let a0 = 1732584193;
1697
+ let b0 = 4023233417;
1698
+ let c0 = 2562383102;
1699
+ let d0 = 271733878;
1700
+ for (let chunkOffset = 0; chunkOffset < bytes.length; chunkOffset += 64) {
1701
+ const words = Array.from({ length: 16 }, (_, index) => {
1702
+ const wordOffset = chunkOffset + index * 4;
1703
+ return (bytes[wordOffset] | bytes[wordOffset + 1] << 8 | bytes[wordOffset + 2] << 16 | bytes[wordOffset + 3] << 24) >>> 0;
1704
+ });
1705
+ let a = a0;
1706
+ let b = b0;
1707
+ let c = c0;
1708
+ let d = d0;
1709
+ for (let index = 0; index < 64; index += 1) {
1710
+ let f = 0;
1711
+ let g = 0;
1712
+ if (index < 16) {
1713
+ f = (b & c | ~b & d) >>> 0;
1714
+ g = index;
1715
+ } else if (index < 32) {
1716
+ f = (d & b | ~d & c) >>> 0;
1717
+ g = (5 * index + 1) % 16;
1718
+ } else if (index < 48) {
1719
+ f = (b ^ c ^ d) >>> 0;
1720
+ g = (3 * index + 5) % 16;
1721
+ } else {
1722
+ f = (c ^ (b | ~d)) >>> 0;
1723
+ g = 7 * index % 16;
1724
+ }
1725
+ const next = a + f + table[index] + words[g] >>> 0;
1726
+ a = d;
1727
+ d = c;
1728
+ c = b;
1729
+ b = b + rotateLeft(next, shifts[index]) >>> 0;
1730
+ }
1731
+ a0 = a0 + a >>> 0;
1732
+ b0 = b0 + b >>> 0;
1733
+ c0 = c0 + c >>> 0;
1734
+ d0 = d0 + d >>> 0;
1735
+ }
1736
+ return [
1737
+ toHexWordLittleEndian(a0),
1738
+ toHexWordLittleEndian(b0),
1739
+ toHexWordLittleEndian(c0),
1740
+ toHexWordLittleEndian(d0)
1741
+ ].join("");
1742
+ }
1743
+ function computeSha1Digest(input) {
1744
+ const bytes = Array.from(textEncoder.encode(input));
1745
+ const bitLength = bytes.length * 8;
1746
+ const lowBits = bitLength >>> 0;
1747
+ const highBits = Math.floor(bitLength / 4294967296) >>> 0;
1748
+ bytes.push(128);
1749
+ while (bytes.length % 64 !== 56) bytes.push(0);
1750
+ for (let index = 3; index >= 0; index -= 1) bytes.push(highBits >>> index * 8 & 255);
1751
+ for (let index = 3; index >= 0; index -= 1) bytes.push(lowBits >>> index * 8 & 255);
1752
+ let h0 = 1732584193;
1753
+ let h1 = 4023233417;
1754
+ let h2 = 2562383102;
1755
+ let h3 = 271733878;
1756
+ let h4 = 3285377520;
1757
+ for (let chunkOffset = 0; chunkOffset < bytes.length; chunkOffset += 64) {
1758
+ const words = Array.from({ length: 80 }, (_, index) => {
1759
+ if (index < 16) {
1760
+ const wordOffset = chunkOffset + index * 4;
1761
+ return (bytes[wordOffset] << 24 | bytes[wordOffset + 1] << 16 | bytes[wordOffset + 2] << 8 | bytes[wordOffset + 3]) >>> 0;
1762
+ }
1763
+ return 0;
1764
+ });
1765
+ for (let index = 16; index < 80; index += 1) words[index] = rotateLeft(words[index - 3] ^ words[index - 8] ^ words[index - 14] ^ words[index - 16], 1);
1766
+ let a = h0;
1767
+ let b = h1;
1768
+ let c = h2;
1769
+ let d = h3;
1770
+ let e = h4;
1771
+ for (let index = 0; index < 80; index += 1) {
1772
+ let f = 0;
1773
+ let k = 0;
1774
+ if (index < 20) {
1775
+ f = (b & c | ~b & d) >>> 0;
1776
+ k = 1518500249;
1777
+ } else if (index < 40) {
1778
+ f = (b ^ c ^ d) >>> 0;
1779
+ k = 1859775393;
1780
+ } else if (index < 60) {
1781
+ f = (b & c | b & d | c & d) >>> 0;
1782
+ k = 2400959708;
1783
+ } else {
1784
+ f = (b ^ c ^ d) >>> 0;
1785
+ k = 3395469782;
1786
+ }
1787
+ const next = rotateLeft(a, 5) + f + e + k + words[index] >>> 0;
1788
+ e = d;
1789
+ d = c;
1790
+ c = rotateLeft(b, 30);
1791
+ b = a;
1792
+ a = next;
1793
+ }
1794
+ h0 = h0 + a >>> 0;
1795
+ h1 = h1 + b >>> 0;
1796
+ h2 = h2 + c >>> 0;
1797
+ h3 = h3 + d >>> 0;
1798
+ h4 = h4 + e >>> 0;
1799
+ }
1800
+ return [
1801
+ toHexWordBigEndian(h0),
1802
+ toHexWordBigEndian(h1),
1803
+ toHexWordBigEndian(h2),
1804
+ toHexWordBigEndian(h3),
1805
+ toHexWordBigEndian(h4)
1806
+ ].join("");
1807
+ }
1500
1808
  function cloneShareMenuSnapshot(snapshot) {
1501
1809
  return {
1502
1810
  isUpdatableMessage: snapshot.isUpdatableMessage,
@@ -1505,6 +1813,116 @@ function cloneShareMenuSnapshot(snapshot) {
1505
1813
  withShareTicket: snapshot.withShareTicket
1506
1814
  };
1507
1815
  }
1816
+ function normalizeImageType(type) {
1817
+ const normalized = (type ?? "").trim().toLowerCase();
1818
+ if (normalized === "jpg") return "jpeg";
1819
+ return normalized;
1820
+ }
1821
+ function normalizeFileExtension(extension) {
1822
+ return extension.trim().replace(LEADING_DOT_RE, "").toLowerCase();
1823
+ }
1824
+ function inferDocumentFileType(filePath) {
1825
+ const extensionMatch = filePath.match(IMAGE_EXTENSION_RE);
1826
+ return extensionMatch ? normalizeFileExtension(extensionMatch[1]) : "unknown";
1827
+ }
1828
+ function isImageFileExtension(extension) {
1829
+ return IMAGE_FILE_EXTENSIONS.has(normalizeFileExtension(extension));
1830
+ }
1831
+ function isVideoFileExtension(extension) {
1832
+ return VIDEO_FILE_EXTENSIONS.has(normalizeFileExtension(extension));
1833
+ }
1834
+ function resolveMessageFileExtensions(option) {
1835
+ const filteredExtensions = (Array.isArray(option.extension) ? option.extension.filter((item) => typeof item === "string").map(normalizeFileExtension).filter(Boolean) : []).filter((extension) => {
1836
+ if (option.type === "image") return isImageFileExtension(extension);
1837
+ if (option.type === "video") return isVideoFileExtension(extension);
1838
+ if (option.type === "file") return !isImageFileExtension(extension) && !isVideoFileExtension(extension);
1839
+ return true;
1840
+ });
1841
+ if (filteredExtensions.length > 0) return filteredExtensions;
1842
+ if (option.type === "image") return ["png", "jpg"];
1843
+ if (option.type === "video") return ["mp4"];
1844
+ if (option.type === "file") return [
1845
+ "txt",
1846
+ "pdf",
1847
+ "doc"
1848
+ ];
1849
+ return [
1850
+ "png",
1851
+ "pdf",
1852
+ "mp4"
1853
+ ];
1854
+ }
1855
+ function inferImageType(filePath, fileContent) {
1856
+ const extensionMatch = filePath.match(IMAGE_EXTENSION_RE);
1857
+ if (extensionMatch) return normalizeImageType(extensionMatch[1]);
1858
+ try {
1859
+ return normalizeImageType(JSON.parse(fileContent)?.config?.fileType) || "png";
1860
+ } catch {
1861
+ return "unknown";
1862
+ }
1863
+ }
1864
+ function inferImageSize(fileContent) {
1865
+ try {
1866
+ const payload = JSON.parse(fileContent);
1867
+ return {
1868
+ height: payload?.config?.destHeight ?? payload?.config?.height ?? 0,
1869
+ width: payload?.config?.destWidth ?? payload?.config?.width ?? 0
1870
+ };
1871
+ } catch {
1872
+ return {
1873
+ height: 0,
1874
+ width: 0
1875
+ };
1876
+ }
1877
+ }
1878
+ function buildImageTempFilePayload(fileType, width, height, metadata = {}) {
1879
+ return JSON.stringify({ config: {
1880
+ fileType,
1881
+ height,
1882
+ quality: metadata.quality,
1883
+ sizeType: metadata.sizeType ?? [],
1884
+ sourceType: metadata.sourceType ?? [],
1885
+ width
1886
+ } });
1887
+ }
1888
+ function buildVideoTempFilePayload(width, height, duration, metadata = {}) {
1889
+ return JSON.stringify({ config: {
1890
+ bitrate: metadata.bitrate ?? 1500,
1891
+ compressed: metadata.compressed ?? true,
1892
+ duration,
1893
+ fps: metadata.fps ?? 30,
1894
+ height,
1895
+ maxDuration: metadata.maxDuration ?? duration,
1896
+ sourceType: metadata.sourceType ?? [],
1897
+ width
1898
+ } });
1899
+ }
1900
+ function inferVideoInfo(filePath, fileContent) {
1901
+ const size = byteLength(fileContent);
1902
+ const type = filePath.match(IMAGE_EXTENSION_RE)?.[1]?.toLowerCase() ?? "mp4";
1903
+ try {
1904
+ const payload = JSON.parse(fileContent);
1905
+ return {
1906
+ bitrate: payload.config.bitrate ?? 1500,
1907
+ duration: payload.config.duration ?? 0,
1908
+ fps: payload.config.fps ?? 30,
1909
+ height: payload.config.height ?? 0,
1910
+ size,
1911
+ type,
1912
+ width: payload.config.width ?? 0
1913
+ };
1914
+ } catch {
1915
+ return {
1916
+ bitrate: 1500,
1917
+ duration: 0,
1918
+ fps: 30,
1919
+ height: 0,
1920
+ size,
1921
+ type,
1922
+ width: 0
1923
+ };
1924
+ }
1925
+ }
1508
1926
  function createNetworkSnapshot(networkType) {
1509
1927
  return {
1510
1928
  isConnected: networkType !== "none",
@@ -1655,6 +2073,9 @@ function createHeadlessWxState() {
1655
2073
  let fileId = 0;
1656
2074
  let loading = null;
1657
2075
  let networkType = "wifi";
2076
+ let previewImage = null;
2077
+ let openedDocument = null;
2078
+ let clipboardData = "";
1658
2079
  let shareMenu = {
1659
2080
  isUpdatableMessage: false,
1660
2081
  menus: [],
@@ -1856,6 +2277,16 @@ function createHeadlessWxState() {
1856
2277
  size: savedFile.size
1857
2278
  };
1858
2279
  };
2280
+ const getFileInfo = (option) => {
2281
+ const normalizedPath = normalizeFsPath(option.filePath);
2282
+ const fileContent = files.get(normalizedPath);
2283
+ if (fileContent == null) throw new Error(`getFileInfo:fail no such file or directory, stat '${normalizedPath}'`);
2284
+ return {
2285
+ digest: (option.digestAlgorithm === "sha1" ? "sha1" : "md5") === "sha1" ? computeSha1Digest(fileContent) : computeMd5Digest(fileContent),
2286
+ errMsg: "getFileInfo:ok",
2287
+ size: byteLength(fileContent)
2288
+ };
2289
+ };
1859
2290
  const removeSavedFile = (filePath) => {
1860
2291
  const normalizedPath = normalizeFsPath(filePath);
1861
2292
  if (!savedFiles.has(normalizedPath)) throw new Error(`removeSavedFile:fail no such file or directory, unlink '${normalizedPath}'`);
@@ -2106,18 +2537,191 @@ function createHeadlessWxState() {
2106
2537
  getSavedFileInfo(option) {
2107
2538
  return getSavedFileInfo(option.filePath);
2108
2539
  },
2540
+ getFileInfo(option) {
2541
+ return getFileInfo(option);
2542
+ },
2109
2543
  getSavedFileList() {
2110
2544
  return getSavedFileList();
2111
2545
  },
2112
2546
  getFileText(filePath) {
2113
2547
  return files.get(filePath) ?? null;
2114
2548
  },
2549
+ createTempFile(fileContent, preferredPath) {
2550
+ const tempFilePath = allocateFilePath("temp", preferredPath);
2551
+ ensureDirectoryTree(tempFilePath);
2552
+ files.set(tempFilePath, String(fileContent));
2553
+ return tempFilePath;
2554
+ },
2555
+ chooseImage(option) {
2556
+ const count = Number.isFinite(option.count) ? Math.max(1, Math.min(9, Math.trunc(option.count ?? 1))) : 9;
2557
+ const sizeType = Array.isArray(option.sizeType) && option.sizeType.length > 0 ? option.sizeType.filter((item) => typeof item === "string") : ["original"];
2558
+ const sourceType = Array.isArray(option.sourceType) && option.sourceType.length > 0 ? option.sourceType.filter((item) => typeof item === "string") : ["album", "camera"];
2559
+ const fileType = sizeType.includes("compressed") ? "jpg" : "png";
2560
+ const tempFiles = Array.from({ length: count }, (_, index) => {
2561
+ const payload = buildImageTempFilePayload(fileType, 160 + index * 12, 120 + index * 8, {
2562
+ sizeType: [...sizeType],
2563
+ sourceType: [...sourceType]
2564
+ });
2565
+ return {
2566
+ path: this.createTempFile(payload, `headless://wxfile/temp/chosen-image-${String(index + 1).padStart(2, "0")}.${fileType}`),
2567
+ size: payload.length
2568
+ };
2569
+ });
2570
+ return {
2571
+ errMsg: "chooseImage:ok",
2572
+ tempFilePaths: tempFiles.map((item) => item.path),
2573
+ tempFiles
2574
+ };
2575
+ },
2576
+ chooseMessageFile(option) {
2577
+ const count = Number.isFinite(option.count) ? Math.max(1, Math.min(100, Math.trunc(option.count ?? 1))) : 1;
2578
+ const extensions = resolveMessageFileExtensions(option);
2579
+ return {
2580
+ errMsg: "chooseMessageFile:ok",
2581
+ tempFiles: Array.from({ length: count }, (_, index) => {
2582
+ const extension = extensions[index % extensions.length];
2583
+ const sequence = String(index + 1).padStart(2, "0");
2584
+ const fileName = `message-file-${sequence}.${extension}`;
2585
+ let fileContent = `headless message file ${fileName}`;
2586
+ if (isImageFileExtension(extension)) fileContent = buildImageTempFilePayload(extension, 160 + index * 12, 120 + index * 8, { sourceType: ["message"] });
2587
+ else if (isVideoFileExtension(extension)) fileContent = buildVideoTempFilePayload(640, 360, 18 + index, {
2588
+ compressed: true,
2589
+ sourceType: ["message"]
2590
+ });
2591
+ return {
2592
+ name: fileName,
2593
+ path: this.createTempFile(fileContent, `headless://wxfile/temp/chosen-message-file-${sequence}.${extension}`),
2594
+ size: byteLength(fileContent),
2595
+ time: 171e10 + index * 1e3,
2596
+ type: extension
2597
+ };
2598
+ })
2599
+ };
2600
+ },
2601
+ chooseMedia(option) {
2602
+ const count = Number.isFinite(option.count) ? Math.max(1, Math.min(9, Math.trunc(option.count ?? 1))) : 1;
2603
+ const mediaTypes = Array.isArray(option.mediaType) && option.mediaType.length > 0 ? option.mediaType.filter((item) => item === "image" || item === "video") : ["image"];
2604
+ const sourceType = Array.isArray(option.sourceType) && option.sourceType.length > 0 ? option.sourceType.filter((item) => typeof item === "string") : ["album", "camera"];
2605
+ const sizeType = Array.isArray(option.sizeType) && option.sizeType.length > 0 ? option.sizeType.filter((item) => typeof item === "string") : ["compressed"];
2606
+ const maxDuration = Number.isFinite(option.maxDuration) ? Math.max(1, Math.trunc(option.maxDuration ?? 60)) : 60;
2607
+ return {
2608
+ errMsg: "chooseMedia:ok",
2609
+ tempFiles: Array.from({ length: count }, (_, index) => {
2610
+ if (mediaTypes[index % mediaTypes.length] === "video") {
2611
+ const duration = Math.min(maxDuration, 18 + index);
2612
+ const width = 640;
2613
+ const height = 360;
2614
+ const payload = buildVideoTempFilePayload(width, height, duration, {
2615
+ compressed: sizeType.includes("compressed"),
2616
+ maxDuration,
2617
+ sourceType: [...sourceType]
2618
+ });
2619
+ const tempFilePath = this.createTempFile(payload, `headless://wxfile/temp/chosen-media-video-${String(index + 1).padStart(2, "0")}.mp4`);
2620
+ const thumbPayload = buildImageTempFilePayload("jpg", 160, 90, {
2621
+ sizeType: ["compressed"],
2622
+ sourceType: [...sourceType]
2623
+ });
2624
+ const thumbTempFilePath = this.createTempFile(thumbPayload, `headless://wxfile/temp/chosen-media-video-thumb-${String(index + 1).padStart(2, "0")}.jpg`);
2625
+ return {
2626
+ duration,
2627
+ fileType: "video",
2628
+ height,
2629
+ size: payload.length,
2630
+ tempFilePath,
2631
+ thumbTempFilePath,
2632
+ width
2633
+ };
2634
+ }
2635
+ const width = 160 + index * 12;
2636
+ const height = 120 + index * 8;
2637
+ const fileType = sizeType.includes("compressed") ? "jpg" : "png";
2638
+ const payload = buildImageTempFilePayload(fileType, width, height, {
2639
+ sizeType: [...sizeType],
2640
+ sourceType: [...sourceType]
2641
+ });
2642
+ return {
2643
+ fileType: "image",
2644
+ height,
2645
+ size: payload.length,
2646
+ tempFilePath: this.createTempFile(payload, `headless://wxfile/temp/chosen-media-image-${String(index + 1).padStart(2, "0")}.${fileType}`),
2647
+ width
2648
+ };
2649
+ }),
2650
+ type: mediaTypes.length > 1 ? "mix" : mediaTypes[0]
2651
+ };
2652
+ },
2653
+ chooseVideo(option) {
2654
+ const compressed = option.compressed !== false;
2655
+ const maxDuration = Number.isFinite(option.maxDuration) ? Math.max(1, Math.trunc(option.maxDuration ?? 60)) : 60;
2656
+ const sourceType = Array.isArray(option.sourceType) && option.sourceType.length > 0 ? option.sourceType.filter((item) => typeof item === "string") : ["album", "camera"];
2657
+ const payload = JSON.stringify({ config: {
2658
+ compressed,
2659
+ duration: Math.min(maxDuration, compressed ? 18 : 36),
2660
+ height: compressed ? 360 : 720,
2661
+ maxDuration,
2662
+ sourceType: [...sourceType],
2663
+ width: compressed ? 640 : 1280
2664
+ } });
2665
+ const tempFilePath = this.createTempFile(payload, "headless://wxfile/temp/chosen-video-01.mp4");
2666
+ return {
2667
+ duration: Math.min(maxDuration, compressed ? 18 : 36),
2668
+ errMsg: "chooseVideo:ok",
2669
+ height: compressed ? 360 : 720,
2670
+ size: payload.length,
2671
+ tempFilePath,
2672
+ width: compressed ? 640 : 1280
2673
+ };
2674
+ },
2675
+ compressImage(option) {
2676
+ const fileContent = files.get(option.src);
2677
+ if (fileContent == null) throw new Error(`compressImage:fail file not found: ${option.src}`);
2678
+ const sourceSize = inferImageSize(fileContent);
2679
+ const sourceType = inferImageType(option.src, fileContent);
2680
+ const width = Number.isFinite(option.compressedWidth) ? Math.max(1, Math.trunc(option.compressedWidth ?? sourceSize.width)) : Math.max(1, sourceSize.width);
2681
+ const height = Number.isFinite(option.compressedHeight) ? Math.max(1, Math.trunc(option.compressedHeight ?? sourceSize.height)) : Math.max(1, sourceSize.height);
2682
+ const normalizedType = sourceType === "unknown" ? "jpg" : sourceType;
2683
+ const fileExtension = normalizedType === "jpeg" ? "jpg" : normalizedType;
2684
+ const payload = buildImageTempFilePayload(normalizedType, width, height, { quality: Number.isFinite(option.quality) ? Number(option.quality) : void 0 });
2685
+ return {
2686
+ errMsg: "compressImage:ok",
2687
+ tempFilePath: this.createTempFile(payload, `headless://wxfile/temp/compressed-image-${String(fileId + 1).padStart(2, "0")}.${fileExtension}`)
2688
+ };
2689
+ },
2115
2690
  getNetworkType() {
2116
2691
  return {
2117
2692
  errMsg: "getNetworkType:ok",
2118
2693
  networkType
2119
2694
  };
2120
2695
  },
2696
+ getImageInfo(option) {
2697
+ const fileContent = files.get(option.src);
2698
+ if (fileContent == null) throw new Error(`getImageInfo:fail file not found: ${option.src}`);
2699
+ const size = inferImageSize(fileContent);
2700
+ return {
2701
+ errMsg: "getImageInfo:ok",
2702
+ height: size.height,
2703
+ orientation: "up",
2704
+ path: option.src,
2705
+ type: inferImageType(option.src, fileContent),
2706
+ width: size.width
2707
+ };
2708
+ },
2709
+ getVideoInfo(option) {
2710
+ const fileContent = files.get(option.src);
2711
+ if (fileContent == null) throw new Error(`getVideoInfo:fail file not found: ${option.src}`);
2712
+ const info = inferVideoInfo(option.src, fileContent);
2713
+ return {
2714
+ bitrate: info.bitrate,
2715
+ duration: info.duration,
2716
+ errMsg: "getVideoInfo:ok",
2717
+ fps: info.fps,
2718
+ height: info.height,
2719
+ orientation: "up",
2720
+ size: info.size,
2721
+ type: info.type,
2722
+ width: info.width
2723
+ };
2724
+ },
2121
2725
  getModalLogs() {
2122
2726
  return modalLogs.map((entry) => ({
2123
2727
  ...entry,
@@ -2152,6 +2756,15 @@ function createHeadlessWxState() {
2152
2756
  getStorageSnapshot() {
2153
2757
  return Object.fromEntries(Array.from(storage.entries(), ([key, value]) => [key, cloneValue$1(value)]));
2154
2758
  },
2759
+ getClipboardData() {
2760
+ return {
2761
+ data: clipboardData,
2762
+ errMsg: "getClipboardData:ok"
2763
+ };
2764
+ },
2765
+ getClipboardSnapshot() {
2766
+ return { data: clipboardData };
2767
+ },
2155
2768
  getStorageSync(key) {
2156
2769
  return cloneValue$1(storage.get(key));
2157
2770
  },
@@ -2161,6 +2774,21 @@ function createHeadlessWxState() {
2161
2774
  getLoading() {
2162
2775
  return loading ? { ...loading } : null;
2163
2776
  },
2777
+ getPreviewImage() {
2778
+ return previewImage ? {
2779
+ current: previewImage.current,
2780
+ urls: [...previewImage.urls],
2781
+ visible: previewImage.visible
2782
+ } : null;
2783
+ },
2784
+ getOpenedDocument() {
2785
+ return openedDocument ? {
2786
+ filePath: openedDocument.filePath,
2787
+ fileType: openedDocument.fileType,
2788
+ showMenu: openedDocument.showMenu,
2789
+ visible: openedDocument.visible
2790
+ } : null;
2791
+ },
2164
2792
  hideShareMenu() {
2165
2793
  shareMenu = {
2166
2794
  ...shareMenu,
@@ -2230,6 +2858,27 @@ function createHeadlessWxState() {
2230
2858
  onNetworkStatusChange(callback) {
2231
2859
  networkStatusChangeCallbacks.add(callback);
2232
2860
  },
2861
+ openDocument(option) {
2862
+ const normalizedPath = normalizeFsPath(option.filePath);
2863
+ if (!files.has(normalizedPath)) throw new Error(`openDocument:fail no such file or directory, open '${normalizedPath}'`);
2864
+ openedDocument = {
2865
+ filePath: normalizedPath,
2866
+ fileType: typeof option.fileType === "string" && option.fileType.trim() !== "" ? normalizeFileExtension(option.fileType) : inferDocumentFileType(normalizedPath),
2867
+ showMenu: option.showMenu !== false,
2868
+ visible: true
2869
+ };
2870
+ return { errMsg: "openDocument:ok" };
2871
+ },
2872
+ previewImage(option) {
2873
+ const urls = Array.isArray(option.urls) ? option.urls.filter((item) => typeof item === "string" && item.trim() !== "") : [];
2874
+ if (urls.length === 0) throw new Error("previewImage:fail invalid urls");
2875
+ previewImage = {
2876
+ current: typeof option.current === "string" && option.current.trim() !== "" ? option.current : urls[0],
2877
+ urls: [...urls],
2878
+ visible: true
2879
+ };
2880
+ return { errMsg: "previewImage:ok" };
2881
+ },
2233
2882
  removeStorageSync(key) {
2234
2883
  storage.delete(key);
2235
2884
  },
@@ -2277,6 +2926,14 @@ function createHeadlessWxState() {
2277
2926
  removeSavedFile(option) {
2278
2927
  return removeSavedFile(option.filePath);
2279
2928
  },
2929
+ saveImageToPhotosAlbum(option) {
2930
+ if (files.get(option.filePath) == null) throw new Error(`saveImageToPhotosAlbum:fail file not found: ${option.filePath}`);
2931
+ return { errMsg: "saveImageToPhotosAlbum:ok" };
2932
+ },
2933
+ saveVideoToPhotosAlbum(option) {
2934
+ if (files.get(option.filePath) == null) throw new Error(`saveVideoToPhotosAlbum:fail file not found: ${option.filePath}`);
2935
+ return { errMsg: "saveVideoToPhotosAlbum:ok" };
2936
+ },
2280
2937
  saveFile(option) {
2281
2938
  const fileContent = files.get(option.tempFilePath);
2282
2939
  if (fileContent == null) throw new Error(`saveFile:fail tempFilePath not found: ${option.tempFilePath}`);
@@ -2292,6 +2949,10 @@ function createHeadlessWxState() {
2292
2949
  setStorageSync(key, value) {
2293
2950
  storage.set(key, cloneValue$1(value));
2294
2951
  },
2952
+ setClipboardData(option) {
2953
+ clipboardData = String(option.data);
2954
+ return { errMsg: "setClipboardData:ok" };
2955
+ },
2295
2956
  setFile(filePath, fileContent) {
2296
2957
  const normalizedPath = normalizeFsPath(filePath);
2297
2958
  ensureDirectoryTree(normalizedPath);
@@ -2435,10 +3096,11 @@ function createHeadlessWxState() {
2435
3096
  }
2436
3097
  //#endregion
2437
3098
  //#region src/view/selectors.ts
2438
- const WHITESPACE_RE = /\s+/;
3099
+ const WHITESPACE_RE$2 = /\s+/;
2439
3100
  const DATA_ATTR_SELECTOR_RE$2 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
3101
+ const COMPOUND_SELECTOR_PART_RE$2 = /#[\w-]+|\.[\w-]+|\[data-[^=\]]+="[^"]*"\]|[A-Za-z][\w-]*/g;
2440
3102
  function getClassList(node) {
2441
- return String(node.attribs?.class ?? "").split(WHITESPACE_RE).map((item) => item.trim()).filter(Boolean);
3103
+ return String(node.attribs?.class ?? "").split(WHITESPACE_RE$2).map((item) => item.trim()).filter(Boolean);
2442
3104
  }
2443
3105
  function matchesSimpleSelector(node, selector) {
2444
3106
  if (node.type !== "tag") return false;
@@ -2452,6 +3114,15 @@ function matchesSimpleSelector(node, selector) {
2452
3114
  }
2453
3115
  return node.name === selector;
2454
3116
  }
3117
+ function parseCompoundSelector$2(selector) {
3118
+ const parts = selector.match(COMPOUND_SELECTOR_PART_RE$2) ?? [];
3119
+ return parts.join("") === selector ? parts : [];
3120
+ }
3121
+ function matchesSelectorToken(node, selector) {
3122
+ const simpleSelectors = parseCompoundSelector$2(selector);
3123
+ if (simpleSelectors.length === 0) return false;
3124
+ return simpleSelectors.every((simpleSelector) => matchesSimpleSelector(node, simpleSelector));
3125
+ }
2455
3126
  function collectDescendants(node, into) {
2456
3127
  for (const child of node.children ?? []) {
2457
3128
  into.push(child);
@@ -2459,7 +3130,7 @@ function collectDescendants(node, into) {
2459
3130
  }
2460
3131
  }
2461
3132
  function querySelectorAll(root, selector) {
2462
- const parts = selector.trim().split(WHITESPACE_RE).filter(Boolean);
3133
+ const parts = selector.trim().split(WHITESPACE_RE$2).filter(Boolean);
2463
3134
  if (parts.length === 0) return [];
2464
3135
  let current = [root];
2465
3136
  for (const part of parts) {
@@ -2468,7 +3139,7 @@ function querySelectorAll(root, selector) {
2468
3139
  const candidates = [];
2469
3140
  if (part === "page" && node.type === "tag" && node.name === "page") candidates.push(node);
2470
3141
  collectDescendants(node, candidates);
2471
- for (const candidate of candidates) if (matchesSimpleSelector(candidate, part)) next.push(candidate);
3142
+ for (const candidate of candidates) if (matchesSelectorToken(candidate, part)) next.push(candidate);
2472
3143
  }
2473
3144
  current = next;
2474
3145
  }
@@ -2476,22 +3147,22 @@ function querySelectorAll(root, selector) {
2476
3147
  }
2477
3148
  //#endregion
2478
3149
  //#region src/view/nodeHandle.ts
2479
- const DATASET_NAME_RE$2 = /-([a-z])/g;
3150
+ const DATASET_NAME_RE$3 = /-([a-z])/g;
2480
3151
  function escapeText$2(text) {
2481
3152
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
2482
3153
  }
2483
- function toDatasetKey$2(attributeName) {
2484
- return attributeName.slice(5).replace(DATASET_NAME_RE$2, (_match, char) => char.toUpperCase());
3154
+ function toDatasetKey$3(attributeName) {
3155
+ return attributeName.slice(5).replace(DATASET_NAME_RE$3, (_match, char) => char.toUpperCase());
2485
3156
  }
2486
- function collectDataset$2(node) {
3157
+ function collectDataset$3(node) {
2487
3158
  const dataset = {};
2488
3159
  for (const [key, value] of Object.entries(node.attribs ?? {})) {
2489
3160
  if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
2490
- dataset[toDatasetKey$2(key)] = value;
3161
+ dataset[toDatasetKey$3(key)] = value;
2491
3162
  }
2492
3163
  return dataset;
2493
3164
  }
2494
- function resolveEventBinding(node, eventName) {
3165
+ function resolveEventBinding$1(node, eventName) {
2495
3166
  const normalizedEventName = eventName.trim();
2496
3167
  if (!normalizedEventName) return null;
2497
3168
  const bindingAttrs = [
@@ -2506,8 +3177,8 @@ function resolveEventBinding(node, eventName) {
2506
3177
  }
2507
3178
  return null;
2508
3179
  }
2509
- function createEventPayload(node, eventName, event) {
2510
- const dataset = collectDataset$2(node);
3180
+ function createEventPayload$1(node, eventName, event) {
3181
+ const dataset = collectDataset$3(node);
2511
3182
  const nodeId = node.attribs?.id ?? "";
2512
3183
  return {
2513
3184
  bubbles: false,
@@ -2572,7 +3243,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
2572
3243
  return this.node.attribs?.[name];
2573
3244
  }
2574
3245
  async dataset() {
2575
- return collectDataset$2(this.node);
3246
+ return collectDataset$3(this.node);
2576
3247
  }
2577
3248
  async scope() {
2578
3249
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
@@ -2602,9 +3273,9 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
2602
3273
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
2603
3274
  const normalizedEventName = eventName.trim();
2604
3275
  if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
2605
- const methodName = resolveEventBinding(this.node, normalizedEventName);
3276
+ const methodName = resolveEventBinding$1(this.node, normalizedEventName);
2606
3277
  if (!methodName) throw new Error(`No ${normalizedEventName} binding was found on <${this.node.name ?? "unknown"}> in headless testing runtime.`);
2607
- return await this.interactions.callMethod(this.node.attribs?.["data-sim-scope"] ?? null, methodName, createEventPayload(this.node, normalizedEventName, event));
3278
+ return await this.interactions.callMethod(this.node.attribs?.["data-sim-scope"] ?? null, methodName, createEventPayload$1(this.node, normalizedEventName, event));
2608
3279
  }
2609
3280
  async tap(event = {}) {
2610
3281
  return await this.trigger("tap", event);
@@ -2688,18 +3359,18 @@ function renderPageTree(project, page) {
2688
3359
  }
2689
3360
  //#endregion
2690
3361
  //#region src/view/selectorQuery.ts
2691
- const DATASET_NAME_RE$1 = /-([a-z])/g;
3362
+ const DATASET_NAME_RE$2 = /-([a-z])/g;
2692
3363
  const LEADING_MARK_PREFIX_RE = /^mark[:\-]?/;
2693
3364
  const MARK_NAME_RE = /[:\-]([a-z])/g;
2694
- const NUMERIC_LIKE_VALUE_RE = /-?\d+(?:\.\d+)?/;
2695
- function toDatasetKey$1(attributeName) {
2696
- return attributeName.slice(5).replace(DATASET_NAME_RE$1, (_match, char) => char.toUpperCase());
3365
+ const NUMERIC_LIKE_VALUE_RE$1 = /-?\d+(?:\.\d+)?/;
3366
+ function toDatasetKey$2(attributeName) {
3367
+ return attributeName.slice(5).replace(DATASET_NAME_RE$2, (_match, char) => char.toUpperCase());
2697
3368
  }
2698
- function collectDataset$1(node) {
3369
+ function collectDataset$2(node) {
2699
3370
  const dataset = {};
2700
3371
  for (const [key, value] of Object.entries(node.attribs ?? {})) {
2701
3372
  if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
2702
- dataset[toDatasetKey$1(key)] = value;
3373
+ dataset[toDatasetKey$2(key)] = value;
2703
3374
  }
2704
3375
  return dataset;
2705
3376
  }
@@ -2728,7 +3399,7 @@ function findNodeByScopeId(root, scopeId) {
2728
3399
  }
2729
3400
  return null;
2730
3401
  }
2731
- function parseStyleDeclarations(styleValue) {
3402
+ function parseStyleDeclarations$1(styleValue) {
2732
3403
  const declarations = {};
2733
3404
  if (!styleValue) return declarations;
2734
3405
  for (const declaration of styleValue.split(";")) {
@@ -2739,17 +3410,17 @@ function parseStyleDeclarations(styleValue) {
2739
3410
  }
2740
3411
  return declarations;
2741
3412
  }
2742
- function parseNumericLikeValue(value) {
3413
+ function parseNumericLikeValue$1(value) {
2743
3414
  if (!value) return 0;
2744
- const match = value.match(NUMERIC_LIKE_VALUE_RE);
3415
+ const match = value.match(NUMERIC_LIKE_VALUE_RE$1);
2745
3416
  return match ? Number(match[0]) : 0;
2746
3417
  }
2747
- function resolveRect(node) {
2748
- const style = parseStyleDeclarations(node.attribs?.style);
2749
- const left = parseNumericLikeValue(node.attribs?.["data-sim-left"] ?? style.left);
2750
- const top = parseNumericLikeValue(node.attribs?.["data-sim-top"] ?? style.top);
2751
- const width = parseNumericLikeValue(node.attribs?.["data-sim-width"] ?? style.width);
2752
- const height = parseNumericLikeValue(node.attribs?.["data-sim-height"] ?? style.height);
3418
+ function resolveRect$1(node) {
3419
+ const style = parseStyleDeclarations$1(node.attribs?.style);
3420
+ const left = parseNumericLikeValue$1(node.attribs?.["data-sim-left"] ?? style.left);
3421
+ const top = parseNumericLikeValue$1(node.attribs?.["data-sim-top"] ?? style.top);
3422
+ const width = parseNumericLikeValue$1(node.attribs?.["data-sim-width"] ?? style.width);
3423
+ const height = parseNumericLikeValue$1(node.attribs?.["data-sim-height"] ?? style.height);
2753
3424
  return {
2754
3425
  bottom: top + height,
2755
3426
  height,
@@ -2759,10 +3430,16 @@ function resolveRect(node) {
2759
3430
  width
2760
3431
  };
2761
3432
  }
3433
+ function resolveSelectorScrollTop(root, selector) {
3434
+ const normalizedSelector = selector?.trim();
3435
+ if (!normalizedSelector) return null;
3436
+ const match = querySelectorAll(root, normalizedSelector)[0];
3437
+ return match ? resolveRect$1(match).top : null;
3438
+ }
2762
3439
  function resolveScrollOffset(node) {
2763
3440
  return {
2764
- scrollLeft: parseNumericLikeValue(node.attribs?.["data-sim-scroll-left"]),
2765
- scrollTop: parseNumericLikeValue(node.attribs?.["data-sim-scroll-top"])
3441
+ scrollLeft: parseNumericLikeValue$1(node.attribs?.["data-sim-scroll-left"]),
3442
+ scrollTop: parseNumericLikeValue$1(node.attribs?.["data-sim-scroll-top"])
2766
3443
  };
2767
3444
  }
2768
3445
  function resolvePropertyValue(node, propertyName) {
@@ -2770,7 +3447,7 @@ function resolvePropertyValue(node, propertyName) {
2770
3447
  if (!normalizedPropertyName) return;
2771
3448
  if (normalizedPropertyName === "id") return node.attribs?.id ?? "";
2772
3449
  if (normalizedPropertyName === "class") return node.attribs?.class ?? "";
2773
- if (normalizedPropertyName === "dataset") return collectDataset$1(node);
3450
+ if (normalizedPropertyName === "dataset") return collectDataset$2(node);
2774
3451
  return node.attribs?.[normalizedPropertyName];
2775
3452
  }
2776
3453
  function pickProperties(node, propertyNames) {
@@ -2779,18 +3456,18 @@ function pickProperties(node, propertyNames) {
2779
3456
  return result;
2780
3457
  }
2781
3458
  function pickComputedStyle(node, propertyNames) {
2782
- const style = parseStyleDeclarations(node.attribs?.style);
3459
+ const style = parseStyleDeclarations$1(node.attribs?.style);
2783
3460
  const result = {};
2784
3461
  for (const propertyName of propertyNames) result[propertyName] = style[propertyName] ?? "";
2785
3462
  return result;
2786
3463
  }
2787
- function resolveFieldsResult(node, fields, _options) {
3464
+ function resolveFieldsResult(node, fields, options) {
2788
3465
  const result = {};
2789
3466
  if (fields.id) result.id = node.attribs?.id ?? "";
2790
- if (fields.dataset) result.dataset = collectDataset$1(node);
3467
+ if (fields.dataset) result.dataset = collectDataset$2(node);
2791
3468
  if (fields.mark) result.mark = collectMark(node);
2792
3469
  if (fields.rect || fields.size) {
2793
- const rect = resolveRect(node);
3470
+ const rect = resolveRect$1(node);
2794
3471
  if (fields.rect) Object.assign(result, rect);
2795
3472
  if (fields.size) {
2796
3473
  result.width = rect.width;
@@ -2800,7 +3477,7 @@ function resolveFieldsResult(node, fields, _options) {
2800
3477
  if (fields.scrollOffset) Object.assign(result, resolveScrollOffset(node));
2801
3478
  if (Array.isArray(fields.properties) && fields.properties.length > 0) Object.assign(result, pickProperties(node, fields.properties));
2802
3479
  if (Array.isArray(fields.computedStyle) && fields.computedStyle.length > 0) Object.assign(result, pickComputedStyle(node, fields.computedStyle));
2803
- if (fields.context) result.context = { type: "unsupported-context" };
3480
+ if (fields.context) result.context = options.resolveContext?.(node) ?? { type: "unsupported-context" };
2804
3481
  if (fields.node) result.node = { type: node.name ?? "unknown" };
2805
3482
  return result;
2806
3483
  }
@@ -2843,10 +3520,755 @@ function resolveSelectorQueryScopeRoot(root, scopeId) {
2843
3520
  return scopedNode ? createScopedRoot(scopedNode) : root;
2844
3521
  }
2845
3522
  //#endregion
3523
+ //#region src/view/animation.ts
3524
+ const DEFAULT_STEP_OPTION = {
3525
+ delay: 0,
3526
+ duration: 400,
3527
+ timingFunction: "linear",
3528
+ transformOrigin: "50% 50% 0"
3529
+ };
3530
+ function normalizeStepOption(option) {
3531
+ return {
3532
+ delay: option?.delay ?? DEFAULT_STEP_OPTION.delay,
3533
+ duration: option?.duration ?? DEFAULT_STEP_OPTION.duration,
3534
+ timingFunction: option?.timingFunction ?? DEFAULT_STEP_OPTION.timingFunction,
3535
+ transformOrigin: option?.transformOrigin ?? DEFAULT_STEP_OPTION.transformOrigin
3536
+ };
3537
+ }
3538
+ function normalizeLength(value) {
3539
+ if (typeof value === "number") return `${value}px`;
3540
+ return value ?? "0px";
3541
+ }
3542
+ function createAction(type, args) {
3543
+ return {
3544
+ args,
3545
+ type
3546
+ };
3547
+ }
3548
+ function createHeadlessAnimation(defaultOption) {
3549
+ const baseOption = normalizeStepOption(defaultOption);
3550
+ let currentActions = [];
3551
+ let queue = [];
3552
+ let animation;
3553
+ const append = (type, args) => {
3554
+ currentActions.push(createAction(type, args));
3555
+ return animation;
3556
+ };
3557
+ animation = {
3558
+ backgroundColor(value) {
3559
+ return append("backgroundColor", [value]);
3560
+ },
3561
+ bottom(value) {
3562
+ return append("bottom", [normalizeLength(value)]);
3563
+ },
3564
+ export() {
3565
+ const exported = queue.map((item) => ({
3566
+ animates: item.animates.map((action) => ({
3567
+ args: [...action.args],
3568
+ type: action.type
3569
+ })),
3570
+ option: { ...item.option }
3571
+ }));
3572
+ queue = [];
3573
+ currentActions = [];
3574
+ return { actions: exported };
3575
+ },
3576
+ height(value) {
3577
+ return append("height", [normalizeLength(value)]);
3578
+ },
3579
+ left(value) {
3580
+ return append("left", [normalizeLength(value)]);
3581
+ },
3582
+ opacity(value) {
3583
+ return append("opacity", [value]);
3584
+ },
3585
+ right(value) {
3586
+ return append("right", [normalizeLength(value)]);
3587
+ },
3588
+ rotate(angle) {
3589
+ return append("rotate", [`${angle}deg`]);
3590
+ },
3591
+ scale(sx, sy) {
3592
+ return append("scale", [sx, sy ?? sx]);
3593
+ },
3594
+ step(option) {
3595
+ queue.push({
3596
+ animates: currentActions.map((action) => ({
3597
+ args: [...action.args],
3598
+ type: action.type
3599
+ })),
3600
+ option: {
3601
+ ...baseOption,
3602
+ ...option ?? {}
3603
+ }
3604
+ });
3605
+ currentActions = [];
3606
+ return animation;
3607
+ },
3608
+ top(value) {
3609
+ return append("top", [normalizeLength(value)]);
3610
+ },
3611
+ translate(tx, ty) {
3612
+ return append("translate", [normalizeLength(tx), normalizeLength(ty)]);
3613
+ },
3614
+ translate3d(tx, ty, tz) {
3615
+ return append("translate3d", [
3616
+ normalizeLength(tx),
3617
+ normalizeLength(ty),
3618
+ normalizeLength(tz)
3619
+ ]);
3620
+ },
3621
+ translateX(translation) {
3622
+ return append("translateX", [normalizeLength(translation)]);
3623
+ },
3624
+ translateY(translation) {
3625
+ return append("translateY", [normalizeLength(translation)]);
3626
+ },
3627
+ translateZ(translation) {
3628
+ return append("translateZ", [normalizeLength(translation)]);
3629
+ },
3630
+ width(value) {
3631
+ return append("width", [normalizeLength(value)]);
3632
+ }
3633
+ };
3634
+ return animation;
3635
+ }
3636
+ //#endregion
3637
+ //#region src/view/canvasContext.ts
3638
+ function findCanvasNode(root, canvasId) {
3639
+ if (root.type === "tag" && root.name === "canvas" && root.attribs?.["canvas-id"] === canvasId) return root;
3640
+ for (const child of root.children ?? []) {
3641
+ const match = findCanvasNode(child, canvasId);
3642
+ if (match) return match;
3643
+ }
3644
+ return null;
3645
+ }
3646
+ function cloneCall(call) {
3647
+ return {
3648
+ args: call.args.map((arg) => Array.isArray(arg) ? [...arg] : arg),
3649
+ type: call.type
3650
+ };
3651
+ }
3652
+ function createHeadlessCanvasContext(driver, canvasId, scope) {
3653
+ const defaultState = {
3654
+ fillStyle: "#000000",
3655
+ fontSize: 16,
3656
+ globalAlpha: 1,
3657
+ lineCap: "butt",
3658
+ lineDash: [],
3659
+ lineDashOffset: 0,
3660
+ lineJoin: "miter",
3661
+ miterLimit: 10,
3662
+ lineWidth: 1,
3663
+ shadowBlur: 0,
3664
+ shadowColor: "#000000",
3665
+ shadowOffsetX: 0,
3666
+ shadowOffsetY: 0,
3667
+ strokeStyle: "#000000",
3668
+ textAlign: "start",
3669
+ textBaseline: "alphabetic"
3670
+ };
3671
+ let state = { ...defaultState };
3672
+ let stateStack = [];
3673
+ let drawCalls = [];
3674
+ let snapshot = {
3675
+ canvasId,
3676
+ drawCalls: [],
3677
+ fillStyle: state.fillStyle,
3678
+ fontSize: state.fontSize,
3679
+ globalAlpha: state.globalAlpha,
3680
+ lineCap: state.lineCap,
3681
+ lineDash: [...state.lineDash],
3682
+ lineDashOffset: state.lineDashOffset,
3683
+ lineJoin: state.lineJoin,
3684
+ miterLimit: state.miterLimit,
3685
+ lineWidth: state.lineWidth,
3686
+ reserve: false,
3687
+ shadowBlur: state.shadowBlur,
3688
+ shadowColor: state.shadowColor,
3689
+ shadowOffsetX: state.shadowOffsetX,
3690
+ shadowOffsetY: state.shadowOffsetY,
3691
+ strokeStyle: state.strokeStyle,
3692
+ textAlign: state.textAlign,
3693
+ textBaseline: state.textBaseline
3694
+ };
3695
+ const resolveCanvas = () => {
3696
+ const scopeResolution = driver.resolveScope(scope);
3697
+ if (scopeResolution.kind === "missing") return null;
3698
+ const rendered = driver.renderCurrentPage();
3699
+ const root = scopeResolution.kind === "component" ? resolveSelectorQueryScopeRoot(rendered.root, scopeResolution.scopeId) : rendered.root;
3700
+ return root ? findCanvasNode(root, canvasId) : null;
3701
+ };
3702
+ const ensureCanvas = () => {
3703
+ const node = resolveCanvas();
3704
+ if (!node) throw new Error(`Canvas with canvas-id "${canvasId}" was not found in headless runtime.`);
3705
+ return node;
3706
+ };
3707
+ const record = (type, args) => {
3708
+ ensureCanvas();
3709
+ drawCalls.push({
3710
+ args,
3711
+ type
3712
+ });
3713
+ };
3714
+ return {
3715
+ arc(x, y, r, sAngle, eAngle, counterclockwise) {
3716
+ record("arc", [
3717
+ x,
3718
+ y,
3719
+ r,
3720
+ sAngle,
3721
+ eAngle,
3722
+ Boolean(counterclockwise)
3723
+ ]);
3724
+ },
3725
+ arcTo(x1, y1, x2, y2, radius) {
3726
+ record("arcTo", [
3727
+ x1,
3728
+ y1,
3729
+ x2,
3730
+ y2,
3731
+ radius
3732
+ ]);
3733
+ },
3734
+ bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
3735
+ record("bezierCurveTo", [
3736
+ cp1x,
3737
+ cp1y,
3738
+ cp2x,
3739
+ cp2y,
3740
+ x,
3741
+ y
3742
+ ]);
3743
+ },
3744
+ __getSnapshot() {
3745
+ return {
3746
+ canvasId: snapshot.canvasId,
3747
+ drawCalls: snapshot.drawCalls.map(cloneCall),
3748
+ fillStyle: snapshot.fillStyle,
3749
+ fontSize: snapshot.fontSize,
3750
+ globalAlpha: snapshot.globalAlpha,
3751
+ lineCap: snapshot.lineCap,
3752
+ lineDash: [...snapshot.lineDash],
3753
+ lineDashOffset: snapshot.lineDashOffset,
3754
+ lineJoin: snapshot.lineJoin,
3755
+ miterLimit: snapshot.miterLimit,
3756
+ lineWidth: snapshot.lineWidth,
3757
+ reserve: snapshot.reserve,
3758
+ shadowBlur: snapshot.shadowBlur,
3759
+ shadowColor: snapshot.shadowColor,
3760
+ shadowOffsetX: snapshot.shadowOffsetX,
3761
+ shadowOffsetY: snapshot.shadowOffsetY,
3762
+ strokeStyle: snapshot.strokeStyle,
3763
+ textAlign: snapshot.textAlign,
3764
+ textBaseline: snapshot.textBaseline
3765
+ };
3766
+ },
3767
+ beginPath() {
3768
+ record("beginPath", []);
3769
+ },
3770
+ clearRect(x, y, width, height) {
3771
+ record("clearRect", [
3772
+ x,
3773
+ y,
3774
+ width,
3775
+ height
3776
+ ]);
3777
+ },
3778
+ clip(fillRule) {
3779
+ record("clip", fillRule == null ? [] : [fillRule]);
3780
+ },
3781
+ closePath() {
3782
+ record("closePath", []);
3783
+ },
3784
+ draw(reserve, callback) {
3785
+ ensureCanvas();
3786
+ snapshot = {
3787
+ canvasId,
3788
+ drawCalls: reserve ? [...snapshot.drawCalls.map(cloneCall), ...drawCalls.map(cloneCall)] : drawCalls.map(cloneCall),
3789
+ fillStyle: state.fillStyle,
3790
+ fontSize: state.fontSize,
3791
+ globalAlpha: state.globalAlpha,
3792
+ lineCap: state.lineCap,
3793
+ lineDash: [...state.lineDash],
3794
+ lineDashOffset: state.lineDashOffset,
3795
+ lineJoin: state.lineJoin,
3796
+ miterLimit: state.miterLimit,
3797
+ lineWidth: state.lineWidth,
3798
+ reserve: Boolean(reserve),
3799
+ shadowBlur: state.shadowBlur,
3800
+ shadowColor: state.shadowColor,
3801
+ shadowOffsetX: state.shadowOffsetX,
3802
+ shadowOffsetY: state.shadowOffsetY,
3803
+ strokeStyle: state.strokeStyle,
3804
+ textAlign: state.textAlign,
3805
+ textBaseline: state.textBaseline
3806
+ };
3807
+ drawCalls = [];
3808
+ state = { ...defaultState };
3809
+ stateStack = [];
3810
+ callback?.();
3811
+ },
3812
+ drawImage(image, ...args) {
3813
+ record("drawImage", [image, ...args]);
3814
+ },
3815
+ fill(fillRule) {
3816
+ record("fill", fillRule == null ? [] : [fillRule]);
3817
+ },
3818
+ fillRect(x, y, width, height) {
3819
+ record("fillRect", [
3820
+ x,
3821
+ y,
3822
+ width,
3823
+ height
3824
+ ]);
3825
+ },
3826
+ fillText(text, x, y, maxWidth) {
3827
+ record("fillText", maxWidth == null ? [
3828
+ text,
3829
+ x,
3830
+ y
3831
+ ] : [
3832
+ text,
3833
+ x,
3834
+ y,
3835
+ maxWidth
3836
+ ]);
3837
+ },
3838
+ lineTo(x, y) {
3839
+ record("lineTo", [x, y]);
3840
+ },
3841
+ measureText(text) {
3842
+ return { width: text.length * state.fontSize * .5 };
3843
+ },
3844
+ moveTo(x, y) {
3845
+ record("moveTo", [x, y]);
3846
+ },
3847
+ quadraticCurveTo(cpx, cpy, x, y) {
3848
+ record("quadraticCurveTo", [
3849
+ cpx,
3850
+ cpy,
3851
+ x,
3852
+ y
3853
+ ]);
3854
+ },
3855
+ rect(x, y, width, height) {
3856
+ record("rect", [
3857
+ x,
3858
+ y,
3859
+ width,
3860
+ height
3861
+ ]);
3862
+ },
3863
+ restore() {
3864
+ state = stateStack.pop() ?? { ...defaultState };
3865
+ record("restore", []);
3866
+ },
3867
+ rotate(rotate) {
3868
+ record("rotate", [rotate]);
3869
+ },
3870
+ save() {
3871
+ stateStack.push({ ...state });
3872
+ record("save", []);
3873
+ },
3874
+ scale(scaleWidth, scaleHeight) {
3875
+ record("scale", [scaleWidth, scaleHeight]);
3876
+ },
3877
+ setFillStyle(value) {
3878
+ state.fillStyle = String(value);
3879
+ record("setFillStyle", [value]);
3880
+ },
3881
+ setFontSize(fontSize) {
3882
+ state.fontSize = Number(fontSize);
3883
+ record("setFontSize", [fontSize]);
3884
+ },
3885
+ setGlobalAlpha(value) {
3886
+ state.globalAlpha = Number(value);
3887
+ record("setGlobalAlpha", [value]);
3888
+ },
3889
+ setLineCap(value) {
3890
+ state.lineCap = String(value);
3891
+ record("setLineCap", [value]);
3892
+ },
3893
+ setLineDash(pattern, offset) {
3894
+ state.lineDash = pattern.map((item) => Number(item));
3895
+ state.lineDashOffset = offset == null ? 0 : Number(offset);
3896
+ record("setLineDash", offset == null ? [pattern.map((item) => Number(item))] : [pattern.map((item) => Number(item)), Number(offset)]);
3897
+ },
3898
+ setLineJoin(value) {
3899
+ state.lineJoin = String(value);
3900
+ record("setLineJoin", [value]);
3901
+ },
3902
+ setMiterLimit(value) {
3903
+ state.miterLimit = Number(value);
3904
+ record("setMiterLimit", [value]);
3905
+ },
3906
+ setLineWidth(value) {
3907
+ state.lineWidth = Number(value);
3908
+ record("setLineWidth", [value]);
3909
+ },
3910
+ setShadow(offsetX, offsetY, blur, color) {
3911
+ state.shadowOffsetX = Number(offsetX);
3912
+ state.shadowOffsetY = Number(offsetY);
3913
+ state.shadowBlur = Number(blur);
3914
+ state.shadowColor = String(color);
3915
+ record("setShadow", [
3916
+ offsetX,
3917
+ offsetY,
3918
+ blur,
3919
+ color
3920
+ ]);
3921
+ },
3922
+ setStrokeStyle(value) {
3923
+ state.strokeStyle = String(value);
3924
+ record("setStrokeStyle", [value]);
3925
+ },
3926
+ setTextAlign(value) {
3927
+ state.textAlign = String(value);
3928
+ record("setTextAlign", [value]);
3929
+ },
3930
+ setTextBaseline(value) {
3931
+ state.textBaseline = String(value);
3932
+ record("setTextBaseline", [value]);
3933
+ },
3934
+ stroke() {
3935
+ record("stroke", []);
3936
+ },
3937
+ strokeRect(x, y, width, height) {
3938
+ record("strokeRect", [
3939
+ x,
3940
+ y,
3941
+ width,
3942
+ height
3943
+ ]);
3944
+ },
3945
+ strokeText(text, x, y, maxWidth) {
3946
+ record("strokeText", maxWidth == null ? [
3947
+ text,
3948
+ x,
3949
+ y
3950
+ ] : [
3951
+ text,
3952
+ x,
3953
+ y,
3954
+ maxWidth
3955
+ ]);
3956
+ },
3957
+ translate(x, y) {
3958
+ record("translate", [x, y]);
3959
+ }
3960
+ };
3961
+ }
3962
+ //#endregion
3963
+ //#region src/view/intersectionObserver.ts
3964
+ const NUMERIC_LIKE_VALUE_RE = /-?\d+(?:\.\d+)?/;
3965
+ function normalizeMargins(margins) {
3966
+ return {
3967
+ bottom: Number(margins?.bottom) || 0,
3968
+ left: Number(margins?.left) || 0,
3969
+ right: Number(margins?.right) || 0,
3970
+ top: Number(margins?.top) || 0
3971
+ };
3972
+ }
3973
+ function parseStyleDeclarations(styleValue) {
3974
+ const declarations = {};
3975
+ if (!styleValue) return declarations;
3976
+ for (const declaration of styleValue.split(";")) {
3977
+ const [rawProperty, ...rawValueParts] = declaration.split(":");
3978
+ const property = rawProperty?.trim();
3979
+ if (!property) continue;
3980
+ declarations[property] = rawValueParts.join(":").trim();
3981
+ }
3982
+ return declarations;
3983
+ }
3984
+ function parseNumericLikeValue(value) {
3985
+ if (!value) return 0;
3986
+ const match = value.match(NUMERIC_LIKE_VALUE_RE);
3987
+ return match ? Number(match[0]) : 0;
3988
+ }
3989
+ function resolveRect(node) {
3990
+ const style = parseStyleDeclarations(node.attribs?.style);
3991
+ const left = parseNumericLikeValue(node.attribs?.["data-sim-left"] ?? style.left);
3992
+ const top = parseNumericLikeValue(node.attribs?.["data-sim-top"] ?? style.top);
3993
+ const width = parseNumericLikeValue(node.attribs?.["data-sim-width"] ?? style.width);
3994
+ const height = parseNumericLikeValue(node.attribs?.["data-sim-height"] ?? style.height);
3995
+ return {
3996
+ bottom: top + height,
3997
+ height,
3998
+ left,
3999
+ right: left + width,
4000
+ top,
4001
+ width
4002
+ };
4003
+ }
4004
+ function applyMargins(rect, margins) {
4005
+ const top = rect.top - (margins.top ?? 0);
4006
+ const left = rect.left - (margins.left ?? 0);
4007
+ const right = rect.right + (margins.right ?? 0);
4008
+ const bottom = rect.bottom + (margins.bottom ?? 0);
4009
+ return {
4010
+ bottom,
4011
+ height: Math.max(0, bottom - top),
4012
+ left,
4013
+ right,
4014
+ top,
4015
+ width: Math.max(0, right - left)
4016
+ };
4017
+ }
4018
+ function intersectRects(source, target) {
4019
+ const left = Math.max(source.left, target.left);
4020
+ const top = Math.max(source.top, target.top);
4021
+ const right = Math.min(source.right, target.right);
4022
+ const bottom = Math.min(source.bottom, target.bottom);
4023
+ if (right <= left || bottom <= top) return {
4024
+ bottom: top,
4025
+ height: 0,
4026
+ left,
4027
+ right: left,
4028
+ top,
4029
+ width: 0
4030
+ };
4031
+ return {
4032
+ bottom,
4033
+ height: bottom - top,
4034
+ left,
4035
+ right,
4036
+ top,
4037
+ width: right - left
4038
+ };
4039
+ }
4040
+ function resolveViewportRect(windowInfo) {
4041
+ return {
4042
+ bottom: windowInfo.windowHeight,
4043
+ height: windowInfo.windowHeight,
4044
+ left: 0,
4045
+ right: windowInfo.windowWidth,
4046
+ top: 0,
4047
+ width: windowInfo.windowWidth
4048
+ };
4049
+ }
4050
+ function createHeadlessIntersectionObserver(driver, scope, _options) {
4051
+ let active = true;
4052
+ let relativeTarget = {
4053
+ kind: "viewport",
4054
+ margins: normalizeMargins()
4055
+ };
4056
+ const resolveScopedRoot = () => {
4057
+ const scopeResolution = driver.resolveScope(scope);
4058
+ if (scopeResolution.kind === "missing") return null;
4059
+ const rendered = driver.renderCurrentPage();
4060
+ return scopeResolution.kind === "component" ? resolveSelectorQueryScopeRoot(rendered.root, scopeResolution.scopeId) : rendered.root;
4061
+ };
4062
+ const resolveTargetNode = (selector) => {
4063
+ const scopedRoot = resolveScopedRoot();
4064
+ if (!scopedRoot) return null;
4065
+ return querySelectorAll(scopedRoot, selector)[0] ?? null;
4066
+ };
4067
+ const resolveRelativeRect = () => {
4068
+ if (relativeTarget.kind === "viewport") return applyMargins(resolveViewportRect(driver.getWindowInfo()), relativeTarget.margins);
4069
+ const relativeNode = resolveTargetNode(relativeTarget.selector);
4070
+ if (!relativeNode) return null;
4071
+ return applyMargins(resolveRect(relativeNode), relativeTarget.margins);
4072
+ };
4073
+ return {
4074
+ disconnect() {
4075
+ active = false;
4076
+ },
4077
+ observe(selector, callback) {
4078
+ if (!active) return;
4079
+ const targetNode = resolveTargetNode(selector);
4080
+ const relativeRect = resolveRelativeRect();
4081
+ if (!targetNode || !relativeRect) return;
4082
+ const boundingClientRect = resolveRect(targetNode);
4083
+ const intersectionRect = intersectRects(boundingClientRect, relativeRect);
4084
+ const targetArea = boundingClientRect.width * boundingClientRect.height;
4085
+ const intersectionArea = intersectionRect.width * intersectionRect.height;
4086
+ callback({
4087
+ boundingClientRect,
4088
+ id: targetNode.attribs?.id ?? "",
4089
+ intersectionRatio: targetArea > 0 ? intersectionArea / targetArea : 0,
4090
+ intersectionRect,
4091
+ relativeRect
4092
+ });
4093
+ },
4094
+ relativeTo(selector, margins) {
4095
+ relativeTarget = {
4096
+ kind: "selector",
4097
+ margins: normalizeMargins(margins),
4098
+ selector
4099
+ };
4100
+ return this;
4101
+ },
4102
+ relativeToViewport(margins) {
4103
+ relativeTarget = {
4104
+ kind: "viewport",
4105
+ margins: normalizeMargins(margins)
4106
+ };
4107
+ return this;
4108
+ }
4109
+ };
4110
+ }
4111
+ //#endregion
4112
+ //#region src/view/mediaQueryObserver.ts
4113
+ function resolveOrientation(windowInfo) {
4114
+ return windowInfo.windowWidth >= windowInfo.windowHeight ? "landscape" : "portrait";
4115
+ }
4116
+ function resolveMatches(descriptor, windowInfo) {
4117
+ if (descriptor.width != null && windowInfo.windowWidth !== descriptor.width) return false;
4118
+ if (descriptor.minWidth != null && windowInfo.windowWidth < descriptor.minWidth) return false;
4119
+ if (descriptor.maxWidth != null && windowInfo.windowWidth > descriptor.maxWidth) return false;
4120
+ if (descriptor.height != null && windowInfo.windowHeight !== descriptor.height) return false;
4121
+ if (descriptor.minHeight != null && windowInfo.windowHeight < descriptor.minHeight) return false;
4122
+ if (descriptor.maxHeight != null && windowInfo.windowHeight > descriptor.maxHeight) return false;
4123
+ if (descriptor.orientation != null && resolveOrientation(windowInfo) !== descriptor.orientation) return false;
4124
+ return true;
4125
+ }
4126
+ function createHeadlessMediaQueryObserver(driver, onDisconnect) {
4127
+ let active = true;
4128
+ let callback;
4129
+ let descriptor;
4130
+ let hasObserved = false;
4131
+ let lastMatches;
4132
+ const emit = (force) => {
4133
+ if (!active || !hasObserved || !callback || !descriptor) return;
4134
+ const matches = resolveMatches(descriptor, driver.getWindowInfo());
4135
+ if (!force && lastMatches === matches) return;
4136
+ lastMatches = matches;
4137
+ callback({ matches });
4138
+ };
4139
+ const observer = {
4140
+ disconnect() {
4141
+ if (!active) return;
4142
+ active = false;
4143
+ hasObserved = false;
4144
+ callback = void 0;
4145
+ descriptor = void 0;
4146
+ onDisconnect?.();
4147
+ },
4148
+ observe(nextDescriptor, nextCallback) {
4149
+ if (!active) return;
4150
+ descriptor = { ...nextDescriptor };
4151
+ callback = nextCallback;
4152
+ hasObserved = true;
4153
+ emit(true);
4154
+ }
4155
+ };
4156
+ return {
4157
+ disconnect: observer.disconnect,
4158
+ notify() {
4159
+ emit(false);
4160
+ },
4161
+ observer
4162
+ };
4163
+ }
4164
+ //#endregion
4165
+ //#region src/view/videoContext.ts
4166
+ const DATASET_NAME_RE$1 = /-([a-z])/g;
4167
+ function toDatasetKey$1(attributeName) {
4168
+ return attributeName.slice(5).replace(DATASET_NAME_RE$1, (_match, char) => char.toUpperCase());
4169
+ }
4170
+ function collectDataset$1(node) {
4171
+ const dataset = {};
4172
+ for (const [key, value] of Object.entries(node.attribs ?? {})) {
4173
+ if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
4174
+ dataset[toDatasetKey$1(key)] = value;
4175
+ }
4176
+ return dataset;
4177
+ }
4178
+ function resolveEventBinding(node, eventName) {
4179
+ const normalizedEventName = eventName.trim();
4180
+ if (!normalizedEventName) return null;
4181
+ const bindingAttrs = [
4182
+ `bind${normalizedEventName}`,
4183
+ `bind:${normalizedEventName}`,
4184
+ `catch${normalizedEventName}`,
4185
+ `catch:${normalizedEventName}`
4186
+ ];
4187
+ for (const attributeName of bindingAttrs) {
4188
+ const methodName = node.attribs?.[attributeName]?.trim();
4189
+ if (methodName) return methodName;
4190
+ }
4191
+ return null;
4192
+ }
4193
+ function createEventPayload(node, eventName, detail) {
4194
+ const dataset = collectDataset$1(node);
4195
+ const nodeId = node.attribs?.id ?? "";
4196
+ return {
4197
+ bubbles: false,
4198
+ capturePhase: false,
4199
+ composed: false,
4200
+ currentTarget: {
4201
+ dataset,
4202
+ id: nodeId
4203
+ },
4204
+ detail,
4205
+ mark: void 0,
4206
+ target: {
4207
+ dataset,
4208
+ id: nodeId
4209
+ },
4210
+ type: eventName
4211
+ };
4212
+ }
4213
+ function createHeadlessVideoContext(driver, videoId, scope) {
4214
+ const state = {
4215
+ currentTime: 0,
4216
+ fullScreen: false,
4217
+ paused: true
4218
+ };
4219
+ const resolveNode = () => {
4220
+ const scopeResolution = driver.resolveScope(scope);
4221
+ if (scopeResolution.kind === "missing") return null;
4222
+ const rendered = driver.renderCurrentPage();
4223
+ return querySelectorAll(scopeResolution.kind === "component" ? resolveSelectorQueryScopeRoot(rendered.root, scopeResolution.scopeId) : rendered.root, `#${videoId}`)[0] ?? null;
4224
+ };
4225
+ const dispatch = (eventName, detail) => {
4226
+ const node = resolveNode();
4227
+ if (!node) return;
4228
+ const methodName = resolveEventBinding(node, eventName);
4229
+ if (!methodName) return;
4230
+ driver.callScopeMethod(node.attribs?.["data-sim-scope"] ?? null, methodName, createEventPayload(node, eventName, detail));
4231
+ };
4232
+ return {
4233
+ exitFullScreen() {
4234
+ state.fullScreen = false;
4235
+ dispatch("fullscreenchange", {
4236
+ currentTime: state.currentTime,
4237
+ fullScreen: false
4238
+ });
4239
+ },
4240
+ pause() {
4241
+ state.paused = true;
4242
+ dispatch("pause", { currentTime: state.currentTime });
4243
+ },
4244
+ play() {
4245
+ state.paused = false;
4246
+ dispatch("play", { currentTime: state.currentTime });
4247
+ },
4248
+ requestFullScreen() {
4249
+ state.fullScreen = true;
4250
+ dispatch("fullscreenchange", {
4251
+ currentTime: state.currentTime,
4252
+ fullScreen: true
4253
+ });
4254
+ },
4255
+ seek(position) {
4256
+ state.currentTime = Number.isFinite(position) ? Number(position) : 0;
4257
+ },
4258
+ stop() {
4259
+ state.currentTime = 0;
4260
+ state.paused = true;
4261
+ dispatch("pause", { currentTime: state.currentTime });
4262
+ }
4263
+ };
4264
+ }
4265
+ //#endregion
2846
4266
  //#region src/browser/session.ts
2847
4267
  const LEADING_SLASH_RE$3 = /^\/+/;
2848
4268
  const PAGE_STACK_LIMIT$1 = 10;
4269
+ const WHITESPACE_RE$1 = /\s+/;
2849
4270
  const DATA_ATTR_SELECTOR_RE$1 = /^\[data-([^=\]]+)="([^"]*)"\]$/;
4271
+ const COMPOUND_SELECTOR_PART_RE$1 = /#[\w-]+|\.[\w-]+|\[data-[^=\]]+="[^"]*"\]|[A-Za-z][\w-]*/g;
2850
4272
  const DATASET_KEY_RE$1 = /-([a-z])/g;
2851
4273
  function stripLeadingSlash$1(route) {
2852
4274
  return route.replace(LEADING_SLASH_RE$3, "");
@@ -2867,6 +4289,28 @@ function parseNavigationUrl$1(url) {
2867
4289
  query: normalizeQuery$1(queryString)
2868
4290
  };
2869
4291
  }
4292
+ function parseCompoundSelector$1(selector) {
4293
+ const parts = selector.match(COMPOUND_SELECTOR_PART_RE$1) ?? [];
4294
+ return parts.join("") === selector ? parts : [];
4295
+ }
4296
+ function matchesComponentSelector$1(scope, selector) {
4297
+ const parts = parseCompoundSelector$1(selector);
4298
+ if (parts.length === 0) return false;
4299
+ return parts.every((part) => {
4300
+ if (part.startsWith("#")) return scope.id === part.slice(1);
4301
+ if (part.startsWith(".")) return scope.classList?.includes(part.slice(1)) ?? false;
4302
+ const dataAttrMatch = part.match(DATA_ATTR_SELECTOR_RE$1);
4303
+ if (dataAttrMatch) {
4304
+ const [, key, value] = dataAttrMatch;
4305
+ const datasetKey = key.replace(DATASET_KEY_RE$1, (_match, char) => char.toUpperCase());
4306
+ return scope.dataset?.[datasetKey] === value;
4307
+ }
4308
+ return scope.alias === part;
4309
+ });
4310
+ }
4311
+ function normalizeSelectorParts$1(selector) {
4312
+ return selector.trim().split(WHITESPACE_RE$1).filter(Boolean);
4313
+ }
2870
4314
  function createAppLaunchOptions$1(pathname, query) {
2871
4315
  return {
2872
4316
  path: stripLeadingSlash$1(pathname),
@@ -2911,6 +4355,8 @@ var BrowserHeadlessSession = class {
2911
4355
  tabBarState = /* @__PURE__ */ new Map();
2912
4356
  tabBarVisible = false;
2913
4357
  systemInfo = createDefaultSystemInfo();
4358
+ mediaQueryObservers = /* @__PURE__ */ new Set();
4359
+ canvasContexts = /* @__PURE__ */ new Map();
2914
4360
  enterOptions = createAppLaunchOptions$1("", {});
2915
4361
  launchOptions = createAppLaunchOptions$1("", {});
2916
4362
  wxState = createHeadlessWxState();
@@ -2944,7 +4390,20 @@ var BrowserHeadlessSession = class {
2944
4390
  });
2945
4391
  this.tabBarVisible = this.tabBarRoutes.size > 0;
2946
4392
  this.moduleLoader = createBrowserModuleLoader(this.files, this.registries, () => this.pages.slice(), () => this.getApp(), {
4393
+ chooseImage: (option) => this.wxState.chooseImage(option ?? {}),
4394
+ chooseMessageFile: (option) => this.wxState.chooseMessageFile(option ?? {}),
4395
+ chooseMedia: (option) => this.wxState.chooseMedia(option ?? {}),
4396
+ chooseVideo: (option) => this.wxState.chooseVideo(option ?? {}),
4397
+ compressImage: (option) => this.wxState.compressImage(option),
4398
+ createAnimation: (option) => this.createAnimation(option),
4399
+ createCanvasContext: (canvasId, scope) => this.createCanvasContext(canvasId, scope),
4400
+ canvasToTempFilePath: (option) => this.canvasToTempFilePath(option),
4401
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
4402
+ createVideoContext: (videoId, scope) => this.createVideoContext(videoId, scope),
2947
4403
  executeSelectorQuery: (requests, scope) => this.executeSelectorQuery(requests, scope),
4404
+ getFileInfo: (option) => this.wxState.getFileInfo(option),
4405
+ getImageInfo: (option) => this.wxState.getImageInfo(option),
4406
+ getVideoInfo: (option) => this.wxState.getVideoInfo(option),
2948
4407
  getFileSystemManager: () => this.wxState.getFileSystemManager(),
2949
4408
  getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
2950
4409
  getSavedFileList: () => this.wxState.getSavedFileList(),
@@ -2965,11 +4424,13 @@ var BrowserHeadlessSession = class {
2965
4424
  extraData: { ...this.launchOptions.referrerInfo.extraData }
2966
4425
  }
2967
4426
  }),
4427
+ getClipboardData: () => this.wxState.getClipboardData(),
2968
4428
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
2969
4429
  getNetworkType: () => this.wxState.getNetworkType(),
2970
4430
  navigateBack: (option) => this.navigateBack(option?.delta),
2971
4431
  navigateTo: (option) => this.navigateTo(option.url),
2972
4432
  pageScrollTo: (option) => this.pageScrollTo(option),
4433
+ openDocument: (option) => this.wxState.openDocument(option),
2973
4434
  clearStorageSync: () => this.wxState.clearStorageSync(),
2974
4435
  getStorageInfoSync: () => this.wxState.getStorageInfoSync(),
2975
4436
  getStorageSync: (key) => this.wxState.getStorageSync(key),
@@ -2981,14 +4442,18 @@ var BrowserHeadlessSession = class {
2981
4442
  reLaunch: (option) => this.reLaunch(option.url),
2982
4443
  redirectTo: (option) => this.redirectTo(option.url),
2983
4444
  removeSavedFile: (option) => this.wxState.removeSavedFile(option),
4445
+ saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
4446
+ saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
2984
4447
  nextTick: (callback) => queueMicrotask(() => callback?.()),
2985
4448
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
2986
4449
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
2987
4450
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
4451
+ previewImage: (option) => this.wxState.previewImage(option),
2988
4452
  request: (option) => this.wxState.request(option),
2989
4453
  saveFile: (option) => this.wxState.saveFile(option),
2990
4454
  setBackgroundColor: (option) => this.setBackgroundColor(option),
2991
4455
  setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
4456
+ setClipboardData: (option) => this.wxState.setClipboardData(option),
2992
4457
  setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
2993
4458
  setNavigationBarColor: (option) => this.setNavigationBarColor(option),
2994
4459
  setNavigationBarTitle: (option) => this.setNavigationBarTitle(option.title),
@@ -3004,6 +4469,7 @@ var BrowserHeadlessSession = class {
3004
4469
  showLoading: (option) => this.wxState.showLoading(option),
3005
4470
  showModal: (option) => this.wxState.showModal(option),
3006
4471
  showToast: (option) => this.wxState.showToast(option),
4472
+ startPullDownRefresh: () => this.startPullDownRefresh(),
3007
4473
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
3008
4474
  switchTab: (option) => this.switchTab(option.url),
3009
4475
  uploadFile: (option) => this.wxState.uploadFile(option),
@@ -3077,6 +4543,15 @@ var BrowserHeadlessSession = class {
3077
4543
  getStorageInfo() {
3078
4544
  return this.wxState.getStorageInfoSync();
3079
4545
  }
4546
+ getClipboardData() {
4547
+ return this.wxState.getClipboardSnapshot();
4548
+ }
4549
+ getPreviewImage() {
4550
+ return this.wxState.getPreviewImage();
4551
+ }
4552
+ getOpenedDocument() {
4553
+ return this.wxState.getOpenedDocument();
4554
+ }
3080
4555
  getPullDownRefreshState() {
3081
4556
  return { ...this.pullDownRefreshState };
3082
4557
  }
@@ -3304,21 +4779,21 @@ var BrowserHeadlessSession = class {
3304
4779
  return this.componentCache.get(scope.ownerScopeId) ?? null;
3305
4780
  }
3306
4781
  selectComponentsWithin(rootScopeId, selector) {
3307
- const normalizedSelector = selector.trim();
3308
- if (!normalizedSelector) return [];
4782
+ const selectorParts = normalizeSelectorParts$1(selector);
4783
+ if (selectorParts.length === 0) return [];
3309
4784
  return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
3310
4785
  if (!candidateScopeId.includes("/")) return false;
3311
4786
  if (rootScopeId && candidateScopeId === rootScopeId) return false;
3312
4787
  if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
3313
- if (normalizedSelector.startsWith("#")) return scope.id === normalizedSelector.slice(1);
3314
- if (normalizedSelector.startsWith(".")) return scope.classList?.includes(normalizedSelector.slice(1)) ?? false;
3315
- const dataAttrMatch = normalizedSelector.match(DATA_ATTR_SELECTOR_RE$1);
3316
- if (dataAttrMatch) {
3317
- const [, key, value] = dataAttrMatch;
3318
- const datasetKey = key.replace(DATASET_KEY_RE$1, (_match, char) => char.toUpperCase());
3319
- return scope.dataset?.[datasetKey] === value;
4788
+ const lastPart = selectorParts.at(-1);
4789
+ if (!lastPart || !matchesComponentSelector$1(scope, lastPart)) return false;
4790
+ let currentScope = scope.ownerScopeId ? this.componentScopes.get(scope.ownerScopeId) : void 0;
4791
+ for (let partIndex = selectorParts.length - 2; partIndex >= 0; partIndex -= 1) {
4792
+ while (currentScope && !matchesComponentSelector$1(currentScope, selectorParts[partIndex])) currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
4793
+ if (!currentScope) return false;
4794
+ currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
3320
4795
  }
3321
- return scope.alias === normalizedSelector;
4796
+ return true;
3322
4797
  }).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
3323
4798
  }
3324
4799
  renderCurrentPage() {
@@ -3331,6 +4806,8 @@ var BrowserHeadlessSession = class {
3331
4806
  moduleLoader: this.moduleLoader,
3332
4807
  project: this.project,
3333
4808
  session: {
4809
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
4810
+ createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
3334
4811
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
3335
4812
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
3336
4813
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -3369,6 +4846,7 @@ var BrowserHeadlessSession = class {
3369
4846
  }
3370
4847
  const instance = this.componentCache.get(normalizedScopeId);
3371
4848
  if (!instance) throw new Error(`Unknown scope "${normalizedScopeId}" in browser simulator runtime.`);
4849
+ instance.__lastInteractionEvent__ = void 0;
3372
4850
  const method = instance[methodName];
3373
4851
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator component scope "${normalizedScopeId}".`);
3374
4852
  return method.apply(instance, args);
@@ -3509,7 +4987,22 @@ var BrowserHeadlessSession = class {
3509
4987
  }
3510
4988
  pageScrollTo(option) {
3511
4989
  const current = this.requireCurrentPage("wx.pageScrollTo()");
3512
- current.__scrollTop__ = Number(option.scrollTop ?? 0);
4990
+ const selectorScrollTop = resolveSelectorScrollTop(renderBrowserPageTree({
4991
+ changedPageKeys: current.__lastChangedKeys__ ?? [],
4992
+ componentCache: this.componentCache,
4993
+ componentScopes: this.componentScopes,
4994
+ files: this.files,
4995
+ moduleLoader: this.moduleLoader,
4996
+ project: this.project,
4997
+ session: {
4998
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
4999
+ createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
5000
+ selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
5001
+ selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
5002
+ selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
5003
+ }
5004
+ }, current).root, option.selector);
5005
+ current.__scrollTop__ = Number(selectorScrollTop ?? option.scrollTop ?? 0);
3513
5006
  current.onPageScroll?.({ scrollTop: current.__scrollTop__ });
3514
5007
  }
3515
5008
  triggerPullDownRefresh() {
@@ -3521,6 +5014,10 @@ var BrowserHeadlessSession = class {
3521
5014
  current.onPullDownRefresh?.();
3522
5015
  return current;
3523
5016
  }
5017
+ startPullDownRefresh() {
5018
+ this.triggerPullDownRefresh();
5019
+ return { errMsg: "startPullDownRefresh:ok" };
5020
+ }
3524
5021
  triggerReachBottom() {
3525
5022
  const current = this.requireCurrentPage("triggerReachBottom()");
3526
5023
  current.onReachBottom?.();
@@ -3531,6 +5028,7 @@ var BrowserHeadlessSession = class {
3531
5028
  applyResizeToSystemInfo(this.systemInfo, options);
3532
5029
  current.onResize?.(options);
3533
5030
  this.runPageComponentLifetime(current.route, "resize", options);
5031
+ this.notifyMediaQueryObservers();
3534
5032
  return current;
3535
5033
  }
3536
5034
  triggerRouteDone(options = {}) {
@@ -3550,6 +5048,11 @@ var BrowserHeadlessSession = class {
3550
5048
  const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
3551
5049
  return executeSelectorQueryRequests(requests, {
3552
5050
  page: current,
5051
+ resolveContext: (node) => {
5052
+ if (node.name !== "canvas") return { type: "unsupported-context" };
5053
+ const canvasId = node.attribs?.["canvas-id"];
5054
+ return typeof canvasId === "string" && canvasId ? this.createCanvasContext(canvasId, scope) : { type: "unsupported-context" };
5055
+ },
3553
5056
  root: resolveSelectorQueryScopeRoot(renderBrowserPageTree({
3554
5057
  changedPageKeys: current.__lastChangedKeys__ ?? [],
3555
5058
  componentCache: this.componentCache,
@@ -3558,6 +5061,8 @@ var BrowserHeadlessSession = class {
3558
5061
  moduleLoader: this.moduleLoader,
3559
5062
  project: this.project,
3560
5063
  session: {
5064
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
5065
+ createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
3561
5066
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
3562
5067
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
3563
5068
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -3575,6 +5080,8 @@ var BrowserHeadlessSession = class {
3575
5080
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
3576
5081
  navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
3577
5082
  });
5083
+ pageInstance.createIntersectionObserver = (options) => this.createIntersectionObserver(pageInstance, options);
5084
+ pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
3578
5085
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
3579
5086
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
3580
5087
  pageInstance.onLoad?.(target.query);
@@ -3624,10 +5131,12 @@ var BrowserHeadlessSession = class {
3624
5131
  this.tabPages.clear();
3625
5132
  this.componentCache.clear();
3626
5133
  this.componentScopes.clear();
5134
+ this.clearMediaQueryObservers();
3627
5135
  this.currentPageInstance = null;
3628
5136
  }
3629
5137
  unloadPage(page) {
3630
5138
  page.onUnload?.();
5139
+ this.clearMediaQueryObservers(page);
3631
5140
  this.detachPageComponents(page.route);
3632
5141
  this.tabPages.delete(stripLeadingSlash$1(page.route));
3633
5142
  }
@@ -3646,6 +5155,18 @@ var BrowserHeadlessSession = class {
3646
5155
  this.componentScopes.delete(scopeId);
3647
5156
  }
3648
5157
  }
5158
+ notifyMediaQueryObservers() {
5159
+ for (const entry of [...this.mediaQueryObservers]) {
5160
+ if (entry.ownerPage !== this.currentPageInstance) continue;
5161
+ entry.notify();
5162
+ }
5163
+ }
5164
+ clearMediaQueryObservers(ownerPage) {
5165
+ for (const entry of [...this.mediaQueryObservers]) {
5166
+ if (ownerPage && entry.ownerPage !== ownerPage) continue;
5167
+ entry.disconnect();
5168
+ }
5169
+ }
3649
5170
  runPageComponentLifetime(route, lifetimeName, payload) {
3650
5171
  const prefix = `page:${stripLeadingSlash$1(route)}`;
3651
5172
  for (const [scopeId, instance] of this.componentCache.entries()) {
@@ -3657,6 +5178,100 @@ var BrowserHeadlessSession = class {
3657
5178
  for (const [scopeId, instance] of this.componentCache.entries()) if (instance === component) return scopeId;
3658
5179
  return null;
3659
5180
  }
5181
+ createVideoContext(videoId, scope) {
5182
+ return createHeadlessVideoContext({
5183
+ callScopeMethod: (scopeId, methodName, event) => this.callScopeMethod(scopeId, methodName, event),
5184
+ renderCurrentPage: () => this.renderCurrentPage(),
5185
+ resolveScope: (value) => {
5186
+ const current = this.currentPageInstance;
5187
+ if (!value || value === current) return { kind: "page" };
5188
+ const scopeId = this.getScopeIdForComponent(value);
5189
+ if (!scopeId) return { kind: "missing" };
5190
+ return {
5191
+ kind: "component",
5192
+ scopeId
5193
+ };
5194
+ }
5195
+ }, videoId, scope);
5196
+ }
5197
+ createAnimation(option) {
5198
+ return createHeadlessAnimation(option);
5199
+ }
5200
+ resolveCanvasScopeKey(scope) {
5201
+ const current = this.currentPageInstance;
5202
+ if (!scope || scope === current) return "page";
5203
+ const scopeId = this.getScopeIdForComponent(scope);
5204
+ return scopeId ? `component:${scopeId}` : "missing";
5205
+ }
5206
+ createCanvasContext(canvasId, scope) {
5207
+ const context = createHeadlessCanvasContext({
5208
+ renderCurrentPage: () => this.renderCurrentPage(),
5209
+ resolveScope: (value) => {
5210
+ const current = this.currentPageInstance;
5211
+ if (!value || value === current) return { kind: "page" };
5212
+ const scopeId = this.getScopeIdForComponent(value);
5213
+ if (!scopeId) return { kind: "missing" };
5214
+ return {
5215
+ kind: "component",
5216
+ scopeId
5217
+ };
5218
+ }
5219
+ }, canvasId, scope);
5220
+ this.canvasContexts.set(`${this.resolveCanvasScopeKey(scope)}:${canvasId}`, context);
5221
+ return context;
5222
+ }
5223
+ canvasToTempFilePath(option) {
5224
+ const context = this.canvasContexts.get(`${this.resolveCanvasScopeKey(option.component)}:${option.canvasId}`);
5225
+ if (!context) throw new Error(`canvasToTempFilePath:fail canvas "${option.canvasId}" has not been drawn in browser runtime.`);
5226
+ return {
5227
+ errMsg: "canvasToTempFilePath:ok",
5228
+ tempFilePath: this.wxState.createTempFile(JSON.stringify({
5229
+ canvasId: option.canvasId,
5230
+ config: {
5231
+ destHeight: option.destHeight,
5232
+ destWidth: option.destWidth,
5233
+ fileType: option.fileType,
5234
+ height: option.height,
5235
+ quality: option.quality,
5236
+ width: option.width,
5237
+ x: option.x,
5238
+ y: option.y
5239
+ },
5240
+ snapshot: context.__getSnapshot()
5241
+ }))
5242
+ };
5243
+ }
5244
+ createIntersectionObserver(scope, options) {
5245
+ return createHeadlessIntersectionObserver({
5246
+ getWindowInfo: () => this.getWindowInfo(),
5247
+ renderCurrentPage: () => this.renderCurrentPage(),
5248
+ resolveScope: (value) => {
5249
+ const current = this.currentPageInstance;
5250
+ if (!value || value === current) return { kind: "page" };
5251
+ const scopeId = this.getScopeIdForComponent(value);
5252
+ if (!scopeId) return { kind: "missing" };
5253
+ return {
5254
+ kind: "component",
5255
+ scopeId
5256
+ };
5257
+ }
5258
+ }, scope, options);
5259
+ }
5260
+ createMediaQueryObserver(scope) {
5261
+ const current = this.requireCurrentPage("createMediaQueryObserver()");
5262
+ const ownerPage = scope === current || !scope ? current : this.currentPageInstance ?? current;
5263
+ let entry;
5264
+ const controller = createHeadlessMediaQueryObserver({ getWindowInfo: () => this.getWindowInfo() }, () => {
5265
+ this.mediaQueryObservers.delete(entry);
5266
+ });
5267
+ entry = {
5268
+ disconnect: controller.disconnect,
5269
+ notify: controller.notify,
5270
+ ownerPage
5271
+ };
5272
+ this.mediaQueryObservers.add(entry);
5273
+ return controller.observer;
5274
+ }
3660
5275
  };
3661
5276
  function createBrowserHeadlessSession(options) {
3662
5277
  return new BrowserHeadlessSession(options);
@@ -4080,6 +5695,8 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
4080
5695
  properties: nextProperties,
4081
5696
  triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
4082
5697
  });
5698
+ componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
5699
+ componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
4083
5700
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
4084
5701
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
4085
5702
  componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
@@ -4253,7 +5870,9 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
4253
5870
  //#region src/runtime/session.ts
4254
5871
  const LEADING_SLASH_RE$1 = /^\/+/;
4255
5872
  const PAGE_STACK_LIMIT = 10;
5873
+ const WHITESPACE_RE = /\s+/;
4256
5874
  const DATA_ATTR_SELECTOR_RE = /^\[data-([^=\]]+)="([^"]*)"\]$/;
5875
+ const COMPOUND_SELECTOR_PART_RE = /#[\w-]+|\.[\w-]+|\[data-[^=\]]+="[^"]*"\]|[A-Za-z][\w-]*/g;
4257
5876
  const DATASET_KEY_RE = /-([a-z])/g;
4258
5877
  function stripLeadingSlash(route) {
4259
5878
  return route.replace(LEADING_SLASH_RE$1, "");
@@ -4274,6 +5893,28 @@ function parseNavigationUrl(url) {
4274
5893
  query: normalizeQuery(queryString)
4275
5894
  };
4276
5895
  }
5896
+ function parseCompoundSelector(selector) {
5897
+ const parts = selector.match(COMPOUND_SELECTOR_PART_RE) ?? [];
5898
+ return parts.join("") === selector ? parts : [];
5899
+ }
5900
+ function matchesComponentSelector(scope, selector) {
5901
+ const parts = parseCompoundSelector(selector);
5902
+ if (parts.length === 0) return false;
5903
+ return parts.every((part) => {
5904
+ if (part.startsWith("#")) return scope.id === part.slice(1);
5905
+ if (part.startsWith(".")) return scope.classList?.includes(part.slice(1)) ?? false;
5906
+ const dataAttrMatch = part.match(DATA_ATTR_SELECTOR_RE);
5907
+ if (dataAttrMatch) {
5908
+ const [, key, value] = dataAttrMatch;
5909
+ const datasetKey = key.replace(DATASET_KEY_RE, (_match, char) => char.toUpperCase());
5910
+ return scope.dataset?.[datasetKey] === value;
5911
+ }
5912
+ return scope.alias === part;
5913
+ });
5914
+ }
5915
+ function normalizeSelectorParts(selector) {
5916
+ return selector.trim().split(WHITESPACE_RE).filter(Boolean);
5917
+ }
4277
5918
  function createAppLaunchOptions(pathname, query) {
4278
5919
  return {
4279
5920
  path: stripLeadingSlash(pathname),
@@ -4315,6 +5956,8 @@ var HeadlessSession = class {
4315
5956
  tabBarState = /* @__PURE__ */ new Map();
4316
5957
  tabBarVisible = false;
4317
5958
  systemInfo = createDefaultSystemInfo();
5959
+ mediaQueryObservers = /* @__PURE__ */ new Set();
5960
+ canvasContexts = /* @__PURE__ */ new Map();
4318
5961
  enterOptions = createAppLaunchOptions("", {});
4319
5962
  launchOptions = createAppLaunchOptions("", {});
4320
5963
  wxState = createHeadlessWxState();
@@ -4347,7 +5990,20 @@ var HeadlessSession = class {
4347
5990
  });
4348
5991
  this.tabBarVisible = this.tabBarRoutes.size > 0;
4349
5992
  this.moduleLoader = createModuleLoader(this.registries, () => this.pages.slice(), () => this.getApp(), {
5993
+ chooseImage: (option) => this.wxState.chooseImage(option ?? {}),
5994
+ chooseMessageFile: (option) => this.wxState.chooseMessageFile(option ?? {}),
5995
+ chooseMedia: (option) => this.wxState.chooseMedia(option ?? {}),
5996
+ chooseVideo: (option) => this.wxState.chooseVideo(option ?? {}),
5997
+ compressImage: (option) => this.wxState.compressImage(option),
5998
+ createAnimation: (option) => this.createAnimation(option),
5999
+ createCanvasContext: (canvasId, scope) => this.createCanvasContext(canvasId, scope),
6000
+ canvasToTempFilePath: (option) => this.canvasToTempFilePath(option),
6001
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
6002
+ createVideoContext: (videoId, scope) => this.createVideoContext(videoId, scope),
4350
6003
  executeSelectorQuery: (requests, scope) => this.executeSelectorQuery(requests, scope),
6004
+ getFileInfo: (option) => this.wxState.getFileInfo(option),
6005
+ getImageInfo: (option) => this.wxState.getImageInfo(option),
6006
+ getVideoInfo: (option) => this.wxState.getVideoInfo(option),
4351
6007
  getFileSystemManager: () => this.wxState.getFileSystemManager(),
4352
6008
  getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
4353
6009
  getSavedFileList: () => this.wxState.getSavedFileList(),
@@ -4368,11 +6024,13 @@ var HeadlessSession = class {
4368
6024
  extraData: { ...this.launchOptions.referrerInfo.extraData }
4369
6025
  }
4370
6026
  }),
6027
+ getClipboardData: () => this.wxState.getClipboardData(),
4371
6028
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
4372
6029
  getNetworkType: () => this.wxState.getNetworkType(),
4373
6030
  navigateBack: (option) => this.navigateBack(option?.delta),
4374
6031
  navigateTo: (option) => this.navigateTo(option.url),
4375
6032
  pageScrollTo: (option) => this.pageScrollTo(option),
6033
+ openDocument: (option) => this.wxState.openDocument(option),
4376
6034
  clearStorageSync: () => this.wxState.clearStorageSync(),
4377
6035
  getStorageInfoSync: () => this.wxState.getStorageInfoSync(),
4378
6036
  getStorageSync: (key) => this.wxState.getStorageSync(key),
@@ -4384,14 +6042,18 @@ var HeadlessSession = class {
4384
6042
  reLaunch: (option) => this.reLaunch(option.url),
4385
6043
  redirectTo: (option) => this.redirectTo(option.url),
4386
6044
  removeSavedFile: (option) => this.wxState.removeSavedFile(option),
6045
+ saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
6046
+ saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
4387
6047
  nextTick: (callback) => queueMicrotask(() => callback?.()),
4388
6048
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
4389
6049
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
4390
6050
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
6051
+ previewImage: (option) => this.wxState.previewImage(option),
4391
6052
  request: (option) => this.wxState.request(option),
4392
6053
  saveFile: (option) => this.wxState.saveFile(option),
4393
6054
  setBackgroundColor: (option) => this.setBackgroundColor(option),
4394
6055
  setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
6056
+ setClipboardData: (option) => this.wxState.setClipboardData(option),
4395
6057
  setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
4396
6058
  setNavigationBarColor: (option) => this.setNavigationBarColor(option),
4397
6059
  setNavigationBarTitle: (option) => this.setNavigationBarTitle(option.title),
@@ -4407,6 +6069,7 @@ var HeadlessSession = class {
4407
6069
  showLoading: (option) => this.wxState.showLoading(option),
4408
6070
  showModal: (option) => this.wxState.showModal(option),
4409
6071
  showToast: (option) => this.wxState.showToast(option),
6072
+ startPullDownRefresh: () => this.startPullDownRefresh(),
4410
6073
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
4411
6074
  switchTab: (option) => this.switchTab(option.url),
4412
6075
  uploadFile: (option) => this.wxState.uploadFile(option),
@@ -4465,6 +6128,8 @@ var HeadlessSession = class {
4465
6128
  moduleLoader: this.moduleLoader,
4466
6129
  project: this.project,
4467
6130
  session: {
6131
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
6132
+ createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
4468
6133
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
4469
6134
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
4470
6135
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -4532,6 +6197,7 @@ var HeadlessSession = class {
4532
6197
  }
4533
6198
  const instance = this.componentCache.get(normalizedScopeId);
4534
6199
  if (!instance) throw new Error(`Unknown scope "${normalizedScopeId}" in headless runtime.`);
6200
+ instance.__lastInteractionEvent__ = void 0;
4535
6201
  const method = instance[methodName];
4536
6202
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless component scope "${normalizedScopeId}".`);
4537
6203
  return method.apply(instance, args);
@@ -4581,6 +6247,15 @@ var HeadlessSession = class {
4581
6247
  getStorageInfo() {
4582
6248
  return this.wxState.getStorageInfoSync();
4583
6249
  }
6250
+ getClipboardData() {
6251
+ return this.wxState.getClipboardSnapshot();
6252
+ }
6253
+ getPreviewImage() {
6254
+ return this.wxState.getPreviewImage();
6255
+ }
6256
+ getOpenedDocument() {
6257
+ return this.wxState.getOpenedDocument();
6258
+ }
4584
6259
  getPullDownRefreshState() {
4585
6260
  return { ...this.pullDownRefreshState };
4586
6261
  }
@@ -4854,7 +6529,8 @@ var HeadlessSession = class {
4854
6529
  }
4855
6530
  pageScrollTo(option) {
4856
6531
  const current = this.requireCurrentPage("wx.pageScrollTo()");
4857
- current.__scrollTop__ = Number(option.scrollTop ?? 0);
6532
+ const selectorScrollTop = resolveSelectorScrollTop(this.renderCurrentPage().root, option.selector);
6533
+ current.__scrollTop__ = Number(selectorScrollTop ?? option.scrollTop ?? 0);
4858
6534
  current.onPageScroll?.({ scrollTop: current.__scrollTop__ });
4859
6535
  }
4860
6536
  triggerPullDownRefresh() {
@@ -4866,6 +6542,10 @@ var HeadlessSession = class {
4866
6542
  current.onPullDownRefresh?.();
4867
6543
  return current;
4868
6544
  }
6545
+ startPullDownRefresh() {
6546
+ this.triggerPullDownRefresh();
6547
+ return { errMsg: "startPullDownRefresh:ok" };
6548
+ }
4869
6549
  triggerReachBottom() {
4870
6550
  const current = this.requireCurrentPage("triggerReachBottom()");
4871
6551
  current.onReachBottom?.();
@@ -4876,6 +6556,7 @@ var HeadlessSession = class {
4876
6556
  applyResizeToSystemInfo(this.systemInfo, options);
4877
6557
  current.onResize?.(options);
4878
6558
  this.runPageComponentLifetime(current.route, "resize", options);
6559
+ this.notifyMediaQueryObservers();
4879
6560
  return current;
4880
6561
  }
4881
6562
  triggerRouteDone(options = {}) {
@@ -4896,6 +6577,11 @@ var HeadlessSession = class {
4896
6577
  const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
4897
6578
  return executeSelectorQueryRequests(requests, {
4898
6579
  page: current,
6580
+ resolveContext: (node) => {
6581
+ if (node.name !== "canvas") return { type: "unsupported-context" };
6582
+ const canvasId = node.attribs?.["canvas-id"];
6583
+ return typeof canvasId === "string" && canvasId ? this.createCanvasContext(canvasId, scope) : { type: "unsupported-context" };
6584
+ },
4899
6585
  root: resolveSelectorQueryScopeRoot(rendered.root, scopeId),
4900
6586
  windowInfo: this.getWindowInfo()
4901
6587
  });
@@ -4909,6 +6595,8 @@ var HeadlessSession = class {
4909
6595
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
4910
6596
  navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
4911
6597
  });
6598
+ pageInstance.createIntersectionObserver = (options) => this.createIntersectionObserver(pageInstance, options);
6599
+ pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
4912
6600
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
4913
6601
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
4914
6602
  pageInstance.onLoad?.(target.query);
@@ -4958,10 +6646,12 @@ var HeadlessSession = class {
4958
6646
  this.tabPages.clear();
4959
6647
  this.componentCache.clear();
4960
6648
  this.componentScopes.clear();
6649
+ this.clearMediaQueryObservers();
4961
6650
  this.currentPageInstance = null;
4962
6651
  }
4963
6652
  unloadPage(page) {
4964
6653
  page.onUnload?.();
6654
+ this.clearMediaQueryObservers(page);
4965
6655
  this.detachPageComponents(page.route);
4966
6656
  this.tabPages.delete(stripLeadingSlash(page.route));
4967
6657
  }
@@ -4972,21 +6662,21 @@ var HeadlessSession = class {
4972
6662
  return current;
4973
6663
  }
4974
6664
  selectComponentsWithin(rootScopeId, selector) {
4975
- const normalizedSelector = selector.trim();
4976
- if (!normalizedSelector) return [];
6665
+ const selectorParts = normalizeSelectorParts(selector);
6666
+ if (selectorParts.length === 0) return [];
4977
6667
  return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
4978
6668
  if (!candidateScopeId.includes("/")) return false;
4979
6669
  if (rootScopeId && candidateScopeId === rootScopeId) return false;
4980
6670
  if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
4981
- if (normalizedSelector.startsWith("#")) return scope.id === normalizedSelector.slice(1);
4982
- if (normalizedSelector.startsWith(".")) return scope.classList?.includes(normalizedSelector.slice(1)) ?? false;
4983
- const dataAttrMatch = normalizedSelector.match(DATA_ATTR_SELECTOR_RE);
4984
- if (dataAttrMatch) {
4985
- const [, key, value] = dataAttrMatch;
4986
- const datasetKey = key.replace(DATASET_KEY_RE, (_match, char) => char.toUpperCase());
4987
- return scope.dataset?.[datasetKey] === value;
6671
+ const lastPart = selectorParts.at(-1);
6672
+ if (!lastPart || !matchesComponentSelector(scope, lastPart)) return false;
6673
+ let currentScope = scope.ownerScopeId ? this.componentScopes.get(scope.ownerScopeId) : void 0;
6674
+ for (let partIndex = selectorParts.length - 2; partIndex >= 0; partIndex -= 1) {
6675
+ while (currentScope && !matchesComponentSelector(currentScope, selectorParts[partIndex])) currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
6676
+ if (!currentScope) return false;
6677
+ currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
4988
6678
  }
4989
- return scope.alias === normalizedSelector;
6679
+ return true;
4990
6680
  }).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
4991
6681
  }
4992
6682
  detachPageComponents(route) {
@@ -4998,6 +6688,18 @@ var HeadlessSession = class {
4998
6688
  this.componentScopes.delete(scopeId);
4999
6689
  }
5000
6690
  }
6691
+ notifyMediaQueryObservers() {
6692
+ for (const entry of [...this.mediaQueryObservers]) {
6693
+ if (entry.ownerPage !== this.currentPageInstance) continue;
6694
+ entry.notify();
6695
+ }
6696
+ }
6697
+ clearMediaQueryObservers(ownerPage) {
6698
+ for (const entry of [...this.mediaQueryObservers]) {
6699
+ if (ownerPage && entry.ownerPage !== ownerPage) continue;
6700
+ entry.disconnect();
6701
+ }
6702
+ }
5001
6703
  runPageComponentLifetime(route, lifetimeName, payload) {
5002
6704
  const prefix = `page:${stripLeadingSlash(route)}`;
5003
6705
  for (const [scopeId, instance] of this.componentCache.entries()) {
@@ -5009,6 +6711,100 @@ var HeadlessSession = class {
5009
6711
  for (const [scopeId, instance] of this.componentCache.entries()) if (instance === component) return scopeId;
5010
6712
  return null;
5011
6713
  }
6714
+ createVideoContext(videoId, scope) {
6715
+ return createHeadlessVideoContext({
6716
+ callScopeMethod: (scopeId, methodName, event) => this.callScopeMethod(scopeId, methodName, event),
6717
+ renderCurrentPage: () => this.renderCurrentPage(),
6718
+ resolveScope: (value) => {
6719
+ const current = this.currentPageInstance;
6720
+ if (!value || value === current) return { kind: "page" };
6721
+ const scopeId = this.getScopeIdForComponent(value);
6722
+ if (!scopeId) return { kind: "missing" };
6723
+ return {
6724
+ kind: "component",
6725
+ scopeId
6726
+ };
6727
+ }
6728
+ }, videoId, scope);
6729
+ }
6730
+ createAnimation(option) {
6731
+ return createHeadlessAnimation(option);
6732
+ }
6733
+ resolveCanvasScopeKey(scope) {
6734
+ const current = this.currentPageInstance;
6735
+ if (!scope || scope === current) return "page";
6736
+ const scopeId = this.getScopeIdForComponent(scope);
6737
+ return scopeId ? `component:${scopeId}` : "missing";
6738
+ }
6739
+ createCanvasContext(canvasId, scope) {
6740
+ const context = createHeadlessCanvasContext({
6741
+ renderCurrentPage: () => this.renderCurrentPage(),
6742
+ resolveScope: (value) => {
6743
+ const current = this.currentPageInstance;
6744
+ if (!value || value === current) return { kind: "page" };
6745
+ const scopeId = this.getScopeIdForComponent(value);
6746
+ if (!scopeId) return { kind: "missing" };
6747
+ return {
6748
+ kind: "component",
6749
+ scopeId
6750
+ };
6751
+ }
6752
+ }, canvasId, scope);
6753
+ this.canvasContexts.set(`${this.resolveCanvasScopeKey(scope)}:${canvasId}`, context);
6754
+ return context;
6755
+ }
6756
+ canvasToTempFilePath(option) {
6757
+ const context = this.canvasContexts.get(`${this.resolveCanvasScopeKey(option.component)}:${option.canvasId}`);
6758
+ if (!context) throw new Error(`canvasToTempFilePath:fail canvas "${option.canvasId}" has not been drawn in headless runtime.`);
6759
+ return {
6760
+ errMsg: "canvasToTempFilePath:ok",
6761
+ tempFilePath: this.wxState.createTempFile(JSON.stringify({
6762
+ canvasId: option.canvasId,
6763
+ config: {
6764
+ destHeight: option.destHeight,
6765
+ destWidth: option.destWidth,
6766
+ fileType: option.fileType,
6767
+ height: option.height,
6768
+ quality: option.quality,
6769
+ width: option.width,
6770
+ x: option.x,
6771
+ y: option.y
6772
+ },
6773
+ snapshot: context.__getSnapshot()
6774
+ }))
6775
+ };
6776
+ }
6777
+ createIntersectionObserver(scope, options) {
6778
+ return createHeadlessIntersectionObserver({
6779
+ getWindowInfo: () => this.getWindowInfo(),
6780
+ renderCurrentPage: () => this.renderCurrentPage(),
6781
+ resolveScope: (value) => {
6782
+ const current = this.currentPageInstance;
6783
+ if (!value || value === current) return { kind: "page" };
6784
+ const scopeId = this.getScopeIdForComponent(value);
6785
+ if (!scopeId) return { kind: "missing" };
6786
+ return {
6787
+ kind: "component",
6788
+ scopeId
6789
+ };
6790
+ }
6791
+ }, scope, options);
6792
+ }
6793
+ createMediaQueryObserver(scope) {
6794
+ const current = this.requireCurrentPage("createMediaQueryObserver()");
6795
+ const ownerPage = scope === current || !scope ? current : this.currentPageInstance ?? current;
6796
+ let entry;
6797
+ const controller = createHeadlessMediaQueryObserver({ getWindowInfo: () => this.getWindowInfo() }, () => {
6798
+ this.mediaQueryObservers.delete(entry);
6799
+ });
6800
+ entry = {
6801
+ disconnect: controller.disconnect,
6802
+ notify: controller.notify,
6803
+ ownerPage
6804
+ };
6805
+ this.mediaQueryObservers.add(entry);
6806
+ return controller.observer;
6807
+ }
5012
6808
  };
5013
6809
  function createHeadlessSession(options) {
5014
6810
  return new HeadlessSession(options);
@@ -5338,4 +7134,4 @@ async function launch(options) {
5338
7134
  return new HeadlessTestingSessionHandle(session.project, session);
5339
7135
  }
5340
7136
  //#endregion
5341
- export { BrowserHeadlessSession, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingScopeHandle, HeadlessTestingSessionHandle, cloneValue, coerceComponentPropertyValue, createAppInstance, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createHeadlessSession, createHeadlessWx, createHeadlessWxState, createHostRegistries, createPageInstance, createProjectDescriptor, executeSelectorQueryRequests, hasBrowserVirtualFile, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, registerAppDefinition, registerComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, renderRuntimePageTree, resolveRoutesFromAppConfig, resolveSelectorQueryScopeRoot, runComponentLifecycle, runComponentObservers, runComponentPageLifetime };
7137
+ 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, resolveSelectorScrollTop, runComponentLifecycle, runComponentObservers, runComponentPageLifetime };