@qontinui/ui-bridge-wrapper 0.4.2 → 0.5.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.
@@ -21,7 +21,7 @@
21
21
  * pure functions so they can be unit-tested without spawning a browser or
22
22
  * calling `main()`.
23
23
  */
24
- export declare const USAGE = "ui-bridge-inject \u2014 drive UI Bridge's injected transport against a UI-Bridge-free page\n\nRequired:\n --url <pageUrl> Page to open. Must start with http:// or https://\n (maps to the transport's options.targetUrl)\n\nRelay (Variant B \u2014 the default mode; --relay is REQUIRED in this mode):\n --relay <uiBridgeBase> UI Bridge relay base; the injected runtime registers\n as a relay tab. Example: http://localhost:3001/api/ui-bridge\n --auth-token <T> Bearer token for an auth-gated relay\n --registration-metadata <json>\n JSON {\"userId\":\"...\",\"sessionId\":\"...\"} for per-user\n tab-scoping on relay heartbeats\n --app-id <id> App id reported to the relay registry\n --app-name <name> Display name reported to the relay registry\n --tab-id <id> Stable per-tab id override\n\nExec (Variant A \u2014 one-shot; presence of any --exec/--exec-stdin selects this mode):\n --exec '<action> <json>' Run one action (repeatable). The value is an action\n id, a space, then a JSON payload (payload optional \u2192\n defaults {}). Example: --exec 'find {\"text\":\"Sign in\"}'\n --exec-stdin Read NDJSON lines from stdin; each line is\n {\"action\":\"...\",\"payload\":{...}}\n\nOptional:\n --headed Launch with a visible window (default: headless)\n --ready-timeout <ms> Max wait for the injected runtime ready/settle gate (default 30000)\n --no-settle Gate ready on the runtime being live only, NOT on the DOM\n settling. By default the launcher waits for the page to paint\n + go quiet (so a client-rendered SPA is drivable immediately),\n which is almost always what you want.\n --settle-quiet <ms> Quiet window with no DOM re-seed before settled (default 500)\n --settle-timeout <ms> Hard cap before settling regardless of mutations (default 10000)\n --expect-selector <css> Don't settle until an element matching this CSS selector\n exists \u2014 use when the target control (e.g. a login form)\n mounts lazily after unrelated chrome. If it never appears\n before --settle-timeout, ready() fails with a BLOCKED error\n instead of returning a control-less page.\n --viewport <WxH> Viewport size, e.g. 1280x720\n --quiet Suppress human-readable logs (JSON results still print)\n --help, -h Print this help and exit\n\nExamples:\n # Variant B: register an injected tab against a relay and stay alive\n ui-bridge-inject --url https://example.com/login \\\n --relay http://localhost:3001/api/ui-bridge --app-name \"example login\"\n\n # Variant A: snapshot the controls on a page, then exit\n ui-bridge-inject --url https://example.com/login \\\n --exec 'getControlSnapshot {}'\n\n # Variant A: find a control and act on it\n ui-bridge-inject --url https://example.com/login \\\n --exec 'find {\"text\":\"Sign in\"}'\n";
24
+ export declare const USAGE = "ui-bridge-inject \u2014 drive UI Bridge's injected transport against a UI-Bridge-free page\n\nRequired:\n --url <pageUrl> Page to open. Must start with http:// or https://\n (maps to the transport's options.targetUrl)\n\nRelay (Variant B \u2014 the default mode; --relay is REQUIRED in this mode):\n --relay <uiBridgeBase> UI Bridge relay base; the injected runtime registers\n as a relay tab. Example: http://localhost:3001/api/ui-bridge\n --auth-token <T> Bearer token for an auth-gated relay\n --registration-metadata <json>\n JSON {\"userId\":\"...\",\"sessionId\":\"...\"} for per-user\n tab-scoping on relay heartbeats\n --app-id <id> App id reported to the relay registry\n --app-name <name> Display name reported to the relay registry\n --tab-id <id> Stable per-tab id override\n\nExec (Variant A \u2014 one-shot; presence of any --exec/--exec-stdin selects this mode):\n --exec '<action> <json>' Run one action (repeatable). The value is an action\n id, a space, then a JSON payload (payload optional \u2192\n defaults {}). Example: --exec 'find {\"text\":\"Sign in\"}'\n --exec-stdin Read NDJSON lines from stdin; each line is\n {\"action\":\"...\",\"payload\":{...}}\n\nOptional:\n --storage-state <path> Seed the browser context from a Playwright storageState\n JSON file (cookies + localStorage) produced by\n 'ui-bridge-login-web --storage-state-out <path>'. This\n carries a saved authenticated session past a login wall,\n so you can drive a login-walled page (e.g. an /admin\n wizard) WITHOUT re-driving the hosted-UI login each run.\n --headed Launch with a visible window (default: headless)\n --ready-timeout <ms> Max wait for the injected runtime ready/settle gate (default 30000)\n --no-settle Gate ready on the runtime being live only, NOT on the DOM\n settling. By default the launcher waits for the page to paint\n + go quiet (so a client-rendered SPA is drivable immediately),\n which is almost always what you want.\n --settle-quiet <ms> Quiet window with no DOM re-seed before settled (default 500)\n --settle-timeout <ms> Hard cap before settling regardless of mutations (default 10000)\n --expect-selector <css> Don't settle until an element matching this CSS selector\n exists \u2014 use when the target control (e.g. a login form)\n mounts lazily after unrelated chrome. If it never appears\n before --settle-timeout, ready() fails with a BLOCKED error\n instead of returning a control-less page.\n --viewport <WxH> Viewport size, e.g. 1280x720\n --launch-arg <arg> Extra Chromium command-line argument (repeatable),\n passed through to chromium.launch({ args }).\n NOTE: when --url is https and --relay resolves to a\n loopback host, the LNA-disable flags\n (--disable-features=LocalNetworkAccessChecks,...) are\n auto-appended \u2014 Chromium otherwise blocks the\n https-page \u2192 loopback-relay fetch (Local Network Access).\n --quiet Suppress human-readable logs (JSON results still print)\n --help, -h Print this help and exit\n\nExamples:\n # Variant B: register an injected tab against a relay and stay alive\n ui-bridge-inject --url https://example.com/login \\\n --relay http://localhost:3001/api/ui-bridge --app-name \"example login\"\n\n # Variant A: snapshot the controls on a page, then exit\n ui-bridge-inject --url https://example.com/login \\\n --exec 'getControlSnapshot {}'\n\n # Variant A: find a control and act on it\n ui-bridge-inject --url https://example.com/login \\\n --exec 'find {\"text\":\"Sign in\"}'\n\n # Reuse a saved login: drive a login-walled page with a captured auth artifact\n ui-bridge-login-web --url \"https://qontinui.io/login?next=%2Fadmin\" \\\n --success /admin --storage-state-out auth.json\n ui-bridge-inject --url https://qontinui.io/admin \\\n --storage-state auth.json --exec 'getControlSnapshot {}'\n";
25
25
  /** A single Variant-A action to execute. */
26
26
  export interface ExecAction {
27
27
  action: string;
@@ -48,6 +48,10 @@ export interface InjectCliArgs {
48
48
  tabId: string | null;
49
49
  viewportWidth: number | null;
50
50
  viewportHeight: number | null;
51
+ /** Path to a Playwright storageState JSON file to seed the context (from --storage-state). */
52
+ storageState: string | null;
53
+ /** Extra Chromium launch args collected from --launch-arg flags (in order). */
54
+ launchArgs: string[];
51
55
  /** Variant-A actions collected from --exec flags (in order). */
52
56
  execActions: ExecAction[];
53
57
  /** True if --exec-stdin was given (read NDJSON from stdin in Variant A). */
@@ -77,6 +81,30 @@ export declare function validateArgs(args: InjectCliArgs): void;
77
81
  * otherwise relay registration (Variant B, the default).
78
82
  */
79
83
  export declare function selectMode(args: InjectCliArgs): 'exec' | 'relay';
84
+ /**
85
+ * Chromium feature flags that must be DISABLED for an https page to fetch a
86
+ * loopback (local-network) relay. Chromium's Local Network Access checks
87
+ * otherwise block `https://example.com` → `http://127.0.0.1:<port>` with
88
+ * "Permission was denied for this request to access the 'loopback' address
89
+ * space" (plan 2026-06-12 item 2).
90
+ */
91
+ export declare const LNA_DISABLE_FEATURES: readonly ["LocalNetworkAccessChecks", "PrivateNetworkAccessSendPreflights", "PrivateNetworkAccessRespectPreflightResults"];
92
+ /** True when a URL hostname is a loopback address (localhost / 127/8 / ::1). */
93
+ export declare function isLoopbackHost(hostname: string): boolean;
94
+ /**
95
+ * Compute the effective Chromium launch args: the user's `--launch-arg`
96
+ * values, plus the LNA-disable features auto-appended when the target page
97
+ * is https AND the relay resolves to a loopback host (the combination
98
+ * Chromium's Local Network Access checks block). If the user already passed
99
+ * a `--disable-features=` arg, the missing LNA features are merged into it
100
+ * (Chromium does not union repeated `--disable-features` flags).
101
+ *
102
+ * Pure — exported for unit tests.
103
+ */
104
+ export declare function buildLaunchArgs(args: Pick<InjectCliArgs, 'url' | 'relay' | 'launchArgs'>): {
105
+ launchArgs: string[];
106
+ lnaAutoAppended: boolean;
107
+ };
80
108
  /**
81
109
  * Build the `options` object for `createTransport({ kind: 'injected', options })`.
82
110
  * Only includes keys the user provided; `targetUrl` is always present.
@@ -1 +1 @@
1
- {"version":3,"file":"inject-cli.d.ts","sourceRoot":"","sources":["../src/inject-cli.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAOH,eAAO,MAAM,KAAK,4zGAsDjB,CA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C5B,+EAA+E;IAC/E,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,gEAAgE;IAChE,WAAW,EAAE,UAAU,EAAE,CAAC;IAC1B,4EAA4E;IAC5E,SAAS,EAAE,OAAO,CAAC;IACnB,KAAK,EAAE,OAAO,CAAC;IACf,IAAI,EAAE,OAAO,CAAC;CACf;AAED;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;gBAC9B,OAAO,EAAE,MAAM;CAI5B;AA2BD;;;GAGG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,aAAa,CA8LvD;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,aAAa,GAAG,IAAI,CActD;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,aAAa,GAAG,MAAM,GAAG,OAAO,CAEhE;AAED;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,4HAIvB,CAAC;AAEX,gFAAgF;AAChF,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CASxD;AAED;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,IAAI,CAAC,aAAa,EAAE,KAAK,GAAG,OAAO,GAAG,YAAY,CAAC,GACxD;IAAE,UAAU,EAAE,MAAM,EAAE,CAAC;IAAC,eAAe,EAAE,OAAO,CAAA;CAAE,CA8BpD;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAoBlF"}
@@ -2,8 +2,8 @@
2
2
  'use strict';
3
3
 
4
4
  var url = require('url');
5
- var module$1 = require('module');
6
5
  var fs = require('fs');
6
+ var module$1 = require('module');
7
7
 
8
8
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
9
9
  // src/types.ts
@@ -224,13 +224,17 @@ var HeadlessTransport = class extends BaseTransport {
224
224
  uiBridgeBase: typeof raw["uiBridgeBase"] === "string" ? raw["uiBridgeBase"] : void 0,
225
225
  waitForUiBridgeMs: typeof raw["waitForUiBridgeMs"] === "number" ? raw["waitForUiBridgeMs"] : void 0,
226
226
  userAgent: typeof raw["userAgent"] === "string" ? raw["userAgent"] : void 0,
227
- forwardConsole: typeof raw["forwardConsole"] === "boolean" ? raw["forwardConsole"] : void 0
227
+ forwardConsole: typeof raw["forwardConsole"] === "boolean" ? raw["forwardConsole"] : void 0,
228
+ launchArgs: Array.isArray(raw["launchArgs"]) && raw["launchArgs"].every((a) => typeof a === "string") ? raw["launchArgs"] : void 0,
229
+ storageStatePath: typeof raw["storageStatePath"] === "string" ? raw["storageStatePath"] : void 0
228
230
  };
229
231
  }
230
232
  async onReady() {
231
233
  let launchHeadlessTab;
234
+ const headlessSpecifier = "@qontinui/ui-bridge-headless";
232
235
  try {
233
- ({ launchHeadlessTab } = await import('@qontinui/ui-bridge-headless'));
236
+ const mod = await import(headlessSpecifier);
237
+ ({ launchHeadlessTab } = mod);
234
238
  } catch (err) {
235
239
  const cause = err instanceof Error ? err.message : String(err);
236
240
  const code = err?.code;
@@ -261,7 +265,9 @@ Underlying import error: ${cause}`
261
265
  viewportHeight: this.options.viewportHeight,
262
266
  userAgent: this.options.userAgent,
263
267
  forwardConsole: this.options.forwardConsole,
264
- initScripts: initScripts.length > 0 ? initScripts : void 0
268
+ initScripts: initScripts.length > 0 ? initScripts : void 0,
269
+ launchArgs: this.options.launchArgs && this.options.launchArgs.length > 0 ? this.options.launchArgs : void 0,
270
+ storageStatePath: this.options.storageStatePath
265
271
  });
266
272
  } catch (err) {
267
273
  const cause = err instanceof Error ? err.message : String(err);
@@ -720,6 +726,38 @@ function createTransport(config) {
720
726
  }
721
727
  }
722
728
 
729
+ // src/session-storage-capture.ts
730
+ function isCapturableOrigin(origin) {
731
+ return typeof origin === "string" && origin.length > 0 && origin !== "null";
732
+ }
733
+ function frameOrigin(frameUrl) {
734
+ try {
735
+ const origin = new URL(frameUrl).origin;
736
+ return isCapturableOrigin(origin) ? origin : null;
737
+ } catch {
738
+ return null;
739
+ }
740
+ }
741
+ function buildMultiOriginSessionStorageMap(frames) {
742
+ const out = {};
743
+ for (const frame of frames) {
744
+ if (frame.kv === null) continue;
745
+ const origin = frameOrigin(frame.url);
746
+ if (origin === null) continue;
747
+ out[origin] = { ...out[origin] ?? {}, ...frame.kv };
748
+ }
749
+ return out;
750
+ }
751
+ function mergeMultiOriginSessionStorageIntoArtifact(artifact, map) {
752
+ const existing = artifact.__sessionStorage && typeof artifact.__sessionStorage === "object" ? artifact.__sessionStorage : {};
753
+ const merged = { ...existing };
754
+ for (const origin of Object.keys(map)) {
755
+ merged[origin] = { ...map[origin] };
756
+ }
757
+ artifact.__sessionStorage = merged;
758
+ return artifact;
759
+ }
760
+
723
761
  // src/cli-args.ts
724
762
  var COMMON_FLAGS = /* @__PURE__ */ new Set(["--help", "-h", "--quiet"]);
725
763
  function isFlagShaped(value) {
@@ -936,6 +974,14 @@ Options:
936
974
  --screenshot <path> Write a full-page PNG of the authed landing to
937
975
  <path> (captured BEFORE the --expect-text check, so
938
976
  a failing assertion still leaves a diagnostic image).
977
+ --storage-state-out <path> On a confirmed-authed landing, write a Playwright
978
+ storageState JSON (cookies + localStorage) to <path>,
979
+ PLUS a custom __sessionStorage key (origin \u2192 kv) so
980
+ cold replays land authed on apps that keep their
981
+ token in sessionStorage (e.g. qontinui-web).
982
+ Feed it to 'ui-bridge-inject --storage-state <path>'
983
+ to drive a login-walled page MANY times without
984
+ re-driving the hosted-UI login each run.
939
985
  --keep-open On success, park the authed session until SIGINT/
940
986
  SIGTERM instead of closing the browser.
941
987
  --quiet Suppress human-readable stderr logs (the JSON
@@ -955,6 +1001,11 @@ Examples:
955
1001
  ui-bridge-login-web --url "https://qontinui.io/login?next=%2Foperations" \\
956
1002
  --success /operations --expect-text "option2-actions-outage-drill,metric_threshold" \\
957
1003
  --screenshot out.png
1004
+ # Capture a reusable auth artifact, then drive a login-walled page with it:
1005
+ ui-bridge-login-web --url "https://qontinui.io/login?next=%2Fadmin%2Fcoord%2Fonboarding" \\
1006
+ --success /admin/coord/onboarding --storage-state-out auth.json
1007
+ ui-bridge-inject --url https://qontinui.io/admin/coord/onboarding \\
1008
+ --storage-state auth.json --exec 'getControlSnapshot {}'
958
1009
  `;
959
1010
  var LoginCliArgError = class extends Error {
960
1011
  constructor(message) {
@@ -986,6 +1037,7 @@ function parseArgs(argv) {
986
1037
  expectText: (valueOf("--expect-text") ?? "").split(",").map((s) => s.trim()).filter((s) => s.length > 0),
987
1038
  scrollToText: valueOf("--scroll-to"),
988
1039
  screenshotPath: valueOf("--screenshot"),
1040
+ storageStateOut: valueOf("--storage-state-out"),
989
1041
  keepOpen: has("--keep-open"),
990
1042
  quiet: has("--quiet"),
991
1043
  help
@@ -1004,6 +1056,7 @@ var KNOWN_FLAGS = /* @__PURE__ */ new Set([
1004
1056
  "--expect-text",
1005
1057
  "--scroll-to",
1006
1058
  "--screenshot",
1059
+ "--storage-state-out",
1007
1060
  "--keep-open",
1008
1061
  ...COMMON_FLAGS
1009
1062
  ]);
@@ -1035,7 +1088,19 @@ ${USAGE}`);
1035
1088
  process.stdout.write(USAGE);
1036
1089
  process.exit(0);
1037
1090
  }
1038
- const { url, email, password, success, timeoutMs, headed, postClick, expectText, scrollToText, screenshotPath } = args;
1091
+ const {
1092
+ url,
1093
+ email,
1094
+ password,
1095
+ success,
1096
+ timeoutMs,
1097
+ headed,
1098
+ postClick,
1099
+ expectText,
1100
+ scrollToText,
1101
+ screenshotPath,
1102
+ storageStateOut
1103
+ } = args;
1039
1104
  const log = makeLogger("[login-web]", args.quiet);
1040
1105
  const transport = createTransport({
1041
1106
  kind: "injected",
@@ -1050,9 +1115,12 @@ ${USAGE}`);
1050
1115
  }
1051
1116
  const finalUrl = page.url();
1052
1117
  log(`final ${finalUrl}`);
1053
- await page.waitForFunction(() => window.__uiBridgeInjected?.ready === true, {
1054
- timeout: 15e3
1055
- }).catch(() => {
1118
+ await page.waitForFunction(
1119
+ () => window.__uiBridgeInjected?.ready === true,
1120
+ {
1121
+ timeout: 15e3
1122
+ }
1123
+ ).catch(() => {
1056
1124
  });
1057
1125
  let snap = null;
1058
1126
  try {
@@ -1077,6 +1145,9 @@ ${USAGE}`);
1077
1145
  await target.click();
1078
1146
  postLoginClicked = true;
1079
1147
  log(`post-login click: ${postClick}`);
1148
+ await target.waitFor({ state: "hidden", timeout: 2e3 }).catch(
1149
+ () => log(`post-login click target still visible after 2s (non-fatal): ${postClick}`)
1150
+ );
1080
1151
  } catch {
1081
1152
  log(`post-login click target never visible (non-fatal): ${postClick}`);
1082
1153
  }
@@ -1094,6 +1165,50 @@ ${USAGE}`);
1094
1165
  log(`screenshot failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`);
1095
1166
  }
1096
1167
  }
1168
+ let storageStateWritten = null;
1169
+ if (ok && storageStateOut) {
1170
+ try {
1171
+ await ctx.browserContext.storageState({ path: storageStateOut });
1172
+ storageStateWritten = storageStateOut;
1173
+ log(`storage-state written: ${storageStateOut}`);
1174
+ try {
1175
+ const frames = [];
1176
+ for (const frame of page.frames()) {
1177
+ let kv = null;
1178
+ try {
1179
+ kv = await frame.evaluate(() => {
1180
+ const o = {};
1181
+ for (let i = 0; i < sessionStorage.length; i++) {
1182
+ const k = sessionStorage.key(i);
1183
+ if (k !== null) o[k] = sessionStorage.getItem(k) ?? "";
1184
+ }
1185
+ return o;
1186
+ });
1187
+ } catch {
1188
+ kv = null;
1189
+ }
1190
+ frames.push({ url: frame.url(), kv });
1191
+ }
1192
+ const map = buildMultiOriginSessionStorageMap(frames);
1193
+ const artifact = JSON.parse(fs.readFileSync(storageStateOut, "utf8"));
1194
+ mergeMultiOriginSessionStorageIntoArtifact(artifact, map);
1195
+ fs.writeFileSync(storageStateOut, JSON.stringify(artifact));
1196
+ const origins = Object.keys(map);
1197
+ const keyCount = origins.reduce((n, o) => n + Object.keys(map[o]).length, 0);
1198
+ log(
1199
+ `sessionStorage captured across ${origins.length} origin(s) [${origins.join(", ")}]: ${keyCount} key(s) total`
1200
+ );
1201
+ } catch (err) {
1202
+ log(
1203
+ `sessionStorage capture failed (non-fatal, storageState still written): ${err instanceof Error ? err.message : String(err)}`
1204
+ );
1205
+ }
1206
+ } catch (err) {
1207
+ log(
1208
+ `storage-state export failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`
1209
+ );
1210
+ }
1211
+ }
1097
1212
  let expectFound;
1098
1213
  let expectMissing;
1099
1214
  if (ok && expectText.length > 0) {
@@ -1115,7 +1230,8 @@ ${USAGE}`);
1115
1230
  postLoginClicked,
1116
1231
  expectFound,
1117
1232
  expectMissing,
1118
- screenshotPath: screenshotPath ? screenshotWritten : void 0
1233
+ screenshotPath: screenshotPath ? screenshotWritten : void 0,
1234
+ storageStatePath: storageStateOut ? storageStateWritten : void 0
1119
1235
  };
1120
1236
  });
1121
1237
  let result;