@qontinui/ui-bridge-wrapper 0.7.2 → 0.9.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.
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- var module$1 = require('module');
5
4
  var fs = require('fs');
5
+ var path = require('path');
6
+ var module$1 = require('module');
7
+ var crypto = require('crypto');
6
8
  var ui_bridge_cli_args_star = require('@qontinui/ui-bridge-cli-args');
7
9
 
8
10
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -271,6 +273,8 @@ var HeadlessTransport = class extends BaseTransport {
271
273
  targetUrl,
272
274
  viewportWidth: typeof raw["viewportWidth"] === "number" ? raw["viewportWidth"] : void 0,
273
275
  viewportHeight: typeof raw["viewportHeight"] === "number" ? raw["viewportHeight"] : void 0,
276
+ deviceScaleFactor: typeof raw["deviceScaleFactor"] === "number" ? raw["deviceScaleFactor"] : void 0,
277
+ colorScheme: raw["colorScheme"] === "light" || raw["colorScheme"] === "dark" ? raw["colorScheme"] : void 0,
274
278
  uiBridgeBase: typeof raw["uiBridgeBase"] === "string" ? raw["uiBridgeBase"] : void 0,
275
279
  waitForUiBridgeMs: typeof raw["waitForUiBridgeMs"] === "number" ? raw["waitForUiBridgeMs"] : void 0,
276
280
  userAgent: typeof raw["userAgent"] === "string" ? raw["userAgent"] : void 0,
@@ -305,6 +309,7 @@ Underlying import error: ${cause}`
305
309
  }
306
310
  const initScripts = await this.buildInitScripts();
307
311
  const relayAuth = this.relayAuth();
312
+ const pinnedTabId = this.pinnedTabId();
308
313
  let tab;
309
314
  try {
310
315
  tab = await launchHeadlessTab({
@@ -314,13 +319,16 @@ Underlying import error: ${cause}`
314
319
  waitForUiBridgeMs: this.options.waitForUiBridgeMs,
315
320
  viewportWidth: this.options.viewportWidth,
316
321
  viewportHeight: this.options.viewportHeight,
322
+ ...this.options.deviceScaleFactor !== void 0 ? { deviceScaleFactor: this.options.deviceScaleFactor } : {},
323
+ ...this.options.colorScheme !== void 0 ? { colorScheme: this.options.colorScheme } : {},
317
324
  userAgent: this.options.userAgent,
318
325
  forwardConsole: this.options.forwardConsole,
319
326
  initScripts: initScripts.length > 0 ? initScripts : void 0,
320
327
  launchArgs: this.options.launchArgs && this.options.launchArgs.length > 0 ? this.options.launchArgs : void 0,
321
328
  storageStatePath: this.options.storageStatePath,
322
329
  ...relayAuth.authToken ? { authToken: relayAuth.authToken } : {},
323
- ...relayAuth.callerUserId ? { callerUserId: relayAuth.callerUserId } : {}
330
+ ...relayAuth.callerUserId ? { callerUserId: relayAuth.callerUserId } : {},
331
+ ...pinnedTabId ? { pinnedTabId } : {}
324
332
  });
325
333
  } catch (err) {
326
334
  const cause = err instanceof Error ? err.message : String(err);
@@ -342,8 +350,39 @@ Underlying launch error: ${cause}`
342
350
  tabId: tab.tabId,
343
351
  close: tab.close
344
352
  };
353
+ await this.verifyEmulation(tab.page);
345
354
  await this.afterLaunch(tab.page);
346
355
  }
356
+ /**
357
+ * Read back the requested device scale factor and colour scheme from the
358
+ * page itself, and refuse a launch whose page reports anything else.
359
+ */
360
+ async verifyEmulation(page) {
361
+ const wantDpr = this.options.deviceScaleFactor;
362
+ const wantScheme = this.options.colorScheme;
363
+ if (wantDpr === void 0 && wantScheme === void 0) return;
364
+ const seen = await page.evaluate(() => ({
365
+ dpr: window.devicePixelRatio,
366
+ dark: window.matchMedia("(prefers-color-scheme: dark)").matches
367
+ }));
368
+ const problems = [];
369
+ if (wantDpr !== void 0 && Math.abs(seen.dpr - wantDpr) > 1e-9) {
370
+ problems.push(`devicePixelRatio ${seen.dpr} (requested ${wantDpr})`);
371
+ }
372
+ if (wantScheme !== void 0 && seen.dark !== (wantScheme === "dark")) {
373
+ problems.push(
374
+ `prefers-color-scheme ${seen.dark ? "dark" : "light"} (requested ${wantScheme})`
375
+ );
376
+ }
377
+ if (problems.length === 0) return;
378
+ await this.onClose().catch(() => {
379
+ });
380
+ throw new WrapperTransportError(
381
+ "EMULATION_NOT_APPLIED",
382
+ `The launched page reports ${problems.join(" and ")}. The installed '@qontinui/ui-bridge-headless' peer most likely predates deviceScaleFactor/colorScheme support (added after 0.5.0) and ignored them; upgrade it. A page measured at an emulation it is not actually rendering at would be stamped with the wrong values.`,
383
+ { details: { requested: { deviceScaleFactor: wantDpr, colorScheme: wantScheme }, seen } }
384
+ );
385
+ }
347
386
  /**
348
387
  * Subclass hook: init-scripts to register on the browser context before the
349
388
  * first navigation (via `context.addInitScript`). Default: none. Injected
@@ -361,6 +400,13 @@ Underlying launch error: ${cause}`
361
400
  relayAuth() {
362
401
  return {};
363
402
  }
403
+ /**
404
+ * Subclass hook: the tab id this launch pinned, so the registration poll
405
+ * returns that tab only. Default: none. Injected mode returns `--tab-id`.
406
+ */
407
+ pinnedTabId() {
408
+ return void 0;
409
+ }
364
410
  /**
365
411
  * Subclass hook: run after launch + navigation, before `ready()` resolves.
366
412
  * Default: no-op. Injected mode overrides it to await the in-page runtime.
@@ -423,6 +469,14 @@ function loadInjectedBundle() {
423
469
  }
424
470
  var InjectedTransport = class extends HeadlessTransport {
425
471
  injected;
472
+ /**
473
+ * The pinned tab's key: 32 random bytes, base64url, generated once per
474
+ * transport (one launch) and kept in this process. The runner binds a tab
475
+ * that presents it to the key's digest, so the pin survives an origin hop
476
+ * while a page that merely learns the pinned id cannot attach as the tab.
477
+ * Lives only in the injected global — never in a storage artifact.
478
+ */
479
+ tabKey = crypto.randomBytes(32).toString("base64url");
426
480
  constructor(config, registry) {
427
481
  const raw = config.options ?? {};
428
482
  const headed = raw["headed"] === true;
@@ -457,9 +511,11 @@ var InjectedTransport = class extends HeadlessTransport {
457
511
  if (this.injected.appId) cfg.appId = this.injected.appId;
458
512
  if (this.injected.appName) cfg.appName = this.injected.appName;
459
513
  }
460
- if (this.injected.tabId) cfg.tabId = this.injected.tabId;
461
- if (this.injected.settleQuietMs !== void 0)
462
- cfg.settleQuietMs = this.injected.settleQuietMs;
514
+ if (this.injected.tabId) {
515
+ cfg.tabId = this.injected.tabId;
516
+ cfg.tabKey = this.tabKey;
517
+ }
518
+ if (this.injected.settleQuietMs !== void 0) cfg.settleQuietMs = this.injected.settleQuietMs;
463
519
  if (this.injected.settleTimeoutMs !== void 0)
464
520
  cfg.settleTimeoutMs = this.injected.settleTimeoutMs;
465
521
  if (this.injected.expectSelector !== void 0)
@@ -478,6 +534,9 @@ var InjectedTransport = class extends HeadlessTransport {
478
534
  ...this.injected.registrationMetadata?.userId ? { callerUserId: this.injected.registrationMetadata.userId } : {}
479
535
  };
480
536
  }
537
+ pinnedTabId() {
538
+ return this.injected.tabId;
539
+ }
481
540
  async buildInitScripts() {
482
541
  const scripts = [];
483
542
  const cfg = this.injectedConfig();
@@ -681,7 +740,7 @@ var LiveSessionTransport = class extends BaseTransport {
681
740
  ws.addEventListener("message", (ev) => this.handleMessage(ev.data));
682
741
  ws.addEventListener("close", () => this.handleClose());
683
742
  ws.addEventListener("error", (ev) => this.handleError(ev));
684
- await new Promise((resolve, reject) => {
743
+ await new Promise((resolve3, reject) => {
685
744
  const onOpen = () => {
686
745
  try {
687
746
  const frame = {
@@ -711,7 +770,7 @@ var LiveSessionTransport = class extends BaseTransport {
711
770
  )
712
771
  );
713
772
  }, timeoutMs);
714
- this.ackResolvers = { resolve, reject, timer };
773
+ this.ackResolvers = { resolve: resolve3, reject, timer };
715
774
  };
716
775
  ws.addEventListener("open", onOpen);
717
776
  });
@@ -893,6 +952,204 @@ function thrownError(err) {
893
952
  source: "thrown"
894
953
  };
895
954
  }
955
+ var DEFAULT_LOCKSTEP_ATTEMPTS = 3;
956
+ var FRAME_SCALE_TOLERANCE_PX = 2;
957
+ var FRAME_INDEX_TOKEN = "{n}";
958
+ var PRIVATE_DIR_MODE = 448;
959
+ var PRIVATE_FILE_MODE = 384;
960
+ function ensurePrivateDir(dir) {
961
+ fs.mkdirSync(dir, { recursive: true, mode: PRIVATE_DIR_MODE });
962
+ }
963
+ function writePrivateFile(path$1, data) {
964
+ const tmp = path.join(
965
+ path.dirname(path$1),
966
+ `.${path.basename(path$1)}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`
967
+ );
968
+ try {
969
+ fs.writeFileSync(tmp, data, { mode: PRIVATE_FILE_MODE, flag: "wx" });
970
+ fs.renameSync(tmp, path$1);
971
+ } catch (err) {
972
+ fs.rmSync(tmp, { force: true });
973
+ throw err;
974
+ }
975
+ }
976
+ var PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
977
+ function pngDimensions(buf) {
978
+ if (buf.length < 24 || PNG_SIGNATURE.some((b, i) => buf[i] !== b)) {
979
+ throw new Error("not a PNG (signature mismatch or truncated header)");
980
+ }
981
+ const chunkType = String.fromCharCode(buf[12], buf[13], buf[14], buf[15]);
982
+ if (chunkType !== "IHDR") {
983
+ throw new Error(`PNG does not start with an IHDR chunk (found ${JSON.stringify(chunkType)})`);
984
+ }
985
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
986
+ return { width: view.getUint32(16), height: view.getUint32(20) };
987
+ }
988
+ function fileNameStart(path) {
989
+ return Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1;
990
+ }
991
+ function expandFramePath(template, position) {
992
+ const at = fileNameStart(template);
993
+ return template.slice(0, at) + template.slice(at).split(FRAME_INDEX_TOKEN).join(String(position));
994
+ }
995
+ function frameTokenInDirectory(template) {
996
+ return template.slice(0, fileNameStart(template)).includes(FRAME_INDEX_TOKEN);
997
+ }
998
+ function frameTokenInFileName(template) {
999
+ return template.slice(fileNameStart(template)).includes(FRAME_INDEX_TOKEN);
1000
+ }
1001
+ async function readPageMetrics(page) {
1002
+ return page.evaluate(() => ({
1003
+ devicePixelRatio: window.devicePixelRatio,
1004
+ innerWidth: window.innerWidth,
1005
+ innerHeight: window.innerHeight,
1006
+ colorScheme: window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
1007
+ }));
1008
+ }
1009
+ function isRecord2(v) {
1010
+ return typeof v === "object" && v !== null && !Array.isArray(v);
1011
+ }
1012
+ function snapshotGeometry(snapshot) {
1013
+ if (!isRecord2(snapshot)) return null;
1014
+ const data = snapshot["data"];
1015
+ const elements = Array.isArray(snapshot["elements"]) ? snapshot["elements"] : isRecord2(data) && Array.isArray(data["elements"]) ? data["elements"] : null;
1016
+ if (elements === null) return null;
1017
+ const out = /* @__PURE__ */ new Map();
1018
+ elements.forEach((el, i) => {
1019
+ if (!isRecord2(el)) return;
1020
+ const id = typeof el["id"] === "string" ? el["id"] : `#${i}`;
1021
+ const b = isRecord2(el["bbox"]) ? el["bbox"] : null;
1022
+ const box = b ? [b["x"], b["y"], b["width"], b["height"]].map((v) => String(v)).join(",") : "-";
1023
+ out.set(id, `${box}|${String(el["visible"])}`);
1024
+ });
1025
+ return out;
1026
+ }
1027
+ function geometryDelta(before, after) {
1028
+ if (before === null || after === null) return null;
1029
+ let changed = 0;
1030
+ for (const [id, key] of before) {
1031
+ if (after.get(id) !== key) changed += 1;
1032
+ }
1033
+ for (const id of after.keys()) {
1034
+ if (!before.has(id)) changed += 1;
1035
+ }
1036
+ return changed;
1037
+ }
1038
+ async function captureFrameInLockstep(opts) {
1039
+ const maxAttempts = Math.max(1, opts.maxAttempts ?? DEFAULT_LOCKSTEP_ATTEMPTS);
1040
+ const now = opts.now ?? (() => /* @__PURE__ */ new Date());
1041
+ const path$1 = path.resolve(opts.path);
1042
+ let snapshot;
1043
+ let png = null;
1044
+ let metrics = null;
1045
+ let capturedAt = "";
1046
+ let changed = null;
1047
+ let attempts = 1;
1048
+ for (; attempts <= maxAttempts; attempts++) {
1049
+ snapshot = await opts.takeSnapshot();
1050
+ try {
1051
+ metrics = await readPageMetrics(opts.page);
1052
+ capturedAt = now().toISOString();
1053
+ png = await opts.page.screenshot({ type: "png", scale: "device", fullPage: false });
1054
+ } catch (err) {
1055
+ return {
1056
+ snapshot,
1057
+ frame: null,
1058
+ frameError: {
1059
+ code: "FRAME_CAPTURE_FAILED",
1060
+ message: `screenshot failed: ${err instanceof Error ? err.message : String(err)}`
1061
+ }
1062
+ };
1063
+ }
1064
+ const after = await opts.takeSnapshot();
1065
+ changed = geometryDelta(snapshotGeometry(snapshot), snapshotGeometry(after));
1066
+ if (changed === 0) break;
1067
+ if (changed === null) break;
1068
+ }
1069
+ attempts = Math.min(attempts, maxAttempts);
1070
+ if (png === null || metrics === null) {
1071
+ return {
1072
+ snapshot,
1073
+ frame: null,
1074
+ frameError: { code: "FRAME_CAPTURE_FAILED", message: "no frame was taken" }
1075
+ };
1076
+ }
1077
+ let size;
1078
+ try {
1079
+ size = pngDimensions(png);
1080
+ } catch (err) {
1081
+ return {
1082
+ snapshot,
1083
+ frame: null,
1084
+ frameError: {
1085
+ code: "FRAME_CAPTURE_FAILED",
1086
+ message: `the screenshot is unreadable: ${err instanceof Error ? err.message : String(err)}`
1087
+ }
1088
+ };
1089
+ }
1090
+ const expectedW = metrics.innerWidth * metrics.devicePixelRatio;
1091
+ const expectedH = metrics.innerHeight * metrics.devicePixelRatio;
1092
+ if (Math.abs(size.width - expectedW) > FRAME_SCALE_TOLERANCE_PX || Math.abs(size.height - expectedH) > FRAME_SCALE_TOLERANCE_PX) {
1093
+ return {
1094
+ snapshot,
1095
+ frame: null,
1096
+ frameError: {
1097
+ code: "FRAME_SCALE_MISMATCH",
1098
+ message: `the screenshot is ${size.width}x${size.height} px, but the page reports a ${metrics.innerWidth}x${metrics.innerHeight} CSS viewport at devicePixelRatio ${metrics.devicePixelRatio} (expected about ${expectedW}x${expectedH}); a CSS box mapped through that ratio would land on the wrong pixels, so no frame is reported`
1099
+ }
1100
+ };
1101
+ }
1102
+ try {
1103
+ ensurePrivateDir(path.dirname(path$1));
1104
+ writePrivateFile(path$1, png);
1105
+ } catch (err) {
1106
+ return {
1107
+ snapshot,
1108
+ frame: null,
1109
+ frameError: {
1110
+ code: "FRAME_CAPTURE_FAILED",
1111
+ message: `could not write ${path$1}: ${err instanceof Error ? err.message : String(err)}`
1112
+ }
1113
+ };
1114
+ }
1115
+ return {
1116
+ snapshot,
1117
+ frame: {
1118
+ path: path$1,
1119
+ format: "png",
1120
+ width: size.width,
1121
+ height: size.height,
1122
+ devicePixelRatio: metrics.devicePixelRatio,
1123
+ cssViewport: { width: metrics.innerWidth, height: metrics.innerHeight },
1124
+ colorScheme: metrics.colorScheme,
1125
+ capturedAt,
1126
+ lockstep: { verified: changed === 0, attempts, changedElements: changed }
1127
+ }
1128
+ };
1129
+ }
1130
+ function expandMatrix(axes) {
1131
+ const viewports = axes.viewports.length > 0 ? axes.viewports : [null];
1132
+ const dprs = axes.dprs.length > 0 ? axes.dprs : [null];
1133
+ const schemes = axes.colorSchemes.length > 0 ? axes.colorSchemes : [null];
1134
+ const cells = [];
1135
+ for (const viewport of viewports) {
1136
+ for (const dpr of dprs) {
1137
+ for (const colorScheme of schemes) {
1138
+ cells.push({ viewport, dpr, colorScheme });
1139
+ }
1140
+ }
1141
+ }
1142
+ return cells;
1143
+ }
1144
+ function cellId(cell) {
1145
+ const vp = cell.viewport ? `${cell.viewport.width}x${cell.viewport.height}` : "viewport-default";
1146
+ const dpr = cell.dpr !== null ? `dpr${cell.dpr}` : "dpr-default";
1147
+ const scheme = cell.colorScheme ?? "scheme-default";
1148
+ return `${vp}_${dpr}_${scheme}`;
1149
+ }
1150
+ function manifestPath(manifestDir, absPath) {
1151
+ return path.relative(manifestDir, absPath).split("\\").join("/");
1152
+ }
896
1153
 
897
1154
  // src/inject-cli.ts
898
1155
  var USAGE = `ui-bridge-inject \u2014 drive UI Bridge's injected transport against a UI-Bridge-free page
@@ -904,7 +1161,12 @@ Required:
904
1161
  Relay (Variant B \u2014 the default mode; --relay is REQUIRED in this mode):
905
1162
  --relay <uiBridgeBase> UI Bridge relay base; the injected runtime registers
906
1163
  as a relay tab. Example: http://localhost:3001/api/ui-bridge
907
- --auth-token <T> Bearer token for an auth-gated relay
1164
+ --auth-token <T> Bearer token for an auth-gated relay. Puts the token on THIS
1165
+ process's command line, which any local process/user can read
1166
+ (Task Manager, /proc, WMI) for the process's whole lifetime \u2014
1167
+ prefer --auth-token-file or $UI_BRIDGE_AUTH_TOKEN instead.
1168
+ --auth-token-file <path> Read the bearer token from a file (trimmed) instead of argv.
1169
+ Takes priority over $UI_BRIDGE_AUTH_TOKEN, loses to --auth-token.
908
1170
  --registration-metadata <json>
909
1171
  JSON {"userId":"...","sessionId":"..."} for per-user
910
1172
  tab-scoping on relay heartbeats
@@ -919,6 +1181,29 @@ Exec (Variant A \u2014 one-shot; presence of any --exec/--exec-stdin selects thi
919
1181
  --exec-stdin Read NDJSON lines from stdin; each line is
920
1182
  {"action":"...","payload":{...}}
921
1183
 
1184
+ Waiting BETWEEN exec steps (CLI-side actions, not in-page ones):
1185
+ Exec steps run back to back with nothing between them, so state that
1186
+ arrives AFTER ready()/settle \u2014 a row fetched by a request the previous
1187
+ step kicked off, a panel that mounts a tick later \u2014 cannot be awaited.
1188
+ Two action ids are handled by the CLI itself for exactly that:
1189
+
1190
+ waitForSelector {"selector":"<css>","timeoutMs":10000,"state":"attached"}
1191
+ Wait until the selector reaches 'state' in the page. 'state' is one of
1192
+ attached (DEFAULT \u2014 the same "exists in the DOM" test --expect-selector
1193
+ applies) | visible | hidden | detached. 'timeoutMs' defaults to 10000.
1194
+ On timeout the step FAILS like any other: an "error" line on stdout and
1195
+ exit 1 at the end.
1196
+ Result: {"waited":true,"selector":..,"state":..,"elapsedMs":..}
1197
+
1198
+ sleep {"ms":250}
1199
+ Unconditional pause. 'ms' is required, 0..600000. Prefer
1200
+ waitForSelector \u2014 a sleep encodes a guess, not a condition.
1201
+ Result: {"slept":250}
1202
+
1203
+ Both go through the same one-line-per-action channel as an in-page action,
1204
+ so an N-step run still prints N lines in order. Neither shadows an in-page
1205
+ action id \u2014 the injected dispatcher defines neither.
1206
+
922
1207
  Exec output & exit code:
923
1208
  One JSON line per action, in order, on stdout \u2014 ALWAYS one line per action,
924
1209
  including failures. An action that succeeded prints {"action":..,"result":..}.
@@ -941,6 +1226,58 @@ Exec (Variant A \u2014 one-shot; presence of any --exec/--exec-stdin selects thi
941
1226
  N actions with N lines. A caller that wants stop-on-first-failure gets it by
942
1227
  running one action per invocation and checking the exit code.
943
1228
 
1229
+ Frames (Variant A):
1230
+ --screenshot <path> Capture a PNG frame IN LOCKSTEP with every
1231
+ getControlSnapshot action: snapshot, frame, snapshot
1232
+ again, retried until both snapshots agree on every
1233
+ element's box. That action's line gains a "frame":
1234
+ {"path","format":"png","width","height",
1235
+ "devicePixelRatio","cssViewport":{"width","height"},
1236
+ "colorScheme","capturedAt",
1237
+ "lockstep":{"verified","attempts","changedElements"}}
1238
+ every field read off the page or the PNG at capture
1239
+ time, never copied from the flags. ${FRAME_INDEX_TOKEN} in the FILE
1240
+ NAME of <path> is replaced by the action's 1-based
1241
+ position (= its output line) and is REQUIRED when the
1242
+ run takes more than one snapshot; ${FRAME_INDEX_TOKEN} in a directory
1243
+ name is refused. A frame that cannot be produced leaves
1244
+ "frame":null plus "frameError":{"code","message"} on the
1245
+ line \u2014 the snapshot still stands \u2014 and exit 1.
1246
+ A frame is RAW PIXELS of the page: data-bridge-redact
1247
+ masks elements in snapshots and over the relay, never
1248
+ in a screenshot, so a frame shows whatever the page
1249
+ showed. Directories created for frames are 0700 and
1250
+ the files 0600.
1251
+ --dpr <n> Device pixel ratio of the browser context, e.g. 2 or
1252
+ 2.625 (Chromium's --force-device-scale-factor does NOT
1253
+ reach the page; this does). Default 1.
1254
+ --color-scheme <dark|light> prefers-color-scheme of the browser context.
1255
+ Default: no override (light).
1256
+ Both are read back from the page after launch; a page
1257
+ that reports anything else fails the run
1258
+ (EMULATION_NOT_APPLIED) instead of being measured as if.
1259
+
1260
+ Capture matrix (its own mode):
1261
+ --capture-matrix <dir> Run the plan once per --viewport \xD7 --dpr \xD7 --color-scheme
1262
+ combination, each a fresh browser context, and store
1263
+ every frame-and-snapshot pair with its provenance:
1264
+ <dir>/<cell>/frame-<n>.png, snapshot-<n>.json,
1265
+ results.ndjson, and <dir>/matrix.json for all cells.
1266
+ In this mode those three flags take comma-separated
1267
+ lists (or repeat): --viewport 390x844,1280x720
1268
+ --dpr 1,2 --color-scheme light,dark. An axis left out
1269
+ stays at the browser default and is named so in the
1270
+ cell id (e.g. 390x844_dpr-default_dark). --exec /
1271
+ --exec-stdin give the per-cell plan (default: one
1272
+ 'getControlSnapshot {}'); a frame is captured beside
1273
+ every getControlSnapshot in it. Prints one JSON line
1274
+ per cell; exits 1 if any cell is not "captured".
1275
+ Takes no --relay and no --screenshot. <dir> must be
1276
+ empty or not exist yet: a non-empty one is refused,
1277
+ never cleared. Directories it creates are 0700 and
1278
+ every frame, snapshot and manifest 0600 \u2014 frames are
1279
+ raw pixels that data-bridge-redact does not scrub.
1280
+
944
1281
  Optional:
945
1282
  --storage-state <path> Seed the browser context from a Playwright storageState
946
1283
  JSON file (cookies + localStorage) produced by
@@ -961,7 +1298,8 @@ Optional:
961
1298
  mounts lazily after unrelated chrome. If it never appears
962
1299
  before --settle-timeout, ready() fails with a BLOCKED error
963
1300
  instead of returning a control-less page.
964
- --viewport <WxH> Viewport size, e.g. 1280x720
1301
+ --viewport <WxH> Viewport size in CSS pixels, e.g. 1280x720 (default 1280x720).
1302
+ Each side 1..8192 CSS pixels.
965
1303
  --launch-arg <arg> Extra Chromium command-line argument (repeatable),
966
1304
  passed through to chromium.launch({ args }).
967
1305
  NOTE: when --url is https and --relay resolves to a
@@ -977,6 +1315,10 @@ Examples:
977
1315
  ui-bridge-inject --url https://example.com/login \\
978
1316
  --relay http://localhost:3001/api/ui-bridge --app-name "example login"
979
1317
 
1318
+ # Variant B against an auth-gated relay, without putting the token on argv
1319
+ ui-bridge-inject --url https://qontinui.io/admin/coord/fleet \\
1320
+ --relay https://qontinui.io/api/ui-bridge --auth-token-file "$HOME/.idtok"
1321
+
980
1322
  # Variant A: snapshot the controls on a page, then exit
981
1323
  ui-bridge-inject --url https://example.com/login \\
982
1324
  --exec 'getControlSnapshot {}'
@@ -985,6 +1327,23 @@ Examples:
985
1327
  ui-bridge-inject --url https://example.com/login \\
986
1328
  --exec 'find {"text":"Sign in"}'
987
1329
 
1330
+ # Variant A: wait for a late-arriving row, THEN read it (no --expect-selector)
1331
+ ui-bridge-inject --url https://example.com/account --exec 'waitForSelector {"selector":"[data-row=account]","timeoutMs":15000}' --exec 'discover {}'
1332
+
1333
+ # A frame in lockstep with the snapshot, at a Retina DPR in dark mode
1334
+ ui-bridge-inject --url http://127.0.0.1:3000/ --viewport 1280x720 --dpr 2 \\
1335
+ --color-scheme dark --screenshot ./frame.png --exec 'getControlSnapshot {}'
1336
+
1337
+ # Before/after a click: {n} names each frame by its action's position
1338
+ ui-bridge-inject --url http://127.0.0.1:3000/ --screenshot './frame-{n}.png' \\
1339
+ --exec 'getControlSnapshot {}' \\
1340
+ --exec 'executeElementAction {"id":"open","request":{"action":"click"}}' \\
1341
+ --exec 'getControlSnapshot {}'
1342
+
1343
+ # Capture matrix: 2 breakpoints x 2 schemes x 2 DPRs = 8 frame-and-snapshot pairs
1344
+ ui-bridge-inject --url http://127.0.0.1:3000/ --capture-matrix ./matrix \\
1345
+ --viewport 390x844,1280x720 --color-scheme light,dark --dpr 1,2
1346
+
988
1347
  # Reuse a saved login: drive a login-walled page with a captured auth artifact
989
1348
  ui-bridge-login-web --url "https://qontinui.io/login?next=%2Fadmin" \\
990
1349
  --success /admin --storage-state-out auth.json
@@ -1020,11 +1379,50 @@ function parseExecValue(raw) {
1020
1379
  }
1021
1380
  return { action, payload };
1022
1381
  }
1382
+ var MAX_DPR = 8;
1383
+ function splitList(flag, raw) {
1384
+ const items = raw.split(",").map((s) => s.trim());
1385
+ if (items.some((s) => s.length === 0)) {
1386
+ throw new InjectCliArgError(
1387
+ `${flag} has an empty item in its list (got ${JSON.stringify(raw)})`
1388
+ );
1389
+ }
1390
+ return items;
1391
+ }
1392
+ var MAX_VIEWPORT_SIDE = 8192;
1393
+ function parseViewport(raw) {
1394
+ const match = raw.match(/^([1-9]\d*)x([1-9]\d*)$/);
1395
+ if (!match) {
1396
+ throw new InjectCliArgError(`--viewport expects WxH in CSS pixels, e.g. 1280x720 (got ${raw})`);
1397
+ }
1398
+ const width = Number.parseInt(match[1], 10);
1399
+ const height = Number.parseInt(match[2], 10);
1400
+ if (width > MAX_VIEWPORT_SIDE || height > MAX_VIEWPORT_SIDE) {
1401
+ throw new InjectCliArgError(
1402
+ `--viewport sides are at most ${MAX_VIEWPORT_SIDE} CSS pixels (got ${raw})`
1403
+ );
1404
+ }
1405
+ return { width, height };
1406
+ }
1407
+ function parseDpr(raw) {
1408
+ const n = /^\d+(\.\d+)?$/.test(raw) ? Number(raw) : Number.NaN;
1409
+ if (!Number.isFinite(n) || n <= 0 || n > MAX_DPR) {
1410
+ throw new InjectCliArgError(
1411
+ `--dpr expects a device pixel ratio in (0, ${MAX_DPR}], e.g. 1, 2 or 2.625 (got ${raw})`
1412
+ );
1413
+ }
1414
+ return n;
1415
+ }
1416
+ function parseColorScheme(raw) {
1417
+ if (raw === "dark" || raw === "light") return raw;
1418
+ throw new InjectCliArgError(`--color-scheme expects dark or light (got ${raw})`);
1419
+ }
1023
1420
  function parseArgs(argv) {
1024
1421
  const args = {
1025
1422
  url: "",
1026
1423
  relay: null,
1027
1424
  authToken: null,
1425
+ authTokenFile: null,
1028
1426
  registrationMetadata: null,
1029
1427
  headed: false,
1030
1428
  readyTimeoutMs: null,
@@ -1035,8 +1433,11 @@ function parseArgs(argv) {
1035
1433
  appId: null,
1036
1434
  appName: null,
1037
1435
  tabId: null,
1038
- viewportWidth: null,
1039
- viewportHeight: null,
1436
+ viewports: [],
1437
+ dprs: [],
1438
+ colorSchemes: [],
1439
+ screenshot: null,
1440
+ captureMatrix: null,
1040
1441
  storageState: null,
1041
1442
  launchArgs: [],
1042
1443
  execActions: [],
@@ -1072,6 +1473,16 @@ function parseArgs(argv) {
1072
1473
  case "--auth-token":
1073
1474
  args.authToken = (0, cli_args_exports.consumeValue)("--auth-token", argv[++i], mkError);
1074
1475
  break;
1476
+ case "--auth-token-file": {
1477
+ const raw = (0, cli_args_exports.consumeValue)("--auth-token-file", argv[++i], mkError);
1478
+ if (raw === null || raw.length === 0) {
1479
+ throw new InjectCliArgError(
1480
+ `--auth-token-file expects a path to a file holding the bearer token (got <missing>)`
1481
+ );
1482
+ }
1483
+ args.authTokenFile = raw;
1484
+ break;
1485
+ }
1075
1486
  case "--app-id":
1076
1487
  args.appId = (0, cli_args_exports.consumeValue)("--app-id", argv[++i], mkError);
1077
1488
  break;
@@ -1174,14 +1585,47 @@ function parseArgs(argv) {
1174
1585
  args.expectSelector = raw;
1175
1586
  break;
1176
1587
  }
1588
+ // The three capture axes. Each occurrence may carry a comma-separated
1589
+ // list and every occurrence appends; `validateArgs` then allows more than
1590
+ // one value only under --capture-matrix, where they are an axis.
1177
1591
  case "--viewport": {
1178
1592
  const raw = (0, cli_args_exports.consumeValue)("--viewport", argv[++i], mkError);
1179
- const match = raw?.match(/^(\d+)x(\d+)$/);
1180
- if (!match) {
1181
- throw new InjectCliArgError(`--viewport expects WxH (got ${raw ?? "<missing>"})`);
1593
+ if (raw === null) throw new InjectCliArgError(`--viewport expects WxH (got <missing>)`);
1594
+ for (const item of splitList("--viewport", raw)) args.viewports.push(parseViewport(item));
1595
+ break;
1596
+ }
1597
+ case "--dpr": {
1598
+ const raw = (0, cli_args_exports.consumeValue)("--dpr", argv[++i], mkError);
1599
+ if (raw === null) throw new InjectCliArgError(`--dpr expects a number (got <missing>)`);
1600
+ for (const item of splitList("--dpr", raw)) args.dprs.push(parseDpr(item));
1601
+ break;
1602
+ }
1603
+ case "--color-scheme": {
1604
+ const raw = (0, cli_args_exports.consumeValue)("--color-scheme", argv[++i], mkError);
1605
+ if (raw === null) {
1606
+ throw new InjectCliArgError(`--color-scheme expects dark or light (got <missing>)`);
1182
1607
  }
1183
- args.viewportWidth = Number.parseInt(match[1], 10);
1184
- args.viewportHeight = Number.parseInt(match[2], 10);
1608
+ for (const item of splitList("--color-scheme", raw)) {
1609
+ args.colorSchemes.push(parseColorScheme(item));
1610
+ }
1611
+ break;
1612
+ }
1613
+ case "--screenshot": {
1614
+ const raw = (0, cli_args_exports.consumeValue)("--screenshot", argv[++i], mkError);
1615
+ if (raw === null || raw.length === 0) {
1616
+ throw new InjectCliArgError(`--screenshot expects a PNG path (got <missing>)`);
1617
+ }
1618
+ args.screenshot = raw;
1619
+ break;
1620
+ }
1621
+ case "--capture-matrix": {
1622
+ const raw = (0, cli_args_exports.consumeValue)("--capture-matrix", argv[++i], mkError);
1623
+ if (raw === null || raw.length === 0) {
1624
+ throw new InjectCliArgError(
1625
+ `--capture-matrix expects an output directory (got <missing>)`
1626
+ );
1627
+ }
1628
+ args.captureMatrix = raw;
1185
1629
  break;
1186
1630
  }
1187
1631
  default:
@@ -1202,15 +1646,77 @@ function validateArgs(args) {
1202
1646
  if (!/^https?:\/\//i.test(args.url)) {
1203
1647
  throw new InjectCliArgError(`--url must start with http:// or https:// (got ${args.url})`);
1204
1648
  }
1205
- if (selectMode(args) === "relay" && !args.relay) {
1649
+ const mode = selectMode(args);
1650
+ if (mode === "matrix") {
1651
+ const dup = (flag, values, key) => {
1652
+ const seen = /* @__PURE__ */ new Set();
1653
+ for (const v of values) {
1654
+ const k = key(v);
1655
+ if (seen.has(k)) throw new InjectCliArgError(`${flag} lists ${k} twice`);
1656
+ seen.add(k);
1657
+ }
1658
+ };
1659
+ dup("--viewport", args.viewports, (v) => `${v.width}x${v.height}`);
1660
+ dup("--dpr", args.dprs, (v) => String(v));
1661
+ dup("--color-scheme", args.colorSchemes, (v) => v);
1662
+ if (args.relay) {
1663
+ throw new InjectCliArgError(
1664
+ "--capture-matrix captures and exits; it does not register relay tabs. Drop --relay."
1665
+ );
1666
+ }
1667
+ if (args.screenshot) {
1668
+ throw new InjectCliArgError(
1669
+ "--capture-matrix names its own frame files (<dir>/<cell>/frame-<n>.png). Drop --screenshot."
1670
+ );
1671
+ }
1672
+ return;
1673
+ }
1674
+ for (const [flag, count] of [
1675
+ ["--viewport", args.viewports.length],
1676
+ ["--dpr", args.dprs.length],
1677
+ ["--color-scheme", args.colorSchemes.length]
1678
+ ]) {
1679
+ if (count > 1) {
1680
+ throw new InjectCliArgError(
1681
+ `${flag} takes one value unless --capture-matrix is given (got ${count})`
1682
+ );
1683
+ }
1684
+ }
1685
+ if (mode === "relay" && args.screenshot) {
1686
+ throw new InjectCliArgError(
1687
+ "--screenshot captures beside getControlSnapshot actions, which only Variant A (--exec / --exec-stdin) runs. A relay tab takes no frame."
1688
+ );
1689
+ }
1690
+ if (mode === "relay" && !args.relay) {
1206
1691
  throw new InjectCliArgError(
1207
1692
  "Variant B (relay) is the default mode and requires --relay. Either pass --relay <uiBridgeBase>, or pass --exec/--exec-stdin for one-shot exec (Variant A)."
1208
1693
  );
1209
1694
  }
1210
1695
  }
1211
1696
  function selectMode(args) {
1697
+ if (args.captureMatrix) return "matrix";
1212
1698
  return args.execActions.length > 0 || args.execStdin ? "exec" : "relay";
1213
1699
  }
1700
+ var SNAPSHOT_ACTIONS = /* @__PURE__ */ new Set(["getControlSnapshot"]);
1701
+ function validateFramePlan(actions, screenshot) {
1702
+ if (screenshot === null) return;
1703
+ if (frameTokenInDirectory(screenshot)) {
1704
+ throw new InjectCliArgError(
1705
+ `--screenshot ${screenshot} has ${FRAME_INDEX_TOKEN} in a directory name, where it is not replaced. Put it in the file name (e.g. frames/frame-${FRAME_INDEX_TOKEN}.png).`
1706
+ );
1707
+ }
1708
+ const snapshots = actions.filter((a) => SNAPSHOT_ACTIONS.has(a.action)).length;
1709
+ if (snapshots === 0) {
1710
+ throw new InjectCliArgError(
1711
+ `--screenshot captures a frame beside each getControlSnapshot action, and this run has none. Add --exec 'getControlSnapshot {}'.`
1712
+ );
1713
+ }
1714
+ if (snapshots > 1 && !frameTokenInFileName(screenshot)) {
1715
+ throw new InjectCliArgError(
1716
+ `--screenshot ${screenshot} names one file but the run takes ${snapshots} snapshots, so each frame would overwrite the last. Put ${FRAME_INDEX_TOKEN} in the file name (e.g. frame-${FRAME_INDEX_TOKEN}.png); it becomes the action's position.`
1717
+ );
1718
+ }
1719
+ }
1214
1720
  var LNA_DISABLE_FEATURES = [
1215
1721
  "LocalNetworkAccessChecks",
1216
1722
  "PrivateNetworkAccessSendPreflights",
@@ -1248,6 +1754,18 @@ function buildLaunchArgs(args) {
1248
1754
  }
1249
1755
  return { launchArgs, lnaAutoAppended };
1250
1756
  }
1757
+ function resolveAuthToken(args, env, readFile) {
1758
+ if (args.authToken) return args.authToken;
1759
+ if (args.authTokenFile) {
1760
+ const raw = readFile(args.authTokenFile).trim();
1761
+ if (raw.length === 0) {
1762
+ throw new InjectCliArgError(`--auth-token-file '${args.authTokenFile}' is empty`);
1763
+ }
1764
+ return raw;
1765
+ }
1766
+ const fromEnv = env.UI_BRIDGE_AUTH_TOKEN?.trim();
1767
+ return fromEnv && fromEnv.length > 0 ? fromEnv : null;
1768
+ }
1251
1769
  function buildTransportOptions(args) {
1252
1770
  const options = { targetUrl: args.url };
1253
1771
  if (args.relay) options.uiBridgeBase = args.relay;
@@ -1264,11 +1782,105 @@ function buildTransportOptions(args) {
1264
1782
  if (args.appId) options.appId = args.appId;
1265
1783
  if (args.appName) options.appName = args.appName;
1266
1784
  if (args.tabId) options.tabId = args.tabId;
1267
- if (args.viewportWidth !== null) options.viewportWidth = args.viewportWidth;
1268
- if (args.viewportHeight !== null) options.viewportHeight = args.viewportHeight;
1785
+ applyCell(options, {
1786
+ viewport: args.viewports[0] ?? null,
1787
+ dpr: args.dprs[0] ?? null,
1788
+ colorScheme: args.colorSchemes[0] ?? null
1789
+ });
1269
1790
  if (args.storageState) options.storageStatePath = args.storageState;
1270
1791
  return options;
1271
1792
  }
1793
+ function applyCell(options, cell) {
1794
+ delete options.viewportWidth;
1795
+ delete options.viewportHeight;
1796
+ delete options.deviceScaleFactor;
1797
+ delete options.colorScheme;
1798
+ if (cell.viewport) {
1799
+ options.viewportWidth = cell.viewport.width;
1800
+ options.viewportHeight = cell.viewport.height;
1801
+ }
1802
+ if (cell.dpr !== null) options.deviceScaleFactor = cell.dpr;
1803
+ if (cell.colorScheme !== null) options.colorScheme = cell.colorScheme;
1804
+ }
1805
+ function buildCellTransportOptions(args, cell) {
1806
+ const options = buildTransportOptions(args);
1807
+ applyCell(options, cell);
1808
+ return options;
1809
+ }
1810
+ var CLI_WAIT_ACTIONS = ["waitForSelector", "sleep"];
1811
+ var WAIT_SELECTOR_STATES = ["attached", "detached", "visible", "hidden"];
1812
+ var DEFAULT_WAIT_SELECTOR_TIMEOUT_MS = 1e4;
1813
+ var MAX_SLEEP_MS = 6e5;
1814
+ function asRecord(payload, action) {
1815
+ if (payload === void 0 || payload === null) return {};
1816
+ if (typeof payload !== "object" || Array.isArray(payload)) {
1817
+ throw new InjectCliArgError(`${action} payload must be a JSON object`);
1818
+ }
1819
+ return payload;
1820
+ }
1821
+ function parseWaitForSelectorPayload(payload) {
1822
+ const obj = asRecord(payload, "waitForSelector");
1823
+ const selector = obj["selector"];
1824
+ if (typeof selector !== "string" || selector.trim().length === 0) {
1825
+ throw new InjectCliArgError(`waitForSelector payload requires a non-empty 'selector' string`);
1826
+ }
1827
+ let timeoutMs = DEFAULT_WAIT_SELECTOR_TIMEOUT_MS;
1828
+ if (obj["timeoutMs"] !== void 0) {
1829
+ const raw = obj["timeoutMs"];
1830
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) {
1831
+ throw new InjectCliArgError(
1832
+ `waitForSelector 'timeoutMs' must be a non-negative number (got ${JSON.stringify(raw)})`
1833
+ );
1834
+ }
1835
+ timeoutMs = raw;
1836
+ }
1837
+ let state = "attached";
1838
+ if (obj["state"] !== void 0) {
1839
+ const raw = obj["state"];
1840
+ if (typeof raw !== "string" || !WAIT_SELECTOR_STATES.includes(raw)) {
1841
+ throw new InjectCliArgError(
1842
+ `waitForSelector 'state' must be one of ${WAIT_SELECTOR_STATES.join(" | ")} (got ${JSON.stringify(raw)})`
1843
+ );
1844
+ }
1845
+ state = raw;
1846
+ }
1847
+ return { selector: selector.trim(), timeoutMs, state };
1848
+ }
1849
+ function parseSleepPayload(payload) {
1850
+ const obj = asRecord(payload, "sleep");
1851
+ const raw = obj["ms"];
1852
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0 || raw > MAX_SLEEP_MS) {
1853
+ throw new InjectCliArgError(
1854
+ `sleep payload requires 'ms' as a number in 0..${MAX_SLEEP_MS} (got ${JSON.stringify(raw)})`
1855
+ );
1856
+ }
1857
+ return { ms: raw };
1858
+ }
1859
+ function validateWaitActions(actions) {
1860
+ for (const { action, payload } of actions) {
1861
+ if (action === "waitForSelector") parseWaitForSelectorPayload(payload);
1862
+ else if (action === "sleep") parseSleepPayload(payload);
1863
+ }
1864
+ }
1865
+ function registerWaitActions(registrar) {
1866
+ registrar.register("sleep", async (params) => {
1867
+ const { ms } = parseSleepPayload(params);
1868
+ await new Promise((resolve3) => setTimeout(resolve3, ms));
1869
+ return { slept: ms };
1870
+ });
1871
+ registrar.register("waitForSelector", async (params, ctx) => {
1872
+ const { selector, timeoutMs, state } = parseWaitForSelectorPayload(params);
1873
+ const page = ctx?.page;
1874
+ if (!page || typeof page.waitForSelector !== "function") {
1875
+ throw new InjectCliArgError(
1876
+ `waitForSelector needs the transport's page handle, which this context does not expose`
1877
+ );
1878
+ }
1879
+ const startedAt = Date.now();
1880
+ await page.waitForSelector(selector, { state, timeout: timeoutMs });
1881
+ return { waited: true, selector, state, elapsedMs: Date.now() - startedAt };
1882
+ });
1883
+ }
1272
1884
  function die(msg) {
1273
1885
  process.stderr.write(`${msg}
1274
1886
  `);
@@ -1279,13 +1891,13 @@ function log(quiet, msg) {
1279
1891
  `);
1280
1892
  }
1281
1893
  function readStdin() {
1282
- return new Promise((resolve, reject) => {
1894
+ return new Promise((resolve3, reject) => {
1283
1895
  let data = "";
1284
1896
  process.stdin.setEncoding("utf8");
1285
1897
  process.stdin.on("data", (chunk) => {
1286
1898
  data += chunk;
1287
1899
  });
1288
- process.stdin.on("end", () => resolve(data));
1900
+ process.stdin.on("end", () => resolve3(data));
1289
1901
  process.stdin.on("error", reject);
1290
1902
  });
1291
1903
  }
@@ -1328,6 +1940,20 @@ ${USAGE}`);
1328
1940
  process.exit(0);
1329
1941
  }
1330
1942
  const mode = selectMode(args);
1943
+ if (mode === "matrix") {
1944
+ await runMatrix(args);
1945
+ return;
1946
+ }
1947
+ let resolvedAuthToken = args.authToken;
1948
+ if (mode === "relay") {
1949
+ try {
1950
+ resolvedAuthToken = resolveAuthToken(args, process.env, (p) => fs.readFileSync(p, "utf8"));
1951
+ } catch (err) {
1952
+ if (err instanceof InjectCliArgError) die(err.message);
1953
+ const msg = err instanceof Error ? err.message : String(err);
1954
+ die(`--auth-token-file '${args.authTokenFile}': cannot read it (${msg})`);
1955
+ }
1956
+ }
1331
1957
  const { launchArgs, lnaAutoAppended } = buildLaunchArgs(args);
1332
1958
  if (lnaAutoAppended) {
1333
1959
  log(
@@ -1335,7 +1961,10 @@ ${USAGE}`);
1335
1961
  `[ui-bridge-inject] https page + loopback relay detected \u2014 auto-appending Chromium LNA-disable flags so the page can fetch the relay: --disable-features=${LNA_DISABLE_FEATURES.join(",")} (effective launch args: ${JSON.stringify(launchArgs)})`
1336
1962
  );
1337
1963
  }
1338
- const transport = createTransport({ kind: "injected", options: buildTransportOptions(args) });
1964
+ const transport = createTransport({
1965
+ kind: "injected",
1966
+ options: buildTransportOptions({ ...args, authToken: resolvedAuthToken })
1967
+ });
1339
1968
  transport.register("__inject_cli_info", (_p, ctx) => {
1340
1969
  const c = ctx;
1341
1970
  return { tabId: c.tabId ?? null, uiBridgeRegistered: c.uiBridgeRegistered ?? false };
@@ -1346,15 +1975,89 @@ ${USAGE}`);
1346
1975
  }
1347
1976
  await runRelay(args, transport);
1348
1977
  }
1349
- async function runExec(args, transport) {
1978
+ async function collectActions(args) {
1350
1979
  const actions = [...args.execActions];
1351
1980
  if (args.execStdin) {
1352
1981
  const raw = await readStdin();
1353
1982
  actions.push(...parseStdinActions(raw));
1354
1983
  }
1984
+ return actions;
1985
+ }
1986
+ var CAPTURE_FRAME_ACTION = "__inject_cli_capture_frame";
1987
+ function registerFrameCapture(registrar) {
1988
+ registrar.register(CAPTURE_FRAME_ACTION, async (params, ctx) => {
1989
+ const { action, payload, path } = params;
1990
+ const c = ctx;
1991
+ const execute = c?.execute;
1992
+ if (!c?.page || typeof execute !== "function") {
1993
+ throw new InjectCliArgError(
1994
+ `${action} with a frame needs the transport's page and in-page execute, which this context does not expose`
1995
+ );
1996
+ }
1997
+ return captureFrameInLockstep({
1998
+ page: c.page,
1999
+ takeSnapshot: () => execute(action, payload),
2000
+ path
2001
+ });
2002
+ });
2003
+ }
2004
+ async function executeActions(transport, actions, framePathFor, onLine) {
2005
+ let anyError = false;
2006
+ for (let i = 0; i < actions.length; i++) {
2007
+ const { action, payload } = actions[i];
2008
+ const position = i + 1;
2009
+ const framePath = framePathFor(position, action);
2010
+ let line;
2011
+ try {
2012
+ if (framePath !== null) {
2013
+ const cap = await transport.dispatch(CAPTURE_FRAME_ACTION, {
2014
+ action,
2015
+ payload,
2016
+ path: framePath
2017
+ });
2018
+ const returnedError = returnedFailureError(action, cap.snapshot);
2019
+ if (returnedError || cap.frameError) anyError = true;
2020
+ line = {
2021
+ action,
2022
+ result: cap.snapshot,
2023
+ ...returnedError ? { error: returnedError } : {},
2024
+ frame: cap.frame,
2025
+ ...cap.frameError ? { frameError: cap.frameError } : {}
2026
+ };
2027
+ } else {
2028
+ if (!transport.handlerRegistry.has(action)) {
2029
+ transport.register(
2030
+ action,
2031
+ (params, ctx) => ctx.execute(action, params)
2032
+ );
2033
+ }
2034
+ const result = await transport.dispatch(action, payload);
2035
+ const returnedError = returnedFailureError(action, result);
2036
+ if (returnedError) anyError = true;
2037
+ line = returnedError ? { action, result, error: returnedError } : { action, result };
2038
+ }
2039
+ } catch (err) {
2040
+ anyError = true;
2041
+ line = { action, error: thrownError(err) };
2042
+ }
2043
+ onLine(line, position);
2044
+ }
2045
+ return anyError;
2046
+ }
2047
+ async function runExec(args, transport) {
2048
+ const actions = await collectActions(args);
1355
2049
  if (actions.length === 0) {
1356
2050
  die("Variant A (exec) selected but no actions were provided");
1357
2051
  }
2052
+ try {
2053
+ validateWaitActions(actions);
2054
+ validateFramePlan(actions, args.screenshot);
2055
+ } catch (err) {
2056
+ if (err instanceof InjectCliArgError) die(err.message);
2057
+ throw err;
2058
+ }
2059
+ registerWaitActions(transport);
2060
+ registerFrameCapture(transport);
1358
2061
  log(args.quiet, `[ui-bridge-inject] launching injected transport (exec mode)`);
1359
2062
  try {
1360
2063
  await transport.ready();
@@ -1366,36 +2069,195 @@ async function runExec(args, transport) {
1366
2069
  });
1367
2070
  process.exit(1);
1368
2071
  }
1369
- let anyError = false;
2072
+ const screenshot = args.screenshot;
2073
+ let anyError;
1370
2074
  try {
1371
- for (const { action, payload } of actions) {
1372
- if (!transport.handlerRegistry.has(action)) {
1373
- transport.register(
1374
- action,
1375
- (params, ctx) => ctx.execute(action, params)
1376
- );
1377
- }
1378
- try {
1379
- const result = await transport.dispatch(action, payload);
1380
- const returnedError = returnedFailureError(action, result);
1381
- if (returnedError) anyError = true;
1382
- process.stdout.write(
1383
- `${JSON.stringify(
1384
- returnedError ? { action, result, error: returnedError } : { action, result }
1385
- )}
1386
- `
1387
- );
1388
- } catch (err) {
1389
- anyError = true;
1390
- process.stdout.write(`${JSON.stringify({ action, error: thrownError(err) })}
2075
+ anyError = await executeActions(
2076
+ transport,
2077
+ actions,
2078
+ (position, action) => screenshot !== null && SNAPSHOT_ACTIONS.has(action) ? expandFramePath(screenshot, position) : null,
2079
+ (line) => process.stdout.write(`${JSON.stringify(line)}
2080
+ `)
2081
+ );
2082
+ } finally {
2083
+ await transport.close().catch(() => {
2084
+ });
2085
+ }
2086
+ process.exit(anyError ? 1 : 0);
2087
+ }
2088
+ function wrapperVersion() {
2089
+ try {
2090
+ const pkg = JSON.parse(fs.readFileSync(new URL("../package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('inject-cli.cjs', document.baseURI).href))), "utf8"));
2091
+ return pkg.name === "@qontinui/ui-bridge-wrapper" && typeof pkg.version === "string" ? pkg.version : null;
2092
+ } catch {
2093
+ return null;
2094
+ }
2095
+ }
2096
+ async function runMatrixCell(args, cell, plan, dir) {
2097
+ const id = cellId(cell);
2098
+ const cellDir = path.join(dir, id);
2099
+ const transport = createTransport({
2100
+ kind: "injected",
2101
+ options: buildCellTransportOptions(args, cell)
2102
+ });
2103
+ registerWaitActions(transport);
2104
+ registerFrameCapture(transport);
2105
+ log(args.quiet, `[ui-bridge-inject] capture matrix: cell ${id}`);
2106
+ try {
2107
+ ensurePrivateDir(cellDir);
2108
+ await transport.ready();
2109
+ } catch (err) {
2110
+ await transport.close().catch(() => {
2111
+ });
2112
+ const e = thrownError(err);
2113
+ return {
2114
+ id,
2115
+ requested: cell,
2116
+ status: "failed",
2117
+ error: { code: e.code, message: e.message },
2118
+ results: null,
2119
+ pairs: []
2120
+ };
2121
+ }
2122
+ const lines = [];
2123
+ const pairs = [];
2124
+ try {
2125
+ const anyError = await executeActions(
2126
+ transport,
2127
+ plan,
2128
+ (position, action) => SNAPSHOT_ACTIONS.has(action) ? path.join(cellDir, `frame-${position}.png`) : null,
2129
+ (line, position) => {
2130
+ lines.push(JSON.stringify(line));
2131
+ if (!SNAPSHOT_ACTIONS.has(line.action) || line.result === void 0) return;
2132
+ const snapshotPath = path.join(cellDir, `snapshot-${position}.json`);
2133
+ writePrivateFile(snapshotPath, `${JSON.stringify(line.result)}
1391
2134
  `);
2135
+ pairs.push({
2136
+ position,
2137
+ snapshot: manifestPath(dir, snapshotPath),
2138
+ frame: line.frame ? { ...line.frame, path: manifestPath(dir, line.frame.path) } : null,
2139
+ ...line.frameError ? { frameError: line.frameError } : {}
2140
+ });
1392
2141
  }
1393
- }
2142
+ );
2143
+ const resultsPath = path.join(cellDir, "results.ndjson");
2144
+ writePrivateFile(resultsPath, `${lines.join("\n")}
2145
+ `);
2146
+ return {
2147
+ id,
2148
+ requested: cell,
2149
+ status: anyError ? "incomplete" : "captured",
2150
+ results: manifestPath(dir, resultsPath),
2151
+ pairs
2152
+ };
2153
+ } catch (err) {
2154
+ const e = thrownError(err);
2155
+ return {
2156
+ id,
2157
+ requested: cell,
2158
+ status: "failed",
2159
+ error: { code: e.code, message: e.message },
2160
+ results: null,
2161
+ pairs
2162
+ };
1394
2163
  } finally {
1395
2164
  await transport.close().catch(() => {
1396
2165
  });
1397
2166
  }
1398
- process.exit(anyError ? 1 : 0);
2167
+ }
2168
+ function assertEmptyMatrixDir(dir) {
2169
+ let entries;
2170
+ try {
2171
+ entries = fs.readdirSync(dir);
2172
+ } catch (err) {
2173
+ const code = err.code;
2174
+ if (code === "ENOENT") return;
2175
+ if (code === "ENOTDIR") {
2176
+ throw new InjectCliArgError(
2177
+ `${dir} is a file, not a directory. Pass an empty directory, or one that does not exist yet.`
2178
+ );
2179
+ }
2180
+ throw err;
2181
+ }
2182
+ if (entries.length > 0) {
2183
+ throw new InjectCliArgError(
2184
+ `${dir} is not empty (${entries.length} entr${entries.length === 1 ? "y" : "ies"}). Pass an empty directory, or one that does not exist yet; the matrix never clears or overwrites one.`
2185
+ );
2186
+ }
2187
+ }
2188
+ async function captureMatrix(args, plan, onCell = () => {
2189
+ }) {
2190
+ if (!args.captureMatrix)
2191
+ throw new InjectCliArgError("captureMatrix needs --capture-matrix <dir>");
2192
+ const dir = path.resolve(args.captureMatrix);
2193
+ assertEmptyMatrixDir(dir);
2194
+ ensurePrivateDir(dir);
2195
+ const cells = expandMatrix({
2196
+ viewports: args.viewports,
2197
+ dprs: args.dprs,
2198
+ colorSchemes: args.colorSchemes
2199
+ });
2200
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2201
+ log(args.quiet, `[ui-bridge-inject] capture matrix: ${cells.length} cell(s) into ${dir}`);
2202
+ const reports = [];
2203
+ for (const cell of cells) {
2204
+ const report = await runMatrixCell(args, cell, plan, dir);
2205
+ reports.push(report);
2206
+ onCell(report, path.join(dir, report.id));
2207
+ }
2208
+ const manifest = {
2209
+ kind: "ui-bridge-capture-matrix",
2210
+ schemaVersion: 1,
2211
+ url: args.url,
2212
+ producer: {
2213
+ name: "ui-bridge-inject",
2214
+ package: "@qontinui/ui-bridge-wrapper",
2215
+ version: wrapperVersion()
2216
+ },
2217
+ startedAt,
2218
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
2219
+ axes: { viewports: args.viewports, dprs: args.dprs, colorSchemes: args.colorSchemes },
2220
+ plan: plan.map((a, i) => ({ position: i + 1, action: a.action, payload: a.payload })),
2221
+ cells: reports
2222
+ };
2223
+ const manifestFile = path.join(dir, "matrix.json");
2224
+ writePrivateFile(manifestFile, `${JSON.stringify(manifest, null, 2)}
2225
+ `);
2226
+ log(args.quiet, `[ui-bridge-inject] capture matrix: manifest ${manifestFile}`);
2227
+ return manifest;
2228
+ }
2229
+ async function runMatrix(args) {
2230
+ const actions = await collectActions(args);
2231
+ const plan = actions.length > 0 ? actions : [{ action: "getControlSnapshot", payload: {} }];
2232
+ try {
2233
+ validateWaitActions(plan);
2234
+ } catch (err) {
2235
+ if (err instanceof InjectCliArgError) die(err.message);
2236
+ throw err;
2237
+ }
2238
+ if (!plan.some((a) => SNAPSHOT_ACTIONS.has(a.action))) {
2239
+ die(
2240
+ `--capture-matrix stores frame-and-snapshot pairs, and this plan takes no getControlSnapshot. Add --exec 'getControlSnapshot {}', or pass no --exec at all.`
2241
+ );
2242
+ }
2243
+ let manifest;
2244
+ try {
2245
+ manifest = await captureMatrix(args, plan, (report, cellDir) => {
2246
+ process.stdout.write(
2247
+ `${JSON.stringify({
2248
+ cell: report.id,
2249
+ status: report.status,
2250
+ frames: report.pairs.filter((p) => p.frame !== null).length,
2251
+ dir: cellDir,
2252
+ ...report.error ? { error: report.error } : {}
2253
+ })}
2254
+ `
2255
+ );
2256
+ });
2257
+ } catch (err) {
2258
+ die(`--capture-matrix: ${err instanceof Error ? err.message : String(err)}`);
2259
+ }
2260
+ process.exit(manifest.cells.every((c) => c.status === "captured") ? 0 : 1);
1399
2261
  }
1400
2262
  async function runRelay(args, transport) {
1401
2263
  log(
@@ -1455,14 +2317,36 @@ if (isMain) {
1455
2317
  });
1456
2318
  }
1457
2319
 
2320
+ exports.CAPTURE_FRAME_ACTION = CAPTURE_FRAME_ACTION;
2321
+ exports.CLI_WAIT_ACTIONS = CLI_WAIT_ACTIONS;
2322
+ exports.DEFAULT_WAIT_SELECTOR_TIMEOUT_MS = DEFAULT_WAIT_SELECTOR_TIMEOUT_MS;
1458
2323
  exports.InjectCliArgError = InjectCliArgError;
1459
2324
  exports.LNA_DISABLE_FEATURES = LNA_DISABLE_FEATURES;
2325
+ exports.MAX_DPR = MAX_DPR;
2326
+ exports.MAX_SLEEP_MS = MAX_SLEEP_MS;
2327
+ exports.MAX_VIEWPORT_SIDE = MAX_VIEWPORT_SIDE;
2328
+ exports.SNAPSHOT_ACTIONS = SNAPSHOT_ACTIONS;
1460
2329
  exports.USAGE = USAGE;
2330
+ exports.WAIT_SELECTOR_STATES = WAIT_SELECTOR_STATES;
2331
+ exports.assertEmptyMatrixDir = assertEmptyMatrixDir;
2332
+ exports.buildCellTransportOptions = buildCellTransportOptions;
1461
2333
  exports.buildLaunchArgs = buildLaunchArgs;
1462
2334
  exports.buildTransportOptions = buildTransportOptions;
2335
+ exports.captureMatrix = captureMatrix;
2336
+ exports.executeActions = executeActions;
1463
2337
  exports.isLoopbackHost = isLoopbackHost;
1464
2338
  exports.parseArgs = parseArgs;
2339
+ exports.parseColorScheme = parseColorScheme;
2340
+ exports.parseDpr = parseDpr;
2341
+ exports.parseSleepPayload = parseSleepPayload;
2342
+ exports.parseViewport = parseViewport;
2343
+ exports.parseWaitForSelectorPayload = parseWaitForSelectorPayload;
2344
+ exports.registerFrameCapture = registerFrameCapture;
2345
+ exports.registerWaitActions = registerWaitActions;
2346
+ exports.resolveAuthToken = resolveAuthToken;
1465
2347
  exports.selectMode = selectMode;
1466
2348
  exports.validateArgs = validateArgs;
2349
+ exports.validateFramePlan = validateFramePlan;
2350
+ exports.validateWaitActions = validateWaitActions;
1467
2351
  //# sourceMappingURL=inject-cli.cjs.map
1468
2352
  //# sourceMappingURL=inject-cli.cjs.map