@qontinui/ui-bridge-wrapper 0.12.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +157 -8
  2. package/dist/capture-specs-cli.cjs +301 -53
  3. package/dist/capture-specs-cli.cjs.map +1 -1
  4. package/dist/capture-specs-cli.d.ts.map +1 -1
  5. package/dist/chunk-IKHDNIU4.js +478 -0
  6. package/dist/chunk-IKHDNIU4.js.map +1 -0
  7. package/dist/chunk-Z32CC665.cjs +488 -0
  8. package/dist/chunk-Z32CC665.cjs.map +1 -0
  9. package/dist/create-transport.d.ts.map +1 -1
  10. package/dist/frame-capture.d.ts +3 -28
  11. package/dist/frame-capture.d.ts.map +1 -1
  12. package/dist/frame-page.d.ts +35 -0
  13. package/dist/frame-page.d.ts.map +1 -0
  14. package/dist/index.cjs +145 -375
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.ts +1 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +90 -351
  19. package/dist/index.js.map +1 -1
  20. package/dist/inject-cli.cjs +407 -134
  21. package/dist/inject-cli.cjs.map +1 -1
  22. package/dist/inject-cli.d.ts +1 -1
  23. package/dist/inject-cli.d.ts.map +1 -1
  24. package/dist/live/index.cjs +40 -0
  25. package/dist/live/index.cjs.map +1 -0
  26. package/dist/live/index.d.ts +32 -0
  27. package/dist/live/index.d.ts.map +1 -0
  28. package/dist/live/index.js +3 -0
  29. package/dist/live/index.js.map +1 -0
  30. package/dist/login-web-cli.cjs +312 -61
  31. package/dist/login-web-cli.cjs.map +1 -1
  32. package/dist/login-web-cli.d.ts.map +1 -1
  33. package/dist/network-throttle.d.ts +5 -0
  34. package/dist/network-throttle.d.ts.map +1 -1
  35. package/dist/screenshot-capture.d.ts +82 -0
  36. package/dist/screenshot-capture.d.ts.map +1 -0
  37. package/dist/timeline-capture.d.ts +74 -10
  38. package/dist/timeline-capture.d.ts.map +1 -1
  39. package/dist/transports/headless.d.ts +46 -1
  40. package/dist/transports/headless.d.ts.map +1 -1
  41. package/dist/transports/injected.d.ts +8 -0
  42. package/dist/transports/injected.d.ts.map +1 -1
  43. package/dist/transports/live.d.ts +27 -1
  44. package/dist/transports/live.d.ts.map +1 -1
  45. package/dist/types.d.ts +3 -1
  46. package/dist/types.d.ts.map +1 -1
  47. package/package.json +11 -8
  48. package/dist/cli-args.d.ts +0 -13
  49. package/dist/cli-args.d.ts.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,171 +1,14 @@
1
1
  'use strict';
2
2
 
3
+ var chunkZ32CC665_cjs = require('./chunk-Z32CC665.cjs');
3
4
  var module$1 = require('module');
4
5
  var fs = require('fs');
5
6
  var crypto = require('crypto');
7
+ require('path');
6
8
 
7
9
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
8
- // src/types.ts
9
- var WrapperTransportError = class extends Error {
10
- code;
11
- retryable;
12
- cause;
13
- /**
14
- * Optional structured diagnostic payload (error-code-specific shape) so
15
- * programmatic callers can branch on data instead of parsing the message —
16
- * e.g. `INJECTED_EXPECT_SELECTOR_UNMET` attaches
17
- * `{ registeredElements, elementCount }`.
18
- */
19
- details;
20
- constructor(code, message, options = {}) {
21
- super(message);
22
- this.name = "WrapperTransportError";
23
- this.code = code;
24
- this.retryable = options.retryable ?? false;
25
- if (options.cause !== void 0) {
26
- this.cause = options.cause;
27
- }
28
- if (options.details !== void 0) {
29
- this.details = options.details;
30
- }
31
- }
32
- };
33
-
34
- // src/handler-registry.ts
35
- var HandlerRegistry = class {
36
- handlers = /* @__PURE__ */ new Map();
37
- /**
38
- * Register (or replace) a handler for `actionId`. Replacement is explicit
39
- * rather than throwing because live reloading / hot module scenarios need
40
- * to update handlers without tearing the whole transport down.
41
- */
42
- register(actionId, fn) {
43
- this.handlers.set(actionId, fn);
44
- }
45
- /** Remove a handler. Returns `true` if a handler was removed. */
46
- unregister(actionId) {
47
- return this.handlers.delete(actionId);
48
- }
49
- /** All registered action ids. Stable iteration order (insertion order). */
50
- list() {
51
- return Array.from(this.handlers.keys());
52
- }
53
- /** Check whether a handler is registered for `actionId`. */
54
- has(actionId) {
55
- return this.handlers.has(actionId);
56
- }
57
- /**
58
- * Invoke the handler registered under `actionId`.
59
- *
60
- * Throws `WrapperTransportError("NO_HANDLER")` if no handler is registered.
61
- * Propagates handler errors wrapped as `WrapperTransportError("HANDLER_ERROR")`
62
- * so callers can uniformly check `err.code`.
63
- */
64
- async dispatch(actionId, params, ctx) {
65
- const handler = this.handlers.get(actionId);
66
- if (!handler) {
67
- throw new WrapperTransportError(
68
- "NO_HANDLER",
69
- `No handler registered for action '${actionId}'`
70
- );
71
- }
72
- try {
73
- const result = await handler(params, ctx);
74
- return result;
75
- } catch (err) {
76
- if (err instanceof WrapperTransportError) throw err;
77
- const message = err instanceof Error ? err.message : String(err);
78
- throw new WrapperTransportError("HANDLER_ERROR", message, { cause: err });
79
- }
80
- }
81
- };
82
-
83
- // src/base-transport.ts
84
- var BaseTransport = class {
85
- _status = "idle";
86
- listeners = /* @__PURE__ */ new Set();
87
- registry;
88
- readyPromise = null;
89
- constructor(registry) {
90
- this.registry = registry ?? new HandlerRegistry();
91
- }
92
- get status() {
93
- return this._status;
94
- }
95
- /** Expose the underlying registry so wrappers can register handlers. */
96
- get handlerRegistry() {
97
- return this.registry;
98
- }
99
- /** Convenience: register a handler on the transport's registry. */
100
- register(actionId, fn) {
101
- this.registry.register(actionId, fn);
102
- }
103
- /**
104
- * Idempotent async setup. First call runs `onReady()`; subsequent calls
105
- * share the same promise until it settles, after which further calls
106
- * are no-ops if `status === 'ready'`, or re-run setup if it errored.
107
- */
108
- async ready() {
109
- if (this._status === "ready") return;
110
- if (this._status === "closed") {
111
- throw new WrapperTransportError("TRANSPORT_CLOSED", `Transport '${this.kind}' is closed`);
112
- }
113
- if (this.readyPromise) return this.readyPromise;
114
- this.setStatus("connecting");
115
- this.readyPromise = this.onReady().then(() => {
116
- this.setStatus("ready");
117
- }).catch((err) => {
118
- this.setStatus("error");
119
- this.readyPromise = null;
120
- throw err;
121
- });
122
- return this.readyPromise;
123
- }
124
- /** Default dispatch — waits for ready, builds ctx, delegates to registry. */
125
- async dispatch(actionId, params) {
126
- await this.ready();
127
- const ctx = await this.buildContext(actionId, params);
128
- return this.registry.dispatch(actionId, params, ctx);
129
- }
130
- async close() {
131
- if (this._status === "closed") return;
132
- try {
133
- await this.onClose();
134
- } finally {
135
- this.setStatus("closed");
136
- this.listeners.clear();
137
- this.readyPromise = null;
138
- }
139
- }
140
- onStatusChange(listener) {
141
- this.listeners.add(listener);
142
- return () => {
143
- this.listeners.delete(listener);
144
- };
145
- }
146
- /** Update status and notify listeners. Safe to call from subclasses. */
147
- setStatus(next) {
148
- if (this._status === next) return;
149
- this._status = next;
150
- for (const l of this.listeners) {
151
- try {
152
- l(next);
153
- } catch {
154
- }
155
- }
156
- }
157
- /**
158
- * Subclass hook: build the context object passed to handlers. Default is
159
- * `undefined` (api transport). Headless/headed override to provide the
160
- * Playwright `page`; live overrides to provide a response helper.
161
- */
162
- async buildContext(_actionId, _params) {
163
- return void 0;
164
- }
165
- };
166
-
167
10
  // src/transports/api.ts
168
- var ApiTransport = class extends BaseTransport {
11
+ var ApiTransport = class extends chunkZ32CC665_cjs.BaseTransport {
169
12
  kind = "api";
170
13
  fallback;
171
14
  constructor(config = { kind: "api" }, registry) {
@@ -196,17 +39,17 @@ var ApiTransport = class extends BaseTransport {
196
39
  try {
197
40
  return await this.fallback(actionId, params);
198
41
  } catch (err) {
199
- if (err instanceof WrapperTransportError) throw err;
42
+ if (err instanceof chunkZ32CC665_cjs.WrapperTransportError) throw err;
200
43
  const message = err instanceof Error ? err.message : String(err);
201
- throw new WrapperTransportError("HANDLER_ERROR", message, { cause: err });
44
+ throw new chunkZ32CC665_cjs.WrapperTransportError("HANDLER_ERROR", message, { cause: err });
202
45
  }
203
46
  }
204
- throw new WrapperTransportError("NO_HANDLER", `No handler registered for action '${actionId}'`);
47
+ throw new chunkZ32CC665_cjs.WrapperTransportError("NO_HANDLER", `No handler registered for action '${actionId}'`);
205
48
  }
206
49
  };
207
50
 
208
51
  // src/transports/headless.ts
209
- var HeadlessTransport = class extends BaseTransport {
52
+ var HeadlessTransport = class extends chunkZ32CC665_cjs.BaseTransport {
210
53
  kind;
211
54
  options;
212
55
  headless;
@@ -221,7 +64,7 @@ var HeadlessTransport = class extends BaseTransport {
221
64
  const raw = config.options ?? {};
222
65
  const targetUrl = raw["targetUrl"];
223
66
  if (typeof targetUrl !== "string" || targetUrl.length === 0) {
224
- throw new WrapperTransportError(
67
+ throw new chunkZ32CC665_cjs.WrapperTransportError(
225
68
  "INVALID_CONFIG",
226
69
  `Transport kind '${this.kind}' requires options.targetUrl (string)`
227
70
  );
@@ -237,9 +80,60 @@ var HeadlessTransport = class extends BaseTransport {
237
80
  userAgent: typeof raw["userAgent"] === "string" ? raw["userAgent"] : void 0,
238
81
  forwardConsole: typeof raw["forwardConsole"] === "boolean" ? raw["forwardConsole"] : void 0,
239
82
  launchArgs: Array.isArray(raw["launchArgs"]) && raw["launchArgs"].every((a) => typeof a === "string") ? raw["launchArgs"] : void 0,
240
- storageStatePath: typeof raw["storageStatePath"] === "string" ? raw["storageStatePath"] : void 0
83
+ storageStatePath: typeof raw["storageStatePath"] === "string" ? raw["storageStatePath"] : void 0,
84
+ ...this.parseContextOptions(raw)
241
85
  };
242
86
  }
87
+ /**
88
+ * `recordHar`, `recordVideo`, `serviceWorkers` and `initRouter`. Unlike the display
89
+ * options above, a malformed value is REFUSED rather than dropped: dropping
90
+ * `recordHar` would leave a caller waiting for an archive that is never
91
+ * written, and dropping `initRouter` would let requests it meant to answer
92
+ * reach the network.
93
+ */
94
+ parseContextOptions(raw) {
95
+ const out = {};
96
+ const invalid = (what) => new chunkZ32CC665_cjs.WrapperTransportError("INVALID_CONFIG", `Transport kind '${this.kind}': ${what}`);
97
+ const har = raw["recordHar"];
98
+ if (har !== void 0) {
99
+ if (typeof har !== "object" || har === null || typeof har.path !== "string" || har.path.length === 0) {
100
+ throw invalid("options.recordHar must be an object with a non-empty string `path`");
101
+ }
102
+ out.recordHar = har;
103
+ }
104
+ const video = raw["recordVideo"];
105
+ if (video !== void 0) {
106
+ if (typeof video !== "object" || video === null || typeof video.dir !== "string" || video.dir.length === 0) {
107
+ throw invalid("options.recordVideo must be an object with a non-empty string `dir`");
108
+ }
109
+ const size = video.size;
110
+ if (size !== void 0) {
111
+ const positiveInt = (n) => typeof n === "number" && Number.isInteger(n) && n > 0;
112
+ const s = size;
113
+ if (typeof size !== "object" || s === null || !positiveInt(s.width) || !positiveInt(s.height)) {
114
+ throw invalid(
115
+ "options.recordVideo.size must be { width, height } with positive integer sides"
116
+ );
117
+ }
118
+ }
119
+ out.recordVideo = video;
120
+ }
121
+ const sw = raw["serviceWorkers"];
122
+ if (sw !== void 0) {
123
+ if (sw !== "allow" && sw !== "block") {
124
+ throw invalid(`options.serviceWorkers must be 'allow' or 'block' (got ${String(sw)})`);
125
+ }
126
+ out.serviceWorkers = sw;
127
+ }
128
+ const router = raw["initRouter"];
129
+ if (router !== void 0) {
130
+ if (typeof router !== "function") {
131
+ throw invalid("options.initRouter must be a function (context) => void | Promise<void>");
132
+ }
133
+ out.initRouter = router;
134
+ }
135
+ return out;
136
+ }
243
137
  async onReady() {
244
138
  let launchHeadlessTab;
245
139
  const headlessSpecifier = "@qontinui/ui-bridge-headless";
@@ -250,7 +144,7 @@ var HeadlessTransport = class extends BaseTransport {
250
144
  const cause = err instanceof Error ? err.message : String(err);
251
145
  const code = err?.code;
252
146
  if (code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND") {
253
- throw new WrapperTransportError(
147
+ throw new chunkZ32CC665_cjs.WrapperTransportError(
254
148
  "INVALID_CONFIG",
255
149
  `Transport kind '${this.kind}' needs the optional '@qontinui/ui-bridge-headless' peer, which is not installed. Install it and the Chromium browser:
256
150
  npm i @qontinui/ui-bridge-headless && npx playwright install chromium
@@ -259,7 +153,7 @@ var HeadlessTransport = class extends BaseTransport {
259
153
  Underlying import error: ${cause}`
260
154
  );
261
155
  }
262
- throw new WrapperTransportError(
156
+ throw new chunkZ32CC665_cjs.WrapperTransportError(
263
157
  "INVALID_CONFIG",
264
158
  `'@qontinui/ui-bridge-headless' is installed but failed to load \u2014 this is a broken install (missing transitive dependency or version skew), not a missing peer. Try reinstalling it. Underlying error: ${cause}`
265
159
  );
@@ -267,6 +161,13 @@ Underlying import error: ${cause}`
267
161
  const initScripts = await this.buildInitScripts();
268
162
  const relayAuth = this.relayAuth();
269
163
  const pinnedTabId = this.pinnedTabId();
164
+ const { recordHar, recordVideo, serviceWorkers, initRouter: callerRouter } = this.options;
165
+ const contextOptionsRequested = recordHar !== void 0 || recordVideo !== void 0 || serviceWorkers === "block" || callerRouter !== void 0;
166
+ let routerCalled = false;
167
+ const initRouter = contextOptionsRequested || serviceWorkers !== void 0 ? async (context) => {
168
+ routerCalled = true;
169
+ if (callerRouter) await callerRouter(context);
170
+ } : void 0;
270
171
  let tab;
271
172
  try {
272
173
  tab = await launchHeadlessTab({
@@ -285,12 +186,16 @@ Underlying import error: ${cause}`
285
186
  storageStatePath: this.options.storageStatePath,
286
187
  ...relayAuth.authToken ? { authToken: relayAuth.authToken } : {},
287
188
  ...relayAuth.callerUserId ? { callerUserId: relayAuth.callerUserId } : {},
288
- ...pinnedTabId ? { pinnedTabId } : {}
189
+ ...pinnedTabId ? { pinnedTabId } : {},
190
+ ...recordHar !== void 0 ? { recordHar } : {},
191
+ ...recordVideo !== void 0 ? { recordVideo } : {},
192
+ ...serviceWorkers !== void 0 ? { serviceWorkers } : {},
193
+ ...initRouter ? { initRouter } : {}
289
194
  });
290
195
  } catch (err) {
291
196
  const cause = err instanceof Error ? err.message : String(err);
292
197
  if (/Executable doesn't exist|browserType\.launch/i.test(cause)) {
293
- throw new WrapperTransportError(
198
+ throw new chunkZ32CC665_cjs.WrapperTransportError(
294
199
  "INVALID_CONFIG",
295
200
  `Playwright's Chromium browser is not installed (the '@qontinui/ui-bridge-headless' peer itself loaded fine). Run:
296
201
  npx playwright install chromium
@@ -307,6 +212,24 @@ Underlying launch error: ${cause}`
307
212
  tabId: tab.tabId,
308
213
  close: tab.close
309
214
  };
215
+ if (contextOptionsRequested && !routerCalled) {
216
+ await this.onClose().catch(() => {
217
+ });
218
+ throw new chunkZ32CC665_cjs.WrapperTransportError(
219
+ "CONTEXT_OPTIONS_NOT_APPLIED",
220
+ `The installed '@qontinui/ui-bridge-headless' peer launched the tab without calling initRouter, so it predates the recordHar / recordVideo / serviceWorkers / initRouter passthrough (0.8.0, ui-bridge#381) and ignored them: no HAR or video would be written and no route installed. Upgrade it to 0.8.0 or later.`,
221
+ {
222
+ details: {
223
+ requested: {
224
+ recordHar: recordHar !== void 0,
225
+ recordVideo: recordVideo !== void 0,
226
+ serviceWorkers: serviceWorkers ?? null,
227
+ initRouter: callerRouter !== void 0
228
+ }
229
+ }
230
+ }
231
+ );
232
+ }
310
233
  await this.verifyEmulation(tab.page);
311
234
  await this.afterLaunch(tab.page);
312
235
  }
@@ -334,7 +257,7 @@ Underlying launch error: ${cause}`
334
257
  if (problems.length === 0) return;
335
258
  await this.onClose().catch(() => {
336
259
  });
337
- throw new WrapperTransportError(
260
+ throw new chunkZ32CC665_cjs.WrapperTransportError(
338
261
  "EMULATION_NOT_APPLIED",
339
262
  `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.`,
340
263
  { details: { requested: { deviceScaleFactor: wantDpr, colorScheme: wantScheme }, seen } }
@@ -378,7 +301,7 @@ Underlying launch error: ${cause}`
378
301
  }
379
302
  async buildContext() {
380
303
  if (!this.tab) {
381
- throw new WrapperTransportError(
304
+ throw new chunkZ32CC665_cjs.WrapperTransportError(
382
305
  "NOT_READY",
383
306
  `Transport '${this.kind}' is not ready; call ready() before dispatch`
384
307
  );
@@ -416,7 +339,7 @@ function loadInjectedBundle() {
416
339
  try {
417
340
  cachedBundle = fs.readFileSync(bundlePath, "utf8");
418
341
  } catch (cause) {
419
- throw new WrapperTransportError(
342
+ throw new chunkZ32CC665_cjs.WrapperTransportError(
420
343
  "INJECTED_BUNDLE_MISSING",
421
344
  `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).`,
422
345
  { cause }
@@ -511,7 +434,7 @@ var InjectedTransport = class extends HeadlessTransport {
511
434
  { timeout: this.injected.readyTimeoutMs }
512
435
  );
513
436
  } catch (cause) {
514
- throw new WrapperTransportError(
437
+ throw new chunkZ32CC665_cjs.WrapperTransportError(
515
438
  "INJECTED_RUNTIME_NOT_READY",
516
439
  `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.`,
517
440
  { cause, retryable: true }
@@ -535,7 +458,7 @@ var InjectedTransport = class extends HeadlessTransport {
535
458
  };
536
459
  });
537
460
  } catch (cause) {
538
- throw new WrapperTransportError(
461
+ throw new chunkZ32CC665_cjs.WrapperTransportError(
539
462
  "INJECTED_RUNTIME_NOT_SETTLED",
540
463
  `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.`,
541
464
  { cause, retryable: true }
@@ -546,12 +469,12 @@ var InjectedTransport = class extends HeadlessTransport {
546
469
  const baseMessage = 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.`;
547
470
  const digest = await this.registeredElementDigest(page);
548
471
  if (digest === null) {
549
- throw new WrapperTransportError("INJECTED_EXPECT_SELECTOR_UNMET", baseMessage, {
472
+ throw new chunkZ32CC665_cjs.WrapperTransportError("INJECTED_EXPECT_SELECTOR_UNMET", baseMessage, {
550
473
  retryable: true
551
474
  });
552
475
  }
553
476
  const summary = digest.length > 0 ? ` Registered: ${digest.map((el) => el.role ? `${el.id} (${el.role})` : el.id).join(", ")}${state.elementCount > digest.length ? ", \u2026" : ""}` : "";
554
- throw new WrapperTransportError(
477
+ throw new chunkZ32CC665_cjs.WrapperTransportError(
555
478
  "INJECTED_EXPECT_SELECTOR_UNMET",
556
479
  `${baseMessage}${summary}`,
557
480
  {
@@ -608,7 +531,7 @@ var InjectedTransport = class extends HeadlessTransport {
608
531
  }
609
532
  async buildContext() {
610
533
  if (!this.tab) {
611
- throw new WrapperTransportError(
534
+ throw new chunkZ32CC665_cjs.WrapperTransportError(
612
535
  "NOT_READY",
613
536
  `Transport 'injected' is not ready; call ready() before dispatch`
614
537
  );
@@ -653,6 +576,7 @@ var InjectedTransport = class extends HeadlessTransport {
653
576
  execute,
654
577
  find: (criteria) => execute("find", criteria ?? {}),
655
578
  act: (id, request) => execute("executeElementAction", { id, request }),
579
+ element: (id) => execute("getElement", { id }),
656
580
  snapshot: (options) => execute("getControlSnapshot", options ?? {}),
657
581
  assert: (spec) => execute("aiAssert", spec)
658
582
  };
@@ -664,192 +588,6 @@ function isRegistrationMetadata(value) {
664
588
  return typeof v.userId === "string" && typeof v.sessionId === "string";
665
589
  }
666
590
 
667
- // src/transports/live.ts
668
- var LiveSessionTransport = class extends BaseTransport {
669
- kind = "live";
670
- url;
671
- appId;
672
- appName;
673
- opts;
674
- wsCtor;
675
- ws = null;
676
- ackResolvers = null;
677
- constructor(config, registry, injected) {
678
- super(registry);
679
- if (!config.runnerUrl) {
680
- throw new WrapperTransportError("INVALID_CONFIG", `Transport kind 'live' requires runnerUrl`);
681
- }
682
- this.url = config.runnerUrl;
683
- this.appId = config.appId;
684
- this.appName = config.appName;
685
- this.opts = config.options ?? {};
686
- const fromInjection = injected?.webSocketCtor;
687
- const fromGlobal = typeof globalThis.WebSocket === "function" ? globalThis.WebSocket : void 0;
688
- const resolved = fromInjection ?? fromGlobal;
689
- if (!resolved) {
690
- throw new WrapperTransportError(
691
- "NO_WEBSOCKET",
692
- `No WebSocket constructor available. Provide one via the second constructor arg or run in an environment with global WebSocket.`
693
- );
694
- }
695
- this.wsCtor = resolved;
696
- }
697
- async onReady() {
698
- const ws = new this.wsCtor(this.url);
699
- this.ws = ws;
700
- ws.addEventListener("message", (ev) => this.handleMessage(ev.data));
701
- ws.addEventListener("close", () => this.handleClose());
702
- ws.addEventListener("error", (ev) => this.handleError(ev));
703
- await new Promise((resolve, reject) => {
704
- const onOpen = () => {
705
- try {
706
- const frame = {
707
- type: "register",
708
- transport: "websocket",
709
- appId: this.appId,
710
- appName: this.appName,
711
- appType: this.opts.appType ?? "wrapper"
712
- };
713
- if (this.opts.framework !== void 0) frame.framework = this.opts.framework;
714
- if (this.opts.version !== void 0) frame.version = this.opts.version;
715
- if (this.opts.capabilities !== void 0) frame.capabilities = this.opts.capabilities;
716
- if (this.opts.origin !== void 0) frame.origin = this.opts.origin;
717
- if (this.opts.pageUrl !== void 0) frame.pageUrl = this.opts.pageUrl;
718
- ws.send(JSON.stringify(frame));
719
- } catch (err) {
720
- reject(err instanceof Error ? err : new Error(String(err)));
721
- return;
722
- }
723
- const timeoutMs = this.opts.handshakeTimeoutMs ?? 1e4;
724
- const timer = setTimeout(() => {
725
- this.ackResolvers = null;
726
- reject(
727
- new WrapperTransportError(
728
- "HANDSHAKE_TIMEOUT",
729
- `Did not receive register ack within ${timeoutMs}ms`
730
- )
731
- );
732
- }, timeoutMs);
733
- this.ackResolvers = { resolve, reject, timer };
734
- };
735
- ws.addEventListener("open", onOpen);
736
- });
737
- }
738
- async onClose() {
739
- const ws = this.ws;
740
- this.ws = null;
741
- if (this.ackResolvers) {
742
- clearTimeout(this.ackResolvers.timer);
743
- this.ackResolvers.reject(
744
- new WrapperTransportError("TRANSPORT_CLOSED", "Transport closed during handshake")
745
- );
746
- this.ackResolvers = null;
747
- }
748
- if (ws) {
749
- try {
750
- ws.close();
751
- } catch {
752
- }
753
- }
754
- }
755
- async buildContext() {
756
- return { kind: "live", commandId: null };
757
- }
758
- handleMessage(data) {
759
- let frame;
760
- try {
761
- const text = typeof data === "string" ? data : String(data);
762
- frame = JSON.parse(text);
763
- } catch {
764
- return;
765
- }
766
- switch (frame.type) {
767
- case "ack":
768
- case "registered": {
769
- const f = frame;
770
- if (!this.ackResolvers) return;
771
- clearTimeout(this.ackResolvers.timer);
772
- if (f.ok === false) {
773
- const err = new WrapperTransportError(
774
- f.error?.code ?? "REGISTER_FAILED",
775
- f.error?.message ?? "Runner refused registration"
776
- );
777
- this.ackResolvers.reject(err);
778
- } else {
779
- this.ackResolvers.resolve();
780
- }
781
- this.ackResolvers = null;
782
- return;
783
- }
784
- case "command": {
785
- const f = frame;
786
- void this.handleCommand(f);
787
- return;
788
- }
789
- default:
790
- return;
791
- }
792
- }
793
- async handleCommand(frame) {
794
- const ctx = { kind: "live", commandId: frame.commandId };
795
- let response;
796
- try {
797
- const result = await this.registry.dispatch(frame.action, frame.payload, ctx);
798
- response = {
799
- type: "response",
800
- commandId: frame.commandId,
801
- success: true,
802
- result
803
- };
804
- } catch (err) {
805
- const code = err instanceof WrapperTransportError ? err.code : "HANDLER_ERROR";
806
- const retryable = err instanceof WrapperTransportError ? err.retryable : false;
807
- const message = err instanceof Error ? err.message : String(err);
808
- response = {
809
- type: "response",
810
- commandId: frame.commandId,
811
- success: false,
812
- error: { code, message, retryable }
813
- };
814
- }
815
- try {
816
- this.ws?.send(JSON.stringify(response));
817
- } catch {
818
- }
819
- }
820
- handleClose() {
821
- if (this._status === "closed") return;
822
- this.setStatus("closed");
823
- if (this.ackResolvers) {
824
- clearTimeout(this.ackResolvers.timer);
825
- this.ackResolvers.reject(
826
- new WrapperTransportError("DISCONNECTED", "WebSocket closed before ack")
827
- );
828
- this.ackResolvers = null;
829
- }
830
- }
831
- handleError(ev) {
832
- if (this.ackResolvers) {
833
- clearTimeout(this.ackResolvers.timer);
834
- const message = this.extractErrorMessage(ev);
835
- this.ackResolvers.reject(
836
- new WrapperTransportError("WEBSOCKET_ERROR", message, { retryable: true })
837
- );
838
- this.ackResolvers = null;
839
- } else {
840
- this.setStatus("error");
841
- }
842
- }
843
- extractErrorMessage(ev) {
844
- if (ev && typeof ev === "object" && "message" in ev) {
845
- const m = ev.message;
846
- if (typeof m === "string") return m;
847
- }
848
- if (ev instanceof Error) return ev.message;
849
- return "WebSocket error";
850
- }
851
- };
852
-
853
591
  // src/create-transport.ts
854
592
  function createTransport(config) {
855
593
  switch (config.kind) {
@@ -864,19 +602,19 @@ function createTransport(config) {
864
602
  case "live": {
865
603
  const opts = config.options ?? {};
866
604
  const injected = typeof opts.webSocketCtor === "function" ? { webSocketCtor: opts.webSocketCtor } : void 0;
867
- return new LiveSessionTransport(config, void 0, injected);
605
+ return new chunkZ32CC665_cjs.LiveSessionTransport(config, void 0, injected);
868
606
  }
869
607
  default: {
870
608
  const kind = config.kind ?? "<missing>";
871
- throw new WrapperTransportError("UNKNOWN_TRANSPORT", `Unknown transport kind '${kind}'`);
609
+ throw new chunkZ32CC665_cjs.WrapperTransportError("UNKNOWN_TRANSPORT", `Unknown transport kind '${kind}'`);
872
610
  }
873
611
  }
874
612
  }
875
613
 
876
614
  // src/helpers/retry.ts
877
- var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
615
+ var defaultSleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
878
616
  var defaultShouldRetry = (err) => {
879
- if (err instanceof WrapperTransportError) {
617
+ if (err instanceof chunkZ32CC665_cjs.WrapperTransportError) {
880
618
  return err.retryable;
881
619
  }
882
620
  return true;
@@ -905,7 +643,7 @@ async function withRetry(fn, opts = {}) {
905
643
 
906
644
  // src/helpers/auth.ts
907
645
  var defaultIsAuthError = (err) => {
908
- if (err instanceof WrapperTransportError) {
646
+ if (err instanceof chunkZ32CC665_cjs.WrapperTransportError) {
909
647
  return /^(AUTH|UNAUTH|401)/i.test(err.code);
910
648
  }
911
649
  const status = err?.status;
@@ -1090,23 +828,55 @@ async function startDispatchServer(transport, port, logName) {
1090
828
  res.writeHead(404, { "Content-Type": "application/json" });
1091
829
  res.end(JSON.stringify({ success: false, error: "not found" }));
1092
830
  });
1093
- await new Promise((resolve, reject) => {
831
+ await new Promise((resolve2, reject) => {
1094
832
  server.once("error", reject);
1095
833
  server.listen(port, "127.0.0.1", () => {
1096
834
  server.removeListener("error", reject);
1097
- resolve();
835
+ resolve2();
1098
836
  });
1099
837
  });
1100
838
  }
1101
839
 
840
+ Object.defineProperty(exports, "BaseTransport", {
841
+ enumerable: true,
842
+ get: function () { return chunkZ32CC665_cjs.BaseTransport; }
843
+ });
844
+ Object.defineProperty(exports, "HandlerRegistry", {
845
+ enumerable: true,
846
+ get: function () { return chunkZ32CC665_cjs.HandlerRegistry; }
847
+ });
848
+ Object.defineProperty(exports, "LiveSessionTransport", {
849
+ enumerable: true,
850
+ get: function () { return chunkZ32CC665_cjs.LiveSessionTransport; }
851
+ });
852
+ Object.defineProperty(exports, "SCREENSHOT_ACTION", {
853
+ enumerable: true,
854
+ get: function () { return chunkZ32CC665_cjs.SCREENSHOT_ACTION; }
855
+ });
856
+ Object.defineProperty(exports, "SCREENSHOT_CAPABILITY", {
857
+ enumerable: true,
858
+ get: function () { return chunkZ32CC665_cjs.SCREENSHOT_CAPABILITY; }
859
+ });
860
+ Object.defineProperty(exports, "SCREENSHOT_TIMEOUT_MS", {
861
+ enumerable: true,
862
+ get: function () { return chunkZ32CC665_cjs.SCREENSHOT_TIMEOUT_MS; }
863
+ });
864
+ Object.defineProperty(exports, "WrapperTransportError", {
865
+ enumerable: true,
866
+ get: function () { return chunkZ32CC665_cjs.WrapperTransportError; }
867
+ });
868
+ Object.defineProperty(exports, "captureScreenshotReply", {
869
+ enumerable: true,
870
+ get: function () { return chunkZ32CC665_cjs.captureScreenshotReply; }
871
+ });
872
+ Object.defineProperty(exports, "registerScreenshotCapture", {
873
+ enumerable: true,
874
+ get: function () { return chunkZ32CC665_cjs.registerScreenshotCapture; }
875
+ });
1102
876
  exports.ApiTransport = ApiTransport;
1103
- exports.BaseTransport = BaseTransport;
1104
- exports.HandlerRegistry = HandlerRegistry;
1105
877
  exports.HeadedTransport = HeadedTransport;
1106
878
  exports.HeadlessTransport = HeadlessTransport;
1107
879
  exports.InjectedTransport = InjectedTransport;
1108
- exports.LiveSessionTransport = LiveSessionTransport;
1109
- exports.WrapperTransportError = WrapperTransportError;
1110
880
  exports.createTransport = createTransport;
1111
881
  exports.emitManifestOnly = emitManifestOnly;
1112
882
  exports.paramSchemaOf = paramSchemaOf;