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