@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.
- package/LICENSE +21 -0
- package/README.md +50 -2
- package/package.json +25 -4
- package/packages/protocol/src/index.d.ts +67 -0
- package/packages/protocol/src/index.js +109 -0
- package/packages/web-mock/src/index.d.ts +31 -0
- package/packages/web-mock/src/index.js +305 -0
- package/packages/web-sdk/src/errors.d.ts +14 -0
- package/packages/web-sdk/src/errors.js +10 -0
- package/packages/web-sdk/src/events.d.ts +32 -0
- package/packages/web-sdk/src/events.js +219 -0
- package/packages/web-sdk/src/index.d.ts +39 -0
- package/packages/web-sdk/src/index.js +466 -0
- package/packages/web-sdk/src/session.d.ts +21 -0
- package/packages/web-sdk/src/session.js +54 -0
- package/packages/web-sdk/src/transport.d.ts +20 -0
- package/packages/web-sdk/src/transport.js +57 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Open JSBridge contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,51 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @open-jsbridge/web
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
面向 Open JSBridge 宿主的 Web SDK。包含 ESM 入口和 TypeScript 类型声明。
|
|
4
|
+
|
|
5
|
+
## 安装
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @open-jsbridge/web
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
验证仓库版本时,在仓库根目录运行 `npm run pack:web`,然后在项目中安装生成的 tarball。
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm install /path/to/open-jsbridge/dist/open-jsbridge-web-0.1.0.tgz
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## App WebView
|
|
18
|
+
|
|
19
|
+
使用默认单例。第一次调用会等待原生 transport 并自动握手。下面的调用要求宿主启用 `device.getInfo`。
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { bridge } from '@open-jsbridge/web'
|
|
23
|
+
|
|
24
|
+
const device = await bridge.call('device.getInfo')
|
|
25
|
+
console.log(device)
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
宿主启用 Toast 后,可以使用同一单例上的类型化入口。
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { ui } from '@open-jsbridge/web'
|
|
32
|
+
|
|
33
|
+
await ui.toast.show({ text: '已保存' })
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## 浏览器本地联调
|
|
37
|
+
|
|
38
|
+
从 `@open-jsbridge/web/mock` 显式安装 Mock transport。应用代码仍使用同一个 SDK 单例。
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { bridge } from '@open-jsbridge/web'
|
|
42
|
+
import { installMockTransport } from '@open-jsbridge/web/mock'
|
|
43
|
+
|
|
44
|
+
const mock = installMockTransport({ events: ['acme.app.configChanged'] })
|
|
45
|
+
const stop = bridge.on<{ theme: string }>('acme.app.configChanged', console.log)
|
|
46
|
+
await stop.ready
|
|
47
|
+
mock?.emit('acme.app.configChanged', { theme: 'dark' })
|
|
48
|
+
stop()
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
[项目仓库和宿主接入方式](https://github.com/Josp3r/open-jsbridge)
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-jsbridge/web",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Web SDK for Open JSBridge hosts",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"types": "./packages/web-sdk/src/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./packages/web-sdk/src/index.d.ts",
|
|
11
|
+
"import": "./packages/web-sdk/src/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./mock": {
|
|
14
|
+
"types": "./packages/web-mock/src/index.d.ts",
|
|
15
|
+
"import": "./packages/web-mock/src/index.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"packages/protocol/src",
|
|
20
|
+
"packages/web-mock/src",
|
|
21
|
+
"packages/web-sdk/src"
|
|
22
|
+
],
|
|
23
|
+
"repository": "https://github.com/Josp3r/open-jsbridge",
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
}
|
|
27
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
export type JsonValue = null | boolean | number | string | JsonObject | JsonValue[];
|
|
2
|
+
export interface JsonObject {
|
|
3
|
+
[key: string]: JsonValue;
|
|
4
|
+
}
|
|
5
|
+
interface RpcMethod {
|
|
6
|
+
jsonrpc: '2.0';
|
|
7
|
+
method: string;
|
|
8
|
+
params?: JsonObject;
|
|
9
|
+
}
|
|
10
|
+
export interface RpcRequest extends RpcMethod {
|
|
11
|
+
id: string;
|
|
12
|
+
}
|
|
13
|
+
export interface RpcNotification extends RpcMethod {
|
|
14
|
+
}
|
|
15
|
+
export interface RpcSuccess {
|
|
16
|
+
jsonrpc: '2.0';
|
|
17
|
+
id: string;
|
|
18
|
+
result: JsonValue;
|
|
19
|
+
}
|
|
20
|
+
export interface RpcFailure {
|
|
21
|
+
jsonrpc: '2.0';
|
|
22
|
+
id: string | null;
|
|
23
|
+
error: {
|
|
24
|
+
code: number;
|
|
25
|
+
message: string;
|
|
26
|
+
data?: JsonValue;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export interface Envelope {
|
|
30
|
+
jsb: '1.0';
|
|
31
|
+
meta?: {
|
|
32
|
+
sid?: string;
|
|
33
|
+
timeout?: number;
|
|
34
|
+
ts?: number;
|
|
35
|
+
traceId?: string;
|
|
36
|
+
[field: string]: JsonValue | undefined;
|
|
37
|
+
};
|
|
38
|
+
rpc: RpcRequest | RpcNotification | RpcSuccess | RpcFailure;
|
|
39
|
+
[field: string]: unknown;
|
|
40
|
+
}
|
|
41
|
+
export declare const ErrorCode: Readonly<{
|
|
42
|
+
readonly ParseError: -32700;
|
|
43
|
+
readonly InvalidRequest: -32600;
|
|
44
|
+
readonly MethodNotFound: -32601;
|
|
45
|
+
readonly InvalidParams: -32602;
|
|
46
|
+
readonly InternalError: -32603;
|
|
47
|
+
readonly Unavailable: -32000;
|
|
48
|
+
readonly Timeout: -32001;
|
|
49
|
+
readonly Cancelled: -32002;
|
|
50
|
+
readonly PermissionDenied: -32003;
|
|
51
|
+
readonly UnsupportedProtocol: -32004;
|
|
52
|
+
readonly NotReady: -32005;
|
|
53
|
+
readonly PayloadTooLarge: -32006;
|
|
54
|
+
readonly UserDenied: -32007;
|
|
55
|
+
readonly RateLimited: -32008;
|
|
56
|
+
readonly SessionExpired: -32009;
|
|
57
|
+
readonly Busy: -32010;
|
|
58
|
+
}>;
|
|
59
|
+
type DecodeErrorCode = typeof ErrorCode.ParseError | typeof ErrorCode.InvalidRequest;
|
|
60
|
+
export declare class WireDecodeError extends Error {
|
|
61
|
+
readonly code: DecodeErrorCode;
|
|
62
|
+
readonly cause?: unknown | undefined;
|
|
63
|
+
constructor(code: DecodeErrorCode, message: string, cause?: unknown | undefined);
|
|
64
|
+
}
|
|
65
|
+
export declare function decodeEnvelope(raw: string): Envelope;
|
|
66
|
+
export declare function encodeEnvelope(envelope: Envelope): string;
|
|
67
|
+
export {};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
export const ErrorCode = Object.freeze({
|
|
2
|
+
ParseError: -32700,
|
|
3
|
+
InvalidRequest: -32600,
|
|
4
|
+
MethodNotFound: -32601,
|
|
5
|
+
InvalidParams: -32602,
|
|
6
|
+
InternalError: -32603,
|
|
7
|
+
Unavailable: -32000,
|
|
8
|
+
Timeout: -32001,
|
|
9
|
+
Cancelled: -32002,
|
|
10
|
+
PermissionDenied: -32003,
|
|
11
|
+
UnsupportedProtocol: -32004,
|
|
12
|
+
NotReady: -32005,
|
|
13
|
+
PayloadTooLarge: -32006,
|
|
14
|
+
UserDenied: -32007,
|
|
15
|
+
RateLimited: -32008,
|
|
16
|
+
SessionExpired: -32009,
|
|
17
|
+
Busy: -32010,
|
|
18
|
+
});
|
|
19
|
+
export class WireDecodeError extends Error {
|
|
20
|
+
constructor(code, message, cause) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.code = code;
|
|
23
|
+
this.cause = cause;
|
|
24
|
+
this.name = 'WireDecodeError';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const methodPattern = /^(?!rpc\.)[a-z][a-zA-Z0-9]*(\.[a-z][a-zA-Z0-9]*)+(@[1-9][0-9]*)?$/;
|
|
28
|
+
function isObject(value) {
|
|
29
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
30
|
+
}
|
|
31
|
+
function hasOwn(value, key) {
|
|
32
|
+
return Object.prototype.hasOwnProperty.call(value, key);
|
|
33
|
+
}
|
|
34
|
+
function isId(value) {
|
|
35
|
+
return typeof value === 'string' && value.length <= 256 && /^.{1,128}$/su.test(value);
|
|
36
|
+
}
|
|
37
|
+
function hasOnlyKeys(value, keys) {
|
|
38
|
+
return Object.keys(value).every((key) => keys.includes(key));
|
|
39
|
+
}
|
|
40
|
+
function isNonNegativeInteger(value) {
|
|
41
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
|
42
|
+
}
|
|
43
|
+
function isMeta(value) {
|
|
44
|
+
return isObject(value) &&
|
|
45
|
+
(!hasOwn(value, 'sid') || (typeof value.sid === 'string' && value.sid.length > 0)) &&
|
|
46
|
+
(!hasOwn(value, 'timeout') || isNonNegativeInteger(value.timeout)) &&
|
|
47
|
+
(!hasOwn(value, 'ts') || isNonNegativeInteger(value.ts)) &&
|
|
48
|
+
(!hasOwn(value, 'traceId') || typeof value.traceId === 'string');
|
|
49
|
+
}
|
|
50
|
+
function isError(value) {
|
|
51
|
+
return isObject(value) && Number.isSafeInteger(value.code) && typeof value.message === 'string' &&
|
|
52
|
+
hasOnlyKeys(value, ['code', 'message', 'data']);
|
|
53
|
+
}
|
|
54
|
+
function isRpcMessage(value) {
|
|
55
|
+
if (!isObject(value) || value.jsonrpc !== '2.0')
|
|
56
|
+
return false;
|
|
57
|
+
if (hasOwn(value, 'method')) {
|
|
58
|
+
return typeof value.method === 'string' && methodPattern.test(value.method) &&
|
|
59
|
+
(!hasOwn(value, 'params') || isObject(value.params)) &&
|
|
60
|
+
(!hasOwn(value, 'id') || isId(value.id)) &&
|
|
61
|
+
hasOnlyKeys(value, ['jsonrpc', 'method', 'params', 'id']);
|
|
62
|
+
}
|
|
63
|
+
if (hasOwn(value, 'error')) {
|
|
64
|
+
return (isId(value.id) || value.id === null) && isError(value.error) &&
|
|
65
|
+
hasOnlyKeys(value, ['jsonrpc', 'id', 'error']);
|
|
66
|
+
}
|
|
67
|
+
return isId(value.id) && hasOwn(value, 'result') &&
|
|
68
|
+
hasOnlyKeys(value, ['jsonrpc', 'id', 'result']);
|
|
69
|
+
}
|
|
70
|
+
function isEnvelope(value) {
|
|
71
|
+
return isObject(value) && value.jsb === '1.0' && isRpcMessage(value.rpc) &&
|
|
72
|
+
(!hasOwn(value, 'meta') || isMeta(value.meta));
|
|
73
|
+
}
|
|
74
|
+
function checkJsonNumber(_key, value) {
|
|
75
|
+
if (typeof value === 'number' &&
|
|
76
|
+
(!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value)))) {
|
|
77
|
+
throw new WireDecodeError(ErrorCode.InvalidRequest, 'Number is outside the supported JSON range');
|
|
78
|
+
}
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
export function decodeEnvelope(raw) {
|
|
82
|
+
let value;
|
|
83
|
+
try {
|
|
84
|
+
value = JSON.parse(raw, checkJsonNumber);
|
|
85
|
+
}
|
|
86
|
+
catch (cause) {
|
|
87
|
+
if (cause instanceof WireDecodeError)
|
|
88
|
+
throw cause;
|
|
89
|
+
throw new WireDecodeError(ErrorCode.ParseError, 'Parse error', cause);
|
|
90
|
+
}
|
|
91
|
+
if (!isEnvelope(value)) {
|
|
92
|
+
throw new WireDecodeError(ErrorCode.InvalidRequest, 'Invalid request');
|
|
93
|
+
}
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
96
|
+
export function encodeEnvelope(envelope) {
|
|
97
|
+
let raw;
|
|
98
|
+
try {
|
|
99
|
+
raw = JSON.stringify(envelope, checkJsonNumber);
|
|
100
|
+
}
|
|
101
|
+
catch (cause) {
|
|
102
|
+
if (cause instanceof WireDecodeError)
|
|
103
|
+
throw cause;
|
|
104
|
+
throw new WireDecodeError(ErrorCode.InvalidRequest, 'Message is not serializable', cause);
|
|
105
|
+
}
|
|
106
|
+
// Encoding can omit undefined members or apply custom serializers. Check the wire representation.
|
|
107
|
+
decodeEnvelope(raw);
|
|
108
|
+
return raw;
|
|
109
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type JsonValue } from '../../protocol/src/index.js';
|
|
2
|
+
declare const networkTypes: readonly ["wifi", "cellular", "ethernet", "other", "none", "unknown"];
|
|
3
|
+
export interface MockAdapterOptions {
|
|
4
|
+
events?: readonly string[];
|
|
5
|
+
/** Advertised events whose subscription requests are denied by the Mock host. */
|
|
6
|
+
deniedEvents?: readonly string[];
|
|
7
|
+
deviceInfo?: {
|
|
8
|
+
os: 'ios' | 'android';
|
|
9
|
+
osVersion: string;
|
|
10
|
+
};
|
|
11
|
+
getNetworkStatus?: () => {
|
|
12
|
+
type: typeof networkTypes[number];
|
|
13
|
+
};
|
|
14
|
+
showToast?: (text: string) => void | Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
/** A standalone Mock session with Promise responses and out-of-band event delivery. */
|
|
17
|
+
export declare function createMockAdapter(options?: MockAdapterOptions): {
|
|
18
|
+
name: string;
|
|
19
|
+
send: (raw: string) => Promise<string | null>;
|
|
20
|
+
emit: (name: string, payload: JsonValue) => boolean;
|
|
21
|
+
listen(onMessage: (raw: string) => void): () => void;
|
|
22
|
+
};
|
|
23
|
+
type FrameDirection = 'request' | 'response' | 'event';
|
|
24
|
+
export interface MockTransportOptions extends MockAdapterOptions {
|
|
25
|
+
onFrame?: (direction: FrameDirection, raw: string | null) => void;
|
|
26
|
+
}
|
|
27
|
+
/** Installs a Mock Host Shim on the current browser window when its transport slot is free. */
|
|
28
|
+
export declare function installMockTransport(options?: MockTransportOptions): {
|
|
29
|
+
emit(name: string, payload: JsonValue): boolean;
|
|
30
|
+
} | undefined;
|
|
31
|
+
export {};
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { decodeEnvelope, encodeEnvelope, ErrorCode, WireDecodeError, } from '../../protocol/src/index.js';
|
|
2
|
+
const helloMethod = 'bridge.hello';
|
|
3
|
+
const echoMethod = 'conformance.echo';
|
|
4
|
+
const toastMethod = 'ui.toast.show';
|
|
5
|
+
const subscribeMethod = 'bridge.subscribe';
|
|
6
|
+
const unsubscribeMethod = 'bridge.unsubscribe';
|
|
7
|
+
const eventNamePattern = /^(?!rpc\.)[a-z][a-zA-Z0-9]*(?:\.[a-z][a-zA-Z0-9]*)+$/;
|
|
8
|
+
const networkTypes = ['wifi', 'cellular', 'ethernet', 'other', 'none', 'unknown'];
|
|
9
|
+
const limits = { maxMessageBytes: 1048576, maxInflight: 64, defaultTimeoutMs: 15000 };
|
|
10
|
+
const utf8 = new TextEncoder();
|
|
11
|
+
let nextSession = 0;
|
|
12
|
+
function exceedsMessageLimit(raw) {
|
|
13
|
+
return raw.length > limits.maxMessageBytes || utf8.encode(raw).byteLength > limits.maxMessageBytes;
|
|
14
|
+
}
|
|
15
|
+
function failure(id, code, message, data, sid) {
|
|
16
|
+
return encodeEnvelope({
|
|
17
|
+
jsb: '1.0', ...(sid === undefined ? {} : { meta: { sid } }),
|
|
18
|
+
rpc: { jsonrpc: '2.0', id, error: { code, message, ...(data === undefined ? {} : { data }) } },
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
function success(id, result, sid) {
|
|
22
|
+
return encodeEnvelope({ jsb: '1.0', meta: { sid }, rpc: { jsonrpc: '2.0', id, result } });
|
|
23
|
+
}
|
|
24
|
+
function readProtocols(params) {
|
|
25
|
+
const protocols = params?.protocols;
|
|
26
|
+
if (!Array.isArray(protocols) || !protocols.length ||
|
|
27
|
+
!protocols.every((major) => typeof major === 'number' && Number.isSafeInteger(major) && major > 0) ||
|
|
28
|
+
new Set(protocols).size !== protocols.length)
|
|
29
|
+
return;
|
|
30
|
+
const { sdk, wants } = params ?? {};
|
|
31
|
+
if (sdk !== undefined && (sdk === null || typeof sdk !== 'object' || Array.isArray(sdk) ||
|
|
32
|
+
typeof sdk.name !== 'string' || typeof sdk.version !== 'string'))
|
|
33
|
+
return;
|
|
34
|
+
if (wants !== undefined && (!Array.isArray(wants) || !wants.every((want) => typeof want === 'string') ||
|
|
35
|
+
new Set(wants).size !== wants.length))
|
|
36
|
+
return;
|
|
37
|
+
return protocols;
|
|
38
|
+
}
|
|
39
|
+
function isEventName(name) {
|
|
40
|
+
return typeof name === 'string' && eventNamePattern.test(name);
|
|
41
|
+
}
|
|
42
|
+
function readEventNames(params) {
|
|
43
|
+
const events = params?.events;
|
|
44
|
+
if (Array.isArray(events) && events.length && events.every(isEventName) &&
|
|
45
|
+
new Set(events).size === events.length)
|
|
46
|
+
return events;
|
|
47
|
+
}
|
|
48
|
+
function isJsonValue(value, ancestors) {
|
|
49
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean' || typeof value === 'number') {
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
if (typeof value !== 'object' || ancestors.has(value))
|
|
53
|
+
return false;
|
|
54
|
+
if (!Array.isArray(value)) {
|
|
55
|
+
const prototype = Object.getPrototypeOf(value);
|
|
56
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
ancestors.add(value);
|
|
60
|
+
for (const entry of Array.isArray(value) ? value : Object.values(value)) {
|
|
61
|
+
if (!isJsonValue(entry, ancestors))
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
ancestors.delete(value);
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
/** A standalone Mock session with Promise responses and out-of-band event delivery. */
|
|
68
|
+
export function createMockAdapter(options) {
|
|
69
|
+
let sid;
|
|
70
|
+
let receiver;
|
|
71
|
+
const helloIds = new Set();
|
|
72
|
+
const requestIds = new Set();
|
|
73
|
+
const methods = new Map([
|
|
74
|
+
[echoMethod, (params) => params ?? {}],
|
|
75
|
+
]);
|
|
76
|
+
const { deviceInfo, getNetworkStatus, showToast } = options ?? {};
|
|
77
|
+
if (deviceInfo) {
|
|
78
|
+
const { os, osVersion } = deviceInfo;
|
|
79
|
+
if ((os === 'ios' || os === 'android') && typeof osVersion === 'string' && osVersion.length > 0) {
|
|
80
|
+
methods.set('device.getInfo', () => ({ os, osVersion }));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (getNetworkStatus) {
|
|
84
|
+
methods.set('network.getStatus', () => {
|
|
85
|
+
const { type } = getNetworkStatus();
|
|
86
|
+
return { type: networkTypes.includes(type) ? type : 'unknown' };
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
if (showToast) {
|
|
90
|
+
methods.set(toastMethod, async (params) => {
|
|
91
|
+
await showToast(params?.text);
|
|
92
|
+
return {};
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
const allowedEvents = new Set(options?.events?.filter(isEventName));
|
|
96
|
+
const deniedEvents = new Set(options?.deniedEvents?.filter(isEventName));
|
|
97
|
+
const eventNames = [...new Set([...allowedEvents, ...deniedEvents])];
|
|
98
|
+
const subscriptions = new Set();
|
|
99
|
+
function resetSession() {
|
|
100
|
+
sid = undefined;
|
|
101
|
+
helloIds.clear();
|
|
102
|
+
requestIds.clear();
|
|
103
|
+
subscriptions.clear();
|
|
104
|
+
}
|
|
105
|
+
function negotiate(request) {
|
|
106
|
+
const protocols = readProtocols(request.params);
|
|
107
|
+
if (!protocols)
|
|
108
|
+
return failure(request.id, ErrorCode.InvalidParams, 'Invalid handshake params');
|
|
109
|
+
if (!protocols.includes(1)) {
|
|
110
|
+
return failure(request.id, ErrorCode.UnsupportedProtocol, 'Unsupported protocol', { supported: [1] });
|
|
111
|
+
}
|
|
112
|
+
sid ?? (sid = globalThis.crypto?.randomUUID?.() ?? `mock-${++nextSession}`);
|
|
113
|
+
return success(request.id, {
|
|
114
|
+
jsb: '1.0', sid, host: { platform: 'mock', name: 'mock', version: '0.1.0' },
|
|
115
|
+
capabilities: {
|
|
116
|
+
methods: Object.fromEntries([...methods.keys()].map((method) => [method, { versions: [1] }])),
|
|
117
|
+
events: eventNames,
|
|
118
|
+
features: [],
|
|
119
|
+
},
|
|
120
|
+
limits,
|
|
121
|
+
}, sid);
|
|
122
|
+
}
|
|
123
|
+
function controlSubscription(method, request, session) {
|
|
124
|
+
const events = readEventNames(request.params);
|
|
125
|
+
if (!events)
|
|
126
|
+
return failure(request.id, ErrorCode.InvalidParams, 'Invalid event subscription params', undefined, session);
|
|
127
|
+
if (method === unsubscribeMethod) {
|
|
128
|
+
const response = success(request.id, { unsubscribed: events }, session);
|
|
129
|
+
if (exceedsMessageLimit(response)) {
|
|
130
|
+
return failure(request.id, ErrorCode.PayloadTooLarge, 'Payload too large', undefined, session);
|
|
131
|
+
}
|
|
132
|
+
for (const event of events)
|
|
133
|
+
subscriptions.delete(event);
|
|
134
|
+
return response;
|
|
135
|
+
}
|
|
136
|
+
const subscribed = [];
|
|
137
|
+
const denied = [];
|
|
138
|
+
for (const event of events) {
|
|
139
|
+
if (allowedEvents.has(event) && !deniedEvents.has(event))
|
|
140
|
+
subscribed.push(event);
|
|
141
|
+
else
|
|
142
|
+
denied.push(event);
|
|
143
|
+
}
|
|
144
|
+
const response = success(request.id, { subscribed, denied }, session);
|
|
145
|
+
if (exceedsMessageLimit(response)) {
|
|
146
|
+
return failure(request.id, ErrorCode.PayloadTooLarge, 'Payload too large', undefined, session);
|
|
147
|
+
}
|
|
148
|
+
for (const event of subscribed)
|
|
149
|
+
subscriptions.add(event);
|
|
150
|
+
return response;
|
|
151
|
+
}
|
|
152
|
+
async function send(raw) {
|
|
153
|
+
if (exceedsMessageLimit(raw))
|
|
154
|
+
return null;
|
|
155
|
+
let envelope;
|
|
156
|
+
try {
|
|
157
|
+
envelope = decodeEnvelope(raw);
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
// This adapter has one route. It can attach a session only after negotiating on that route.
|
|
161
|
+
if (sid && error instanceof WireDecodeError && error.code === ErrorCode.ParseError) {
|
|
162
|
+
return failure(null, error.code, error.message, undefined, sid);
|
|
163
|
+
}
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
const { rpc, meta } = envelope;
|
|
167
|
+
if (!('method' in rpc) || !('id' in rpc))
|
|
168
|
+
return null;
|
|
169
|
+
const method = rpc.method.endsWith('@1') ? rpc.method.slice(0, -2) : rpc.method;
|
|
170
|
+
if (method === helloMethod) {
|
|
171
|
+
if ((meta?.sid !== undefined && meta.sid !== sid) || helloIds.has(rpc.id))
|
|
172
|
+
return null;
|
|
173
|
+
helloIds.add(rpc.id);
|
|
174
|
+
if (meta?.timeout === 0) {
|
|
175
|
+
return failure(rpc.id, ErrorCode.InvalidParams, 'Invalid request timeout', undefined, sid);
|
|
176
|
+
}
|
|
177
|
+
return negotiate(rpc);
|
|
178
|
+
}
|
|
179
|
+
if (!sid || meta?.sid !== sid || requestIds.has(rpc.id))
|
|
180
|
+
return null;
|
|
181
|
+
requestIds.add(rpc.id);
|
|
182
|
+
const control = method === subscribeMethod || method === unsubscribeMethod;
|
|
183
|
+
const handle = methods.get(method);
|
|
184
|
+
if (!control && !handle)
|
|
185
|
+
return failure(rpc.id, ErrorCode.MethodNotFound, 'Method not found', undefined, sid);
|
|
186
|
+
if (meta.timeout === 0)
|
|
187
|
+
return failure(rpc.id, ErrorCode.InvalidParams, 'Invalid request timeout', undefined, sid);
|
|
188
|
+
if (control)
|
|
189
|
+
return controlSubscription(method, rpc, sid);
|
|
190
|
+
if (method === toastMethod) {
|
|
191
|
+
const text = rpc.params?.text;
|
|
192
|
+
if (typeof text !== 'string' || text.length === 0 || [...text].length > 120 ||
|
|
193
|
+
Object.keys(rpc.params ?? {}).length !== 1) {
|
|
194
|
+
return failure(rpc.id, ErrorCode.InvalidParams, 'Invalid toast params', undefined, sid);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
else if (method !== echoMethod && Object.keys(rpc.params ?? {}).length > 0) {
|
|
198
|
+
return failure(rpc.id, ErrorCode.InvalidParams, 'Expected empty params', undefined, sid);
|
|
199
|
+
}
|
|
200
|
+
const replySid = sid;
|
|
201
|
+
try {
|
|
202
|
+
const result = handle(rpc.params);
|
|
203
|
+
const value = result instanceof Promise ? await result : result;
|
|
204
|
+
if (sid !== replySid)
|
|
205
|
+
return null;
|
|
206
|
+
const response = success(rpc.id, value, replySid);
|
|
207
|
+
if (exceedsMessageLimit(response)) {
|
|
208
|
+
return failure(rpc.id, ErrorCode.PayloadTooLarge, 'Payload too large', undefined, sid);
|
|
209
|
+
}
|
|
210
|
+
return response;
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
return sid === replySid ? failure(rpc.id, ErrorCode.InternalError, 'Internal error', undefined, replySid) : null;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
function emit(name, payload) {
|
|
217
|
+
const receive = receiver;
|
|
218
|
+
if (!sid || !receive || !subscriptions.has(name))
|
|
219
|
+
return false;
|
|
220
|
+
let raw;
|
|
221
|
+
try {
|
|
222
|
+
if (!isJsonValue(payload, new Set()))
|
|
223
|
+
return false;
|
|
224
|
+
raw = encodeEnvelope({
|
|
225
|
+
jsb: '1.0', meta: { sid },
|
|
226
|
+
rpc: { jsonrpc: '2.0', method: 'bridge.event', params: { name, payload } },
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
if (exceedsMessageLimit(raw) || receiver !== receive || !subscriptions.has(name))
|
|
233
|
+
return false;
|
|
234
|
+
receive(raw);
|
|
235
|
+
return true;
|
|
236
|
+
}
|
|
237
|
+
return {
|
|
238
|
+
name: 'mock',
|
|
239
|
+
send,
|
|
240
|
+
emit,
|
|
241
|
+
listen(onMessage) {
|
|
242
|
+
if (receiver)
|
|
243
|
+
resetSession();
|
|
244
|
+
const receive = (raw) => onMessage(raw);
|
|
245
|
+
receiver = receive;
|
|
246
|
+
return () => {
|
|
247
|
+
if (receiver !== receive)
|
|
248
|
+
return;
|
|
249
|
+
receiver = undefined;
|
|
250
|
+
resetSession();
|
|
251
|
+
};
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
/** Installs a Mock Host Shim on the current browser window when its transport slot is free. */
|
|
256
|
+
export function installMockTransport(options) {
|
|
257
|
+
if (typeof window === 'undefined' || '__OJSB_TRANSPORT__' in window)
|
|
258
|
+
return;
|
|
259
|
+
const target = window;
|
|
260
|
+
const adapter = createMockAdapter(options);
|
|
261
|
+
const onFrame = options?.onFrame;
|
|
262
|
+
const observe = (direction, raw) => {
|
|
263
|
+
try {
|
|
264
|
+
onFrame?.(direction, raw);
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
// Observation must not interrupt transport traffic.
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
const transport = Object.freeze({
|
|
271
|
+
name: adapter.name,
|
|
272
|
+
protocols: Object.freeze([1]),
|
|
273
|
+
async postMessage(raw) {
|
|
274
|
+
observe('request', raw);
|
|
275
|
+
const reply = await adapter.send(raw);
|
|
276
|
+
observe('response', reply);
|
|
277
|
+
return reply;
|
|
278
|
+
},
|
|
279
|
+
});
|
|
280
|
+
const forwardEvent = (raw) => {
|
|
281
|
+
const receive = target.__OJSB_RECEIVE__;
|
|
282
|
+
if (typeof receive !== 'function')
|
|
283
|
+
return;
|
|
284
|
+
observe('event', raw);
|
|
285
|
+
receive.call(target, raw);
|
|
286
|
+
};
|
|
287
|
+
Object.defineProperty(target, '__OJSB_TRANSPORT__', {
|
|
288
|
+
value: transport,
|
|
289
|
+
writable: false,
|
|
290
|
+
configurable: false,
|
|
291
|
+
});
|
|
292
|
+
let unlisten = adapter.listen(forwardEvent);
|
|
293
|
+
target.addEventListener('pagehide', () => {
|
|
294
|
+
unlisten();
|
|
295
|
+
unlisten = adapter.listen(forwardEvent);
|
|
296
|
+
});
|
|
297
|
+
target.dispatchEvent(new CustomEvent('ojsb:transportready'));
|
|
298
|
+
return {
|
|
299
|
+
emit(name, payload) {
|
|
300
|
+
if (typeof target.__OJSB_RECEIVE__ !== 'function')
|
|
301
|
+
return false;
|
|
302
|
+
return adapter.emit(name, payload);
|
|
303
|
+
},
|
|
304
|
+
};
|
|
305
|
+
}
|
|
@@ -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,32 @@
|
|
|
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 type EventListener<T = unknown> = (payload: T) => void;
|
|
5
|
+
export interface EventSubscription {
|
|
6
|
+
(): void;
|
|
7
|
+
readonly ready: Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
export interface EventControl {
|
|
10
|
+
onReply: (result: JsonValue) => void;
|
|
11
|
+
onDispatch?: () => void;
|
|
12
|
+
waitForSlot?: boolean;
|
|
13
|
+
}
|
|
14
|
+
type Request = (method: 'bridge.subscribe' | 'bridge.unsubscribe', params: JsonObject, control: EventControl) => Promise<unknown>;
|
|
15
|
+
export declare function hasSessionEvent(session: Session | undefined, name: string): boolean;
|
|
16
|
+
export declare class EventSubscriptions {
|
|
17
|
+
private readonly request;
|
|
18
|
+
private readonly connect;
|
|
19
|
+
private readonly subscriptions;
|
|
20
|
+
private session;
|
|
21
|
+
constructor(request: Request, connect: () => void);
|
|
22
|
+
on<T>(name: string, listener: EventListener<T>): EventSubscription;
|
|
23
|
+
off<T>(name: string, listener?: EventListener<T>): void;
|
|
24
|
+
start(session: Session): void;
|
|
25
|
+
reset(): void;
|
|
26
|
+
rejectWaiting(error: BridgeError): void;
|
|
27
|
+
deliver(params: JsonObject | undefined): void;
|
|
28
|
+
private rejectListeners;
|
|
29
|
+
private reconcile;
|
|
30
|
+
private unsubscribe;
|
|
31
|
+
}
|
|
32
|
+
export {};
|