@qontinui/ui-bridge-wrapper 0.2.0 → 0.4.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.
@@ -0,0 +1,1156 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var url = require('url');
5
+ var module$1 = require('module');
6
+ var fs = require('fs');
7
+
8
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
9
+ // src/types.ts
10
+ var WrapperTransportError = class extends Error {
11
+ code;
12
+ retryable;
13
+ cause;
14
+ constructor(code, message, options = {}) {
15
+ super(message);
16
+ this.name = "WrapperTransportError";
17
+ this.code = code;
18
+ this.retryable = options.retryable ?? false;
19
+ if (options.cause !== void 0) {
20
+ this.cause = options.cause;
21
+ }
22
+ }
23
+ };
24
+
25
+ // src/handler-registry.ts
26
+ var HandlerRegistry = class {
27
+ handlers = /* @__PURE__ */ new Map();
28
+ /**
29
+ * Register (or replace) a handler for `actionId`. Replacement is explicit
30
+ * rather than throwing because live reloading / hot module scenarios need
31
+ * to update handlers without tearing the whole transport down.
32
+ */
33
+ register(actionId, fn) {
34
+ this.handlers.set(actionId, fn);
35
+ }
36
+ /** Remove a handler. Returns `true` if a handler was removed. */
37
+ unregister(actionId) {
38
+ return this.handlers.delete(actionId);
39
+ }
40
+ /** All registered action ids. Stable iteration order (insertion order). */
41
+ list() {
42
+ return Array.from(this.handlers.keys());
43
+ }
44
+ /** Check whether a handler is registered for `actionId`. */
45
+ has(actionId) {
46
+ return this.handlers.has(actionId);
47
+ }
48
+ /**
49
+ * Invoke the handler registered under `actionId`.
50
+ *
51
+ * Throws `WrapperTransportError("NO_HANDLER")` if no handler is registered.
52
+ * Propagates handler errors wrapped as `WrapperTransportError("HANDLER_ERROR")`
53
+ * so callers can uniformly check `err.code`.
54
+ */
55
+ async dispatch(actionId, params, ctx) {
56
+ const handler = this.handlers.get(actionId);
57
+ if (!handler) {
58
+ throw new WrapperTransportError(
59
+ "NO_HANDLER",
60
+ `No handler registered for action '${actionId}'`
61
+ );
62
+ }
63
+ try {
64
+ const result = await handler(params, ctx);
65
+ return result;
66
+ } catch (err) {
67
+ if (err instanceof WrapperTransportError) throw err;
68
+ const message = err instanceof Error ? err.message : String(err);
69
+ throw new WrapperTransportError("HANDLER_ERROR", message, { cause: err });
70
+ }
71
+ }
72
+ };
73
+
74
+ // src/base-transport.ts
75
+ var BaseTransport = class {
76
+ _status = "idle";
77
+ listeners = /* @__PURE__ */ new Set();
78
+ registry;
79
+ readyPromise = null;
80
+ constructor(registry) {
81
+ this.registry = registry ?? new HandlerRegistry();
82
+ }
83
+ get status() {
84
+ return this._status;
85
+ }
86
+ /** Expose the underlying registry so wrappers can register handlers. */
87
+ get handlerRegistry() {
88
+ return this.registry;
89
+ }
90
+ /** Convenience: register a handler on the transport's registry. */
91
+ register(actionId, fn) {
92
+ this.registry.register(actionId, fn);
93
+ }
94
+ /**
95
+ * Idempotent async setup. First call runs `onReady()`; subsequent calls
96
+ * share the same promise until it settles, after which further calls
97
+ * are no-ops if `status === 'ready'`, or re-run setup if it errored.
98
+ */
99
+ async ready() {
100
+ if (this._status === "ready") return;
101
+ if (this._status === "closed") {
102
+ throw new WrapperTransportError("TRANSPORT_CLOSED", `Transport '${this.kind}' is closed`);
103
+ }
104
+ if (this.readyPromise) return this.readyPromise;
105
+ this.setStatus("connecting");
106
+ this.readyPromise = this.onReady().then(() => {
107
+ this.setStatus("ready");
108
+ }).catch((err) => {
109
+ this.setStatus("error");
110
+ this.readyPromise = null;
111
+ throw err;
112
+ });
113
+ return this.readyPromise;
114
+ }
115
+ /** Default dispatch — waits for ready, builds ctx, delegates to registry. */
116
+ async dispatch(actionId, params) {
117
+ await this.ready();
118
+ const ctx = await this.buildContext(actionId, params);
119
+ return this.registry.dispatch(actionId, params, ctx);
120
+ }
121
+ async close() {
122
+ if (this._status === "closed") return;
123
+ try {
124
+ await this.onClose();
125
+ } finally {
126
+ this.setStatus("closed");
127
+ this.listeners.clear();
128
+ this.readyPromise = null;
129
+ }
130
+ }
131
+ onStatusChange(listener) {
132
+ this.listeners.add(listener);
133
+ return () => {
134
+ this.listeners.delete(listener);
135
+ };
136
+ }
137
+ /** Update status and notify listeners. Safe to call from subclasses. */
138
+ setStatus(next) {
139
+ if (this._status === next) return;
140
+ this._status = next;
141
+ for (const l of this.listeners) {
142
+ try {
143
+ l(next);
144
+ } catch {
145
+ }
146
+ }
147
+ }
148
+ /**
149
+ * Subclass hook: build the context object passed to handlers. Default is
150
+ * `undefined` (api transport). Headless/headed override to provide the
151
+ * Playwright `page`; live overrides to provide a response helper.
152
+ */
153
+ async buildContext(_actionId, _params) {
154
+ return void 0;
155
+ }
156
+ };
157
+
158
+ // src/transports/api.ts
159
+ var ApiTransport = class extends BaseTransport {
160
+ kind = "api";
161
+ fallback;
162
+ constructor(config = { kind: "api" }, registry) {
163
+ super(registry);
164
+ const handler = config.options?.handler;
165
+ if (typeof handler === "function") {
166
+ this.fallback = handler;
167
+ }
168
+ }
169
+ async onReady() {
170
+ }
171
+ async onClose() {
172
+ }
173
+ async buildContext() {
174
+ return { kind: "api" };
175
+ }
176
+ /**
177
+ * Override dispatch to fall back to `options.handler` when no explicit
178
+ * registration exists for `actionId`.
179
+ */
180
+ async dispatch(actionId, params) {
181
+ await this.ready();
182
+ if (this.registry.has(actionId)) {
183
+ const ctx = await this.buildContext();
184
+ return this.registry.dispatch(actionId, params, ctx);
185
+ }
186
+ if (this.fallback) {
187
+ try {
188
+ return await this.fallback(actionId, params);
189
+ } catch (err) {
190
+ if (err instanceof WrapperTransportError) throw err;
191
+ const message = err instanceof Error ? err.message : String(err);
192
+ throw new WrapperTransportError("HANDLER_ERROR", message, { cause: err });
193
+ }
194
+ }
195
+ throw new WrapperTransportError("NO_HANDLER", `No handler registered for action '${actionId}'`);
196
+ }
197
+ };
198
+
199
+ // src/transports/headless.ts
200
+ var HeadlessTransport = class extends BaseTransport {
201
+ kind;
202
+ options;
203
+ headless;
204
+ tab = null;
205
+ constructor(config, registry, overrides = {}) {
206
+ super(registry);
207
+ this.kind = overrides.kind ?? "headless";
208
+ this.headless = overrides.headless ?? true;
209
+ this.options = this.parseOptions(config);
210
+ }
211
+ parseOptions(config) {
212
+ const raw = config.options ?? {};
213
+ const targetUrl = raw["targetUrl"];
214
+ if (typeof targetUrl !== "string" || targetUrl.length === 0) {
215
+ throw new WrapperTransportError(
216
+ "INVALID_CONFIG",
217
+ `Transport kind '${this.kind}' requires options.targetUrl (string)`
218
+ );
219
+ }
220
+ return {
221
+ targetUrl,
222
+ viewportWidth: typeof raw["viewportWidth"] === "number" ? raw["viewportWidth"] : void 0,
223
+ viewportHeight: typeof raw["viewportHeight"] === "number" ? raw["viewportHeight"] : void 0,
224
+ uiBridgeBase: typeof raw["uiBridgeBase"] === "string" ? raw["uiBridgeBase"] : void 0,
225
+ waitForUiBridgeMs: typeof raw["waitForUiBridgeMs"] === "number" ? raw["waitForUiBridgeMs"] : void 0,
226
+ userAgent: typeof raw["userAgent"] === "string" ? raw["userAgent"] : void 0,
227
+ forwardConsole: typeof raw["forwardConsole"] === "boolean" ? raw["forwardConsole"] : void 0
228
+ };
229
+ }
230
+ async onReady() {
231
+ const { launchHeadlessTab } = await import('@qontinui/ui-bridge-headless');
232
+ const initScripts = await this.buildInitScripts();
233
+ const tab = await launchHeadlessTab({
234
+ url: this.options.targetUrl,
235
+ headless: this.headless,
236
+ uiBridgeBase: this.options.uiBridgeBase,
237
+ waitForUiBridgeMs: this.options.waitForUiBridgeMs,
238
+ viewportWidth: this.options.viewportWidth,
239
+ viewportHeight: this.options.viewportHeight,
240
+ userAgent: this.options.userAgent,
241
+ forwardConsole: this.options.forwardConsole,
242
+ initScripts: initScripts.length > 0 ? initScripts : void 0
243
+ });
244
+ this.tab = {
245
+ browser: tab.browser,
246
+ context: tab.context,
247
+ page: tab.page,
248
+ uiBridgeRegistered: tab.uiBridgeRegistered,
249
+ tabId: tab.tabId,
250
+ close: tab.close
251
+ };
252
+ await this.afterLaunch(tab.page);
253
+ }
254
+ /**
255
+ * Subclass hook: init-scripts to register on the browser context before the
256
+ * first navigation (via `context.addInitScript`). Default: none. Injected
257
+ * mode overrides this to inject the config + runtime bundle pre-paint.
258
+ */
259
+ async buildInitScripts() {
260
+ return [];
261
+ }
262
+ /**
263
+ * Subclass hook: run after launch + navigation, before `ready()` resolves.
264
+ * Default: no-op. Injected mode overrides it to await the in-page runtime.
265
+ */
266
+ async afterLaunch(_page) {
267
+ }
268
+ async onClose() {
269
+ if (!this.tab) return;
270
+ const t = this.tab;
271
+ this.tab = null;
272
+ await t.close();
273
+ }
274
+ async buildContext() {
275
+ if (!this.tab) {
276
+ throw new WrapperTransportError(
277
+ "NOT_READY",
278
+ `Transport '${this.kind}' is not ready; call ready() before dispatch`
279
+ );
280
+ }
281
+ return {
282
+ kind: this.kind,
283
+ page: this.tab.page,
284
+ browserContext: this.tab.context,
285
+ browser: this.tab.browser,
286
+ uiBridgeRegistered: this.tab.uiBridgeRegistered,
287
+ tabId: this.tab.tabId
288
+ };
289
+ }
290
+ };
291
+
292
+ // src/transports/headed.ts
293
+ var HeadedTransport = class extends HeadlessTransport {
294
+ constructor(config, registry) {
295
+ super(config, registry, { kind: "headed", headless: false });
296
+ }
297
+ };
298
+ var require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('inject-cli.cjs', document.baseURI).href)));
299
+ var cachedBundle = null;
300
+ function loadInjectedBundle() {
301
+ if (cachedBundle !== null) return cachedBundle;
302
+ let bundlePath;
303
+ try {
304
+ bundlePath = require2.resolve("@qontinui/ui-bridge/injected/bundle.global.js");
305
+ } catch {
306
+ const pkgJson = require2.resolve("@qontinui/ui-bridge/package.json");
307
+ bundlePath = pkgJson.replace(/package\.json$/, "dist/injected/bundle.global.js");
308
+ }
309
+ try {
310
+ cachedBundle = fs.readFileSync(bundlePath, "utf8");
311
+ } catch (cause) {
312
+ throw new WrapperTransportError(
313
+ "INJECTED_BUNDLE_MISSING",
314
+ `Could not read the UI Bridge injected runtime bundle at '${bundlePath}'. Ensure @qontinui/ui-bridge is built (the IIFE is emitted by its tsup build).`,
315
+ { cause }
316
+ );
317
+ }
318
+ return cachedBundle;
319
+ }
320
+ var InjectedTransport = class extends HeadlessTransport {
321
+ injected;
322
+ constructor(config, registry) {
323
+ const raw = config.options ?? {};
324
+ const headed = raw["headed"] === true;
325
+ super(config, registry, { kind: "injected", headless: !headed });
326
+ this.injected = {
327
+ headed,
328
+ readyTimeoutMs: typeof raw["readyTimeoutMs"] === "number" ? raw["readyTimeoutMs"] : 3e4,
329
+ waitForSettle: raw["waitForSettle"] !== false,
330
+ settleQuietMs: typeof raw["settleQuietMs"] === "number" ? raw["settleQuietMs"] : void 0,
331
+ settleTimeoutMs: typeof raw["settleTimeoutMs"] === "number" ? raw["settleTimeoutMs"] : void 0,
332
+ expectSelector: typeof raw["expectSelector"] === "string" && raw["expectSelector"].length > 0 ? raw["expectSelector"] : void 0,
333
+ authToken: typeof raw["authToken"] === "string" ? raw["authToken"] : void 0,
334
+ registrationMetadata: isRegistrationMetadata(raw["registrationMetadata"]) ? raw["registrationMetadata"] : void 0,
335
+ appId: typeof raw["appId"] === "string" ? raw["appId"] : void 0,
336
+ appName: typeof raw["appName"] === "string" ? raw["appName"] : void 0,
337
+ tabId: typeof raw["tabId"] === "string" ? raw["tabId"] : void 0
338
+ };
339
+ }
340
+ /**
341
+ * Build the `__uiBridgeInjectedConfig` injected ahead of the bundle, or null
342
+ * if there's nothing to configure. Carries the relay fields (Variant B only,
343
+ * when `uiBridgeBase` is set) AND the settle-tuning fields (both variants).
344
+ */
345
+ injectedConfig() {
346
+ const cfg = {};
347
+ const base = this.options.uiBridgeBase;
348
+ if (base) {
349
+ cfg.uiBridgeBase = base;
350
+ if (this.injected.authToken) cfg.authToken = this.injected.authToken;
351
+ if (this.injected.registrationMetadata)
352
+ cfg.registrationMetadata = this.injected.registrationMetadata;
353
+ if (this.injected.appId) cfg.appId = this.injected.appId;
354
+ if (this.injected.appName) cfg.appName = this.injected.appName;
355
+ if (this.injected.tabId) cfg.tabId = this.injected.tabId;
356
+ }
357
+ if (this.injected.settleQuietMs !== void 0)
358
+ cfg.settleQuietMs = this.injected.settleQuietMs;
359
+ if (this.injected.settleTimeoutMs !== void 0)
360
+ cfg.settleTimeoutMs = this.injected.settleTimeoutMs;
361
+ if (this.injected.expectSelector !== void 0)
362
+ cfg.expectSelector = this.injected.expectSelector;
363
+ return Object.keys(cfg).length > 0 ? cfg : null;
364
+ }
365
+ async buildInitScripts() {
366
+ const scripts = [];
367
+ const cfg = this.injectedConfig();
368
+ if (cfg) {
369
+ scripts.push(`window.__uiBridgeInjectedConfig = ${JSON.stringify(cfg)};`);
370
+ }
371
+ scripts.push(loadInjectedBundle());
372
+ return scripts;
373
+ }
374
+ async afterLaunch(page) {
375
+ try {
376
+ await page.waitForFunction(
377
+ () => window.__uiBridgeInjected?.ready === true,
378
+ void 0,
379
+ { timeout: this.injected.readyTimeoutMs }
380
+ );
381
+ } catch (cause) {
382
+ throw new WrapperTransportError(
383
+ "INJECTED_RUNTIME_NOT_READY",
384
+ `The injected UI Bridge runtime did not report ready within ${this.injected.readyTimeoutMs}ms. The bundle may have failed to evaluate (check page console / CSP) or the page never reached DOMContentLoaded.`,
385
+ { cause, retryable: true }
386
+ );
387
+ }
388
+ if (this.injected.waitForSettle) {
389
+ let state;
390
+ try {
391
+ await page.waitForFunction(
392
+ () => window.__uiBridgeInjected?.settled === true,
393
+ void 0,
394
+ { timeout: this.injected.readyTimeoutMs }
395
+ );
396
+ state = await page.evaluate(() => {
397
+ const api = window.__uiBridgeInjected;
398
+ return {
399
+ settled: api?.settled === true,
400
+ settledByTimeout: api?.settledByTimeout === true,
401
+ expectSatisfied: api?.expectSatisfied === true,
402
+ elementCount: api?.elementCount ?? 0
403
+ };
404
+ });
405
+ } catch (cause) {
406
+ throw new WrapperTransportError(
407
+ "INJECTED_RUNTIME_NOT_SETTLED",
408
+ `The injected UI Bridge runtime did not report settled within ${this.injected.readyTimeoutMs}ms. The page kept mutating past its settle cap, or the realm was torn down. Pass options.waitForSettle=false to gate on ready only, or raise options.settleTimeoutMs / readyTimeoutMs.`,
409
+ { cause, retryable: true }
410
+ );
411
+ }
412
+ if (state.settledByTimeout && !state.expectSatisfied) {
413
+ const sel = this.injected.expectSelector;
414
+ throw new WrapperTransportError(
415
+ "INJECTED_EXPECT_SELECTOR_UNMET",
416
+ sel ? `The injected runtime settled at its cap without the expected control (selector '${sel}') appearing \u2014 ${state.elementCount} element(s) were registered, but none matched. The control may mount slower than the settle cap (raise options.settleTimeoutMs), the selector may be wrong, or the inject failed. Treat as BLOCKED/UNVERIFIED, not a clean page.` : `The injected runtime settled at its cap with an empty registry (0 elements). The page never rendered interactive content within the settle cap, or the inject failed. Raise options.settleTimeoutMs for a slow page; otherwise treat as BLOCKED/UNVERIFIED.`,
417
+ { retryable: true }
418
+ );
419
+ }
420
+ }
421
+ }
422
+ async buildContext() {
423
+ if (!this.tab) {
424
+ throw new WrapperTransportError(
425
+ "NOT_READY",
426
+ `Transport 'injected' is not ready; call ready() before dispatch`
427
+ );
428
+ }
429
+ const { page, context: browserContext, browser, uiBridgeRegistered, tabId } = this.tab;
430
+ const execute = (action, payload) => page.evaluate(
431
+ (args) => window.__uiBridgeInjected.execute(args[0], args[1]),
432
+ [action, payload]
433
+ );
434
+ const settleState = () => page.evaluate(() => {
435
+ const api = window.__uiBridgeInjected;
436
+ return {
437
+ settled: api?.settled === true,
438
+ elementCount: api?.elementCount ?? 0,
439
+ settledByTimeout: api?.settledByTimeout === true,
440
+ expectSatisfied: api?.expectSatisfied === true
441
+ };
442
+ });
443
+ const whenSettled = (timeoutMs) => page.evaluate(
444
+ (ms) => {
445
+ const api = window.__uiBridgeInjected;
446
+ if (api?.whenSettled) return api.whenSettled(ms ?? void 0);
447
+ return Promise.resolve({
448
+ settled: api?.settled === true,
449
+ elementCount: api?.elementCount ?? 0,
450
+ settledByTimeout: api?.settledByTimeout === true,
451
+ expectSatisfied: api?.expectSatisfied === true
452
+ });
453
+ },
454
+ timeoutMs ?? null
455
+ );
456
+ return {
457
+ kind: "injected",
458
+ page,
459
+ browserContext,
460
+ browser,
461
+ uiBridgeRegistered,
462
+ ready: true,
463
+ tabId,
464
+ settleState,
465
+ whenSettled,
466
+ execute,
467
+ find: (criteria) => execute("find", criteria ?? {}),
468
+ act: (id, request) => execute("executeElementAction", { id, request }),
469
+ snapshot: (options) => execute("getControlSnapshot", options ?? {}),
470
+ assert: (spec) => execute("aiAssert", spec)
471
+ };
472
+ }
473
+ };
474
+ function isRegistrationMetadata(value) {
475
+ if (!value || typeof value !== "object") return false;
476
+ const v = value;
477
+ return typeof v.userId === "string" && typeof v.sessionId === "string";
478
+ }
479
+
480
+ // src/transports/live.ts
481
+ var LiveSessionTransport = class extends BaseTransport {
482
+ kind = "live";
483
+ url;
484
+ appId;
485
+ appName;
486
+ opts;
487
+ wsCtor;
488
+ ws = null;
489
+ ackResolvers = null;
490
+ constructor(config, registry, injected) {
491
+ super(registry);
492
+ if (!config.runnerUrl) {
493
+ throw new WrapperTransportError("INVALID_CONFIG", `Transport kind 'live' requires runnerUrl`);
494
+ }
495
+ this.url = config.runnerUrl;
496
+ this.appId = config.appId;
497
+ this.appName = config.appName;
498
+ this.opts = config.options ?? {};
499
+ const fromInjection = injected?.webSocketCtor;
500
+ const fromGlobal = typeof globalThis.WebSocket === "function" ? globalThis.WebSocket : void 0;
501
+ const resolved = fromInjection ?? fromGlobal;
502
+ if (!resolved) {
503
+ throw new WrapperTransportError(
504
+ "NO_WEBSOCKET",
505
+ `No WebSocket constructor available. Provide one via the second constructor arg or run in an environment with global WebSocket.`
506
+ );
507
+ }
508
+ this.wsCtor = resolved;
509
+ }
510
+ async onReady() {
511
+ const ws = new this.wsCtor(this.url);
512
+ this.ws = ws;
513
+ ws.addEventListener("message", (ev) => this.handleMessage(ev.data));
514
+ ws.addEventListener("close", () => this.handleClose());
515
+ ws.addEventListener("error", (ev) => this.handleError(ev));
516
+ await new Promise((resolve, reject) => {
517
+ const onOpen = () => {
518
+ try {
519
+ const frame = {
520
+ type: "register",
521
+ transport: "websocket",
522
+ appId: this.appId,
523
+ appName: this.appName,
524
+ appType: this.opts.appType ?? "wrapper"
525
+ };
526
+ if (this.opts.framework !== void 0) frame.framework = this.opts.framework;
527
+ if (this.opts.version !== void 0) frame.version = this.opts.version;
528
+ if (this.opts.capabilities !== void 0) frame.capabilities = this.opts.capabilities;
529
+ if (this.opts.origin !== void 0) frame.origin = this.opts.origin;
530
+ if (this.opts.pageUrl !== void 0) frame.pageUrl = this.opts.pageUrl;
531
+ ws.send(JSON.stringify(frame));
532
+ } catch (err) {
533
+ reject(err instanceof Error ? err : new Error(String(err)));
534
+ return;
535
+ }
536
+ const timeoutMs = this.opts.handshakeTimeoutMs ?? 1e4;
537
+ const timer = setTimeout(() => {
538
+ this.ackResolvers = null;
539
+ reject(
540
+ new WrapperTransportError(
541
+ "HANDSHAKE_TIMEOUT",
542
+ `Did not receive register ack within ${timeoutMs}ms`
543
+ )
544
+ );
545
+ }, timeoutMs);
546
+ this.ackResolvers = { resolve, reject, timer };
547
+ };
548
+ ws.addEventListener("open", onOpen);
549
+ });
550
+ }
551
+ async onClose() {
552
+ const ws = this.ws;
553
+ this.ws = null;
554
+ if (this.ackResolvers) {
555
+ clearTimeout(this.ackResolvers.timer);
556
+ this.ackResolvers.reject(
557
+ new WrapperTransportError("TRANSPORT_CLOSED", "Transport closed during handshake")
558
+ );
559
+ this.ackResolvers = null;
560
+ }
561
+ if (ws) {
562
+ try {
563
+ ws.close();
564
+ } catch {
565
+ }
566
+ }
567
+ }
568
+ async buildContext() {
569
+ return { kind: "live", commandId: null };
570
+ }
571
+ handleMessage(data) {
572
+ let frame;
573
+ try {
574
+ const text = typeof data === "string" ? data : String(data);
575
+ frame = JSON.parse(text);
576
+ } catch {
577
+ return;
578
+ }
579
+ switch (frame.type) {
580
+ case "ack":
581
+ case "registered": {
582
+ const f = frame;
583
+ if (!this.ackResolvers) return;
584
+ clearTimeout(this.ackResolvers.timer);
585
+ if (f.ok === false) {
586
+ const err = new WrapperTransportError(
587
+ f.error?.code ?? "REGISTER_FAILED",
588
+ f.error?.message ?? "Runner refused registration"
589
+ );
590
+ this.ackResolvers.reject(err);
591
+ } else {
592
+ this.ackResolvers.resolve();
593
+ }
594
+ this.ackResolvers = null;
595
+ return;
596
+ }
597
+ case "command": {
598
+ const f = frame;
599
+ void this.handleCommand(f);
600
+ return;
601
+ }
602
+ default:
603
+ return;
604
+ }
605
+ }
606
+ async handleCommand(frame) {
607
+ const ctx = { kind: "live", commandId: frame.commandId };
608
+ let response;
609
+ try {
610
+ const result = await this.registry.dispatch(frame.action, frame.payload, ctx);
611
+ response = {
612
+ type: "response",
613
+ commandId: frame.commandId,
614
+ success: true,
615
+ result
616
+ };
617
+ } catch (err) {
618
+ const code = err instanceof WrapperTransportError ? err.code : "HANDLER_ERROR";
619
+ const retryable = err instanceof WrapperTransportError ? err.retryable : false;
620
+ const message = err instanceof Error ? err.message : String(err);
621
+ response = {
622
+ type: "response",
623
+ commandId: frame.commandId,
624
+ success: false,
625
+ error: { code, message, retryable }
626
+ };
627
+ }
628
+ try {
629
+ this.ws?.send(JSON.stringify(response));
630
+ } catch {
631
+ }
632
+ }
633
+ handleClose() {
634
+ if (this._status === "closed") return;
635
+ this.setStatus("closed");
636
+ if (this.ackResolvers) {
637
+ clearTimeout(this.ackResolvers.timer);
638
+ this.ackResolvers.reject(
639
+ new WrapperTransportError("DISCONNECTED", "WebSocket closed before ack")
640
+ );
641
+ this.ackResolvers = null;
642
+ }
643
+ }
644
+ handleError(ev) {
645
+ if (this.ackResolvers) {
646
+ clearTimeout(this.ackResolvers.timer);
647
+ const message = this.extractErrorMessage(ev);
648
+ this.ackResolvers.reject(
649
+ new WrapperTransportError("WEBSOCKET_ERROR", message, { retryable: true })
650
+ );
651
+ this.ackResolvers = null;
652
+ } else {
653
+ this.setStatus("error");
654
+ }
655
+ }
656
+ extractErrorMessage(ev) {
657
+ if (ev && typeof ev === "object" && "message" in ev) {
658
+ const m = ev.message;
659
+ if (typeof m === "string") return m;
660
+ }
661
+ if (ev instanceof Error) return ev.message;
662
+ return "WebSocket error";
663
+ }
664
+ };
665
+
666
+ // src/create-transport.ts
667
+ function createTransport(config) {
668
+ switch (config.kind) {
669
+ case "api":
670
+ return new ApiTransport(config);
671
+ case "headless":
672
+ return new HeadlessTransport(config);
673
+ case "headed":
674
+ return new HeadedTransport(config);
675
+ case "injected":
676
+ return new InjectedTransport(config);
677
+ case "live": {
678
+ const opts = config.options ?? {};
679
+ const injected = typeof opts.webSocketCtor === "function" ? { webSocketCtor: opts.webSocketCtor } : void 0;
680
+ return new LiveSessionTransport(config, void 0, injected);
681
+ }
682
+ default: {
683
+ const kind = config.kind ?? "<missing>";
684
+ throw new WrapperTransportError("UNKNOWN_TRANSPORT", `Unknown transport kind '${kind}'`);
685
+ }
686
+ }
687
+ }
688
+
689
+ // src/inject-cli.ts
690
+ var USAGE = `ui-bridge-inject \u2014 drive UI Bridge's injected transport against a UI-Bridge-free page
691
+
692
+ Required:
693
+ --url <pageUrl> Page to open. Must start with http:// or https://
694
+ (maps to the transport's options.targetUrl)
695
+
696
+ Relay (Variant B \u2014 the default mode; --relay is REQUIRED in this mode):
697
+ --relay <uiBridgeBase> UI Bridge relay base; the injected runtime registers
698
+ as a relay tab. Example: http://localhost:3001/api/ui-bridge
699
+ --auth-token <T> Bearer token for an auth-gated relay
700
+ --registration-metadata <json>
701
+ JSON {"userId":"...","sessionId":"..."} for per-user
702
+ tab-scoping on relay heartbeats
703
+ --app-id <id> App id reported to the relay registry
704
+ --app-name <name> Display name reported to the relay registry
705
+ --tab-id <id> Stable per-tab id override
706
+
707
+ Exec (Variant A \u2014 one-shot; presence of any --exec/--exec-stdin selects this mode):
708
+ --exec '<action> <json>' Run one action (repeatable). The value is an action
709
+ id, a space, then a JSON payload (payload optional \u2192
710
+ defaults {}). Example: --exec 'find {"text":"Sign in"}'
711
+ --exec-stdin Read NDJSON lines from stdin; each line is
712
+ {"action":"...","payload":{...}}
713
+
714
+ Optional:
715
+ --headed Launch with a visible window (default: headless)
716
+ --ready-timeout <ms> Max wait for the injected runtime ready/settle gate (default 30000)
717
+ --no-settle Gate ready on the runtime being live only, NOT on the DOM
718
+ settling. By default the launcher waits for the page to paint
719
+ + go quiet (so a client-rendered SPA is drivable immediately),
720
+ which is almost always what you want.
721
+ --settle-quiet <ms> Quiet window with no DOM re-seed before settled (default 500)
722
+ --settle-timeout <ms> Hard cap before settling regardless of mutations (default 10000)
723
+ --expect-selector <css> Don't settle until an element matching this CSS selector
724
+ exists \u2014 use when the target control (e.g. a login form)
725
+ mounts lazily after unrelated chrome. If it never appears
726
+ before --settle-timeout, ready() fails with a BLOCKED error
727
+ instead of returning a control-less page.
728
+ --viewport <WxH> Viewport size, e.g. 1280x720
729
+ --quiet Suppress human-readable logs (JSON results still print)
730
+ --help, -h Print this help and exit
731
+
732
+ Examples:
733
+ # Variant B: register an injected tab against a relay and stay alive
734
+ ui-bridge-inject --url https://example.com/login \\
735
+ --relay http://localhost:3001/api/ui-bridge --app-name "example login"
736
+
737
+ # Variant A: snapshot the controls on a page, then exit
738
+ ui-bridge-inject --url https://example.com/login \\
739
+ --exec 'getControlSnapshot {}'
740
+
741
+ # Variant A: find a control and act on it
742
+ ui-bridge-inject --url https://example.com/login \\
743
+ --exec 'find {"text":"Sign in"}'
744
+ `;
745
+ var InjectCliArgError = class extends Error {
746
+ constructor(message) {
747
+ super(message);
748
+ this.name = "InjectCliArgError";
749
+ }
750
+ };
751
+ function parseExecValue(raw) {
752
+ const trimmed = raw.trim();
753
+ if (trimmed.length === 0) {
754
+ throw new InjectCliArgError(`--exec expects '<action> <json-payload>' (got empty value)`);
755
+ }
756
+ const spaceIdx = trimmed.indexOf(" ");
757
+ if (spaceIdx === -1) {
758
+ return { action: trimmed, payload: {} };
759
+ }
760
+ const action = trimmed.slice(0, spaceIdx);
761
+ const payloadRaw = trimmed.slice(spaceIdx + 1).trim();
762
+ if (payloadRaw.length === 0) return { action, payload: {} };
763
+ let payload;
764
+ try {
765
+ payload = JSON.parse(payloadRaw);
766
+ } catch (err) {
767
+ const msg = err instanceof Error ? err.message : String(err);
768
+ throw new InjectCliArgError(
769
+ `--exec payload for action '${action}' is not valid JSON: ${msg} (got ${payloadRaw})`
770
+ );
771
+ }
772
+ return { action, payload };
773
+ }
774
+ function parseArgs(argv) {
775
+ const args = {
776
+ url: "",
777
+ relay: null,
778
+ authToken: null,
779
+ registrationMetadata: null,
780
+ headed: false,
781
+ readyTimeoutMs: null,
782
+ waitForSettle: true,
783
+ settleQuietMs: null,
784
+ settleTimeoutMs: null,
785
+ expectSelector: null,
786
+ appId: null,
787
+ appName: null,
788
+ tabId: null,
789
+ viewportWidth: null,
790
+ viewportHeight: null,
791
+ execActions: [],
792
+ execStdin: false,
793
+ quiet: false,
794
+ help: false
795
+ };
796
+ for (let i = 0; i < argv.length; i++) {
797
+ const arg = argv[i];
798
+ switch (arg) {
799
+ case "--help":
800
+ case "-h":
801
+ args.help = true;
802
+ break;
803
+ case "--headed":
804
+ args.headed = true;
805
+ break;
806
+ case "--quiet":
807
+ args.quiet = true;
808
+ break;
809
+ case "--exec-stdin":
810
+ args.execStdin = true;
811
+ break;
812
+ case "--url":
813
+ args.url = argv[++i] ?? "";
814
+ break;
815
+ case "--relay":
816
+ args.relay = argv[++i] ?? null;
817
+ break;
818
+ case "--auth-token":
819
+ args.authToken = argv[++i] ?? null;
820
+ break;
821
+ case "--app-id":
822
+ args.appId = argv[++i] ?? null;
823
+ break;
824
+ case "--app-name":
825
+ args.appName = argv[++i] ?? null;
826
+ break;
827
+ case "--tab-id":
828
+ args.tabId = argv[++i] ?? null;
829
+ break;
830
+ case "--exec": {
831
+ const raw = argv[++i];
832
+ if (raw === void 0) {
833
+ throw new InjectCliArgError(`--exec expects '<action> <json-payload>' (got <missing>)`);
834
+ }
835
+ args.execActions.push(parseExecValue(raw));
836
+ break;
837
+ }
838
+ case "--registration-metadata": {
839
+ const raw = argv[++i];
840
+ if (raw === void 0) {
841
+ throw new InjectCliArgError(
842
+ `--registration-metadata expects JSON {"userId","sessionId"} (got <missing>)`
843
+ );
844
+ }
845
+ let parsed;
846
+ try {
847
+ parsed = JSON.parse(raw);
848
+ } catch (err) {
849
+ const msg = err instanceof Error ? err.message : String(err);
850
+ throw new InjectCliArgError(`--registration-metadata is not valid JSON: ${msg}`);
851
+ }
852
+ if (!parsed || typeof parsed !== "object" || typeof parsed.userId !== "string" || typeof parsed.sessionId !== "string") {
853
+ throw new InjectCliArgError(
854
+ `--registration-metadata must be a JSON object with string 'userId' and 'sessionId'`
855
+ );
856
+ }
857
+ const m = parsed;
858
+ args.registrationMetadata = { userId: m.userId, sessionId: m.sessionId };
859
+ break;
860
+ }
861
+ case "--ready-timeout": {
862
+ const raw = argv[++i];
863
+ const n = raw === void 0 ? NaN : Number.parseInt(raw, 10);
864
+ if (!Number.isFinite(n) || n <= 0) {
865
+ throw new InjectCliArgError(
866
+ `--ready-timeout expects a positive integer (got ${raw ?? "<missing>"})`
867
+ );
868
+ }
869
+ args.readyTimeoutMs = n;
870
+ break;
871
+ }
872
+ case "--no-settle":
873
+ args.waitForSettle = false;
874
+ break;
875
+ case "--settle-quiet": {
876
+ const raw = argv[++i];
877
+ const n = raw === void 0 ? NaN : Number.parseInt(raw, 10);
878
+ if (!Number.isFinite(n) || n < 0) {
879
+ throw new InjectCliArgError(
880
+ `--settle-quiet expects a non-negative integer (got ${raw ?? "<missing>"})`
881
+ );
882
+ }
883
+ args.settleQuietMs = n;
884
+ break;
885
+ }
886
+ case "--settle-timeout": {
887
+ const raw = argv[++i];
888
+ const n = raw === void 0 ? NaN : Number.parseInt(raw, 10);
889
+ if (!Number.isFinite(n) || n <= 0) {
890
+ throw new InjectCliArgError(
891
+ `--settle-timeout expects a positive integer (got ${raw ?? "<missing>"})`
892
+ );
893
+ }
894
+ args.settleTimeoutMs = n;
895
+ break;
896
+ }
897
+ case "--expect-selector": {
898
+ const raw = argv[++i];
899
+ if (raw === void 0 || raw.length === 0) {
900
+ throw new InjectCliArgError(`--expect-selector expects a CSS selector (got <missing>)`);
901
+ }
902
+ args.expectSelector = raw;
903
+ break;
904
+ }
905
+ case "--viewport": {
906
+ const raw = argv[++i];
907
+ const match = raw?.match(/^(\d+)x(\d+)$/);
908
+ if (!match) {
909
+ throw new InjectCliArgError(`--viewport expects WxH (got ${raw ?? "<missing>"})`);
910
+ }
911
+ args.viewportWidth = Number.parseInt(match[1], 10);
912
+ args.viewportHeight = Number.parseInt(match[2], 10);
913
+ break;
914
+ }
915
+ default:
916
+ if (arg !== void 0 && arg.startsWith("--")) {
917
+ throw new InjectCliArgError(`Unknown flag: ${arg}`);
918
+ }
919
+ break;
920
+ }
921
+ }
922
+ validateArgs(args);
923
+ return args;
924
+ }
925
+ function validateArgs(args) {
926
+ if (args.help) return;
927
+ if (!args.url) {
928
+ throw new InjectCliArgError("--url is required");
929
+ }
930
+ if (!/^https?:\/\//i.test(args.url)) {
931
+ throw new InjectCliArgError(`--url must start with http:// or https:// (got ${args.url})`);
932
+ }
933
+ if (selectMode(args) === "relay" && !args.relay) {
934
+ throw new InjectCliArgError(
935
+ "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)."
936
+ );
937
+ }
938
+ }
939
+ function selectMode(args) {
940
+ return args.execActions.length > 0 || args.execStdin ? "exec" : "relay";
941
+ }
942
+ function buildTransportOptions(args) {
943
+ const options = { targetUrl: args.url };
944
+ if (args.relay) options.uiBridgeBase = args.relay;
945
+ if (args.authToken) options.authToken = args.authToken;
946
+ if (args.registrationMetadata) options.registrationMetadata = args.registrationMetadata;
947
+ if (args.headed) options.headed = true;
948
+ if (args.readyTimeoutMs !== null) options.readyTimeoutMs = args.readyTimeoutMs;
949
+ if (!args.waitForSettle) options.waitForSettle = false;
950
+ if (args.settleQuietMs !== null) options.settleQuietMs = args.settleQuietMs;
951
+ if (args.settleTimeoutMs !== null) options.settleTimeoutMs = args.settleTimeoutMs;
952
+ if (args.expectSelector !== null) options.expectSelector = args.expectSelector;
953
+ if (args.appId) options.appId = args.appId;
954
+ if (args.appName) options.appName = args.appName;
955
+ if (args.tabId) options.tabId = args.tabId;
956
+ if (args.viewportWidth !== null) options.viewportWidth = args.viewportWidth;
957
+ if (args.viewportHeight !== null) options.viewportHeight = args.viewportHeight;
958
+ return options;
959
+ }
960
+ function die(msg) {
961
+ process.stderr.write(`${msg}
962
+ `);
963
+ process.exit(2);
964
+ }
965
+ function log(quiet, msg) {
966
+ if (!quiet) process.stderr.write(`${msg}
967
+ `);
968
+ }
969
+ function readStdin() {
970
+ return new Promise((resolve, reject) => {
971
+ let data = "";
972
+ process.stdin.setEncoding("utf8");
973
+ process.stdin.on("data", (chunk) => {
974
+ data += chunk;
975
+ });
976
+ process.stdin.on("end", () => resolve(data));
977
+ process.stdin.on("error", reject);
978
+ });
979
+ }
980
+ function parseStdinActions(raw) {
981
+ const out = [];
982
+ const lines = raw.split("\n");
983
+ for (const line of lines) {
984
+ const trimmed = line.trim();
985
+ if (trimmed.length === 0) continue;
986
+ let parsed;
987
+ try {
988
+ parsed = JSON.parse(trimmed);
989
+ } catch (err) {
990
+ const msg = err instanceof Error ? err.message : String(err);
991
+ throw new InjectCliArgError(`--exec-stdin line is not valid JSON: ${msg} (got ${trimmed})`);
992
+ }
993
+ if (!parsed || typeof parsed !== "object") {
994
+ throw new InjectCliArgError(`--exec-stdin line must be a JSON object (got ${trimmed})`);
995
+ }
996
+ const obj = parsed;
997
+ if (typeof obj.action !== "string" || obj.action.length === 0) {
998
+ throw new InjectCliArgError(`--exec-stdin line must have a string 'action' (got ${trimmed})`);
999
+ }
1000
+ out.push({ action: obj.action, payload: "payload" in obj ? obj.payload : {} });
1001
+ }
1002
+ return out;
1003
+ }
1004
+ async function main() {
1005
+ let args;
1006
+ try {
1007
+ args = parseArgs(process.argv.slice(2));
1008
+ } catch (err) {
1009
+ if (err instanceof InjectCliArgError) die(`${err.message}
1010
+
1011
+ ${USAGE}`);
1012
+ throw err;
1013
+ }
1014
+ if (args.help) {
1015
+ process.stdout.write(USAGE);
1016
+ process.exit(0);
1017
+ }
1018
+ const mode = selectMode(args);
1019
+ const transport = createTransport({ kind: "injected", options: buildTransportOptions(args) });
1020
+ transport.register("__inject_cli_info", (_p, ctx) => {
1021
+ const c = ctx;
1022
+ return { tabId: c.tabId ?? null, uiBridgeRegistered: c.uiBridgeRegistered ?? false };
1023
+ });
1024
+ if (mode === "exec") {
1025
+ await runExec(args, transport);
1026
+ return;
1027
+ }
1028
+ await runRelay(args, transport);
1029
+ }
1030
+ async function runExec(args, transport) {
1031
+ const actions = [...args.execActions];
1032
+ if (args.execStdin) {
1033
+ const raw = await readStdin();
1034
+ actions.push(...parseStdinActions(raw));
1035
+ }
1036
+ if (actions.length === 0) {
1037
+ die("Variant A (exec) selected but no actions were provided");
1038
+ }
1039
+ log(args.quiet, `[ui-bridge-inject] launching injected transport (exec mode)`);
1040
+ try {
1041
+ await transport.ready();
1042
+ } catch (err) {
1043
+ const msg = err instanceof Error ? err.message : String(err);
1044
+ process.stderr.write(`[ui-bridge-inject] ready failed: ${msg}
1045
+ `);
1046
+ await transport.close().catch(() => {
1047
+ });
1048
+ process.exit(1);
1049
+ }
1050
+ let anyError = false;
1051
+ try {
1052
+ for (const { action, payload } of actions) {
1053
+ if (!transport.handlerRegistry.has(action)) {
1054
+ transport.register(
1055
+ action,
1056
+ (params, ctx) => ctx.execute(action, params)
1057
+ );
1058
+ }
1059
+ try {
1060
+ const result = await transport.dispatch(action, payload);
1061
+ process.stdout.write(`${JSON.stringify({ action, result })}
1062
+ `);
1063
+ } catch (err) {
1064
+ anyError = true;
1065
+ if (err instanceof WrapperTransportError) {
1066
+ process.stdout.write(
1067
+ `${JSON.stringify({ action, error: { code: err.code, message: err.message } })}
1068
+ `
1069
+ );
1070
+ } else {
1071
+ const message = err instanceof Error ? err.message : String(err);
1072
+ process.stdout.write(
1073
+ `${JSON.stringify({ action, error: { code: "UNKNOWN", message } })}
1074
+ `
1075
+ );
1076
+ }
1077
+ }
1078
+ }
1079
+ } finally {
1080
+ await transport.close().catch(() => {
1081
+ });
1082
+ }
1083
+ process.exit(anyError ? 1 : 0);
1084
+ }
1085
+ async function runRelay(args, transport) {
1086
+ log(
1087
+ args.quiet,
1088
+ `[ui-bridge-inject] launching injected transport (relay mode, ${args.headed ? "headed" : "headless"})`
1089
+ );
1090
+ log(args.quiet, `[ui-bridge-inject] url: ${args.url} relay: ${args.relay}`);
1091
+ try {
1092
+ await transport.ready();
1093
+ } catch (err) {
1094
+ const msg = err instanceof Error ? err.message : String(err);
1095
+ process.stderr.write(`[ui-bridge-inject] ready failed: ${msg}
1096
+ `);
1097
+ await transport.close().catch(() => {
1098
+ });
1099
+ process.exit(1);
1100
+ }
1101
+ const info = await transport.dispatch("__inject_cli_info");
1102
+ process.stdout.write(
1103
+ `${JSON.stringify({
1104
+ tabId: info.tabId,
1105
+ uiBridgeRegistered: info.uiBridgeRegistered,
1106
+ url: args.url
1107
+ })}
1108
+ `
1109
+ );
1110
+ if (!info.uiBridgeRegistered) {
1111
+ process.stderr.write(
1112
+ `[ui-bridge-inject] WARN: the injected runtime did not report a registered relay tab. Verify the relay at ${args.relay} is reachable and accepts the registration.
1113
+ `
1114
+ );
1115
+ }
1116
+ log(args.quiet, `[ui-bridge-inject] ready \u2014 press Ctrl+C to exit`);
1117
+ let shuttingDown = false;
1118
+ const shutdown = async (reason, exitCode) => {
1119
+ if (shuttingDown) return;
1120
+ shuttingDown = true;
1121
+ log(args.quiet, `[ui-bridge-inject] shutting down (${reason})`);
1122
+ await transport.close().catch(() => {
1123
+ });
1124
+ process.exit(exitCode);
1125
+ };
1126
+ process.on("SIGINT", () => {
1127
+ void shutdown("SIGINT", 130);
1128
+ });
1129
+ process.on("SIGTERM", () => {
1130
+ void shutdown("SIGTERM", 143);
1131
+ });
1132
+ }
1133
+ var isMain = (() => {
1134
+ try {
1135
+ 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)));
1136
+ } catch {
1137
+ return false;
1138
+ }
1139
+ })();
1140
+ if (isMain) {
1141
+ void main().catch((err) => {
1142
+ const msg = err instanceof Error ? err.message : String(err);
1143
+ process.stderr.write(`[ui-bridge-inject] fatal: ${msg}
1144
+ `);
1145
+ process.exit(1);
1146
+ });
1147
+ }
1148
+
1149
+ exports.InjectCliArgError = InjectCliArgError;
1150
+ exports.USAGE = USAGE;
1151
+ exports.buildTransportOptions = buildTransportOptions;
1152
+ exports.parseArgs = parseArgs;
1153
+ exports.selectMode = selectMode;
1154
+ exports.validateArgs = validateArgs;
1155
+ //# sourceMappingURL=inject-cli.cjs.map
1156
+ //# sourceMappingURL=inject-cli.cjs.map