@browserbox/hyper-frame 3.0.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.
- package/LICENSE +662 -0
- package/README.md +153 -0
- package/TRADEMARK.md +16 -0
- package/package.json +20 -0
- package/src/hyper-frame.js +3986 -0
|
@@ -0,0 +1,3986 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
* Hyper-Frame — an iframe that can frame any website.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @file Hyper-Frame Web Component — Canonical Embedding API
|
|
8
|
+
* @description Custom element for embedding BrowserBox remote browser sessions.
|
|
9
|
+
* This file is the single source of truth for the <hyper-frame> custom element
|
|
10
|
+
* API. Synced package/demo copies are refreshed with `npm run sync:webview-api`.
|
|
11
|
+
* Consumers create a `<hyper-frame>` element, set a `login-link`, and
|
|
12
|
+
* call methods on it.
|
|
13
|
+
*
|
|
14
|
+
* ## Usage
|
|
15
|
+
* ```html
|
|
16
|
+
* <hyper-frame
|
|
17
|
+
* login-link="https://bbx.example.com/login?token=..."
|
|
18
|
+
* width="100%"
|
|
19
|
+
* height="100%">
|
|
20
|
+
* </hyper-frame>
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* ## Attributes
|
|
24
|
+
* | Attribute | Required | Default | Description |
|
|
25
|
+
* |-----------|----------|---------|-------------|
|
|
26
|
+
* | `login-link` | yes | — | Full BrowserBox login URL with auth token |
|
|
27
|
+
* | `width` | no | `"100%"` | CSS width (px if bare number) |
|
|
28
|
+
* | `height` | no | `"100%"` | CSS height (px if bare number) |
|
|
29
|
+
* | `embedder-origin` | no | `"*"` | Origin of the embedding page (passed to BrowserBox iframe) |
|
|
30
|
+
* | `request-timeout-ms` | no | `30000` | API call timeout (ms) |
|
|
31
|
+
* | `media-permissions` | no | `"default"` | Set to `"none"` to deny embedded mic/camera/display-capture use |
|
|
32
|
+
* | `session-unload-warning` | no | `"default"` | Set to `"none"` to suppress BrowserBox's own "leave remote browser?" beforeunload warning |
|
|
33
|
+
* | `beforeunload-behavior` | no | `"default"` | Set to `"leave"` to auto-depart or `"remain"` to auto-remain when a remote page triggers a beforeunload dialog |
|
|
34
|
+
*
|
|
35
|
+
* ## Events * | Event | Detail | Description |
|
|
36
|
+
* |-------|--------|-------------|
|
|
37
|
+
* | `ready` | `{ type }` | Legacy transport handshake completed |
|
|
38
|
+
* | `api-ready` | `{ methods: string[] }` | Modern API available |
|
|
39
|
+
* | `ready-timeout` | `{ timeoutMs, error }` | Ready handshake timed out |
|
|
40
|
+
* | `tab-created` | `{ index, id, url }` | New tab opened |
|
|
41
|
+
* | `tab-attached` | `{ id, url, title }` | Existing/created tab attached to a session |
|
|
42
|
+
* | `tab-closed` | `{ index, id }` | Tab closed |
|
|
43
|
+
* | `active-tab-changed` | `{ index, id }` | Active tab switched |
|
|
44
|
+
* | `tab-updated` | `{ id, url, title, faviconDataURI }` | Tab metadata updated |
|
|
45
|
+
* | `did-start-loading` | `{ tabId, url }` | Page load started |
|
|
46
|
+
* | `did-stop-loading` | `{ tabId, url }` | Page load finished |
|
|
47
|
+
* | `did-navigate` | `{ tabId, url }` | Navigation committed |
|
|
48
|
+
* | `policy-denied` | `{ url, reason }` | Navigation blocked by policy |
|
|
49
|
+
* | `modal-opened` | `{ id, type, actions, dismissAction, ... }` | BrowserBox modal became visible |
|
|
50
|
+
* | `modal-updated` | `{ id, type, actions, dismissAction, ... }` | BrowserBox modal metadata changed |
|
|
51
|
+
* | `modal-closed` | `{ id, type, action, reason }` | BrowserBox modal closed or was answered |
|
|
52
|
+
* | `sos` | `{ reasonCode, message, retryUrl, ... }` | Fatal unusable signal from embedded BrowserBox |
|
|
53
|
+
* | `usability-changed` | `{ usable: boolean }` | Browser usability state changed |
|
|
54
|
+
* | `disconnected` | — | Session ended (element removed or login-link changed) |
|
|
55
|
+
*
|
|
56
|
+
* ## Transport
|
|
57
|
+
* The component auto-detects transport on first API call:
|
|
58
|
+
* - **modern** (`bbx-api-call`): Full method dispatch, discovered via `api-ready`
|
|
59
|
+
* - **legacy** (individual postMessage types): Fallback for older BBX versions
|
|
60
|
+
* Detection is one-shot — once resolved, transport is locked for the session.
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* const bbx = document.querySelector('hyper-frame');
|
|
64
|
+
* await bbx.whenReady();
|
|
65
|
+
* await bbx.createTab('https://example.com');
|
|
66
|
+
* const tabs = await bbx.getTabs();
|
|
67
|
+
* console.log(tabs); // [{ index: 0, id: '...', url: '...', title: '...' }]
|
|
68
|
+
*/
|
|
69
|
+
|
|
70
|
+
function readOnlyProperty(getter) {
|
|
71
|
+
return {
|
|
72
|
+
enumerable: true,
|
|
73
|
+
configurable: false,
|
|
74
|
+
get: getter,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const ERROR_CODES = Object.freeze({
|
|
79
|
+
BASE: 'ERR_BROWSERBOX',
|
|
80
|
+
NOT_READY: 'ERR_NOT_READY',
|
|
81
|
+
POLICY_DENIED: 'ERR_POLICY_DENIED',
|
|
82
|
+
TIMEOUT: 'ERR_TIMEOUT',
|
|
83
|
+
TRANSPORT: 'ERR_TRANSPORT',
|
|
84
|
+
UNSUPPORTED: 'ERR_UNSUPPORTED',
|
|
85
|
+
INVALID_ARGUMENT: 'ERR_INVALID_ARGUMENT',
|
|
86
|
+
NOT_FOUND: 'ERR_NOT_FOUND',
|
|
87
|
+
CONFLICT: 'ERR_CONFLICT',
|
|
88
|
+
INTERNAL: 'ERR_INTERNAL',
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
const POLICY_PROFILE_ID = 'hyper-frame-local-v1';
|
|
92
|
+
const POLICY_ID = 'hyper-frame-local';
|
|
93
|
+
const POLICY_BASELINE_ID = 'hyper-frame-local';
|
|
94
|
+
const POLICY_SCHEMA_VERSION = 1;
|
|
95
|
+
|
|
96
|
+
function createBrowserBoxError(message, {
|
|
97
|
+
code = ERROR_CODES.BASE,
|
|
98
|
+
retriable = false,
|
|
99
|
+
status,
|
|
100
|
+
cause,
|
|
101
|
+
...details
|
|
102
|
+
} = {}) {
|
|
103
|
+
return new BrowserBoxError(message, {
|
|
104
|
+
code,
|
|
105
|
+
retriable,
|
|
106
|
+
...(status === undefined ? {} : { status }),
|
|
107
|
+
...(cause === undefined ? {} : { cause }),
|
|
108
|
+
...details,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function throwInvalidArgument(message, details = {}) {
|
|
113
|
+
throw createBrowserBoxError(message, {
|
|
114
|
+
code: ERROR_CODES.INVALID_ARGUMENT,
|
|
115
|
+
status: 400,
|
|
116
|
+
...details,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function assertPlainObject(value, label) {
|
|
121
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
122
|
+
throwInvalidArgument(`hyper-frame ${label} requires an object.`, {
|
|
123
|
+
label,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
return value;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function assertNonEmptyString(value, label) {
|
|
130
|
+
const normalized = typeof value === 'string' ? value.trim() : '';
|
|
131
|
+
if (!normalized) {
|
|
132
|
+
throwInvalidArgument(`hyper-frame ${label} requires a non-empty string.`, {
|
|
133
|
+
label,
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
return normalized;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function normalizeTabInfo(tab, fallbackIndex = null) {
|
|
140
|
+
if (!tab || typeof tab !== 'object') {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
const id = [tab.id, tab.tabId, tab.targetId].find((candidate) =>
|
|
144
|
+
typeof candidate === 'string' && candidate.length > 0
|
|
145
|
+
) || '';
|
|
146
|
+
const faviconDataURI = typeof tab.faviconDataURI === 'string' && tab.faviconDataURI.length > 0
|
|
147
|
+
? tab.faviconDataURI
|
|
148
|
+
: (typeof tab.favicon === 'string' && tab.favicon.startsWith('data:') ? tab.favicon : null);
|
|
149
|
+
return {
|
|
150
|
+
id,
|
|
151
|
+
index: Number.isInteger(tab.index) ? tab.index : (Number.isInteger(fallbackIndex) ? fallbackIndex : 0),
|
|
152
|
+
active: Boolean(tab.active ?? tab.isActive ?? tab.selected),
|
|
153
|
+
url: typeof tab.url === 'string' ? tab.url : '',
|
|
154
|
+
title: typeof tab.title === 'string' ? tab.title : '',
|
|
155
|
+
canGoBack: Boolean(tab.canGoBack),
|
|
156
|
+
canGoForward: Boolean(tab.canGoForward),
|
|
157
|
+
loading: Boolean(tab.loading ?? tab.isLoading),
|
|
158
|
+
hasFavicon: Boolean(tab.hasFavicon ?? faviconDataURI ?? tab.favicon),
|
|
159
|
+
isDefaultFavicon: Boolean(tab.isDefaultFavicon),
|
|
160
|
+
faviconDataURI,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function coerceNumber(...candidates) {
|
|
165
|
+
for (const candidate of candidates) {
|
|
166
|
+
const value = Number(candidate);
|
|
167
|
+
if (Number.isFinite(value)) {
|
|
168
|
+
return value;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function normalizePageMetrics(metrics) {
|
|
175
|
+
const input = metrics && typeof metrics === 'object' ? metrics : {};
|
|
176
|
+
return {
|
|
177
|
+
viewportWidth: coerceNumber(input.viewportWidth, input.innerWidth, input.width) ?? 0,
|
|
178
|
+
viewportHeight: coerceNumber(input.viewportHeight, input.innerHeight, input.height) ?? 0,
|
|
179
|
+
...(coerceNumber(input.devicePixelRatio, globalThis.devicePixelRatio) === undefined
|
|
180
|
+
? {}
|
|
181
|
+
: { devicePixelRatio: coerceNumber(input.devicePixelRatio, globalThis.devicePixelRatio) }),
|
|
182
|
+
...(coerceNumber(input.scrollX, input.scrollLeft) === undefined ? {} : { scrollX: coerceNumber(input.scrollX, input.scrollLeft) }),
|
|
183
|
+
...(coerceNumber(input.scrollY, input.scrollTop) === undefined ? {} : { scrollY: coerceNumber(input.scrollY, input.scrollTop) }),
|
|
184
|
+
...(coerceNumber(input.documentWidth, input.availWidth, input.scrollWidth) === undefined
|
|
185
|
+
? {}
|
|
186
|
+
: { documentWidth: coerceNumber(input.documentWidth, input.availWidth, input.scrollWidth) }),
|
|
187
|
+
...(coerceNumber(input.documentHeight, input.availHeight, input.scrollHeight) === undefined
|
|
188
|
+
? {}
|
|
189
|
+
: { documentHeight: coerceNumber(input.documentHeight, input.availHeight, input.scrollHeight) }),
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function base64EncodeBytes(bytes) {
|
|
194
|
+
let binary = '';
|
|
195
|
+
const chunkSize = 0x8000;
|
|
196
|
+
for (let index = 0; index < bytes.length; index += chunkSize) {
|
|
197
|
+
const slice = bytes.subarray(index, index + chunkSize);
|
|
198
|
+
binary += String.fromCharCode(...slice);
|
|
199
|
+
}
|
|
200
|
+
return btoa(binary);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function normalizeCaptureResult(result, format = 'png') {
|
|
204
|
+
if (typeof result === 'string') {
|
|
205
|
+
if (result.startsWith('data:')) {
|
|
206
|
+
return result;
|
|
207
|
+
}
|
|
208
|
+
const mimeType = format === 'jpeg' ? 'image/jpeg' : 'image/png';
|
|
209
|
+
return `data:${mimeType};base64,${result}`;
|
|
210
|
+
}
|
|
211
|
+
if (result instanceof ArrayBuffer) {
|
|
212
|
+
const mimeType = format === 'jpeg' ? 'image/jpeg' : 'image/png';
|
|
213
|
+
return `data:${mimeType};base64,${base64EncodeBytes(new Uint8Array(result))}`;
|
|
214
|
+
}
|
|
215
|
+
if (typeof Blob !== 'undefined' && result instanceof Blob) {
|
|
216
|
+
const buffer = await result.arrayBuffer();
|
|
217
|
+
return normalizeCaptureResult(buffer, format);
|
|
218
|
+
}
|
|
219
|
+
if (ArrayBuffer.isView(result)) {
|
|
220
|
+
const mimeType = format === 'jpeg' ? 'image/jpeg' : 'image/png';
|
|
221
|
+
return `data:${mimeType};base64,${base64EncodeBytes(new Uint8Array(result.buffer, result.byteOffset, result.byteLength))}`;
|
|
222
|
+
}
|
|
223
|
+
if (result && typeof result === 'object') {
|
|
224
|
+
if (typeof result.dataURI === 'string') {
|
|
225
|
+
return normalizeCaptureResult(result.dataURI, format);
|
|
226
|
+
}
|
|
227
|
+
if (typeof result.dataUrl === 'string') {
|
|
228
|
+
return normalizeCaptureResult(result.dataUrl, format);
|
|
229
|
+
}
|
|
230
|
+
if (typeof result.base64 === 'string') {
|
|
231
|
+
return normalizeCaptureResult(result.base64, format);
|
|
232
|
+
}
|
|
233
|
+
if (typeof result.data === 'string') {
|
|
234
|
+
return normalizeCaptureResult(result.data, format);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
throw createBrowserBoxError('hyper-frame capture returned an unsupported result.', {
|
|
238
|
+
code: ERROR_CODES.INTERNAL,
|
|
239
|
+
status: 500,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function extractEvaluateValue(result) {
|
|
244
|
+
if (typeof result === 'string') {
|
|
245
|
+
return result;
|
|
246
|
+
}
|
|
247
|
+
if (typeof result?.result?.value === 'string') {
|
|
248
|
+
return result.result.value;
|
|
249
|
+
}
|
|
250
|
+
if (typeof result?.value === 'string') {
|
|
251
|
+
return result.value;
|
|
252
|
+
}
|
|
253
|
+
return '';
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function normalizePreviewResult(target, resolution) {
|
|
257
|
+
const source = resolution && typeof resolution === 'object' ? resolution : {};
|
|
258
|
+
const selector = typeof target?.selector === 'string'
|
|
259
|
+
? target.selector
|
|
260
|
+
: (typeof source.selector === 'string' ? source.selector : undefined);
|
|
261
|
+
const matches = Number.isInteger(source.matchCount)
|
|
262
|
+
? source.matchCount
|
|
263
|
+
: (Array.isArray(source.matches) ? source.matches.length : 0);
|
|
264
|
+
const sample = Array.isArray(source.sample)
|
|
265
|
+
? source.sample
|
|
266
|
+
.filter((entry) => entry && typeof entry === 'object')
|
|
267
|
+
.map((entry) => ({
|
|
268
|
+
...(typeof entry.text === 'string' ? { text: entry.text } : {}),
|
|
269
|
+
...(typeof entry.href === 'string' ? { href: entry.href } : {}),
|
|
270
|
+
}))
|
|
271
|
+
: undefined;
|
|
272
|
+
return {
|
|
273
|
+
...(selector ? { selector } : {}),
|
|
274
|
+
matches,
|
|
275
|
+
...(sample && sample.length > 0 ? { sample } : {}),
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function normalizeExtractResult(target, result) {
|
|
280
|
+
const selector = typeof target?.selector === 'string'
|
|
281
|
+
? target.selector
|
|
282
|
+
: (typeof result?.selector === 'string' ? result.selector : undefined);
|
|
283
|
+
const rawItems = Array.isArray(result)
|
|
284
|
+
? result
|
|
285
|
+
: (Array.isArray(result?.items) ? result.items : []);
|
|
286
|
+
const items = rawItems
|
|
287
|
+
.filter((entry) => entry && typeof entry === 'object')
|
|
288
|
+
.map((entry) => ({
|
|
289
|
+
...(typeof entry.text === 'string' ? { text: entry.text } : {}),
|
|
290
|
+
...(typeof entry.href === 'string' ? { href: entry.href } : {}),
|
|
291
|
+
...(typeof entry.html === 'string' ? { html: entry.html } : {}),
|
|
292
|
+
}));
|
|
293
|
+
return {
|
|
294
|
+
...(selector ? { selector } : {}),
|
|
295
|
+
items,
|
|
296
|
+
count: Number.isInteger(result?.count) ? result.count : items.length,
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function normalizeRawSelection(rawSelection) {
|
|
301
|
+
const input = rawSelection && typeof rawSelection === 'object' ? rawSelection : {};
|
|
302
|
+
const selectors = Array.isArray(input.selectors)
|
|
303
|
+
? input.selectors.filter((value) => typeof value === 'string' && value.length > 0)
|
|
304
|
+
: (typeof input.selector === 'string' && input.selector.length > 0 ? [input.selector] : []);
|
|
305
|
+
return {
|
|
306
|
+
...(typeof input.selector === 'string' && input.selector.length > 0 ? { selector: input.selector } : {}),
|
|
307
|
+
...(selectors.length > 0 ? { selectors } : {}),
|
|
308
|
+
...(typeof input.text === 'string' ? { text: input.text } : {}),
|
|
309
|
+
...(typeof input.href === 'string' ? { href: input.href || null } : {}),
|
|
310
|
+
...(typeof input.htmlSnippet === 'string'
|
|
311
|
+
? { htmlSnippet: input.htmlSnippet }
|
|
312
|
+
: (typeof input.html === 'string' ? { htmlSnippet: input.html } : {})),
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function normalizeActionResult(action, value) {
|
|
317
|
+
return {
|
|
318
|
+
ok: true,
|
|
319
|
+
action,
|
|
320
|
+
...(value === undefined ? {} : { value }),
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function createLocalPolicySnapshot(capabilities, metadata = {}) {
|
|
325
|
+
const timestamp = new Date().toISOString();
|
|
326
|
+
return {
|
|
327
|
+
schemaVersion: POLICY_SCHEMA_VERSION,
|
|
328
|
+
policyProfile: POLICY_PROFILE_ID,
|
|
329
|
+
policyId: POLICY_ID,
|
|
330
|
+
baselineId: POLICY_BASELINE_ID,
|
|
331
|
+
policyVersion: 1,
|
|
332
|
+
issuedAt: timestamp,
|
|
333
|
+
updatedAt: timestamp,
|
|
334
|
+
...metadata,
|
|
335
|
+
apiCapabilities: clonePolicyTree(capabilities),
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function createTabsNamespace(instance) {
|
|
340
|
+
return Object.freeze({
|
|
341
|
+
async list() {
|
|
342
|
+
const tabs = await instance.callApi('getTabs');
|
|
343
|
+
return Array.isArray(tabs)
|
|
344
|
+
? tabs.map((tab, index) => normalizeTabInfo(tab, index)).filter(Boolean)
|
|
345
|
+
: [];
|
|
346
|
+
},
|
|
347
|
+
async getActive() {
|
|
348
|
+
return instance._getActiveTabInfo();
|
|
349
|
+
},
|
|
350
|
+
async create(input = {}) {
|
|
351
|
+
assertPlainObject(input, 'tabs.create(input)');
|
|
352
|
+
const url = typeof input.url === 'string' ? input.url : '';
|
|
353
|
+
const shouldActivate = input.active !== false;
|
|
354
|
+
const previousActiveTab = shouldActivate ? null : await instance._getActiveTabInfo();
|
|
355
|
+
const beforeCount = await instance.callApi('getTabCount');
|
|
356
|
+
await instance.callApi('createTab', url);
|
|
357
|
+
await instance.callApi('waitForTabCount', beforeCount + 1, {
|
|
358
|
+
timeoutMs: instance.requestTimeoutMs,
|
|
359
|
+
});
|
|
360
|
+
const tabs = await this.list();
|
|
361
|
+
const createdTab = tabs[tabs.length - 1] || null;
|
|
362
|
+
if (!shouldActivate && previousActiveTab?.id) {
|
|
363
|
+
await instance.callApi('switchToTabById', previousActiveTab.id);
|
|
364
|
+
}
|
|
365
|
+
return createdTab;
|
|
366
|
+
},
|
|
367
|
+
async activate(tabId) {
|
|
368
|
+
return instance.callApi('switchToTabById', assertNonEmptyString(tabId, 'tabs.activate(tabId)'));
|
|
369
|
+
},
|
|
370
|
+
async close(tabId) {
|
|
371
|
+
return instance.callApi('closeTabById', assertNonEmptyString(tabId, 'tabs.close(tabId)'));
|
|
372
|
+
},
|
|
373
|
+
async closeAll() {
|
|
374
|
+
return instance.callApi('closeAllTabs', { keep: 0 });
|
|
375
|
+
},
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function createPageNamespace(instance) {
|
|
380
|
+
return Object.freeze({
|
|
381
|
+
async navigate(url, opts = {}) {
|
|
382
|
+
return instance.callApi('navigateTo', assertNonEmptyString(url, 'page.navigate(url)'), opts);
|
|
383
|
+
},
|
|
384
|
+
async reload() {
|
|
385
|
+
return instance.callApi('reload');
|
|
386
|
+
},
|
|
387
|
+
async back() {
|
|
388
|
+
return instance.callApi('goBack');
|
|
389
|
+
},
|
|
390
|
+
async forward() {
|
|
391
|
+
return instance.callApi('goForward');
|
|
392
|
+
},
|
|
393
|
+
async stop() {
|
|
394
|
+
return instance.callApi('stop');
|
|
395
|
+
},
|
|
396
|
+
async url() {
|
|
397
|
+
return (await instance._getActiveTabInfo('page.read'))?.url || '';
|
|
398
|
+
},
|
|
399
|
+
async title() {
|
|
400
|
+
return (await instance._getActiveTabInfo('page.read'))?.title || '';
|
|
401
|
+
},
|
|
402
|
+
async favicon() {
|
|
403
|
+
const activeTab = await instance._getActiveTabInfo('page.read');
|
|
404
|
+
return activeTab?.faviconDataURI || activeTab?.favicon || null;
|
|
405
|
+
},
|
|
406
|
+
async metrics() {
|
|
407
|
+
return normalizePageMetrics(await instance.callApi('getScreenMetrics'));
|
|
408
|
+
},
|
|
409
|
+
async text(options = {}) {
|
|
410
|
+
return instance._getPageText(options);
|
|
411
|
+
},
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function createCaptureNamespace(instance) {
|
|
416
|
+
return Object.freeze({
|
|
417
|
+
async enable(enabled = true) {
|
|
418
|
+
instance._assertCapability('capture.frame');
|
|
419
|
+
return instance.callApi('frameCapture', Boolean(enabled));
|
|
420
|
+
},
|
|
421
|
+
async next() {
|
|
422
|
+
instance._assertCapability('capture.frame');
|
|
423
|
+
return instance.callApi('getFrame');
|
|
424
|
+
},
|
|
425
|
+
async frame(options = {}) {
|
|
426
|
+
instance._assertCapability('capture.frame');
|
|
427
|
+
return normalizeCaptureResult(
|
|
428
|
+
await instance.callApi('captureFrame', { ...options, scope: 'frame' }),
|
|
429
|
+
options?.format,
|
|
430
|
+
);
|
|
431
|
+
},
|
|
432
|
+
async viewport(options = {}) {
|
|
433
|
+
instance._assertCapability('capture.viewport');
|
|
434
|
+
return normalizeCaptureResult(
|
|
435
|
+
await instance.callApi('captureFrame', { ...options, scope: 'viewport' }),
|
|
436
|
+
options?.format,
|
|
437
|
+
);
|
|
438
|
+
},
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function cloneJsonValue(value) {
|
|
443
|
+
if (value === undefined) {
|
|
444
|
+
return undefined;
|
|
445
|
+
}
|
|
446
|
+
return JSON.parse(JSON.stringify(value));
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function generateOpaqueId(prefix = 'bbx') {
|
|
450
|
+
const token = Math.random().toString(36).slice(2, 10);
|
|
451
|
+
return `${prefix}-${Date.now()}-${token}`;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function scheduleMicrotask(callback) {
|
|
455
|
+
if (typeof globalThis.queueMicrotask === 'function') {
|
|
456
|
+
globalThis.queueMicrotask(callback);
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
Promise.resolve().then(callback);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function isDomNode(value) {
|
|
463
|
+
return Boolean(value) && typeof value === 'object' && typeof value.nodeType === 'number';
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function normalizeAugmentSpec(spec) {
|
|
467
|
+
assertPlainObject(spec, 'augment(spec)');
|
|
468
|
+
const kind = assertNonEmptyString(spec.kind || 'custom', 'augment(spec.kind)');
|
|
469
|
+
const space = assertNonEmptyString(spec.space || 'session', 'augment(spec.space)');
|
|
470
|
+
return {
|
|
471
|
+
id: typeof spec.id === 'string' && spec.id.trim() ? spec.id.trim() : generateOpaqueId('bbx-augment'),
|
|
472
|
+
kind,
|
|
473
|
+
space,
|
|
474
|
+
position: typeof spec.position === 'string' ? spec.position : undefined,
|
|
475
|
+
target: spec.target && typeof spec.target === 'object' ? cloneJsonValue(spec.target) : undefined,
|
|
476
|
+
content: normalizeAugmentContent(spec.content),
|
|
477
|
+
style: spec.style,
|
|
478
|
+
interactive: Boolean(spec.interactive),
|
|
479
|
+
visible: spec.visible !== false,
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function normalizeAugmentContent(content) {
|
|
484
|
+
if (content === undefined || content === null || isDomNode(content)) {
|
|
485
|
+
return content;
|
|
486
|
+
}
|
|
487
|
+
if (typeof content === 'string') {
|
|
488
|
+
return { type: 'html', html: content };
|
|
489
|
+
}
|
|
490
|
+
if (content && typeof content === 'object' && !Array.isArray(content)) {
|
|
491
|
+
if (typeof content.type === 'string') {
|
|
492
|
+
if (content.type === 'text' && typeof content.text === 'string') {
|
|
493
|
+
return { type: 'text', text: content.text };
|
|
494
|
+
}
|
|
495
|
+
if (content.type === 'html' && typeof content.html === 'string') {
|
|
496
|
+
return { type: 'html', html: content.html };
|
|
497
|
+
}
|
|
498
|
+
if (content.type === 'json' && content.data !== undefined) {
|
|
499
|
+
return { type: 'json', data: cloneJsonValue(content.data) };
|
|
500
|
+
}
|
|
501
|
+
throwInvalidArgument('hyper-frame augment content type is invalid.', {
|
|
502
|
+
contentType: content.type,
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
if (typeof content.html === 'string') {
|
|
506
|
+
return { type: 'html', html: content.html };
|
|
507
|
+
}
|
|
508
|
+
return { type: 'json', data: cloneJsonValue(content) };
|
|
509
|
+
}
|
|
510
|
+
if (Array.isArray(content)) {
|
|
511
|
+
return { type: 'json', data: cloneJsonValue(content) };
|
|
512
|
+
}
|
|
513
|
+
throwInvalidArgument('hyper-frame augment content must be text/html/json compatible.', {
|
|
514
|
+
contentType: typeof content,
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function normalizeAugmentInfo(spec) {
|
|
519
|
+
return {
|
|
520
|
+
id: spec.id,
|
|
521
|
+
kind: spec.kind,
|
|
522
|
+
space: spec.space,
|
|
523
|
+
...(spec.position === undefined ? {} : { position: spec.position }),
|
|
524
|
+
...(spec.target === undefined ? {} : { target: cloneJsonValue(spec.target) }),
|
|
525
|
+
interactive: Boolean(spec.interactive),
|
|
526
|
+
visible: spec.visible !== false,
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function createAugmentApi(instance) {
|
|
531
|
+
const augment = async (spec) => instance._createAugment(spec);
|
|
532
|
+
augment.update = async (id, patch) => instance._updateAugment(id, patch);
|
|
533
|
+
augment.remove = async (id) => instance._removeAugment(id);
|
|
534
|
+
augment.list = async () => instance._listAugments();
|
|
535
|
+
return Object.freeze(augment);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function createPatternHandle(instance, pattern, previewId) {
|
|
539
|
+
return Object.freeze({
|
|
540
|
+
get selector() {
|
|
541
|
+
return typeof pattern?.selector === 'string' ? pattern.selector : '';
|
|
542
|
+
},
|
|
543
|
+
async preview() {
|
|
544
|
+
return instance._previewSelectionPattern(pattern, previewId);
|
|
545
|
+
},
|
|
546
|
+
async extract(options = {}) {
|
|
547
|
+
return instance._extractSelection(pattern, options);
|
|
548
|
+
},
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function createSelectionHandle(instance, rawSelection) {
|
|
553
|
+
const previewId = generateOpaqueId('bbx-select-preview');
|
|
554
|
+
return Object.freeze({
|
|
555
|
+
async getRaw() {
|
|
556
|
+
return normalizeRawSelection(cloneJsonValue(rawSelection));
|
|
557
|
+
},
|
|
558
|
+
async generalize() {
|
|
559
|
+
const pattern = await instance._generalizeSelection(rawSelection);
|
|
560
|
+
return createPatternHandle(instance, pattern, previewId);
|
|
561
|
+
},
|
|
562
|
+
async preview() {
|
|
563
|
+
return instance._previewSelectionPattern(rawSelection, previewId);
|
|
564
|
+
},
|
|
565
|
+
async extract(options = {}) {
|
|
566
|
+
return instance._extractSelection(rawSelection, options);
|
|
567
|
+
},
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
function createSessionFacade(instance) {
|
|
572
|
+
const session = {
|
|
573
|
+
health: (options) => instance.health(options),
|
|
574
|
+
refresh: () => instance.refresh(),
|
|
575
|
+
disconnect: () => instance.disconnect(),
|
|
576
|
+
observe: (config) => instance.observe(config),
|
|
577
|
+
act: (action) => instance.act(action),
|
|
578
|
+
capabilities: () => instance.capabilities(),
|
|
579
|
+
select: (options) => instance.select(options),
|
|
580
|
+
frameCapture: (enabled = true) => instance.frameCapture(enabled),
|
|
581
|
+
getFrame: () => instance.getFrame(),
|
|
582
|
+
cleanSlate: (url) => instance.cleanSlate(url),
|
|
583
|
+
};
|
|
584
|
+
|
|
585
|
+
Object.defineProperties(session, {
|
|
586
|
+
id: readOnlyProperty(() => instance.routingMid || null),
|
|
587
|
+
usable: readOnlyProperty(() => instance._usable),
|
|
588
|
+
transport: readOnlyProperty(() => instance._transportMode),
|
|
589
|
+
ready: readOnlyProperty(() => instance._isReady),
|
|
590
|
+
tabs: readOnlyProperty(() => instance.tabs),
|
|
591
|
+
page: readOnlyProperty(() => instance.page),
|
|
592
|
+
capture: readOnlyProperty(() => instance.capture),
|
|
593
|
+
augment: readOnlyProperty(() => instance.augment),
|
|
594
|
+
policy: readOnlyProperty(() => instance.policy),
|
|
595
|
+
});
|
|
596
|
+
|
|
597
|
+
return Object.freeze(session);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const POLICY_DEFAULTS = {
|
|
601
|
+
tabs: { read: true, write: true },
|
|
602
|
+
page: { read: true, navigate: true },
|
|
603
|
+
act: {
|
|
604
|
+
navigate: true,
|
|
605
|
+
click: true,
|
|
606
|
+
type: true,
|
|
607
|
+
evaluate: true,
|
|
608
|
+
wait: true,
|
|
609
|
+
},
|
|
610
|
+
augment: {
|
|
611
|
+
read: false,
|
|
612
|
+
write: false,
|
|
613
|
+
page: false,
|
|
614
|
+
viewport: false,
|
|
615
|
+
chrome: false,
|
|
616
|
+
session: false,
|
|
617
|
+
},
|
|
618
|
+
capture: { frame: false, viewport: false, stream: false },
|
|
619
|
+
select: { use: false, extract: false },
|
|
620
|
+
events: { read: true },
|
|
621
|
+
policy: { read: true },
|
|
622
|
+
modals: { read: true, respond: true },
|
|
623
|
+
};
|
|
624
|
+
|
|
625
|
+
const INTERACTION_MODE_PRESETS = {
|
|
626
|
+
'view-only': {
|
|
627
|
+
tabs: { write: false },
|
|
628
|
+
page: { navigate: false },
|
|
629
|
+
act: {
|
|
630
|
+
navigate: false,
|
|
631
|
+
click: false,
|
|
632
|
+
type: false,
|
|
633
|
+
evaluate: false,
|
|
634
|
+
wait: false,
|
|
635
|
+
},
|
|
636
|
+
},
|
|
637
|
+
limited: {
|
|
638
|
+
tabs: { write: false },
|
|
639
|
+
page: { navigate: true },
|
|
640
|
+
act: {
|
|
641
|
+
navigate: true,
|
|
642
|
+
click: true,
|
|
643
|
+
type: true,
|
|
644
|
+
evaluate: false,
|
|
645
|
+
wait: true,
|
|
646
|
+
},
|
|
647
|
+
},
|
|
648
|
+
full: {},
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
const IMPLEMENTED_CAPABILITIES = {
|
|
652
|
+
'tabs.read': true,
|
|
653
|
+
'tabs.write': true,
|
|
654
|
+
'page.read': true,
|
|
655
|
+
'page.navigate': true,
|
|
656
|
+
'act.navigate': true,
|
|
657
|
+
'act.click': true,
|
|
658
|
+
'act.type': true,
|
|
659
|
+
'act.evaluate': true,
|
|
660
|
+
'act.wait': true,
|
|
661
|
+
'augment.read': true,
|
|
662
|
+
'augment.write': true,
|
|
663
|
+
'augment.page': true,
|
|
664
|
+
'augment.viewport': true,
|
|
665
|
+
'augment.chrome': true,
|
|
666
|
+
'augment.session': true,
|
|
667
|
+
'capture.frame': true,
|
|
668
|
+
'capture.viewport': true,
|
|
669
|
+
'capture.stream': false,
|
|
670
|
+
'select.use': true,
|
|
671
|
+
'select.extract': true,
|
|
672
|
+
'events.read': true,
|
|
673
|
+
'policy.read': true,
|
|
674
|
+
'modals.read': true,
|
|
675
|
+
'modals.respond': true,
|
|
676
|
+
};
|
|
677
|
+
|
|
678
|
+
const METHOD_CAPABILITY_MAP = {
|
|
679
|
+
getTabs: ['tabs.read'],
|
|
680
|
+
getActiveTabIndex: ['tabs.read'],
|
|
681
|
+
getTabCount: ['tabs.read'],
|
|
682
|
+
getFavicons: ['tabs.read'],
|
|
683
|
+
waitForNonDefaultFavicon: ['tabs.read'],
|
|
684
|
+
waitForTabCount: ['tabs.read'],
|
|
685
|
+
waitForTabUrl: ['tabs.read'],
|
|
686
|
+
createTab: ['tabs.write'],
|
|
687
|
+
createTabs: ['tabs.write'],
|
|
688
|
+
closeTab: ['tabs.write'],
|
|
689
|
+
closeTabById: ['tabs.write'],
|
|
690
|
+
closeAllTabs: ['tabs.write'],
|
|
691
|
+
switchToTab: ['tabs.write'],
|
|
692
|
+
switchToTabById: ['tabs.write'],
|
|
693
|
+
navigateTo: ['page.navigate'],
|
|
694
|
+
navigateTab: ['tabs.write', 'page.navigate'],
|
|
695
|
+
submitOmnibox: ['page.navigate'],
|
|
696
|
+
reload: ['page.navigate'],
|
|
697
|
+
goBack: ['page.navigate'],
|
|
698
|
+
goForward: ['page.navigate'],
|
|
699
|
+
stop: ['page.navigate'],
|
|
700
|
+
getPageText: ['page.read'],
|
|
701
|
+
resolvePageTarget: ['page.read'],
|
|
702
|
+
beginSelect: ['select.use'],
|
|
703
|
+
generalizeSelection: ['select.use'],
|
|
704
|
+
extractSelection: ['select.extract'],
|
|
705
|
+
captureFrame: ['capture.frame'],
|
|
706
|
+
getScreenMetrics: ['page.read'],
|
|
707
|
+
waitForSelector: ['act.wait'],
|
|
708
|
+
waitForNavigation: ['act.wait'],
|
|
709
|
+
click: ['act.click'],
|
|
710
|
+
type: ['act.type'],
|
|
711
|
+
evaluate: ['act.evaluate'],
|
|
712
|
+
uiVisible: ['page.read'],
|
|
713
|
+
allowUserToggleUI: ['page.read'],
|
|
714
|
+
getTransportDiagnostics: ['events.read'],
|
|
715
|
+
getCurrentModal: ['modals.read'],
|
|
716
|
+
respondToModal: ['modals.respond'],
|
|
717
|
+
dismissModal: ['modals.respond'],
|
|
718
|
+
frameCapture: ['capture.frame'],
|
|
719
|
+
getFrame: ['capture.frame'],
|
|
720
|
+
cleanSlate: ['tabs.write', 'page.navigate'],
|
|
721
|
+
};
|
|
722
|
+
|
|
723
|
+
const EVENT_ALIAS_MAP = {
|
|
724
|
+
'api-ready': ['api.ready'],
|
|
725
|
+
'usability-changed': ['session.usability.changed'],
|
|
726
|
+
'iframe-retry': ['session.retry'],
|
|
727
|
+
disconnected: ['session.disconnected'],
|
|
728
|
+
'tab-created': ['tab.created'],
|
|
729
|
+
'tab-attached': ['tab.attached'],
|
|
730
|
+
'tab-closed': ['tab.closed'],
|
|
731
|
+
'tab-updated': ['tab.updated'],
|
|
732
|
+
'active-tab-changed': ['tab.activated'],
|
|
733
|
+
'did-navigate': ['page.navigated'],
|
|
734
|
+
'did-start-loading': ['page.load.started'],
|
|
735
|
+
'did-stop-loading': ['page.load.stopped'],
|
|
736
|
+
'favicon-changed': ['page.favicon.changed'],
|
|
737
|
+
'policy-denied': ['policy.denied'],
|
|
738
|
+
'modal-opened': ['modal.opened'],
|
|
739
|
+
'modal-updated': ['modal.updated'],
|
|
740
|
+
'modal-closed': ['modal.closed'],
|
|
741
|
+
};
|
|
742
|
+
|
|
743
|
+
function debugBrowserBoxWebview(...args) {
|
|
744
|
+
if (globalThis.BROWSERBOX_WEBVIEW_DEBUG === true) {
|
|
745
|
+
console.log(...args);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
function clonePolicyTree(node) {
|
|
750
|
+
if (node === null || typeof node !== 'object') {
|
|
751
|
+
return node;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
const rootClone = Array.isArray(node) ? [] : {};
|
|
755
|
+
const seen = new WeakMap([[node, rootClone]]);
|
|
756
|
+
const pending = [{ source: node, clone: rootClone }];
|
|
757
|
+
|
|
758
|
+
while (pending.length > 0) {
|
|
759
|
+
const { source, clone } = pending.pop();
|
|
760
|
+
const entries = Array.isArray(source) ? source.entries() : Object.entries(source);
|
|
761
|
+
|
|
762
|
+
for (const [key, value] of entries) {
|
|
763
|
+
if (value === null || typeof value !== 'object') {
|
|
764
|
+
clone[key] = value;
|
|
765
|
+
continue;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
const existingClone = seen.get(value);
|
|
769
|
+
if (existingClone) {
|
|
770
|
+
clone[key] = existingClone;
|
|
771
|
+
continue;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
const childClone = Array.isArray(value) ? [] : {};
|
|
775
|
+
seen.set(value, childClone);
|
|
776
|
+
clone[key] = childClone;
|
|
777
|
+
pending.push({ source: value, clone: childClone });
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
return rootClone;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
function freezePolicyTree(node) {
|
|
785
|
+
if (node === null || typeof node !== 'object') {
|
|
786
|
+
return node;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
const seen = new WeakSet();
|
|
790
|
+
const pending = [node];
|
|
791
|
+
|
|
792
|
+
while (pending.length > 0) {
|
|
793
|
+
const current = pending.pop();
|
|
794
|
+
if (seen.has(current)) {
|
|
795
|
+
continue;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
seen.add(current);
|
|
799
|
+
Object.freeze(current);
|
|
800
|
+
|
|
801
|
+
for (const value of Object.values(current)) {
|
|
802
|
+
if (value && typeof value === 'object') {
|
|
803
|
+
pending.push(value);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
return node;
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
function createPolicySnapshotView(snapshot) {
|
|
812
|
+
return freezePolicyTree(clonePolicyTree(snapshot));
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
function mergePolicyTree(base, patch) {
|
|
816
|
+
if (typeof base === 'boolean') {
|
|
817
|
+
return typeof patch === 'boolean' ? patch : base;
|
|
818
|
+
}
|
|
819
|
+
const patchObject = patch && typeof patch === 'object' && !Array.isArray(patch) ? patch : {};
|
|
820
|
+
const merged = {};
|
|
821
|
+
for (const [key, value] of Object.entries(base)) {
|
|
822
|
+
merged[key] = mergePolicyTree(value, patchObject[key]);
|
|
823
|
+
}
|
|
824
|
+
return merged;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
function flattenPolicyTree(node, prefix = '', output = {}) {
|
|
828
|
+
for (const [key, value] of Object.entries(node)) {
|
|
829
|
+
const nextPrefix = prefix ? `${prefix}.${key}` : key;
|
|
830
|
+
if (typeof value === 'boolean') {
|
|
831
|
+
output[nextPrefix] = value;
|
|
832
|
+
} else {
|
|
833
|
+
flattenPolicyTree(value, nextPrefix, output);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
return output;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
function intersectPolicyTrees(base, restriction) {
|
|
840
|
+
if (typeof base === 'boolean') {
|
|
841
|
+
return base && Boolean(restriction);
|
|
842
|
+
}
|
|
843
|
+
const patch = restriction && typeof restriction === 'object' && !Array.isArray(restriction) ? restriction : {};
|
|
844
|
+
const merged = {};
|
|
845
|
+
for (const [key, value] of Object.entries(base)) {
|
|
846
|
+
merged[key] = intersectPolicyTrees(value, patch[key]);
|
|
847
|
+
}
|
|
848
|
+
return merged;
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
function isPolicySnapshot(value) {
|
|
852
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
function extractApiCapabilities(policySnapshot) {
|
|
856
|
+
if (!isPolicySnapshot(policySnapshot)) {
|
|
857
|
+
return clonePolicyTree(POLICY_DEFAULTS);
|
|
858
|
+
}
|
|
859
|
+
const source = isPolicySnapshot(policySnapshot.apiCapabilities)
|
|
860
|
+
? policySnapshot.apiCapabilities
|
|
861
|
+
: policySnapshot;
|
|
862
|
+
return mergePolicyTree(clonePolicyTree(POLICY_DEFAULTS), source);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
function mergePolicySnapshots(serverPolicySnapshot, localPolicySnapshot) {
|
|
866
|
+
const localCapabilities = extractApiCapabilities(localPolicySnapshot);
|
|
867
|
+
const serverCapabilities = serverPolicySnapshot
|
|
868
|
+
? extractApiCapabilities(serverPolicySnapshot)
|
|
869
|
+
: clonePolicyTree(POLICY_DEFAULTS);
|
|
870
|
+
const effectiveCapabilities = intersectPolicyTrees(serverCapabilities, localCapabilities);
|
|
871
|
+
const timestamp = new Date().toISOString();
|
|
872
|
+
const base = serverPolicySnapshot && isPolicySnapshot(serverPolicySnapshot)
|
|
873
|
+
? clonePolicyTree(serverPolicySnapshot)
|
|
874
|
+
: clonePolicyTree(localPolicySnapshot);
|
|
875
|
+
return {
|
|
876
|
+
schemaVersion: Number.isInteger(base?.schemaVersion) ? base.schemaVersion : POLICY_SCHEMA_VERSION,
|
|
877
|
+
policyProfile: typeof base?.policyProfile === 'string' ? base.policyProfile : POLICY_PROFILE_ID,
|
|
878
|
+
policyId: typeof base?.policyId === 'string' ? base.policyId : POLICY_ID,
|
|
879
|
+
baselineId: typeof base?.baselineId === 'string' ? base.baselineId : POLICY_BASELINE_ID,
|
|
880
|
+
policyVersion: Number.isInteger(base?.policyVersion) ? base.policyVersion : 1,
|
|
881
|
+
issuedAt: typeof base?.issuedAt === 'string' ? base.issuedAt : timestamp,
|
|
882
|
+
updatedAt: timestamp,
|
|
883
|
+
...base,
|
|
884
|
+
apiCapabilities: effectiveCapabilities,
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
function normalizePolicyStateSnapshot(snapshot) {
|
|
889
|
+
if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) {
|
|
890
|
+
return null;
|
|
891
|
+
}
|
|
892
|
+
const candidate = snapshot.policy && typeof snapshot.policy === 'object' && !Array.isArray(snapshot.policy)
|
|
893
|
+
? snapshot.policy
|
|
894
|
+
: snapshot;
|
|
895
|
+
if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
|
|
896
|
+
return null;
|
|
897
|
+
}
|
|
898
|
+
return {
|
|
899
|
+
...clonePolicyTree(candidate),
|
|
900
|
+
apiCapabilities: extractApiCapabilities(candidate),
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
const EVENT_CAPABILITY_RULES = Object.freeze({
|
|
905
|
+
'tab-created': 'tabs.read',
|
|
906
|
+
'tab-attached': 'tabs.read',
|
|
907
|
+
'tab-closed': 'tabs.read',
|
|
908
|
+
'tab-updated': 'tabs.read',
|
|
909
|
+
'active-tab-changed': 'tabs.read',
|
|
910
|
+
'tab.created': 'tabs.read',
|
|
911
|
+
'tab.attached': 'tabs.read',
|
|
912
|
+
'tab.closed': 'tabs.read',
|
|
913
|
+
'tab.updated': 'tabs.read',
|
|
914
|
+
'tab.activated': 'tabs.read',
|
|
915
|
+
'did-navigate': 'page.read',
|
|
916
|
+
'did-start-loading': 'page.read',
|
|
917
|
+
'did-stop-loading': 'page.read',
|
|
918
|
+
'favicon-changed': 'page.read',
|
|
919
|
+
'page.navigated': 'page.read',
|
|
920
|
+
'page.load.started': 'page.read',
|
|
921
|
+
'page.load.stopped': 'page.read',
|
|
922
|
+
'page.favicon.changed': 'page.read',
|
|
923
|
+
'policy.changed': 'policy.read',
|
|
924
|
+
'modal-opened': 'modals.read',
|
|
925
|
+
'modal-updated': 'modals.read',
|
|
926
|
+
'modal-closed': 'modals.read',
|
|
927
|
+
'modal.opened': 'modals.read',
|
|
928
|
+
'modal.updated': 'modals.read',
|
|
929
|
+
'modal.closed': 'modals.read',
|
|
930
|
+
});
|
|
931
|
+
|
|
932
|
+
function createPolicyNamespace(instance) {
|
|
933
|
+
return Object.freeze({
|
|
934
|
+
async get() {
|
|
935
|
+
instance._assertCapability('policy.read');
|
|
936
|
+
return instance._getPolicySnapshotView();
|
|
937
|
+
},
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
class BrowserBoxError extends Error {
|
|
942
|
+
constructor(message, {
|
|
943
|
+
code = ERROR_CODES.BASE,
|
|
944
|
+
retriable,
|
|
945
|
+
status,
|
|
946
|
+
cause,
|
|
947
|
+
...details
|
|
948
|
+
} = {}) {
|
|
949
|
+
super(message);
|
|
950
|
+
this.name = new.target.name;
|
|
951
|
+
this.code = code;
|
|
952
|
+
if (retriable !== undefined) {
|
|
953
|
+
this.retriable = Boolean(retriable);
|
|
954
|
+
}
|
|
955
|
+
if (status !== undefined) {
|
|
956
|
+
this.status = status;
|
|
957
|
+
}
|
|
958
|
+
if (cause !== undefined) {
|
|
959
|
+
this.cause = cause;
|
|
960
|
+
}
|
|
961
|
+
Object.assign(this, details);
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
toJSON() {
|
|
965
|
+
const json = {
|
|
966
|
+
name: this.name,
|
|
967
|
+
message: this.message,
|
|
968
|
+
code: this.code,
|
|
969
|
+
};
|
|
970
|
+
for (const key of Object.keys(this)) {
|
|
971
|
+
if (!(key in json)) {
|
|
972
|
+
json[key] = this[key];
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
return json;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
class BrowserBoxPolicyError extends BrowserBoxError {
|
|
980
|
+
constructor(capability) {
|
|
981
|
+
super(`hyper-frame policy denied capability '${capability}'.`, {
|
|
982
|
+
code: ERROR_CODES.POLICY_DENIED,
|
|
983
|
+
status: 403,
|
|
984
|
+
capability,
|
|
985
|
+
source: 'embedder-policy',
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
const DEFAULT_IFRAME_ALLOW_FEATURES = [
|
|
991
|
+
'accelerometer',
|
|
992
|
+
'camera',
|
|
993
|
+
'encrypted-media',
|
|
994
|
+
'display-capture',
|
|
995
|
+
'geolocation',
|
|
996
|
+
'gyroscope',
|
|
997
|
+
'microphone',
|
|
998
|
+
'midi',
|
|
999
|
+
'clipboard-read',
|
|
1000
|
+
'clipboard-write',
|
|
1001
|
+
'web-share',
|
|
1002
|
+
'fullscreen',
|
|
1003
|
+
];
|
|
1004
|
+
const MEDIA_ALLOW_FEATURES = new Set(['camera', 'microphone', 'display-capture']);
|
|
1005
|
+
|
|
1006
|
+
function normalizeMediaPermissions(value) {
|
|
1007
|
+
return String(value || '').trim().toLowerCase() === 'none' ? 'none' : 'default';
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
function normalizeSessionUnloadWarning(value) {
|
|
1011
|
+
return String(value || '').trim().toLowerCase() === 'none' ? 'none' : 'default';
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
function normalizeBeforeUnloadBehavior(value) {
|
|
1015
|
+
const raw = String(value || '').trim().toLowerCase();
|
|
1016
|
+
if (raw === 'allow' || raw === 'leave') return 'allow';
|
|
1017
|
+
if (raw === 'block' || raw === 'remain') return 'block';
|
|
1018
|
+
return 'default';
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
function computeIframeAllow(mediaPermissions) {
|
|
1022
|
+
const features = normalizeMediaPermissions(mediaPermissions) === 'none'
|
|
1023
|
+
? DEFAULT_IFRAME_ALLOW_FEATURES.filter((f) => !MEDIA_ALLOW_FEATURES.has(f))
|
|
1024
|
+
: DEFAULT_IFRAME_ALLOW_FEATURES;
|
|
1025
|
+
return features.join('; ');
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
class HyperFrame extends HTMLElement {
|
|
1029
|
+
static get observedAttributes() {
|
|
1030
|
+
return [
|
|
1031
|
+
'login-link',
|
|
1032
|
+
'width',
|
|
1033
|
+
'height',
|
|
1034
|
+
'embedder-origin',
|
|
1035
|
+
'parent-origin', // deprecated alias for embedder-origin
|
|
1036
|
+
'request-timeout-ms',
|
|
1037
|
+
'ui-visible',
|
|
1038
|
+
'allow-user-toggle-ui',
|
|
1039
|
+
'policy',
|
|
1040
|
+
'interaction-mode',
|
|
1041
|
+
'chrome',
|
|
1042
|
+
'augment-root',
|
|
1043
|
+
'capture',
|
|
1044
|
+
'media-permissions',
|
|
1045
|
+
'session-unload-warning',
|
|
1046
|
+
'beforeunload-behavior',
|
|
1047
|
+
];
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
constructor() {
|
|
1051
|
+
super();
|
|
1052
|
+
this.attachShadow({ mode: 'open' });
|
|
1053
|
+
|
|
1054
|
+
this._shell = document.createElement('div');
|
|
1055
|
+
this._shell.className = 'bbx-shell';
|
|
1056
|
+
this.iframe = document.createElement('iframe');
|
|
1057
|
+
this.iframe.allowFullscreen = true;
|
|
1058
|
+
this.iframe.setAttribute(
|
|
1059
|
+
'allow',
|
|
1060
|
+
computeIframeAllow(this.getAttribute('media-permissions'))
|
|
1061
|
+
);
|
|
1062
|
+
this.iframe.setAttribute(
|
|
1063
|
+
'sandbox',
|
|
1064
|
+
'allow-same-origin allow-forms allow-scripts allow-top-navigation allow-top-navigation-by-user-activation allow-storage-access-by-user-activation allow-popups allow-popups-to-escape-sandbox allow-downloads allow-modals allow-pointer-lock'
|
|
1065
|
+
);
|
|
1066
|
+
|
|
1067
|
+
const style = document.createElement('style');
|
|
1068
|
+
style.textContent = `
|
|
1069
|
+
:host {
|
|
1070
|
+
display: block;
|
|
1071
|
+
margin: 0;
|
|
1072
|
+
padding: 0;
|
|
1073
|
+
overflow: hidden;
|
|
1074
|
+
outline: none;
|
|
1075
|
+
position: relative;
|
|
1076
|
+
}
|
|
1077
|
+
:host(:focus), :host(:focus-visible) {
|
|
1078
|
+
outline: none;
|
|
1079
|
+
}
|
|
1080
|
+
.bbx-shell {
|
|
1081
|
+
position: relative;
|
|
1082
|
+
width: 100%;
|
|
1083
|
+
height: 100%;
|
|
1084
|
+
overflow: hidden;
|
|
1085
|
+
background: transparent;
|
|
1086
|
+
}
|
|
1087
|
+
iframe {
|
|
1088
|
+
border: none;
|
|
1089
|
+
width: 100%;
|
|
1090
|
+
height: 100%;
|
|
1091
|
+
margin: 0;
|
|
1092
|
+
padding: 0;
|
|
1093
|
+
display: block;
|
|
1094
|
+
outline: none;
|
|
1095
|
+
position: absolute;
|
|
1096
|
+
inset: 0;
|
|
1097
|
+
}
|
|
1098
|
+
iframe:focus, iframe:focus-visible {
|
|
1099
|
+
outline: none;
|
|
1100
|
+
}
|
|
1101
|
+
.bbx-layer {
|
|
1102
|
+
position: absolute;
|
|
1103
|
+
inset: 0;
|
|
1104
|
+
pointer-events: none;
|
|
1105
|
+
}
|
|
1106
|
+
.bbx-layer[data-space="toast"] {
|
|
1107
|
+
inset: auto 0 0 auto;
|
|
1108
|
+
display: flex;
|
|
1109
|
+
flex-direction: column;
|
|
1110
|
+
align-items: flex-end;
|
|
1111
|
+
gap: 12px;
|
|
1112
|
+
padding: 12px;
|
|
1113
|
+
max-width: min(420px, 100%);
|
|
1114
|
+
}
|
|
1115
|
+
.bbx-augment {
|
|
1116
|
+
box-sizing: border-box;
|
|
1117
|
+
color: #fff;
|
|
1118
|
+
font: 13px/1.4 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
|
1119
|
+
}
|
|
1120
|
+
.bbx-augment[data-interactive="true"] {
|
|
1121
|
+
pointer-events: auto;
|
|
1122
|
+
}
|
|
1123
|
+
.bbx-augment-surface {
|
|
1124
|
+
position: absolute;
|
|
1125
|
+
inset: 0;
|
|
1126
|
+
}
|
|
1127
|
+
.bbx-augment-content {
|
|
1128
|
+
width: 100%;
|
|
1129
|
+
height: 100%;
|
|
1130
|
+
}
|
|
1131
|
+
.bbx-augment-panel,
|
|
1132
|
+
.bbx-augment-sidebar,
|
|
1133
|
+
.bbx-augment-toolbar,
|
|
1134
|
+
.bbx-augment-note,
|
|
1135
|
+
.bbx-augment-badge,
|
|
1136
|
+
.bbx-augment-custom,
|
|
1137
|
+
.bbx-augment-toast {
|
|
1138
|
+
background: rgba(24, 24, 27, 0.92);
|
|
1139
|
+
border: 1px solid rgba(255, 255, 255, 0.16);
|
|
1140
|
+
border-radius: 12px;
|
|
1141
|
+
box-shadow: 0 18px 40px rgba(0, 0, 0, 0.35);
|
|
1142
|
+
padding: 12px;
|
|
1143
|
+
backdrop-filter: blur(10px);
|
|
1144
|
+
}
|
|
1145
|
+
.bbx-augment-toolbar {
|
|
1146
|
+
border-radius: 999px;
|
|
1147
|
+
}
|
|
1148
|
+
.bbx-highlight-box {
|
|
1149
|
+
position: absolute;
|
|
1150
|
+
border: 2px solid rgba(250, 204, 21, 0.95);
|
|
1151
|
+
background: rgba(250, 204, 21, 0.18);
|
|
1152
|
+
border-radius: 8px;
|
|
1153
|
+
box-shadow: 0 0 0 1px rgba(17, 24, 39, 0.18) inset;
|
|
1154
|
+
}
|
|
1155
|
+
.bbx-highlight-box[data-tone="info"] {
|
|
1156
|
+
border-color: rgba(59, 130, 246, 0.95);
|
|
1157
|
+
background: rgba(59, 130, 246, 0.18);
|
|
1158
|
+
}
|
|
1159
|
+
.bbx-highlight-box[data-tone="success"] {
|
|
1160
|
+
border-color: rgba(34, 197, 94, 0.95);
|
|
1161
|
+
background: rgba(34, 197, 94, 0.18);
|
|
1162
|
+
}
|
|
1163
|
+
.bbx-highlight-box[data-tone="danger"] {
|
|
1164
|
+
border-color: rgba(239, 68, 68, 0.95);
|
|
1165
|
+
background: rgba(239, 68, 68, 0.18);
|
|
1166
|
+
}
|
|
1167
|
+
`;
|
|
1168
|
+
this._augmentRoots = {
|
|
1169
|
+
page: this._createAugmentLayer('page'),
|
|
1170
|
+
viewport: this._createAugmentLayer('viewport'),
|
|
1171
|
+
chrome: this._createAugmentLayer('chrome'),
|
|
1172
|
+
session: this._createAugmentLayer('session'),
|
|
1173
|
+
toast: this._createAugmentLayer('toast'),
|
|
1174
|
+
};
|
|
1175
|
+
this._shell.append(
|
|
1176
|
+
this.iframe,
|
|
1177
|
+
this._augmentRoots.page,
|
|
1178
|
+
this._augmentRoots.viewport,
|
|
1179
|
+
this._augmentRoots.chrome,
|
|
1180
|
+
this._augmentRoots.session,
|
|
1181
|
+
this._augmentRoots.toast,
|
|
1182
|
+
);
|
|
1183
|
+
this.shadowRoot.append(style, this._shell);
|
|
1184
|
+
|
|
1185
|
+
this._requestSeq = 0;
|
|
1186
|
+
this._pending = new Map();
|
|
1187
|
+
this._apiMethods = [];
|
|
1188
|
+
this._isReady = false;
|
|
1189
|
+
this._usable = false;
|
|
1190
|
+
this._readyPromise = Promise.resolve(true);
|
|
1191
|
+
this._initPingTimer = null;
|
|
1192
|
+
this._transportMode = 'unknown';
|
|
1193
|
+
this._legacyTabsCache = [];
|
|
1194
|
+
|
|
1195
|
+
// Iframe connection retry state
|
|
1196
|
+
this._iframeRetryCount = 0;
|
|
1197
|
+
this._iframeRetryMax = 5;
|
|
1198
|
+
this._iframeRetryPingThreshold = 30; // pings (1s each) before retry — covers ~90s cold starts
|
|
1199
|
+
this._initPingCount = 0;
|
|
1200
|
+
this._reconnectStopped = false;
|
|
1201
|
+
this._silentRecoveryUsed = false;
|
|
1202
|
+
this._silentRecoveryParam = 'bbx_embed_retry';
|
|
1203
|
+
|
|
1204
|
+
// Mid routing durability handshake state
|
|
1205
|
+
this._routingMid = '';
|
|
1206
|
+
this._midStorageKey = 'bbx.embedder.mid';
|
|
1207
|
+
this._midSyncAcked = false;
|
|
1208
|
+
this._midSyncTimer = null;
|
|
1209
|
+
this._midSyncAttempt = 0;
|
|
1210
|
+
this._midSyncMaxAttempts = 90;
|
|
1211
|
+
this._midSyncIntervalMs = 1000;
|
|
1212
|
+
|
|
1213
|
+
// UI config sync state (embedder → BrowserBox iframe)
|
|
1214
|
+
this._uiSyncAcked = false;
|
|
1215
|
+
this._serverPolicySnapshot = null;
|
|
1216
|
+
this._policySnapshot = this._resolvePolicySnapshot();
|
|
1217
|
+
this._capabilityMap = this._buildCapabilityMap(this._policySnapshot);
|
|
1218
|
+
this._policySnapshotCache = {
|
|
1219
|
+
source: null,
|
|
1220
|
+
value: null,
|
|
1221
|
+
};
|
|
1222
|
+
this._eventSubscribers = new Set();
|
|
1223
|
+
this._eventSeq = 0;
|
|
1224
|
+
this._augmentRegistry = new Map();
|
|
1225
|
+
this._pageAugmentRefreshScheduled = false;
|
|
1226
|
+
this._resizeObserver = null;
|
|
1227
|
+
this._lastError = null;
|
|
1228
|
+
this._frameBootstrapTimer = null;
|
|
1229
|
+
this._frameBootstrapInFlight = null;
|
|
1230
|
+
this._frameBootstrapRetryTimer = null;
|
|
1231
|
+
this._frameBootstrapRetryRemaining = 0;
|
|
1232
|
+
this._frameBootstrapEpoch = 0;
|
|
1233
|
+
this._lastSuccessfulBootstrapAt = 0;
|
|
1234
|
+
this._iframeViewportKickTimer = null;
|
|
1235
|
+
this._resizeBootstrapTimer = null;
|
|
1236
|
+
this._lastResizeWidth = -1;
|
|
1237
|
+
this._lastResizeHeight = -1;
|
|
1238
|
+
this._visibilityPollTimer = null;
|
|
1239
|
+
this._lastEffectiveVisibility = null;
|
|
1240
|
+
this._deferredVisibilityRecheckTimer = null;
|
|
1241
|
+
|
|
1242
|
+
this._boundMessage = this._handleMessage.bind(this);
|
|
1243
|
+
this._boundLoad = this._handleLoad.bind(this);
|
|
1244
|
+
this._boundResize = this._handleResize.bind(this);
|
|
1245
|
+
this._boundVisibilityChange = () => this._handleResumeTrigger('document-visibility');
|
|
1246
|
+
this._boundPageShow = () => this._handleResumeTrigger('page-show');
|
|
1247
|
+
this._boundWindowFocus = () => this._handleResumeTrigger('window-focus');
|
|
1248
|
+
this._resetReadyPromise();
|
|
1249
|
+
this.tabs = createTabsNamespace(this);
|
|
1250
|
+
this.page = createPageNamespace(this);
|
|
1251
|
+
this.capture = createCaptureNamespace(this);
|
|
1252
|
+
this.augment = createAugmentApi(this);
|
|
1253
|
+
this.policy = createPolicyNamespace(this);
|
|
1254
|
+
this.session = createSessionFacade(this);
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
connectedCallback() {
|
|
1258
|
+
window.addEventListener('message', this._boundMessage);
|
|
1259
|
+
window.addEventListener('resize', this._boundResize);
|
|
1260
|
+
window.addEventListener('pageshow', this._boundPageShow);
|
|
1261
|
+
window.addEventListener('focus', this._boundWindowFocus);
|
|
1262
|
+
document.addEventListener('visibilitychange', this._boundVisibilityChange);
|
|
1263
|
+
this.iframe.addEventListener('load', this._boundLoad);
|
|
1264
|
+
if (!this._resizeObserver && typeof ResizeObserver === 'function') {
|
|
1265
|
+
this._resizeObserver = new ResizeObserver(() => this._handleResize());
|
|
1266
|
+
this._resizeObserver.observe(this);
|
|
1267
|
+
}
|
|
1268
|
+
this._startVisibilityPolling();
|
|
1269
|
+
this.updateIframe();
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
disconnectedCallback() {
|
|
1273
|
+
window.removeEventListener('message', this._boundMessage);
|
|
1274
|
+
window.removeEventListener('resize', this._boundResize);
|
|
1275
|
+
window.removeEventListener('pageshow', this._boundPageShow);
|
|
1276
|
+
window.removeEventListener('focus', this._boundWindowFocus);
|
|
1277
|
+
document.removeEventListener('visibilitychange', this._boundVisibilityChange);
|
|
1278
|
+
this.iframe.removeEventListener('load', this._boundLoad);
|
|
1279
|
+
this._resizeObserver?.disconnect?.();
|
|
1280
|
+
this._resizeObserver = null;
|
|
1281
|
+
this._invalidateFrameBootstrap('disconnected');
|
|
1282
|
+
if (this._iframeViewportKickTimer) {
|
|
1283
|
+
clearTimeout(this._iframeViewportKickTimer);
|
|
1284
|
+
this._iframeViewportKickTimer = null;
|
|
1285
|
+
}
|
|
1286
|
+
if (this._resizeBootstrapTimer) {
|
|
1287
|
+
clearTimeout(this._resizeBootstrapTimer);
|
|
1288
|
+
this._resizeBootstrapTimer = null;
|
|
1289
|
+
}
|
|
1290
|
+
if (this._deferredVisibilityRecheckTimer) {
|
|
1291
|
+
clearTimeout(this._deferredVisibilityRecheckTimer);
|
|
1292
|
+
this._deferredVisibilityRecheckTimer = null;
|
|
1293
|
+
}
|
|
1294
|
+
this._stopVisibilityPolling();
|
|
1295
|
+
this._stopInitPing();
|
|
1296
|
+
this._stopMidSync();
|
|
1297
|
+
this._rejectPending(createBrowserBoxError('hyper-frame disconnected.', {
|
|
1298
|
+
code: ERROR_CODES.TRANSPORT,
|
|
1299
|
+
retriable: true,
|
|
1300
|
+
status: 503,
|
|
1301
|
+
}));
|
|
1302
|
+
this._setUsable(false, 'disconnected');
|
|
1303
|
+
this._emitBrowserBoxEvent('disconnected', {});
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
attributeChangedCallback(name, oldValue, newValue) {
|
|
1307
|
+
if (oldValue === newValue) {
|
|
1308
|
+
return;
|
|
1309
|
+
}
|
|
1310
|
+
if (name === 'login-link') {
|
|
1311
|
+
this._isReady = false;
|
|
1312
|
+
this._apiMethods = [];
|
|
1313
|
+
this._transportMode = 'unknown';
|
|
1314
|
+
this._legacyTabsCache = [];
|
|
1315
|
+
this._iframeRetryCount = 0;
|
|
1316
|
+
this._initPingCount = 0;
|
|
1317
|
+
this._reconnectStopped = false;
|
|
1318
|
+
this._silentRecoveryUsed = false;
|
|
1319
|
+
this._lastSuccessfulBootstrapAt = 0;
|
|
1320
|
+
this._resetReadyPromise();
|
|
1321
|
+
this._invalidateFrameBootstrap('login-link-changed');
|
|
1322
|
+
this._rejectPending(createBrowserBoxError('hyper-frame source changed.', {
|
|
1323
|
+
code: ERROR_CODES.TRANSPORT,
|
|
1324
|
+
retriable: true,
|
|
1325
|
+
status: 503,
|
|
1326
|
+
}));
|
|
1327
|
+
this._emitBrowserBoxEvent('disconnected', {
|
|
1328
|
+
reason: 'login-link-changed',
|
|
1329
|
+
});
|
|
1330
|
+
this._updateIframeSrcFromAttribute(name);
|
|
1331
|
+
this._startMidSync('login-link-changed');
|
|
1332
|
+
return;
|
|
1333
|
+
}
|
|
1334
|
+
if (name === 'width' || name === 'height') {
|
|
1335
|
+
this._applyHostDimensions();
|
|
1336
|
+
return;
|
|
1337
|
+
}
|
|
1338
|
+
if (name === 'ui-visible' || name === 'allow-user-toggle-ui') {
|
|
1339
|
+
this._sendUISync('attribute-changed');
|
|
1340
|
+
return;
|
|
1341
|
+
}
|
|
1342
|
+
if (name === 'media-permissions') {
|
|
1343
|
+
if (this.iframe) {
|
|
1344
|
+
this.iframe.setAttribute('allow', computeIframeAllow(newValue));
|
|
1345
|
+
}
|
|
1346
|
+
this._sendUISync('media-permissions-attribute-changed');
|
|
1347
|
+
return;
|
|
1348
|
+
}
|
|
1349
|
+
if (name === 'session-unload-warning') {
|
|
1350
|
+
this._sendUISync('session-unload-warning-attribute-changed');
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
if (name === 'beforeunload-behavior') {
|
|
1354
|
+
this._sendUISync('beforeunload-behavior-attribute-changed');
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
if (name === 'policy' || name === 'interaction-mode' || name === 'chrome' || name === 'augment-root' || name === 'capture') {
|
|
1358
|
+
if (name === 'chrome') {
|
|
1359
|
+
this._sendUISync('chrome-attribute-changed');
|
|
1360
|
+
}
|
|
1361
|
+
this._refreshPolicyState('attribute-changed');
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
_resetReadyPromise() {
|
|
1366
|
+
this._readyPromise = new Promise((resolve) => {
|
|
1367
|
+
this._resolveReady = resolve;
|
|
1368
|
+
});
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
_setReady() {
|
|
1372
|
+
if (!this._isReady) {
|
|
1373
|
+
this._isReady = true;
|
|
1374
|
+
this._setUsable(true, 'ready');
|
|
1375
|
+
this._iframeRetryCount = 0;
|
|
1376
|
+
this._reconnectStopped = false;
|
|
1377
|
+
this._stopInitPing();
|
|
1378
|
+
if (typeof this._resolveReady === 'function') {
|
|
1379
|
+
this._resolveReady(true);
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
this._invalidateFrameBootstrap('ready');
|
|
1383
|
+
this._scheduleFrameBootstrap('ready', 120);
|
|
1384
|
+
this._startFrameBootstrapRetries('ready');
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
_rejectPending(error) {
|
|
1388
|
+
for (const pending of this._pending.values()) {
|
|
1389
|
+
clearTimeout(pending.timer);
|
|
1390
|
+
pending.reject(error);
|
|
1391
|
+
}
|
|
1392
|
+
this._pending.clear();
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
_setUsable(next, reason = '') {
|
|
1396
|
+
const usable = Boolean(next);
|
|
1397
|
+
if (this._usable === usable) return;
|
|
1398
|
+
this._usable = usable;
|
|
1399
|
+
this._emitBrowserBoxEvent('usability-changed', {
|
|
1400
|
+
usable,
|
|
1401
|
+
reason,
|
|
1402
|
+
});
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
_createAugmentLayer(space) {
|
|
1406
|
+
const layer = document.createElement('div');
|
|
1407
|
+
layer.className = 'bbx-layer';
|
|
1408
|
+
layer.dataset.space = space;
|
|
1409
|
+
return layer;
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
_handleResize() {
|
|
1413
|
+
const w = this.clientWidth;
|
|
1414
|
+
const h = this.clientHeight;
|
|
1415
|
+
const RESIZE_TOLERANCE_PX = 2;
|
|
1416
|
+
if (
|
|
1417
|
+
this._lastResizeWidth >= 0
|
|
1418
|
+
&& this._lastResizeHeight >= 0
|
|
1419
|
+
&& Math.abs(w - this._lastResizeWidth) <= RESIZE_TOLERANCE_PX
|
|
1420
|
+
&& Math.abs(h - this._lastResizeHeight) <= RESIZE_TOLERANCE_PX
|
|
1421
|
+
) return;
|
|
1422
|
+
this._lastResizeWidth = w;
|
|
1423
|
+
this._lastResizeHeight = h;
|
|
1424
|
+
this._emitBrowserBoxEvent('viewport.resized', {
|
|
1425
|
+
width: w,
|
|
1426
|
+
height: h,
|
|
1427
|
+
});
|
|
1428
|
+
this._schedulePageAugmentRefresh();
|
|
1429
|
+
this._sendViewportReset('viewport-resized');
|
|
1430
|
+
if (this._resizeBootstrapTimer) clearTimeout(this._resizeBootstrapTimer);
|
|
1431
|
+
this._resizeBootstrapTimer = setTimeout(() => {
|
|
1432
|
+
this._resizeBootstrapTimer = null;
|
|
1433
|
+
this._invalidateFrameBootstrap('resize-settled');
|
|
1434
|
+
this._scheduleFrameBootstrap('resize-settled', 0);
|
|
1435
|
+
}, 450);
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
_stopFrameBootstrap() {
|
|
1439
|
+
if (this._frameBootstrapTimer) {
|
|
1440
|
+
clearTimeout(this._frameBootstrapTimer);
|
|
1441
|
+
this._frameBootstrapTimer = null;
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
_stopFrameBootstrapRetries() {
|
|
1446
|
+
if (this._frameBootstrapRetryTimer) {
|
|
1447
|
+
clearTimeout(this._frameBootstrapRetryTimer);
|
|
1448
|
+
this._frameBootstrapRetryTimer = null;
|
|
1449
|
+
}
|
|
1450
|
+
this._frameBootstrapRetryRemaining = 0;
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
_invalidateFrameBootstrap(_reason = 'state-changed') { // eslint-disable-line no-unused-vars
|
|
1454
|
+
this._frameBootstrapEpoch += 1;
|
|
1455
|
+
this._stopFrameBootstrap();
|
|
1456
|
+
this._stopFrameBootstrapRetries();
|
|
1457
|
+
return this._frameBootstrapEpoch;
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
_kickIframeViewportGeometry() {
|
|
1461
|
+
if (!this.iframe?.isConnected) {
|
|
1462
|
+
return false;
|
|
1463
|
+
}
|
|
1464
|
+
const width = Math.max(0, Math.floor(this.clientWidth));
|
|
1465
|
+
const height = Math.max(0, Math.floor(this.clientHeight));
|
|
1466
|
+
if (width <= 0 || height <= 0) {
|
|
1467
|
+
return false;
|
|
1468
|
+
}
|
|
1469
|
+
// Skip the +1px kick when using percentage sizing (embedded mode) —
|
|
1470
|
+
// the kick triggers parent relayout → ResizeObserver → infinite loop.
|
|
1471
|
+
const widthAttr = this.getAttribute('width') || '100%';
|
|
1472
|
+
const heightAttr = this.getAttribute('height') || '100%';
|
|
1473
|
+
if (!/^\d+$/.test(widthAttr) || !/^\d+$/.test(heightAttr)) {
|
|
1474
|
+
return false;
|
|
1475
|
+
}
|
|
1476
|
+
if (this._iframeViewportKickTimer) {
|
|
1477
|
+
clearTimeout(this._iframeViewportKickTimer);
|
|
1478
|
+
this._iframeViewportKickTimer = null;
|
|
1479
|
+
}
|
|
1480
|
+
const previousWidth = this.iframe.style.width;
|
|
1481
|
+
const previousHeight = this.iframe.style.height;
|
|
1482
|
+
this.iframe.style.width = `${width + 1}px`;
|
|
1483
|
+
this.iframe.style.height = `${height + 1}px`;
|
|
1484
|
+
this._iframeViewportKickTimer = setTimeout(() => {
|
|
1485
|
+
this._iframeViewportKickTimer = null;
|
|
1486
|
+
this.iframe.style.width = previousWidth;
|
|
1487
|
+
this.iframe.style.height = previousHeight;
|
|
1488
|
+
}, 40);
|
|
1489
|
+
return true;
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
_isEffectivelyVisible() {
|
|
1493
|
+
if (!this.isConnected) {
|
|
1494
|
+
return false;
|
|
1495
|
+
}
|
|
1496
|
+
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
|
|
1497
|
+
return false;
|
|
1498
|
+
}
|
|
1499
|
+
if (this.clientWidth <= 0 || this.clientHeight <= 0) {
|
|
1500
|
+
return false;
|
|
1501
|
+
}
|
|
1502
|
+
let node = this;
|
|
1503
|
+
while (node && node instanceof Element) {
|
|
1504
|
+
const style = window.getComputedStyle(node);
|
|
1505
|
+
if (
|
|
1506
|
+
style.display === 'none'
|
|
1507
|
+
|| style.visibility === 'hidden'
|
|
1508
|
+
|| Number(style.opacity) === 0
|
|
1509
|
+
) {
|
|
1510
|
+
return false;
|
|
1511
|
+
}
|
|
1512
|
+
node = node.parentElement;
|
|
1513
|
+
}
|
|
1514
|
+
return true;
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
_scheduleVisibilityWake(reason = 'became-visible') {
|
|
1518
|
+
// If a bootstrap succeeded very recently, skip: routine focus/visibility
|
|
1519
|
+
// events from the host page don't need to restart the cast pipeline.
|
|
1520
|
+
// `reactivateActiveTab` / `requestFrameRefresh` deliberately reset
|
|
1521
|
+
// `_lastEffectiveVisibility` so their explicit wakes bypass this cooldown.
|
|
1522
|
+
const VISIBILITY_WAKE_COOLDOWN_MS = 2500;
|
|
1523
|
+
const since = Date.now() - this._lastSuccessfulBootstrapAt;
|
|
1524
|
+
if (this._lastSuccessfulBootstrapAt && since < VISIBILITY_WAKE_COOLDOWN_MS) {
|
|
1525
|
+
console.info(`[hyper-frame] visibility wake skipped (${reason}, last success ${since}ms ago)`);
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1528
|
+
console.info(`[hyper-frame] visibility wake scheduled (${reason})`);
|
|
1529
|
+
this._invalidateFrameBootstrap(`visibility-wake:${reason}`);
|
|
1530
|
+
this._scheduleFrameBootstrap(reason, 50);
|
|
1531
|
+
this._startFrameBootstrapRetries(reason, {
|
|
1532
|
+
attempts: 6,
|
|
1533
|
+
initialDelayMs: 180,
|
|
1534
|
+
intervalMs: 650,
|
|
1535
|
+
});
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
_checkEffectiveVisibility() {
|
|
1539
|
+
const nextVisible = this._isEffectivelyVisible();
|
|
1540
|
+
const previousVisible = this._lastEffectiveVisibility;
|
|
1541
|
+
this._lastEffectiveVisibility = nextVisible;
|
|
1542
|
+
if (previousVisible === false && nextVisible === true) {
|
|
1543
|
+
this._scheduleVisibilityWake('became-visible');
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
_handleResumeTrigger(reason = 'document-visibility') {
|
|
1548
|
+
const wasVisible = this._lastEffectiveVisibility;
|
|
1549
|
+
this._checkEffectiveVisibility();
|
|
1550
|
+
if (wasVisible === true && this._lastEffectiveVisibility === true) {
|
|
1551
|
+
this._scheduleVisibilityWake(reason);
|
|
1552
|
+
}
|
|
1553
|
+
// If we transitioned hidden→visible, _checkEffectiveVisibility already
|
|
1554
|
+
// scheduled the wake. But if the poll timer hasn't run yet (fast
|
|
1555
|
+
// minimize/restore), wasVisible might still be true from before the hide
|
|
1556
|
+
// while _lastEffectiveVisibility just flipped to true inside the check.
|
|
1557
|
+
// The guard above covers that (both true → wake). For the remaining edge
|
|
1558
|
+
// case where an external caller (host window manager) fires this while
|
|
1559
|
+
// the component was hidden and is now visible, always force a deferred
|
|
1560
|
+
// recheck so layout can settle.
|
|
1561
|
+
if (!this._deferredVisibilityRecheckTimer) {
|
|
1562
|
+
this._deferredVisibilityRecheckTimer = setTimeout(() => {
|
|
1563
|
+
this._deferredVisibilityRecheckTimer = null;
|
|
1564
|
+
this._checkEffectiveVisibility();
|
|
1565
|
+
}, 120);
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
_startVisibilityPolling() {
|
|
1570
|
+
this._stopVisibilityPolling();
|
|
1571
|
+
this._lastEffectiveVisibility = this._isEffectivelyVisible();
|
|
1572
|
+
this._visibilityPollTimer = setInterval(() => {
|
|
1573
|
+
this._checkEffectiveVisibility();
|
|
1574
|
+
}, 250);
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
_stopVisibilityPolling() {
|
|
1578
|
+
if (this._visibilityPollTimer) {
|
|
1579
|
+
clearInterval(this._visibilityPollTimer);
|
|
1580
|
+
this._visibilityPollTimer = null;
|
|
1581
|
+
}
|
|
1582
|
+
this._lastEffectiveVisibility = null;
|
|
1583
|
+
}
|
|
1584
|
+
|
|
1585
|
+
_scheduleFrameBootstrap(reason = 'lifecycle', delayMs = 120) {
|
|
1586
|
+
this._stopFrameBootstrap();
|
|
1587
|
+
this._frameBootstrapTimer = setTimeout(() => {
|
|
1588
|
+
this._frameBootstrapTimer = null;
|
|
1589
|
+
void this._bootstrapActiveTabFrame(reason);
|
|
1590
|
+
}, Math.max(0, delayMs));
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
_startFrameBootstrapRetries(reason = 'ready', {
|
|
1594
|
+
attempts = 24,
|
|
1595
|
+
initialDelayMs = 400,
|
|
1596
|
+
intervalMs = 800,
|
|
1597
|
+
} = {}) {
|
|
1598
|
+
this._stopFrameBootstrapRetries();
|
|
1599
|
+
this._frameBootstrapRetryRemaining = Math.max(0, attempts);
|
|
1600
|
+
if (this._frameBootstrapRetryRemaining === 0) {
|
|
1601
|
+
return;
|
|
1602
|
+
}
|
|
1603
|
+
const run = async () => {
|
|
1604
|
+
if (!this.isConnected || this._frameBootstrapRetryRemaining <= 0) {
|
|
1605
|
+
this._stopFrameBootstrapRetries();
|
|
1606
|
+
return;
|
|
1607
|
+
}
|
|
1608
|
+
const attempt = (attempts - this._frameBootstrapRetryRemaining) + 1;
|
|
1609
|
+
this._frameBootstrapRetryRemaining -= 1;
|
|
1610
|
+
const ok = await this._bootstrapActiveTabFrame(`${reason}-retry-${attempt}`);
|
|
1611
|
+
// A successful bootstrap means the active tab is bound and the viewport
|
|
1612
|
+
// was re-asserted — additional retries would just churn the cast. Only
|
|
1613
|
+
// keep retrying if the bootstrap short-circuited (dimensions, readiness,
|
|
1614
|
+
// or tab lookup failed).
|
|
1615
|
+
if (ok || this._frameBootstrapRetryRemaining <= 0) {
|
|
1616
|
+
this._stopFrameBootstrapRetries();
|
|
1617
|
+
return;
|
|
1618
|
+
}
|
|
1619
|
+
this._frameBootstrapRetryTimer = setTimeout(run, Math.max(250, intervalMs));
|
|
1620
|
+
};
|
|
1621
|
+
this._frameBootstrapRetryTimer = setTimeout(run, Math.max(0, initialDelayMs));
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
async _bootstrapActiveTabFrame(reason = 'lifecycle') {
|
|
1625
|
+
if (this._frameBootstrapInFlight) {
|
|
1626
|
+
return this._frameBootstrapInFlight;
|
|
1627
|
+
}
|
|
1628
|
+
this._frameBootstrapInFlight = (async () => {
|
|
1629
|
+
const bootstrapEpoch = this._frameBootstrapEpoch;
|
|
1630
|
+
try {
|
|
1631
|
+
if (!this.isConnected) {
|
|
1632
|
+
return false;
|
|
1633
|
+
}
|
|
1634
|
+
if (this.clientWidth <= 0 || this.clientHeight <= 0) {
|
|
1635
|
+
return false;
|
|
1636
|
+
}
|
|
1637
|
+
const ready = await this._ensureReadyForApi();
|
|
1638
|
+
if (!ready) {
|
|
1639
|
+
return false;
|
|
1640
|
+
}
|
|
1641
|
+
if (this._transportMode === 'unknown') {
|
|
1642
|
+
await this._resolveTransport();
|
|
1643
|
+
}
|
|
1644
|
+
const activeTab = await this._getActiveTabInfo(null).catch(() => null);
|
|
1645
|
+
const tabId = activeTab?.id || activeTab?.targetId || null;
|
|
1646
|
+
if (!tabId) {
|
|
1647
|
+
return false;
|
|
1648
|
+
}
|
|
1649
|
+
if (bootstrapEpoch !== this._frameBootstrapEpoch) {
|
|
1650
|
+
return false;
|
|
1651
|
+
}
|
|
1652
|
+
const kickedViewportGeometry = this._kickIframeViewportGeometry();
|
|
1653
|
+
if (kickedViewportGeometry) {
|
|
1654
|
+
await new Promise((resolve) => setTimeout(resolve, 80));
|
|
1655
|
+
}
|
|
1656
|
+
if (bootstrapEpoch !== this._frameBootstrapEpoch) {
|
|
1657
|
+
return false;
|
|
1658
|
+
}
|
|
1659
|
+
const currentTab = await this._getActiveTabInfo(null).catch(() => null);
|
|
1660
|
+
const currentTabId = currentTab?.id || currentTab?.targetId || null;
|
|
1661
|
+
if (!currentTabId || currentTabId !== tabId) {
|
|
1662
|
+
return false;
|
|
1663
|
+
}
|
|
1664
|
+
const forcedViewportReset = this._sendViewportReset(`frame-bootstrap:${reason}`);
|
|
1665
|
+
if (forcedViewportReset) {
|
|
1666
|
+
await new Promise((resolve) => setTimeout(resolve, 80));
|
|
1667
|
+
}
|
|
1668
|
+
if (bootstrapEpoch !== this._frameBootstrapEpoch) {
|
|
1669
|
+
return false;
|
|
1670
|
+
}
|
|
1671
|
+
const activeAfterReset = await this._getActiveTabInfo(null).catch(() => null);
|
|
1672
|
+
const activeAfterResetId = activeAfterReset?.id || activeAfterReset?.targetId || null;
|
|
1673
|
+
if (!activeAfterResetId || activeAfterResetId !== tabId) {
|
|
1674
|
+
return false;
|
|
1675
|
+
}
|
|
1676
|
+
if (this._transportMode === 'legacy') {
|
|
1677
|
+
await this._legacyCall('switchToTabById', [tabId]);
|
|
1678
|
+
} else {
|
|
1679
|
+
await this._request('bbx-api-call', {
|
|
1680
|
+
method: 'switchToTabById',
|
|
1681
|
+
args: [tabId],
|
|
1682
|
+
}, {
|
|
1683
|
+
timeoutMs: Math.min(this.requestTimeoutMs, 5000),
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
this._lastSuccessfulBootstrapAt = Date.now();
|
|
1687
|
+
console.info(`[hyper-frame] bootstrapped frame (${reason})`, {
|
|
1688
|
+
tabId,
|
|
1689
|
+
transport: this._transportMode,
|
|
1690
|
+
kickedViewportGeometry,
|
|
1691
|
+
forcedViewportReset,
|
|
1692
|
+
});
|
|
1693
|
+
return true;
|
|
1694
|
+
} catch (error) {
|
|
1695
|
+
console.warn(`[hyper-frame] active tab frame bootstrap failed (${reason})`, {
|
|
1696
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1697
|
+
});
|
|
1698
|
+
return false;
|
|
1699
|
+
} finally {
|
|
1700
|
+
this._frameBootstrapInFlight = null;
|
|
1701
|
+
}
|
|
1702
|
+
})();
|
|
1703
|
+
return this._frameBootstrapInFlight;
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
async _withRetry(task, {
|
|
1707
|
+
attempts = 3,
|
|
1708
|
+
baseDelayMs = 250,
|
|
1709
|
+
maxDelayMs = 1500,
|
|
1710
|
+
shouldRetry = () => false,
|
|
1711
|
+
} = {}) {
|
|
1712
|
+
let attempt = 0;
|
|
1713
|
+
let lastError = null;
|
|
1714
|
+
while (attempt < attempts) {
|
|
1715
|
+
try {
|
|
1716
|
+
return await task(attempt);
|
|
1717
|
+
} catch (error) {
|
|
1718
|
+
lastError = error;
|
|
1719
|
+
attempt += 1;
|
|
1720
|
+
if (attempt >= attempts || !shouldRetry(error, attempt)) {
|
|
1721
|
+
throw error;
|
|
1722
|
+
}
|
|
1723
|
+
const delayMs = Math.min(maxDelayMs, baseDelayMs * (2 ** (attempt - 1)));
|
|
1724
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
throw lastError || createBrowserBoxError('hyper-frame retry failed.', {
|
|
1728
|
+
code: ERROR_CODES.INTERNAL,
|
|
1729
|
+
status: 500,
|
|
1730
|
+
});
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
_isRetryableApiError(error) {
|
|
1734
|
+
const message = String(error?.message || '').toLowerCase();
|
|
1735
|
+
return (
|
|
1736
|
+
error?.retriable === true
|
|
1737
|
+
|| error?.code === ERROR_CODES.NOT_READY
|
|
1738
|
+
|| error?.code === ERROR_CODES.TIMEOUT
|
|
1739
|
+
|| error?.code === ERROR_CODES.TRANSPORT
|
|
1740
|
+
|| message.includes('timed out')
|
|
1741
|
+
|| message.includes('not ready')
|
|
1742
|
+
|| message.includes('disconnected')
|
|
1743
|
+
|| message.includes('reconnect stopped')
|
|
1744
|
+
);
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
_rememberError(error) {
|
|
1748
|
+
if (!error) {
|
|
1749
|
+
this._lastError = null;
|
|
1750
|
+
return;
|
|
1751
|
+
}
|
|
1752
|
+
this._lastError = {
|
|
1753
|
+
code: typeof error.code === 'string' ? error.code : ERROR_CODES.INTERNAL,
|
|
1754
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1755
|
+
};
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
_normalizeRemoteError(error, context = {}) {
|
|
1759
|
+
if (error instanceof BrowserBoxError) {
|
|
1760
|
+
return error;
|
|
1761
|
+
}
|
|
1762
|
+
const message = error instanceof Error ? error.message : String(error || 'Unknown BrowserBox error');
|
|
1763
|
+
const lower = message.toLowerCase();
|
|
1764
|
+
let code = ERROR_CODES.INTERNAL;
|
|
1765
|
+
let status = 500;
|
|
1766
|
+
let retriable = false;
|
|
1767
|
+
|
|
1768
|
+
if (lower.includes('timed out')) {
|
|
1769
|
+
code = ERROR_CODES.TIMEOUT;
|
|
1770
|
+
status = 504;
|
|
1771
|
+
retriable = true;
|
|
1772
|
+
} else if (lower.includes('not ready') || lower.includes('selection is already active')) {
|
|
1773
|
+
code = ERROR_CODES.NOT_READY;
|
|
1774
|
+
status = 409;
|
|
1775
|
+
retriable = true;
|
|
1776
|
+
} else if (lower.includes('already exists')) {
|
|
1777
|
+
code = ERROR_CODES.CONFLICT;
|
|
1778
|
+
status = 409;
|
|
1779
|
+
} else if (lower.includes('unknown api method') || lower.includes('no legacy fallback')) {
|
|
1780
|
+
code = ERROR_CODES.UNSUPPORTED;
|
|
1781
|
+
status = 501;
|
|
1782
|
+
} else if (
|
|
1783
|
+
lower.includes('requires a non-empty')
|
|
1784
|
+
|| lower.includes('requires an object')
|
|
1785
|
+
|| lower.includes('requires target.selector')
|
|
1786
|
+
|| lower.includes('requires selection.selector')
|
|
1787
|
+
|| lower.includes('requires data.method')
|
|
1788
|
+
|| lower.includes('requires payload')
|
|
1789
|
+
) {
|
|
1790
|
+
code = ERROR_CODES.INVALID_ARGUMENT;
|
|
1791
|
+
status = 400;
|
|
1792
|
+
} else if (
|
|
1793
|
+
lower.includes('does not exist')
|
|
1794
|
+
|| lower.includes('no target tab')
|
|
1795
|
+
|| lower.includes('no active tab')
|
|
1796
|
+
) {
|
|
1797
|
+
code = ERROR_CODES.NOT_FOUND;
|
|
1798
|
+
status = 404;
|
|
1799
|
+
} else if (lower.includes('does not support')) {
|
|
1800
|
+
code = ERROR_CODES.UNSUPPORTED;
|
|
1801
|
+
status = 501;
|
|
1802
|
+
} else if (lower.includes('disconnected') || lower.includes('iframe')) {
|
|
1803
|
+
code = ERROR_CODES.TRANSPORT;
|
|
1804
|
+
status = 503;
|
|
1805
|
+
retriable = true;
|
|
1806
|
+
}
|
|
1807
|
+
|
|
1808
|
+
return createBrowserBoxError(message, {
|
|
1809
|
+
code,
|
|
1810
|
+
status,
|
|
1811
|
+
retriable,
|
|
1812
|
+
...context,
|
|
1813
|
+
...(error instanceof Error && error.cause !== undefined ? { cause: error.cause } : {}),
|
|
1814
|
+
});
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
_handleLoad() {
|
|
1818
|
+
if (this._reconnectStopped) {
|
|
1819
|
+
return;
|
|
1820
|
+
}
|
|
1821
|
+
const needsReset = this._isReady;
|
|
1822
|
+
this._isReady = false;
|
|
1823
|
+
this._apiMethods = [];
|
|
1824
|
+
this._transportMode = 'unknown';
|
|
1825
|
+
this._legacyTabsCache = [];
|
|
1826
|
+
this._initPingCount = 0;
|
|
1827
|
+
this._lastSuccessfulBootstrapAt = 0;
|
|
1828
|
+
if (needsReset) {
|
|
1829
|
+
this._iframeRetryCount = 0;
|
|
1830
|
+
this._resetReadyPromise();
|
|
1831
|
+
}
|
|
1832
|
+
this._midSyncAcked = false;
|
|
1833
|
+
this._uiSyncAcked = false;
|
|
1834
|
+
this._startMidSync('iframe-load');
|
|
1835
|
+
this._sendUISync('iframe-load');
|
|
1836
|
+
this._startInitPing();
|
|
1837
|
+
}
|
|
1838
|
+
|
|
1839
|
+
_startInitPing() {
|
|
1840
|
+
if (this._reconnectStopped) {
|
|
1841
|
+
return;
|
|
1842
|
+
}
|
|
1843
|
+
this._stopInitPing();
|
|
1844
|
+
this._initPingCount = 0;
|
|
1845
|
+
this._postRaw({ type: 'init' });
|
|
1846
|
+
this._initPingTimer = setInterval(() => {
|
|
1847
|
+
if (this._reconnectStopped) {
|
|
1848
|
+
this._stopInitPing();
|
|
1849
|
+
return;
|
|
1850
|
+
}
|
|
1851
|
+
if (this._isReady) {
|
|
1852
|
+
this._stopInitPing();
|
|
1853
|
+
return;
|
|
1854
|
+
}
|
|
1855
|
+
this._initPingCount += 1;
|
|
1856
|
+
if (this._initPingCount >= this._iframeRetryPingThreshold) {
|
|
1857
|
+
if (this._iframeRetryCount < this._iframeRetryMax) {
|
|
1858
|
+
this._retryIframeLoad();
|
|
1859
|
+
return;
|
|
1860
|
+
}
|
|
1861
|
+
if (this._attemptSilentRecovery('iframe-unresponsive')) {
|
|
1862
|
+
return;
|
|
1863
|
+
}
|
|
1864
|
+
this.stopReconnectAttempts('iframe-unresponsive');
|
|
1865
|
+
return;
|
|
1866
|
+
}
|
|
1867
|
+
this._postRaw({ type: 'init' });
|
|
1868
|
+
}, 1000);
|
|
1869
|
+
}
|
|
1870
|
+
|
|
1871
|
+
_retryIframeLoad() {
|
|
1872
|
+
this._stopInitPing();
|
|
1873
|
+
this._iframeRetryCount += 1;
|
|
1874
|
+
const src = this.iframe.src;
|
|
1875
|
+
if (!src) return;
|
|
1876
|
+
const delay = Math.min(2000 * this._iframeRetryCount, 8000);
|
|
1877
|
+
console.log(
|
|
1878
|
+
`[hyper-frame] iframe not responsive after ${this._iframeRetryPingThreshold}s, `
|
|
1879
|
+
+ `retry ${this._iframeRetryCount}/${this._iframeRetryMax} in ${delay}ms`
|
|
1880
|
+
);
|
|
1881
|
+
this._emitBrowserBoxEvent('iframe-retry', {
|
|
1882
|
+
attempt: this._iframeRetryCount,
|
|
1883
|
+
maxAttempts: this._iframeRetryMax,
|
|
1884
|
+
delayMs: delay,
|
|
1885
|
+
});
|
|
1886
|
+
setTimeout(() => {
|
|
1887
|
+
if (this._isReady || this._reconnectStopped) return;
|
|
1888
|
+
this._assignIframeSrc(src, '_retryIframeLoad');
|
|
1889
|
+
}, delay);
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
_assignIframeSrc(nextSrc, reason) {
|
|
1893
|
+
const stack = new Error().stack || '(no stack available)';
|
|
1894
|
+
debugBrowserBoxWebview('[DEBUG][SRC_ASSIGN]', {
|
|
1895
|
+
reason,
|
|
1896
|
+
currentSrc: this.iframe.src,
|
|
1897
|
+
nextSrc,
|
|
1898
|
+
stack,
|
|
1899
|
+
});
|
|
1900
|
+
this.iframe.src = nextSrc;
|
|
1901
|
+
}
|
|
1902
|
+
|
|
1903
|
+
_normalizeUrl(url) {
|
|
1904
|
+
if (typeof url !== 'string' || url.length === 0) return '';
|
|
1905
|
+
try {
|
|
1906
|
+
return new URL(url, window.location.href).href;
|
|
1907
|
+
} catch {
|
|
1908
|
+
return url;
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
_attemptSilentRecovery(reason) {
|
|
1913
|
+
if (this._silentRecoveryUsed) {
|
|
1914
|
+
return false;
|
|
1915
|
+
}
|
|
1916
|
+
const currentSrc = this._normalizeUrl(this.iframe.src || this.getAttribute('login-link'));
|
|
1917
|
+
if (!currentSrc) {
|
|
1918
|
+
return false;
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
let nextSrc;
|
|
1922
|
+
try {
|
|
1923
|
+
const parsed = new URL(currentSrc, window.location.href);
|
|
1924
|
+
const existingAttempt = Number(parsed.searchParams.get(this._silentRecoveryParam) || 0);
|
|
1925
|
+
if (!Number.isFinite(existingAttempt) || existingAttempt >= 1) {
|
|
1926
|
+
return false;
|
|
1927
|
+
}
|
|
1928
|
+
parsed.searchParams.set(this._silentRecoveryParam, String(existingAttempt + 1));
|
|
1929
|
+
// Cache-bust to avoid stale iframe boot assets after session/token rotation.
|
|
1930
|
+
parsed.searchParams.set('bbx_recover_t', String(Date.now()));
|
|
1931
|
+
nextSrc = parsed.href;
|
|
1932
|
+
} catch {
|
|
1933
|
+
return false;
|
|
1934
|
+
}
|
|
1935
|
+
|
|
1936
|
+
this._silentRecoveryUsed = true;
|
|
1937
|
+
this._isReady = false;
|
|
1938
|
+
this._apiMethods = [];
|
|
1939
|
+
this._transportMode = 'unknown';
|
|
1940
|
+
this._legacyTabsCache = [];
|
|
1941
|
+
this._iframeRetryCount = 0;
|
|
1942
|
+
this._initPingCount = 0;
|
|
1943
|
+
this._midSyncAcked = false;
|
|
1944
|
+
this._reconnectStopped = false;
|
|
1945
|
+
this._resetReadyPromise();
|
|
1946
|
+
this._rejectPending(createBrowserBoxError(`hyper-frame silent recovery (${reason}).`, {
|
|
1947
|
+
code: ERROR_CODES.TRANSPORT,
|
|
1948
|
+
retriable: true,
|
|
1949
|
+
status: 503,
|
|
1950
|
+
reason,
|
|
1951
|
+
}));
|
|
1952
|
+
|
|
1953
|
+
console.info('[hyper-frame] attempting one-shot silent recovery reload', {
|
|
1954
|
+
reason,
|
|
1955
|
+
nextSrc,
|
|
1956
|
+
});
|
|
1957
|
+
this._assignIframeSrc(nextSrc, 'silent-recovery');
|
|
1958
|
+
return true;
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
_updateIframeSrcFromAttribute(trigger) {
|
|
1962
|
+
const loginLink = this.getAttribute('login-link');
|
|
1963
|
+
if (!loginLink) return;
|
|
1964
|
+
this._refreshRoutingMid(loginLink);
|
|
1965
|
+
const normalizedCurrent = this._normalizeUrl(this.iframe.src);
|
|
1966
|
+
const normalizedNext = this._normalizeUrl(loginLink);
|
|
1967
|
+
if (normalizedCurrent === normalizedNext) {
|
|
1968
|
+
return;
|
|
1969
|
+
}
|
|
1970
|
+
this._assignIframeSrc(loginLink, trigger);
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
_applyHostDimensions() {
|
|
1974
|
+
const width = this.getAttribute('width') || '100%';
|
|
1975
|
+
const height = this.getAttribute('height') || '100%';
|
|
1976
|
+
this.style.width = /^\d+$/.test(width) ? `${width}px` : width;
|
|
1977
|
+
this.style.height = /^\d+$/.test(height) ? `${height}px` : height;
|
|
1978
|
+
}
|
|
1979
|
+
|
|
1980
|
+
_stopInitPing() {
|
|
1981
|
+
if (this._initPingTimer) {
|
|
1982
|
+
clearInterval(this._initPingTimer);
|
|
1983
|
+
this._initPingTimer = null;
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
_normalizeMid(value) {
|
|
1988
|
+
const mid = String(value || '').trim();
|
|
1989
|
+
return /^[A-Za-z0-9-]{6,64}$/.test(mid) ? mid : '';
|
|
1990
|
+
}
|
|
1991
|
+
|
|
1992
|
+
_refreshRoutingMid(loginLink = this.getAttribute('login-link')) {
|
|
1993
|
+
let storageKey = this._midStorageKey;
|
|
1994
|
+
let midFromLogin = '';
|
|
1995
|
+
try {
|
|
1996
|
+
const parsed = new URL(loginLink || '', window.location.href);
|
|
1997
|
+
storageKey = `bbx.embedder.mid:${parsed.origin}`;
|
|
1998
|
+
midFromLogin = this._normalizeMid(parsed.searchParams.get('mid'));
|
|
1999
|
+
} catch {
|
|
2000
|
+
// Keep fallback values when login-link is not parseable.
|
|
2001
|
+
}
|
|
2002
|
+
|
|
2003
|
+
let persistedMid = '';
|
|
2004
|
+
try {
|
|
2005
|
+
persistedMid = this._normalizeMid(window.localStorage?.getItem?.(storageKey));
|
|
2006
|
+
} catch {
|
|
2007
|
+
// Storage may be blocked in some embedding contexts.
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
const resolvedMid = midFromLogin || persistedMid || this._routingMid;
|
|
2011
|
+
this._midStorageKey = storageKey;
|
|
2012
|
+
this._routingMid = resolvedMid || '';
|
|
2013
|
+
|
|
2014
|
+
if (midFromLogin) {
|
|
2015
|
+
try {
|
|
2016
|
+
window.localStorage?.setItem?.(storageKey, midFromLogin);
|
|
2017
|
+
} catch {
|
|
2018
|
+
// Storage writes are best-effort only.
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
|
|
2022
|
+
if (this._routingMid) {
|
|
2023
|
+
this.setAttribute('routing-mid', this._routingMid);
|
|
2024
|
+
} else {
|
|
2025
|
+
this.removeAttribute('routing-mid');
|
|
2026
|
+
}
|
|
2027
|
+
if (this._routingMid) {
|
|
2028
|
+
console.info('[bbx-mid] routing mid resolved', {
|
|
2029
|
+
mid: this._routingMid,
|
|
2030
|
+
source: midFromLogin ? 'login-link' : (persistedMid ? 'storage' : 'memory'),
|
|
2031
|
+
});
|
|
2032
|
+
} else {
|
|
2033
|
+
console.info('[bbx-mid] no routing mid resolved');
|
|
2034
|
+
}
|
|
2035
|
+
return this._routingMid;
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
_postMidSync(reason = '') {
|
|
2039
|
+
const mid = this._refreshRoutingMid();
|
|
2040
|
+
if (!mid || !this.iframe.contentWindow) {
|
|
2041
|
+
return false;
|
|
2042
|
+
}
|
|
2043
|
+
// Mid-sync messages use '*' targetOrigin because the iframe may
|
|
2044
|
+
// still be navigating to the BBX origin (from parent origin).
|
|
2045
|
+
// These messages contain only the routing mid, not sensitive data.
|
|
2046
|
+
try {
|
|
2047
|
+
this.iframe.contentWindow.postMessage({
|
|
2048
|
+
type: 'bbx-mid-sync',
|
|
2049
|
+
data: {
|
|
2050
|
+
mid,
|
|
2051
|
+
reason,
|
|
2052
|
+
attempt: this._midSyncAttempt,
|
|
2053
|
+
},
|
|
2054
|
+
}, '*');
|
|
2055
|
+
} catch (error) {
|
|
2056
|
+
console.warn('[bbx-mid] postMessage failed', { error: error.message });
|
|
2057
|
+
return false;
|
|
2058
|
+
}
|
|
2059
|
+
console.info('[bbx-mid] sent sync', {
|
|
2060
|
+
mid,
|
|
2061
|
+
reason,
|
|
2062
|
+
attempt: this._midSyncAttempt,
|
|
2063
|
+
});
|
|
2064
|
+
return true;
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
_startMidSync(reason = 'start') {
|
|
2068
|
+
this._stopMidSync();
|
|
2069
|
+
this._midSyncAcked = false;
|
|
2070
|
+
this._midSyncAttempt = 0;
|
|
2071
|
+
if (!this._postMidSync(reason)) {
|
|
2072
|
+
return;
|
|
2073
|
+
}
|
|
2074
|
+
this._midSyncAttempt = 1;
|
|
2075
|
+
this._midSyncTimer = setInterval(() => {
|
|
2076
|
+
if (this._midSyncAcked) {
|
|
2077
|
+
this._stopMidSync();
|
|
2078
|
+
return;
|
|
2079
|
+
}
|
|
2080
|
+
if (this._midSyncAttempt >= this._midSyncMaxAttempts) {
|
|
2081
|
+
this._stopMidSync();
|
|
2082
|
+
console.warn('[bbx-mid] sync timeout', {
|
|
2083
|
+
attempts: this._midSyncAttempt,
|
|
2084
|
+
mid: this._routingMid,
|
|
2085
|
+
});
|
|
2086
|
+
this.dispatchEvent(new CustomEvent('mid-sync-timeout', {
|
|
2087
|
+
detail: {
|
|
2088
|
+
attempts: this._midSyncAttempt,
|
|
2089
|
+
mid: this._routingMid,
|
|
2090
|
+
},
|
|
2091
|
+
}));
|
|
2092
|
+
this._setUsable(false, 'mid-sync-timeout');
|
|
2093
|
+
return;
|
|
2094
|
+
}
|
|
2095
|
+
this._midSyncAttempt += 1;
|
|
2096
|
+
this._postMidSync('retry');
|
|
2097
|
+
}, this._midSyncIntervalMs);
|
|
2098
|
+
}
|
|
2099
|
+
|
|
2100
|
+
_stopMidSync() {
|
|
2101
|
+
if (this._midSyncTimer) {
|
|
2102
|
+
clearInterval(this._midSyncTimer);
|
|
2103
|
+
this._midSyncTimer = null;
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
|
|
2107
|
+
_resolveUIConfig() {
|
|
2108
|
+
const parseBool = (v, fallback) => {
|
|
2109
|
+
if (v === null || v === undefined) return fallback;
|
|
2110
|
+
const raw = String(v).trim().toLowerCase();
|
|
2111
|
+
if (raw === 'true' || raw === '1') return true;
|
|
2112
|
+
if (raw === 'false' || raw === '0') return false;
|
|
2113
|
+
return fallback;
|
|
2114
|
+
};
|
|
2115
|
+
const chromeMode = String(this.getAttribute('chrome') || 'default').trim().toLowerCase();
|
|
2116
|
+
const chromeVisibleByMode = chromeMode === 'none' ? false : true;
|
|
2117
|
+
const mediaPermissions = normalizeMediaPermissions(this.getAttribute('media-permissions'));
|
|
2118
|
+
const sessionUnloadWarning = normalizeSessionUnloadWarning(this.getAttribute('session-unload-warning'));
|
|
2119
|
+
const beforeUnloadBehavior = normalizeBeforeUnloadBehavior(this.getAttribute('beforeunload-behavior'));
|
|
2120
|
+
return {
|
|
2121
|
+
uiVisible: parseBool(this.getAttribute('ui-visible'), chromeVisibleByMode),
|
|
2122
|
+
allowUserToggleUI: parseBool(this.getAttribute('allow-user-toggle-ui'), true),
|
|
2123
|
+
chromeMode,
|
|
2124
|
+
mediaPermissions,
|
|
2125
|
+
sessionUnloadWarning,
|
|
2126
|
+
beforeUnloadBehavior,
|
|
2127
|
+
};
|
|
2128
|
+
}
|
|
2129
|
+
|
|
2130
|
+
_resolveLocalPolicySnapshot() {
|
|
2131
|
+
const interactionModeRaw = this.getAttribute('interaction-mode') || 'full';
|
|
2132
|
+
const interactionMode = String(interactionModeRaw).trim().toLowerCase();
|
|
2133
|
+
const preset = INTERACTION_MODE_PRESETS[interactionMode] || INTERACTION_MODE_PRESETS.full;
|
|
2134
|
+
let capabilityOverride = {};
|
|
2135
|
+
const policyRaw = this.getAttribute('policy');
|
|
2136
|
+
if (policyRaw) {
|
|
2137
|
+
try {
|
|
2138
|
+
const parsed = JSON.parse(policyRaw);
|
|
2139
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
2140
|
+
capabilityOverride = extractApiCapabilities(parsed);
|
|
2141
|
+
} else {
|
|
2142
|
+
console.error('[hyper-frame] policy attribute must decode to an object.', {
|
|
2143
|
+
policy: policyRaw,
|
|
2144
|
+
});
|
|
2145
|
+
}
|
|
2146
|
+
} catch (error) {
|
|
2147
|
+
console.error('[hyper-frame] failed to parse policy attribute.', {
|
|
2148
|
+
policy: policyRaw,
|
|
2149
|
+
error,
|
|
2150
|
+
});
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
2153
|
+
const captureMode = String(this.getAttribute('capture') || 'snapshot').trim().toLowerCase();
|
|
2154
|
+
const captureOverride = {
|
|
2155
|
+
capture: {
|
|
2156
|
+
frame: captureMode !== 'off',
|
|
2157
|
+
viewport: captureMode !== 'off',
|
|
2158
|
+
stream: captureMode === 'sampled',
|
|
2159
|
+
},
|
|
2160
|
+
};
|
|
2161
|
+
const localOverride = mergePolicyTree(
|
|
2162
|
+
clonePolicyTree(POLICY_DEFAULTS),
|
|
2163
|
+
{
|
|
2164
|
+
...capabilityOverride,
|
|
2165
|
+
capture: {
|
|
2166
|
+
...(capabilityOverride.capture || {}),
|
|
2167
|
+
...captureOverride.capture,
|
|
2168
|
+
},
|
|
2169
|
+
},
|
|
2170
|
+
);
|
|
2171
|
+
const capabilities = mergePolicyTree(
|
|
2172
|
+
mergePolicyTree(clonePolicyTree(POLICY_DEFAULTS), preset),
|
|
2173
|
+
localOverride,
|
|
2174
|
+
);
|
|
2175
|
+
return createLocalPolicySnapshot(capabilities, {
|
|
2176
|
+
baselineId: `hyper-frame-${interactionMode}`,
|
|
2177
|
+
featureControls: {
|
|
2178
|
+
chromeMode: String(this.getAttribute('chrome') || 'default').trim().toLowerCase(),
|
|
2179
|
+
augmentRoot: String(this.getAttribute('augment-root') || 'open').trim().toLowerCase(),
|
|
2180
|
+
captureMode,
|
|
2181
|
+
},
|
|
2182
|
+
});
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
_resolvePolicySnapshot() {
|
|
2186
|
+
return mergePolicySnapshots(this._serverPolicySnapshot, this._resolveLocalPolicySnapshot());
|
|
2187
|
+
}
|
|
2188
|
+
|
|
2189
|
+
_buildCapabilityMap(policySnapshot) {
|
|
2190
|
+
const policyCapabilities = flattenPolicyTree(extractApiCapabilities(policySnapshot));
|
|
2191
|
+
const resolved = {};
|
|
2192
|
+
for (const [capability, allowedByPolicy] of Object.entries(policyCapabilities)) {
|
|
2193
|
+
resolved[capability] = Boolean(allowedByPolicy) && Boolean(IMPLEMENTED_CAPABILITIES[capability]);
|
|
2194
|
+
}
|
|
2195
|
+
return resolved;
|
|
2196
|
+
}
|
|
2197
|
+
|
|
2198
|
+
_invalidatePolicySnapshotCache() {
|
|
2199
|
+
this._policySnapshotCache.source = null;
|
|
2200
|
+
this._policySnapshotCache.value = null;
|
|
2201
|
+
}
|
|
2202
|
+
|
|
2203
|
+
_getPolicySnapshotView() {
|
|
2204
|
+
if (this._policySnapshotCache.source === this._policySnapshot && this._policySnapshotCache.value) {
|
|
2205
|
+
return this._policySnapshotCache.value;
|
|
2206
|
+
}
|
|
2207
|
+
|
|
2208
|
+
const snapshotView = createPolicySnapshotView(this._policySnapshot);
|
|
2209
|
+
this._policySnapshotCache.source = this._policySnapshot;
|
|
2210
|
+
this._policySnapshotCache.value = snapshotView;
|
|
2211
|
+
return snapshotView;
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
_refreshPolicyState(reason = 'refresh') {
|
|
2215
|
+
const previousPolicy = JSON.stringify(this._policySnapshot);
|
|
2216
|
+
const previousCapabilities = JSON.stringify(this._capabilityMap);
|
|
2217
|
+
const nextPolicySnapshot = this._resolvePolicySnapshot();
|
|
2218
|
+
const nextCapabilityMap = this._buildCapabilityMap(nextPolicySnapshot);
|
|
2219
|
+
|
|
2220
|
+
if (
|
|
2221
|
+
previousPolicy === JSON.stringify(nextPolicySnapshot)
|
|
2222
|
+
&& previousCapabilities === JSON.stringify(nextCapabilityMap)
|
|
2223
|
+
) {
|
|
2224
|
+
return;
|
|
2225
|
+
}
|
|
2226
|
+
|
|
2227
|
+
this._policySnapshot = nextPolicySnapshot;
|
|
2228
|
+
this._capabilityMap = nextCapabilityMap;
|
|
2229
|
+
this._invalidatePolicySnapshotCache();
|
|
2230
|
+
this._emitBrowserBoxEvent('policy.changed', {
|
|
2231
|
+
reason,
|
|
2232
|
+
policy: this._getPolicySnapshotView(),
|
|
2233
|
+
capabilities: { ...this._capabilityMap },
|
|
2234
|
+
});
|
|
2235
|
+
}
|
|
2236
|
+
|
|
2237
|
+
_capabilitiesForMethod(method, args = []) {
|
|
2238
|
+
if (method === 'captureFrame') {
|
|
2239
|
+
const scope = String(args?.[0]?.scope || 'frame').trim().toLowerCase();
|
|
2240
|
+
return [scope === 'viewport' ? 'capture.viewport' : 'capture.frame'];
|
|
2241
|
+
}
|
|
2242
|
+
const requirements = METHOD_CAPABILITY_MAP[method];
|
|
2243
|
+
return Array.isArray(requirements) ? requirements : [];
|
|
2244
|
+
}
|
|
2245
|
+
|
|
2246
|
+
_assertCapability(capability) {
|
|
2247
|
+
if (this._capabilityMap?.[capability]) {
|
|
2248
|
+
return true;
|
|
2249
|
+
}
|
|
2250
|
+
const detail = {
|
|
2251
|
+
error: `Capability denied: ${capability}`,
|
|
2252
|
+
policyDenied: {
|
|
2253
|
+
action: capability,
|
|
2254
|
+
capability,
|
|
2255
|
+
reasonCode: 'embed-policy-denied',
|
|
2256
|
+
policyId: this._policySnapshot?.policyId || POLICY_ID,
|
|
2257
|
+
baselineId: this._policySnapshot?.baselineId || POLICY_BASELINE_ID,
|
|
2258
|
+
decisionSchemaVersion: 'embedder-policy/v1',
|
|
2259
|
+
source: this._serverPolicySnapshot ? 'server+embedder-policy' : 'embedder-policy',
|
|
2260
|
+
},
|
|
2261
|
+
};
|
|
2262
|
+
this._emitBrowserBoxEvent('policy-denied', detail);
|
|
2263
|
+
throw new BrowserBoxPolicyError(capability);
|
|
2264
|
+
}
|
|
2265
|
+
|
|
2266
|
+
_isEventAllowed(eventName) {
|
|
2267
|
+
if (!this._capabilityMap?.['events.read']) {
|
|
2268
|
+
return false;
|
|
2269
|
+
}
|
|
2270
|
+
const requiredCapability = EVENT_CAPABILITY_RULES[eventName];
|
|
2271
|
+
return !requiredCapability || Boolean(this._capabilityMap?.[requiredCapability]);
|
|
2272
|
+
}
|
|
2273
|
+
|
|
2274
|
+
_emitBrowserBoxEvent(eventName, detail = {}) {
|
|
2275
|
+
const eventNames = [eventName, ...(EVENT_ALIAS_MAP[eventName] || [])];
|
|
2276
|
+
for (const name of eventNames) {
|
|
2277
|
+
if (!this._isEventAllowed(name)) {
|
|
2278
|
+
continue;
|
|
2279
|
+
}
|
|
2280
|
+
const eventDetail = detail && typeof detail === 'object' ? { ...detail } : detail;
|
|
2281
|
+
this.dispatchEvent(new CustomEvent(name, { detail: eventDetail }));
|
|
2282
|
+
this._pushEventRecord(name, eventDetail);
|
|
2283
|
+
}
|
|
2284
|
+
if (
|
|
2285
|
+
eventName === 'page.navigated'
|
|
2286
|
+
|| eventName === 'page.load.stopped'
|
|
2287
|
+
|| eventName === 'did-navigate'
|
|
2288
|
+
|| eventName === 'did-stop-loading'
|
|
2289
|
+
|| eventName === 'viewport.resized'
|
|
2290
|
+
) {
|
|
2291
|
+
this._schedulePageAugmentRefresh();
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
_pushEventRecord(type, detail) {
|
|
2296
|
+
const tabId = this._normalizeTabId(detail);
|
|
2297
|
+
const record = {
|
|
2298
|
+
id: `bbx-event-${++this._eventSeq}`,
|
|
2299
|
+
type,
|
|
2300
|
+
detail,
|
|
2301
|
+
timestamp: new Date().toISOString(),
|
|
2302
|
+
sessionId: this._routingMid || null,
|
|
2303
|
+
...(tabId ? { tabId } : {}),
|
|
2304
|
+
};
|
|
2305
|
+
for (const subscriber of this._eventSubscribers) {
|
|
2306
|
+
if (subscriber.closed || !subscriber.filter(record)) {
|
|
2307
|
+
continue;
|
|
2308
|
+
}
|
|
2309
|
+
if (subscriber.resolve) {
|
|
2310
|
+
const resolve = subscriber.resolve;
|
|
2311
|
+
subscriber.resolve = null;
|
|
2312
|
+
resolve({ value: record, done: false });
|
|
2313
|
+
continue;
|
|
2314
|
+
}
|
|
2315
|
+
if (subscriber.queue.length >= subscriber.maxQueue) {
|
|
2316
|
+
subscriber.queue.shift();
|
|
2317
|
+
}
|
|
2318
|
+
subscriber.queue.push(record);
|
|
2319
|
+
}
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
_schedulePageAugmentRefresh() {
|
|
2323
|
+
if (this._pageAugmentRefreshScheduled) {
|
|
2324
|
+
return;
|
|
2325
|
+
}
|
|
2326
|
+
this._pageAugmentRefreshScheduled = true;
|
|
2327
|
+
scheduleMicrotask(() => {
|
|
2328
|
+
this._pageAugmentRefreshScheduled = false;
|
|
2329
|
+
this._refreshPageAugments().catch((error) => {
|
|
2330
|
+
console.warn('[hyper-frame] failed to refresh page augments', error);
|
|
2331
|
+
});
|
|
2332
|
+
});
|
|
2333
|
+
}
|
|
2334
|
+
|
|
2335
|
+
async _refreshPageAugments() {
|
|
2336
|
+
const pageAugments = [...this._augmentRegistry.values()].filter((record) => record.spec.space === 'page');
|
|
2337
|
+
if (pageAugments.length === 0) {
|
|
2338
|
+
return;
|
|
2339
|
+
}
|
|
2340
|
+
await Promise.all(pageAugments.map(async (record) => {
|
|
2341
|
+
record.resolution = await this._resolveAugmentTarget(record.spec);
|
|
2342
|
+
this._renderAugmentRecord(record);
|
|
2343
|
+
}));
|
|
2344
|
+
}
|
|
2345
|
+
|
|
2346
|
+
_sendUISync(reason = '') {
|
|
2347
|
+
if (!this.iframe.contentWindow) return false;
|
|
2348
|
+
const config = this._resolveUIConfig();
|
|
2349
|
+
this._postRaw({
|
|
2350
|
+
type: 'bbx-ui-sync',
|
|
2351
|
+
data: {
|
|
2352
|
+
uiVisible: config.uiVisible,
|
|
2353
|
+
allowUserToggleUI: config.allowUserToggleUI,
|
|
2354
|
+
chromeMode: config.chromeMode,
|
|
2355
|
+
mediaPermissions: config.mediaPermissions,
|
|
2356
|
+
sessionUnloadWarning: config.sessionUnloadWarning,
|
|
2357
|
+
beforeunloadBehavior: config.beforeUnloadBehavior,
|
|
2358
|
+
embedderOrigin: this.embedderOrigin,
|
|
2359
|
+
reason,
|
|
2360
|
+
},
|
|
2361
|
+
});
|
|
2362
|
+
return true;
|
|
2363
|
+
}
|
|
2364
|
+
|
|
2365
|
+
_sendViewportReset(reason = '') {
|
|
2366
|
+
if (!this.iframe.contentWindow) return false;
|
|
2367
|
+
this._postRaw({
|
|
2368
|
+
type: 'bbx-viewport-reset',
|
|
2369
|
+
data: {
|
|
2370
|
+
reason,
|
|
2371
|
+
},
|
|
2372
|
+
});
|
|
2373
|
+
return true;
|
|
2374
|
+
}
|
|
2375
|
+
|
|
2376
|
+
/**
|
|
2377
|
+
* Derive the BrowserBox iframe origin from the login-link URL.
|
|
2378
|
+
* This is the origin of the iframe content, used for:
|
|
2379
|
+
* - outbound postMessage targetOrigin (webview → iframe)
|
|
2380
|
+
* - inbound origin validation (iframe → webview)
|
|
2381
|
+
* Falls back to '*' during initial load before login-link is set.
|
|
2382
|
+
*/
|
|
2383
|
+
_browserboxOrigin() {
|
|
2384
|
+
const loginLink = this.getAttribute('login-link');
|
|
2385
|
+
if (loginLink) {
|
|
2386
|
+
try {
|
|
2387
|
+
return new URL(loginLink).origin;
|
|
2388
|
+
} catch {
|
|
2389
|
+
// login-link not parseable yet
|
|
2390
|
+
}
|
|
2391
|
+
}
|
|
2392
|
+
return '*';
|
|
2393
|
+
}
|
|
2394
|
+
|
|
2395
|
+
_outboundTargetOrigin() {
|
|
2396
|
+
return this._browserboxOrigin();
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
_validateIncomingOrigin(origin) {
|
|
2400
|
+
const expected = this._browserboxOrigin();
|
|
2401
|
+
return expected === '*' || origin === expected;
|
|
2402
|
+
}
|
|
2403
|
+
|
|
2404
|
+
_normalizeTabId(detail) {
|
|
2405
|
+
if (!detail || typeof detail !== 'object') return null;
|
|
2406
|
+
const candidates = [detail.id, detail.tabId, detail.targetId];
|
|
2407
|
+
for (const candidate of candidates) {
|
|
2408
|
+
if (typeof candidate === 'string' && candidate.length > 0) {
|
|
2409
|
+
return candidate;
|
|
2410
|
+
}
|
|
2411
|
+
}
|
|
2412
|
+
return null;
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
_updateLegacyTabCache(detail) {
|
|
2416
|
+
const tabId = this._normalizeTabId(detail);
|
|
2417
|
+
if (!tabId) return;
|
|
2418
|
+
const index = this._legacyTabsCache.findIndex((tab) => this._normalizeTabId(tab) === tabId);
|
|
2419
|
+
if (index === -1) return;
|
|
2420
|
+
const existing = this._legacyTabsCache[index];
|
|
2421
|
+
this._legacyTabsCache[index] = {
|
|
2422
|
+
...existing,
|
|
2423
|
+
...detail,
|
|
2424
|
+
index: existing.index ?? detail.index ?? index,
|
|
2425
|
+
};
|
|
2426
|
+
}
|
|
2427
|
+
|
|
2428
|
+
_addLegacyTabCache(detail) {
|
|
2429
|
+
const tabId = this._normalizeTabId(detail);
|
|
2430
|
+
if (!tabId) return;
|
|
2431
|
+
const existingIndex = this._legacyTabsCache.findIndex((tab) => this._normalizeTabId(tab) === tabId);
|
|
2432
|
+
if (existingIndex !== -1) {
|
|
2433
|
+
this._updateLegacyTabCache(detail);
|
|
2434
|
+
return;
|
|
2435
|
+
}
|
|
2436
|
+
const index = Number.isInteger(detail.index) ? detail.index : this._legacyTabsCache.length;
|
|
2437
|
+
const entry = { ...detail, index };
|
|
2438
|
+
this._legacyTabsCache.splice(Math.min(index, this._legacyTabsCache.length), 0, entry);
|
|
2439
|
+
this._legacyTabsCache = this._legacyTabsCache.map((tab, i) => ({ ...tab, index: i }));
|
|
2440
|
+
}
|
|
2441
|
+
|
|
2442
|
+
_removeLegacyTabCache(detail) {
|
|
2443
|
+
const tabId = this._normalizeTabId(detail);
|
|
2444
|
+
if (!tabId) return;
|
|
2445
|
+
this._legacyTabsCache = this._legacyTabsCache
|
|
2446
|
+
.filter((tab) => this._normalizeTabId(tab) !== tabId)
|
|
2447
|
+
.map((tab, i) => ({ ...tab, index: i }));
|
|
2448
|
+
}
|
|
2449
|
+
|
|
2450
|
+
async _getActiveTabInfo(capability = 'tabs.read') {
|
|
2451
|
+
if (capability) {
|
|
2452
|
+
this._assertCapability(capability);
|
|
2453
|
+
}
|
|
2454
|
+
const activeTab = await this._request('getActiveTab', {}).catch(() => null);
|
|
2455
|
+
if (activeTab) {
|
|
2456
|
+
return normalizeTabInfo({ ...activeTab, active: true }, activeTab.index);
|
|
2457
|
+
}
|
|
2458
|
+
const tabs = await this.callApi('getTabs').catch(() => []);
|
|
2459
|
+
const activeIndex = await this.callApi('getActiveTabIndex').catch(() => -1);
|
|
2460
|
+
if (!Array.isArray(tabs) || activeIndex < 0 || activeIndex >= tabs.length) {
|
|
2461
|
+
return null;
|
|
2462
|
+
}
|
|
2463
|
+
return normalizeTabInfo({ ...tabs[activeIndex], active: true }, activeIndex);
|
|
2464
|
+
}
|
|
2465
|
+
|
|
2466
|
+
async _getPageText(options = {}) {
|
|
2467
|
+
this._assertCapability('page.read');
|
|
2468
|
+
try {
|
|
2469
|
+
const result = await this.callApi('getPageText', options);
|
|
2470
|
+
return extractEvaluateValue(result);
|
|
2471
|
+
} catch (error) {
|
|
2472
|
+
const message = String(error?.message || '');
|
|
2473
|
+
const missingMethod = message.includes('Unknown API method')
|
|
2474
|
+
|| message.includes('Unknown BrowserBox API method')
|
|
2475
|
+
|| message.includes('No legacy fallback');
|
|
2476
|
+
if (!missingMethod) {
|
|
2477
|
+
throw error;
|
|
2478
|
+
}
|
|
2479
|
+
const mainContentOnly = Boolean(options?.mainContentOnly);
|
|
2480
|
+
const targetExpression = mainContentOnly
|
|
2481
|
+
? '(document.querySelector("main, article, [role=\\"main\\"]") || document.body || document.documentElement)'
|
|
2482
|
+
: '(document.body || document.documentElement)';
|
|
2483
|
+
const result = await this.evaluate(`(() => {
|
|
2484
|
+
const root = ${targetExpression};
|
|
2485
|
+
if (!root) return "";
|
|
2486
|
+
return typeof root.innerText === "string" ? root.innerText : (root.textContent || "");
|
|
2487
|
+
})()`, {
|
|
2488
|
+
timeoutMs: Number.isFinite(options?.timeoutMs) ? options.timeoutMs : this.requestTimeoutMs,
|
|
2489
|
+
});
|
|
2490
|
+
return extractEvaluateValue(result);
|
|
2491
|
+
}
|
|
2492
|
+
}
|
|
2493
|
+
|
|
2494
|
+
async _callApiDirect(method, args = [], requestOptions = {}) {
|
|
2495
|
+
if (typeof method !== 'string' || method.trim().length === 0) {
|
|
2496
|
+
throwInvalidArgument('hyper-frame API method requires a non-empty string.');
|
|
2497
|
+
}
|
|
2498
|
+
if (!Array.isArray(args)) {
|
|
2499
|
+
throwInvalidArgument('hyper-frame API args must be an array.');
|
|
2500
|
+
}
|
|
2501
|
+
const normalizedMethod = method.trim();
|
|
2502
|
+
const ready = await this._ensureReadyForApi();
|
|
2503
|
+
if (!ready) {
|
|
2504
|
+
throw createBrowserBoxError(`hyper-frame API method '${normalizedMethod}' called before handshake completed.`, {
|
|
2505
|
+
code: ERROR_CODES.NOT_READY,
|
|
2506
|
+
retriable: true,
|
|
2507
|
+
status: 409,
|
|
2508
|
+
method: normalizedMethod,
|
|
2509
|
+
});
|
|
2510
|
+
}
|
|
2511
|
+
for (const capability of this._capabilitiesForMethod(normalizedMethod, args)) {
|
|
2512
|
+
this._assertCapability(capability);
|
|
2513
|
+
}
|
|
2514
|
+
if (this._transportMode === 'unknown') {
|
|
2515
|
+
await this._resolveTransport();
|
|
2516
|
+
}
|
|
2517
|
+
if (this._transportMode === 'legacy') {
|
|
2518
|
+
return this._legacyCall(normalizedMethod, args);
|
|
2519
|
+
}
|
|
2520
|
+
return this._request('bbx-api-call', { method: normalizedMethod, args }, requestOptions);
|
|
2521
|
+
}
|
|
2522
|
+
|
|
2523
|
+
async _resolveAugmentTarget(spec) {
|
|
2524
|
+
if (!spec?.target || spec.space !== 'page') {
|
|
2525
|
+
return null;
|
|
2526
|
+
}
|
|
2527
|
+
return this._callApiDirect('resolvePageTarget', [spec.target, {
|
|
2528
|
+
maxMatches: 12,
|
|
2529
|
+
}], {
|
|
2530
|
+
timeoutMs: this.requestTimeoutMs,
|
|
2531
|
+
});
|
|
2532
|
+
}
|
|
2533
|
+
|
|
2534
|
+
_applyAugmentContent(node, content) {
|
|
2535
|
+
node.replaceChildren();
|
|
2536
|
+
const contentNode = document.createElement('div');
|
|
2537
|
+
contentNode.className = 'bbx-augment-content';
|
|
2538
|
+
|
|
2539
|
+
if (isDomNode(content)) {
|
|
2540
|
+
contentNode.append(content.cloneNode(true));
|
|
2541
|
+
} else if (content && typeof content === 'object' && !Array.isArray(content)) {
|
|
2542
|
+
if (content.type === 'html' && typeof content.html === 'string') {
|
|
2543
|
+
contentNode.innerHTML = content.html;
|
|
2544
|
+
} else if (content.type === 'text' && typeof content.text === 'string') {
|
|
2545
|
+
contentNode.textContent = content.text;
|
|
2546
|
+
} else if (content.type === 'json') {
|
|
2547
|
+
contentNode.textContent = JSON.stringify(content.data, null, 2);
|
|
2548
|
+
}
|
|
2549
|
+
} else if (content !== undefined && content !== null) {
|
|
2550
|
+
contentNode.textContent = typeof content === 'string' ? content : JSON.stringify(content, null, 2);
|
|
2551
|
+
}
|
|
2552
|
+
|
|
2553
|
+
node.append(contentNode);
|
|
2554
|
+
}
|
|
2555
|
+
|
|
2556
|
+
_applyAugmentPosition(node, spec, resolution = null) {
|
|
2557
|
+
node.style.position = spec.kind === 'toast' ? 'relative' : 'absolute';
|
|
2558
|
+
node.style.top = '';
|
|
2559
|
+
node.style.right = '';
|
|
2560
|
+
node.style.bottom = '';
|
|
2561
|
+
node.style.left = '';
|
|
2562
|
+
node.style.width = '';
|
|
2563
|
+
node.style.height = '';
|
|
2564
|
+
node.style.transform = '';
|
|
2565
|
+
node.style.maxWidth = '';
|
|
2566
|
+
node.style.maxHeight = '';
|
|
2567
|
+
|
|
2568
|
+
if (spec.space === 'page' && spec.kind !== 'highlight') {
|
|
2569
|
+
const box = resolution?.matches?.[0];
|
|
2570
|
+
if (box) {
|
|
2571
|
+
node.style.left = `${box.x}px`;
|
|
2572
|
+
node.style.top = `${box.y}px`;
|
|
2573
|
+
node.style.width = `${Math.max(40, box.width)}px`;
|
|
2574
|
+
node.style.height = `${Math.max(24, box.height)}px`;
|
|
2575
|
+
return;
|
|
2576
|
+
}
|
|
2577
|
+
}
|
|
2578
|
+
|
|
2579
|
+
const position = spec.position || (spec.kind === 'sidebar' ? 'right' : spec.kind === 'toolbar' ? 'top' : 'top-right');
|
|
2580
|
+
|
|
2581
|
+
if (spec.kind === 'sidebar') {
|
|
2582
|
+
node.style.top = '0';
|
|
2583
|
+
node.style.bottom = '0';
|
|
2584
|
+
node.style.width = 'min(360px, 38%)';
|
|
2585
|
+
if (position.includes('left')) {
|
|
2586
|
+
node.style.left = '0';
|
|
2587
|
+
} else {
|
|
2588
|
+
node.style.right = '0';
|
|
2589
|
+
}
|
|
2590
|
+
return;
|
|
2591
|
+
}
|
|
2592
|
+
|
|
2593
|
+
if (spec.kind === 'toolbar') {
|
|
2594
|
+
node.style.top = '12px';
|
|
2595
|
+
node.style.left = '50%';
|
|
2596
|
+
node.style.transform = 'translateX(-50%)';
|
|
2597
|
+
node.style.width = 'auto';
|
|
2598
|
+
node.style.maxWidth = 'calc(100% - 24px)';
|
|
2599
|
+
return;
|
|
2600
|
+
}
|
|
2601
|
+
|
|
2602
|
+
if (spec.kind === 'toast') {
|
|
2603
|
+
node.style.position = 'relative';
|
|
2604
|
+
node.style.maxWidth = '100%';
|
|
2605
|
+
return;
|
|
2606
|
+
}
|
|
2607
|
+
|
|
2608
|
+
node.style.maxWidth = 'min(360px, calc(100% - 24px))';
|
|
2609
|
+
if (position.includes('top')) {
|
|
2610
|
+
node.style.top = '12px';
|
|
2611
|
+
} else if (position.includes('bottom')) {
|
|
2612
|
+
node.style.bottom = '12px';
|
|
2613
|
+
} else {
|
|
2614
|
+
node.style.top = '50%';
|
|
2615
|
+
node.style.transform = 'translateY(-50%)';
|
|
2616
|
+
}
|
|
2617
|
+
if (position.includes('left')) {
|
|
2618
|
+
node.style.left = '12px';
|
|
2619
|
+
} else if (position.includes('right')) {
|
|
2620
|
+
node.style.right = '12px';
|
|
2621
|
+
} else {
|
|
2622
|
+
node.style.left = '50%';
|
|
2623
|
+
node.style.transform = node.style.transform ? `${node.style.transform} translateX(-50%)` : 'translateX(-50%)';
|
|
2624
|
+
}
|
|
2625
|
+
}
|
|
2626
|
+
|
|
2627
|
+
_applyAugmentStyle(node, spec) {
|
|
2628
|
+
node.style.cssText += '';
|
|
2629
|
+
if (typeof spec.style === 'string') {
|
|
2630
|
+
const tone = spec.style.trim().toLowerCase();
|
|
2631
|
+
if (tone && !tone.includes(':')) {
|
|
2632
|
+
node.dataset.tone = tone;
|
|
2633
|
+
} else if (tone) {
|
|
2634
|
+
node.style.cssText += `;${tone}`;
|
|
2635
|
+
}
|
|
2636
|
+
return;
|
|
2637
|
+
}
|
|
2638
|
+
if (spec.style && typeof spec.style === 'object' && !Array.isArray(spec.style)) {
|
|
2639
|
+
for (const [key, value] of Object.entries(spec.style)) {
|
|
2640
|
+
node.style.setProperty(key, String(value));
|
|
2641
|
+
}
|
|
2642
|
+
}
|
|
2643
|
+
}
|
|
2644
|
+
|
|
2645
|
+
_renderHighlightAugment(node, record) {
|
|
2646
|
+
const tone = typeof record.spec.style === 'string' ? record.spec.style.trim().toLowerCase() : 'warning';
|
|
2647
|
+
const matches = Array.isArray(record.resolution?.matches) ? record.resolution.matches : [];
|
|
2648
|
+
node.replaceChildren();
|
|
2649
|
+
node.className = 'bbx-augment bbx-augment-surface';
|
|
2650
|
+
node.dataset.kind = record.spec.kind;
|
|
2651
|
+
node.dataset.space = record.spec.space;
|
|
2652
|
+
node.dataset.interactive = String(record.spec.interactive);
|
|
2653
|
+
node.style.display = record.spec.visible && matches.length > 0 ? 'block' : 'none';
|
|
2654
|
+
for (const box of matches) {
|
|
2655
|
+
const highlight = document.createElement('div');
|
|
2656
|
+
highlight.className = 'bbx-highlight-box';
|
|
2657
|
+
highlight.dataset.tone = tone;
|
|
2658
|
+
highlight.style.left = `${box.x}px`;
|
|
2659
|
+
highlight.style.top = `${box.y}px`;
|
|
2660
|
+
highlight.style.width = `${box.width}px`;
|
|
2661
|
+
highlight.style.height = `${box.height}px`;
|
|
2662
|
+
node.append(highlight);
|
|
2663
|
+
}
|
|
2664
|
+
}
|
|
2665
|
+
|
|
2666
|
+
_renderStandardAugment(node, record) {
|
|
2667
|
+
node.className = `bbx-augment bbx-augment-${record.spec.kind}`;
|
|
2668
|
+
node.dataset.kind = record.spec.kind;
|
|
2669
|
+
node.dataset.space = record.spec.space;
|
|
2670
|
+
node.dataset.interactive = String(record.spec.interactive);
|
|
2671
|
+
node.style.display = record.spec.visible ? '' : 'none';
|
|
2672
|
+
this._applyAugmentPosition(node, record.spec, record.resolution);
|
|
2673
|
+
this._applyAugmentContent(node, record.spec.content);
|
|
2674
|
+
this._applyAugmentStyle(node, record.spec);
|
|
2675
|
+
}
|
|
2676
|
+
|
|
2677
|
+
_renderAugmentRecord(record) {
|
|
2678
|
+
const root = this._augmentRoots[record.spec.kind === 'toast' ? 'toast' : record.spec.space] || this._augmentRoots.session;
|
|
2679
|
+
if (!record.node) {
|
|
2680
|
+
record.node = document.createElement('div');
|
|
2681
|
+
record.node.dataset.augmentId = record.spec.id;
|
|
2682
|
+
root.append(record.node);
|
|
2683
|
+
} else if (record.node.parentNode !== root) {
|
|
2684
|
+
root.append(record.node);
|
|
2685
|
+
}
|
|
2686
|
+
|
|
2687
|
+
if (record.spec.kind === 'highlight') {
|
|
2688
|
+
this._renderHighlightAugment(record.node, record);
|
|
2689
|
+
} else {
|
|
2690
|
+
this._renderStandardAugment(record.node, record);
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
|
|
2694
|
+
async _createAugment(spec) {
|
|
2695
|
+
const normalized = normalizeAugmentSpec(spec);
|
|
2696
|
+
this._assertCapability('augment.write');
|
|
2697
|
+
this._assertCapability(`augment.${normalized.space}`);
|
|
2698
|
+
if (this._augmentRegistry.has(normalized.id)) {
|
|
2699
|
+
throw createBrowserBoxError(`hyper-frame augment '${normalized.id}' already exists.`, {
|
|
2700
|
+
code: ERROR_CODES.CONFLICT,
|
|
2701
|
+
status: 409,
|
|
2702
|
+
augmentId: normalized.id,
|
|
2703
|
+
});
|
|
2704
|
+
}
|
|
2705
|
+
const record = {
|
|
2706
|
+
spec: normalized,
|
|
2707
|
+
resolution: await this._resolveAugmentTarget(normalized),
|
|
2708
|
+
node: null,
|
|
2709
|
+
};
|
|
2710
|
+
this._augmentRegistry.set(normalized.id, record);
|
|
2711
|
+
this._renderAugmentRecord(record);
|
|
2712
|
+
return Object.freeze({
|
|
2713
|
+
id: normalized.id,
|
|
2714
|
+
kind: normalized.kind,
|
|
2715
|
+
space: normalized.space,
|
|
2716
|
+
...(normalized.position === undefined ? {} : { position: normalized.position }),
|
|
2717
|
+
...(normalized.target === undefined ? {} : { target: cloneJsonValue(normalized.target) }),
|
|
2718
|
+
interactive: normalized.interactive,
|
|
2719
|
+
visible: normalized.visible,
|
|
2720
|
+
remove: () => this._removeAugment(normalized.id),
|
|
2721
|
+
update: (patch) => this._updateAugment(normalized.id, patch),
|
|
2722
|
+
});
|
|
2723
|
+
}
|
|
2724
|
+
|
|
2725
|
+
async _updateAugment(id, patch) {
|
|
2726
|
+
const augmentId = assertNonEmptyString(id, 'augment.update(id)');
|
|
2727
|
+
this._assertCapability('augment.write');
|
|
2728
|
+
const record = this._augmentRegistry.get(augmentId);
|
|
2729
|
+
if (!record) {
|
|
2730
|
+
throw createBrowserBoxError(`hyper-frame augment '${augmentId}' does not exist.`, {
|
|
2731
|
+
code: ERROR_CODES.NOT_FOUND,
|
|
2732
|
+
status: 404,
|
|
2733
|
+
augmentId,
|
|
2734
|
+
});
|
|
2735
|
+
}
|
|
2736
|
+
const merged = normalizeAugmentSpec({
|
|
2737
|
+
...record.spec,
|
|
2738
|
+
...(patch && typeof patch === 'object' && !Array.isArray(patch) ? patch : {}),
|
|
2739
|
+
id: augmentId,
|
|
2740
|
+
});
|
|
2741
|
+
this._assertCapability(`augment.${merged.space}`);
|
|
2742
|
+
record.spec = merged;
|
|
2743
|
+
record.resolution = await this._resolveAugmentTarget(merged);
|
|
2744
|
+
this._renderAugmentRecord(record);
|
|
2745
|
+
}
|
|
2746
|
+
|
|
2747
|
+
async _removeAugment(id) {
|
|
2748
|
+
const augmentId = assertNonEmptyString(id, 'augment.remove(id)');
|
|
2749
|
+
this._assertCapability('augment.write');
|
|
2750
|
+
const record = this._augmentRegistry.get(augmentId);
|
|
2751
|
+
if (!record) {
|
|
2752
|
+
return false;
|
|
2753
|
+
}
|
|
2754
|
+
record.node?.remove();
|
|
2755
|
+
this._augmentRegistry.delete(augmentId);
|
|
2756
|
+
return true;
|
|
2757
|
+
}
|
|
2758
|
+
|
|
2759
|
+
async _listAugments() {
|
|
2760
|
+
this._assertCapability('augment.read');
|
|
2761
|
+
return [...this._augmentRegistry.values()].map((record) => normalizeAugmentInfo(record.spec));
|
|
2762
|
+
}
|
|
2763
|
+
|
|
2764
|
+
async select(options = {}) {
|
|
2765
|
+
this._assertCapability('select.use');
|
|
2766
|
+
const timeoutMs = Number.isFinite(options?.timeoutMs)
|
|
2767
|
+
? Math.max(1000, Math.round(options.timeoutMs))
|
|
2768
|
+
: Math.max(this.requestTimeoutMs, 120000);
|
|
2769
|
+
const rawSelection = await this._callApiDirect('beginSelect', [options], { timeoutMs });
|
|
2770
|
+
return createSelectionHandle(this, rawSelection);
|
|
2771
|
+
}
|
|
2772
|
+
|
|
2773
|
+
async _generalizeSelection(rawSelection) {
|
|
2774
|
+
return this._callApiDirect('generalizeSelection', [rawSelection], {
|
|
2775
|
+
timeoutMs: this.requestTimeoutMs,
|
|
2776
|
+
});
|
|
2777
|
+
}
|
|
2778
|
+
|
|
2779
|
+
async _extractSelection(target, options = {}) {
|
|
2780
|
+
this._assertCapability('select.extract');
|
|
2781
|
+
const extractOptions = {
|
|
2782
|
+
...options,
|
|
2783
|
+
...(Number.isInteger(options?.limit) ? { maxItems: options.limit } : {}),
|
|
2784
|
+
};
|
|
2785
|
+
const result = await this._callApiDirect('extractSelection', [target, extractOptions], {
|
|
2786
|
+
timeoutMs: Number.isFinite(options?.timeoutMs) ? options.timeoutMs : this.requestTimeoutMs,
|
|
2787
|
+
});
|
|
2788
|
+
return normalizeExtractResult(target, result);
|
|
2789
|
+
}
|
|
2790
|
+
|
|
2791
|
+
async _previewSelectionPattern(target, previewId) {
|
|
2792
|
+
const pattern = target?.selector ? { selector: target.selector } : target;
|
|
2793
|
+
const resolution = await this._callApiDirect('resolvePageTarget', [pattern, { maxMatches: 12 }], {
|
|
2794
|
+
timeoutMs: this.requestTimeoutMs,
|
|
2795
|
+
});
|
|
2796
|
+
await this._upsertPreviewAugment(previewId, pattern, resolution);
|
|
2797
|
+
return normalizePreviewResult(pattern, resolution);
|
|
2798
|
+
}
|
|
2799
|
+
|
|
2800
|
+
async _upsertPreviewAugment(previewId, pattern, resolution) {
|
|
2801
|
+
const record = this._augmentRegistry.get(previewId);
|
|
2802
|
+
const spec = {
|
|
2803
|
+
id: previewId,
|
|
2804
|
+
kind: 'highlight',
|
|
2805
|
+
space: 'page',
|
|
2806
|
+
target: pattern,
|
|
2807
|
+
style: 'info',
|
|
2808
|
+
interactive: false,
|
|
2809
|
+
visible: true,
|
|
2810
|
+
};
|
|
2811
|
+
if (!record) {
|
|
2812
|
+
this._augmentRegistry.set(previewId, {
|
|
2813
|
+
spec,
|
|
2814
|
+
resolution,
|
|
2815
|
+
node: null,
|
|
2816
|
+
});
|
|
2817
|
+
this._renderAugmentRecord(this._augmentRegistry.get(previewId));
|
|
2818
|
+
return;
|
|
2819
|
+
}
|
|
2820
|
+
record.spec = spec;
|
|
2821
|
+
record.resolution = resolution;
|
|
2822
|
+
this._renderAugmentRecord(record);
|
|
2823
|
+
}
|
|
2824
|
+
|
|
2825
|
+
_handleMessage(event) {
|
|
2826
|
+
if (event.source !== this.iframe.contentWindow) {
|
|
2827
|
+
return;
|
|
2828
|
+
}
|
|
2829
|
+
if (!this._validateIncomingOrigin(event.origin)) {
|
|
2830
|
+
return;
|
|
2831
|
+
}
|
|
2832
|
+
|
|
2833
|
+
const payload = event.data || {};
|
|
2834
|
+
if (typeof payload.type !== 'string') {
|
|
2835
|
+
return;
|
|
2836
|
+
}
|
|
2837
|
+
|
|
2838
|
+
if (payload.type === 'bbx-mid-request') {
|
|
2839
|
+
console.info('[bbx-mid] child requested mid');
|
|
2840
|
+
this._postMidSync('child-request');
|
|
2841
|
+
return;
|
|
2842
|
+
}
|
|
2843
|
+
|
|
2844
|
+
if (payload.type === 'bbx-mid-ack') {
|
|
2845
|
+
const ackMid = this._normalizeMid(payload.data?.mid ?? payload.mid);
|
|
2846
|
+
console.info('[bbx-mid] received ack', {
|
|
2847
|
+
ackMid,
|
|
2848
|
+
expectedMid: this._routingMid,
|
|
2849
|
+
});
|
|
2850
|
+
if (this._routingMid && (!ackMid || ackMid === this._routingMid)) {
|
|
2851
|
+
this._midSyncAcked = true;
|
|
2852
|
+
this._stopMidSync();
|
|
2853
|
+
console.info('[bbx-mid] sync established', {
|
|
2854
|
+
mid: this._routingMid,
|
|
2855
|
+
attempts: Math.max(1, this._midSyncAttempt),
|
|
2856
|
+
});
|
|
2857
|
+
this.dispatchEvent(new CustomEvent('mid-synced', {
|
|
2858
|
+
detail: {
|
|
2859
|
+
mid: this._routingMid,
|
|
2860
|
+
attempts: Math.max(1, this._midSyncAttempt),
|
|
2861
|
+
},
|
|
2862
|
+
}));
|
|
2863
|
+
} else {
|
|
2864
|
+
console.warn('[bbx-mid] ack mid mismatch', {
|
|
2865
|
+
ackMid,
|
|
2866
|
+
expectedMid: this._routingMid,
|
|
2867
|
+
});
|
|
2868
|
+
}
|
|
2869
|
+
return;
|
|
2870
|
+
}
|
|
2871
|
+
|
|
2872
|
+
if (payload.type === 'bbx-ui-request') {
|
|
2873
|
+
this._sendUISync('child-request');
|
|
2874
|
+
return;
|
|
2875
|
+
}
|
|
2876
|
+
|
|
2877
|
+
if (payload.type === 'bbx-ui-ack') {
|
|
2878
|
+
this._uiSyncAcked = true;
|
|
2879
|
+
return;
|
|
2880
|
+
}
|
|
2881
|
+
|
|
2882
|
+
if (payload.type === 'bbx-sos') {
|
|
2883
|
+
const incoming = (payload.data && typeof payload.data === 'object')
|
|
2884
|
+
? payload.data
|
|
2885
|
+
: {};
|
|
2886
|
+
const reasonCode = typeof incoming.reasonCode === 'string' && incoming.reasonCode.length > 0
|
|
2887
|
+
? incoming.reasonCode
|
|
2888
|
+
: 'browser-unusable';
|
|
2889
|
+
const detail = {
|
|
2890
|
+
...incoming,
|
|
2891
|
+
reasonCode,
|
|
2892
|
+
iframeOrigin: event.origin,
|
|
2893
|
+
routingMid: this._routingMid || '',
|
|
2894
|
+
loginLink: this.loginLink || '',
|
|
2895
|
+
forwardedAt: Date.now(),
|
|
2896
|
+
forwardedBy: 'hyper-frame',
|
|
2897
|
+
};
|
|
2898
|
+
this._setUsable(false, `sos:${reasonCode}`);
|
|
2899
|
+
this._emitBrowserBoxEvent('sos', detail);
|
|
2900
|
+
this._forwardToParent({
|
|
2901
|
+
type: 'bbx-sos',
|
|
2902
|
+
data: detail,
|
|
2903
|
+
});
|
|
2904
|
+
return;
|
|
2905
|
+
}
|
|
2906
|
+
|
|
2907
|
+
if (payload.requestId && this._pending.has(payload.requestId)) {
|
|
2908
|
+
const pending = this._pending.get(payload.requestId);
|
|
2909
|
+
clearTimeout(pending.timer);
|
|
2910
|
+
this._pending.delete(payload.requestId);
|
|
2911
|
+
if (payload.error) {
|
|
2912
|
+
const error = this._normalizeRemoteError(payload.error, {
|
|
2913
|
+
requestId: payload.requestId,
|
|
2914
|
+
requestType: payload.type,
|
|
2915
|
+
});
|
|
2916
|
+
this._rememberError(error);
|
|
2917
|
+
pending.reject(error);
|
|
2918
|
+
} else {
|
|
2919
|
+
this._rememberError(null);
|
|
2920
|
+
pending.resolve(payload.data);
|
|
2921
|
+
}
|
|
2922
|
+
return;
|
|
2923
|
+
}
|
|
2924
|
+
|
|
2925
|
+
if (payload.type === 'tab-api-ready') {
|
|
2926
|
+
this._setReady();
|
|
2927
|
+
this._emitBrowserBoxEvent('ready', { type: payload.type });
|
|
2928
|
+
return;
|
|
2929
|
+
}
|
|
2930
|
+
|
|
2931
|
+
if (payload.type === 'bbx-api-ready') {
|
|
2932
|
+
if (Array.isArray(payload.data?.methods)) {
|
|
2933
|
+
this._apiMethods = payload.data.methods.slice();
|
|
2934
|
+
this._transportMode = 'modern';
|
|
2935
|
+
}
|
|
2936
|
+
if (payload.data?.policy) {
|
|
2937
|
+
this._serverPolicySnapshot = normalizePolicyStateSnapshot(payload.data.policy);
|
|
2938
|
+
this._refreshPolicyState('server-policy-ready');
|
|
2939
|
+
}
|
|
2940
|
+
this._setReady();
|
|
2941
|
+
this._emitBrowserBoxEvent('api-ready', payload.data || {});
|
|
2942
|
+
return;
|
|
2943
|
+
}
|
|
2944
|
+
|
|
2945
|
+
if (payload.type === 'bbx-policy-sync') {
|
|
2946
|
+
this._serverPolicySnapshot = normalizePolicyStateSnapshot(payload.data?.policy ?? payload.data);
|
|
2947
|
+
this._refreshPolicyState('server-policy-sync');
|
|
2948
|
+
return;
|
|
2949
|
+
}
|
|
2950
|
+
|
|
2951
|
+
if (payload.type === 'active-tab-changed') {
|
|
2952
|
+
this._invalidateFrameBootstrap('active-tab-changed');
|
|
2953
|
+
}
|
|
2954
|
+
|
|
2955
|
+
if (payload.type === 'tab-updated' || payload.type === 'tab-attached') {
|
|
2956
|
+
this._updateLegacyTabCache(payload.data);
|
|
2957
|
+
} else if (payload.type === 'tab-created') {
|
|
2958
|
+
this._addLegacyTabCache(payload.data);
|
|
2959
|
+
} else if (payload.type === 'tab-closed') {
|
|
2960
|
+
this._removeLegacyTabCache(payload.data);
|
|
2961
|
+
}
|
|
2962
|
+
|
|
2963
|
+
this._emitBrowserBoxEvent(payload.type, payload.data || {});
|
|
2964
|
+
}
|
|
2965
|
+
|
|
2966
|
+
_request(type, data = {}, options = {}) {
|
|
2967
|
+
if (!this.iframe.contentWindow) {
|
|
2968
|
+
const error = createBrowserBoxError('hyper-frame iframe is not ready.', {
|
|
2969
|
+
code: ERROR_CODES.TRANSPORT,
|
|
2970
|
+
retriable: true,
|
|
2971
|
+
status: 503,
|
|
2972
|
+
requestType: type,
|
|
2973
|
+
});
|
|
2974
|
+
this._rememberError(error);
|
|
2975
|
+
return Promise.reject(error);
|
|
2976
|
+
}
|
|
2977
|
+
|
|
2978
|
+
const timeoutMs = Number.isFinite(options.timeoutMs)
|
|
2979
|
+
? Math.max(100, Math.round(options.timeoutMs))
|
|
2980
|
+
: this.requestTimeoutMs;
|
|
2981
|
+
|
|
2982
|
+
const requestId = `bbx-${Date.now()}-${++this._requestSeq}`;
|
|
2983
|
+
const message = { type, requestId, data, ...(options.messageExtras || {}) };
|
|
2984
|
+
const targetOrigin = this._outboundTargetOrigin();
|
|
2985
|
+
|
|
2986
|
+
return new Promise((resolve, reject) => {
|
|
2987
|
+
const timer = setTimeout(() => {
|
|
2988
|
+
this._pending.delete(requestId);
|
|
2989
|
+
const error = createBrowserBoxError(`hyper-frame request timed out (${type}) after ${timeoutMs}ms.`, {
|
|
2990
|
+
code: ERROR_CODES.TIMEOUT,
|
|
2991
|
+
retriable: true,
|
|
2992
|
+
status: 504,
|
|
2993
|
+
requestId,
|
|
2994
|
+
requestType: type,
|
|
2995
|
+
timeoutMs,
|
|
2996
|
+
});
|
|
2997
|
+
this._rememberError(error);
|
|
2998
|
+
reject(error);
|
|
2999
|
+
}, timeoutMs);
|
|
3000
|
+
|
|
3001
|
+
this._pending.set(requestId, { resolve, reject, timer });
|
|
3002
|
+
try {
|
|
3003
|
+
this.iframe.contentWindow.postMessage(message, targetOrigin);
|
|
3004
|
+
} catch (error) {
|
|
3005
|
+
clearTimeout(timer);
|
|
3006
|
+
this._pending.delete(requestId);
|
|
3007
|
+
const transportError = createBrowserBoxError(`hyper-frame failed to postMessage '${type}'.`, {
|
|
3008
|
+
code: ERROR_CODES.TRANSPORT,
|
|
3009
|
+
retriable: true,
|
|
3010
|
+
status: 503,
|
|
3011
|
+
requestId,
|
|
3012
|
+
requestType: type,
|
|
3013
|
+
cause: error,
|
|
3014
|
+
});
|
|
3015
|
+
this._rememberError(transportError);
|
|
3016
|
+
reject(transportError);
|
|
3017
|
+
}
|
|
3018
|
+
});
|
|
3019
|
+
}
|
|
3020
|
+
|
|
3021
|
+
_postRaw(message) {
|
|
3022
|
+
if (!this.iframe.contentWindow) {
|
|
3023
|
+
return;
|
|
3024
|
+
}
|
|
3025
|
+
this.iframe.contentWindow.postMessage(message, this._outboundTargetOrigin());
|
|
3026
|
+
}
|
|
3027
|
+
|
|
3028
|
+
_forwardToParent(message) {
|
|
3029
|
+
if (window.parent === window) {
|
|
3030
|
+
return;
|
|
3031
|
+
}
|
|
3032
|
+
try {
|
|
3033
|
+
window.parent.postMessage(message, '*');
|
|
3034
|
+
} catch (error) {
|
|
3035
|
+
console.warn('[hyper-frame] failed to forward message to parent', error);
|
|
3036
|
+
}
|
|
3037
|
+
}
|
|
3038
|
+
|
|
3039
|
+
async whenReady({ timeoutMs = this.requestTimeoutMs } = {}) {
|
|
3040
|
+
if (this._isReady) {
|
|
3041
|
+
return true;
|
|
3042
|
+
}
|
|
3043
|
+
|
|
3044
|
+
const timeout = new Promise((_, reject) => {
|
|
3045
|
+
setTimeout(() => reject(createBrowserBoxError(`hyper-frame ready timeout after ${timeoutMs}ms.`, {
|
|
3046
|
+
code: ERROR_CODES.TIMEOUT,
|
|
3047
|
+
retriable: true,
|
|
3048
|
+
status: 504,
|
|
3049
|
+
timeoutMs,
|
|
3050
|
+
})), timeoutMs);
|
|
3051
|
+
});
|
|
3052
|
+
|
|
3053
|
+
await Promise.race([this._readyPromise, timeout]);
|
|
3054
|
+
return true;
|
|
3055
|
+
}
|
|
3056
|
+
|
|
3057
|
+
on(eventName, handler, options) {
|
|
3058
|
+
this._assertCapability('events.read');
|
|
3059
|
+
if (typeof eventName !== 'string' || eventName.trim().length === 0) {
|
|
3060
|
+
throwInvalidArgument('hyper-frame on(eventName, handler) requires a non-empty eventName.');
|
|
3061
|
+
}
|
|
3062
|
+
if (typeof handler !== 'function') {
|
|
3063
|
+
throwInvalidArgument('hyper-frame on(eventName, handler) requires handler to be a function.');
|
|
3064
|
+
}
|
|
3065
|
+
this.addEventListener(eventName, handler, options);
|
|
3066
|
+
return () => {
|
|
3067
|
+
this.removeEventListener(eventName, handler, options);
|
|
3068
|
+
};
|
|
3069
|
+
}
|
|
3070
|
+
|
|
3071
|
+
off(eventName, handler, options) {
|
|
3072
|
+
if (typeof eventName !== 'string' || eventName.trim().length === 0) {
|
|
3073
|
+
throwInvalidArgument('hyper-frame off(eventName, handler) requires a non-empty eventName.');
|
|
3074
|
+
}
|
|
3075
|
+
if (typeof handler !== 'function') {
|
|
3076
|
+
throwInvalidArgument('hyper-frame off(eventName, handler) requires handler to be a function.');
|
|
3077
|
+
}
|
|
3078
|
+
this.removeEventListener(eventName, handler, options);
|
|
3079
|
+
}
|
|
3080
|
+
|
|
3081
|
+
async observe(config = {}) {
|
|
3082
|
+
this._assertCapability('events.read');
|
|
3083
|
+
const subscriptionEntries = [];
|
|
3084
|
+
const snapshot = (!config || typeof config !== 'object' || Array.isArray(config))
|
|
3085
|
+
? {}
|
|
3086
|
+
: { ...config };
|
|
3087
|
+
const id = generateOpaqueId('bbx-observe');
|
|
3088
|
+
return {
|
|
3089
|
+
id,
|
|
3090
|
+
config: snapshot,
|
|
3091
|
+
on: (eventName, handler, options) => {
|
|
3092
|
+
const unsubscribe = this.on(eventName, handler, options);
|
|
3093
|
+
subscriptionEntries.push({ eventName, handler, options });
|
|
3094
|
+
return unsubscribe;
|
|
3095
|
+
},
|
|
3096
|
+
off: (eventName, handler, options) => {
|
|
3097
|
+
this.off(eventName, handler, options);
|
|
3098
|
+
},
|
|
3099
|
+
unsubscribe: () => {
|
|
3100
|
+
for (const entry of subscriptionEntries.splice(0, subscriptionEntries.length)) {
|
|
3101
|
+
this.removeEventListener(entry.eventName, entry.handler, entry.options);
|
|
3102
|
+
}
|
|
3103
|
+
},
|
|
3104
|
+
};
|
|
3105
|
+
}
|
|
3106
|
+
|
|
3107
|
+
events(options = {}) {
|
|
3108
|
+
this._assertCapability('events.read');
|
|
3109
|
+
const eventNames = Array.isArray(options?.eventNames)
|
|
3110
|
+
? new Set(options.eventNames.map((name) => String(name)))
|
|
3111
|
+
: null;
|
|
3112
|
+
const subscriber = {
|
|
3113
|
+
queue: [],
|
|
3114
|
+
resolve: null,
|
|
3115
|
+
closed: false,
|
|
3116
|
+
maxQueue: Number.isInteger(options?.maxQueue) ? Math.max(10, options.maxQueue) : 100,
|
|
3117
|
+
filter: eventNames ? ((event) => eventNames.has(event.type)) : (() => true),
|
|
3118
|
+
};
|
|
3119
|
+
this._eventSubscribers.add(subscriber);
|
|
3120
|
+
|
|
3121
|
+
const cleanup = () => {
|
|
3122
|
+
subscriber.closed = true;
|
|
3123
|
+
this._eventSubscribers.delete(subscriber);
|
|
3124
|
+
if (subscriber.resolve) {
|
|
3125
|
+
const resolve = subscriber.resolve;
|
|
3126
|
+
subscriber.resolve = null;
|
|
3127
|
+
resolve({ value: undefined, done: true });
|
|
3128
|
+
}
|
|
3129
|
+
};
|
|
3130
|
+
|
|
3131
|
+
return {
|
|
3132
|
+
[Symbol.asyncIterator]() {
|
|
3133
|
+
return this;
|
|
3134
|
+
},
|
|
3135
|
+
next: () => {
|
|
3136
|
+
if (subscriber.closed) {
|
|
3137
|
+
return Promise.resolve({ value: undefined, done: true });
|
|
3138
|
+
}
|
|
3139
|
+
const queued = subscriber.queue.shift();
|
|
3140
|
+
if (queued) {
|
|
3141
|
+
return Promise.resolve({ value: queued, done: false });
|
|
3142
|
+
}
|
|
3143
|
+
return new Promise((resolve) => {
|
|
3144
|
+
subscriber.resolve = resolve;
|
|
3145
|
+
});
|
|
3146
|
+
},
|
|
3147
|
+
return: () => {
|
|
3148
|
+
cleanup();
|
|
3149
|
+
return Promise.resolve({ value: undefined, done: true });
|
|
3150
|
+
},
|
|
3151
|
+
throw: async (error) => {
|
|
3152
|
+
cleanup();
|
|
3153
|
+
throw error;
|
|
3154
|
+
},
|
|
3155
|
+
};
|
|
3156
|
+
}
|
|
3157
|
+
|
|
3158
|
+
async _ensureReadyForApi() {
|
|
3159
|
+
if (this._isReady) {
|
|
3160
|
+
return true;
|
|
3161
|
+
}
|
|
3162
|
+
const softTimeoutMs = Math.min(this.requestTimeoutMs, 8000);
|
|
3163
|
+
try {
|
|
3164
|
+
await this.whenReady({ timeoutMs: softTimeoutMs });
|
|
3165
|
+
return true;
|
|
3166
|
+
} catch (error) {
|
|
3167
|
+
this._rememberError(error);
|
|
3168
|
+
this.dispatchEvent(new CustomEvent('ready-timeout', {
|
|
3169
|
+
detail: {
|
|
3170
|
+
timeoutMs: softTimeoutMs,
|
|
3171
|
+
error: error instanceof Error ? error.message : String(error),
|
|
3172
|
+
},
|
|
3173
|
+
}));
|
|
3174
|
+
return false;
|
|
3175
|
+
}
|
|
3176
|
+
}
|
|
3177
|
+
|
|
3178
|
+
_legacyMethodList() {
|
|
3179
|
+
return [
|
|
3180
|
+
'getTabs',
|
|
3181
|
+
'getActiveTabIndex',
|
|
3182
|
+
'getTabCount',
|
|
3183
|
+
'createTab',
|
|
3184
|
+
'createTabs',
|
|
3185
|
+
'closeTab',
|
|
3186
|
+
'closeTabById',
|
|
3187
|
+
'closeAllTabs',
|
|
3188
|
+
'switchToTab',
|
|
3189
|
+
'switchToTabById',
|
|
3190
|
+
'navigateTo',
|
|
3191
|
+
'navigateTab',
|
|
3192
|
+
'submitOmnibox',
|
|
3193
|
+
'reload',
|
|
3194
|
+
'goBack',
|
|
3195
|
+
'goForward',
|
|
3196
|
+
'stop',
|
|
3197
|
+
'evaluate',
|
|
3198
|
+
'waitForTabCount',
|
|
3199
|
+
'waitForTabUrl',
|
|
3200
|
+
];
|
|
3201
|
+
}
|
|
3202
|
+
|
|
3203
|
+
/**
|
|
3204
|
+
* Resolve transport mode. Called once on first API call if transport is
|
|
3205
|
+
* still 'unknown'. After resolution, transport is locked for the session.
|
|
3206
|
+
* @returns {Promise<'modern'|'legacy'>}
|
|
3207
|
+
*/
|
|
3208
|
+
async _resolveTransport() {
|
|
3209
|
+
if (this._transportMode !== 'unknown') return this._transportMode;
|
|
3210
|
+
try {
|
|
3211
|
+
await this._request('bbx-api-call', { method: 'getTabCount', args: [] }, {
|
|
3212
|
+
timeoutMs: Math.min(this.requestTimeoutMs, 5000),
|
|
3213
|
+
});
|
|
3214
|
+
this._transportMode = 'modern';
|
|
3215
|
+
} catch {
|
|
3216
|
+
this._transportMode = 'legacy';
|
|
3217
|
+
}
|
|
3218
|
+
return this._transportMode;
|
|
3219
|
+
}
|
|
3220
|
+
|
|
3221
|
+
async listApiMethods(options = {}) {
|
|
3222
|
+
if (this._apiMethods.length > 0 && options.refresh !== true) {
|
|
3223
|
+
return this._apiMethods.slice();
|
|
3224
|
+
}
|
|
3225
|
+
const ready = await this._ensureReadyForApi();
|
|
3226
|
+
if (!ready) {
|
|
3227
|
+
throw createBrowserBoxError('hyper-frame API handshake is not ready.', {
|
|
3228
|
+
code: ERROR_CODES.NOT_READY,
|
|
3229
|
+
retriable: true,
|
|
3230
|
+
status: 409,
|
|
3231
|
+
});
|
|
3232
|
+
}
|
|
3233
|
+
if (this._transportMode === 'legacy') {
|
|
3234
|
+
this._apiMethods = this._legacyMethodList();
|
|
3235
|
+
return this._apiMethods.slice();
|
|
3236
|
+
}
|
|
3237
|
+
try {
|
|
3238
|
+
const methods = await this._request('bbx-api-list', {}, {
|
|
3239
|
+
...options,
|
|
3240
|
+
timeoutMs: Number.isFinite(options.timeoutMs)
|
|
3241
|
+
? options.timeoutMs
|
|
3242
|
+
: Math.min(this.requestTimeoutMs, 30000),
|
|
3243
|
+
});
|
|
3244
|
+
this._apiMethods = Array.isArray(methods) ? methods.slice() : [];
|
|
3245
|
+
this._transportMode = 'modern';
|
|
3246
|
+
} catch {
|
|
3247
|
+
this._transportMode = 'legacy';
|
|
3248
|
+
this._apiMethods = this._legacyMethodList();
|
|
3249
|
+
}
|
|
3250
|
+
return this._apiMethods.slice();
|
|
3251
|
+
}
|
|
3252
|
+
|
|
3253
|
+
/**
|
|
3254
|
+
* Call a BrowserBox API method by name.
|
|
3255
|
+
* @param {string} method - API method name (e.g. 'getTabs', 'createTab')
|
|
3256
|
+
* @param {...*} args - Method arguments
|
|
3257
|
+
* @returns {Promise<*>} Method result
|
|
3258
|
+
* @throws {Error} If method is empty, transport fails, or call times out
|
|
3259
|
+
*/
|
|
3260
|
+
async callApi(method, ...args) {
|
|
3261
|
+
if (typeof method !== 'string' || method.trim().length === 0) {
|
|
3262
|
+
throwInvalidArgument('callApi(method, ...args) requires a non-empty method string.');
|
|
3263
|
+
}
|
|
3264
|
+
const invoke = async () => {
|
|
3265
|
+
const ready = await this._ensureReadyForApi();
|
|
3266
|
+
if (!ready) {
|
|
3267
|
+
throw createBrowserBoxError(`hyper-frame API method '${method}' called before handshake completed.`, {
|
|
3268
|
+
code: ERROR_CODES.NOT_READY,
|
|
3269
|
+
retriable: true,
|
|
3270
|
+
status: 409,
|
|
3271
|
+
method,
|
|
3272
|
+
});
|
|
3273
|
+
}
|
|
3274
|
+
const normalizedMethod = method.trim();
|
|
3275
|
+
for (const capability of this._capabilitiesForMethod(normalizedMethod, args)) {
|
|
3276
|
+
this._assertCapability(capability);
|
|
3277
|
+
}
|
|
3278
|
+
|
|
3279
|
+
if (this._transportMode === 'unknown') {
|
|
3280
|
+
await this._resolveTransport();
|
|
3281
|
+
}
|
|
3282
|
+
|
|
3283
|
+
if (this._transportMode === 'legacy') {
|
|
3284
|
+
return this._legacyCall(normalizedMethod, args);
|
|
3285
|
+
}
|
|
3286
|
+
|
|
3287
|
+
return this._request('bbx-api-call', { method: normalizedMethod, args }, {
|
|
3288
|
+
timeoutMs: this.requestTimeoutMs,
|
|
3289
|
+
});
|
|
3290
|
+
};
|
|
3291
|
+
|
|
3292
|
+
try {
|
|
3293
|
+
const result = await this._withRetry(invoke, {
|
|
3294
|
+
attempts: 3,
|
|
3295
|
+
baseDelayMs: 300,
|
|
3296
|
+
maxDelayMs: 1500,
|
|
3297
|
+
shouldRetry: (error) => this._isRetryableApiError(error),
|
|
3298
|
+
});
|
|
3299
|
+
this._rememberError(null);
|
|
3300
|
+
this._setUsable(true, 'api-ok');
|
|
3301
|
+
return result;
|
|
3302
|
+
} catch (error) {
|
|
3303
|
+
this._rememberError(error);
|
|
3304
|
+
if (this._isRetryableApiError(error)) {
|
|
3305
|
+
this._setUsable(false, 'api-failed');
|
|
3306
|
+
}
|
|
3307
|
+
throw this._normalizeRemoteError(error, { method });
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
|
|
3311
|
+
async act(actionRequest) {
|
|
3312
|
+
if (!actionRequest || typeof actionRequest !== 'object' || Array.isArray(actionRequest)) {
|
|
3313
|
+
throwInvalidArgument('hyper-frame act(action) requires an object action request.');
|
|
3314
|
+
}
|
|
3315
|
+
const actionNames = Object.keys(actionRequest).filter((key) => actionRequest[key] !== undefined);
|
|
3316
|
+
if (actionNames.length !== 1) {
|
|
3317
|
+
throwInvalidArgument('hyper-frame act(action) requires exactly one action key.');
|
|
3318
|
+
}
|
|
3319
|
+
|
|
3320
|
+
const actionName = actionNames[0];
|
|
3321
|
+
const payload = actionRequest[actionName];
|
|
3322
|
+
let value;
|
|
3323
|
+
|
|
3324
|
+
switch (actionName) {
|
|
3325
|
+
case 'navigate':
|
|
3326
|
+
value = await this.page.navigate(assertNonEmptyString(payload, 'act({ navigate })'));
|
|
3327
|
+
return normalizeActionResult(actionName, value);
|
|
3328
|
+
case 'click': {
|
|
3329
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
3330
|
+
throwInvalidArgument('hyper-frame act({ click }) requires an object payload.');
|
|
3331
|
+
}
|
|
3332
|
+
const { selector, ...clickOptions } = payload;
|
|
3333
|
+
value = await this.click(assertNonEmptyString(selector, 'act({ click: { selector } })'), clickOptions);
|
|
3334
|
+
return normalizeActionResult(actionName, value);
|
|
3335
|
+
}
|
|
3336
|
+
case 'type': {
|
|
3337
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
3338
|
+
throwInvalidArgument('hyper-frame act({ type }) requires an object payload.');
|
|
3339
|
+
}
|
|
3340
|
+
const {
|
|
3341
|
+
selector,
|
|
3342
|
+
text,
|
|
3343
|
+
...typeOptions
|
|
3344
|
+
} = payload;
|
|
3345
|
+
if (typeof text !== 'string') {
|
|
3346
|
+
throwInvalidArgument('hyper-frame act({ type }) requires payload.text to be a string.');
|
|
3347
|
+
}
|
|
3348
|
+
value = await this.type(assertNonEmptyString(selector, 'act({ type: { selector } })'), text, typeOptions);
|
|
3349
|
+
return normalizeActionResult(actionName, value);
|
|
3350
|
+
}
|
|
3351
|
+
case 'evaluate':
|
|
3352
|
+
value = await this.evaluate(assertNonEmptyString(payload, 'act({ evaluate })'));
|
|
3353
|
+
return normalizeActionResult(actionName, value);
|
|
3354
|
+
case 'waitForNavigation':
|
|
3355
|
+
value = await this.waitForNavigation((payload && typeof payload === 'object' && !Array.isArray(payload)) ? payload : {});
|
|
3356
|
+
return normalizeActionResult(actionName, value);
|
|
3357
|
+
case 'waitForSelector': {
|
|
3358
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
3359
|
+
throwInvalidArgument('hyper-frame act({ waitForSelector }) requires an object payload.');
|
|
3360
|
+
}
|
|
3361
|
+
const { selector, ...waitOptions } = payload;
|
|
3362
|
+
value = await this.waitForSelector(
|
|
3363
|
+
assertNonEmptyString(selector, 'act({ waitForSelector: { selector } })'),
|
|
3364
|
+
waitOptions,
|
|
3365
|
+
);
|
|
3366
|
+
return normalizeActionResult(actionName, value);
|
|
3367
|
+
}
|
|
3368
|
+
default:
|
|
3369
|
+
throw createBrowserBoxError(`hyper-frame act(action) does not support '${actionName}'.`, {
|
|
3370
|
+
code: ERROR_CODES.UNSUPPORTED,
|
|
3371
|
+
status: 501,
|
|
3372
|
+
action: actionName,
|
|
3373
|
+
});
|
|
3374
|
+
}
|
|
3375
|
+
}
|
|
3376
|
+
|
|
3377
|
+
navigate(url, opts = {}) {
|
|
3378
|
+
return this.page.navigate(url, opts);
|
|
3379
|
+
}
|
|
3380
|
+
|
|
3381
|
+
async capabilities() {
|
|
3382
|
+
return { ...this._capabilityMap };
|
|
3383
|
+
}
|
|
3384
|
+
|
|
3385
|
+
/**
|
|
3386
|
+
* Ensure at least one tab exists, creating one if necessary.
|
|
3387
|
+
* Many operations (navigateTo, goBack, reload, …) silently fail when the
|
|
3388
|
+
* session has zero tabs. Call this before any tab-dependent action.
|
|
3389
|
+
* @param {string} [url] - Optional URL to open if a tab must be created.
|
|
3390
|
+
* @returns {Promise<void>}
|
|
3391
|
+
*/
|
|
3392
|
+
async _ensureTab(url) {
|
|
3393
|
+
try {
|
|
3394
|
+
const tabs = await this.callApi('getTabs');
|
|
3395
|
+
if (Array.isArray(tabs) && tabs.length > 0) return;
|
|
3396
|
+
} catch { /* treat failure as "no tabs" */ }
|
|
3397
|
+
await this.callApi('createTab', url || '');
|
|
3398
|
+
}
|
|
3399
|
+
|
|
3400
|
+
// Canonical BrowserBox API wrappers
|
|
3401
|
+
switchToTab(index) { return this.callApi('switchToTab', index); }
|
|
3402
|
+
switchToTabById(targetId) { return this.callApi('switchToTabById', targetId); }
|
|
3403
|
+
async navigateTo(url, opts = {}) {
|
|
3404
|
+
await this._ensureTab(url);
|
|
3405
|
+
return this.callApi('navigateTo', url, opts);
|
|
3406
|
+
}
|
|
3407
|
+
navigateTab(index, url, opts = {}) { return this.callApi('navigateTab', index, url, opts); }
|
|
3408
|
+
submitOmnibox(query, opts = {}) { return this.callApi('submitOmnibox', query, opts); }
|
|
3409
|
+
createTab(url = '') { return this.callApi('createTab', url); }
|
|
3410
|
+
createTabs(count, opts = {}) { return this.callApi('createTabs', count, opts); }
|
|
3411
|
+
closeTab(index = null) { return this.callApi('closeTab', index); }
|
|
3412
|
+
closeTabById(targetId) { return this.callApi('closeTabById', targetId); }
|
|
3413
|
+
closeAllTabs(opts = {}) { return this.callApi('closeAllTabs', opts); }
|
|
3414
|
+
getTabs() { return this.callApi('getTabs'); }
|
|
3415
|
+
getFavicons() { return this.callApi('getFavicons'); }
|
|
3416
|
+
waitForNonDefaultFavicon(index, opts = {}) { return this.callApi('waitForNonDefaultFavicon', index, opts); }
|
|
3417
|
+
waitForTabCount(expectedCount, opts = {}) { return this.callApi('waitForTabCount', expectedCount, opts); }
|
|
3418
|
+
waitForTabUrl(index, opts = {}) { return this.callApi('waitForTabUrl', index, opts); }
|
|
3419
|
+
getActiveTabIndex() { return this.callApi('getActiveTabIndex'); }
|
|
3420
|
+
getTabCount() { return this.callApi('getTabCount'); }
|
|
3421
|
+
reload() { return this.callApi('reload'); }
|
|
3422
|
+
goBack() { return this.callApi('goBack'); }
|
|
3423
|
+
goForward() { return this.callApi('goForward'); }
|
|
3424
|
+
stop() { return this.callApi('stop'); }
|
|
3425
|
+
getScreenMetrics() { return this.callApi('getScreenMetrics'); }
|
|
3426
|
+
getTransportDiagnostics() { return this.callApi('getTransportDiagnostics'); }
|
|
3427
|
+
frameCapture(enabled = true) { return this.callApi('frameCapture', Boolean(enabled)); }
|
|
3428
|
+
getFrame() { return this.callApi('getFrame'); }
|
|
3429
|
+
cleanSlate(url) { return this.callApi('cleanSlate', url); }
|
|
3430
|
+
async health({ timeoutMs } = {}) {
|
|
3431
|
+
const startedAt = (typeof performance !== 'undefined' && typeof performance.now === 'function')
|
|
3432
|
+
? performance.now()
|
|
3433
|
+
: Date.now();
|
|
3434
|
+
const finalize = (ok, transport, error = null) => ({
|
|
3435
|
+
ok,
|
|
3436
|
+
usable: this._usable,
|
|
3437
|
+
ready: this._isReady,
|
|
3438
|
+
transport,
|
|
3439
|
+
sessionId: this.routingMid || null,
|
|
3440
|
+
timestamp: new Date().toISOString(),
|
|
3441
|
+
latencyMs: Math.max(
|
|
3442
|
+
0,
|
|
3443
|
+
Math.round(((typeof performance !== 'undefined' && typeof performance.now === 'function')
|
|
3444
|
+
? performance.now()
|
|
3445
|
+
: Date.now()) - startedAt),
|
|
3446
|
+
),
|
|
3447
|
+
diagnostics: {
|
|
3448
|
+
reconnecting: !this._isReady && !this._reconnectStopped,
|
|
3449
|
+
lastErrorCode: error?.code || this._lastError?.code,
|
|
3450
|
+
lastErrorMessage: error?.message || this._lastError?.message,
|
|
3451
|
+
},
|
|
3452
|
+
});
|
|
3453
|
+
if (!this.iframe.contentWindow) {
|
|
3454
|
+
this._setUsable(false, 'iframe-not-ready');
|
|
3455
|
+
const error = createBrowserBoxError('hyper-frame health check failed: iframe is not ready.', {
|
|
3456
|
+
code: ERROR_CODES.TRANSPORT,
|
|
3457
|
+
retriable: true,
|
|
3458
|
+
status: 503,
|
|
3459
|
+
});
|
|
3460
|
+
this._rememberError(error);
|
|
3461
|
+
return finalize(false, this._transportMode, error);
|
|
3462
|
+
}
|
|
3463
|
+
const effectiveTimeoutMs = Number.isFinite(timeoutMs)
|
|
3464
|
+
? Math.max(100, Math.round(timeoutMs))
|
|
3465
|
+
: Math.min(this.requestTimeoutMs, 8000);
|
|
3466
|
+
const tryModern = () => this._request(
|
|
3467
|
+
'bbx-api-call',
|
|
3468
|
+
{ method: 'getTabCount', args: [] },
|
|
3469
|
+
{ timeoutMs: effectiveTimeoutMs },
|
|
3470
|
+
);
|
|
3471
|
+
const tryLegacy = () => this._request('getTabCount', {}, { timeoutMs: effectiveTimeoutMs });
|
|
3472
|
+
|
|
3473
|
+
try {
|
|
3474
|
+
const result = await this._withRetry(async () => {
|
|
3475
|
+
if (this._transportMode === 'modern') {
|
|
3476
|
+
await tryModern();
|
|
3477
|
+
return true;
|
|
3478
|
+
}
|
|
3479
|
+
if (this._transportMode === 'legacy') {
|
|
3480
|
+
await tryLegacy();
|
|
3481
|
+
return true;
|
|
3482
|
+
}
|
|
3483
|
+
try {
|
|
3484
|
+
await tryModern();
|
|
3485
|
+
this._transportMode = 'modern';
|
|
3486
|
+
return true;
|
|
3487
|
+
} catch (modernError) {
|
|
3488
|
+
try {
|
|
3489
|
+
await tryLegacy();
|
|
3490
|
+
this._transportMode = 'legacy';
|
|
3491
|
+
return true;
|
|
3492
|
+
} catch (legacyError) {
|
|
3493
|
+
const message = `hyper-frame health check failed after ${effectiveTimeoutMs}ms `
|
|
3494
|
+
+ `(modern error: ${modernError instanceof Error ? modernError.message : String(modernError)}; `
|
|
3495
|
+
+ `legacy error: ${legacyError instanceof Error ? legacyError.message : String(legacyError)})`;
|
|
3496
|
+
throw createBrowserBoxError(message, {
|
|
3497
|
+
code: ERROR_CODES.TRANSPORT,
|
|
3498
|
+
retriable: true,
|
|
3499
|
+
status: 503,
|
|
3500
|
+
cause: legacyError,
|
|
3501
|
+
});
|
|
3502
|
+
}
|
|
3503
|
+
}
|
|
3504
|
+
}, {
|
|
3505
|
+
attempts: 2,
|
|
3506
|
+
baseDelayMs: 250,
|
|
3507
|
+
maxDelayMs: 750,
|
|
3508
|
+
shouldRetry: (error) => this._isRetryableApiError(error),
|
|
3509
|
+
});
|
|
3510
|
+
this._rememberError(null);
|
|
3511
|
+
this._setUsable(true, 'health-ok');
|
|
3512
|
+
return finalize(Boolean(result), this._transportMode);
|
|
3513
|
+
} catch (error) {
|
|
3514
|
+
const normalizedError = this._normalizeRemoteError(error, { method: 'health' });
|
|
3515
|
+
this._rememberError(normalizedError);
|
|
3516
|
+
this._setUsable(false, 'health-failed');
|
|
3517
|
+
return finalize(false, this._transportMode, normalizedError);
|
|
3518
|
+
}
|
|
3519
|
+
}
|
|
3520
|
+
|
|
3521
|
+
// UI visibility controls — update attribute (source of truth) + sync to iframe
|
|
3522
|
+
uiVisible(visible) {
|
|
3523
|
+
if (visible !== undefined) {
|
|
3524
|
+
this.setAttribute('ui-visible', String(Boolean(visible)));
|
|
3525
|
+
}
|
|
3526
|
+
return this.callApi('uiVisible', visible);
|
|
3527
|
+
}
|
|
3528
|
+
allowUserToggleUI(allow) {
|
|
3529
|
+
if (allow !== undefined) {
|
|
3530
|
+
this.setAttribute('allow-user-toggle-ui', String(Boolean(allow)));
|
|
3531
|
+
}
|
|
3532
|
+
return this.callApi('allowUserToggleUI', allow);
|
|
3533
|
+
}
|
|
3534
|
+
getCurrentModal() {
|
|
3535
|
+
return this.callApi('getCurrentModal');
|
|
3536
|
+
}
|
|
3537
|
+
respondToModal(request = {}) {
|
|
3538
|
+
assertPlainObject(request, 'respondToModal(request)');
|
|
3539
|
+
return this.callApi('respondToModal', request);
|
|
3540
|
+
}
|
|
3541
|
+
dismissModal(request = {}) {
|
|
3542
|
+
if (request !== undefined) {
|
|
3543
|
+
assertPlainObject(request, 'dismissModal(request)');
|
|
3544
|
+
}
|
|
3545
|
+
return this.callApi('dismissModal', request || {});
|
|
3546
|
+
}
|
|
3547
|
+
|
|
3548
|
+
// Automation surface
|
|
3549
|
+
waitForSelector(selector, opts = {}) { return this.callApi('waitForSelector', selector, opts); }
|
|
3550
|
+
click(selector, opts = {}) { return this.callApi('click', selector, opts); }
|
|
3551
|
+
type(selector, text, opts = {}) { return this.callApi('type', selector, text, opts); }
|
|
3552
|
+
evaluate(expression, opts = {}) { return this.callApi('evaluate', expression, opts); }
|
|
3553
|
+
waitForNavigation(opts = {}) { return this.callApi('waitForNavigation', opts); }
|
|
3554
|
+
|
|
3555
|
+
refresh() {
|
|
3556
|
+
if (this.iframe.src) {
|
|
3557
|
+
this._isReady = false;
|
|
3558
|
+
this._apiMethods = [];
|
|
3559
|
+
this._transportMode = 'unknown';
|
|
3560
|
+
this._legacyTabsCache = [];
|
|
3561
|
+
this._reconnectStopped = false;
|
|
3562
|
+
this._midSyncAcked = false;
|
|
3563
|
+
this._resetReadyPromise();
|
|
3564
|
+
this._rejectPending(createBrowserBoxError('hyper-frame refreshed.', {
|
|
3565
|
+
code: ERROR_CODES.TRANSPORT,
|
|
3566
|
+
retriable: true,
|
|
3567
|
+
status: 503,
|
|
3568
|
+
}));
|
|
3569
|
+
const currentSrc = this.iframe.src;
|
|
3570
|
+
this._assignIframeSrc(currentSrc, 'refresh');
|
|
3571
|
+
}
|
|
3572
|
+
}
|
|
3573
|
+
|
|
3574
|
+
async disconnect() {
|
|
3575
|
+
this.stopReconnectAttempts('session.disconnect');
|
|
3576
|
+
this._isReady = false;
|
|
3577
|
+
this._apiMethods = [];
|
|
3578
|
+
this._transportMode = 'unknown';
|
|
3579
|
+
this._legacyTabsCache = [];
|
|
3580
|
+
this._resetReadyPromise();
|
|
3581
|
+
if (this.iframe.src) {
|
|
3582
|
+
this.iframe.removeAttribute('src');
|
|
3583
|
+
}
|
|
3584
|
+
this._emitBrowserBoxEvent('disconnected', {
|
|
3585
|
+
reason: 'session.disconnect',
|
|
3586
|
+
});
|
|
3587
|
+
return true;
|
|
3588
|
+
}
|
|
3589
|
+
|
|
3590
|
+
stopReconnectAttempts(reason = 'manual-stop') {
|
|
3591
|
+
this._reconnectStopped = true;
|
|
3592
|
+
this._stopInitPing();
|
|
3593
|
+
this._stopMidSync();
|
|
3594
|
+
this._setUsable(false, reason);
|
|
3595
|
+
this._rejectPending(createBrowserBoxError(`hyper-frame reconnect stopped (${reason}).`, {
|
|
3596
|
+
code: ERROR_CODES.TRANSPORT,
|
|
3597
|
+
retriable: true,
|
|
3598
|
+
status: 503,
|
|
3599
|
+
reason,
|
|
3600
|
+
}));
|
|
3601
|
+
}
|
|
3602
|
+
|
|
3603
|
+
/**
|
|
3604
|
+
* Public API: host window managers call this when the webview's container
|
|
3605
|
+
* becomes visible again (e.g. desktop window restored from minimize).
|
|
3606
|
+
* Bypasses poll-timer latency and forces immediate frame reactivation.
|
|
3607
|
+
*/
|
|
3608
|
+
requestFrameRefresh(reason = 'host-request') {
|
|
3609
|
+
this._lastEffectiveVisibility = false;
|
|
3610
|
+
// Host-driven refreshes (window un-minimize, taskbar restore) must bypass
|
|
3611
|
+
// the visibility-wake cooldown — those are the exact cases where cast
|
|
3612
|
+
// really did stall and a rebind is required.
|
|
3613
|
+
this._lastSuccessfulBootstrapAt = 0;
|
|
3614
|
+
this._scheduleVisibilityWake(reason);
|
|
3615
|
+
}
|
|
3616
|
+
|
|
3617
|
+
/**
|
|
3618
|
+
* Direct "re-click the active tab" — calls switchToTabById without
|
|
3619
|
+
* visibility or dimension checks. Use this from host UI actions
|
|
3620
|
+
* (taskbar restore, window un-minimize) where we KNOW the element is
|
|
3621
|
+
* about to be visible but layout may not have settled yet.
|
|
3622
|
+
* Falls back to the full bootstrap chain if the quick path fails.
|
|
3623
|
+
*/
|
|
3624
|
+
async reactivateActiveTab(reason = 'host-reactivate') {
|
|
3625
|
+
try {
|
|
3626
|
+
const ready = await this._ensureReadyForApi();
|
|
3627
|
+
if (!ready) {
|
|
3628
|
+
this.requestFrameRefresh(reason);
|
|
3629
|
+
return false;
|
|
3630
|
+
}
|
|
3631
|
+
const activeTab = await this._getActiveTabInfo(null).catch(() => null);
|
|
3632
|
+
const tabId = activeTab?.id || activeTab?.targetId || null;
|
|
3633
|
+
if (!tabId) {
|
|
3634
|
+
this.requestFrameRefresh(reason);
|
|
3635
|
+
return false;
|
|
3636
|
+
}
|
|
3637
|
+
if (this._transportMode === 'legacy') {
|
|
3638
|
+
await this._legacyCall('switchToTabById', [tabId]);
|
|
3639
|
+
} else {
|
|
3640
|
+
await this._request('bbx-api-call', {
|
|
3641
|
+
method: 'switchToTabById',
|
|
3642
|
+
args: [tabId],
|
|
3643
|
+
}, {
|
|
3644
|
+
timeoutMs: Math.min(this.requestTimeoutMs, 5000),
|
|
3645
|
+
});
|
|
3646
|
+
}
|
|
3647
|
+
console.info('[hyper-frame] reactivateActiveTab succeeded', { reason, tabId });
|
|
3648
|
+
return true;
|
|
3649
|
+
} catch (error) {
|
|
3650
|
+
console.warn('[hyper-frame] reactivateActiveTab failed, falling back', {
|
|
3651
|
+
reason,
|
|
3652
|
+
error: error instanceof Error ? error.message : String(error),
|
|
3653
|
+
});
|
|
3654
|
+
this.requestFrameRefresh(reason);
|
|
3655
|
+
return false;
|
|
3656
|
+
}
|
|
3657
|
+
}
|
|
3658
|
+
|
|
3659
|
+
updateIframe() {
|
|
3660
|
+
this._refreshRoutingMid();
|
|
3661
|
+
this._updateIframeSrcFromAttribute('updateIframe');
|
|
3662
|
+
this._applyHostDimensions();
|
|
3663
|
+
this._sendUISync('updateIframe');
|
|
3664
|
+
}
|
|
3665
|
+
|
|
3666
|
+
get loginLink() {
|
|
3667
|
+
return this.getAttribute('login-link');
|
|
3668
|
+
}
|
|
3669
|
+
|
|
3670
|
+
set loginLink(value) {
|
|
3671
|
+
if (value) this.setAttribute('login-link', value);
|
|
3672
|
+
else this.removeAttribute('login-link');
|
|
3673
|
+
}
|
|
3674
|
+
|
|
3675
|
+
get routingMid() {
|
|
3676
|
+
return this._routingMid || '';
|
|
3677
|
+
}
|
|
3678
|
+
|
|
3679
|
+
get width() {
|
|
3680
|
+
return this.getAttribute('width');
|
|
3681
|
+
}
|
|
3682
|
+
|
|
3683
|
+
set width(value) {
|
|
3684
|
+
if (value) this.setAttribute('width', value);
|
|
3685
|
+
else this.removeAttribute('width');
|
|
3686
|
+
}
|
|
3687
|
+
|
|
3688
|
+
get height() {
|
|
3689
|
+
return this.getAttribute('height');
|
|
3690
|
+
}
|
|
3691
|
+
|
|
3692
|
+
set height(value) {
|
|
3693
|
+
if (value) this.setAttribute('height', value);
|
|
3694
|
+
else this.removeAttribute('height');
|
|
3695
|
+
}
|
|
3696
|
+
|
|
3697
|
+
get embedderOrigin() {
|
|
3698
|
+
return this.getAttribute('embedder-origin')
|
|
3699
|
+
|| this.getAttribute('parent-origin')
|
|
3700
|
+
|| '*';
|
|
3701
|
+
}
|
|
3702
|
+
|
|
3703
|
+
set embedderOrigin(value) {
|
|
3704
|
+
if (value) this.setAttribute('embedder-origin', value);
|
|
3705
|
+
else this.removeAttribute('embedder-origin');
|
|
3706
|
+
}
|
|
3707
|
+
|
|
3708
|
+
/** @deprecated Use embedderOrigin instead. */
|
|
3709
|
+
get parentOrigin() {
|
|
3710
|
+
return this.embedderOrigin;
|
|
3711
|
+
}
|
|
3712
|
+
|
|
3713
|
+
/** @deprecated Use embedderOrigin instead. */
|
|
3714
|
+
set parentOrigin(value) {
|
|
3715
|
+
this.embedderOrigin = value;
|
|
3716
|
+
}
|
|
3717
|
+
|
|
3718
|
+
get requestTimeoutMs() {
|
|
3719
|
+
const raw = this.getAttribute('request-timeout-ms');
|
|
3720
|
+
const parsed = Number.parseInt(raw || '30000', 10);
|
|
3721
|
+
if (!Number.isFinite(parsed) || parsed < 100) {
|
|
3722
|
+
return 30000;
|
|
3723
|
+
}
|
|
3724
|
+
return parsed;
|
|
3725
|
+
}
|
|
3726
|
+
|
|
3727
|
+
set requestTimeoutMs(value) {
|
|
3728
|
+
if (value === null || value === undefined) {
|
|
3729
|
+
this.removeAttribute('request-timeout-ms');
|
|
3730
|
+
return;
|
|
3731
|
+
}
|
|
3732
|
+
this.setAttribute('request-timeout-ms', String(value));
|
|
3733
|
+
}
|
|
3734
|
+
|
|
3735
|
+
/**
|
|
3736
|
+
* Legacy transport dispatch. Each handler is a small function in a lookup
|
|
3737
|
+
* table — avoids the 180-line if/else chain (Architecture §6, §3).
|
|
3738
|
+
* @param {string} method
|
|
3739
|
+
* @param {Array} args
|
|
3740
|
+
* @param {Error|null} originalError
|
|
3741
|
+
* @returns {Promise<*>}
|
|
3742
|
+
*/
|
|
3743
|
+
async _legacyCall(method, args = [], originalError = null) {
|
|
3744
|
+
const handler = this._legacyHandlers[method];
|
|
3745
|
+
if (!handler) {
|
|
3746
|
+
const detail = originalError?.message ? ` (${originalError.message})` : '';
|
|
3747
|
+
throw createBrowserBoxError(`No legacy fallback for API method '${method}'${detail}`, {
|
|
3748
|
+
code: ERROR_CODES.UNSUPPORTED,
|
|
3749
|
+
status: 501,
|
|
3750
|
+
method,
|
|
3751
|
+
...(originalError ? { cause: originalError } : {}),
|
|
3752
|
+
});
|
|
3753
|
+
}
|
|
3754
|
+
return handler.call(this, args, originalError);
|
|
3755
|
+
}
|
|
3756
|
+
|
|
3757
|
+
get _legacyHandlers() {
|
|
3758
|
+
if (this.__legacyHandlers) return this.__legacyHandlers;
|
|
3759
|
+
const self = this;
|
|
3760
|
+
|
|
3761
|
+
const fail = (message, originalError = null) => {
|
|
3762
|
+
const detail = originalError?.message ? ` (${originalError.message})` : '';
|
|
3763
|
+
throw self._normalizeRemoteError(
|
|
3764
|
+
createBrowserBoxError(`${message}${detail}`, {
|
|
3765
|
+
code: ERROR_CODES.INTERNAL,
|
|
3766
|
+
status: 500,
|
|
3767
|
+
...(originalError ? { cause: originalError } : {}),
|
|
3768
|
+
}),
|
|
3769
|
+
);
|
|
3770
|
+
};
|
|
3771
|
+
|
|
3772
|
+
const resolveTabId = async (indexArg = null) => {
|
|
3773
|
+
if (typeof indexArg === 'string' && indexArg.trim().length > 0) return indexArg.trim();
|
|
3774
|
+
const tabs = await self._legacyHandlers.getTabs.call(self, []);
|
|
3775
|
+
if (Array.isArray(tabs) && tabs.length > 0) {
|
|
3776
|
+
const requested = Number.isInteger(indexArg) ? indexArg : 0;
|
|
3777
|
+
const normalized = requested < 0 ? tabs.length + requested : requested;
|
|
3778
|
+
const safeIndex = Math.max(0, Math.min(tabs.length - 1, normalized));
|
|
3779
|
+
return tabs[safeIndex]?.id || tabs[safeIndex]?.targetId || null;
|
|
3780
|
+
}
|
|
3781
|
+
const activeTab = await self._request('getActiveTab', {}).catch(() => null);
|
|
3782
|
+
return activeTab?.id || activeTab?.targetId || null;
|
|
3783
|
+
};
|
|
3784
|
+
|
|
3785
|
+
this.__legacyHandlers = {
|
|
3786
|
+
async getTabs() {
|
|
3787
|
+
let tabs;
|
|
3788
|
+
try {
|
|
3789
|
+
tabs = await self._request('getTabs', {});
|
|
3790
|
+
} catch {
|
|
3791
|
+
tabs = self._legacyTabsCache.slice();
|
|
3792
|
+
}
|
|
3793
|
+
if (!Array.isArray(tabs)) return self._legacyTabsCache.slice();
|
|
3794
|
+
const normalizedTabs = tabs.map((tab, index) => ({ index, ...tab }));
|
|
3795
|
+
self._legacyTabsCache = normalizedTabs.slice();
|
|
3796
|
+
return normalizedTabs;
|
|
3797
|
+
},
|
|
3798
|
+
|
|
3799
|
+
async getActiveTabIndex() {
|
|
3800
|
+
const [tabs, activeTab] = await Promise.all([
|
|
3801
|
+
self._legacyHandlers.getTabs.call(self, []),
|
|
3802
|
+
self._request('getActiveTab', {}).catch(() => null),
|
|
3803
|
+
]);
|
|
3804
|
+
if (!activeTab || !Array.isArray(tabs)) return -1;
|
|
3805
|
+
const activeId = activeTab.id || activeTab.targetId || null;
|
|
3806
|
+
return tabs.findIndex((tab) => (tab.id || tab.targetId) === activeId);
|
|
3807
|
+
},
|
|
3808
|
+
|
|
3809
|
+
async getTabCount() {
|
|
3810
|
+
const tabs = await self._legacyHandlers.getTabs.call(self, []);
|
|
3811
|
+
return Array.isArray(tabs) ? tabs.length : 0;
|
|
3812
|
+
},
|
|
3813
|
+
|
|
3814
|
+
async createTab(args) {
|
|
3815
|
+
const url = typeof args[0] === 'string' ? args[0] : '';
|
|
3816
|
+
self._postRaw({ type: 'createTab', data: { url } });
|
|
3817
|
+
return true;
|
|
3818
|
+
},
|
|
3819
|
+
|
|
3820
|
+
async createTabs(args) {
|
|
3821
|
+
const count = Number.isInteger(args[0]) && args[0] > 0 ? args[0] : 0;
|
|
3822
|
+
const opts = args[1] || {};
|
|
3823
|
+
const url = typeof opts.url === 'string' ? opts.url : '';
|
|
3824
|
+
for (let i = 0; i < count; i += 1) {
|
|
3825
|
+
self._postRaw({ type: 'createTab', data: { url } });
|
|
3826
|
+
}
|
|
3827
|
+
return true;
|
|
3828
|
+
},
|
|
3829
|
+
|
|
3830
|
+
async closeTab(args, originalError) {
|
|
3831
|
+
const tabId = await resolveTabId(args[0]);
|
|
3832
|
+
if (!tabId) fail('Legacy closeTab failed: no target tab', originalError);
|
|
3833
|
+
self._postRaw({ type: 'closeTab', tabId, data: {} });
|
|
3834
|
+
return true;
|
|
3835
|
+
},
|
|
3836
|
+
|
|
3837
|
+
async closeTabById(args, originalError) {
|
|
3838
|
+
const tabId = typeof args[0] === 'string' && args[0].trim().length > 0 ? args[0].trim() : null;
|
|
3839
|
+
if (!tabId) fail('Legacy closeTabById requires a non-empty targetId string', originalError);
|
|
3840
|
+
self._postRaw({ type: 'closeTab', tabId, data: {} });
|
|
3841
|
+
return true;
|
|
3842
|
+
},
|
|
3843
|
+
|
|
3844
|
+
async closeAllTabs(args) {
|
|
3845
|
+
const opts = args[0] || {};
|
|
3846
|
+
const keep = Number.isInteger(opts.keep) ? Math.max(0, opts.keep) : 0;
|
|
3847
|
+
const tabs = await self._legacyHandlers.getTabs.call(self, []);
|
|
3848
|
+
if (!Array.isArray(tabs) || tabs.length <= keep) return tabs?.length || 0;
|
|
3849
|
+
for (let i = tabs.length - 1; i >= keep; i -= 1) {
|
|
3850
|
+
const tabId = tabs[i]?.id || tabs[i]?.targetId;
|
|
3851
|
+
if (!tabId) continue;
|
|
3852
|
+
self._postRaw({ type: 'closeTab', tabId, data: {} });
|
|
3853
|
+
}
|
|
3854
|
+
return Math.max(keep, 0);
|
|
3855
|
+
},
|
|
3856
|
+
|
|
3857
|
+
async switchToTab(args, originalError) {
|
|
3858
|
+
const tabId = await resolveTabId(args[0]);
|
|
3859
|
+
if (!tabId) fail('Legacy switchToTab failed: no target tab', originalError);
|
|
3860
|
+
self._postRaw({ type: 'setActiveTab', tabId, data: {} });
|
|
3861
|
+
return true;
|
|
3862
|
+
},
|
|
3863
|
+
|
|
3864
|
+
async switchToTabById(args, originalError) {
|
|
3865
|
+
const tabId = typeof args[0] === 'string' && args[0].trim().length > 0 ? args[0].trim() : null;
|
|
3866
|
+
if (!tabId) fail('Legacy switchToTabById requires a non-empty targetId string', originalError);
|
|
3867
|
+
self._postRaw({ type: 'setActiveTab', tabId, data: {} });
|
|
3868
|
+
return true;
|
|
3869
|
+
},
|
|
3870
|
+
|
|
3871
|
+
async navigateTo(args, originalError) {
|
|
3872
|
+
const url = typeof args[0] === 'string' ? args[0] : '';
|
|
3873
|
+
const tabId = await resolveTabId(null);
|
|
3874
|
+
if (!tabId) fail('Legacy navigateTo failed: no active tab', originalError);
|
|
3875
|
+
self._postRaw({ type: 'loadURL', tabId, data: { url } });
|
|
3876
|
+
return true;
|
|
3877
|
+
},
|
|
3878
|
+
|
|
3879
|
+
async navigateTab(args, originalError) {
|
|
3880
|
+
const tabId = await resolveTabId(args[0]);
|
|
3881
|
+
const url = typeof args[1] === 'string' ? args[1] : '';
|
|
3882
|
+
if (!tabId) fail('Legacy navigateTab failed: no target tab', originalError);
|
|
3883
|
+
self._postRaw({ type: 'setActiveTab', tabId, data: {} });
|
|
3884
|
+
self._postRaw({ type: 'loadURL', tabId, data: { url } });
|
|
3885
|
+
return true;
|
|
3886
|
+
},
|
|
3887
|
+
|
|
3888
|
+
async submitOmnibox(args, originalError) {
|
|
3889
|
+
const query = typeof args[0] === 'string' ? args[0] : '';
|
|
3890
|
+
return self._legacyHandlers.navigateTo.call(self, [query], originalError);
|
|
3891
|
+
},
|
|
3892
|
+
|
|
3893
|
+
async reload(args, originalError) {
|
|
3894
|
+
const tabId = await resolveTabId(null);
|
|
3895
|
+
if (!tabId) fail('Legacy reload failed: no active tab', originalError);
|
|
3896
|
+
self._postRaw({ type: 'reload', tabId, data: {} });
|
|
3897
|
+
return true;
|
|
3898
|
+
},
|
|
3899
|
+
|
|
3900
|
+
async goBack(args, originalError) {
|
|
3901
|
+
const tabId = await resolveTabId(null);
|
|
3902
|
+
if (!tabId) fail('Legacy goBack failed: no active tab', originalError);
|
|
3903
|
+
self._postRaw({ type: 'goBack', tabId, data: {} });
|
|
3904
|
+
return true;
|
|
3905
|
+
},
|
|
3906
|
+
|
|
3907
|
+
async goForward(args, originalError) {
|
|
3908
|
+
const tabId = await resolveTabId(null);
|
|
3909
|
+
if (!tabId) fail('Legacy goForward failed: no active tab', originalError);
|
|
3910
|
+
self._postRaw({ type: 'goForward', tabId, data: {} });
|
|
3911
|
+
return true;
|
|
3912
|
+
},
|
|
3913
|
+
|
|
3914
|
+
async stop(args, originalError) {
|
|
3915
|
+
const tabId = await resolveTabId(null);
|
|
3916
|
+
if (!tabId) fail('Legacy stop failed: no active tab', originalError);
|
|
3917
|
+
self._postRaw({ type: 'stop', tabId, data: {} });
|
|
3918
|
+
return true;
|
|
3919
|
+
},
|
|
3920
|
+
|
|
3921
|
+
async evaluate(args, originalError) {
|
|
3922
|
+
const expression = typeof args[0] === 'string' ? args[0] : '';
|
|
3923
|
+
const tabId = await resolveTabId(null);
|
|
3924
|
+
if (!tabId) fail('Legacy evaluate failed: no active tab', originalError);
|
|
3925
|
+
if (expression.includes('history.back')) {
|
|
3926
|
+
self._postRaw({ type: 'goBack', tabId, data: {} });
|
|
3927
|
+
return true;
|
|
3928
|
+
}
|
|
3929
|
+
if (expression.includes('history.forward')) {
|
|
3930
|
+
self._postRaw({ type: 'goForward', tabId, data: {} });
|
|
3931
|
+
return true;
|
|
3932
|
+
}
|
|
3933
|
+
if (expression.includes('window.stop')) {
|
|
3934
|
+
self._postRaw({ type: 'stop', tabId, data: {} });
|
|
3935
|
+
return true;
|
|
3936
|
+
}
|
|
3937
|
+
fail('Legacy evaluate only supports history.back, history.forward, and window.stop', originalError);
|
|
3938
|
+
},
|
|
3939
|
+
|
|
3940
|
+
async waitForTabCount(args, originalError) {
|
|
3941
|
+
const expectedCount = Number.isInteger(args[0]) ? args[0] : 0;
|
|
3942
|
+
const opts = args[1] || {};
|
|
3943
|
+
const timeoutMs = Number.isFinite(opts.timeoutMs) ? opts.timeoutMs : self.requestTimeoutMs;
|
|
3944
|
+
const pollMs = Number.isFinite(opts.pollMs) ? Math.max(50, opts.pollMs) : 150;
|
|
3945
|
+
const deadline = Date.now() + timeoutMs;
|
|
3946
|
+
while (Date.now() < deadline) {
|
|
3947
|
+
const tabs = await self._legacyHandlers.getTabs.call(self, []);
|
|
3948
|
+
if (tabs.length === expectedCount) return tabs.length;
|
|
3949
|
+
await new Promise((resolve) => setTimeout(resolve, pollMs));
|
|
3950
|
+
}
|
|
3951
|
+
fail(`Legacy waitForTabCount timed out waiting for ${expectedCount}`, originalError);
|
|
3952
|
+
},
|
|
3953
|
+
|
|
3954
|
+
async waitForTabUrl(args, originalError) {
|
|
3955
|
+
const tabIndex = Number.isInteger(args[0]) ? args[0] : 0;
|
|
3956
|
+
const opts = args[1] || {};
|
|
3957
|
+
const timeoutMs = Number.isFinite(opts.timeoutMs) ? opts.timeoutMs : self.requestTimeoutMs;
|
|
3958
|
+
const pollMs = Number.isFinite(opts.pollMs) ? Math.max(50, opts.pollMs) : 150;
|
|
3959
|
+
const expectIncludes = typeof opts.expectIncludes === 'string' ? opts.expectIncludes : '';
|
|
3960
|
+
const allowBlank = Boolean(opts.allowBlank);
|
|
3961
|
+
const deadline = Date.now() + timeoutMs;
|
|
3962
|
+
while (Date.now() < deadline) {
|
|
3963
|
+
const tabs = await self._legacyHandlers.getTabs.call(self, []);
|
|
3964
|
+
if (Array.isArray(tabs) && tabs.length > 0) {
|
|
3965
|
+
const safeIndex = Math.max(0, Math.min(tabs.length - 1, tabIndex));
|
|
3966
|
+
const url = tabs[safeIndex]?.url || '';
|
|
3967
|
+
if (allowBlank || url) {
|
|
3968
|
+
if (!expectIncludes || url.includes(expectIncludes)) {
|
|
3969
|
+
return { index: safeIndex, id: tabs[safeIndex]?.id || tabs[safeIndex]?.targetId, url };
|
|
3970
|
+
}
|
|
3971
|
+
}
|
|
3972
|
+
}
|
|
3973
|
+
await new Promise((resolve) => setTimeout(resolve, pollMs));
|
|
3974
|
+
}
|
|
3975
|
+
fail(`Legacy waitForTabUrl timed out for tab ${tabIndex}`, originalError);
|
|
3976
|
+
},
|
|
3977
|
+
};
|
|
3978
|
+
|
|
3979
|
+
return this.__legacyHandlers;
|
|
3980
|
+
}
|
|
3981
|
+
|
|
3982
|
+
}
|
|
3983
|
+
|
|
3984
|
+
if (!customElements.get('hyper-frame')) {
|
|
3985
|
+
customElements.define('hyper-frame', HyperFrame);
|
|
3986
|
+
}
|