@qontinui/ui-bridge-wrapper 0.7.1 → 0.8.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,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- var url = require('url');
5
- var module$1 = require('module');
6
4
  var fs = require('fs');
5
+ var path = require('path');
6
+ var module$1 = require('module');
7
+ var crypto = require('crypto');
7
8
  var ui_bridge_cli_args_star = require('@qontinui/ui-bridge-cli-args');
8
9
 
9
10
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -31,6 +32,12 @@ var __defProp = Object.defineProperty;
31
32
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
32
33
  var __getOwnPropNames = Object.getOwnPropertyNames;
33
34
  var __hasOwnProp = Object.prototype.hasOwnProperty;
35
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
36
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
37
+ }) : x)(function(x) {
38
+ if (typeof require !== "undefined") return require.apply(this, arguments);
39
+ throw Error('Dynamic require of "' + x + '" is not supported');
40
+ });
34
41
  var __copyProps = (to, from, except, desc) => {
35
42
  if (from && typeof from === "object" || typeof from === "function") {
36
43
  for (let key of __getOwnPropNames(from))
@@ -266,6 +273,8 @@ var HeadlessTransport = class extends BaseTransport {
266
273
  targetUrl,
267
274
  viewportWidth: typeof raw["viewportWidth"] === "number" ? raw["viewportWidth"] : void 0,
268
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,
269
278
  uiBridgeBase: typeof raw["uiBridgeBase"] === "string" ? raw["uiBridgeBase"] : void 0,
270
279
  waitForUiBridgeMs: typeof raw["waitForUiBridgeMs"] === "number" ? raw["waitForUiBridgeMs"] : void 0,
271
280
  userAgent: typeof raw["userAgent"] === "string" ? raw["userAgent"] : void 0,
@@ -300,6 +309,7 @@ Underlying import error: ${cause}`
300
309
  }
301
310
  const initScripts = await this.buildInitScripts();
302
311
  const relayAuth = this.relayAuth();
312
+ const pinnedTabId = this.pinnedTabId();
303
313
  let tab;
304
314
  try {
305
315
  tab = await launchHeadlessTab({
@@ -309,13 +319,16 @@ Underlying import error: ${cause}`
309
319
  waitForUiBridgeMs: this.options.waitForUiBridgeMs,
310
320
  viewportWidth: this.options.viewportWidth,
311
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 } : {},
312
324
  userAgent: this.options.userAgent,
313
325
  forwardConsole: this.options.forwardConsole,
314
326
  initScripts: initScripts.length > 0 ? initScripts : void 0,
315
327
  launchArgs: this.options.launchArgs && this.options.launchArgs.length > 0 ? this.options.launchArgs : void 0,
316
328
  storageStatePath: this.options.storageStatePath,
317
329
  ...relayAuth.authToken ? { authToken: relayAuth.authToken } : {},
318
- ...relayAuth.callerUserId ? { callerUserId: relayAuth.callerUserId } : {}
330
+ ...relayAuth.callerUserId ? { callerUserId: relayAuth.callerUserId } : {},
331
+ ...pinnedTabId ? { pinnedTabId } : {}
319
332
  });
320
333
  } catch (err) {
321
334
  const cause = err instanceof Error ? err.message : String(err);
@@ -337,8 +350,39 @@ Underlying launch error: ${cause}`
337
350
  tabId: tab.tabId,
338
351
  close: tab.close
339
352
  };
353
+ await this.verifyEmulation(tab.page);
340
354
  await this.afterLaunch(tab.page);
341
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
+ }
342
386
  /**
343
387
  * Subclass hook: init-scripts to register on the browser context before the
344
388
  * first navigation (via `context.addInitScript`). Default: none. Injected
@@ -356,6 +400,13 @@ Underlying launch error: ${cause}`
356
400
  relayAuth() {
357
401
  return {};
358
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
+ }
359
410
  /**
360
411
  * Subclass hook: run after launch + navigation, before `ready()` resolves.
361
412
  * Default: no-op. Injected mode overrides it to await the in-page runtime.
@@ -418,6 +469,14 @@ function loadInjectedBundle() {
418
469
  }
419
470
  var InjectedTransport = class extends HeadlessTransport {
420
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");
421
480
  constructor(config, registry) {
422
481
  const raw = config.options ?? {};
423
482
  const headed = raw["headed"] === true;
@@ -452,9 +511,11 @@ var InjectedTransport = class extends HeadlessTransport {
452
511
  if (this.injected.appId) cfg.appId = this.injected.appId;
453
512
  if (this.injected.appName) cfg.appName = this.injected.appName;
454
513
  }
455
- if (this.injected.tabId) cfg.tabId = this.injected.tabId;
456
- if (this.injected.settleQuietMs !== void 0)
457
- 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;
458
519
  if (this.injected.settleTimeoutMs !== void 0)
459
520
  cfg.settleTimeoutMs = this.injected.settleTimeoutMs;
460
521
  if (this.injected.expectSelector !== void 0)
@@ -473,6 +534,9 @@ var InjectedTransport = class extends HeadlessTransport {
473
534
  ...this.injected.registrationMetadata?.userId ? { callerUserId: this.injected.registrationMetadata.userId } : {}
474
535
  };
475
536
  }
537
+ pinnedTabId() {
538
+ return this.injected.tabId;
539
+ }
476
540
  async buildInitScripts() {
477
541
  const scripts = [];
478
542
  const cfg = this.injectedConfig();
@@ -676,7 +740,7 @@ var LiveSessionTransport = class extends BaseTransport {
676
740
  ws.addEventListener("message", (ev) => this.handleMessage(ev.data));
677
741
  ws.addEventListener("close", () => this.handleClose());
678
742
  ws.addEventListener("error", (ev) => this.handleError(ev));
679
- await new Promise((resolve, reject) => {
743
+ await new Promise((resolve3, reject) => {
680
744
  const onOpen = () => {
681
745
  try {
682
746
  const frame = {
@@ -706,7 +770,7 @@ var LiveSessionTransport = class extends BaseTransport {
706
770
  )
707
771
  );
708
772
  }, timeoutMs);
709
- this.ackResolvers = { resolve, reject, timer };
773
+ this.ackResolvers = { resolve: resolve3, reject, timer };
710
774
  };
711
775
  ws.addEventListener("open", onOpen);
712
776
  });
@@ -853,6 +917,240 @@ function createTransport(config) {
853
917
  var cli_args_exports = {};
854
918
  __reExport(cli_args_exports, ui_bridge_cli_args_star__namespace);
855
919
 
920
+ // src/action-outcome.ts
921
+ var RETURNED_FAILURE_CODE = "ACTION_FAILED";
922
+ function isRecord(v) {
923
+ return typeof v === "object" && v !== null && !Array.isArray(v);
924
+ }
925
+ function nonEmptyString(v) {
926
+ return typeof v === "string" && v.length > 0 ? v : null;
927
+ }
928
+ function isReturnedFailure(result) {
929
+ return isRecord(result) && result.success === false;
930
+ }
931
+ function returnedFailureError(action, result) {
932
+ if (!isReturnedFailure(result)) return null;
933
+ const r = result;
934
+ const failureDetails = isRecord(r.failureDetails) ? r.failureDetails : null;
935
+ const errorObj = isRecord(r.error) ? r.error : null;
936
+ const code = nonEmptyString(failureDetails?.errorCode) ?? nonEmptyString(errorObj?.code) ?? RETURNED_FAILURE_CODE;
937
+ const message = nonEmptyString(r.error) ?? nonEmptyString(errorObj?.message) ?? nonEmptyString(failureDetails?.message) ?? `action '${action}' reported success: false`;
938
+ const details = failureDetails ?? errorObj ?? void 0;
939
+ const out = { code, message, source: "returned" };
940
+ if (details !== void 0) out.details = details;
941
+ return out;
942
+ }
943
+ function thrownError(err) {
944
+ if (err instanceof WrapperTransportError) {
945
+ const out = { code: err.code, message: err.message, source: "thrown" };
946
+ if (err.details !== void 0) out.details = err.details;
947
+ return out;
948
+ }
949
+ return {
950
+ code: "UNKNOWN",
951
+ message: err instanceof Error ? err.message : String(err),
952
+ source: "thrown"
953
+ };
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
+ }
1153
+
856
1154
  // src/inject-cli.ts
857
1155
  var USAGE = `ui-bridge-inject \u2014 drive UI Bridge's injected transport against a UI-Bridge-free page
858
1156
 
@@ -863,7 +1161,12 @@ Required:
863
1161
  Relay (Variant B \u2014 the default mode; --relay is REQUIRED in this mode):
864
1162
  --relay <uiBridgeBase> UI Bridge relay base; the injected runtime registers
865
1163
  as a relay tab. Example: http://localhost:3001/api/ui-bridge
866
- --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.
867
1170
  --registration-metadata <json>
868
1171
  JSON {"userId":"...","sessionId":"..."} for per-user
869
1172
  tab-scoping on relay heartbeats
@@ -878,6 +1181,103 @@ Exec (Variant A \u2014 one-shot; presence of any --exec/--exec-stdin selects thi
878
1181
  --exec-stdin Read NDJSON lines from stdin; each line is
879
1182
  {"action":"...","payload":{...}}
880
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
+
1207
+ Exec output & exit code:
1208
+ One JSON line per action, in order, on stdout \u2014 ALWAYS one line per action,
1209
+ including failures. An action that succeeded prints {"action":..,"result":..}.
1210
+ An action that FAILED additionally carries an "error" key:
1211
+ {"action":..,"result":..,"error":{"code":..,"message":..,"source":"returned",
1212
+ "details":{..}}}
1213
+ A failure is EITHER thrown by the transport (source "thrown") OR returned by
1214
+ the in-page handler as {"success":false,...} (source "returned") \u2014 a missing,
1215
+ invisible or disabled element is the RETURNED kind, so "result" alone never
1216
+ tells you whether the action did anything. Branch on "error"; "error.code" is
1217
+ the handler's own errorCode (ELEMENT_NOT_FOUND / ELEMENT_NOT_VISIBLE /
1218
+ ELEMENT_NOT_ENABLED / ...) and "error.details" is its full failureDetails,
1219
+ unflattened.
1220
+
1221
+ A failed action does NOT abort the actions after it. Every action runs, each
1222
+ gets its line, and the process exits 1 at the end if ANY action failed (0 if
1223
+ all succeeded). This is the pre-existing behaviour of a thrown failure, kept
1224
+ for a returned one so there is one convention rather than two \u2014 and it is
1225
+ what keeps the one-line-per-action contract intact for a caller that pairs
1226
+ N actions with N lines. A caller that wants stop-on-first-failure gets it by
1227
+ running one action per invocation and checking the exit code.
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
+
881
1281
  Optional:
882
1282
  --storage-state <path> Seed the browser context from a Playwright storageState
883
1283
  JSON file (cookies + localStorage) produced by
@@ -898,7 +1298,8 @@ Optional:
898
1298
  mounts lazily after unrelated chrome. If it never appears
899
1299
  before --settle-timeout, ready() fails with a BLOCKED error
900
1300
  instead of returning a control-less page.
901
- --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.
902
1303
  --launch-arg <arg> Extra Chromium command-line argument (repeatable),
903
1304
  passed through to chromium.launch({ args }).
904
1305
  NOTE: when --url is https and --relay resolves to a
@@ -914,6 +1315,10 @@ Examples:
914
1315
  ui-bridge-inject --url https://example.com/login \\
915
1316
  --relay http://localhost:3001/api/ui-bridge --app-name "example login"
916
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
+
917
1322
  # Variant A: snapshot the controls on a page, then exit
918
1323
  ui-bridge-inject --url https://example.com/login \\
919
1324
  --exec 'getControlSnapshot {}'
@@ -922,6 +1327,23 @@ Examples:
922
1327
  ui-bridge-inject --url https://example.com/login \\
923
1328
  --exec 'find {"text":"Sign in"}'
924
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
+
925
1347
  # Reuse a saved login: drive a login-walled page with a captured auth artifact
926
1348
  ui-bridge-login-web --url "https://qontinui.io/login?next=%2Fadmin" \\
927
1349
  --success /admin --storage-state-out auth.json
@@ -957,11 +1379,50 @@ function parseExecValue(raw) {
957
1379
  }
958
1380
  return { action, payload };
959
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
+ }
960
1420
  function parseArgs(argv) {
961
1421
  const args = {
962
1422
  url: "",
963
1423
  relay: null,
964
1424
  authToken: null,
1425
+ authTokenFile: null,
965
1426
  registrationMetadata: null,
966
1427
  headed: false,
967
1428
  readyTimeoutMs: null,
@@ -972,8 +1433,11 @@ function parseArgs(argv) {
972
1433
  appId: null,
973
1434
  appName: null,
974
1435
  tabId: null,
975
- viewportWidth: null,
976
- viewportHeight: null,
1436
+ viewports: [],
1437
+ dprs: [],
1438
+ colorSchemes: [],
1439
+ screenshot: null,
1440
+ captureMatrix: null,
977
1441
  storageState: null,
978
1442
  launchArgs: [],
979
1443
  execActions: [],
@@ -1009,6 +1473,16 @@ function parseArgs(argv) {
1009
1473
  case "--auth-token":
1010
1474
  args.authToken = (0, cli_args_exports.consumeValue)("--auth-token", argv[++i], mkError);
1011
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
+ }
1012
1486
  case "--app-id":
1013
1487
  args.appId = (0, cli_args_exports.consumeValue)("--app-id", argv[++i], mkError);
1014
1488
  break;
@@ -1111,14 +1585,47 @@ function parseArgs(argv) {
1111
1585
  args.expectSelector = raw;
1112
1586
  break;
1113
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.
1114
1591
  case "--viewport": {
1115
1592
  const raw = (0, cli_args_exports.consumeValue)("--viewport", argv[++i], mkError);
1116
- const match = raw?.match(/^(\d+)x(\d+)$/);
1117
- if (!match) {
1118
- 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>)`);
1607
+ }
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
+ );
1119
1627
  }
1120
- args.viewportWidth = Number.parseInt(match[1], 10);
1121
- args.viewportHeight = Number.parseInt(match[2], 10);
1628
+ args.captureMatrix = raw;
1122
1629
  break;
1123
1630
  }
1124
1631
  default:
@@ -1139,15 +1646,77 @@ function validateArgs(args) {
1139
1646
  if (!/^https?:\/\//i.test(args.url)) {
1140
1647
  throw new InjectCliArgError(`--url must start with http:// or https:// (got ${args.url})`);
1141
1648
  }
1142
- 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) {
1143
1691
  throw new InjectCliArgError(
1144
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)."
1145
1693
  );
1146
1694
  }
1147
1695
  }
1148
1696
  function selectMode(args) {
1697
+ if (args.captureMatrix) return "matrix";
1149
1698
  return args.execActions.length > 0 || args.execStdin ? "exec" : "relay";
1150
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
+ }
1151
1720
  var LNA_DISABLE_FEATURES = [
1152
1721
  "LocalNetworkAccessChecks",
1153
1722
  "PrivateNetworkAccessSendPreflights",
@@ -1185,6 +1754,18 @@ function buildLaunchArgs(args) {
1185
1754
  }
1186
1755
  return { launchArgs, lnaAutoAppended };
1187
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
+ }
1188
1769
  function buildTransportOptions(args) {
1189
1770
  const options = { targetUrl: args.url };
1190
1771
  if (args.relay) options.uiBridgeBase = args.relay;
@@ -1201,11 +1782,105 @@ function buildTransportOptions(args) {
1201
1782
  if (args.appId) options.appId = args.appId;
1202
1783
  if (args.appName) options.appName = args.appName;
1203
1784
  if (args.tabId) options.tabId = args.tabId;
1204
- if (args.viewportWidth !== null) options.viewportWidth = args.viewportWidth;
1205
- 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
+ });
1206
1790
  if (args.storageState) options.storageStatePath = args.storageState;
1207
1791
  return options;
1208
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
+ }
1209
1884
  function die(msg) {
1210
1885
  process.stderr.write(`${msg}
1211
1886
  `);
@@ -1216,13 +1891,13 @@ function log(quiet, msg) {
1216
1891
  `);
1217
1892
  }
1218
1893
  function readStdin() {
1219
- return new Promise((resolve, reject) => {
1894
+ return new Promise((resolve3, reject) => {
1220
1895
  let data = "";
1221
1896
  process.stdin.setEncoding("utf8");
1222
1897
  process.stdin.on("data", (chunk) => {
1223
1898
  data += chunk;
1224
1899
  });
1225
- process.stdin.on("end", () => resolve(data));
1900
+ process.stdin.on("end", () => resolve3(data));
1226
1901
  process.stdin.on("error", reject);
1227
1902
  });
1228
1903
  }
@@ -1265,6 +1940,20 @@ ${USAGE}`);
1265
1940
  process.exit(0);
1266
1941
  }
1267
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
+ }
1268
1957
  const { launchArgs, lnaAutoAppended } = buildLaunchArgs(args);
1269
1958
  if (lnaAutoAppended) {
1270
1959
  log(
@@ -1272,7 +1961,10 @@ ${USAGE}`);
1272
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)})`
1273
1962
  );
1274
1963
  }
1275
- const transport = createTransport({ kind: "injected", options: buildTransportOptions(args) });
1964
+ const transport = createTransport({
1965
+ kind: "injected",
1966
+ options: buildTransportOptions({ ...args, authToken: resolvedAuthToken })
1967
+ });
1276
1968
  transport.register("__inject_cli_info", (_p, ctx) => {
1277
1969
  const c = ctx;
1278
1970
  return { tabId: c.tabId ?? null, uiBridgeRegistered: c.uiBridgeRegistered ?? false };
@@ -1283,15 +1975,89 @@ ${USAGE}`);
1283
1975
  }
1284
1976
  await runRelay(args, transport);
1285
1977
  }
1286
- async function runExec(args, transport) {
1978
+ async function collectActions(args) {
1287
1979
  const actions = [...args.execActions];
1288
1980
  if (args.execStdin) {
1289
1981
  const raw = await readStdin();
1290
1982
  actions.push(...parseStdinActions(raw));
1291
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);
1292
2049
  if (actions.length === 0) {
1293
2050
  die("Variant A (exec) selected but no actions were provided");
1294
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);
1295
2061
  log(args.quiet, `[ui-bridge-inject] launching injected transport (exec mode)`);
1296
2062
  try {
1297
2063
  await transport.ready();
@@ -1303,40 +2069,195 @@ async function runExec(args, transport) {
1303
2069
  });
1304
2070
  process.exit(1);
1305
2071
  }
1306
- let anyError = false;
2072
+ const screenshot = args.screenshot;
2073
+ let anyError;
1307
2074
  try {
1308
- for (const { action, payload } of actions) {
1309
- if (!transport.handlerRegistry.has(action)) {
1310
- transport.register(
1311
- action,
1312
- (params, ctx) => ctx.execute(action, params)
1313
- );
1314
- }
1315
- try {
1316
- const result = await transport.dispatch(action, payload);
1317
- process.stdout.write(`${JSON.stringify({ action, result })}
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)}
1318
2134
  `);
1319
- } catch (err) {
1320
- anyError = true;
1321
- if (err instanceof WrapperTransportError) {
1322
- process.stdout.write(
1323
- `${JSON.stringify({ action, error: { code: err.code, message: err.message } })}
1324
- `
1325
- );
1326
- } else {
1327
- const message = err instanceof Error ? err.message : String(err);
1328
- process.stdout.write(
1329
- `${JSON.stringify({ action, error: { code: "UNKNOWN", message } })}
1330
- `
1331
- );
1332
- }
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
+ });
1333
2141
  }
1334
- }
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
+ };
1335
2163
  } finally {
1336
2164
  await transport.close().catch(() => {
1337
2165
  });
1338
2166
  }
1339
- 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);
1340
2261
  }
1341
2262
  async function runRelay(args, transport) {
1342
2263
  log(
@@ -1386,13 +2307,7 @@ async function runRelay(args, transport) {
1386
2307
  void shutdown("SIGTERM", 143);
1387
2308
  });
1388
2309
  }
1389
- var isMain = (() => {
1390
- try {
1391
- return process.argv[1] === url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('inject-cli.cjs', document.baseURI).href)));
1392
- } catch {
1393
- return false;
1394
- }
1395
- })();
2310
+ var isMain = typeof __require !== "undefined" && typeof module !== "undefined" && __require.main === module;
1396
2311
  if (isMain) {
1397
2312
  void main().catch((err) => {
1398
2313
  const msg = err instanceof Error ? err.message : String(err);
@@ -1402,14 +2317,36 @@ if (isMain) {
1402
2317
  });
1403
2318
  }
1404
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;
1405
2323
  exports.InjectCliArgError = InjectCliArgError;
1406
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;
1407
2329
  exports.USAGE = USAGE;
2330
+ exports.WAIT_SELECTOR_STATES = WAIT_SELECTOR_STATES;
2331
+ exports.assertEmptyMatrixDir = assertEmptyMatrixDir;
2332
+ exports.buildCellTransportOptions = buildCellTransportOptions;
1408
2333
  exports.buildLaunchArgs = buildLaunchArgs;
1409
2334
  exports.buildTransportOptions = buildTransportOptions;
2335
+ exports.captureMatrix = captureMatrix;
2336
+ exports.executeActions = executeActions;
1410
2337
  exports.isLoopbackHost = isLoopbackHost;
1411
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;
1412
2347
  exports.selectMode = selectMode;
1413
2348
  exports.validateArgs = validateArgs;
2349
+ exports.validateFramePlan = validateFramePlan;
2350
+ exports.validateWaitActions = validateWaitActions;
1414
2351
  //# sourceMappingURL=inject-cli.cjs.map
1415
2352
  //# sourceMappingURL=inject-cli.cjs.map