xshell 0.0.58 → 0.0.60
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/net.browser.d.ts +45 -40
- package/net.browser.js +124 -123
- package/net.browser.js.map +1 -1
- package/net.d.ts +45 -40
- package/net.js +124 -123
- package/net.js.map +1 -1
- package/package.json +22 -23
- package/process.d.ts +6 -0
- package/process.js.map +1 -1
- package/prototype.browser.d.ts +8 -8
- package/prototype.browser.js.map +1 -1
- package/prototype.d.ts +20 -16
- package/prototype.js +17 -12
- package/prototype.js.map +1 -1
- package/repl.d.ts +1 -1
- package/repl.js +12 -10
- package/repl.js.map +1 -1
- package/server.js.map +1 -1
- package/utils.browser.d.ts +14 -2
- package/utils.browser.js +41 -7
- package/utils.browser.js.map +1 -1
- package/utils.d.ts +15 -3
- package/utils.js +32 -3
- package/utils.js.map +1 -1
package/net.browser.d.ts
CHANGED
|
@@ -39,70 +39,75 @@ export declare function connect_websocket(url: string | URL, { protocols, on_ope
|
|
|
39
39
|
data: ArrayBuffer | string;
|
|
40
40
|
}, websocket: WebSocket): any;
|
|
41
41
|
}): Promise<WebSocket>;
|
|
42
|
+
/** 接收到消息后的处理函数
|
|
43
|
+
返回值可以是:
|
|
44
|
+
- 数组: 会自动被封装为 { id: 相同, data: 返回值, done: true } 这样的消息并调用 websocket.send 将其发送
|
|
45
|
+
- void: 什么都不做
|
|
46
|
+
- 以上的 promise */
|
|
47
|
+
export declare type MessageHandler = (message: Message, websocket?: WebSocket) => void | any[] | Promise<void | any[]>;
|
|
42
48
|
/** 二进制消息格式
|
|
43
49
|
- json.length (小端序): 4 字节
|
|
44
50
|
- json 数据
|
|
45
51
|
- binary 数据
|
|
46
52
|
*/
|
|
47
|
-
export interface Message<
|
|
48
|
-
/**
|
|
53
|
+
export interface Message<TData extends any[] = any[]> {
|
|
54
|
+
/** rpc id: 在 rpc 系统中认为是唯一的。用来在单个 websocket 连接上复用多个 rpc 请求。多个相同 id 的 message 组成一个请求流 */
|
|
49
55
|
id?: number;
|
|
50
|
-
/** rpc
|
|
56
|
+
/** 只在 rpc 发起时指定被调用的 function name,发起时 rpc 时必传 */
|
|
51
57
|
func?: string;
|
|
52
|
-
/**
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
|
|
58
|
+
/** 通过这个 flag 主动表明这是发往对方的最后一个 message, 对方可以销毁 handler 了
|
|
59
|
+
并非强制,可以不说明,由双方的函数自己约定
|
|
60
|
+
*/
|
|
61
|
+
done?: boolean;
|
|
62
|
+
/** 通知对方这里产生的错误,本质上类似 data 也是一种数据,并不代表 rpc 的结束,后续可能继续有 rpc message 交换 */
|
|
63
|
+
error?: Error;
|
|
64
|
+
/** data 是一个数组, 作为:
|
|
58
65
|
- rpc 发起方调用 func 的参数,或者请求流 message 携带的数据
|
|
59
|
-
-
|
|
66
|
+
- 结果或者响应流的数据,传给请求发起方
|
|
67
|
+
|
|
68
|
+
里面是可序列化为 json 的 js 变量,或者是 Uint8Array
|
|
69
|
+
Uint8Array 的参数处理后被替换为 Uint8Array.byteLength, 并将下标记录在 bins 中
|
|
70
|
+
|
|
71
|
+
注意: 数组中如果有 undefined 值,传输到对面会变成 null 值
|
|
60
72
|
*/
|
|
61
|
-
|
|
62
|
-
/** bins:
|
|
73
|
+
data?: TData;
|
|
74
|
+
/** bins: data 中哪些下标对应的原始值是 Uint8Array 类型的,如: [0, 3] */
|
|
63
75
|
bins?: number[];
|
|
64
|
-
/** 被调方执行 func 产生的错误 */
|
|
65
|
-
error?: Error;
|
|
66
|
-
/** 如果请求或者响应是一个流,通过这个 flag 表明是最后一个 message, 并且可以销毁 handler 了 */
|
|
67
|
-
done?: boolean;
|
|
68
76
|
}
|
|
69
|
-
/** 通过创建
|
|
77
|
+
/** 通过创建 remote 对象对 websocket rpc 进行抽象
|
|
70
78
|
调用方使用 remote.call 进行调用
|
|
71
|
-
被调方在创建
|
|
72
|
-
*/
|
|
79
|
+
被调方在创建 remote 对象时传入 funcs 注册处理函数,并使用 remote.handle 方法处理 websocket message
|
|
80
|
+
未连接时自动连接,断开后自动重连 */
|
|
73
81
|
export declare class Remote {
|
|
74
82
|
url: string;
|
|
75
|
-
websocket
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
funcs: Record<string,
|
|
79
|
-
/**
|
|
80
|
-
handlers:
|
|
83
|
+
/** 主动发起 websocket 连接的客户端 (构造函数传 url) 有这个属性 */
|
|
84
|
+
websocket?: WebSocket;
|
|
85
|
+
/** 通过 rpc message.func 被调用的 rpc 函数 */
|
|
86
|
+
funcs: Record<string, MessageHandler>;
|
|
87
|
+
/** map<id, message handler>: 通过 rpc message.id 找到对应的 handler, unary rpc 接收方不需要设置 handlers, 发送方需要 */
|
|
88
|
+
handlers: Map<number, MessageHandler>;
|
|
81
89
|
print: boolean;
|
|
82
|
-
/** 在未连接时或连接断开后,调用 call 是否自动连接到 remote */
|
|
83
|
-
autoconnect: boolean;
|
|
84
90
|
pconnect: Promise<any>;
|
|
85
91
|
get connected(): boolean;
|
|
86
|
-
static parse<
|
|
87
|
-
static pack({ id, func,
|
|
88
|
-
constructor({ url, funcs, websocket
|
|
92
|
+
static parse<TData extends any[] = any[]>(array_buffer: ArrayBuffer): Message<TData>;
|
|
93
|
+
static pack({ id, func, data, done, error }: Message): Uint8Array;
|
|
94
|
+
constructor({ url, funcs, websocket }?: {
|
|
89
95
|
url?: string;
|
|
90
96
|
funcs?: Remote['funcs'];
|
|
91
97
|
websocket?: WebSocket;
|
|
92
|
-
autoconnect?: boolean;
|
|
93
98
|
});
|
|
99
|
+
/** 幂等,保证 websocket 已连接,否则抛出异常,不需要手动调用,在其它方法中已默认自动重连 */
|
|
94
100
|
connect(): Promise<void>;
|
|
95
101
|
disconnect(): void;
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
1. 被调用方接收 message 并开始处理
|
|
103
|
-
2. 调用方处理 message 响应
|
|
104
|
-
*/
|
|
102
|
+
/** 接收 websocket 连接的 remote 端必传 websocket 参数;发起端选传,如果传了必须等于 this.websocket
|
|
103
|
+
发送或连接出错时自动清理 message.id 对应的 handler */
|
|
104
|
+
send(message: Message, websocket?: WebSocket): Promise<void>;
|
|
105
|
+
/** 处理接收到的 websocket message 并解析, 根据 id dispatch 到对应的 handler 进行处理
|
|
106
|
+
如果 message.done == true 则清理 handler
|
|
107
|
+
如果 handler 返回了值,则包装为 message 发送 */
|
|
105
108
|
handle(event: {
|
|
106
109
|
data: ArrayBuffer;
|
|
107
110
|
}, websocket: WebSocket): Promise<void>;
|
|
111
|
+
/** 调用 remote 中的 func, 只适用于最简单的一元 rpc (请求, 响应) */
|
|
112
|
+
call<TReturn extends any[] = any[]>(func: string, args?: any[]): Promise<TReturn>;
|
|
108
113
|
}
|
package/net.browser.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types='tampermonkey' />
|
|
2
|
-
import { concat } from './utils.browser.js';
|
|
2
|
+
import { assert, concat, genid } from './utils.browser.js';
|
|
3
3
|
export async function request(url, { method, queries, headers, body, type = 'application/json', cors, by = window.GM_xmlhttpRequest ? 'GM_xmlhttpRequest' : 'fetch', raw, } = {}) {
|
|
4
4
|
url = new URL(url, location.href);
|
|
5
5
|
if (queries)
|
|
@@ -78,16 +78,22 @@ export async function connect_websocket(url, { protocols, on_open, on_close, on_
|
|
|
78
78
|
websocket.binaryType = 'arraybuffer';
|
|
79
79
|
return new Promise((resolve, reject) => {
|
|
80
80
|
websocket.addEventListener('open', async (event) => {
|
|
81
|
-
console.log(
|
|
81
|
+
console.log(new Date().toLocaleTimeString() + ': ' +
|
|
82
|
+
'websocket connected: ' +
|
|
83
|
+
(protocols ?
|
|
84
|
+
typeof protocols === 'string' ? `protocol: ${protocols}, url: ` : `protocol: [${protocols.join(', ')}], url: `
|
|
85
|
+
:
|
|
86
|
+
'') +
|
|
87
|
+
websocket.url);
|
|
82
88
|
await on_open?.(event, websocket);
|
|
83
89
|
resolve(websocket);
|
|
84
90
|
});
|
|
85
91
|
websocket.addEventListener('close', event => {
|
|
86
|
-
console.log(`${
|
|
92
|
+
console.log(`${new Date().toLocaleTimeString()}: websocket closed: url: ${websocket.url}, code: ${event.code}, reason: ${event.reason}`);
|
|
87
93
|
on_close?.(event, websocket);
|
|
88
94
|
});
|
|
89
95
|
websocket.addEventListener('error', event => {
|
|
90
|
-
const message = `${websocket.url}
|
|
96
|
+
const message = `${new Date().toLocaleTimeString()} websocket errored: ${websocket.url}`;
|
|
91
97
|
on_error?.(event, websocket);
|
|
92
98
|
reject(Object.assign(new Error(message), { event }));
|
|
93
99
|
});
|
|
@@ -96,21 +102,19 @@ export async function connect_websocket(url, { protocols, on_open, on_close, on_
|
|
|
96
102
|
});
|
|
97
103
|
});
|
|
98
104
|
}
|
|
99
|
-
/** 通过创建
|
|
105
|
+
/** 通过创建 remote 对象对 websocket rpc 进行抽象
|
|
100
106
|
调用方使用 remote.call 进行调用
|
|
101
|
-
被调方在创建
|
|
102
|
-
*/
|
|
107
|
+
被调方在创建 remote 对象时传入 funcs 注册处理函数,并使用 remote.handle 方法处理 websocket message
|
|
108
|
+
未连接时自动连接,断开后自动重连 */
|
|
103
109
|
export class Remote {
|
|
104
110
|
url;
|
|
111
|
+
/** 主动发起 websocket 连接的客户端 (构造函数传 url) 有这个属性 */
|
|
105
112
|
websocket;
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
handlers = [];
|
|
113
|
+
/** 通过 rpc message.func 被调用的 rpc 函数 */
|
|
114
|
+
funcs;
|
|
115
|
+
/** map<id, message handler>: 通过 rpc message.id 找到对应的 handler, unary rpc 接收方不需要设置 handlers, 发送方需要 */
|
|
116
|
+
handlers = new Map();
|
|
111
117
|
print = false;
|
|
112
|
-
/** 在未连接时或连接断开后,调用 call 是否自动连接到 remote */
|
|
113
|
-
autoconnect = true;
|
|
114
118
|
pconnect;
|
|
115
119
|
get connected() {
|
|
116
120
|
return this.websocket?.readyState === WebSocket.OPEN;
|
|
@@ -123,154 +127,151 @@ export class Remote {
|
|
|
123
127
|
let message = JSON.parse(decoder.decode(buf.subarray(4, offset)));
|
|
124
128
|
if (message.bins) {
|
|
125
129
|
const { bins } = message;
|
|
126
|
-
let {
|
|
130
|
+
let { data } = message;
|
|
127
131
|
for (const ibin of bins) {
|
|
128
|
-
const len_buf =
|
|
129
|
-
|
|
132
|
+
const len_buf = data[ibin];
|
|
133
|
+
data[ibin] = buf.subarray(offset, offset + len_buf);
|
|
130
134
|
offset += len_buf;
|
|
131
135
|
}
|
|
132
136
|
}
|
|
137
|
+
if (message.error)
|
|
138
|
+
message.error = Object.assign(new Error(), message.error);
|
|
133
139
|
return message;
|
|
134
140
|
}
|
|
135
|
-
static pack({ id, func,
|
|
136
|
-
let
|
|
141
|
+
static pack({ id, func, data = [], done, error }) {
|
|
142
|
+
let data_ = new Array(data.length);
|
|
137
143
|
let bins = [];
|
|
138
144
|
let bufs = [];
|
|
139
|
-
for (let i = 0; i <
|
|
140
|
-
const
|
|
141
|
-
if (
|
|
145
|
+
for (let i = 0; i < data.length; i++) {
|
|
146
|
+
const item = data[i];
|
|
147
|
+
if (item instanceof Uint8Array) {
|
|
142
148
|
bins.push(i);
|
|
143
|
-
bufs.push(
|
|
144
|
-
|
|
149
|
+
bufs.push(item);
|
|
150
|
+
data_[i] = item.length;
|
|
145
151
|
}
|
|
152
|
+
else
|
|
153
|
+
data_[i] = item;
|
|
146
154
|
}
|
|
147
155
|
const data_json = {
|
|
148
156
|
id,
|
|
149
157
|
...func ? { func } : {},
|
|
150
|
-
...ignore ? { ignore } : {},
|
|
151
|
-
..._async ? { async: _async } : {},
|
|
152
158
|
...done ? { done } : {},
|
|
153
159
|
...error ? { error } : {},
|
|
154
|
-
...
|
|
160
|
+
...data_.length ? { data: data_ } : {},
|
|
155
161
|
...bins.length ? { bins } : {},
|
|
156
162
|
};
|
|
157
163
|
const str_json = encoder.encode(JSON.stringify(data_json));
|
|
158
164
|
let dv = new DataView(new ArrayBuffer(4));
|
|
159
165
|
dv.setUint32(0, str_json.length, true);
|
|
160
|
-
return concat([
|
|
161
|
-
dv,
|
|
162
|
-
str_json,
|
|
163
|
-
...bufs
|
|
164
|
-
]);
|
|
166
|
+
return concat([dv, str_json, ...bufs]);
|
|
165
167
|
}
|
|
166
|
-
constructor({ url, funcs, websocket
|
|
168
|
+
constructor({ url, funcs = {}, websocket } = {}) {
|
|
167
169
|
this.url = url;
|
|
168
|
-
|
|
169
|
-
this.funcs = funcs;
|
|
170
|
+
this.funcs = funcs;
|
|
170
171
|
this.websocket = websocket;
|
|
171
|
-
if (typeof autoconnect !== 'undefined')
|
|
172
|
-
this.autoconnect = autoconnect;
|
|
173
172
|
}
|
|
173
|
+
/** 幂等,保证 websocket 已连接,否则抛出异常,不需要手动调用,在其它方法中已默认自动重连 */
|
|
174
174
|
async connect() {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
175
|
+
if (this.connected)
|
|
176
|
+
return;
|
|
177
|
+
const ptail = this.pconnect;
|
|
178
|
+
let resolve;
|
|
179
|
+
this.pconnect = new Promise((_resolve, _reject) => {
|
|
180
|
+
resolve = _resolve;
|
|
181
181
|
});
|
|
182
|
+
await ptail;
|
|
183
|
+
try {
|
|
184
|
+
if (!this.connected)
|
|
185
|
+
// 保存的 rpc 状态在 this.handlers, 与 websocket 无关,因此即使断开重连也不影响 rpc 的运行,即
|
|
186
|
+
// 底层连接断开后自动重连对上层应该是无感知的,除非再次连接时失败
|
|
187
|
+
this.websocket = await connect_websocket(this.url, { on_message: this.handle.bind(this) });
|
|
188
|
+
}
|
|
189
|
+
finally {
|
|
190
|
+
resolve();
|
|
191
|
+
}
|
|
182
192
|
}
|
|
183
193
|
disconnect() {
|
|
184
194
|
this.websocket?.close();
|
|
185
|
-
this.id = 0;
|
|
186
|
-
this.handlers = [];
|
|
187
195
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
如果为 unary rpc, 可以不传 handler, await call 之后可以得到响应 message 的 args
|
|
197
|
-
*/
|
|
198
|
-
async call(message, handler) {
|
|
199
|
-
if (!this.connected)
|
|
200
|
-
if (this.autoconnect) {
|
|
201
|
-
// 临界区:保证多个 call 并发时只连接一次
|
|
202
|
-
const ptail = this.pconnect;
|
|
203
|
-
let resolve;
|
|
204
|
-
this.pconnect = new Promise((_resolve, _reject) => {
|
|
205
|
-
resolve = _resolve;
|
|
206
|
-
});
|
|
207
|
-
try {
|
|
208
|
-
await ptail;
|
|
209
|
-
}
|
|
210
|
-
catch { }
|
|
211
|
-
// 临界区结束,只有一个 call 调用运行到这里,可以开始连接 WebSocket
|
|
212
|
-
if (!this.connected) {
|
|
213
|
-
if (this.websocket)
|
|
214
|
-
console.log(`${this.url} 已断开,尝试自动重连`);
|
|
215
|
-
else
|
|
216
|
-
console.log(`${this.url} 未连接,尝试自动连接`);
|
|
217
|
-
try {
|
|
218
|
-
await this.connect();
|
|
219
|
-
}
|
|
220
|
-
finally {
|
|
221
|
-
resolve();
|
|
222
|
-
}
|
|
223
|
-
}
|
|
196
|
+
/** 接收 websocket 连接的 remote 端必传 websocket 参数;发起端选传,如果传了必须等于 this.websocket
|
|
197
|
+
发送或连接出错时自动清理 message.id 对应的 handler */
|
|
198
|
+
async send(message, websocket) {
|
|
199
|
+
try {
|
|
200
|
+
if (this.url) {
|
|
201
|
+
assert(!websocket || websocket === this.websocket);
|
|
202
|
+
await this.connect();
|
|
203
|
+
websocket = this.websocket;
|
|
224
204
|
}
|
|
225
|
-
else
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
};
|
|
241
|
-
this.send(message);
|
|
242
|
-
this.id++;
|
|
243
|
-
});
|
|
205
|
+
else {
|
|
206
|
+
assert(websocket);
|
|
207
|
+
assert(!websocket.url, `The websocket received by the server should have no url attribute, websocket.url: ${websocket.url}`);
|
|
208
|
+
if (websocket.readyState !== WebSocket.OPEN)
|
|
209
|
+
throw new Error(`remote.send(): websocket client disconnected`);
|
|
210
|
+
}
|
|
211
|
+
if (!message.id)
|
|
212
|
+
message.id = genid();
|
|
213
|
+
websocket.send(Remote.pack(message));
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
if (message.id)
|
|
217
|
+
this.handlers.delete(message.id);
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
244
220
|
}
|
|
245
|
-
/** 处理接收到的
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
*/
|
|
221
|
+
/** 处理接收到的 websocket message 并解析, 根据 id dispatch 到对应的 handler 进行处理
|
|
222
|
+
如果 message.done == true 则清理 handler
|
|
223
|
+
如果 handler 返回了值,则包装为 message 发送 */
|
|
249
224
|
async handle(event, websocket) {
|
|
250
225
|
const message = Remote.parse(event.data);
|
|
251
|
-
const {
|
|
226
|
+
const { id, func, done } = message;
|
|
252
227
|
if (this.print)
|
|
253
228
|
console.log(message);
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
await handler(message, websocket);
|
|
260
|
-
}
|
|
261
|
-
catch (error) {
|
|
262
|
-
this.send({
|
|
263
|
-
id,
|
|
264
|
-
error,
|
|
265
|
-
done: true
|
|
266
|
-
}, websocket);
|
|
267
|
-
throw error;
|
|
268
|
-
}
|
|
269
|
-
else { // 作为发起方
|
|
270
|
-
this.handlers[id](message);
|
|
229
|
+
let handler;
|
|
230
|
+
if (func)
|
|
231
|
+
handler = this.funcs[func];
|
|
232
|
+
else {
|
|
233
|
+
handler = this.handlers.get(id);
|
|
271
234
|
if (done)
|
|
272
|
-
this.handlers
|
|
235
|
+
this.handlers.delete(id);
|
|
273
236
|
}
|
|
237
|
+
try {
|
|
238
|
+
if (handler) {
|
|
239
|
+
const data = await handler(message, websocket);
|
|
240
|
+
if (data)
|
|
241
|
+
await this.send({ id, data }, websocket);
|
|
242
|
+
}
|
|
243
|
+
else if (message.error)
|
|
244
|
+
throw message.error;
|
|
245
|
+
else
|
|
246
|
+
throw new Error(`rpc handler not found: ${func ? `func: ${func.quote()}` : `id: ${id}`}`);
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
// handle 出错并不意味着 rpc 一定会结束,可能 error 是运行中的正常数据,所以不能清理 handler
|
|
250
|
+
if (websocket.readyState === WebSocket.OPEN &&
|
|
251
|
+
!message.error // 防止无限循环往对方发送 error, 只有在对方无错误时才可以发送
|
|
252
|
+
)
|
|
253
|
+
try {
|
|
254
|
+
await this.send({ id, error, /* 不能设置 done 清理对面 handler, 理由同上 */ }, websocket);
|
|
255
|
+
}
|
|
256
|
+
catch { }
|
|
257
|
+
// 再往上层抛出错误没有意义了,上层调用栈是 websocket.on('message') 之类的
|
|
258
|
+
console.log(error);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
/** 调用 remote 中的 func, 只适用于最简单的一元 rpc (请求, 响应) */
|
|
262
|
+
async call(func, args) {
|
|
263
|
+
return new Promise(async (resolve, reject) => {
|
|
264
|
+
const id = genid();
|
|
265
|
+
this.handlers.set(id, (message) => {
|
|
266
|
+
const { error, data } = message;
|
|
267
|
+
if (error)
|
|
268
|
+
reject(error);
|
|
269
|
+
else
|
|
270
|
+
resolve(data);
|
|
271
|
+
this.handlers.delete(id);
|
|
272
|
+
});
|
|
273
|
+
await this.send({ id, func, data: args }); // 不需要 done: true, 因为对面的 remote.handlers 中不会有这个 id 的 handler
|
|
274
|
+
});
|
|
274
275
|
}
|
|
275
276
|
}
|
|
276
277
|
//# sourceMappingURL=net.browser.js.map
|
package/net.browser.js.map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gBACJ,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,IAAI,CAAA;SAC/B;IACL,CAAC;CACJ","sourcesContent":["/// <reference types='tampermonkey' />\n\nimport { concat } from './utils.browser.js'\n\nexport interface RequestOptions {\n method?: 'get' | 'post' | 'put' | 'head' | 'delete' | 'patch'\n \n queries?: Record<string, any>\n \n headers?: Record<string, string>\n \n body?: string | object | HTMLFormElement\n \n type?: 'application/json' | 'application/x-www-form-urlencoded' | 'multipart/form-data'\n \n cors?: boolean\n \n by?: 'fetch' | 'GM_xmlhttpRequest'\n}\n\nexport interface RequestRawOptions extends RequestOptions {\n raw: true\n}\n\n/**\n - url: 可以只有 pathname 部分\n - options:\n - type: `'application/json'` 请求的 content-type 头 (如果有 body)\n - by: `window.GM_xmlhttpRequest ? 'GM_xmlhttpRequest' : 'fetch'` 发起请求所使用的底层方法\n*/\nexport async function request (url: string | URL): Promise<string>\nexport async function request (url: string | URL, options: RequestRawOptions): Promise<Response>\nexport async function request (url: string | URL, options: RequestOptions): Promise<string>\nexport async function request (url: string | URL, {\n method,\n \n queries,\n \n headers,\n \n body,\n \n type = 'application/json',\n \n cors,\n \n by = window.GM_xmlhttpRequest ? 'GM_xmlhttpRequest' : 'fetch',\n \n raw,\n}: RequestOptions & { raw?: boolean } = { }) {\n url = new URL(url, location.href)\n \n if (queries)\n for (const key in queries) {\n let value = queries[key]\n if (typeof value === 'boolean')\n value = value ? '1' : '0'\n url.searchParams.append(key, value)\n }\n \n if (body && !method)\n method = 'post'\n \n if (type === 'application/json' && typeof body !== 'undefined' && typeof body !== 'string')\n body = JSON.stringify(body)\n \n url = url.toString()\n \n if (by === 'fetch') {\n const options: RequestInit = {\n ... method ? { method: method.toUpperCase() } : { },\n \n ... cors ? { mode: 'cors' } : { },\n \n credentials: 'include',\n \n headers: {\n ... body ? { 'content-type': type } : { },\n ... headers,\n },\n \n ... body ? { body: body as string } : { },\n }\n \n const response = await fetch(\n url,\n options\n )\n \n if (!response.ok)\n throw Object.assign(\n new Error(`StatusCodeError: ${response.status}`),\n { url, response, ...options }\n )\n \n if (raw)\n return response\n \n return response.text()\n }\n \n \n return new Promise((resolve, reject) => {\n GM_xmlhttpRequest({\n ... method ? { method: (method as any).toUpperCase() } : { },\n \n url: url as string,\n \n headers: {\n ... body ? { 'content-type': type } : { },\n ... headers,\n },\n \n ... body ? { data: body as string, } : { },\n \n onload (response) {\n if (!(200 <= response.status && response.status <= 299)) {\n reject(\n Object.assign(\n new Error(`StatusCodeError: ${response.status}`), \n { url, queries, method, headers, body, response }\n )\n )\n return\n }\n \n resolve(response.responseText)\n }\n })\n })\n}\n\n\n/** 发起 http 请求并将响应体作为 json 解析 */\nexport async function request_json <T = any> (url: string, options?: RequestOptions): Promise<T> {\n const resp = await request(url, options)\n if (!resp) return\n try {\n return JSON.parse(resp)\n } catch (error) {\n console.error(resp)\n throw error\n }\n}\n\n\n\nlet decoder = new TextDecoder()\n\nlet encoder = new TextEncoder()\n\n\n/** 连接 websocket url, 设置各种事件监听器 \n - url\n - options:\n - on_message: 根据 websocket frame 的 opcode 不同 (text frame 或 binary frame) event 中的 data 对应为 ArrayBuffer 或者 string\n https://datatracker.ietf.org/doc/html/rfc6455#section-5.2\n*/\nexport async function connect_websocket (\n url: string | URL,\n {\n protocols,\n on_open,\n on_close,\n on_error,\n on_message\n }: {\n protocols?: string | string[]\n on_open? (event: any, websocket: WebSocket): any\n on_close? (event: { code: number, reason: string }, websocket: WebSocket): any\n on_error? (event: any, websocket: WebSocket): any\n on_message (event: { data: ArrayBuffer | string }, websocket: WebSocket): any\n }\n) {\n let websocket = new WebSocket(url, protocols)\n \n // https://stackoverflow.com/questions/11821096/what-is-the-difference-between-an-arraybuffer-and-a-blob/39951543\n websocket.binaryType = 'arraybuffer'\n \n return new Promise<WebSocket>((resolve, reject) => {\n websocket.addEventListener('open', async event => {\n console.log(`${websocket.url} opened`)\n \n await on_open?.(event, websocket)\n \n resolve(websocket)\n })\n \n websocket.addEventListener('close', event => {\n console.log(`${websocket.url} closed with code = ${event.code}, reason = '${event.reason}'`)\n on_close?.(event, websocket)\n })\n \n websocket.addEventListener('error', event => {\n const message = `${websocket.url} errored`\n on_error?.(event, websocket)\n reject(\n Object.assign(\n new Error(message),\n { event }\n )\n )\n })\n \n websocket.addEventListener('message', event => {\n on_message(event as any, websocket)\n })\n })\n}\n\n\n/** 二进制消息格式 \n - json.length (小端序): 4 字节\n - json 数据\n - binary 数据\n*/\nexport interface Message <T extends any[] = any[]> {\n /** 本次 rpc 的 id */\n id?: number\n \n /** rpc 发起方指定被调用的 function name, 多个相同 id, func 的 message 组成一个请求流 */\n func?: string\n \n /** 等待执行,但不要序列化返回 func 的执行结果 (message 中无 args) */\n ignore?: boolean\n \n /** 不等待 func 执行,remote 收到后直接确认返回 (message 中 done = true) */\n async?: boolean\n \n /** 这个数组里面要么是对应的 JS 参数,要么是 Uint8Array 参数对应的 binary length \n args 可以是: \n - rpc 发起方调用 func 的参数,或者请求流 message 携带的数据\n - 作为结果或者响应流的 message 数据,传给请求发起方\n */\n args?: T\n \n /** bins: 哪几个 arg 是 Uint8Array 类型的,如: [0, 3] */\n bins?: number[]\n \n /** 被调方执行 func 产生的错误 */\n error?: Error\n \n /** 如果请求或者响应是一个流,通过这个 flag 表明是最后一个 message, 并且可以销毁 handler 了 */\n done?: boolean\n}\n\n/** 通过创建 Remote 对象对 WebSocket RPC 进行抽象 \n 调用方使用 remote.call 进行调用 \n 被调方在创建 Remote 对象时传入 funcs 注册处理函数,并使用 Remote.handle 方法处理 WebSocket message \n*/\nexport class Remote {\n url: string\n \n websocket: WebSocket\n \n id = 0\n \n /** 被调方的 message 处理器 */\n funcs: Record<\n string, \n (message: Message, websocket?: WebSocket) => void | Promise<void>\n > = { }\n \n /** 调用方发起的 rpc 对应响应的 message 处理器 */\n handlers: ((message: Message) => any)[] = [ ]\n \n print = false\n \n /** 在未连接时或连接断开后,调用 call 是否自动连接到 remote */\n autoconnect = true\n \n pconnect: Promise<any>\n \n \n get connected () {\n return this.websocket?.readyState === WebSocket.OPEN\n }\n \n \n static parse <T extends any[] = any[]> (array_buffer: ArrayBuffer) {\n const buf = new Uint8Array(array_buffer as ArrayBuffer)\n const dv = new DataView(array_buffer)\n \n const len_json = dv.getUint32(0, true)\n \n let offset = 4 + len_json\n \n let message: Message<T> = JSON.parse(\n decoder.decode(\n buf.subarray(4, offset)\n )\n )\n \n if (message.bins) {\n const { bins } = message\n let { args } = message\n \n for (const ibin of bins) {\n const len_buf = args[ibin]\n args[ibin] = buf.subarray(offset, offset + len_buf)\n offset += len_buf\n }\n }\n \n return message\n }\n \n \n static pack ({\n id,\n func,\n ignore,\n async: _async,\n done,\n error,\n args: _args = [ ],\n }: Message) {\n let args = [..._args]\n \n let bins: number[] = [ ]\n let bufs: Uint8Array[] = [ ]\n \n for (let i = 0; i < args.length; i++) {\n const arg = args[i]\n if (arg instanceof Uint8Array) {\n bins.push(i)\n bufs.push(arg)\n args[i] = arg.length\n }\n }\n \n const data_json = {\n id,\n ... func ? { func } : { },\n ... ignore ? { ignore } : { },\n ... _async ? { async: _async } : { },\n ... done ? { done } : { },\n ... error ? { error } : { },\n ... args.length ? { args } : { },\n ... bins.length ? { bins } : { },\n }\n \n const str_json = encoder.encode(\n JSON.stringify(data_json)\n )\n \n let dv = new DataView(\n new ArrayBuffer(4)\n )\n \n dv.setUint32(0, str_json.length, true)\n \n return concat([\n dv,\n str_json,\n ... bufs\n ])\n }\n \n \n constructor ({\n url,\n funcs,\n websocket,\n autoconnect\n }: {\n url?: string\n funcs?: Remote['funcs']\n websocket?: WebSocket\n autoconnect?: boolean\n } = { }) {\n this.url = url\n \n if (funcs)\n this.funcs = funcs\n \n this.websocket = websocket\n \n if (typeof autoconnect !== 'undefined')\n this.autoconnect = autoconnect\n }\n \n \n async connect () {\n this.websocket = await connect_websocket(this.url, {\n on_message: this.handle.bind(this),\n on_close: () => {\n this.id = 0\n this.handlers = [ ]\n },\n })\n }\n \n \n disconnect () {\n this.websocket?.close()\n this.id = 0\n this.handlers = [ ]\n }\n \n \n send (message: Message, websocket = this.websocket) {\n if (websocket?.readyState !== WebSocket.OPEN)\n throw new Error(`${websocket?.url || 'websocket'} 已断开,无法调用 remote.send`)\n \n if (!('id' in message))\n message.id = this.id\n \n websocket.send(\n Remote.pack(message)\n )\n }\n \n \n /** 调用 remote 中的 func, 中间消息及返回结果可由 handler 处理,处理 done message 之后的返回值作为 call 函数的返回值 \n 如果为 unary rpc, 可以不传 handler, await call 之后可以得到响应 message 的 args\n */\n async call <T extends any[] = any[]> (\n message: Message,\n handler?: (message: Message<T>) => any\n ) {\n if (!this.connected)\n if (this.autoconnect) {\n // 临界区:保证多个 call 并发时只连接一次\n const ptail = this.pconnect\n \n let resolve: () => void\n this.pconnect = new Promise<void>((_resolve, _reject) => {\n resolve = _resolve\n })\n \n try {\n await ptail\n } catch { }\n // 临界区结束,只有一个 call 调用运行到这里,可以开始连接 WebSocket\n \n if (!this.connected) {\n if (this.websocket)\n console.log(`${this.url} 已断开,尝试自动重连`)\n else\n console.log(`${this.url} 未连接,尝试自动连接`)\n \n try {\n await this.connect()\n } finally {\n resolve()\n }\n }\n } else\n throw new Error(`${this.url} 未连接或已断开,无法调用 remote.call`)\n \n return new Promise<T>((resolve, reject) => {\n this.handlers[this.id] = async (message: Message<T>) => {\n const { error, done } = message\n \n if (error) {\n reject(\n Object.assign(\n new Error(),\n error\n )\n )\n return\n }\n \n const result = handler ?\n await handler(message)\n :\n message.args\n \n if (done)\n resolve(result)\n }\n \n this.send(message)\n \n this.id++\n })\n }\n \n \n /** 处理接收到的 WebSocket message\n 1. 被调用方接收 message 并开始处理\n 2. 调用方处理 message 响应\n */\n async handle (event: { data: ArrayBuffer }, websocket: WebSocket) {\n const message = Remote.parse(event.data)\n \n const { func, id, done } = message\n \n if (this.print)\n console.log(message)\n \n if (func) // 作为被调方\n try {\n const handler = this.funcs[func]\n \n if (!handler)\n throw new Error(`找不到 rpc handler for '${func}'`)\n \n await handler(message, websocket)\n } catch (error) {\n this.send(\n {\n id,\n error,\n done: true\n },\n websocket\n )\n \n throw error\n }\n else { // 作为发起方\n this.handlers[id](message)\n \n if (done)\n this.handlers[id] = null\n }\n }\n}\n\n\n"]}
|
|
1
|
+
{"version":3,"file":"net.browser.js","sourceRoot":"","sources":["net.browser.ts"],"names":[],"mappings":"AAAA,sCAAsC;AAEtC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AA+B1D,MAAM,CAAC,KAAK,UAAU,OAAO,CAAE,GAAiB,EAAE,EAC9C,MAAM,EAEN,OAAO,EAEP,OAAO,EAEP,IAAI,EAEJ,IAAI,GAAG,kBAAkB,EAEzB,IAAI,EAEJ,EAAE,GAAG,MAAM,CAAC,iBAAiB,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,OAAO,EAE7D,GAAG,MACiC,EAAG;IACvC,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAA;IAEjC,IAAI,OAAO;QACP,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE;YACvB,IAAI,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAA;YACxB,IAAI,OAAO,KAAK,KAAK,SAAS;gBAC1B,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAA;YAC7B,GAAG,CAAC,YAAY,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;SACtC;IAEL,IAAI,IAAI,IAAI,CAAC,MAAM;QACf,MAAM,GAAG,MAAM,CAAA;IAEnB,IAAI,IAAI,KAAK,kBAAkB,IAAI,OAAO,IAAI,KAAK,WAAW,IAAI,OAAO,IAAI,KAAK,QAAQ;QACtF,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA;IAE/B,GAAG,GAAG,GAAG,CAAC,QAAQ,EAAE,CAAA;IAEp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,mDAAmD;YACnD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;SACrB;IACL,CAAC;IAGD,iDAAiD;IACjD,KAAK,CAAC,IAAI,CAAkC,IAAY,EAAE,IAAY;QAClE,OAAO,IAAI,OAAO,CAAU,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE;YAClD,MAAM,EAAE,GAAG,KAAK,EAAE,CAAA;YAElB,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,OAAyB,EAAE,EAAE;gBAChD,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,OAAO,CAAA;gBAC/B,IAAI,KAAK;oBACL,MAAM,CAAC,KAAK,CAAC,CAAA;;oBAEb,OAAO,CAAC,IAAI,CAAC,CAAA;gBACjB,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;YAC5B,CAAC,CAAC,CAAA;YAEF,MAAM,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAA,CAAE,4DAA4D;QAC3G,CAAC,CAAC,CAAA;IACN,CAAC;CACJ","sourcesContent":["/// <reference types='tampermonkey' />\n\nimport { assert, concat, genid } from './utils.browser.js'\n\nexport interface RequestOptions {\n method?: 'get' | 'post' | 'put' | 'head' | 'delete' | 'patch'\n \n queries?: Record<string, any>\n \n headers?: Record<string, string>\n \n body?: string | object | HTMLFormElement\n \n type?: 'application/json' | 'application/x-www-form-urlencoded' | 'multipart/form-data'\n \n cors?: boolean\n \n by?: 'fetch' | 'GM_xmlhttpRequest'\n}\n\nexport interface RequestRawOptions extends RequestOptions {\n raw: true\n}\n\n/**\n - url: 可以只有 pathname 部分\n - options:\n - type: `'application/json'` 请求的 content-type 头 (如果有 body)\n - by: `window.GM_xmlhttpRequest ? 'GM_xmlhttpRequest' : 'fetch'` 发起请求所使用的底层方法\n*/\nexport async function request (url: string | URL): Promise<string>\nexport async function request (url: string | URL, options: RequestRawOptions): Promise<Response>\nexport async function request (url: string | URL, options: RequestOptions): Promise<string>\nexport async function request (url: string | URL, {\n method,\n \n queries,\n \n headers,\n \n body,\n \n type = 'application/json',\n \n cors,\n \n by = window.GM_xmlhttpRequest ? 'GM_xmlhttpRequest' : 'fetch',\n \n raw,\n}: RequestOptions & { raw?: boolean } = { }) {\n url = new URL(url, location.href)\n \n if (queries)\n for (const key in queries) {\n let value = queries[key]\n if (typeof value === 'boolean')\n value = value ? '1' : '0'\n url.searchParams.append(key, value)\n }\n \n if (body && !method)\n method = 'post'\n \n if (type === 'application/json' && typeof body !== 'undefined' && typeof body !== 'string')\n body = JSON.stringify(body)\n \n url = url.toString()\n \n if (by === 'fetch') {\n const options: RequestInit = {\n ... method ? { method: method.toUpperCase() } : { },\n \n ... cors ? { mode: 'cors' } : { },\n \n credentials: 'include',\n \n headers: {\n ... body ? { 'content-type': type } : { },\n ... headers,\n },\n \n ... body ? { body: body as string } : { },\n }\n \n const response = await fetch(\n url,\n options\n )\n \n if (!response.ok)\n throw Object.assign(\n new Error(`StatusCodeError: ${response.status}`),\n { url, response, ...options }\n )\n \n if (raw)\n return response\n \n return response.text()\n }\n \n \n return new Promise((resolve, reject) => {\n GM_xmlhttpRequest({\n ... method ? { method: (method as any).toUpperCase() } : { },\n \n url: url as string,\n \n headers: {\n ... body ? { 'content-type': type } : { },\n ... headers,\n },\n \n ... body ? { data: body as string, } : { },\n \n onload (response) {\n if (!(200 <= response.status && response.status <= 299)) {\n reject(\n Object.assign(\n new Error(`StatusCodeError: ${response.status}`), \n { url, queries, method, headers, body, response }\n )\n )\n return\n }\n \n resolve(response.responseText)\n }\n })\n })\n}\n\n\n/** 发起 http 请求并将响应体作为 json 解析 */\nexport async function request_json <T = any> (url: string, options?: RequestOptions): Promise<T> {\n const resp = await request(url, options)\n if (!resp) return\n try {\n return JSON.parse(resp)\n } catch (error) {\n console.error(resp)\n throw error\n }\n}\n\n\n\nlet decoder = new TextDecoder()\n\nlet encoder = new TextEncoder()\n\n\n/** 连接 websocket url, 设置各种事件监听器 \n - url\n - options:\n - on_message: 根据 websocket frame 的 opcode 不同 (text frame 或 binary frame) event 中的 data 对应为 ArrayBuffer 或者 string\n https://datatracker.ietf.org/doc/html/rfc6455#section-5.2\n*/\nexport async function connect_websocket (\n url: string | URL,\n {\n protocols,\n on_open,\n on_close,\n on_error,\n on_message\n }: {\n protocols?: string | string[]\n on_open? (event: any, websocket: WebSocket): any\n on_close? (event: { code: number, reason: string }, websocket: WebSocket): any\n on_error? (event: any, websocket: WebSocket): any\n on_message (event: { data: ArrayBuffer | string }, websocket: WebSocket): any\n }\n) {\n let websocket = new WebSocket(url, protocols)\n \n // https://stackoverflow.com/questions/11821096/what-is-the-difference-between-an-arraybuffer-and-a-blob/39951543\n websocket.binaryType = 'arraybuffer'\n \n return new Promise<WebSocket>((resolve, reject) => {\n websocket.addEventListener('open', async event => {\n console.log(\n new Date().toLocaleTimeString() + ': ' +\n 'websocket connected: ' +\n (protocols ? \n typeof protocols === 'string' ? `protocol: ${protocols}, url: ` : `protocol: [${protocols.join(', ')}], url: `\n :\n '') +\n websocket.url\n )\n \n await on_open?.(event, websocket)\n \n resolve(websocket)\n })\n \n websocket.addEventListener('close', event => {\n console.log(`${new Date().toLocaleTimeString()}: websocket closed: url: ${websocket.url}, code: ${event.code}, reason: ${event.reason}`)\n on_close?.(event, websocket)\n })\n \n websocket.addEventListener('error', event => {\n const message = `${new Date().toLocaleTimeString()} websocket errored: ${websocket.url}`\n on_error?.(event, websocket)\n reject(\n Object.assign(\n new Error(message),\n { event }\n )\n )\n })\n \n websocket.addEventListener('message', event => {\n on_message(event as any, websocket)\n })\n })\n}\n\n\n/** 接收到消息后的处理函数 \n 返回值可以是:\n - 数组: 会自动被封装为 { id: 相同, data: 返回值, done: true } 这样的消息并调用 websocket.send 将其发送\n - void: 什么都不做\n - 以上的 promise */\nexport type MessageHandler = (message: Message, websocket?: WebSocket) => void | any[] | Promise<void | any[]>\n\n\n/** 二进制消息格式 \n - json.length (小端序): 4 字节\n - json 数据\n - binary 数据\n*/\nexport interface Message <TData extends any[] = any[]> {\n /** rpc id: 在 rpc 系统中认为是唯一的。用来在单个 websocket 连接上复用多个 rpc 请求。多个相同 id 的 message 组成一个请求流 */\n id?: number\n \n /** 只在 rpc 发起时指定被调用的 function name,发起时 rpc 时必传 */\n func?: string\n \n /** 通过这个 flag 主动表明这是发往对方的最后一个 message, 对方可以销毁 handler 了 \n 并非强制,可以不说明,由双方的函数自己约定\n */\n done?: boolean\n \n /** 通知对方这里产生的错误,本质上类似 data 也是一种数据,并不代表 rpc 的结束,后续可能继续有 rpc message 交换 */\n error?: Error\n \n /** data 是一个数组, 作为:\n - rpc 发起方调用 func 的参数,或者请求流 message 携带的数据\n - 结果或者响应流的数据,传给请求发起方\n \n 里面是可序列化为 json 的 js 变量,或者是 Uint8Array \n Uint8Array 的参数处理后被替换为 Uint8Array.byteLength, 并将下标记录在 bins 中\n \n 注意: 数组中如果有 undefined 值,传输到对面会变成 null 值\n */\n data?: TData\n \n /** bins: data 中哪些下标对应的原始值是 Uint8Array 类型的,如: [0, 3] */\n bins?: number[]\n}\n\n/** 通过创建 remote 对象对 websocket rpc 进行抽象 \n 调用方使用 remote.call 进行调用 \n 被调方在创建 remote 对象时传入 funcs 注册处理函数,并使用 remote.handle 方法处理 websocket message \n 未连接时自动连接,断开后自动重连 */\nexport class Remote {\n url: string\n \n /** 主动发起 websocket 连接的客户端 (构造函数传 url) 有这个属性 */\n websocket?: WebSocket\n \n /** 通过 rpc message.func 被调用的 rpc 函数 */\n funcs: Record<string, MessageHandler>\n \n /** map<id, message handler>: 通过 rpc message.id 找到对应的 handler, unary rpc 接收方不需要设置 handlers, 发送方需要 */\n handlers = new Map<number, MessageHandler>()\n \n \n print = false\n \n pconnect: Promise<any>\n \n \n get connected () {\n return this.websocket?.readyState === WebSocket.OPEN\n }\n \n \n static parse <TData extends any[] = any[]> (array_buffer: ArrayBuffer) {\n const buf = new Uint8Array(array_buffer as ArrayBuffer)\n const dv = new DataView(array_buffer)\n \n const len_json = dv.getUint32(0, true)\n \n let offset = 4 + len_json\n \n let message: Message<TData> = JSON.parse(decoder.decode(buf.subarray(4, offset)))\n \n if (message.bins) {\n const { bins } = message\n let { data } = message\n \n for (const ibin of bins) {\n const len_buf = data[ibin]\n data[ibin] = buf.subarray(offset, offset + len_buf)\n offset += len_buf\n }\n }\n \n if (message.error)\n message.error = Object.assign(new Error(), message.error)\n \n return message\n }\n \n \n static pack ({ id, func, data = [ ], done, error }: Message) {\n let data_ = new Array(data.length)\n let bins: number[] = [ ]\n let bufs: Uint8Array[] = [ ]\n \n for (let i = 0; i < data.length; i++) {\n const item = data[i]\n if (item instanceof Uint8Array) {\n bins.push(i)\n bufs.push(item)\n data_[i] = item.length\n } else\n data_[i] = item\n }\n \n const data_json = {\n id,\n ... func ? { func } : { },\n ... done ? { done } : { },\n ... error ? { error } : { },\n ... data_.length ? { data: data_ } : { },\n ... bins.length ? { bins } : { },\n }\n \n const str_json = encoder.encode(JSON.stringify(data_json))\n \n let dv = new DataView(new ArrayBuffer(4))\n \n dv.setUint32(0, str_json.length, true)\n \n return concat([dv, str_json, ... bufs])\n }\n \n \n constructor ({\n url, funcs = { }, websocket\n }: {\n url?: string, funcs?: Remote['funcs'], websocket?: WebSocket\n } = { }) {\n this.url = url\n this.funcs = funcs\n this.websocket = websocket\n }\n \n \n /** 幂等,保证 websocket 已连接,否则抛出异常,不需要手动调用,在其它方法中已默认自动重连 */\n async connect () {\n if (this.connected)\n return\n \n const ptail = this.pconnect\n \n let resolve: () => void\n this.pconnect = new Promise<void>((_resolve, _reject) => {\n resolve = _resolve\n })\n \n await ptail\n \n try {\n if (!this.connected)\n // 保存的 rpc 状态在 this.handlers, 与 websocket 无关,因此即使断开重连也不影响 rpc 的运行,即\n // 底层连接断开后自动重连对上层应该是无感知的,除非再次连接时失败\n this.websocket = await connect_websocket(this.url, { on_message: this.handle.bind(this) })\n } finally {\n resolve()\n }\n }\n \n \n disconnect () {\n this.websocket?.close()\n }\n \n \n /** 接收 websocket 连接的 remote 端必传 websocket 参数;发起端选传,如果传了必须等于 this.websocket \n 发送或连接出错时自动清理 message.id 对应的 handler */\n async send (message: Message, websocket?: WebSocket) {\n try {\n if (this.url) {\n assert(!websocket || websocket === this.websocket)\n await this.connect()\n websocket = this.websocket\n } else {\n assert(websocket)\n assert(!websocket.url, `The websocket received by the server should have no url attribute, websocket.url: ${websocket.url}`)\n if (websocket.readyState !== WebSocket.OPEN)\n throw new Error(`remote.send(): websocket client disconnected`)\n }\n \n if (!message.id)\n message.id = genid()\n \n websocket.send(Remote.pack(message))\n } catch (error) {\n if (message.id)\n this.handlers.delete(message.id)\n throw error\n }\n }\n \n \n /** 处理接收到的 websocket message 并解析, 根据 id dispatch 到对应的 handler 进行处理 \n 如果 message.done == true 则清理 handler \n 如果 handler 返回了值,则包装为 message 发送 */\n async handle (event: { data: ArrayBuffer }, websocket: WebSocket) {\n const message = Remote.parse(event.data)\n \n const { id, func, done } = message\n \n if (this.print)\n console.log(message)\n \n let handler: MessageHandler\n \n if (func)\n handler = this.funcs[func]\n else {\n handler = this.handlers.get(id)\n if (done)\n this.handlers.delete(id)\n }\n \n try {\n if (handler) {\n const data = await handler(message, websocket)\n if (data)\n await this.send({ id, data }, websocket)\n } else if (message.error)\n throw message.error\n else\n throw new Error(`rpc handler not found: ${func ? `func: ${func.quote()}` : `id: ${id}`}`)\n } catch (error) {\n // handle 出错并不意味着 rpc 一定会结束,可能 error 是运行中的正常数据,所以不能清理 handler\n \n if (\n websocket.readyState === WebSocket.OPEN &&\n !message.error // 防止无限循环往对方发送 error, 只有在对方无错误时才可以发送\n )\n try { await this.send({ id, error, /* 不能设置 done 清理对面 handler, 理由同上 */ }, websocket) } catch { }\n \n // 再往上层抛出错误没有意义了,上层调用栈是 websocket.on('message') 之类的\n console.log(error)\n }\n }\n \n \n /** 调用 remote 中的 func, 只适用于最简单的一元 rpc (请求, 响应) */\n async call <TReturn extends any[] = any[]> (func: string, args?: any[]) {\n return new Promise<TReturn>(async (resolve, reject) => {\n const id = genid()\n \n this.handlers.set(id, (message: Message<TReturn>) => {\n const { error, data } = message\n if (error)\n reject(error)\n else\n resolve(data)\n this.handlers.delete(id)\n })\n \n await this.send({ id, func, data: args }) // 不需要 done: true, 因为对面的 remote.handlers 中不会有这个 id 的 handler\n })\n }\n}\n\n"]}
|