@qontinui/ui-bridge-wrapper 0.2.0 → 0.4.1

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.
package/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { createRequire } from 'module';
2
+ import { readFileSync } from 'fs';
3
+
1
4
  // src/types.ts
2
5
  var WrapperTransportError = class extends Error {
3
6
  code;
@@ -220,7 +223,21 @@ var HeadlessTransport = class extends BaseTransport {
220
223
  };
221
224
  }
222
225
  async onReady() {
223
- const { launchHeadlessTab } = await import('@qontinui/ui-bridge-headless');
226
+ let launchHeadlessTab;
227
+ try {
228
+ ({ launchHeadlessTab } = await import('@qontinui/ui-bridge-headless'));
229
+ } catch (err) {
230
+ const cause = err instanceof Error ? err.message : String(err);
231
+ throw new WrapperTransportError(
232
+ "INVALID_CONFIG",
233
+ `Transport kind '${this.kind}' needs the optional '@qontinui/ui-bridge-headless' peer, which is not installed. Install it and the Chromium browser:
234
+ npm i @qontinui/ui-bridge-headless && npx playwright install chromium
235
+ (bare \`npx @qontinui/ui-bridge-wrapper \u2026\` does NOT install peers \u2014 pass each peer with \`-p\`, e.g.
236
+ npx -y -p @qontinui/ui-bridge-wrapper -p @qontinui/ui-bridge -p @qontinui/ui-bridge-headless -p playwright ui-bridge-login-web \u2026)
237
+ Underlying import error: ${cause}`
238
+ );
239
+ }
240
+ const initScripts = await this.buildInitScripts();
224
241
  const tab = await launchHeadlessTab({
225
242
  url: this.options.targetUrl,
226
243
  headless: this.headless,
@@ -229,7 +246,8 @@ var HeadlessTransport = class extends BaseTransport {
229
246
  viewportWidth: this.options.viewportWidth,
230
247
  viewportHeight: this.options.viewportHeight,
231
248
  userAgent: this.options.userAgent,
232
- forwardConsole: this.options.forwardConsole
249
+ forwardConsole: this.options.forwardConsole,
250
+ initScripts: initScripts.length > 0 ? initScripts : void 0
233
251
  });
234
252
  this.tab = {
235
253
  browser: tab.browser,
@@ -239,6 +257,21 @@ var HeadlessTransport = class extends BaseTransport {
239
257
  tabId: tab.tabId,
240
258
  close: tab.close
241
259
  };
260
+ await this.afterLaunch(tab.page);
261
+ }
262
+ /**
263
+ * Subclass hook: init-scripts to register on the browser context before the
264
+ * first navigation (via `context.addInitScript`). Default: none. Injected
265
+ * mode overrides this to inject the config + runtime bundle pre-paint.
266
+ */
267
+ async buildInitScripts() {
268
+ return [];
269
+ }
270
+ /**
271
+ * Subclass hook: run after launch + navigation, before `ready()` resolves.
272
+ * Default: no-op. Injected mode overrides it to await the in-page runtime.
273
+ */
274
+ async afterLaunch(_page) {
242
275
  }
243
276
  async onClose() {
244
277
  if (!this.tab) return;
@@ -270,6 +303,187 @@ var HeadedTransport = class extends HeadlessTransport {
270
303
  super(config, registry, { kind: "headed", headless: false });
271
304
  }
272
305
  };
306
+ var require2 = createRequire(import.meta.url);
307
+ var cachedBundle = null;
308
+ function loadInjectedBundle() {
309
+ if (cachedBundle !== null) return cachedBundle;
310
+ let bundlePath;
311
+ try {
312
+ bundlePath = require2.resolve("@qontinui/ui-bridge/injected/bundle.global.js");
313
+ } catch {
314
+ const pkgJson = require2.resolve("@qontinui/ui-bridge/package.json");
315
+ bundlePath = pkgJson.replace(/package\.json$/, "dist/injected/bundle.global.js");
316
+ }
317
+ try {
318
+ cachedBundle = readFileSync(bundlePath, "utf8");
319
+ } catch (cause) {
320
+ throw new WrapperTransportError(
321
+ "INJECTED_BUNDLE_MISSING",
322
+ `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).`,
323
+ { cause }
324
+ );
325
+ }
326
+ return cachedBundle;
327
+ }
328
+ var InjectedTransport = class extends HeadlessTransport {
329
+ injected;
330
+ constructor(config, registry) {
331
+ const raw = config.options ?? {};
332
+ const headed = raw["headed"] === true;
333
+ super(config, registry, { kind: "injected", headless: !headed });
334
+ this.injected = {
335
+ headed,
336
+ readyTimeoutMs: typeof raw["readyTimeoutMs"] === "number" ? raw["readyTimeoutMs"] : 3e4,
337
+ waitForSettle: raw["waitForSettle"] !== false,
338
+ settleQuietMs: typeof raw["settleQuietMs"] === "number" ? raw["settleQuietMs"] : void 0,
339
+ settleTimeoutMs: typeof raw["settleTimeoutMs"] === "number" ? raw["settleTimeoutMs"] : void 0,
340
+ expectSelector: typeof raw["expectSelector"] === "string" && raw["expectSelector"].length > 0 ? raw["expectSelector"] : void 0,
341
+ authToken: typeof raw["authToken"] === "string" ? raw["authToken"] : void 0,
342
+ registrationMetadata: isRegistrationMetadata(raw["registrationMetadata"]) ? raw["registrationMetadata"] : void 0,
343
+ appId: typeof raw["appId"] === "string" ? raw["appId"] : void 0,
344
+ appName: typeof raw["appName"] === "string" ? raw["appName"] : void 0,
345
+ tabId: typeof raw["tabId"] === "string" ? raw["tabId"] : void 0
346
+ };
347
+ }
348
+ /**
349
+ * Build the `__uiBridgeInjectedConfig` injected ahead of the bundle, or null
350
+ * if there's nothing to configure. Carries the relay fields (Variant B only,
351
+ * when `uiBridgeBase` is set) AND the settle-tuning fields (both variants).
352
+ */
353
+ injectedConfig() {
354
+ const cfg = {};
355
+ const base = this.options.uiBridgeBase;
356
+ if (base) {
357
+ cfg.uiBridgeBase = base;
358
+ if (this.injected.authToken) cfg.authToken = this.injected.authToken;
359
+ if (this.injected.registrationMetadata)
360
+ cfg.registrationMetadata = this.injected.registrationMetadata;
361
+ if (this.injected.appId) cfg.appId = this.injected.appId;
362
+ if (this.injected.appName) cfg.appName = this.injected.appName;
363
+ if (this.injected.tabId) cfg.tabId = this.injected.tabId;
364
+ }
365
+ if (this.injected.settleQuietMs !== void 0)
366
+ cfg.settleQuietMs = this.injected.settleQuietMs;
367
+ if (this.injected.settleTimeoutMs !== void 0)
368
+ cfg.settleTimeoutMs = this.injected.settleTimeoutMs;
369
+ if (this.injected.expectSelector !== void 0)
370
+ cfg.expectSelector = this.injected.expectSelector;
371
+ return Object.keys(cfg).length > 0 ? cfg : null;
372
+ }
373
+ async buildInitScripts() {
374
+ const scripts = [];
375
+ const cfg = this.injectedConfig();
376
+ if (cfg) {
377
+ scripts.push(`window.__uiBridgeInjectedConfig = ${JSON.stringify(cfg)};`);
378
+ }
379
+ scripts.push(loadInjectedBundle());
380
+ return scripts;
381
+ }
382
+ async afterLaunch(page) {
383
+ try {
384
+ await page.waitForFunction(
385
+ () => window.__uiBridgeInjected?.ready === true,
386
+ void 0,
387
+ { timeout: this.injected.readyTimeoutMs }
388
+ );
389
+ } catch (cause) {
390
+ throw new WrapperTransportError(
391
+ "INJECTED_RUNTIME_NOT_READY",
392
+ `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.`,
393
+ { cause, retryable: true }
394
+ );
395
+ }
396
+ if (this.injected.waitForSettle) {
397
+ let state;
398
+ try {
399
+ await page.waitForFunction(
400
+ () => window.__uiBridgeInjected?.settled === true,
401
+ void 0,
402
+ { timeout: this.injected.readyTimeoutMs }
403
+ );
404
+ state = await page.evaluate(() => {
405
+ const api = window.__uiBridgeInjected;
406
+ return {
407
+ settled: api?.settled === true,
408
+ settledByTimeout: api?.settledByTimeout === true,
409
+ expectSatisfied: api?.expectSatisfied === true,
410
+ elementCount: api?.elementCount ?? 0
411
+ };
412
+ });
413
+ } catch (cause) {
414
+ throw new WrapperTransportError(
415
+ "INJECTED_RUNTIME_NOT_SETTLED",
416
+ `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.`,
417
+ { cause, retryable: true }
418
+ );
419
+ }
420
+ if (state.settledByTimeout && !state.expectSatisfied) {
421
+ const sel = this.injected.expectSelector;
422
+ throw new WrapperTransportError(
423
+ "INJECTED_EXPECT_SELECTOR_UNMET",
424
+ 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.`,
425
+ { retryable: true }
426
+ );
427
+ }
428
+ }
429
+ }
430
+ async buildContext() {
431
+ if (!this.tab) {
432
+ throw new WrapperTransportError(
433
+ "NOT_READY",
434
+ `Transport 'injected' is not ready; call ready() before dispatch`
435
+ );
436
+ }
437
+ const { page, context: browserContext, browser, uiBridgeRegistered, tabId } = this.tab;
438
+ const execute = (action, payload) => page.evaluate(
439
+ (args) => window.__uiBridgeInjected.execute(args[0], args[1]),
440
+ [action, payload]
441
+ );
442
+ const settleState = () => page.evaluate(() => {
443
+ const api = window.__uiBridgeInjected;
444
+ return {
445
+ settled: api?.settled === true,
446
+ elementCount: api?.elementCount ?? 0,
447
+ settledByTimeout: api?.settledByTimeout === true,
448
+ expectSatisfied: api?.expectSatisfied === true
449
+ };
450
+ });
451
+ const whenSettled = (timeoutMs) => page.evaluate(
452
+ (ms) => {
453
+ const api = window.__uiBridgeInjected;
454
+ if (api?.whenSettled) return api.whenSettled(ms ?? void 0);
455
+ return Promise.resolve({
456
+ settled: api?.settled === true,
457
+ elementCount: api?.elementCount ?? 0,
458
+ settledByTimeout: api?.settledByTimeout === true,
459
+ expectSatisfied: api?.expectSatisfied === true
460
+ });
461
+ },
462
+ timeoutMs ?? null
463
+ );
464
+ return {
465
+ kind: "injected",
466
+ page,
467
+ browserContext,
468
+ browser,
469
+ uiBridgeRegistered,
470
+ ready: true,
471
+ tabId,
472
+ settleState,
473
+ whenSettled,
474
+ execute,
475
+ find: (criteria) => execute("find", criteria ?? {}),
476
+ act: (id, request) => execute("executeElementAction", { id, request }),
477
+ snapshot: (options) => execute("getControlSnapshot", options ?? {}),
478
+ assert: (spec) => execute("aiAssert", spec)
479
+ };
480
+ }
481
+ };
482
+ function isRegistrationMetadata(value) {
483
+ if (!value || typeof value !== "object") return false;
484
+ const v = value;
485
+ return typeof v.userId === "string" && typeof v.sessionId === "string";
486
+ }
273
487
 
274
488
  // src/transports/live.ts
275
489
  var LiveSessionTransport = class extends BaseTransport {
@@ -466,6 +680,8 @@ function createTransport(config) {
466
680
  return new HeadlessTransport(config);
467
681
  case "headed":
468
682
  return new HeadedTransport(config);
683
+ case "injected":
684
+ return new InjectedTransport(config);
469
685
  case "live": {
470
686
  const opts = config.options ?? {};
471
687
  const injected = typeof opts.webSocketCtor === "function" ? { webSocketCtor: opts.webSocketCtor } : void 0;
@@ -704,6 +920,6 @@ async function startDispatchServer(transport, port, logName) {
704
920
  });
705
921
  }
706
922
 
707
- export { ApiTransport, BaseTransport, HandlerRegistry, HeadedTransport, HeadlessTransport, LiveSessionTransport, WrapperTransportError, createTransport, emitManifestOnly, paramSchemaOf, runWrapperEntrypoint, withAuthRefresh, withRetry };
923
+ export { ApiTransport, BaseTransport, HandlerRegistry, HeadedTransport, HeadlessTransport, InjectedTransport, LiveSessionTransport, WrapperTransportError, createTransport, emitManifestOnly, paramSchemaOf, runWrapperEntrypoint, withAuthRefresh, withRetry };
708
924
  //# sourceMappingURL=index.js.map
709
925
  //# sourceMappingURL=index.js.map