@mpcore/simulator 0.1.2 → 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);
@@ -2486,22 +3147,22 @@ function querySelectorAll(root, selector) {
2486
3147
  }
2487
3148
  //#endregion
2488
3149
  //#region src/view/nodeHandle.ts
2489
- const DATASET_NAME_RE$2 = /-([a-z])/g;
3150
+ const DATASET_NAME_RE$3 = /-([a-z])/g;
2490
3151
  function escapeText$2(text) {
2491
3152
  return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
2492
3153
  }
2493
- function toDatasetKey$2(attributeName) {
2494
- 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());
2495
3156
  }
2496
- function collectDataset$2(node) {
3157
+ function collectDataset$3(node) {
2497
3158
  const dataset = {};
2498
3159
  for (const [key, value] of Object.entries(node.attribs ?? {})) {
2499
3160
  if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
2500
- dataset[toDatasetKey$2(key)] = value;
3161
+ dataset[toDatasetKey$3(key)] = value;
2501
3162
  }
2502
3163
  return dataset;
2503
3164
  }
2504
- function resolveEventBinding(node, eventName) {
3165
+ function resolveEventBinding$1(node, eventName) {
2505
3166
  const normalizedEventName = eventName.trim();
2506
3167
  if (!normalizedEventName) return null;
2507
3168
  const bindingAttrs = [
@@ -2516,8 +3177,8 @@ function resolveEventBinding(node, eventName) {
2516
3177
  }
2517
3178
  return null;
2518
3179
  }
2519
- function createEventPayload(node, eventName, event) {
2520
- const dataset = collectDataset$2(node);
3180
+ function createEventPayload$1(node, eventName, event) {
3181
+ const dataset = collectDataset$3(node);
2521
3182
  const nodeId = node.attribs?.id ?? "";
2522
3183
  return {
2523
3184
  bubbles: false,
@@ -2582,7 +3243,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
2582
3243
  return this.node.attribs?.[name];
2583
3244
  }
2584
3245
  async dataset() {
2585
- return collectDataset$2(this.node);
3246
+ return collectDataset$3(this.node);
2586
3247
  }
2587
3248
  async scope() {
2588
3249
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
@@ -2612,9 +3273,9 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
2612
3273
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
2613
3274
  const normalizedEventName = eventName.trim();
2614
3275
  if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
2615
- const methodName = resolveEventBinding(this.node, normalizedEventName);
3276
+ const methodName = resolveEventBinding$1(this.node, normalizedEventName);
2616
3277
  if (!methodName) throw new Error(`No ${normalizedEventName} binding was found on <${this.node.name ?? "unknown"}> in headless testing runtime.`);
2617
- 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));
2618
3279
  }
2619
3280
  async tap(event = {}) {
2620
3281
  return await this.trigger("tap", event);
@@ -2698,18 +3359,18 @@ function renderPageTree(project, page) {
2698
3359
  }
2699
3360
  //#endregion
2700
3361
  //#region src/view/selectorQuery.ts
2701
- const DATASET_NAME_RE$1 = /-([a-z])/g;
3362
+ const DATASET_NAME_RE$2 = /-([a-z])/g;
2702
3363
  const LEADING_MARK_PREFIX_RE = /^mark[:\-]?/;
2703
3364
  const MARK_NAME_RE = /[:\-]([a-z])/g;
2704
- const NUMERIC_LIKE_VALUE_RE = /-?\d+(?:\.\d+)?/;
2705
- function toDatasetKey$1(attributeName) {
2706
- 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());
2707
3368
  }
2708
- function collectDataset$1(node) {
3369
+ function collectDataset$2(node) {
2709
3370
  const dataset = {};
2710
3371
  for (const [key, value] of Object.entries(node.attribs ?? {})) {
2711
3372
  if (!key.startsWith("data-") || key.startsWith("data-sim-")) continue;
2712
- dataset[toDatasetKey$1(key)] = value;
3373
+ dataset[toDatasetKey$2(key)] = value;
2713
3374
  }
2714
3375
  return dataset;
2715
3376
  }
@@ -2738,7 +3399,7 @@ function findNodeByScopeId(root, scopeId) {
2738
3399
  }
2739
3400
  return null;
2740
3401
  }
2741
- function parseStyleDeclarations(styleValue) {
3402
+ function parseStyleDeclarations$1(styleValue) {
2742
3403
  const declarations = {};
2743
3404
  if (!styleValue) return declarations;
2744
3405
  for (const declaration of styleValue.split(";")) {
@@ -2749,17 +3410,17 @@ function parseStyleDeclarations(styleValue) {
2749
3410
  }
2750
3411
  return declarations;
2751
3412
  }
2752
- function parseNumericLikeValue(value) {
3413
+ function parseNumericLikeValue$1(value) {
2753
3414
  if (!value) return 0;
2754
- const match = value.match(NUMERIC_LIKE_VALUE_RE);
3415
+ const match = value.match(NUMERIC_LIKE_VALUE_RE$1);
2755
3416
  return match ? Number(match[0]) : 0;
2756
3417
  }
2757
- function resolveRect(node) {
2758
- const style = parseStyleDeclarations(node.attribs?.style);
2759
- const left = parseNumericLikeValue(node.attribs?.["data-sim-left"] ?? style.left);
2760
- const top = parseNumericLikeValue(node.attribs?.["data-sim-top"] ?? style.top);
2761
- const width = parseNumericLikeValue(node.attribs?.["data-sim-width"] ?? style.width);
2762
- 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);
2763
3424
  return {
2764
3425
  bottom: top + height,
2765
3426
  height,
@@ -2773,12 +3434,12 @@ function resolveSelectorScrollTop(root, selector) {
2773
3434
  const normalizedSelector = selector?.trim();
2774
3435
  if (!normalizedSelector) return null;
2775
3436
  const match = querySelectorAll(root, normalizedSelector)[0];
2776
- return match ? resolveRect(match).top : null;
3437
+ return match ? resolveRect$1(match).top : null;
2777
3438
  }
2778
3439
  function resolveScrollOffset(node) {
2779
3440
  return {
2780
- scrollLeft: parseNumericLikeValue(node.attribs?.["data-sim-scroll-left"]),
2781
- 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"])
2782
3443
  };
2783
3444
  }
2784
3445
  function resolvePropertyValue(node, propertyName) {
@@ -2786,7 +3447,7 @@ function resolvePropertyValue(node, propertyName) {
2786
3447
  if (!normalizedPropertyName) return;
2787
3448
  if (normalizedPropertyName === "id") return node.attribs?.id ?? "";
2788
3449
  if (normalizedPropertyName === "class") return node.attribs?.class ?? "";
2789
- if (normalizedPropertyName === "dataset") return collectDataset$1(node);
3450
+ if (normalizedPropertyName === "dataset") return collectDataset$2(node);
2790
3451
  return node.attribs?.[normalizedPropertyName];
2791
3452
  }
2792
3453
  function pickProperties(node, propertyNames) {
@@ -2795,18 +3456,18 @@ function pickProperties(node, propertyNames) {
2795
3456
  return result;
2796
3457
  }
2797
3458
  function pickComputedStyle(node, propertyNames) {
2798
- const style = parseStyleDeclarations(node.attribs?.style);
3459
+ const style = parseStyleDeclarations$1(node.attribs?.style);
2799
3460
  const result = {};
2800
3461
  for (const propertyName of propertyNames) result[propertyName] = style[propertyName] ?? "";
2801
3462
  return result;
2802
3463
  }
2803
- function resolveFieldsResult(node, fields, _options) {
3464
+ function resolveFieldsResult(node, fields, options) {
2804
3465
  const result = {};
2805
3466
  if (fields.id) result.id = node.attribs?.id ?? "";
2806
- if (fields.dataset) result.dataset = collectDataset$1(node);
3467
+ if (fields.dataset) result.dataset = collectDataset$2(node);
2807
3468
  if (fields.mark) result.mark = collectMark(node);
2808
3469
  if (fields.rect || fields.size) {
2809
- const rect = resolveRect(node);
3470
+ const rect = resolveRect$1(node);
2810
3471
  if (fields.rect) Object.assign(result, rect);
2811
3472
  if (fields.size) {
2812
3473
  result.width = rect.width;
@@ -2816,7 +3477,7 @@ function resolveFieldsResult(node, fields, _options) {
2816
3477
  if (fields.scrollOffset) Object.assign(result, resolveScrollOffset(node));
2817
3478
  if (Array.isArray(fields.properties) && fields.properties.length > 0) Object.assign(result, pickProperties(node, fields.properties));
2818
3479
  if (Array.isArray(fields.computedStyle) && fields.computedStyle.length > 0) Object.assign(result, pickComputedStyle(node, fields.computedStyle));
2819
- if (fields.context) result.context = { type: "unsupported-context" };
3480
+ if (fields.context) result.context = options.resolveContext?.(node) ?? { type: "unsupported-context" };
2820
3481
  if (fields.node) result.node = { type: node.name ?? "unknown" };
2821
3482
  return result;
2822
3483
  }
@@ -2859,6 +3520,749 @@ function resolveSelectorQueryScopeRoot(root, scopeId) {
2859
3520
  return scopedNode ? createScopedRoot(scopedNode) : root;
2860
3521
  }
2861
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
2862
4266
  //#region src/browser/session.ts
2863
4267
  const LEADING_SLASH_RE$3 = /^\/+/;
2864
4268
  const PAGE_STACK_LIMIT$1 = 10;
@@ -2951,6 +4355,8 @@ var BrowserHeadlessSession = class {
2951
4355
  tabBarState = /* @__PURE__ */ new Map();
2952
4356
  tabBarVisible = false;
2953
4357
  systemInfo = createDefaultSystemInfo();
4358
+ mediaQueryObservers = /* @__PURE__ */ new Set();
4359
+ canvasContexts = /* @__PURE__ */ new Map();
2954
4360
  enterOptions = createAppLaunchOptions$1("", {});
2955
4361
  launchOptions = createAppLaunchOptions$1("", {});
2956
4362
  wxState = createHeadlessWxState();
@@ -2984,7 +4390,20 @@ var BrowserHeadlessSession = class {
2984
4390
  });
2985
4391
  this.tabBarVisible = this.tabBarRoutes.size > 0;
2986
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),
2987
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),
2988
4407
  getFileSystemManager: () => this.wxState.getFileSystemManager(),
2989
4408
  getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
2990
4409
  getSavedFileList: () => this.wxState.getSavedFileList(),
@@ -3005,11 +4424,13 @@ var BrowserHeadlessSession = class {
3005
4424
  extraData: { ...this.launchOptions.referrerInfo.extraData }
3006
4425
  }
3007
4426
  }),
4427
+ getClipboardData: () => this.wxState.getClipboardData(),
3008
4428
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
3009
4429
  getNetworkType: () => this.wxState.getNetworkType(),
3010
4430
  navigateBack: (option) => this.navigateBack(option?.delta),
3011
4431
  navigateTo: (option) => this.navigateTo(option.url),
3012
4432
  pageScrollTo: (option) => this.pageScrollTo(option),
4433
+ openDocument: (option) => this.wxState.openDocument(option),
3013
4434
  clearStorageSync: () => this.wxState.clearStorageSync(),
3014
4435
  getStorageInfoSync: () => this.wxState.getStorageInfoSync(),
3015
4436
  getStorageSync: (key) => this.wxState.getStorageSync(key),
@@ -3021,14 +4442,18 @@ var BrowserHeadlessSession = class {
3021
4442
  reLaunch: (option) => this.reLaunch(option.url),
3022
4443
  redirectTo: (option) => this.redirectTo(option.url),
3023
4444
  removeSavedFile: (option) => this.wxState.removeSavedFile(option),
4445
+ saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
4446
+ saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
3024
4447
  nextTick: (callback) => queueMicrotask(() => callback?.()),
3025
4448
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
3026
4449
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
3027
4450
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
4451
+ previewImage: (option) => this.wxState.previewImage(option),
3028
4452
  request: (option) => this.wxState.request(option),
3029
4453
  saveFile: (option) => this.wxState.saveFile(option),
3030
4454
  setBackgroundColor: (option) => this.setBackgroundColor(option),
3031
4455
  setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
4456
+ setClipboardData: (option) => this.wxState.setClipboardData(option),
3032
4457
  setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
3033
4458
  setNavigationBarColor: (option) => this.setNavigationBarColor(option),
3034
4459
  setNavigationBarTitle: (option) => this.setNavigationBarTitle(option.title),
@@ -3044,6 +4469,7 @@ var BrowserHeadlessSession = class {
3044
4469
  showLoading: (option) => this.wxState.showLoading(option),
3045
4470
  showModal: (option) => this.wxState.showModal(option),
3046
4471
  showToast: (option) => this.wxState.showToast(option),
4472
+ startPullDownRefresh: () => this.startPullDownRefresh(),
3047
4473
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
3048
4474
  switchTab: (option) => this.switchTab(option.url),
3049
4475
  uploadFile: (option) => this.wxState.uploadFile(option),
@@ -3117,6 +4543,15 @@ var BrowserHeadlessSession = class {
3117
4543
  getStorageInfo() {
3118
4544
  return this.wxState.getStorageInfoSync();
3119
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
+ }
3120
4555
  getPullDownRefreshState() {
3121
4556
  return { ...this.pullDownRefreshState };
3122
4557
  }
@@ -3350,16 +4785,12 @@ var BrowserHeadlessSession = class {
3350
4785
  if (!candidateScopeId.includes("/")) return false;
3351
4786
  if (rootScopeId && candidateScopeId === rootScopeId) return false;
3352
4787
  if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
3353
- let partIndex = selectorParts.length - 1;
3354
- let currentScope = scope;
3355
- while (partIndex >= 0) {
3356
- if (!currentScope || !matchesComponentSelector$1(currentScope, selectorParts[partIndex])) {
3357
- currentScope = currentScope?.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
3358
- if (!currentScope) return false;
3359
- continue;
3360
- }
3361
- partIndex -= 1;
3362
- if (partIndex < 0) return true;
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;
3363
4794
  currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
3364
4795
  }
3365
4796
  return true;
@@ -3375,6 +4806,8 @@ var BrowserHeadlessSession = class {
3375
4806
  moduleLoader: this.moduleLoader,
3376
4807
  project: this.project,
3377
4808
  session: {
4809
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
4810
+ createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
3378
4811
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
3379
4812
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
3380
4813
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -3413,6 +4846,7 @@ var BrowserHeadlessSession = class {
3413
4846
  }
3414
4847
  const instance = this.componentCache.get(normalizedScopeId);
3415
4848
  if (!instance) throw new Error(`Unknown scope "${normalizedScopeId}" in browser simulator runtime.`);
4849
+ instance.__lastInteractionEvent__ = void 0;
3416
4850
  const method = instance[methodName];
3417
4851
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator component scope "${normalizedScopeId}".`);
3418
4852
  return method.apply(instance, args);
@@ -3561,6 +4995,8 @@ var BrowserHeadlessSession = class {
3561
4995
  moduleLoader: this.moduleLoader,
3562
4996
  project: this.project,
3563
4997
  session: {
4998
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
4999
+ createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
3564
5000
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
3565
5001
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
3566
5002
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -3578,6 +5014,10 @@ var BrowserHeadlessSession = class {
3578
5014
  current.onPullDownRefresh?.();
3579
5015
  return current;
3580
5016
  }
5017
+ startPullDownRefresh() {
5018
+ this.triggerPullDownRefresh();
5019
+ return { errMsg: "startPullDownRefresh:ok" };
5020
+ }
3581
5021
  triggerReachBottom() {
3582
5022
  const current = this.requireCurrentPage("triggerReachBottom()");
3583
5023
  current.onReachBottom?.();
@@ -3588,6 +5028,7 @@ var BrowserHeadlessSession = class {
3588
5028
  applyResizeToSystemInfo(this.systemInfo, options);
3589
5029
  current.onResize?.(options);
3590
5030
  this.runPageComponentLifetime(current.route, "resize", options);
5031
+ this.notifyMediaQueryObservers();
3591
5032
  return current;
3592
5033
  }
3593
5034
  triggerRouteDone(options = {}) {
@@ -3607,6 +5048,11 @@ var BrowserHeadlessSession = class {
3607
5048
  const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
3608
5049
  return executeSelectorQueryRequests(requests, {
3609
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
+ },
3610
5056
  root: resolveSelectorQueryScopeRoot(renderBrowserPageTree({
3611
5057
  changedPageKeys: current.__lastChangedKeys__ ?? [],
3612
5058
  componentCache: this.componentCache,
@@ -3615,6 +5061,8 @@ var BrowserHeadlessSession = class {
3615
5061
  moduleLoader: this.moduleLoader,
3616
5062
  project: this.project,
3617
5063
  session: {
5064
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
5065
+ createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
3618
5066
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
3619
5067
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
3620
5068
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -3632,6 +5080,8 @@ var BrowserHeadlessSession = class {
3632
5080
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
3633
5081
  navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
3634
5082
  });
5083
+ pageInstance.createIntersectionObserver = (options) => this.createIntersectionObserver(pageInstance, options);
5084
+ pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
3635
5085
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
3636
5086
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
3637
5087
  pageInstance.onLoad?.(target.query);
@@ -3681,10 +5131,12 @@ var BrowserHeadlessSession = class {
3681
5131
  this.tabPages.clear();
3682
5132
  this.componentCache.clear();
3683
5133
  this.componentScopes.clear();
5134
+ this.clearMediaQueryObservers();
3684
5135
  this.currentPageInstance = null;
3685
5136
  }
3686
5137
  unloadPage(page) {
3687
5138
  page.onUnload?.();
5139
+ this.clearMediaQueryObservers(page);
3688
5140
  this.detachPageComponents(page.route);
3689
5141
  this.tabPages.delete(stripLeadingSlash$1(page.route));
3690
5142
  }
@@ -3703,6 +5155,18 @@ var BrowserHeadlessSession = class {
3703
5155
  this.componentScopes.delete(scopeId);
3704
5156
  }
3705
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
+ }
3706
5170
  runPageComponentLifetime(route, lifetimeName, payload) {
3707
5171
  const prefix = `page:${stripLeadingSlash$1(route)}`;
3708
5172
  for (const [scopeId, instance] of this.componentCache.entries()) {
@@ -3714,6 +5178,100 @@ var BrowserHeadlessSession = class {
3714
5178
  for (const [scopeId, instance] of this.componentCache.entries()) if (instance === component) return scopeId;
3715
5179
  return null;
3716
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
+ }
3717
5275
  };
3718
5276
  function createBrowserHeadlessSession(options) {
3719
5277
  return new BrowserHeadlessSession(options);
@@ -4137,6 +5695,8 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
4137
5695
  properties: nextProperties,
4138
5696
  triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
4139
5697
  });
5698
+ componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
5699
+ componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
4140
5700
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
4141
5701
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
4142
5702
  componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
@@ -4396,6 +5956,8 @@ var HeadlessSession = class {
4396
5956
  tabBarState = /* @__PURE__ */ new Map();
4397
5957
  tabBarVisible = false;
4398
5958
  systemInfo = createDefaultSystemInfo();
5959
+ mediaQueryObservers = /* @__PURE__ */ new Set();
5960
+ canvasContexts = /* @__PURE__ */ new Map();
4399
5961
  enterOptions = createAppLaunchOptions("", {});
4400
5962
  launchOptions = createAppLaunchOptions("", {});
4401
5963
  wxState = createHeadlessWxState();
@@ -4428,7 +5990,20 @@ var HeadlessSession = class {
4428
5990
  });
4429
5991
  this.tabBarVisible = this.tabBarRoutes.size > 0;
4430
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),
4431
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),
4432
6007
  getFileSystemManager: () => this.wxState.getFileSystemManager(),
4433
6008
  getSavedFileInfo: (option) => this.wxState.getSavedFileInfo(option),
4434
6009
  getSavedFileList: () => this.wxState.getSavedFileList(),
@@ -4449,11 +6024,13 @@ var HeadlessSession = class {
4449
6024
  extraData: { ...this.launchOptions.referrerInfo.extraData }
4450
6025
  }
4451
6026
  }),
6027
+ getClipboardData: () => this.wxState.getClipboardData(),
4452
6028
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
4453
6029
  getNetworkType: () => this.wxState.getNetworkType(),
4454
6030
  navigateBack: (option) => this.navigateBack(option?.delta),
4455
6031
  navigateTo: (option) => this.navigateTo(option.url),
4456
6032
  pageScrollTo: (option) => this.pageScrollTo(option),
6033
+ openDocument: (option) => this.wxState.openDocument(option),
4457
6034
  clearStorageSync: () => this.wxState.clearStorageSync(),
4458
6035
  getStorageInfoSync: () => this.wxState.getStorageInfoSync(),
4459
6036
  getStorageSync: (key) => this.wxState.getStorageSync(key),
@@ -4465,14 +6042,18 @@ var HeadlessSession = class {
4465
6042
  reLaunch: (option) => this.reLaunch(option.url),
4466
6043
  redirectTo: (option) => this.redirectTo(option.url),
4467
6044
  removeSavedFile: (option) => this.wxState.removeSavedFile(option),
6045
+ saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
6046
+ saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
4468
6047
  nextTick: (callback) => queueMicrotask(() => callback?.()),
4469
6048
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
4470
6049
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
4471
6050
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
6051
+ previewImage: (option) => this.wxState.previewImage(option),
4472
6052
  request: (option) => this.wxState.request(option),
4473
6053
  saveFile: (option) => this.wxState.saveFile(option),
4474
6054
  setBackgroundColor: (option) => this.setBackgroundColor(option),
4475
6055
  setBackgroundTextStyle: (option) => this.setBackgroundTextStyle(option.textStyle),
6056
+ setClipboardData: (option) => this.wxState.setClipboardData(option),
4476
6057
  setStorageSync: (key, value) => this.wxState.setStorageSync(key, value),
4477
6058
  setNavigationBarColor: (option) => this.setNavigationBarColor(option),
4478
6059
  setNavigationBarTitle: (option) => this.setNavigationBarTitle(option.title),
@@ -4488,6 +6069,7 @@ var HeadlessSession = class {
4488
6069
  showLoading: (option) => this.wxState.showLoading(option),
4489
6070
  showModal: (option) => this.wxState.showModal(option),
4490
6071
  showToast: (option) => this.wxState.showToast(option),
6072
+ startPullDownRefresh: () => this.startPullDownRefresh(),
4491
6073
  stopPullDownRefresh: () => this.stopPullDownRefresh(),
4492
6074
  switchTab: (option) => this.switchTab(option.url),
4493
6075
  uploadFile: (option) => this.wxState.uploadFile(option),
@@ -4546,6 +6128,8 @@ var HeadlessSession = class {
4546
6128
  moduleLoader: this.moduleLoader,
4547
6129
  project: this.project,
4548
6130
  session: {
6131
+ createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
6132
+ createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
4549
6133
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
4550
6134
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
4551
6135
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -4613,6 +6197,7 @@ var HeadlessSession = class {
4613
6197
  }
4614
6198
  const instance = this.componentCache.get(normalizedScopeId);
4615
6199
  if (!instance) throw new Error(`Unknown scope "${normalizedScopeId}" in headless runtime.`);
6200
+ instance.__lastInteractionEvent__ = void 0;
4616
6201
  const method = instance[methodName];
4617
6202
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless component scope "${normalizedScopeId}".`);
4618
6203
  return method.apply(instance, args);
@@ -4662,6 +6247,15 @@ var HeadlessSession = class {
4662
6247
  getStorageInfo() {
4663
6248
  return this.wxState.getStorageInfoSync();
4664
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
+ }
4665
6259
  getPullDownRefreshState() {
4666
6260
  return { ...this.pullDownRefreshState };
4667
6261
  }
@@ -4948,6 +6542,10 @@ var HeadlessSession = class {
4948
6542
  current.onPullDownRefresh?.();
4949
6543
  return current;
4950
6544
  }
6545
+ startPullDownRefresh() {
6546
+ this.triggerPullDownRefresh();
6547
+ return { errMsg: "startPullDownRefresh:ok" };
6548
+ }
4951
6549
  triggerReachBottom() {
4952
6550
  const current = this.requireCurrentPage("triggerReachBottom()");
4953
6551
  current.onReachBottom?.();
@@ -4958,6 +6556,7 @@ var HeadlessSession = class {
4958
6556
  applyResizeToSystemInfo(this.systemInfo, options);
4959
6557
  current.onResize?.(options);
4960
6558
  this.runPageComponentLifetime(current.route, "resize", options);
6559
+ this.notifyMediaQueryObservers();
4961
6560
  return current;
4962
6561
  }
4963
6562
  triggerRouteDone(options = {}) {
@@ -4978,6 +6577,11 @@ var HeadlessSession = class {
4978
6577
  const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
4979
6578
  return executeSelectorQueryRequests(requests, {
4980
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
+ },
4981
6585
  root: resolveSelectorQueryScopeRoot(rendered.root, scopeId),
4982
6586
  windowInfo: this.getWindowInfo()
4983
6587
  });
@@ -4991,6 +6595,8 @@ var HeadlessSession = class {
4991
6595
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
4992
6596
  navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
4993
6597
  });
6598
+ pageInstance.createIntersectionObserver = (options) => this.createIntersectionObserver(pageInstance, options);
6599
+ pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
4994
6600
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
4995
6601
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
4996
6602
  pageInstance.onLoad?.(target.query);
@@ -5040,10 +6646,12 @@ var HeadlessSession = class {
5040
6646
  this.tabPages.clear();
5041
6647
  this.componentCache.clear();
5042
6648
  this.componentScopes.clear();
6649
+ this.clearMediaQueryObservers();
5043
6650
  this.currentPageInstance = null;
5044
6651
  }
5045
6652
  unloadPage(page) {
5046
6653
  page.onUnload?.();
6654
+ this.clearMediaQueryObservers(page);
5047
6655
  this.detachPageComponents(page.route);
5048
6656
  this.tabPages.delete(stripLeadingSlash(page.route));
5049
6657
  }
@@ -5060,16 +6668,12 @@ var HeadlessSession = class {
5060
6668
  if (!candidateScopeId.includes("/")) return false;
5061
6669
  if (rootScopeId && candidateScopeId === rootScopeId) return false;
5062
6670
  if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
5063
- let partIndex = selectorParts.length - 1;
5064
- let currentScope = scope;
5065
- while (partIndex >= 0) {
5066
- if (!currentScope || !matchesComponentSelector(currentScope, selectorParts[partIndex])) {
5067
- currentScope = currentScope?.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
5068
- if (!currentScope) return false;
5069
- continue;
5070
- }
5071
- partIndex -= 1;
5072
- if (partIndex < 0) return true;
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;
5073
6677
  currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
5074
6678
  }
5075
6679
  return true;
@@ -5084,6 +6688,18 @@ var HeadlessSession = class {
5084
6688
  this.componentScopes.delete(scopeId);
5085
6689
  }
5086
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
+ }
5087
6703
  runPageComponentLifetime(route, lifetimeName, payload) {
5088
6704
  const prefix = `page:${stripLeadingSlash(route)}`;
5089
6705
  for (const [scopeId, instance] of this.componentCache.entries()) {
@@ -5095,6 +6711,100 @@ var HeadlessSession = class {
5095
6711
  for (const [scopeId, instance] of this.componentCache.entries()) if (instance === component) return scopeId;
5096
6712
  return null;
5097
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
+ }
5098
6808
  };
5099
6809
  function createHeadlessSession(options) {
5100
6810
  return new HeadlessSession(options);