@open-jsbridge/web 0.0.0-stage → 0.2.0

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