@open-jsbridge/web 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,466 @@
1
+ import { decodeEnvelope, encodeEnvelope, ErrorCode, } from '../../protocol/src/index.js';
2
+ import { BridgeError } from './errors.js';
3
+ import { EventSubscriptions, hasSessionEvent } from './events.js';
4
+ import { isObject, readSession } from './session.js';
5
+ import { findBrowserAdapter } from './transport.js';
6
+ export { BridgeError, ErrorCode };
7
+ const versionSuffix = /@([1-9][0-9]*)$/;
8
+ const timerLimit = 2147483647;
9
+ let bridgeCount = 0;
10
+ function exceedsMessageLimit(raw, maxMessageBytes) {
11
+ return raw.length > maxMessageBytes || new TextEncoder().encode(raw).byteLength > maxMessageBytes;
12
+ }
13
+ function atDeadline(deadline, expire) {
14
+ const check = () => {
15
+ const remaining = Math.ceil(deadline - performance.now());
16
+ if (remaining <= 0)
17
+ expire();
18
+ else
19
+ timer = setTimeout(check, Math.min(remaining, timerLimit));
20
+ };
21
+ let timer = setTimeout(check, Math.max(0, Math.min(Math.ceil(deadline - performance.now()), timerLimit)));
22
+ return () => clearTimeout(timer);
23
+ }
24
+ class WebBridge {
25
+ constructor(options, handshakeTimeout, queueLimit) {
26
+ this.options = options;
27
+ this.handshakeTimeout = handshakeTimeout;
28
+ this.queueLimit = queueLimit;
29
+ this.currentState = 'idle';
30
+ this.lifecycleBound = false;
31
+ this.suspended = false;
32
+ this.pending = new Map();
33
+ this.cancelReceipts = new Set();
34
+ this.draining = false;
35
+ this.events = new EventSubscriptions((method, params, control) => this.request(method, params, {}, control), () => this.connectForEvents());
36
+ this.idPrefix = `w-${++bridgeCount}-${Math.random().toString(36).slice(2, 8)}`;
37
+ this.nextId = 0;
38
+ }
39
+ get state() { return this.currentState; }
40
+ get host() { return this.session?.host; }
41
+ ready() {
42
+ if (this.suspended)
43
+ return Promise.reject(new BridgeError(ErrorCode.Unavailable, 'Bridge unavailable'));
44
+ if (!this.connection) {
45
+ this.bindBrowserLifecycle();
46
+ const lifetime = new AbortController();
47
+ this.lifetime = lifetime;
48
+ this.connection = this.connect(lifetime.signal);
49
+ }
50
+ return this.connection;
51
+ }
52
+ has(method, version) {
53
+ if (typeof method !== 'string')
54
+ return false;
55
+ const base = method.replace(versionSuffix, '');
56
+ const advertised = this.session?.methods.get(base);
57
+ const suffix = versionSuffix.exec(method);
58
+ if (!advertised || (suffix && version !== undefined && Number(suffix[1]) !== version))
59
+ return false;
60
+ const requested = version ?? (suffix ? Number(suffix[1]) : undefined);
61
+ return requested === undefined || advertised.has(requested);
62
+ }
63
+ hasEvent(name) { return hasSessionEvent(this.session, name); }
64
+ on(name, listener) {
65
+ return this.events.on(name, listener);
66
+ }
67
+ off(name, listener) { this.events.off(name, listener); }
68
+ call(method, params, options = {}) {
69
+ return this.request(method, params, options);
70
+ }
71
+ request(method, params, options, control) {
72
+ const { signal, traceId, version } = options;
73
+ if (typeof method !== 'string') {
74
+ return Promise.reject(new BridgeError(ErrorCode.InvalidParams, 'Expected a string method', { traceId }));
75
+ }
76
+ const context = { method, traceId };
77
+ if (signal?.aborted)
78
+ return Promise.reject(new BridgeError(ErrorCode.Cancelled, 'Call cancelled', context));
79
+ if (this.state === 'unavailable') {
80
+ return Promise.reject(new BridgeError(ErrorCode.Unavailable, 'Bridge unavailable', context));
81
+ }
82
+ if (params !== undefined && !isObject(params)) {
83
+ return Promise.reject(new BridgeError(ErrorCode.InvalidParams, 'Expected object params', context));
84
+ }
85
+ const suffix = versionSuffix.exec(method);
86
+ if (version !== undefined && (!Number.isSafeInteger(version) || version < 1 ||
87
+ (suffix && Number(suffix[1]) !== version))) {
88
+ return Promise.reject(new BridgeError(ErrorCode.InvalidParams, 'Invalid method version', context));
89
+ }
90
+ const timeout = options.timeout ?? this.session?.defaultTimeout ?? 15000;
91
+ if (!Number.isSafeInteger(timeout) || timeout <= 0) {
92
+ return Promise.reject(new BridgeError(ErrorCode.InvalidParams, 'Expected a positive timeout', context));
93
+ }
94
+ const wireMethod = version === undefined || suffix ? method : `${method}@${version}`;
95
+ const eventControl = control !== undefined;
96
+ const waitForSlot = control?.waitForSlot === true;
97
+ const session = this.session;
98
+ if (session) {
99
+ const error = this.unsupportedMethod(wireMethod, eventControl, traceId);
100
+ if (error)
101
+ return Promise.reject(error);
102
+ }
103
+ // Event maintenance must eventually run even when the waiting queue is full.
104
+ const capacity = (session?.maxInflight ?? 0) - this.cancelReceipts.size;
105
+ if (!waitForSlot && this.pending.size - capacity >= this.queueLimit) {
106
+ return Promise.reject(new BridgeError(ErrorCode.NotReady, 'Pending call queue is full', context));
107
+ }
108
+ const id = this.createId();
109
+ const request = {
110
+ jsonrpc: '2.0', id, method: wireMethod, ...(params === undefined ? {} : { params }),
111
+ };
112
+ const deadline = waitForSlot ? undefined : performance.now() + timeout;
113
+ return new Promise((resolve, reject) => {
114
+ const pending = {
115
+ request, traceId, deadline, eventControl, onDispatch: control?.onDispatch, reject,
116
+ resolve: (value) => {
117
+ control?.onReply(value);
118
+ resolve(value);
119
+ },
120
+ };
121
+ this.pending.set(id, pending);
122
+ if (deadline !== undefined)
123
+ this.startTimeout(pending, deadline);
124
+ if (signal) {
125
+ const abort = () => this.fail(id, ErrorCode.Cancelled, 'Call cancelled', true);
126
+ signal.addEventListener('abort', abort, { once: true });
127
+ pending.stopListening = () => signal.removeEventListener('abort', abort);
128
+ }
129
+ if (this.session)
130
+ this.drain();
131
+ else
132
+ void this.ready().catch(() => { });
133
+ });
134
+ }
135
+ connectForEvents() {
136
+ if (this.suspended)
137
+ return;
138
+ if (this.state === 'unavailable') {
139
+ this.events.rejectWaiting(new BridgeError(ErrorCode.Unavailable, 'Bridge unavailable'));
140
+ }
141
+ else
142
+ void this.ready().catch(() => { });
143
+ }
144
+ createId() { return `${this.idPrefix}-${++this.nextId}`; }
145
+ bindBrowserLifecycle() {
146
+ if (this.lifecycleBound || typeof window === 'undefined')
147
+ return;
148
+ this.lifecycleBound = true;
149
+ window.addEventListener('pagehide', () => this.invalidate());
150
+ window.addEventListener('pageshow', (event) => {
151
+ if (!event.persisted)
152
+ return;
153
+ this.invalidate();
154
+ this.suspended = false;
155
+ void this.ready().catch(() => { });
156
+ });
157
+ }
158
+ invalidate() {
159
+ this.suspended = true;
160
+ this.currentState = 'unavailable';
161
+ this.session = undefined;
162
+ this.connection = undefined;
163
+ this.events.reset();
164
+ this.lifetime?.abort();
165
+ this.lifetime = undefined;
166
+ const hello = this.hello;
167
+ this.hello = undefined;
168
+ hello?.reject(new BridgeError(ErrorCode.Cancelled, 'Handshake cancelled'));
169
+ for (const id of this.pending.keys())
170
+ this.fail(id, ErrorCode.Cancelled, 'Page hidden');
171
+ this.detach();
172
+ }
173
+ detach() {
174
+ for (const release of this.cancelReceipts)
175
+ release();
176
+ const unlisten = this.unlisten;
177
+ this.unlisten = undefined;
178
+ this.adapter = undefined;
179
+ try {
180
+ unlisten?.();
181
+ }
182
+ catch { /* Pending calls have already been retired. */ }
183
+ }
184
+ async connect(signal) {
185
+ this.currentState = 'connecting';
186
+ const requireActive = () => {
187
+ if (signal.aborted)
188
+ throw new BridgeError(ErrorCode.Cancelled, 'Handshake cancelled');
189
+ };
190
+ try {
191
+ const adapter = await (this.options.adapter ?? findBrowserAdapter(this.handshakeTimeout, signal));
192
+ requireActive();
193
+ if (!adapter || adapter.detect?.() === false)
194
+ throw new BridgeError(ErrorCode.Unavailable, 'No transport');
195
+ if (adapter.protocols && !adapter.protocols.includes(1)) {
196
+ throw new BridgeError(ErrorCode.UnsupportedProtocol, 'Unsupported protocol', {
197
+ data: { supported: [...adapter.protocols] },
198
+ });
199
+ }
200
+ const unlisten = adapter.listen((raw) => {
201
+ if (!signal.aborted)
202
+ this.receive(raw);
203
+ });
204
+ if (signal.aborted)
205
+ unlisten();
206
+ requireActive();
207
+ this.adapter = adapter;
208
+ this.unlisten = unlisten;
209
+ const session = await this.handshake();
210
+ requireActive();
211
+ this.session = session;
212
+ this.currentState = 'ready';
213
+ for (const call of this.pending.values()) {
214
+ const { request: { id, method }, deadline, eventControl, traceId } = call;
215
+ const error = deadline !== undefined && performance.now() >= deadline
216
+ ? new BridgeError(ErrorCode.Timeout, 'Call timed out', { method, traceId })
217
+ : this.unsupportedMethod(method, eventControl, traceId);
218
+ if (error)
219
+ this.take(id)?.reject(error);
220
+ }
221
+ this.drain();
222
+ requireActive();
223
+ this.events.start(session);
224
+ requireActive();
225
+ return session.host;
226
+ }
227
+ catch (error) {
228
+ if (signal.aborted)
229
+ throw new BridgeError(ErrorCode.Cancelled, 'Handshake cancelled');
230
+ this.currentState = 'unavailable';
231
+ this.session = undefined;
232
+ for (const id of this.pending.keys())
233
+ this.fail(id, ErrorCode.Unavailable, 'Bridge unavailable');
234
+ this.detach();
235
+ const failure = error instanceof BridgeError ? error : new BridgeError(ErrorCode.Unavailable, 'Transport unavailable');
236
+ this.events.rejectWaiting(failure);
237
+ throw failure;
238
+ }
239
+ }
240
+ async handshake() {
241
+ const id = this.createId();
242
+ const deadline = performance.now() + this.handshakeTimeout;
243
+ const request = encodeEnvelope({
244
+ jsb: '1.0',
245
+ rpc: { jsonrpc: '2.0', id, method: 'bridge.hello', params: {
246
+ protocols: [1], sdk: { name: 'open-jsbridge', version: '0.1.0' }, wants: ['cancel', 'events'],
247
+ } },
248
+ });
249
+ const stopTimer = atDeadline(deadline, () => {
250
+ if (this.hello?.id === id)
251
+ this.hello.reject(new BridgeError(ErrorCode.Unavailable, 'Handshake timed out'));
252
+ });
253
+ try {
254
+ return await new Promise((resolve, reject) => {
255
+ this.hello = { id, deadline, resolve, reject };
256
+ this.post(request, id, () => reject(new BridgeError(ErrorCode.Unavailable, 'Handshake failed to send')));
257
+ });
258
+ }
259
+ finally {
260
+ if (this.hello?.id === id)
261
+ this.hello = undefined;
262
+ stopTimer();
263
+ }
264
+ }
265
+ drain() {
266
+ const session = this.session;
267
+ if (!session || this.draining || session.inflight >= session.maxInflight)
268
+ return;
269
+ // Adapters can synchronously deliver a response while send() is on the stack.
270
+ this.draining = true;
271
+ try {
272
+ for (const call of this.pending.values()) {
273
+ if (this.session !== session || session.inflight >= session.maxInflight)
274
+ break;
275
+ if (!call.session)
276
+ this.dispatch(call, session);
277
+ }
278
+ }
279
+ finally {
280
+ this.draining = false;
281
+ }
282
+ }
283
+ unsupportedMethod(method, eventControl, traceId) {
284
+ if (eventControl && (method === 'bridge.subscribe' || method === 'bridge.unsubscribe'))
285
+ return;
286
+ if (this.has(method))
287
+ return;
288
+ const reason = this.has(method.replace(versionSuffix, '')) ? 'version_unsupported' : 'method_not_found';
289
+ return new BridgeError(ErrorCode.MethodNotFound, 'Method not available', { method, traceId, data: { reason } });
290
+ }
291
+ dispatch(pending, session) {
292
+ const { request, traceId } = pending;
293
+ const now = performance.now();
294
+ const deadline = pending.deadline ?? now + session.defaultTimeout;
295
+ const timeout = Math.ceil(deadline - now);
296
+ if (timeout <= 0)
297
+ return this.fail(request.id, ErrorCode.Timeout, 'Call timed out');
298
+ let raw;
299
+ try {
300
+ raw = encodeEnvelope({
301
+ jsb: '1.0', rpc: request,
302
+ meta: { sid: session.sid, ts: Date.now(), timeout, ...(traceId === undefined ? {} : { traceId }) },
303
+ });
304
+ }
305
+ catch {
306
+ this.fail(request.id, ErrorCode.InvalidParams, 'Call could not be encoded');
307
+ return;
308
+ }
309
+ if (!this.pending.has(request.id))
310
+ return;
311
+ if (exceedsMessageLimit(raw, session.maxMessageBytes)) {
312
+ this.fail(request.id, ErrorCode.PayloadTooLarge, 'Call exceeds the negotiated byte limit');
313
+ return;
314
+ }
315
+ if (performance.now() >= deadline) {
316
+ this.fail(request.id, ErrorCode.Timeout, 'Call timed out');
317
+ return;
318
+ }
319
+ if (pending.deadline === undefined)
320
+ this.startTimeout(pending, deadline);
321
+ pending.session = session;
322
+ session.inflight++;
323
+ pending.onDispatch?.();
324
+ this.post(raw, request.id, () => this.fail(request.id, ErrorCode.Unavailable, 'Call failed to send'));
325
+ }
326
+ startTimeout(pending, deadline) {
327
+ pending.deadline = deadline;
328
+ pending.stopTimer = atDeadline(deadline, () => this.fail(pending.request.id, ErrorCode.Timeout, 'Call timed out', true));
329
+ }
330
+ post(raw, id, onFailure = () => { }) {
331
+ const signal = this.lifetime?.signal;
332
+ try {
333
+ const response = this.adapter?.send(raw);
334
+ if (response)
335
+ void response.then((reply) => {
336
+ if (!signal?.aborted && reply !== null && id !== undefined)
337
+ this.receive(reply, id);
338
+ }, onFailure);
339
+ return response;
340
+ }
341
+ catch {
342
+ onFailure();
343
+ }
344
+ }
345
+ postCancel(id, session) {
346
+ const raw = encodeEnvelope({
347
+ jsb: '1.0', meta: { sid: session.sid },
348
+ rpc: { jsonrpc: '2.0', method: 'bridge.cancel', params: { requestId: id } },
349
+ });
350
+ let stopTimer;
351
+ const release = () => {
352
+ if (!this.cancelReceipts.delete(release))
353
+ return;
354
+ stopTimer?.();
355
+ session.inflight--;
356
+ this.drain();
357
+ };
358
+ // Hold the slot while a WithReply transport has a cancel receipt outstanding.
359
+ const deadline = performance.now() + session.defaultTimeout;
360
+ this.cancelReceipts.add(release);
361
+ session.inflight++;
362
+ const receipt = this.post(raw);
363
+ if (!receipt) {
364
+ release();
365
+ return;
366
+ }
367
+ if (this.cancelReceipts.has(release))
368
+ stopTimer = atDeadline(deadline, release);
369
+ void receipt.then(release, release);
370
+ }
371
+ receive(raw, replyId) {
372
+ const activeSession = this.session;
373
+ if (typeof raw !== 'string' || (activeSession && exceedsMessageLimit(raw, activeSession.maxMessageBytes)))
374
+ return;
375
+ let envelope;
376
+ try {
377
+ envelope = decodeEnvelope(raw);
378
+ }
379
+ catch {
380
+ return;
381
+ }
382
+ const { rpc, meta } = envelope;
383
+ if ('method' in rpc) {
384
+ if (replyId === undefined && rpc.method === 'bridge.event' && !('id' in rpc) &&
385
+ activeSession && activeSession.sid === meta?.sid)
386
+ this.events.deliver(rpc.params);
387
+ return;
388
+ }
389
+ if (typeof rpc.id !== 'string' || (replyId !== undefined && replyId !== rpc.id))
390
+ return;
391
+ const attempt = this.hello;
392
+ if (attempt?.id === rpc.id) {
393
+ if (performance.now() >= attempt.deadline)
394
+ return;
395
+ if ('error' in rpc) {
396
+ this.hello = undefined;
397
+ attempt.reject(new BridgeError(rpc.error.code, rpc.error.message, { data: rpc.error.data }));
398
+ }
399
+ else {
400
+ const session = readSession(rpc.result, meta?.sid);
401
+ if (!session)
402
+ return;
403
+ this.hello = undefined;
404
+ attempt.resolve(session);
405
+ }
406
+ return;
407
+ }
408
+ if (!activeSession || activeSession.sid !== meta?.sid)
409
+ return;
410
+ const call = this.pending.get(rpc.id);
411
+ if (call?.session !== activeSession)
412
+ return;
413
+ if (call.deadline !== undefined && performance.now() >= call.deadline) {
414
+ this.fail(rpc.id, ErrorCode.Timeout, 'Call timed out', true);
415
+ return;
416
+ }
417
+ this.take(rpc.id);
418
+ if ('error' in rpc) {
419
+ call.reject(new BridgeError(rpc.error.code, rpc.error.message, {
420
+ data: rpc.error.data, method: call.request.method, traceId: call.traceId,
421
+ }));
422
+ }
423
+ else
424
+ call.resolve(rpc.result);
425
+ this.drain();
426
+ }
427
+ take(id) {
428
+ const call = this.pending.get(id);
429
+ if (!call)
430
+ return;
431
+ this.pending.delete(id);
432
+ if (call.session)
433
+ call.session.inflight--;
434
+ call.stopTimer?.();
435
+ call.stopListening?.();
436
+ return call;
437
+ }
438
+ fail(id, code, message, cancel = false) {
439
+ const call = this.take(id);
440
+ if (!call)
441
+ return;
442
+ call.reject(new BridgeError(code, message, { method: call.request.method, traceId: call.traceId }));
443
+ const session = call.session;
444
+ if (cancel && session === this.session && session?.features.includes('cancel')) {
445
+ this.postCancel(id, session);
446
+ }
447
+ this.drain();
448
+ }
449
+ }
450
+ export function createBridge(options = {}) {
451
+ const { handshakeTimeout = 3000, queueLimit = 100 } = options;
452
+ if (!Number.isInteger(handshakeTimeout) || handshakeTimeout <= 0 || handshakeTimeout > timerLimit) {
453
+ throw new RangeError('handshakeTimeout must be a positive timer interval');
454
+ }
455
+ if (!Number.isSafeInteger(queueLimit) || queueLimit < 0)
456
+ throw new RangeError('Invalid queueLimit');
457
+ return new WebBridge(options, handshakeTimeout, queueLimit);
458
+ }
459
+ export const bridge = createBridge();
460
+ export const ui = {
461
+ toast: {
462
+ show(params, options) {
463
+ return bridge.call('ui.toast.show@1', params, options);
464
+ },
465
+ },
466
+ };
@@ -0,0 +1,21 @@
1
+ import type { JsonObject, JsonValue } from '../../protocol/src/index.js';
2
+ export interface HostInfo {
3
+ readonly platform: string;
4
+ readonly name: string;
5
+ readonly version: string;
6
+ readonly appId?: string;
7
+ readonly appVersion?: string;
8
+ }
9
+ export interface Session {
10
+ sid: string;
11
+ host: HostInfo;
12
+ methods: Map<string, ReadonlySet<number>>;
13
+ events: ReadonlySet<string>;
14
+ features: readonly string[];
15
+ defaultTimeout: number;
16
+ maxMessageBytes: number;
17
+ maxInflight: number;
18
+ inflight: number;
19
+ }
20
+ export declare function isObject(value: unknown): value is JsonObject;
21
+ export declare function readSession(result: JsonValue, sid?: string): Session | undefined;
@@ -0,0 +1,54 @@
1
+ export function isObject(value) {
2
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
3
+ }
4
+ function isPositiveInteger(value) {
5
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
6
+ }
7
+ function isStringArray(value) {
8
+ return Array.isArray(value) && value.every((entry) => typeof entry === 'string') &&
9
+ new Set(value).size === value.length;
10
+ }
11
+ export function readSession(result, sid) {
12
+ if (!isObject(result) || result.jsb !== '1.0' || typeof result.sid !== 'string' || !result.sid ||
13
+ (sid !== undefined && sid !== result.sid))
14
+ return;
15
+ const { host, capabilities, limits } = result;
16
+ if (!isObject(host) || typeof host.platform !== 'string' ||
17
+ typeof host.name !== 'string' || typeof host.version !== 'string' ||
18
+ (host.appId !== undefined && typeof host.appId !== 'string') ||
19
+ (host.appVersion !== undefined && typeof host.appVersion !== 'string'))
20
+ return;
21
+ if (!isObject(capabilities) || !isObject(capabilities.methods) ||
22
+ !isStringArray(capabilities.events) || !isStringArray(capabilities.features))
23
+ return;
24
+ if (!isObject(limits) || !isPositiveInteger(limits.maxMessageBytes) ||
25
+ !isPositiveInteger(limits.maxInflight) || !isPositiveInteger(limits.defaultTimeoutMs) ||
26
+ limits.defaultTimeoutMs > 2147483647)
27
+ return;
28
+ const methods = new Map();
29
+ for (const [method, entry] of Object.entries(capabilities.methods)) {
30
+ if (!isObject(entry) || !Array.isArray(entry.versions) || !entry.versions.length ||
31
+ !entry.versions.every(isPositiveInteger))
32
+ return;
33
+ const versions = new Set(entry.versions);
34
+ if (versions.size !== entry.versions.length)
35
+ return;
36
+ methods.set(method, versions);
37
+ }
38
+ const hostInfo = { platform: host.platform, name: host.name, version: host.version };
39
+ return {
40
+ sid: result.sid,
41
+ host: {
42
+ ...hostInfo,
43
+ ...(host.appId === undefined ? {} : { appId: host.appId }),
44
+ ...(host.appVersion === undefined ? {} : { appVersion: host.appVersion }),
45
+ },
46
+ methods,
47
+ events: new Set(capabilities.events),
48
+ features: capabilities.features,
49
+ defaultTimeout: limits.defaultTimeoutMs,
50
+ maxMessageBytes: limits.maxMessageBytes,
51
+ maxInflight: limits.maxInflight,
52
+ inflight: 0,
53
+ };
54
+ }
@@ -0,0 +1,20 @@
1
+ export interface Adapter {
2
+ readonly name?: string;
3
+ readonly protocols?: readonly number[];
4
+ detect?(): boolean;
5
+ send(raw: string): void | Promise<string | null>;
6
+ listen(onMessage: (raw: string) => void): () => void;
7
+ }
8
+ interface OJSBTransport {
9
+ readonly name: string;
10
+ readonly protocols: readonly number[];
11
+ postMessage(raw: string): void | Promise<string | null>;
12
+ }
13
+ declare global {
14
+ interface Window {
15
+ __OJSB_TRANSPORT__?: Readonly<OJSBTransport>;
16
+ __OJSB_RECEIVE__?: (raw: string) => void;
17
+ }
18
+ }
19
+ export declare function findBrowserAdapter(timeout: number, signal: AbortSignal): Promise<Adapter | undefined>;
20
+ export {};
@@ -0,0 +1,57 @@
1
+ const receivers = new WeakMap();
2
+ export function findBrowserAdapter(timeout, signal) {
3
+ if (typeof window === 'undefined' || signal.aborted)
4
+ return Promise.resolve(undefined);
5
+ const target = window;
6
+ const detect = () => {
7
+ const transport = target.__OJSB_TRANSPORT__;
8
+ if (typeof transport?.postMessage !== 'function')
9
+ return;
10
+ return {
11
+ name: transport.name,
12
+ protocols: transport.protocols,
13
+ send: (raw) => transport.postMessage(raw),
14
+ listen(onMessage) {
15
+ if (receivers.has(target))
16
+ throw new Error('The injected shim already has a receiver');
17
+ receivers.set(target, onMessage);
18
+ try {
19
+ target.__OJSB_RECEIVE__ = onMessage;
20
+ }
21
+ catch (error) {
22
+ receivers.delete(target);
23
+ throw error;
24
+ }
25
+ return () => {
26
+ // Native shims expose a forwarding getter, so ownership is tracked independently.
27
+ if (receivers.get(target) !== onMessage)
28
+ return;
29
+ receivers.delete(target);
30
+ target.__OJSB_RECEIVE__ = undefined;
31
+ };
32
+ },
33
+ };
34
+ };
35
+ const existing = detect();
36
+ if (existing)
37
+ return Promise.resolve(existing);
38
+ return new Promise((resolve) => {
39
+ const finish = (adapter) => {
40
+ clearTimeout(timer);
41
+ target.removeEventListener('ojsb:transportready', onReady);
42
+ signal.removeEventListener('abort', onAbort);
43
+ resolve(adapter);
44
+ };
45
+ const onAbort = () => finish();
46
+ const onReady = () => {
47
+ const adapter = detect();
48
+ if (adapter)
49
+ finish(adapter);
50
+ };
51
+ const timer = setTimeout(finish, timeout);
52
+ target.addEventListener('ojsb:transportready', onReady);
53
+ signal.addEventListener('abort', onAbort, { once: true });
54
+ if (signal.aborted)
55
+ onAbort();
56
+ });
57
+ }