@qontinui/ui-bridge-wrapper 0.12.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +157 -8
  2. package/dist/capture-specs-cli.cjs +301 -53
  3. package/dist/capture-specs-cli.cjs.map +1 -1
  4. package/dist/capture-specs-cli.d.ts.map +1 -1
  5. package/dist/chunk-IKHDNIU4.js +478 -0
  6. package/dist/chunk-IKHDNIU4.js.map +1 -0
  7. package/dist/chunk-Z32CC665.cjs +488 -0
  8. package/dist/chunk-Z32CC665.cjs.map +1 -0
  9. package/dist/create-transport.d.ts.map +1 -1
  10. package/dist/frame-capture.d.ts +3 -28
  11. package/dist/frame-capture.d.ts.map +1 -1
  12. package/dist/frame-page.d.ts +35 -0
  13. package/dist/frame-page.d.ts.map +1 -0
  14. package/dist/index.cjs +145 -375
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.ts +1 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +90 -351
  19. package/dist/index.js.map +1 -1
  20. package/dist/inject-cli.cjs +407 -134
  21. package/dist/inject-cli.cjs.map +1 -1
  22. package/dist/inject-cli.d.ts +1 -1
  23. package/dist/inject-cli.d.ts.map +1 -1
  24. package/dist/live/index.cjs +40 -0
  25. package/dist/live/index.cjs.map +1 -0
  26. package/dist/live/index.d.ts +32 -0
  27. package/dist/live/index.d.ts.map +1 -0
  28. package/dist/live/index.js +3 -0
  29. package/dist/live/index.js.map +1 -0
  30. package/dist/login-web-cli.cjs +312 -61
  31. package/dist/login-web-cli.cjs.map +1 -1
  32. package/dist/login-web-cli.d.ts.map +1 -1
  33. package/dist/network-throttle.d.ts +5 -0
  34. package/dist/network-throttle.d.ts.map +1 -1
  35. package/dist/screenshot-capture.d.ts +82 -0
  36. package/dist/screenshot-capture.d.ts.map +1 -0
  37. package/dist/timeline-capture.d.ts +74 -10
  38. package/dist/timeline-capture.d.ts.map +1 -1
  39. package/dist/transports/headless.d.ts +46 -1
  40. package/dist/transports/headless.d.ts.map +1 -1
  41. package/dist/transports/injected.d.ts +8 -0
  42. package/dist/transports/injected.d.ts.map +1 -1
  43. package/dist/transports/live.d.ts +27 -1
  44. package/dist/transports/live.d.ts.map +1 -1
  45. package/dist/types.d.ts +3 -1
  46. package/dist/types.d.ts.map +1 -1
  47. package/package.json +11 -8
  48. package/dist/cli-args.d.ts +0 -13
  49. package/dist/cli-args.d.ts.map +0 -1
@@ -5,48 +5,14 @@ var fs = require('fs');
5
5
  var path = require('path');
6
6
  var module$1 = require('module');
7
7
  var crypto = require('crypto');
8
- var ui_bridge_cli_args_star = require('@qontinui/ui-bridge-cli-args');
9
8
 
10
9
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
11
- function _interopNamespace(e) {
12
- if (e && e.__esModule) return e;
13
- var n = Object.create(null);
14
- if (e) {
15
- Object.keys(e).forEach(function (k) {
16
- if (k !== 'default') {
17
- var d = Object.getOwnPropertyDescriptor(e, k);
18
- Object.defineProperty(n, k, d.get ? d : {
19
- enumerable: true,
20
- get: function () { return e[k]; }
21
- });
22
- }
23
- });
24
- }
25
- n.default = e;
26
- return Object.freeze(n);
27
- }
28
-
29
- var ui_bridge_cli_args_star__namespace = /*#__PURE__*/_interopNamespace(ui_bridge_cli_args_star);
30
-
31
- var __defProp = Object.defineProperty;
32
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
33
- var __getOwnPropNames = Object.getOwnPropertyNames;
34
- var __hasOwnProp = Object.prototype.hasOwnProperty;
35
10
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
36
11
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
37
12
  }) : x)(function(x) {
38
13
  if (typeof require !== "undefined") return require.apply(this, arguments);
39
14
  throw Error('Dynamic require of "' + x + '" is not supported');
40
15
  });
41
- var __copyProps = (to, from, except, desc) => {
42
- if (from && typeof from === "object" || typeof from === "function") {
43
- for (let key of __getOwnPropNames(from))
44
- if (!__hasOwnProp.call(to, key) && key !== except)
45
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
46
- }
47
- return to;
48
- };
49
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget);
50
16
 
51
17
  // src/types.ts
52
18
  var WrapperTransportError = class extends Error {
@@ -280,9 +246,60 @@ var HeadlessTransport = class extends BaseTransport {
280
246
  userAgent: typeof raw["userAgent"] === "string" ? raw["userAgent"] : void 0,
281
247
  forwardConsole: typeof raw["forwardConsole"] === "boolean" ? raw["forwardConsole"] : void 0,
282
248
  launchArgs: Array.isArray(raw["launchArgs"]) && raw["launchArgs"].every((a) => typeof a === "string") ? raw["launchArgs"] : void 0,
283
- storageStatePath: typeof raw["storageStatePath"] === "string" ? raw["storageStatePath"] : void 0
249
+ storageStatePath: typeof raw["storageStatePath"] === "string" ? raw["storageStatePath"] : void 0,
250
+ ...this.parseContextOptions(raw)
284
251
  };
285
252
  }
253
+ /**
254
+ * `recordHar`, `recordVideo`, `serviceWorkers` and `initRouter`. Unlike the display
255
+ * options above, a malformed value is REFUSED rather than dropped: dropping
256
+ * `recordHar` would leave a caller waiting for an archive that is never
257
+ * written, and dropping `initRouter` would let requests it meant to answer
258
+ * reach the network.
259
+ */
260
+ parseContextOptions(raw) {
261
+ const out = {};
262
+ const invalid = (what) => new WrapperTransportError("INVALID_CONFIG", `Transport kind '${this.kind}': ${what}`);
263
+ const har = raw["recordHar"];
264
+ if (har !== void 0) {
265
+ if (typeof har !== "object" || har === null || typeof har.path !== "string" || har.path.length === 0) {
266
+ throw invalid("options.recordHar must be an object with a non-empty string `path`");
267
+ }
268
+ out.recordHar = har;
269
+ }
270
+ const video = raw["recordVideo"];
271
+ if (video !== void 0) {
272
+ if (typeof video !== "object" || video === null || typeof video.dir !== "string" || video.dir.length === 0) {
273
+ throw invalid("options.recordVideo must be an object with a non-empty string `dir`");
274
+ }
275
+ const size = video.size;
276
+ if (size !== void 0) {
277
+ const positiveInt = (n) => typeof n === "number" && Number.isInteger(n) && n > 0;
278
+ const s = size;
279
+ if (typeof size !== "object" || s === null || !positiveInt(s.width) || !positiveInt(s.height)) {
280
+ throw invalid(
281
+ "options.recordVideo.size must be { width, height } with positive integer sides"
282
+ );
283
+ }
284
+ }
285
+ out.recordVideo = video;
286
+ }
287
+ const sw = raw["serviceWorkers"];
288
+ if (sw !== void 0) {
289
+ if (sw !== "allow" && sw !== "block") {
290
+ throw invalid(`options.serviceWorkers must be 'allow' or 'block' (got ${String(sw)})`);
291
+ }
292
+ out.serviceWorkers = sw;
293
+ }
294
+ const router = raw["initRouter"];
295
+ if (router !== void 0) {
296
+ if (typeof router !== "function") {
297
+ throw invalid("options.initRouter must be a function (context) => void | Promise<void>");
298
+ }
299
+ out.initRouter = router;
300
+ }
301
+ return out;
302
+ }
286
303
  async onReady() {
287
304
  let launchHeadlessTab;
288
305
  const headlessSpecifier = "@qontinui/ui-bridge-headless";
@@ -310,6 +327,13 @@ Underlying import error: ${cause}`
310
327
  const initScripts = await this.buildInitScripts();
311
328
  const relayAuth = this.relayAuth();
312
329
  const pinnedTabId = this.pinnedTabId();
330
+ const { recordHar, recordVideo, serviceWorkers, initRouter: callerRouter } = this.options;
331
+ const contextOptionsRequested = recordHar !== void 0 || recordVideo !== void 0 || serviceWorkers === "block" || callerRouter !== void 0;
332
+ let routerCalled = false;
333
+ const initRouter = contextOptionsRequested || serviceWorkers !== void 0 ? async (context) => {
334
+ routerCalled = true;
335
+ if (callerRouter) await callerRouter(context);
336
+ } : void 0;
313
337
  let tab;
314
338
  try {
315
339
  tab = await launchHeadlessTab({
@@ -328,7 +352,11 @@ Underlying import error: ${cause}`
328
352
  storageStatePath: this.options.storageStatePath,
329
353
  ...relayAuth.authToken ? { authToken: relayAuth.authToken } : {},
330
354
  ...relayAuth.callerUserId ? { callerUserId: relayAuth.callerUserId } : {},
331
- ...pinnedTabId ? { pinnedTabId } : {}
355
+ ...pinnedTabId ? { pinnedTabId } : {},
356
+ ...recordHar !== void 0 ? { recordHar } : {},
357
+ ...recordVideo !== void 0 ? { recordVideo } : {},
358
+ ...serviceWorkers !== void 0 ? { serviceWorkers } : {},
359
+ ...initRouter ? { initRouter } : {}
332
360
  });
333
361
  } catch (err) {
334
362
  const cause = err instanceof Error ? err.message : String(err);
@@ -350,6 +378,24 @@ Underlying launch error: ${cause}`
350
378
  tabId: tab.tabId,
351
379
  close: tab.close
352
380
  };
381
+ if (contextOptionsRequested && !routerCalled) {
382
+ await this.onClose().catch(() => {
383
+ });
384
+ throw new WrapperTransportError(
385
+ "CONTEXT_OPTIONS_NOT_APPLIED",
386
+ `The installed '@qontinui/ui-bridge-headless' peer launched the tab without calling initRouter, so it predates the recordHar / recordVideo / serviceWorkers / initRouter passthrough (0.8.0, ui-bridge#381) and ignored them: no HAR or video would be written and no route installed. Upgrade it to 0.8.0 or later.`,
387
+ {
388
+ details: {
389
+ requested: {
390
+ recordHar: recordHar !== void 0,
391
+ recordVideo: recordVideo !== void 0,
392
+ serviceWorkers: serviceWorkers ?? null,
393
+ initRouter: callerRouter !== void 0
394
+ }
395
+ }
396
+ }
397
+ );
398
+ }
353
399
  await this.verifyEmulation(tab.page);
354
400
  await this.afterLaunch(tab.page);
355
401
  }
@@ -696,6 +742,7 @@ var InjectedTransport = class extends HeadlessTransport {
696
742
  execute,
697
743
  find: (criteria) => execute("find", criteria ?? {}),
698
744
  act: (id, request) => execute("executeElementAction", { id, request }),
745
+ element: (id) => execute("getElement", { id }),
699
746
  snapshot: (options) => execute("getControlSnapshot", options ?? {}),
700
747
  assert: (spec) => execute("aiAssert", spec)
701
748
  };
@@ -707,6 +754,113 @@ function isRegistrationMetadata(value) {
707
754
  return typeof v.userId === "string" && typeof v.sessionId === "string";
708
755
  }
709
756
 
757
+ // src/frame-page.ts
758
+ var PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
759
+ function pngDimensions(buf) {
760
+ if (buf.length < 24 || PNG_SIGNATURE.some((b, i) => buf[i] !== b)) {
761
+ throw new Error("not a PNG (signature mismatch or truncated header)");
762
+ }
763
+ const chunkType = String.fromCharCode(buf[12], buf[13], buf[14], buf[15]);
764
+ if (chunkType !== "IHDR") {
765
+ throw new Error(`PNG does not start with an IHDR chunk (found ${JSON.stringify(chunkType)})`);
766
+ }
767
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
768
+ return { width: view.getUint32(16), height: view.getUint32(20) };
769
+ }
770
+ async function readPageMetrics(page) {
771
+ return page.evaluate(() => ({
772
+ devicePixelRatio: window.devicePixelRatio,
773
+ innerWidth: window.innerWidth,
774
+ innerHeight: window.innerHeight,
775
+ colorScheme: window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
776
+ }));
777
+ }
778
+
779
+ // src/screenshot-capture.ts
780
+ var SCREENSHOT_CAPABILITY = "screenshot";
781
+ var SCREENSHOT_ACTION = "getScreenshot";
782
+ var SCREENSHOT_TIMEOUT_MS = 1e4;
783
+ var NO_COMPOSITOR_FRAME = /Unable to capture screenshot/;
784
+ var NO_COMPOSITOR_FRAME_RETRY_MS = 16;
785
+ function toBase64(bytes) {
786
+ const CHUNK = 32768;
787
+ let binary = "";
788
+ for (let i = 0; i < bytes.length; i += CHUNK) {
789
+ binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
790
+ }
791
+ return btoa(binary);
792
+ }
793
+ function errorText(err) {
794
+ return err instanceof Error ? err.message : String(err);
795
+ }
796
+ async function captureScreenshotReply(page, options = {}) {
797
+ const timeoutMs = options.timeoutMs ?? SCREENSHOT_TIMEOUT_MS;
798
+ const retryMs = options.retryMs ?? NO_COMPOSITOR_FRAME_RETRY_MS;
799
+ const deadline = Date.now() + timeoutMs;
800
+ let timedOut = false;
801
+ let timer;
802
+ const attempt = async () => {
803
+ let metrics;
804
+ try {
805
+ metrics = await readPageMetrics(page);
806
+ } catch (err) {
807
+ throw new WrapperTransportError(
808
+ "SCREENSHOT_FAILED",
809
+ `could not read the page's viewport: ${errorText(err)}`,
810
+ { cause: err }
811
+ );
812
+ }
813
+ for (; ; ) {
814
+ let png;
815
+ try {
816
+ png = await page.screenshot({ type: "png", scale: "device", fullPage: false });
817
+ } catch (err) {
818
+ const text = errorText(err);
819
+ const noFrameYet = NO_COMPOSITOR_FRAME.test(text);
820
+ if (noFrameYet && !timedOut && Date.now() + retryMs < deadline) {
821
+ await new Promise((r) => setTimeout(r, retryMs));
822
+ if (timedOut) throw err;
823
+ continue;
824
+ }
825
+ throw new WrapperTransportError("SCREENSHOT_FAILED", `screenshot failed: ${text}`, {
826
+ retryable: noFrameYet,
827
+ cause: err
828
+ });
829
+ }
830
+ try {
831
+ pngDimensions(png);
832
+ } catch (err) {
833
+ throw new WrapperTransportError(
834
+ "SCREENSHOT_FAILED",
835
+ `the screenshot is unreadable: ${errorText(err)}`,
836
+ { cause: err }
837
+ );
838
+ }
839
+ return { screenshot: toBase64(png), width: metrics.innerWidth, height: metrics.innerHeight };
840
+ }
841
+ };
842
+ const timeout = new Promise((_, reject) => {
843
+ timer = setTimeout(() => {
844
+ timedOut = true;
845
+ reject(
846
+ new WrapperTransportError(
847
+ "SCREENSHOT_TIMEOUT",
848
+ `screenshot did not complete within ${timeoutMs}ms`,
849
+ { retryable: true }
850
+ )
851
+ );
852
+ }, timeoutMs);
853
+ });
854
+ try {
855
+ return await Promise.race([attempt(), timeout]);
856
+ } finally {
857
+ clearTimeout(timer);
858
+ }
859
+ }
860
+ function registerScreenshotCapture(registrar, page, options = {}) {
861
+ registrar.register(SCREENSHOT_ACTION, () => captureScreenshotReply(page, options));
862
+ }
863
+
710
864
  // src/transports/live.ts
711
865
  var LiveSessionTransport = class extends BaseTransport {
712
866
  kind = "live";
@@ -726,6 +880,16 @@ var LiveSessionTransport = class extends BaseTransport {
726
880
  this.appId = config.appId;
727
881
  this.appName = config.appName;
728
882
  this.opts = config.options ?? {};
883
+ const page = this.opts.screenshotPage;
884
+ if (page !== void 0) {
885
+ if (page === null || typeof page.screenshot !== "function" || typeof page.evaluate !== "function") {
886
+ throw new WrapperTransportError(
887
+ "INVALID_CONFIG",
888
+ `options.screenshotPage must expose screenshot() and evaluate() (a Playwright Page does)`
889
+ );
890
+ }
891
+ registerScreenshotCapture(this.registry, page);
892
+ }
729
893
  const fromInjection = injected?.webSocketCtor;
730
894
  const fromGlobal = typeof globalThis.WebSocket === "function" ? globalThis.WebSocket : void 0;
731
895
  const resolved = fromInjection ?? fromGlobal;
@@ -755,7 +919,8 @@ var LiveSessionTransport = class extends BaseTransport {
755
919
  };
756
920
  if (this.opts.framework !== void 0) frame.framework = this.opts.framework;
757
921
  if (this.opts.version !== void 0) frame.version = this.opts.version;
758
- if (this.opts.capabilities !== void 0) frame.capabilities = this.opts.capabilities;
922
+ const capabilities = this.advertisedCapabilities();
923
+ if (capabilities !== void 0) frame.capabilities = capabilities;
759
924
  if (this.opts.origin !== void 0) frame.origin = this.opts.origin;
760
925
  if (this.opts.pageUrl !== void 0) frame.pageUrl = this.opts.pageUrl;
761
926
  ws.send(JSON.stringify(frame));
@@ -795,6 +960,18 @@ var LiveSessionTransport = class extends BaseTransport {
795
960
  }
796
961
  }
797
962
  }
963
+ /**
964
+ * The register frame's `capabilities`: the caller's list, plus
965
+ * `"screenshot"` exactly when this transport registered the handler for it.
966
+ * `undefined` (field omitted) when there is nothing to advertise.
967
+ */
968
+ advertisedCapabilities() {
969
+ const declared = this.opts.capabilities;
970
+ if (this.opts.screenshotPage === void 0) return declared;
971
+ const list = [...declared ?? []];
972
+ if (!list.includes(SCREENSHOT_CAPABILITY)) list.push(SCREENSHOT_CAPABILITY);
973
+ return list;
974
+ }
798
975
  async buildContext() {
799
976
  return { kind: "live", commandId: null };
800
977
  }
@@ -916,9 +1093,33 @@ function createTransport(config) {
916
1093
  }
917
1094
  }
918
1095
 
919
- // src/cli-args.ts
920
- var cli_args_exports = {};
921
- __reExport(cli_args_exports, ui_bridge_cli_args_star__namespace);
1096
+ // ../ui-bridge-cli-args/dist/index.js
1097
+ function isFlagShaped(value) {
1098
+ return value.startsWith("--");
1099
+ }
1100
+ function consumeValue(flag, raw, error) {
1101
+ if (raw === void 0) return null;
1102
+ if (isFlagShaped(raw)) {
1103
+ throw error(
1104
+ `${flag} expects a value but got the flag '${raw}' \u2014 did you omit ${flag}'s argument?`
1105
+ );
1106
+ }
1107
+ return raw;
1108
+ }
1109
+ function parseNonNegativeInt(flag, raw, error) {
1110
+ const n = raw !== null && /^\d+$/.test(raw) ? Number(raw) : NaN;
1111
+ if (!Number.isSafeInteger(n)) {
1112
+ throw error(`${flag} expects a non-negative integer (got ${raw ?? "<missing>"})`);
1113
+ }
1114
+ return n;
1115
+ }
1116
+ function parsePositiveInt(flag, raw, error) {
1117
+ const n = raw !== null && /^\d+$/.test(raw) ? Number(raw) : NaN;
1118
+ if (!Number.isSafeInteger(n) || n <= 0) {
1119
+ throw error(`${flag} expects a positive integer (got ${raw ?? "<missing>"})`);
1120
+ }
1121
+ return n;
1122
+ }
922
1123
 
923
1124
  // src/inject-cli-errors.ts
924
1125
  var InjectCliArgError = class extends Error {
@@ -935,7 +1136,7 @@ var NETWORK_PRESETS = {
935
1136
  };
936
1137
  var MAX_LATENCY_MS = 6e4;
937
1138
  var MAX_THROUGHPUT_KBPS = 1e7;
938
- function parsePositiveInt(raw, field, max, allowZero) {
1139
+ function parsePositiveInt2(raw, field, max, allowZero) {
939
1140
  const n = /^\d+$/.test(raw) ? Number(raw) : Number.NaN;
940
1141
  if (!Number.isFinite(n) || n > max || !allowZero && n === 0) {
941
1142
  throw new InjectCliArgError(
@@ -973,9 +1174,9 @@ function parseThrottle(raw) {
973
1174
  }
974
1175
  return {
975
1176
  name: "custom",
976
- latencyMs: parsePositiveInt(fields.get("latency"), "latency", MAX_LATENCY_MS, true),
977
- downloadKbps: parsePositiveInt(fields.get("down"), "down", MAX_THROUGHPUT_KBPS, false),
978
- uploadKbps: parsePositiveInt(fields.get("up"), "up", MAX_THROUGHPUT_KBPS, false)
1177
+ latencyMs: parsePositiveInt2(fields.get("latency"), "latency", MAX_LATENCY_MS, true),
1178
+ downloadKbps: parsePositiveInt2(fields.get("down"), "down", MAX_THROUGHPUT_KBPS, false),
1179
+ uploadKbps: parsePositiveInt2(fields.get("up"), "up", MAX_THROUGHPUT_KBPS, false)
979
1180
  };
980
1181
  }
981
1182
  function cdpConditions(profile) {
@@ -1021,18 +1222,6 @@ function writePrivateFile(path$1, data) {
1021
1222
  throw err;
1022
1223
  }
1023
1224
  }
1024
- var PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
1025
- function pngDimensions(buf) {
1026
- if (buf.length < 24 || PNG_SIGNATURE.some((b, i) => buf[i] !== b)) {
1027
- throw new Error("not a PNG (signature mismatch or truncated header)");
1028
- }
1029
- const chunkType = String.fromCharCode(buf[12], buf[13], buf[14], buf[15]);
1030
- if (chunkType !== "IHDR") {
1031
- throw new Error(`PNG does not start with an IHDR chunk (found ${JSON.stringify(chunkType)})`);
1032
- }
1033
- const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
1034
- return { width: view.getUint32(16), height: view.getUint32(20) };
1035
- }
1036
1225
  function fileNameStart(path) {
1037
1226
  return Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1;
1038
1227
  }
@@ -1046,14 +1235,6 @@ function frameTokenInDirectory(template) {
1046
1235
  function frameTokenInFileName(template) {
1047
1236
  return template.slice(fileNameStart(template)).includes(FRAME_INDEX_TOKEN);
1048
1237
  }
1049
- async function readPageMetrics(page) {
1050
- return page.evaluate(() => ({
1051
- devicePixelRatio: window.devicePixelRatio,
1052
- innerWidth: window.innerWidth,
1053
- innerHeight: window.innerHeight,
1054
- colorScheme: window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
1055
- }));
1056
- }
1057
1238
  function isRecord(v) {
1058
1239
  return typeof v === "object" && v !== null && !Array.isArray(v);
1059
1240
  }
@@ -1181,6 +1362,7 @@ var CAPTURE_TIMELINE_ACTION = "captureTimeline";
1181
1362
  var MAX_TIMELINE_FRAMES = 120;
1182
1363
  var MAX_TIMELINE_INTERVAL_MS = 1e4;
1183
1364
  var DEFAULT_TIMELINE_READY_TIMEOUT_MS = 3e4;
1365
+ var MAX_SLEEPS_PER_FRAME_WAIT = 3;
1184
1366
  function asRecord(payload) {
1185
1367
  if (payload === void 0 || payload === null) return {};
1186
1368
  if (typeof payload !== "object" || Array.isArray(payload)) {
@@ -1258,6 +1440,24 @@ function assertEmptyDir(dir) {
1258
1440
  }
1259
1441
  }
1260
1442
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1443
+ async function takeFrameByDeadline(page, deadline, now) {
1444
+ const start = now();
1445
+ const maxAttempts = Math.ceil((deadline - start) / NO_COMPOSITOR_FRAME_RETRY_MS) + 2;
1446
+ let at = start;
1447
+ for (let attempts = 1; ; attempts++) {
1448
+ try {
1449
+ const png = await page.screenshot({ type: "png", scale: "device", fullPage: false });
1450
+ return { png, at, attempts };
1451
+ } catch (err) {
1452
+ const error = err instanceof Error ? err.message : String(err);
1453
+ if (!NO_COMPOSITOR_FRAME.test(error) || attempts >= maxAttempts || now() + NO_COMPOSITOR_FRAME_RETRY_MS >= deadline) {
1454
+ return { error, at, attempts };
1455
+ }
1456
+ }
1457
+ await sleep(NO_COMPOSITOR_FRAME_RETRY_MS);
1458
+ at = now();
1459
+ }
1460
+ }
1261
1461
  async function captureTimeline(page, payload, now = Date.now, execute) {
1262
1462
  const concurrent = payload.during ?? null;
1263
1463
  if (concurrent !== null && !execute) {
@@ -1288,26 +1488,33 @@ async function captureTimeline(page, payload, now = Date.now, execute) {
1288
1488
  })() : null;
1289
1489
  for (let k = 1; k <= payload.frames; k++) {
1290
1490
  const due = t0 + (k - 1) * payload.intervalMs;
1291
- for (let wait = due - now(); wait > 0; wait = due - now()) await sleep(wait);
1292
- const at = now();
1293
- const capturedAt = new Date(at).toISOString();
1294
- try {
1295
- const png = await page.screenshot({ type: "png", scale: "device", fullPage: false });
1296
- const { width, height } = pngDimensions(png);
1297
- const path$1 = path.join(dir, `frame-${k}.png`);
1298
- writePrivateFile(path$1, png);
1299
- frames.push({ index: k, path: path$1, offsetMs: at - t0, capturedAt, width, height });
1300
- } catch (err) {
1301
- frames.push({
1302
- index: k,
1303
- path: null,
1304
- offsetMs: at - t0,
1305
- capturedAt,
1306
- width: null,
1307
- height: null,
1308
- error: err instanceof Error ? err.message : String(err)
1309
- });
1491
+ for (let wait = due - now(), sleeps = 0; wait > 0 && sleeps < MAX_SLEEPS_PER_FRAME_WAIT; wait = due - now(), sleeps++) {
1492
+ await sleep(wait);
1493
+ }
1494
+ const deadline = k === 1 && payload.reload ? t0 + payload.readyTimeoutMs : t0 + k * payload.intervalMs;
1495
+ const shot = await takeFrameByDeadline(page, deadline, now);
1496
+ const frame = {
1497
+ index: k,
1498
+ path: null,
1499
+ offsetMs: shot.at - t0,
1500
+ capturedAt: new Date(shot.at).toISOString(),
1501
+ width: null,
1502
+ height: null,
1503
+ ...shot.attempts > 1 ? { attempts: shot.attempts } : {}
1504
+ };
1505
+ if ("error" in shot) {
1506
+ frame.error = shot.error;
1507
+ } else {
1508
+ try {
1509
+ const { width, height } = pngDimensions(shot.png);
1510
+ const path$1 = path.join(dir, `frame-${k}.png`);
1511
+ writePrivateFile(path$1, shot.png);
1512
+ Object.assign(frame, { path: path$1, width, height });
1513
+ } catch (err) {
1514
+ frame.error = err instanceof Error ? err.message : String(err);
1515
+ }
1310
1516
  }
1517
+ frames.push(frame);
1311
1518
  }
1312
1519
  const during = duringRun ? await duringRun : void 0;
1313
1520
  let runtimeReady = null;
@@ -1478,27 +1685,96 @@ Exec (Variant A \u2014 one-shot; presence of any --exec/--exec-stdin selects thi
1478
1685
  so an N-step run still prints N lines in order. Neither shadows an in-page
1479
1686
  action id \u2014 the injected dispatcher defines neither.
1480
1687
 
1481
- A timed multi-frame capture (CLI-side too):
1688
+ Reading and acting on one element (in-page actions):
1689
+
1690
+ getElement {"id":"<id>"}
1691
+ One element as a snapshot carries it: identity (id, type, tagName,
1692
+ label, role, accessibleName), "state", box ("bbox", "visible") and
1693
+ "actions" \u2014 the same object as the matching getControlSnapshot element,
1694
+ redaction included. {"elementId":"<id>"} is accepted too; given both,
1695
+ they must name the same element. Nothing settles first: run
1696
+ waitForSelector before it for a settled read. Beside the id it
1697
+ tolerates, and ignores, settleTimeout and skipSettle (it does not
1698
+ settle), targetTabId, and the WebSocket protocol's "includeState" (the
1699
+ state is always included); any other key is refused with
1700
+ INVALID_REQUEST. An unknown id, or one whose DOM node is gone, is a
1701
+ RETURNED ELEMENT_NOT_FOUND (an "error" line, exit 1), never a null
1702
+ result.
1703
+
1704
+ getElementState {"id":"<id>"}
1705
+ The state alone (visible, enabled, focused, ariaPressed, value, ...).
1706
+ It reads "id" only, and an unknown id is a THROWN error (HANDLER_ERROR).
1707
+
1708
+ executeElementAction {"id":"<id>","request":{"action":"click"}}
1709
+ Act on one element. "request" holds the verb and the fields it reads
1710
+ ("value", "text", "clear", "params", "fromSnapshotId", ...). Two other
1711
+ spellings are accepted:
1712
+ {"elementId":"<id>","request":{"action":"focus"}} "elementId" for "id"
1713
+ {"id":"<id>","action":"type","text":"hi"} flat: the payload,
1714
+ minus "id"/"elementId", IS the request
1715
+ No key BESIDE a "request" object is silently dropped: a top-level
1716
+ "action" or request field ("value", "text", ...) there must equal the
1717
+ same field inside "request" (an agreeing duplicate is accepted); one
1718
+ that is only at the top level, or at both levels with different
1719
+ values, is refused, and so are an "id" and an "elementId" that name
1720
+ different elements. settleTimeout, skipSettle and targetTabId stay
1721
+ allowed at the top level. The request fields themselves (the keys
1722
+ inside "request", or every key of a flat payload but the id) reach
1723
+ the action as sent, so a misspelt one there ("txt" for "text") is not
1724
+ caught. Every refused shape is a RETURNED INVALID_REQUEST (an "error"
1725
+ line, exit 1; never a thrown TypeError) whose message names the
1726
+ canonical shape
1727
+ {"id":"<elementId>","request":{"action":"<action>", \u2026}}
1728
+ and both accepted spellings, and names keys and the kinds of values,
1729
+ never a value, with one exception: an "id" and an "elementId" that
1730
+ disagree are both named (they are the element ids the caller sent, and
1731
+ naming both is what makes the conflict diagnosable); "error.details"
1732
+ adds "expectedPayload" and "receivedKeys". A well-formed payload with
1733
+ an unknown verb is refused with UNSUPPORTED_ACTION, naming the
1734
+ accepted verbs.
1735
+
1736
+ A timed multi-frame capture (CLI-side, like the waits):
1482
1737
 
1483
1738
  captureTimeline {"dir":"<dir>","frames":8,"intervalMs":250,"reload":false}
1484
1739
  Screenshot the page 'frames' times (1..120), one every 'intervalMs'
1485
1740
  (0..10000), into <dir>/frame-<k>.png \u2014 the loading-to-loaded timeline
1486
1741
  of a slot, NOT a lockstep pair (it records movement on purpose). <dir>
1487
1742
  must be empty or not exist. With "reload":true the clock starts at a
1488
- fresh navigation commit, so frame 1 is the page before it painted; the
1743
+ fresh navigation commit, and frame 1 is the first frame the page
1744
+ produced after that commit. Right after the commit the new document can
1745
+ have no compositor frame yet, and Chromium refuses the screenshot
1746
+ ("Unable to capture screenshot"); frame 1 retries that refusal every
1747
+ 16 ms until 'readyTimeoutMs' after the commit. A frame's "offsetMs" is
1748
+ when the screenshot that produced it was requested, so a frame 1 that
1749
+ had to wait reads the tens of ms its retries took, not 0. Under
1750
+ --throttle that first frame can still be the previous document's held
1751
+ frame; "offsetMs" dates it either way. Every other frame retries the
1752
+ same refusal only while the retry falls due before the next frame's
1753
+ due time ("intervalMs":0 is one attempt), so retries never take a
1754
+ later frame's slot; an attempt still under way when the next frame
1755
+ falls due delays it by what is left of that attempt, as any slow
1756
+ screenshot does. No other error is retried. A frame that took more
1757
+ than one attempt says how many in "attempts". The
1489
1758
  reload drops any media override, and the action waits for the injected
1490
1759
  runtime to settle again ('readyTimeoutMs', default 30000) so the next
1491
1760
  step finds a drivable page. In --capture-matrix a relative <dir> lands
1492
1761
  inside each cell's directory.
1493
1762
  Result: {"success","dir","reloaded","intervalMs","startedAt",
1494
- "frames":[{"index","path","offsetMs","capturedAt","width","height"}],
1763
+ "frames":[{"index","path","offsetMs","capturedAt","width","height",
1764
+ "attempts" (only when > 1)}],
1495
1765
  "devicePixelRatio","cssViewport","colorScheme","runtimeReady","network"}
1496
- A frame that could not be taken carries "error" and fails the step.
1766
+ A frame that could not be taken, or was still refused at its deadline,
1767
+ carries "error" and fails the step.
1497
1768
  "during":{"action":"mediaOverride","payload":{...}} runs that in-page
1498
1769
  action CONCURRENTLY with the frames, so the timeline shows the candidate
1499
1770
  ARRIVING (under --throttle, its slow-network load) while the override
1500
1771
  still confirms decode before it answers; its result rides on the line
1501
1772
  as "during" and a failed action fails the step. Not with "reload".
1773
+ An image URL this document already decoded is NOT observed arriving:
1774
+ Chromium 158 serves it again with no request, even under --no-cache
1775
+ (Chromium 147 refetched it); only a new URL or a reload reaches the
1776
+ network. So give the candidate a URL the document has not decoded,
1777
+ such as a per-candidate query string ("cand.png?2").
1502
1778
 
1503
1779
  Swapping an image in place (dev control, served by the injected runtime):
1504
1780
 
@@ -1509,6 +1785,10 @@ Exec (Variant A \u2014 one-shot; presence of any --exec/--exec-stdin selects thi
1509
1785
  Swap one slot's image, wait for decode() and confirm currentSrc before
1510
1786
  answering (an override that cannot be confirmed is rolled back and
1511
1787
  fails). Inside a <picture> every <source srcset> is replaced too.
1788
+ On Chromium 158 a candidate URL this document already decoded is
1789
+ served with no request, even under --no-cache: only a new URL or a
1790
+ reload reaches the network, so a slow-network candidate needs its own
1791
+ URL (a per-candidate query string).
1512
1792
  mediaOverrideRestore {"overrideId":"mo-\u2026"} (or {} for all)
1513
1793
  Put the originals back and verify each attribute reads back.
1514
1794
  mediaOverrideList {}
@@ -1589,6 +1869,11 @@ Network (every mode; applied to the page once it is ready, before any action):
1589
1869
  captureTimeline {"reload":true} loads throttled.
1590
1870
  --no-cache Disable the HTTP cache too (Network.setCacheDisabled):
1591
1871
  a warm cache would let a "slow" reload paint at once.
1872
+ It does NOT reach the document's in-memory image
1873
+ cache: on Chromium 158 a URL this page already
1874
+ decoded is answered at once, throttle or not -- give
1875
+ a repeated mediaOverride candidate its own URL
1876
+ (e.g. ?2).
1592
1877
  What was applied is stamped as "network" on every
1593
1878
  captureTimeline result, each capture-matrix cell, and
1594
1879
  the relay info line; CDP has no getter, so the stamp
@@ -1802,16 +2087,16 @@ function parseArgs(argv) {
1802
2087
  // String value-flags: guard each consumed value against the flag-shaped
1803
2088
  // swallow (`--url --headed` must error, not capture `--headed` as the url).
1804
2089
  case "--url":
1805
- args.url = (0, cli_args_exports.consumeValue)("--url", argv[++i], mkError) ?? "";
2090
+ args.url = consumeValue("--url", argv[++i], mkError) ?? "";
1806
2091
  break;
1807
2092
  case "--relay":
1808
- args.relay = (0, cli_args_exports.consumeValue)("--relay", argv[++i], mkError);
2093
+ args.relay = consumeValue("--relay", argv[++i], mkError);
1809
2094
  break;
1810
2095
  case "--auth-token":
1811
- args.authToken = (0, cli_args_exports.consumeValue)("--auth-token", argv[++i], mkError);
2096
+ args.authToken = consumeValue("--auth-token", argv[++i], mkError);
1812
2097
  break;
1813
2098
  case "--auth-token-file": {
1814
- const raw = (0, cli_args_exports.consumeValue)("--auth-token-file", argv[++i], mkError);
2099
+ const raw = consumeValue("--auth-token-file", argv[++i], mkError);
1815
2100
  if (raw === null || raw.length === 0) {
1816
2101
  throw new InjectCliArgError(
1817
2102
  `--auth-token-file expects a path to a file holding the bearer token (got <missing>)`
@@ -1821,16 +2106,16 @@ function parseArgs(argv) {
1821
2106
  break;
1822
2107
  }
1823
2108
  case "--app-id":
1824
- args.appId = (0, cli_args_exports.consumeValue)("--app-id", argv[++i], mkError);
2109
+ args.appId = consumeValue("--app-id", argv[++i], mkError);
1825
2110
  break;
1826
2111
  case "--app-name":
1827
- args.appName = (0, cli_args_exports.consumeValue)("--app-name", argv[++i], mkError);
2112
+ args.appName = consumeValue("--app-name", argv[++i], mkError);
1828
2113
  break;
1829
2114
  case "--tab-id":
1830
- args.tabId = (0, cli_args_exports.consumeValue)("--tab-id", argv[++i], mkError);
2115
+ args.tabId = consumeValue("--tab-id", argv[++i], mkError);
1831
2116
  break;
1832
2117
  case "--storage-state": {
1833
- const raw = (0, cli_args_exports.consumeValue)("--storage-state", argv[++i], mkError);
2118
+ const raw = consumeValue("--storage-state", argv[++i], mkError);
1834
2119
  if (raw === null || raw.length === 0) {
1835
2120
  throw new InjectCliArgError(
1836
2121
  `--storage-state expects a path to a storageState JSON file (got <missing>)`
@@ -1848,7 +2133,7 @@ function parseArgs(argv) {
1848
2133
  break;
1849
2134
  }
1850
2135
  case "--exec": {
1851
- const raw = (0, cli_args_exports.consumeValue)("--exec", argv[++i], mkError);
2136
+ const raw = consumeValue("--exec", argv[++i], mkError);
1852
2137
  if (raw === null) {
1853
2138
  throw new InjectCliArgError(`--exec expects '<action> <json-payload>' (got <missing>)`);
1854
2139
  }
@@ -1856,7 +2141,7 @@ function parseArgs(argv) {
1856
2141
  break;
1857
2142
  }
1858
2143
  case "--registration-metadata": {
1859
- const raw = (0, cli_args_exports.consumeValue)("--registration-metadata", argv[++i], mkError);
2144
+ const raw = consumeValue("--registration-metadata", argv[++i], mkError);
1860
2145
  if (raw === null) {
1861
2146
  throw new InjectCliArgError(
1862
2147
  `--registration-metadata expects JSON {"userId","sessionId"} (got <missing>)`
@@ -1878,44 +2163,32 @@ function parseArgs(argv) {
1878
2163
  args.registrationMetadata = { userId: m.userId, sessionId: m.sessionId };
1879
2164
  break;
1880
2165
  }
1881
- case "--ready-timeout": {
1882
- const raw = (0, cli_args_exports.consumeValue)("--ready-timeout", argv[++i], mkError);
1883
- const n = raw === null ? NaN : Number.parseInt(raw, 10);
1884
- if (!Number.isFinite(n) || n <= 0) {
1885
- throw new InjectCliArgError(
1886
- `--ready-timeout expects a positive integer (got ${raw ?? "<missing>"})`
1887
- );
1888
- }
1889
- args.readyTimeoutMs = n;
2166
+ case "--ready-timeout":
2167
+ args.readyTimeoutMs = parsePositiveInt(
2168
+ "--ready-timeout",
2169
+ consumeValue("--ready-timeout", argv[++i], mkError),
2170
+ mkError
2171
+ );
1890
2172
  break;
1891
- }
1892
2173
  case "--no-settle":
1893
2174
  args.waitForSettle = false;
1894
2175
  break;
1895
- case "--settle-quiet": {
1896
- const raw = (0, cli_args_exports.consumeValue)("--settle-quiet", argv[++i], mkError);
1897
- const n = raw === null ? NaN : Number.parseInt(raw, 10);
1898
- if (!Number.isFinite(n) || n < 0) {
1899
- throw new InjectCliArgError(
1900
- `--settle-quiet expects a non-negative integer (got ${raw ?? "<missing>"})`
1901
- );
1902
- }
1903
- args.settleQuietMs = n;
2176
+ case "--settle-quiet":
2177
+ args.settleQuietMs = parseNonNegativeInt(
2178
+ "--settle-quiet",
2179
+ consumeValue("--settle-quiet", argv[++i], mkError),
2180
+ mkError
2181
+ );
1904
2182
  break;
1905
- }
1906
- case "--settle-timeout": {
1907
- const raw = (0, cli_args_exports.consumeValue)("--settle-timeout", argv[++i], mkError);
1908
- const n = raw === null ? NaN : Number.parseInt(raw, 10);
1909
- if (!Number.isFinite(n) || n <= 0) {
1910
- throw new InjectCliArgError(
1911
- `--settle-timeout expects a positive integer (got ${raw ?? "<missing>"})`
1912
- );
1913
- }
1914
- args.settleTimeoutMs = n;
2183
+ case "--settle-timeout":
2184
+ args.settleTimeoutMs = parsePositiveInt(
2185
+ "--settle-timeout",
2186
+ consumeValue("--settle-timeout", argv[++i], mkError),
2187
+ mkError
2188
+ );
1915
2189
  break;
1916
- }
1917
2190
  case "--expect-selector": {
1918
- const raw = (0, cli_args_exports.consumeValue)("--expect-selector", argv[++i], mkError);
2191
+ const raw = consumeValue("--expect-selector", argv[++i], mkError);
1919
2192
  if (raw === null || raw.length === 0) {
1920
2193
  throw new InjectCliArgError(`--expect-selector expects a CSS selector (got <missing>)`);
1921
2194
  }
@@ -1926,19 +2199,19 @@ function parseArgs(argv) {
1926
2199
  // list and every occurrence appends; `validateArgs` then allows more than
1927
2200
  // one value only under --capture-matrix, where they are an axis.
1928
2201
  case "--viewport": {
1929
- const raw = (0, cli_args_exports.consumeValue)("--viewport", argv[++i], mkError);
2202
+ const raw = consumeValue("--viewport", argv[++i], mkError);
1930
2203
  if (raw === null) throw new InjectCliArgError(`--viewport expects WxH (got <missing>)`);
1931
2204
  for (const item of splitList("--viewport", raw)) args.viewports.push(parseViewport(item));
1932
2205
  break;
1933
2206
  }
1934
2207
  case "--dpr": {
1935
- const raw = (0, cli_args_exports.consumeValue)("--dpr", argv[++i], mkError);
2208
+ const raw = consumeValue("--dpr", argv[++i], mkError);
1936
2209
  if (raw === null) throw new InjectCliArgError(`--dpr expects a number (got <missing>)`);
1937
2210
  for (const item of splitList("--dpr", raw)) args.dprs.push(parseDpr(item));
1938
2211
  break;
1939
2212
  }
1940
2213
  case "--color-scheme": {
1941
- const raw = (0, cli_args_exports.consumeValue)("--color-scheme", argv[++i], mkError);
2214
+ const raw = consumeValue("--color-scheme", argv[++i], mkError);
1942
2215
  if (raw === null) {
1943
2216
  throw new InjectCliArgError(`--color-scheme expects dark or light (got <missing>)`);
1944
2217
  }
@@ -1948,7 +2221,7 @@ function parseArgs(argv) {
1948
2221
  break;
1949
2222
  }
1950
2223
  case "--screenshot": {
1951
- const raw = (0, cli_args_exports.consumeValue)("--screenshot", argv[++i], mkError);
2224
+ const raw = consumeValue("--screenshot", argv[++i], mkError);
1952
2225
  if (raw === null || raw.length === 0) {
1953
2226
  throw new InjectCliArgError(`--screenshot expects a PNG path (got <missing>)`);
1954
2227
  }
@@ -1956,7 +2229,7 @@ function parseArgs(argv) {
1956
2229
  break;
1957
2230
  }
1958
2231
  case "--throttle": {
1959
- const raw = (0, cli_args_exports.consumeValue)("--throttle", argv[++i], mkError);
2232
+ const raw = consumeValue("--throttle", argv[++i], mkError);
1960
2233
  if (raw === null)
1961
2234
  throw new InjectCliArgError("--throttle expects a profile (got <missing>)");
1962
2235
  if (args.throttle !== null) throw new InjectCliArgError("--throttle given twice");
@@ -1967,7 +2240,7 @@ function parseArgs(argv) {
1967
2240
  args.noCache = true;
1968
2241
  break;
1969
2242
  case "--capture-matrix": {
1970
- const raw = (0, cli_args_exports.consumeValue)("--capture-matrix", argv[++i], mkError);
2243
+ const raw = consumeValue("--capture-matrix", argv[++i], mkError);
1971
2244
  if (raw === null || raw.length === 0) {
1972
2245
  throw new InjectCliArgError(
1973
2246
  `--capture-matrix expects an output directory (got <missing>)`