hypha-rpc 0.1.0-post5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4688 @@
1
+ (function webpackUniversalModuleDefinition(root, factory) {
2
+ if(typeof exports === 'object' && typeof module === 'object')
3
+ module.exports = factory();
4
+ else if(typeof define === 'function' && define.amd)
5
+ define("hyphaWebsocketClient", [], factory);
6
+ else if(typeof exports === 'object')
7
+ exports["hyphaWebsocketClient"] = factory();
8
+ else
9
+ root["hyphaWebsocketClient"] = factory();
10
+ })(this, () => {
11
+ return /******/ (() => { // webpackBootstrap
12
+ /******/ "use strict";
13
+ /******/ var __webpack_modules__ = ({
14
+
15
+ /***/ "./src/rpc.js":
16
+ /*!********************!*\
17
+ !*** ./src/rpc.js ***!
18
+ \********************/
19
+ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
20
+
21
+ __webpack_require__.r(__webpack_exports__);
22
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
23
+ /* harmony export */ API_VERSION: () => (/* binding */ API_VERSION),
24
+ /* harmony export */ RPC: () => (/* binding */ RPC)
25
+ /* harmony export */ });
26
+ /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ "./src/utils.js");
27
+ /* harmony import */ var _msgpack_msgpack__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @msgpack/msgpack */ "./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs");
28
+ /* harmony import */ var _msgpack_msgpack__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @msgpack/msgpack */ "./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs");
29
+ /**
30
+ * Contains the RPC object used both by the application
31
+ * site, and by each plugin
32
+ */
33
+
34
+
35
+
36
+
37
+ const API_VERSION = "0.3.0";
38
+ const CHUNK_SIZE = 1024 * 500;
39
+
40
+ const ArrayBufferView = Object.getPrototypeOf(
41
+ Object.getPrototypeOf(new Uint8Array()),
42
+ ).constructor;
43
+
44
+ function _appendBuffer(buffer1, buffer2) {
45
+ const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
46
+ tmp.set(new Uint8Array(buffer1), 0);
47
+ tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
48
+ return tmp.buffer;
49
+ }
50
+
51
+ function indexObject(obj, is) {
52
+ if (!is) throw new Error("undefined index");
53
+ if (typeof is === "string") return indexObject(obj, is.split("."));
54
+ else if (is.length === 0) return obj;
55
+ else return indexObject(obj[is[0]], is.slice(1));
56
+ }
57
+ function getFunctionInfo(func) {
58
+ const funcString = func.toString();
59
+
60
+ // Extract function name
61
+ const nameMatch = funcString.match(/function\s*(\w*)/);
62
+ const name = (nameMatch && nameMatch[1]) || "";
63
+
64
+ // Extract function parameters, excluding comments
65
+ const paramsMatch = funcString.match(/\(([^)]*)\)/);
66
+ let params = "";
67
+ if (paramsMatch) {
68
+ params = paramsMatch[1]
69
+ .split(",")
70
+ .map((p) =>
71
+ p
72
+ .replace(/\/\*.*?\*\//g, "") // Remove block comments
73
+ .replace(/\/\/.*$/g, ""),
74
+ ) // Remove line comments
75
+ .filter((p) => p.trim().length > 0) // Remove empty strings after removing comments
76
+ .map((p) => p.trim()) // Trim remaining whitespace
77
+ .join(", ");
78
+ }
79
+
80
+ // Extract function docstring (block comment)
81
+ let docMatch = funcString.match(/\)\s*\{\s*\/\*([\s\S]*?)\*\//);
82
+ const docstringBlock = (docMatch && docMatch[1].trim()) || "";
83
+
84
+ // Extract function docstring (line comment)
85
+ docMatch = funcString.match(/\)\s*\{\s*(\/\/[\s\S]*?)\n\s*[^\s\/]/);
86
+ const docstringLine =
87
+ (docMatch &&
88
+ docMatch[1]
89
+ .split("\n")
90
+ .map((s) => s.replace(/^\/\/\s*/, "").trim())
91
+ .join("\n")) ||
92
+ "";
93
+
94
+ const docstring = docstringBlock || docstringLine;
95
+ return (
96
+ name &&
97
+ params.length > 0 && {
98
+ name: name,
99
+ sig: params,
100
+ doc: docstring,
101
+ }
102
+ );
103
+ }
104
+
105
+ function concatArrayBuffers(buffers) {
106
+ var buffersLengths = buffers.map(function (b) {
107
+ return b.byteLength;
108
+ }),
109
+ totalBufferlength = buffersLengths.reduce(function (p, c) {
110
+ return p + c;
111
+ }, 0),
112
+ unit8Arr = new Uint8Array(totalBufferlength);
113
+ buffersLengths.reduce(function (p, c, i) {
114
+ unit8Arr.set(new Uint8Array(buffers[i]), p);
115
+ return p + c;
116
+ }, 0);
117
+ return unit8Arr.buffer;
118
+ }
119
+
120
+ class Timer {
121
+ constructor(timeout, callback, args, label) {
122
+ this._timeout = timeout;
123
+ this._callback = callback;
124
+ this._args = args;
125
+ this._label = label || "timer";
126
+ this._task = null;
127
+ this.started = false;
128
+ }
129
+
130
+ start() {
131
+ if (this.started) {
132
+ this.reset();
133
+ } else {
134
+ this._task = setTimeout(() => {
135
+ this._callback.apply(this, this._args);
136
+ }, this._timeout * 1000);
137
+ this.started = true;
138
+ }
139
+ }
140
+
141
+ clear() {
142
+ if (this._task) {
143
+ clearTimeout(this._task);
144
+ this._task = null;
145
+ this.started = false;
146
+ } else {
147
+ console.warn(`Clearing a timer (${this._label}) which is not started`);
148
+ }
149
+ }
150
+
151
+ reset() {
152
+ if (this._task) {
153
+ clearTimeout(this._task);
154
+ }
155
+ this._task = setTimeout(() => {
156
+ this._callback.apply(this, this._args);
157
+ }, this._timeout * 1000);
158
+ this.started = true;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * RPC object represents a single site in the
164
+ * communication protocol between the application and the plugin
165
+ *
166
+ * @param {Object} connection a special object allowing to send
167
+ * and receive messages from the opposite site (basically it
168
+ * should only provide send() and onMessage() methods)
169
+ */
170
+ class RPC extends _utils_js__WEBPACK_IMPORTED_MODULE_0__.MessageEmitter {
171
+ constructor(
172
+ connection,
173
+ {
174
+ client_id = null,
175
+ manager_id = null,
176
+ default_context = null,
177
+ name = null,
178
+ codecs = null,
179
+ method_timeout = null,
180
+ max_message_buffer_size = 0,
181
+ debug = false,
182
+ workspace = null,
183
+ silent = false,
184
+ app_id = null,
185
+ },
186
+ ) {
187
+ super(debug);
188
+ this._codecs = codecs || {};
189
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(client_id && typeof client_id === "string");
190
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(client_id, "client_id is required");
191
+ this._client_id = client_id;
192
+ this._name = name;
193
+ this._app_id = app_id || "*";
194
+ this._local_workspace = workspace;
195
+ this.manager_id = manager_id;
196
+ this._silent = silent;
197
+ this.default_context = default_context || {};
198
+ this._method_annotations = new WeakMap();
199
+ this._max_message_buffer_size = max_message_buffer_size;
200
+ this._chunk_store = {};
201
+ this._method_timeout = method_timeout || 30;
202
+
203
+ // make sure there is an execute function
204
+ this._services = {};
205
+ this._object_store = {
206
+ services: this._services,
207
+ };
208
+
209
+ if (connection) {
210
+ this.add_service({
211
+ id: "built-in",
212
+ type: "built-in",
213
+ name: `Built-in services for ${this._local_workspace}/${this._client_id}`,
214
+ config: { require_context: true, visibility: "public" },
215
+ ping: this._ping.bind(this),
216
+ get_service: this.get_local_service.bind(this),
217
+ register_service: this.register_service.bind(this),
218
+ message_cache: {
219
+ create: this._create_message.bind(this),
220
+ append: this._append_message.bind(this),
221
+ process: this._process_message.bind(this),
222
+ remove: this._remove_message.bind(this),
223
+ },
224
+ });
225
+ this.on("method", this._handle_method.bind(this));
226
+
227
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(connection.emit_message && connection.on_message);
228
+ this._emit_message = connection.emit_message.bind(connection);
229
+ connection.on_message(this._on_message.bind(this));
230
+ this._connection = connection;
231
+ const updateServices = async () => {
232
+ if (!this._silent && this.manager_id) {
233
+ console.log("Connection established, reporting services...");
234
+ for (let service of Object.values(this._services)) {
235
+ const serviceInfo = this._extract_service_info(service);
236
+ await this.emit({
237
+ type: "service-added",
238
+ to: "*/" + this.manager_id,
239
+ service: serviceInfo,
240
+ });
241
+ }
242
+ }
243
+ }
244
+ connection.on_connect(updateServices);
245
+ updateServices();
246
+ } else {
247
+ this._emit_message = function () {
248
+ console.log("No connection to emit message");
249
+ };
250
+ }
251
+ }
252
+
253
+ register_codec(config) {
254
+ if (!config["name"] || (!config["encoder"] && !config["decoder"])) {
255
+ throw new Error(
256
+ "Invalid codec format, please make sure you provide a name, type, encoder and decoder.",
257
+ );
258
+ } else {
259
+ if (config.type) {
260
+ for (let k of Object.keys(this._codecs)) {
261
+ if (this._codecs[k].type === config.type || k === config.name) {
262
+ delete this._codecs[k];
263
+ console.warn("Remove duplicated codec: " + k);
264
+ }
265
+ }
266
+ }
267
+ this._codecs[config["name"]] = config;
268
+ }
269
+ }
270
+
271
+ async _ping(msg, context) {
272
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(msg == "ping");
273
+ return "pong";
274
+ }
275
+
276
+ async ping(client_id, timeout) {
277
+ let method = this._generate_remote_method({
278
+ _rtarget: client_id,
279
+ _rmethod: "services.built-in.ping",
280
+ _rpromise: true,
281
+ _rdoc: "Ping a remote client",
282
+ _rsig: "ping(msg)",
283
+ });
284
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)((await method("ping", timeout)) == "pong");
285
+ }
286
+
287
+ _create_message(key, heartbeat, overwrite, context) {
288
+ if (heartbeat) {
289
+ if (!this._object_store[key]) {
290
+ throw new Error(`session does not exist anymore: ${key}`);
291
+ }
292
+ this._object_store[key]["timer"].reset();
293
+ }
294
+
295
+ if (!this._object_store["message_cache"]) {
296
+ this._object_store["message_cache"] = {};
297
+ }
298
+ if (!overwrite && this._object_store["message_cache"][key]) {
299
+ throw new Error(
300
+ `Message with the same key (${key}) already exists in the cache store, please use overwrite=true or remove it first.`,
301
+ );
302
+ }
303
+
304
+ this._object_store["message_cache"][key] = [];
305
+ }
306
+
307
+ _append_message(key, data, heartbeat, context) {
308
+ if (heartbeat) {
309
+ if (!this._object_store[key]) {
310
+ throw new Error(`session does not exist anymore: ${key}`);
311
+ }
312
+ this._object_store[key]["timer"].reset();
313
+ }
314
+ const cache = this._object_store["message_cache"];
315
+ if (!cache[key]) {
316
+ throw new Error(`Message with key ${key} does not exists.`);
317
+ }
318
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(data instanceof ArrayBufferView);
319
+ cache[key].push(data);
320
+ }
321
+
322
+ _remove_message(key, context) {
323
+ const cache = this._object_store["message_cache"];
324
+ if (!cache[key]) {
325
+ throw new Error(`Message with key ${key} does not exists.`);
326
+ }
327
+ delete cache[key];
328
+ }
329
+
330
+ _process_message(key, heartbeat, context) {
331
+ if (heartbeat) {
332
+ if (!this._object_store[key]) {
333
+ throw new Error(`session does not exist anymore: ${key}`);
334
+ }
335
+ this._object_store[key]["timer"].reset();
336
+ }
337
+ const cache = this._object_store["message_cache"];
338
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(!!context, "Context is required");
339
+ if (!cache[key]) {
340
+ throw new Error(`Message with key ${key} does not exists.`);
341
+ }
342
+ cache[key] = concatArrayBuffers(cache[key]);
343
+ console.debug(`Processing message ${key} (bytes=${cache[key].byteLength})`);
344
+ let unpacker = (0,_msgpack_msgpack__WEBPACK_IMPORTED_MODULE_1__.decodeMulti)(cache[key]);
345
+ const { done, value } = unpacker.next();
346
+ const main = value;
347
+ // Make sure the fields are from trusted source
348
+ Object.assign(main, {
349
+ from: context.from,
350
+ to: context.to,
351
+ user: context.user,
352
+ });
353
+ main["ctx"] = JSON.parse(JSON.stringify(main));
354
+ Object.assign(main["ctx"], this.default_context);
355
+ if (!done) {
356
+ let extra = unpacker.next();
357
+ Object.assign(main, extra.value);
358
+ }
359
+ this._fire(main["type"], main);
360
+ console.debug(
361
+ this._client_id,
362
+ `Processed message ${key} (bytes=${cache[key].byteLength})`,
363
+ );
364
+ delete cache[key];
365
+ }
366
+
367
+ _on_message(message) {
368
+ try {
369
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(message instanceof ArrayBuffer);
370
+ let unpacker = (0,_msgpack_msgpack__WEBPACK_IMPORTED_MODULE_1__.decodeMulti)(message);
371
+ const { done, value } = unpacker.next();
372
+ const main = value;
373
+ // Add trusted context to the method call
374
+ main["ctx"] = JSON.parse(JSON.stringify(main));
375
+ Object.assign(main["ctx"], this.default_context);
376
+ if (!done) {
377
+ let extra = unpacker.next();
378
+ Object.assign(main, extra.value);
379
+ }
380
+ this._fire(main["type"], main);
381
+ } catch (error) {
382
+ console.error("Failed to process message", error);
383
+ }
384
+ }
385
+
386
+ reset() {
387
+ this._event_handlers = {};
388
+ this._services = {};
389
+ }
390
+
391
+ async disconnect() {
392
+ this._fire("disconnect");
393
+ await this._connection.disconnect();
394
+ }
395
+
396
+ async get_manager_service(timeout) {
397
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(this.manager_id, "Manager id is not set");
398
+ const svc = await this.get_remote_service(
399
+ `*/${this.manager_id}:default`,
400
+ timeout,
401
+ );
402
+ return svc;
403
+ }
404
+
405
+ get_all_local_services() {
406
+ return this._services;
407
+ }
408
+ get_local_service(service_id, context) {
409
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(service_id);
410
+ const [ws, client_id] = context["to"].split("/");
411
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
412
+ client_id === this._client_id,
413
+ "Services can only be accessed locally",
414
+ );
415
+
416
+ const service = this._services[service_id];
417
+ if (!service) {
418
+ throw new Error("Service not found: " + service_id);
419
+ }
420
+
421
+ service.config["workspace"] = ws;
422
+ // allow access for the same workspace
423
+ if (service.config.visibility == "public") {
424
+ return service;
425
+ }
426
+
427
+ // allow access for the same workspace
428
+ if (context["ws"] === ws) {
429
+ return service;
430
+ }
431
+
432
+ throw new Error(
433
+ `Permission denied for protected service: ${service_id}, workspace mismatch: ${ws} != ${context["ws"]}`,
434
+ );
435
+ }
436
+ async get_remote_service(service_uri, timeout) {
437
+ timeout = timeout === undefined ? this._method_timeout : timeout;
438
+ if (!service_uri && this.manager_id) {
439
+ service_uri = "*/" + this.manager_id;
440
+ } else if (!service_uri.includes(":")) {
441
+ service_uri = this._client_id + ":" + service_uri;
442
+ }
443
+ const provider = service_uri.split(":")[0];
444
+ let service_id = service_uri.split(":")[1];
445
+ if (service_id.includes("@")) {
446
+ service_id = service_id.split("@")[0];
447
+ const app_id = service_uri.split("@")[1];
448
+ if (this._app_id)
449
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
450
+ app_id === this._app_id,
451
+ `Invalid app id: ${app_id} != ${this._app_id}`,
452
+ );
453
+ }
454
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(provider, `Invalid service uri: ${service_uri}`);
455
+
456
+ try {
457
+ const method = this._generate_remote_method({
458
+ _rtarget: provider,
459
+ _rmethod: "services.built-in.get_service",
460
+ _rpromise: true,
461
+ _rdoc: "Get a remote service",
462
+ _rsig: "get_service(service_id)",
463
+ });
464
+ const svc = await (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.waitFor)(
465
+ method(service_id),
466
+ timeout,
467
+ "Timeout Error: Failed to get remote service: " + service_uri,
468
+ );
469
+ svc.id = `${provider}:${service_id}`;
470
+ return svc;
471
+ } catch (e) {
472
+ console.error("Failed to get remote service: " + service_uri, e);
473
+ throw e;
474
+ }
475
+ }
476
+ _annotate_service_methods(
477
+ aObject,
478
+ object_id,
479
+ require_context,
480
+ run_in_executor,
481
+ visibility,
482
+ ) {
483
+ if (typeof aObject === "function") {
484
+ // mark the method as a remote method that requires context
485
+ let method_name = object_id.split(".")[1];
486
+ this._method_annotations.set(aObject, {
487
+ require_context: Array.isArray(require_context)
488
+ ? require_context.includes(method_name)
489
+ : !!require_context,
490
+ run_in_executor: run_in_executor,
491
+ method_id: "services." + object_id,
492
+ visibility: visibility,
493
+ });
494
+ } else if (aObject instanceof Array || aObject instanceof Object) {
495
+ for (let key of Object.keys(aObject)) {
496
+ let val = aObject[key];
497
+ if (typeof val === "function" && val.__rpc_object__) {
498
+ let client_id = val.__rpc_object__._rtarget;
499
+ if (client_id.includes("/")) {
500
+ client_id = client_id.split("/")[1];
501
+ }
502
+ if (this._client_id === client_id) {
503
+ if (aObject instanceof Array) {
504
+ aObject = aObject.slice();
505
+ }
506
+ // recover local method
507
+ aObject[key] = indexObject(
508
+ this._object_store,
509
+ val.__rpc_object__._rmethod,
510
+ );
511
+ val = aObject[key]; // make sure it's annotated later
512
+ } else {
513
+ throw new Error(
514
+ `Local method not found: ${val.__rpc_object__._rmethod}, client id mismatch ${this._client_id} != ${client_id}`,
515
+ );
516
+ }
517
+ }
518
+ this._annotate_service_methods(
519
+ val,
520
+ object_id + "." + key,
521
+ require_context,
522
+ run_in_executor,
523
+ visibility,
524
+ );
525
+ }
526
+ }
527
+ }
528
+ add_service(api, overwrite) {
529
+ if (!api || Array.isArray(api)) throw new Error("Invalid service object");
530
+ if (api.constructor === Object) {
531
+ api = Object.assign({}, api);
532
+ } else {
533
+ const normApi = {};
534
+ const props = Object.getOwnPropertyNames(api).concat(
535
+ Object.getOwnPropertyNames(Object.getPrototypeOf(api)),
536
+ );
537
+ for (let k of props) {
538
+ if (k !== "constructor") {
539
+ if (typeof api[k] === "function") normApi[k] = api[k].bind(api);
540
+ else normApi[k] = api[k];
541
+ }
542
+ }
543
+ // For class instance, we need set a default id
544
+ api.id = api.id || "default";
545
+ api = normApi;
546
+ }
547
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
548
+ api.id && typeof api.id === "string",
549
+ `Service id not found: ${api}`,
550
+ );
551
+ if (!api.name) {
552
+ api.name = api.id;
553
+ }
554
+ if (!api.config) {
555
+ api.config = {};
556
+ }
557
+ if (!api.type) {
558
+ api.type = "generic";
559
+ }
560
+ // require_context only applies to the top-level functions
561
+ let require_context = false,
562
+ run_in_executor = false;
563
+ if (api.config.require_context)
564
+ require_context = api.config.require_context;
565
+ if (api.config.run_in_executor) run_in_executor = true;
566
+ const visibility = api.config.visibility || "protected";
567
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(["protected", "public"].includes(visibility));
568
+ this._annotate_service_methods(
569
+ api,
570
+ api["id"],
571
+ require_context,
572
+ run_in_executor,
573
+ visibility,
574
+ );
575
+
576
+ if (this._services[api.id]) {
577
+ if (overwrite) {
578
+ delete this._services[api.id];
579
+ } else {
580
+ throw new Error(
581
+ `Service already exists: ${api.id}, please specify a different id (not ${api.id}) or overwrite=true`,
582
+ );
583
+ }
584
+ }
585
+ this._services[api.id] = api;
586
+ return api;
587
+ }
588
+
589
+ _extract_service_info(service) {
590
+ return {
591
+ id: `${this._client_id}:${service["id"]}`,
592
+ type: service["type"],
593
+ name: service["name"],
594
+ description: service["description"] || "",
595
+ config: service["config"],
596
+ app_id: this._app_id,
597
+ };
598
+ }
599
+
600
+ async register_service(api, overwrite, notify, context) {
601
+ if (notify === undefined) notify = true;
602
+ if (context) {
603
+ // If this function is called from remote, we need to make sure
604
+ const [workspace, client_id] = context["to"].split("/");
605
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(client_id === this._client_id);
606
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
607
+ workspace === context["ws"],
608
+ "Services can only be registered from the same workspace",
609
+ );
610
+ }
611
+ const service = this.add_service(api, overwrite);
612
+ const serviceInfo = this._extract_service_info(service);
613
+ if (notify) {
614
+ if (this.manager_id) {
615
+ this.emit({
616
+ type: "service-added",
617
+ to: "*/" + this.manager_id,
618
+ service: serviceInfo,
619
+ });
620
+ } else {
621
+ this.emit({ type: "service-added", to: "*", service: serviceInfo });
622
+ }
623
+ }
624
+ return serviceInfo;
625
+ }
626
+ async unregister_service(service, notify) {
627
+ if (service instanceof Object) {
628
+ service = service.id;
629
+ }
630
+ if (!this._services[service]) {
631
+ throw new Error(`Service not found: ${service}`);
632
+ }
633
+ const api = this._services[service];
634
+ delete this._services[service];
635
+ if (notify) {
636
+ const serviceInfo = this._extract_service_info(api);
637
+ if (this.manager_id) {
638
+ this.emit({
639
+ type: "service-removed",
640
+ to: "*/" + this.manager_id,
641
+ service: serviceInfo,
642
+ });
643
+ } else {
644
+ this.emit({ type: "service-removed", to: "*", service: serviceInfo });
645
+ }
646
+ }
647
+ }
648
+
649
+ _ndarray(typedArray, shape, dtype) {
650
+ const _dtype = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.typedArrayToDtype)(typedArray);
651
+ if (dtype && dtype !== _dtype) {
652
+ throw (
653
+ "dtype doesn't match the type of the array: " + _dtype + " != " + dtype
654
+ );
655
+ }
656
+ shape = shape || [typedArray.length];
657
+ return {
658
+ _rtype: "ndarray",
659
+ _rvalue: typedArray.buffer,
660
+ _rshape: shape,
661
+ _rdtype: _dtype,
662
+ };
663
+ }
664
+
665
+ _encode_callback(
666
+ name,
667
+ callback,
668
+ session_id,
669
+ clear_after_called,
670
+ timer,
671
+ local_workspace,
672
+ ) {
673
+ let method_id = `${session_id}.${name}`;
674
+ let encoded = {
675
+ _rtype: "method",
676
+ _rtarget: local_workspace
677
+ ? `${local_workspace}/${this._client_id}`
678
+ : this._client_id,
679
+ _rmethod: method_id,
680
+ _rpromise: false,
681
+ };
682
+
683
+ const self = this;
684
+ let wrapped_callback = function () {
685
+ try {
686
+ callback.apply(null, Array.prototype.slice.call(arguments));
687
+ } catch (error) {
688
+ console.error("Error in callback:", method_id, error);
689
+ } finally {
690
+ if (clear_after_called && self._object_store[session_id]) {
691
+ // console.log("Deleting session", session_id, "from", self._client_id);
692
+ delete self._object_store[session_id];
693
+ }
694
+ if (timer && timer.started) {
695
+ timer.clear();
696
+ }
697
+ }
698
+ };
699
+
700
+ return [encoded, wrapped_callback];
701
+ }
702
+
703
+ async _encode_promise(
704
+ resolve,
705
+ reject,
706
+ session_id,
707
+ clear_after_called,
708
+ timer,
709
+ local_workspace,
710
+ ) {
711
+ let store = this._get_session_store(session_id, true);
712
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
713
+ store,
714
+ `Failed to create session store ${session_id} due to invalid parent`,
715
+ );
716
+ let encoded = {};
717
+
718
+ if (timer && reject && this._method_timeout) {
719
+ encoded.heartbeat = await this._encode(
720
+ timer.reset.bind(timer),
721
+ session_id,
722
+ local_workspace,
723
+ );
724
+ encoded.interval = this._method_timeout / 2;
725
+ store.timer = timer;
726
+ } else {
727
+ timer = null;
728
+ }
729
+
730
+ [encoded.resolve, store.resolve] = this._encode_callback(
731
+ "resolve",
732
+ resolve,
733
+ session_id,
734
+ clear_after_called,
735
+ timer,
736
+ local_workspace,
737
+ );
738
+ [encoded.reject, store.reject] = this._encode_callback(
739
+ "reject",
740
+ reject,
741
+ session_id,
742
+ clear_after_called,
743
+ timer,
744
+ local_workspace,
745
+ );
746
+ return encoded;
747
+ }
748
+
749
+ async _send_chunks(data, target_id, session_id) {
750
+ let remote_services = await this.get_remote_service(
751
+ `${target_id}:built-in`,
752
+ );
753
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
754
+ remote_services.message_cache,
755
+ "Remote client does not support message caching for long message.",
756
+ );
757
+ let message_cache = remote_services.message_cache;
758
+ let message_id = session_id || (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.randId)();
759
+ await message_cache.create(message_id, !!session_id);
760
+ let total_size = data.length;
761
+ let chunk_num = Math.ceil(total_size / CHUNK_SIZE);
762
+ for (let idx = 0; idx < chunk_num; idx++) {
763
+ let start_byte = idx * CHUNK_SIZE;
764
+ await message_cache.append(
765
+ message_id,
766
+ data.slice(start_byte, start_byte + CHUNK_SIZE),
767
+ !!session_id,
768
+ );
769
+ console.log(
770
+ `Sending chunk ${idx + 1}/${chunk_num} (${total_size} bytes)`,
771
+ );
772
+ }
773
+ // console.log(`All chunks sent (${chunk_num})`);
774
+ await message_cache.process(message_id, !!session_id);
775
+ }
776
+
777
+ emit(main_message, extra_data) {
778
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
779
+ typeof main_message === "object" && main_message.type,
780
+ "Invalid message, must be an object with a type field.",
781
+ );
782
+ let message_package = (0,_msgpack_msgpack__WEBPACK_IMPORTED_MODULE_2__.encode)(main_message);
783
+ if (extra_data) {
784
+ const extra = (0,_msgpack_msgpack__WEBPACK_IMPORTED_MODULE_2__.encode)(extra_data);
785
+ message_package = new Uint8Array([...message_package, ...extra]);
786
+ }
787
+ const total_size = message_package.length;
788
+ if (total_size <= CHUNK_SIZE + 1024) {
789
+ return this._emit_message(message_package);
790
+ } else {
791
+ throw new Error("Message is too large to send in one go.");
792
+ }
793
+ }
794
+
795
+ _generate_remote_method(
796
+ encoded_method,
797
+ remote_parent,
798
+ local_parent,
799
+ remote_workspace,
800
+ local_workspace,
801
+ ) {
802
+ let target_id = encoded_method._rtarget;
803
+ if (remote_workspace && !target_id.includes("/")) {
804
+ if (remote_workspace !== target_id) {
805
+ target_id = remote_workspace + "/" + target_id;
806
+ }
807
+ // Fix the target id to be an absolute id
808
+ encoded_method._rtarget = target_id;
809
+ }
810
+ let method_id = encoded_method._rmethod;
811
+ let with_promise = encoded_method._rpromise;
812
+ const self = this;
813
+
814
+ function remote_method() {
815
+ return new Promise(async (resolve, reject) => {
816
+ let local_session_id = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.randId)();
817
+ if (local_parent) {
818
+ // Store the children session under the parent
819
+ local_session_id = local_parent + "." + local_session_id;
820
+ }
821
+ let store = self._get_session_store(local_session_id, true);
822
+ if (!store) {
823
+ reject(
824
+ new Error(
825
+ `Runtime Error: Failed to get session store ${local_session_id}`,
826
+ ),
827
+ );
828
+ return;
829
+ }
830
+ store["target_id"] = target_id;
831
+ const args = await self._encode(
832
+ Array.prototype.slice.call(arguments),
833
+ local_session_id,
834
+ local_workspace,
835
+ );
836
+ const argLength = args.length;
837
+ // if the last argument is an object, mark it as kwargs
838
+ const withKwargs =
839
+ argLength > 0 &&
840
+ typeof args[argLength - 1] === "object" &&
841
+ args[argLength - 1] !== null &&
842
+ args[argLength - 1]._rkwargs;
843
+ if (withKwargs) delete args[argLength - 1]._rkwargs;
844
+
845
+ let from_client;
846
+ if (!self._local_workspace) {
847
+ from_client = self._client_id;
848
+ } else {
849
+ from_client = self._local_workspace + "/" + self._client_id;
850
+ }
851
+
852
+ let main_message = {
853
+ type: "method",
854
+ from: from_client,
855
+ to: target_id,
856
+ method: method_id,
857
+ };
858
+ let extra_data = {};
859
+ if (args) {
860
+ extra_data["args"] = args;
861
+ }
862
+ if (withKwargs) {
863
+ extra_data["with_kwargs"] = withKwargs;
864
+ }
865
+
866
+ // console.log(
867
+ // `Calling remote method ${target_id}:${method_id}, session: ${local_session_id}`
868
+ // );
869
+ if (remote_parent) {
870
+ // Set the parent session
871
+ // Note: It's a session id for the remote, not the current client
872
+ main_message["parent"] = remote_parent;
873
+ }
874
+
875
+ let timer = null;
876
+ if (with_promise) {
877
+ // Only pass the current session id to the remote
878
+ // if we want to received the result
879
+ // I.e. the session id won't be passed for promises themselves
880
+ main_message["session"] = local_session_id;
881
+ let method_name = `${target_id}:${method_id}`;
882
+ timer = new Timer(
883
+ self._method_timeout,
884
+ reject,
885
+ [`Method call time out: ${method_name}`],
886
+ method_name,
887
+ );
888
+ // By default, hypha will clear the session after the method is called
889
+ // However, if the args contains _rintf === true, we will not clear the session
890
+ let clear_after_called = true;
891
+ for (let arg of args) {
892
+ if (typeof arg === "object" && arg._rintf === true) {
893
+ clear_after_called = false;
894
+ break;
895
+ }
896
+ }
897
+ extra_data["promise"] = await self._encode_promise(
898
+ resolve,
899
+ reject,
900
+ local_session_id,
901
+ clear_after_called,
902
+ timer,
903
+ local_workspace,
904
+ );
905
+ }
906
+ // The message consists of two segments, the main message and extra data
907
+ let message_package = (0,_msgpack_msgpack__WEBPACK_IMPORTED_MODULE_2__.encode)(main_message);
908
+ if (extra_data) {
909
+ const extra = (0,_msgpack_msgpack__WEBPACK_IMPORTED_MODULE_2__.encode)(extra_data);
910
+ message_package = new Uint8Array([...message_package, ...extra]);
911
+ }
912
+ const total_size = message_package.length;
913
+ if (total_size <= CHUNK_SIZE + 1024) {
914
+ self._emit_message(message_package).then(function () {
915
+ if (timer) {
916
+ // console.log(`Start watchdog timer.`);
917
+ // Only start the timer after we send the message successfully
918
+ timer.start();
919
+ }
920
+ });
921
+ } else {
922
+ // send chunk by chunk
923
+ self
924
+ ._send_chunks(message_package, target_id, remote_parent)
925
+ .then(function () {
926
+ if (timer) {
927
+ // console.log(`Start watchdog timer.`);
928
+ // Only start the timer after we send the message successfully
929
+ timer.start();
930
+ }
931
+ })
932
+ .catch(function (err) {
933
+ console.error("Failed to send message", err);
934
+ reject(err);
935
+ });
936
+ }
937
+ });
938
+ }
939
+
940
+ // Generate debugging information for the method
941
+ remote_method.__rpc_object__ = encoded_method;
942
+ const parts = method_id.split(".");
943
+ remote_method.__name__ = parts[parts.length - 1];
944
+ remote_method.__doc__ = encoded_method._rdoc;
945
+ remote_method.__sig__ = encoded_method._rsig;
946
+ return remote_method;
947
+ }
948
+
949
+ get_client_info() {
950
+ const services = [];
951
+ for (let service of Object.values(this._services)) {
952
+ services.push(this._extract_service_info(service));
953
+ }
954
+
955
+ return {
956
+ id: this._client_id,
957
+ services: services,
958
+ };
959
+ }
960
+
961
+ async _handle_method(data) {
962
+ let reject = null;
963
+ let heartbeat_task = null;
964
+ try {
965
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(data.method && data.ctx && data.from && data.ws);
966
+ const method_name = data.from + ":" + data.method;
967
+ const remote_workspace = data.from.split("/")[0];
968
+ // Make sure the target id is an absolute id
969
+ data["to"] = data["to"].includes("/")
970
+ ? data["to"]
971
+ : remote_workspace + "/" + data["to"];
972
+ data["ctx"]["to"] = data["to"];
973
+ let local_workspace;
974
+ if (!this._local_workspace) {
975
+ local_workspace = data["to"].split("/")[0];
976
+ } else {
977
+ if (this._local_workspace && this._local_workspace !== "*") {
978
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
979
+ data["to"].split("/")[0] === this._local_workspace,
980
+ "Workspace mismatch: " +
981
+ data["to"].split("/")[0] +
982
+ " != " +
983
+ this._local_workspace,
984
+ );
985
+ }
986
+ local_workspace = this._local_workspace;
987
+ }
988
+ const local_parent = data.parent;
989
+
990
+ let resolve, reject;
991
+ if (data.promise) {
992
+ // Decode the promise with the remote session id
993
+ // Such that the session id will be passed to the remote as a parent session id
994
+ const promise = await this._decode(
995
+ data.promise,
996
+ data.session,
997
+ local_parent,
998
+ remote_workspace,
999
+ local_workspace,
1000
+ );
1001
+ resolve = promise.resolve;
1002
+ reject = promise.reject;
1003
+ if (promise.heartbeat && promise.interval) {
1004
+ async function heartbeat() {
1005
+ try {
1006
+ console.log("Reset heartbeat timer: " + data.method);
1007
+ await promise.heartbeat();
1008
+ } catch (err) {
1009
+ console.error(err);
1010
+ }
1011
+ }
1012
+ heartbeat_task = setInterval(heartbeat, promise.interval * 1000);
1013
+ }
1014
+ }
1015
+
1016
+ let method;
1017
+
1018
+ try {
1019
+ method = indexObject(this._object_store, data["method"]);
1020
+ } catch (e) {
1021
+ console.debug("Failed to find method", method_name, this._client_id, e);
1022
+ throw new Error(`Method not found: ${method_name} at ${this._client_id}`);
1023
+ }
1024
+
1025
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
1026
+ method && typeof method === "function",
1027
+ "Invalid method: " + method_name,
1028
+ );
1029
+
1030
+ // Check permission
1031
+ if (this._method_annotations.has(method)) {
1032
+ // For services, it should not be protected
1033
+ if (this._method_annotations.get(method).visibility === "protected") {
1034
+ if (local_workspace !== remote_workspace) {
1035
+ throw new Error(
1036
+ "Permission denied for protected method " +
1037
+ method_name +
1038
+ ", workspace mismatch: " +
1039
+ local_workspace +
1040
+ " != " +
1041
+ remote_workspace,
1042
+ );
1043
+ }
1044
+ }
1045
+ } else {
1046
+ // For sessions, the target_id should match exactly
1047
+ let session_target_id =
1048
+ this._object_store[data.method.split(".")[0]].target_id;
1049
+ if (
1050
+ local_workspace === remote_workspace &&
1051
+ session_target_id &&
1052
+ session_target_id.indexOf("/") === -1
1053
+ ) {
1054
+ session_target_id = local_workspace + "/" + session_target_id;
1055
+ }
1056
+ if (session_target_id !== data.from) {
1057
+ throw new Error(
1058
+ "Access denied for method call (" +
1059
+ method_name +
1060
+ ") from " +
1061
+ data.from +
1062
+ " to target " +
1063
+ session_target_id,
1064
+ );
1065
+ }
1066
+ }
1067
+
1068
+ // Make sure the parent session is still open
1069
+ if (local_parent) {
1070
+ // The parent session should be a session that generate the current method call
1071
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
1072
+ this._get_session_store(local_parent, true) !== null,
1073
+ "Parent session was closed: " + local_parent,
1074
+ );
1075
+ }
1076
+ let args;
1077
+ if (data.args) {
1078
+ args = await this._decode(
1079
+ data.args,
1080
+ data.session,
1081
+ null,
1082
+ remote_workspace,
1083
+ null,
1084
+ );
1085
+ } else {
1086
+ args = [];
1087
+ }
1088
+ if (
1089
+ this._method_annotations.has(method) &&
1090
+ this._method_annotations.get(method).require_context
1091
+ ) {
1092
+ args.push(data.ctx);
1093
+ }
1094
+ // console.log("Executing method: " + method_name);
1095
+ if (data.promise) {
1096
+ const result = method.apply(null, args);
1097
+ if (result instanceof Promise) {
1098
+ result
1099
+ .then((result) => {
1100
+ resolve(result);
1101
+ clearInterval(heartbeat_task);
1102
+ })
1103
+ .catch((err) => {
1104
+ reject(err);
1105
+ clearInterval(heartbeat_task);
1106
+ });
1107
+ } else {
1108
+ resolve(result);
1109
+ clearInterval(heartbeat_task);
1110
+ }
1111
+ } else {
1112
+ method.apply(null, args);
1113
+ clearInterval(heartbeat_task);
1114
+ }
1115
+ } catch (err) {
1116
+ if (reject) {
1117
+ reject(err);
1118
+ console.debug("Error during calling method: ", err);
1119
+ } else {
1120
+ console.error("Error during calling method: ", err);
1121
+ }
1122
+ // make sure we clear the heartbeat timer
1123
+ clearInterval(heartbeat_task);
1124
+ }
1125
+ }
1126
+
1127
+ encode(aObject, session_id) {
1128
+ return this._encode(aObject, session_id);
1129
+ }
1130
+
1131
+ _get_session_store(session_id, create) {
1132
+ let store = this._object_store;
1133
+ const levels = session_id.split(".");
1134
+ if (create) {
1135
+ const last_index = levels.length - 1;
1136
+ for (let level of levels.slice(0, last_index)) {
1137
+ if (!store[level]) {
1138
+ return null;
1139
+ }
1140
+ store = store[level];
1141
+ }
1142
+ // Create the last level
1143
+ if (!store[levels[last_index]]) {
1144
+ store[levels[last_index]] = {};
1145
+ }
1146
+ return store[levels[last_index]];
1147
+ } else {
1148
+ for (let level of levels) {
1149
+ if (!store[level]) {
1150
+ return null;
1151
+ }
1152
+ store = store[level];
1153
+ }
1154
+ return store;
1155
+ }
1156
+ }
1157
+
1158
+ /**
1159
+ * Prepares the provided set of remote method arguments for
1160
+ * sending to the remote site, replaces all the callbacks with
1161
+ * identifiers
1162
+ *
1163
+ * @param {Array} args to wrap
1164
+ *
1165
+ * @returns {Array} wrapped arguments
1166
+ */
1167
+ async _encode(aObject, session_id, local_workspace) {
1168
+ const aType = typeof aObject;
1169
+ if (
1170
+ aType === "number" ||
1171
+ aType === "string" ||
1172
+ aType === "boolean" ||
1173
+ aObject === null ||
1174
+ aObject === undefined ||
1175
+ aObject instanceof Uint8Array
1176
+ ) {
1177
+ return aObject;
1178
+ }
1179
+ if (aObject instanceof ArrayBuffer) {
1180
+ return {
1181
+ _rtype: "memoryview",
1182
+ _rvalue: new Uint8Array(aObject),
1183
+ };
1184
+ }
1185
+ // Reuse the remote object
1186
+ if (aObject.__rpc_object__) {
1187
+ return aObject.__rpc_object__;
1188
+ }
1189
+
1190
+ let bObject;
1191
+
1192
+ // skip if already encoded
1193
+ if (aObject.constructor instanceof Object && aObject._rtype) {
1194
+ // make sure the interface functions are encoded
1195
+ const temp = aObject._rtype;
1196
+ delete aObject._rtype;
1197
+ bObject = await this._encode(aObject, session_id, local_workspace);
1198
+ bObject._rtype = temp;
1199
+ return bObject;
1200
+ }
1201
+
1202
+ if (typeof aObject === "function") {
1203
+ if (this._method_annotations.has(aObject)) {
1204
+ let annotation = this._method_annotations.get(aObject);
1205
+ bObject = {
1206
+ _rtype: "method",
1207
+ _rtarget: this._client_id,
1208
+ _rmethod: annotation.method_id,
1209
+ _rpromise: true,
1210
+ };
1211
+ } else {
1212
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(typeof session_id === "string");
1213
+ let object_id;
1214
+ if (aObject.__name__) {
1215
+ object_id = `${(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.randId)()}-${aObject.__name__}`;
1216
+ } else {
1217
+ object_id = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.randId)();
1218
+ }
1219
+ bObject = {
1220
+ _rtype: "method",
1221
+ _rtarget: this._client_id,
1222
+ _rmethod: `${session_id}.${object_id}`,
1223
+ _rpromise: true,
1224
+ };
1225
+ let store = this._get_session_store(session_id, true);
1226
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
1227
+ store !== null,
1228
+ `Failed to create session store ${session_id} due to invalid parent`,
1229
+ );
1230
+ store[object_id] = aObject;
1231
+ }
1232
+ bObject._rdoc = aObject.__doc__;
1233
+ bObject._rsig = aObject.__sig__;
1234
+ if (!bObject._rdoc || !bObject._rsig) {
1235
+ try {
1236
+ const funcInfo = getFunctionInfo(aObject);
1237
+ if (funcInfo && !bObject._rdoc) {
1238
+ bObject._rdoc = `${funcInfo.doc}`;
1239
+ }
1240
+ if (funcInfo && !bObject._rsig) {
1241
+ bObject._rsig = `${funcInfo.name}(${funcInfo.sig})`;
1242
+ }
1243
+ } catch (e) {
1244
+ console.error("Failed to extract function docstring:", aObject);
1245
+ }
1246
+ }
1247
+
1248
+ return bObject;
1249
+ }
1250
+ const isarray = Array.isArray(aObject);
1251
+
1252
+ for (let tp of Object.keys(this._codecs)) {
1253
+ const codec = this._codecs[tp];
1254
+ if (codec.encoder && aObject instanceof codec.type) {
1255
+ // TODO: what if multiple encoders found
1256
+ let encodedObj = await Promise.resolve(codec.encoder(aObject));
1257
+ if (encodedObj && !encodedObj._rtype) encodedObj._rtype = codec.name;
1258
+ // encode the functions in the interface object
1259
+ if (typeof encodedObj === "object") {
1260
+ const temp = encodedObj._rtype;
1261
+ delete encodedObj._rtype;
1262
+ encodedObj = await this._encode(
1263
+ encodedObj,
1264
+ session_id,
1265
+ local_workspace,
1266
+ );
1267
+ encodedObj._rtype = temp;
1268
+ }
1269
+ bObject = encodedObj;
1270
+ return bObject;
1271
+ }
1272
+ }
1273
+
1274
+ if (
1275
+ /*global tf*/
1276
+ typeof tf !== "undefined" &&
1277
+ tf.Tensor &&
1278
+ aObject instanceof tf.Tensor
1279
+ ) {
1280
+ const v_buffer = aObject.dataSync();
1281
+ bObject = {
1282
+ _rtype: "ndarray",
1283
+ _rvalue: new Uint8Array(v_buffer.buffer),
1284
+ _rshape: aObject.shape,
1285
+ _rdtype: aObject.dtype,
1286
+ };
1287
+ } else if (
1288
+ /*global nj*/
1289
+ typeof nj !== "undefined" &&
1290
+ nj.NdArray &&
1291
+ aObject instanceof nj.NdArray
1292
+ ) {
1293
+ const dtype = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.typedArrayToDtype)(aObject.selection.data);
1294
+ bObject = {
1295
+ _rtype: "ndarray",
1296
+ _rvalue: new Uint8Array(aObject.selection.data.buffer),
1297
+ _rshape: aObject.shape,
1298
+ _rdtype: dtype,
1299
+ };
1300
+ } else if (aObject instanceof Error) {
1301
+ console.error(aObject);
1302
+ bObject = {
1303
+ _rtype: "error",
1304
+ _rvalue: aObject.toString(),
1305
+ _rtrace: aObject.stack,
1306
+ };
1307
+ }
1308
+ // send objects supported by structure clone algorithm
1309
+ // https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
1310
+ else if (
1311
+ aObject !== Object(aObject) ||
1312
+ aObject instanceof Boolean ||
1313
+ aObject instanceof String ||
1314
+ aObject instanceof Date ||
1315
+ aObject instanceof RegExp ||
1316
+ aObject instanceof ImageData ||
1317
+ (typeof FileList !== "undefined" && aObject instanceof FileList) ||
1318
+ (typeof FileSystemDirectoryHandle !== "undefined" &&
1319
+ aObject instanceof FileSystemDirectoryHandle) ||
1320
+ (typeof FileSystemFileHandle !== "undefined" &&
1321
+ aObject instanceof FileSystemFileHandle) ||
1322
+ (typeof FileSystemHandle !== "undefined" &&
1323
+ aObject instanceof FileSystemHandle) ||
1324
+ (typeof FileSystemWritableFileStream !== "undefined" &&
1325
+ aObject instanceof FileSystemWritableFileStream)
1326
+ ) {
1327
+ bObject = aObject;
1328
+ // TODO: avoid object such as DynamicPlugin instance.
1329
+ } else if (aObject instanceof Blob) {
1330
+ let _current_pos = 0;
1331
+ async function read(length) {
1332
+ let blob;
1333
+ if (length) {
1334
+ blob = aObject.slice(_current_pos, _current_pos + length);
1335
+ } else {
1336
+ blob = aObject.slice(_current_pos);
1337
+ }
1338
+ const ret = new Uint8Array(await blob.arrayBuffer());
1339
+ _current_pos = _current_pos + ret.byteLength;
1340
+ return ret;
1341
+ }
1342
+ function seek(pos) {
1343
+ _current_pos = pos;
1344
+ }
1345
+ bObject = {
1346
+ _rtype: "iostream",
1347
+ _rnative: "js:blob",
1348
+ type: aObject.type,
1349
+ name: aObject.name,
1350
+ size: aObject.size,
1351
+ path: aObject._path || aObject.webkitRelativePath,
1352
+ read: await this._encode(read, session_id, local_workspace),
1353
+ seek: await this._encode(seek, session_id, local_workspace),
1354
+ };
1355
+ } else if (aObject instanceof ArrayBufferView) {
1356
+ const dtype = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.typedArrayToDtype)(aObject);
1357
+ bObject = {
1358
+ _rtype: "typedarray",
1359
+ _rvalue: new Uint8Array(aObject.buffer),
1360
+ _rdtype: dtype,
1361
+ };
1362
+ } else if (aObject instanceof DataView) {
1363
+ bObject = {
1364
+ _rtype: "memoryview",
1365
+ _rvalue: new Uint8Array(aObject.buffer),
1366
+ };
1367
+ } else if (aObject instanceof Set) {
1368
+ bObject = {
1369
+ _rtype: "set",
1370
+ _rvalue: await this._encode(
1371
+ Array.from(aObject),
1372
+ session_id,
1373
+ local_workspace,
1374
+ ),
1375
+ };
1376
+ } else if (aObject instanceof Map) {
1377
+ bObject = {
1378
+ _rtype: "orderedmap",
1379
+ _rvalue: await this._encode(
1380
+ Array.from(aObject),
1381
+ session_id,
1382
+ local_workspace,
1383
+ ),
1384
+ };
1385
+ } else if (
1386
+ aObject.constructor instanceof Object ||
1387
+ Array.isArray(aObject)
1388
+ ) {
1389
+ bObject = isarray ? [] : {};
1390
+ const keys = Object.keys(aObject);
1391
+ for (let k of keys) {
1392
+ bObject[k] = await this._encode(
1393
+ aObject[k],
1394
+ session_id,
1395
+ local_workspace,
1396
+ );
1397
+ }
1398
+ } else {
1399
+ throw `hypha-rpc: Unsupported data type: ${aObject}, you can register a custom codec to encode/decode the object.`;
1400
+ }
1401
+
1402
+ if (!bObject) {
1403
+ throw new Error("Failed to encode object");
1404
+ }
1405
+ return bObject;
1406
+ }
1407
+
1408
+ async decode(aObject) {
1409
+ return await this._decode(aObject);
1410
+ }
1411
+
1412
+ async _decode(
1413
+ aObject,
1414
+ remote_parent,
1415
+ local_parent,
1416
+ remote_workspace,
1417
+ local_workspace,
1418
+ ) {
1419
+ if (!aObject) {
1420
+ return aObject;
1421
+ }
1422
+ let bObject;
1423
+ if (aObject._rtype) {
1424
+ if (
1425
+ this._codecs[aObject._rtype] &&
1426
+ this._codecs[aObject._rtype].decoder
1427
+ ) {
1428
+ const temp = aObject._rtype;
1429
+ delete aObject._rtype;
1430
+ aObject = await this._decode(
1431
+ aObject,
1432
+ remote_parent,
1433
+ local_parent,
1434
+ remote_workspace,
1435
+ local_workspace,
1436
+ );
1437
+ aObject._rtype = temp;
1438
+
1439
+ bObject = await Promise.resolve(
1440
+ this._codecs[aObject._rtype].decoder(aObject),
1441
+ );
1442
+ } else if (aObject._rtype === "method") {
1443
+ bObject = this._generate_remote_method(
1444
+ aObject,
1445
+ remote_parent,
1446
+ local_parent,
1447
+ remote_workspace,
1448
+ local_workspace,
1449
+ );
1450
+ } else if (aObject._rtype === "ndarray") {
1451
+ /*global nj tf*/
1452
+ //create build array/tensor if used in the plugin
1453
+ if (typeof nj !== "undefined" && nj.array) {
1454
+ if (Array.isArray(aObject._rvalue)) {
1455
+ aObject._rvalue = aObject._rvalue.reduce(_appendBuffer);
1456
+ }
1457
+ bObject = nj
1458
+ .array(new Uint8(aObject._rvalue), aObject._rdtype)
1459
+ .reshape(aObject._rshape);
1460
+ } else if (typeof tf !== "undefined" && tf.Tensor) {
1461
+ if (Array.isArray(aObject._rvalue)) {
1462
+ aObject._rvalue = aObject._rvalue.reduce(_appendBuffer);
1463
+ }
1464
+ const arraytype = _utils_js__WEBPACK_IMPORTED_MODULE_0__.dtypeToTypedArray[aObject._rdtype];
1465
+ bObject = tf.tensor(
1466
+ new arraytype(aObject._rvalue),
1467
+ aObject._rshape,
1468
+ aObject._rdtype,
1469
+ );
1470
+ } else {
1471
+ //keep it as regular if transfered to the main app
1472
+ bObject = aObject;
1473
+ }
1474
+ } else if (aObject._rtype === "error") {
1475
+ bObject = new Error(
1476
+ "RemoteError: " + aObject._rvalue + "\n" + (aObject._rtrace || ""),
1477
+ );
1478
+ } else if (aObject._rtype === "typedarray") {
1479
+ const arraytype = _utils_js__WEBPACK_IMPORTED_MODULE_0__.dtypeToTypedArray[aObject._rdtype];
1480
+ if (!arraytype)
1481
+ throw new Error("unsupported dtype: " + aObject._rdtype);
1482
+ const buffer = aObject._rvalue.buffer.slice(
1483
+ aObject._rvalue.byteOffset,
1484
+ aObject._rvalue.byteOffset + aObject._rvalue.byteLength,
1485
+ );
1486
+ bObject = new arraytype(buffer);
1487
+ } else if (aObject._rtype === "memoryview") {
1488
+ bObject = aObject._rvalue.buffer.slice(
1489
+ aObject._rvalue.byteOffset,
1490
+ aObject._rvalue.byteOffset + aObject._rvalue.byteLength,
1491
+ ); // ArrayBuffer
1492
+ } else if (aObject._rtype === "iostream") {
1493
+ if (aObject._rnative === "js:blob") {
1494
+ const read = await this._generate_remote_method(
1495
+ aObject.read,
1496
+ remote_parent,
1497
+ local_parent,
1498
+ remote_workspace,
1499
+ local_workspace,
1500
+ );
1501
+ const bytes = await read();
1502
+ bObject = new Blob([bytes], {
1503
+ type: aObject.type,
1504
+ name: aObject.name,
1505
+ });
1506
+ } else {
1507
+ bObject = {};
1508
+ for (let k of Object.keys(aObject)) {
1509
+ if (!k.startsWith("_")) {
1510
+ bObject[k] = await this._decode(
1511
+ aObject[k],
1512
+ remote_parent,
1513
+ local_parent,
1514
+ remote_workspace,
1515
+ local_workspace,
1516
+ );
1517
+ }
1518
+ }
1519
+ }
1520
+ bObject["__rpc_object__"] = aObject;
1521
+ } else if (aObject._rtype === "orderedmap") {
1522
+ bObject = new Map(
1523
+ await this._decode(
1524
+ aObject._rvalue,
1525
+ remote_parent,
1526
+ local_parent,
1527
+ remote_workspace,
1528
+ local_workspace,
1529
+ ),
1530
+ );
1531
+ } else if (aObject._rtype === "set") {
1532
+ bObject = new Set(
1533
+ await this._decode(
1534
+ aObject._rvalue,
1535
+ remote_parent,
1536
+ local_parent,
1537
+ remote_workspace,
1538
+ local_workspace,
1539
+ ),
1540
+ );
1541
+ } else {
1542
+ const temp = aObject._rtype;
1543
+ delete aObject._rtype;
1544
+ bObject = await this._decode(
1545
+ aObject,
1546
+ remote_parent,
1547
+ local_parent,
1548
+ remote_workspace,
1549
+ local_workspace,
1550
+ );
1551
+ bObject._rtype = temp;
1552
+ }
1553
+ } else if (aObject.constructor === Object || Array.isArray(aObject)) {
1554
+ const isarray = Array.isArray(aObject);
1555
+ bObject = isarray ? [] : {};
1556
+ for (let k of Object.keys(aObject)) {
1557
+ if (isarray || aObject.hasOwnProperty(k)) {
1558
+ const v = aObject[k];
1559
+ bObject[k] = await this._decode(
1560
+ v,
1561
+ remote_parent,
1562
+ local_parent,
1563
+ remote_workspace,
1564
+ local_workspace,
1565
+ );
1566
+ }
1567
+ }
1568
+ } else {
1569
+ bObject = aObject;
1570
+ }
1571
+ if (bObject === undefined) {
1572
+ throw new Error("Failed to decode object");
1573
+ }
1574
+ return bObject;
1575
+ }
1576
+ }
1577
+
1578
+
1579
+ /***/ }),
1580
+
1581
+ /***/ "./src/utils.js":
1582
+ /*!**********************!*\
1583
+ !*** ./src/utils.js ***!
1584
+ \**********************/
1585
+ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1586
+
1587
+ __webpack_require__.r(__webpack_exports__);
1588
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1589
+ /* harmony export */ MessageEmitter: () => (/* binding */ MessageEmitter),
1590
+ /* harmony export */ assert: () => (/* binding */ assert),
1591
+ /* harmony export */ cacheRequirements: () => (/* binding */ cacheRequirements),
1592
+ /* harmony export */ dtypeToTypedArray: () => (/* binding */ dtypeToTypedArray),
1593
+ /* harmony export */ loadRequirements: () => (/* binding */ loadRequirements),
1594
+ /* harmony export */ loadRequirementsInWebworker: () => (/* binding */ loadRequirementsInWebworker),
1595
+ /* harmony export */ loadRequirementsInWindow: () => (/* binding */ loadRequirementsInWindow),
1596
+ /* harmony export */ normalizeConfig: () => (/* binding */ normalizeConfig),
1597
+ /* harmony export */ randId: () => (/* binding */ randId),
1598
+ /* harmony export */ typedArrayToDtype: () => (/* binding */ typedArrayToDtype),
1599
+ /* harmony export */ typedArrayToDtypeMapping: () => (/* binding */ typedArrayToDtypeMapping),
1600
+ /* harmony export */ urlJoin: () => (/* binding */ urlJoin),
1601
+ /* harmony export */ waitFor: () => (/* binding */ waitFor)
1602
+ /* harmony export */ });
1603
+ function randId() {
1604
+ return Math.random().toString(36).substr(2, 10) + new Date().getTime();
1605
+ }
1606
+
1607
+ const dtypeToTypedArray = {
1608
+ int8: Int8Array,
1609
+ int16: Int16Array,
1610
+ int32: Int32Array,
1611
+ uint8: Uint8Array,
1612
+ uint16: Uint16Array,
1613
+ uint32: Uint32Array,
1614
+ float32: Float32Array,
1615
+ float64: Float64Array,
1616
+ array: Array,
1617
+ };
1618
+
1619
+ async function loadRequirementsInWindow(requirements) {
1620
+ function _importScript(url) {
1621
+ //url is URL of external file, implementationCode is the code
1622
+ //to be called from the file, location is the location to
1623
+ //insert the <script> element
1624
+ return new Promise((resolve, reject) => {
1625
+ var scriptTag = document.createElement("script");
1626
+ scriptTag.src = url;
1627
+ scriptTag.type = "text/javascript";
1628
+ scriptTag.onload = resolve;
1629
+ scriptTag.onreadystatechange = function () {
1630
+ if (this.readyState === "loaded" || this.readyState === "complete") {
1631
+ resolve();
1632
+ }
1633
+ };
1634
+ scriptTag.onerror = reject;
1635
+ document.head.appendChild(scriptTag);
1636
+ });
1637
+ }
1638
+
1639
+ // support importScripts outside web worker
1640
+ async function importScripts() {
1641
+ var args = Array.prototype.slice.call(arguments),
1642
+ len = args.length,
1643
+ i = 0;
1644
+ for (; i < len; i++) {
1645
+ await _importScript(args[i]);
1646
+ }
1647
+ }
1648
+
1649
+ if (
1650
+ requirements &&
1651
+ (Array.isArray(requirements) || typeof requirements === "string")
1652
+ ) {
1653
+ try {
1654
+ var link_node;
1655
+ requirements =
1656
+ typeof requirements === "string" ? [requirements] : requirements;
1657
+ if (Array.isArray(requirements)) {
1658
+ for (var i = 0; i < requirements.length; i++) {
1659
+ if (
1660
+ requirements[i].toLowerCase().endsWith(".css") ||
1661
+ requirements[i].startsWith("css:")
1662
+ ) {
1663
+ if (requirements[i].startsWith("css:")) {
1664
+ requirements[i] = requirements[i].slice(4);
1665
+ }
1666
+ link_node = document.createElement("link");
1667
+ link_node.rel = "stylesheet";
1668
+ link_node.href = requirements[i];
1669
+ document.head.appendChild(link_node);
1670
+ } else if (
1671
+ requirements[i].toLowerCase().endsWith(".mjs") ||
1672
+ requirements[i].startsWith("mjs:")
1673
+ ) {
1674
+ // import esmodule
1675
+ if (requirements[i].startsWith("mjs:")) {
1676
+ requirements[i] = requirements[i].slice(4);
1677
+ }
1678
+ await import(/* webpackIgnore: true */ requirements[i]);
1679
+ } else if (
1680
+ requirements[i].toLowerCase().endsWith(".js") ||
1681
+ requirements[i].startsWith("js:")
1682
+ ) {
1683
+ if (requirements[i].startsWith("js:")) {
1684
+ requirements[i] = requirements[i].slice(3);
1685
+ }
1686
+ await importScripts(requirements[i]);
1687
+ } else if (requirements[i].startsWith("http")) {
1688
+ await importScripts(requirements[i]);
1689
+ } else if (requirements[i].startsWith("cache:")) {
1690
+ //ignore cache
1691
+ } else {
1692
+ console.log("Unprocessed requirements url: " + requirements[i]);
1693
+ }
1694
+ }
1695
+ } else {
1696
+ throw "unsupported requirements definition";
1697
+ }
1698
+ } catch (e) {
1699
+ throw "failed to import required scripts: " + requirements.toString();
1700
+ }
1701
+ }
1702
+ }
1703
+
1704
+ async function loadRequirementsInWebworker(requirements) {
1705
+ if (
1706
+ requirements &&
1707
+ (Array.isArray(requirements) || typeof requirements === "string")
1708
+ ) {
1709
+ try {
1710
+ if (!Array.isArray(requirements)) {
1711
+ requirements = [requirements];
1712
+ }
1713
+ for (var i = 0; i < requirements.length; i++) {
1714
+ if (
1715
+ requirements[i].toLowerCase().endsWith(".css") ||
1716
+ requirements[i].startsWith("css:")
1717
+ ) {
1718
+ throw "unable to import css in a webworker";
1719
+ } else if (
1720
+ requirements[i].toLowerCase().endsWith(".js") ||
1721
+ requirements[i].startsWith("js:")
1722
+ ) {
1723
+ if (requirements[i].startsWith("js:")) {
1724
+ requirements[i] = requirements[i].slice(3);
1725
+ }
1726
+ importScripts(requirements[i]);
1727
+ } else if (requirements[i].startsWith("http")) {
1728
+ importScripts(requirements[i]);
1729
+ } else if (requirements[i].startsWith("cache:")) {
1730
+ //ignore cache
1731
+ } else {
1732
+ console.log("Unprocessed requirements url: " + requirements[i]);
1733
+ }
1734
+ }
1735
+ } catch (e) {
1736
+ throw "failed to import required scripts: " + requirements.toString();
1737
+ }
1738
+ }
1739
+ }
1740
+
1741
+ function loadRequirements(requirements) {
1742
+ if (
1743
+ typeof WorkerGlobalScope !== "undefined" &&
1744
+ self instanceof WorkerGlobalScope
1745
+ ) {
1746
+ return loadRequirementsInWebworker(requirements);
1747
+ } else {
1748
+ return loadRequirementsInWindow(requirements);
1749
+ }
1750
+ }
1751
+
1752
+ function normalizeConfig(config) {
1753
+ config.version = config.version || "0.1.0";
1754
+ config.description =
1755
+ config.description || `[TODO: add description for ${config.name} ]`;
1756
+ config.type = config.type || "rpc-window";
1757
+ config.id = config.id || randId();
1758
+ config.target_origin = config.target_origin || "*";
1759
+ config.allow_execution = config.allow_execution || false;
1760
+ // remove functions
1761
+ config = Object.keys(config).reduce((p, c) => {
1762
+ if (typeof config[c] !== "function") p[c] = config[c];
1763
+ return p;
1764
+ }, {});
1765
+ return config;
1766
+ }
1767
+ const typedArrayToDtypeMapping = {
1768
+ Int8Array: "int8",
1769
+ Int16Array: "int16",
1770
+ Int32Array: "int32",
1771
+ Uint8Array: "uint8",
1772
+ Uint16Array: "uint16",
1773
+ Uint32Array: "uint32",
1774
+ Float32Array: "float32",
1775
+ Float64Array: "float64",
1776
+ Array: "array",
1777
+ };
1778
+
1779
+ const typedArrayToDtypeKeys = [];
1780
+ for (const arrType of Object.keys(typedArrayToDtypeMapping)) {
1781
+ typedArrayToDtypeKeys.push(eval(arrType));
1782
+ }
1783
+
1784
+ function typedArrayToDtype(obj) {
1785
+ let dtype = typedArrayToDtypeMapping[obj.constructor.name];
1786
+ if (!dtype) {
1787
+ const pt = Object.getPrototypeOf(obj);
1788
+ for (const arrType of typedArrayToDtypeKeys) {
1789
+ if (pt instanceof arrType) {
1790
+ dtype = typedArrayToDtypeMapping[arrType.name];
1791
+ break;
1792
+ }
1793
+ }
1794
+ }
1795
+ return dtype;
1796
+ }
1797
+
1798
+ function cacheUrlInServiceWorker(url) {
1799
+ return new Promise(function (resolve, reject) {
1800
+ const message = {
1801
+ command: "add",
1802
+ url: url,
1803
+ };
1804
+ if (!navigator.serviceWorker || !navigator.serviceWorker.register) {
1805
+ reject("Service worker is not supported.");
1806
+ return;
1807
+ }
1808
+ const messageChannel = new MessageChannel();
1809
+ messageChannel.port1.onmessage = function (event) {
1810
+ if (event.data && event.data.error) {
1811
+ reject(event.data.error);
1812
+ } else {
1813
+ resolve(event.data && event.data.result);
1814
+ }
1815
+ };
1816
+
1817
+ if (navigator.serviceWorker && navigator.serviceWorker.controller) {
1818
+ navigator.serviceWorker.controller.postMessage(message, [
1819
+ messageChannel.port2,
1820
+ ]);
1821
+ } else {
1822
+ reject("Service worker controller is not available");
1823
+ }
1824
+ });
1825
+ }
1826
+
1827
+ async function cacheRequirements(requirements) {
1828
+ requirements = requirements || [];
1829
+ if (!Array.isArray(requirements)) {
1830
+ requirements = [requirements];
1831
+ }
1832
+ for (let req of requirements) {
1833
+ //remove prefix
1834
+ if (req.startsWith("js:")) req = req.slice(3);
1835
+ if (req.startsWith("css:")) req = req.slice(4);
1836
+ if (req.startsWith("cache:")) req = req.slice(6);
1837
+ if (!req.startsWith("http")) continue;
1838
+
1839
+ await cacheUrlInServiceWorker(req).catch((e) => {
1840
+ console.error(e);
1841
+ });
1842
+ }
1843
+ }
1844
+
1845
+ function assert(condition, message) {
1846
+ if (!condition) {
1847
+ throw new Error(message || "Assertion failed");
1848
+ }
1849
+ }
1850
+
1851
+ //#Source https://bit.ly/2neWfJ2
1852
+ function urlJoin(...args) {
1853
+ return args
1854
+ .join("/")
1855
+ .replace(/[\/]+/g, "/")
1856
+ .replace(/^(.+):\//, "$1://")
1857
+ .replace(/^file:/, "file:/")
1858
+ .replace(/\/(\?|&|#[^!])/g, "$1")
1859
+ .replace(/\?/g, "&")
1860
+ .replace("&", "?");
1861
+ }
1862
+
1863
+ function waitFor(prom, time, error) {
1864
+ let timer;
1865
+ return Promise.race([
1866
+ prom,
1867
+ new Promise(
1868
+ (_r, rej) =>
1869
+ (timer = setTimeout(() => {
1870
+ rej(error || "Timeout Error");
1871
+ }, time * 1000)),
1872
+ ),
1873
+ ]).finally(() => clearTimeout(timer));
1874
+ }
1875
+
1876
+ class MessageEmitter {
1877
+ constructor(debug) {
1878
+ this._event_handlers = {};
1879
+ this._once_handlers = {};
1880
+ this._debug = debug;
1881
+ }
1882
+ emit() {
1883
+ throw new Error("emit is not implemented");
1884
+ }
1885
+ on(event, handler) {
1886
+ if (!this._event_handlers[event]) {
1887
+ this._event_handlers[event] = [];
1888
+ }
1889
+ this._event_handlers[event].push(handler);
1890
+ }
1891
+ once(event, handler) {
1892
+ handler.___event_run_once = true;
1893
+ this.on(event, handler);
1894
+ }
1895
+ off(event, handler) {
1896
+ if (!event && !handler) {
1897
+ // remove all events handlers
1898
+ this._event_handlers = {};
1899
+ } else if (event && !handler) {
1900
+ // remove all hanlders for the event
1901
+ if (this._event_handlers[event]) this._event_handlers[event] = [];
1902
+ } else {
1903
+ // remove a specific handler
1904
+ if (this._event_handlers[event]) {
1905
+ const idx = this._event_handlers[event].indexOf(handler);
1906
+ if (idx >= 0) {
1907
+ this._event_handlers[event].splice(idx, 1);
1908
+ }
1909
+ }
1910
+ }
1911
+ }
1912
+ _fire(event, data) {
1913
+ if (this._event_handlers[event]) {
1914
+ var i = this._event_handlers[event].length;
1915
+ while (i--) {
1916
+ const handler = this._event_handlers[event][i];
1917
+ try {
1918
+ handler(data);
1919
+ } catch (e) {
1920
+ console.error(e);
1921
+ } finally {
1922
+ if (handler.___event_run_once) {
1923
+ this._event_handlers[event].splice(i, 1);
1924
+ }
1925
+ }
1926
+ }
1927
+ } else {
1928
+ if (this._debug) {
1929
+ console.warn("unhandled event", event, data);
1930
+ }
1931
+ }
1932
+ }
1933
+ }
1934
+
1935
+
1936
+ /***/ }),
1937
+
1938
+ /***/ "./src/webrtc-client.js":
1939
+ /*!******************************!*\
1940
+ !*** ./src/webrtc-client.js ***!
1941
+ \******************************/
1942
+ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1943
+
1944
+ __webpack_require__.r(__webpack_exports__);
1945
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1946
+ /* harmony export */ getRTCService: () => (/* binding */ getRTCService),
1947
+ /* harmony export */ registerRTCService: () => (/* binding */ registerRTCService)
1948
+ /* harmony export */ });
1949
+ /* harmony import */ var _rpc_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./rpc.js */ "./src/rpc.js");
1950
+ /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./src/utils.js");
1951
+
1952
+
1953
+
1954
+ class WebRTCConnection {
1955
+ constructor(channel) {
1956
+ this._data_channel = channel;
1957
+ this._handle_message = null;
1958
+ this._reconnection_token = null;
1959
+ this._data_channel.onmessage = async (event) => {
1960
+ let data = event.data;
1961
+ if (data instanceof Blob) {
1962
+ data = await data.arrayBuffer();
1963
+ }
1964
+ this._handle_message(data);
1965
+ };
1966
+ const self = this;
1967
+ this._data_channel.onclose = function () {
1968
+ console.log("websocket closed");
1969
+ self._data_channel = null;
1970
+ };
1971
+ }
1972
+
1973
+ on_message(handler) {
1974
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(handler, "handler is required");
1975
+ this._handle_message = handler;
1976
+ }
1977
+
1978
+ async emit_message(data) {
1979
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(this._handle_message, "No handler for message");
1980
+ try {
1981
+ this._data_channel.send(data);
1982
+ } catch (exp) {
1983
+ // data = msgpack_unpackb(data);
1984
+ console.error(`Failed to send data, error: ${exp}`);
1985
+ throw exp;
1986
+ }
1987
+ }
1988
+
1989
+ async disconnect(reason) {
1990
+ this._data_channel = null;
1991
+ console.info(`data channel connection disconnected (${reason})`);
1992
+ }
1993
+ }
1994
+
1995
+ async function _setupRPC(config) {
1996
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(config.channel, "No channel provided");
1997
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(config.workspace, "No workspace provided");
1998
+ const channel = config.channel;
1999
+ const clientId = config.client_id || (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.randId)();
2000
+ const connection = new WebRTCConnection(channel);
2001
+ config.context = config.context || {};
2002
+ config.context.connection_type = "webrtc";
2003
+ const rpc = new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC(connection, {
2004
+ client_id: clientId,
2005
+ manager_id: null,
2006
+ default_context: config.context,
2007
+ name: config.name,
2008
+ method_timeout: config.method_timeout || 10.0,
2009
+ workspace: config.workspace,
2010
+ });
2011
+ return rpc;
2012
+ }
2013
+
2014
+ async function _createOffer(params, server, config, onInit, context) {
2015
+ config = config || {};
2016
+ let offer = new RTCSessionDescription({
2017
+ sdp: params.sdp,
2018
+ type: params.type,
2019
+ });
2020
+
2021
+ let pc = new RTCPeerConnection({
2022
+ iceServers: config.ice_servers || [
2023
+ { urls: ["stun:stun.l.google.com:19302"] },
2024
+ ],
2025
+ sdpSemantics: "unified-plan",
2026
+ });
2027
+
2028
+ if (server) {
2029
+ pc.addEventListener("datachannel", async (event) => {
2030
+ const channel = event.channel;
2031
+ let ctx = null;
2032
+ if (context && context.user) ctx = { user: context.user };
2033
+ const rpc = await _setupRPC({
2034
+ channel: channel,
2035
+ client_id: channel.label,
2036
+ workspace: server.config.workspace,
2037
+ context: ctx,
2038
+ });
2039
+ // Map all the local services to the webrtc client
2040
+ rpc._services = server.rpc._services;
2041
+ });
2042
+ }
2043
+
2044
+ if (onInit) {
2045
+ await onInit(pc);
2046
+ }
2047
+
2048
+ await pc.setRemoteDescription(offer);
2049
+
2050
+ let answer = await pc.createAnswer();
2051
+ await pc.setLocalDescription(answer);
2052
+
2053
+ return {
2054
+ sdp: pc.localDescription.sdp,
2055
+ type: pc.localDescription.type,
2056
+ workspace: server.config.workspace,
2057
+ };
2058
+ }
2059
+
2060
+ async function getRTCService(server, service_id, config) {
2061
+ config = config || {};
2062
+ config.peer_id = config.peer_id || (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.randId)();
2063
+
2064
+ const pc = new RTCPeerConnection({
2065
+ iceServers: config.ice_servers || [
2066
+ { urls: ["stun:stun.l.google.com:19302"] },
2067
+ ],
2068
+ sdpSemantics: "unified-plan",
2069
+ });
2070
+
2071
+ return new Promise(async (resolve, reject) => {
2072
+ try {
2073
+ pc.addEventListener(
2074
+ "connectionstatechange",
2075
+ () => {
2076
+ if (pc.connectionState === "failed") {
2077
+ pc.close();
2078
+ reject(new Error("Connection failed"));
2079
+ }
2080
+ },
2081
+ false,
2082
+ );
2083
+
2084
+ if (config.on_init) {
2085
+ await config.on_init(pc);
2086
+ delete config.on_init;
2087
+ }
2088
+ let channel = pc.createDataChannel(config.peer_id, { ordered: true });
2089
+ channel.binaryType = "arraybuffer";
2090
+ const offer = await pc.createOffer();
2091
+ await pc.setLocalDescription(offer);
2092
+ const svc = await server.getService(service_id);
2093
+ const answer = await svc.offer({
2094
+ sdp: pc.localDescription.sdp,
2095
+ type: pc.localDescription.type,
2096
+ });
2097
+
2098
+ channel.onopen = () => {
2099
+ config.channel = channel;
2100
+ config.workspace = answer.workspace;
2101
+ // Wait for the channel to be open before returning the rpc
2102
+ // This is needed for safari to work
2103
+ setTimeout(async () => {
2104
+ const rpc = await _setupRPC(config);
2105
+ pc.rpc = rpc;
2106
+ async function getService(name) {
2107
+ return await rpc.get_remote_service(config.peer_id + ":" + name);
2108
+ }
2109
+ async function disconnect() {
2110
+ await rpc.disconnect();
2111
+ pc.close();
2112
+ }
2113
+ pc.get_service = getService;
2114
+ pc.getService = getService;
2115
+ pc.disconnect = disconnect;
2116
+ pc.register_codec = rpc.register_codec;
2117
+ pc.registerCodec = rpc.register_codec;
2118
+ resolve(pc);
2119
+ }, 500);
2120
+ };
2121
+
2122
+ channel.onclose = () => reject(new Error("Data channel closed"));
2123
+
2124
+ await pc.setRemoteDescription(
2125
+ new RTCSessionDescription({
2126
+ sdp: answer.sdp,
2127
+ type: answer.type,
2128
+ }),
2129
+ );
2130
+ } catch (e) {
2131
+ reject(e);
2132
+ }
2133
+ });
2134
+ }
2135
+
2136
+ async function registerRTCService(server, service_id, config) {
2137
+ config = config || {
2138
+ visibility: "protected",
2139
+ require_context: true,
2140
+ };
2141
+ const onInit = config.on_init;
2142
+ delete config.on_init;
2143
+ await server.registerService({
2144
+ id: service_id,
2145
+ config,
2146
+ offer: (params, context) =>
2147
+ _createOffer(params, server, config, onInit, context),
2148
+ });
2149
+ }
2150
+
2151
+
2152
+
2153
+
2154
+ /***/ }),
2155
+
2156
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs":
2157
+ /*!*************************************************************************!*\
2158
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs ***!
2159
+ \*************************************************************************/
2160
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2161
+
2162
+ __webpack_require__.r(__webpack_exports__);
2163
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2164
+ /* harmony export */ CachedKeyDecoder: () => (/* binding */ CachedKeyDecoder)
2165
+ /* harmony export */ });
2166
+ /* harmony import */ var _utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/utf8.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs");
2167
+
2168
+ var DEFAULT_MAX_KEY_LENGTH = 16;
2169
+ var DEFAULT_MAX_LENGTH_PER_KEY = 16;
2170
+ var CachedKeyDecoder = /** @class */ (function () {
2171
+ function CachedKeyDecoder(maxKeyLength, maxLengthPerKey) {
2172
+ if (maxKeyLength === void 0) { maxKeyLength = DEFAULT_MAX_KEY_LENGTH; }
2173
+ if (maxLengthPerKey === void 0) { maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY; }
2174
+ this.maxKeyLength = maxKeyLength;
2175
+ this.maxLengthPerKey = maxLengthPerKey;
2176
+ this.hit = 0;
2177
+ this.miss = 0;
2178
+ // avoid `new Array(N)`, which makes a sparse array,
2179
+ // because a sparse array is typically slower than a non-sparse array.
2180
+ this.caches = [];
2181
+ for (var i = 0; i < this.maxKeyLength; i++) {
2182
+ this.caches.push([]);
2183
+ }
2184
+ }
2185
+ CachedKeyDecoder.prototype.canBeCached = function (byteLength) {
2186
+ return byteLength > 0 && byteLength <= this.maxKeyLength;
2187
+ };
2188
+ CachedKeyDecoder.prototype.find = function (bytes, inputOffset, byteLength) {
2189
+ var records = this.caches[byteLength - 1];
2190
+ FIND_CHUNK: for (var _i = 0, records_1 = records; _i < records_1.length; _i++) {
2191
+ var record = records_1[_i];
2192
+ var recordBytes = record.bytes;
2193
+ for (var j = 0; j < byteLength; j++) {
2194
+ if (recordBytes[j] !== bytes[inputOffset + j]) {
2195
+ continue FIND_CHUNK;
2196
+ }
2197
+ }
2198
+ return record.str;
2199
+ }
2200
+ return null;
2201
+ };
2202
+ CachedKeyDecoder.prototype.store = function (bytes, value) {
2203
+ var records = this.caches[bytes.length - 1];
2204
+ var record = { bytes: bytes, str: value };
2205
+ if (records.length >= this.maxLengthPerKey) {
2206
+ // `records` are full!
2207
+ // Set `record` to an arbitrary position.
2208
+ records[(Math.random() * records.length) | 0] = record;
2209
+ }
2210
+ else {
2211
+ records.push(record);
2212
+ }
2213
+ };
2214
+ CachedKeyDecoder.prototype.decode = function (bytes, inputOffset, byteLength) {
2215
+ var cachedValue = this.find(bytes, inputOffset, byteLength);
2216
+ if (cachedValue != null) {
2217
+ this.hit++;
2218
+ return cachedValue;
2219
+ }
2220
+ this.miss++;
2221
+ var str = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_0__.utf8DecodeJs)(bytes, inputOffset, byteLength);
2222
+ // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.
2223
+ var slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
2224
+ this.store(slicedCopyOfBytes, str);
2225
+ return str;
2226
+ };
2227
+ return CachedKeyDecoder;
2228
+ }());
2229
+
2230
+ //# sourceMappingURL=CachedKeyDecoder.mjs.map
2231
+
2232
+ /***/ }),
2233
+
2234
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs":
2235
+ /*!********************************************************************!*\
2236
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs ***!
2237
+ \********************************************************************/
2238
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2239
+
2240
+ __webpack_require__.r(__webpack_exports__);
2241
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2242
+ /* harmony export */ DecodeError: () => (/* binding */ DecodeError)
2243
+ /* harmony export */ });
2244
+ var __extends = (undefined && undefined.__extends) || (function () {
2245
+ var extendStatics = function (d, b) {
2246
+ extendStatics = Object.setPrototypeOf ||
2247
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
2248
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
2249
+ return extendStatics(d, b);
2250
+ };
2251
+ return function (d, b) {
2252
+ if (typeof b !== "function" && b !== null)
2253
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
2254
+ extendStatics(d, b);
2255
+ function __() { this.constructor = d; }
2256
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2257
+ };
2258
+ })();
2259
+ var DecodeError = /** @class */ (function (_super) {
2260
+ __extends(DecodeError, _super);
2261
+ function DecodeError(message) {
2262
+ var _this = _super.call(this, message) || this;
2263
+ // fix the prototype chain in a cross-platform way
2264
+ var proto = Object.create(DecodeError.prototype);
2265
+ Object.setPrototypeOf(_this, proto);
2266
+ Object.defineProperty(_this, "name", {
2267
+ configurable: true,
2268
+ enumerable: false,
2269
+ value: DecodeError.name,
2270
+ });
2271
+ return _this;
2272
+ }
2273
+ return DecodeError;
2274
+ }(Error));
2275
+
2276
+ //# sourceMappingURL=DecodeError.mjs.map
2277
+
2278
+ /***/ }),
2279
+
2280
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs":
2281
+ /*!****************************************************************!*\
2282
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs ***!
2283
+ \****************************************************************/
2284
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2285
+
2286
+ __webpack_require__.r(__webpack_exports__);
2287
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2288
+ /* harmony export */ DataViewIndexOutOfBoundsError: () => (/* binding */ DataViewIndexOutOfBoundsError),
2289
+ /* harmony export */ Decoder: () => (/* binding */ Decoder)
2290
+ /* harmony export */ });
2291
+ /* harmony import */ var _utils_prettyByte_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/prettyByte.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs");
2292
+ /* harmony import */ var _ExtensionCodec_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ExtensionCodec.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs");
2293
+ /* harmony import */ var _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/int.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs");
2294
+ /* harmony import */ var _utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/utf8.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs");
2295
+ /* harmony import */ var _utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/typedArrays.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs");
2296
+ /* harmony import */ var _CachedKeyDecoder_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CachedKeyDecoder.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs");
2297
+ /* harmony import */ var _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./DecodeError.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs");
2298
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2299
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2300
+ return new (P || (P = Promise))(function (resolve, reject) {
2301
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2302
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2303
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2304
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
2305
+ });
2306
+ };
2307
+ var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
2308
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
2309
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2310
+ function verb(n) { return function (v) { return step([n, v]); }; }
2311
+ function step(op) {
2312
+ if (f) throw new TypeError("Generator is already executing.");
2313
+ while (_) try {
2314
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
2315
+ if (y = 0, t) op = [op[0] & 2, t.value];
2316
+ switch (op[0]) {
2317
+ case 0: case 1: t = op; break;
2318
+ case 4: _.label++; return { value: op[1], done: false };
2319
+ case 5: _.label++; y = op[1]; op = [0]; continue;
2320
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
2321
+ default:
2322
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2323
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2324
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2325
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2326
+ if (t[2]) _.ops.pop();
2327
+ _.trys.pop(); continue;
2328
+ }
2329
+ op = body.call(thisArg, _);
2330
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2331
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2332
+ }
2333
+ };
2334
+ var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
2335
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
2336
+ var m = o[Symbol.asyncIterator], i;
2337
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
2338
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
2339
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
2340
+ };
2341
+ var __await = (undefined && undefined.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
2342
+ var __asyncGenerator = (undefined && undefined.__asyncGenerator) || function (thisArg, _arguments, generator) {
2343
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
2344
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
2345
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
2346
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
2347
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
2348
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
2349
+ function fulfill(value) { resume("next", value); }
2350
+ function reject(value) { resume("throw", value); }
2351
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
2352
+ };
2353
+
2354
+
2355
+
2356
+
2357
+
2358
+
2359
+
2360
+ var isValidMapKeyType = function (key) {
2361
+ var keyType = typeof key;
2362
+ return keyType === "string" || keyType === "number";
2363
+ };
2364
+ var HEAD_BYTE_REQUIRED = -1;
2365
+ var EMPTY_VIEW = new DataView(new ArrayBuffer(0));
2366
+ var EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);
2367
+ // IE11: Hack to support IE11.
2368
+ // IE11: Drop this hack and just use RangeError when IE11 is obsolete.
2369
+ var DataViewIndexOutOfBoundsError = (function () {
2370
+ try {
2371
+ // IE11: The spec says it should throw RangeError,
2372
+ // IE11: but in IE11 it throws TypeError.
2373
+ EMPTY_VIEW.getInt8(0);
2374
+ }
2375
+ catch (e) {
2376
+ return e.constructor;
2377
+ }
2378
+ throw new Error("never reached");
2379
+ })();
2380
+ var MORE_DATA = new DataViewIndexOutOfBoundsError("Insufficient data");
2381
+ var sharedCachedKeyDecoder = new _CachedKeyDecoder_mjs__WEBPACK_IMPORTED_MODULE_0__.CachedKeyDecoder();
2382
+ var Decoder = /** @class */ (function () {
2383
+ function Decoder(extensionCodec, context, maxStrLength, maxBinLength, maxArrayLength, maxMapLength, maxExtLength, keyDecoder) {
2384
+ if (extensionCodec === void 0) { extensionCodec = _ExtensionCodec_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtensionCodec.defaultCodec; }
2385
+ if (context === void 0) { context = undefined; }
2386
+ if (maxStrLength === void 0) { maxStrLength = _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.UINT32_MAX; }
2387
+ if (maxBinLength === void 0) { maxBinLength = _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.UINT32_MAX; }
2388
+ if (maxArrayLength === void 0) { maxArrayLength = _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.UINT32_MAX; }
2389
+ if (maxMapLength === void 0) { maxMapLength = _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.UINT32_MAX; }
2390
+ if (maxExtLength === void 0) { maxExtLength = _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.UINT32_MAX; }
2391
+ if (keyDecoder === void 0) { keyDecoder = sharedCachedKeyDecoder; }
2392
+ this.extensionCodec = extensionCodec;
2393
+ this.context = context;
2394
+ this.maxStrLength = maxStrLength;
2395
+ this.maxBinLength = maxBinLength;
2396
+ this.maxArrayLength = maxArrayLength;
2397
+ this.maxMapLength = maxMapLength;
2398
+ this.maxExtLength = maxExtLength;
2399
+ this.keyDecoder = keyDecoder;
2400
+ this.totalPos = 0;
2401
+ this.pos = 0;
2402
+ this.view = EMPTY_VIEW;
2403
+ this.bytes = EMPTY_BYTES;
2404
+ this.headByte = HEAD_BYTE_REQUIRED;
2405
+ this.stack = [];
2406
+ }
2407
+ Decoder.prototype.reinitializeState = function () {
2408
+ this.totalPos = 0;
2409
+ this.headByte = HEAD_BYTE_REQUIRED;
2410
+ this.stack.length = 0;
2411
+ // view, bytes, and pos will be re-initialized in setBuffer()
2412
+ };
2413
+ Decoder.prototype.setBuffer = function (buffer) {
2414
+ this.bytes = (0,_utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_3__.ensureUint8Array)(buffer);
2415
+ this.view = (0,_utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_3__.createDataView)(this.bytes);
2416
+ this.pos = 0;
2417
+ };
2418
+ Decoder.prototype.appendBuffer = function (buffer) {
2419
+ if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {
2420
+ this.setBuffer(buffer);
2421
+ }
2422
+ else {
2423
+ var remainingData = this.bytes.subarray(this.pos);
2424
+ var newData = (0,_utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_3__.ensureUint8Array)(buffer);
2425
+ // concat remainingData + newData
2426
+ var newBuffer = new Uint8Array(remainingData.length + newData.length);
2427
+ newBuffer.set(remainingData);
2428
+ newBuffer.set(newData, remainingData.length);
2429
+ this.setBuffer(newBuffer);
2430
+ }
2431
+ };
2432
+ Decoder.prototype.hasRemaining = function (size) {
2433
+ return this.view.byteLength - this.pos >= size;
2434
+ };
2435
+ Decoder.prototype.createExtraByteError = function (posToShow) {
2436
+ var _a = this, view = _a.view, pos = _a.pos;
2437
+ return new RangeError("Extra ".concat(view.byteLength - pos, " of ").concat(view.byteLength, " byte(s) found at buffer[").concat(posToShow, "]"));
2438
+ };
2439
+ /**
2440
+ * @throws {@link DecodeError}
2441
+ * @throws {@link RangeError}
2442
+ */
2443
+ Decoder.prototype.decode = function (buffer) {
2444
+ this.reinitializeState();
2445
+ this.setBuffer(buffer);
2446
+ var object = this.doDecodeSync();
2447
+ if (this.hasRemaining(1)) {
2448
+ throw this.createExtraByteError(this.pos);
2449
+ }
2450
+ return object;
2451
+ };
2452
+ Decoder.prototype.decodeMulti = function (buffer) {
2453
+ return __generator(this, function (_a) {
2454
+ switch (_a.label) {
2455
+ case 0:
2456
+ this.reinitializeState();
2457
+ this.setBuffer(buffer);
2458
+ _a.label = 1;
2459
+ case 1:
2460
+ if (!this.hasRemaining(1)) return [3 /*break*/, 3];
2461
+ return [4 /*yield*/, this.doDecodeSync()];
2462
+ case 2:
2463
+ _a.sent();
2464
+ return [3 /*break*/, 1];
2465
+ case 3: return [2 /*return*/];
2466
+ }
2467
+ });
2468
+ };
2469
+ Decoder.prototype.decodeAsync = function (stream) {
2470
+ var stream_1, stream_1_1;
2471
+ var e_1, _a;
2472
+ return __awaiter(this, void 0, void 0, function () {
2473
+ var decoded, object, buffer, e_1_1, _b, headByte, pos, totalPos;
2474
+ return __generator(this, function (_c) {
2475
+ switch (_c.label) {
2476
+ case 0:
2477
+ decoded = false;
2478
+ _c.label = 1;
2479
+ case 1:
2480
+ _c.trys.push([1, 6, 7, 12]);
2481
+ stream_1 = __asyncValues(stream);
2482
+ _c.label = 2;
2483
+ case 2: return [4 /*yield*/, stream_1.next()];
2484
+ case 3:
2485
+ if (!(stream_1_1 = _c.sent(), !stream_1_1.done)) return [3 /*break*/, 5];
2486
+ buffer = stream_1_1.value;
2487
+ if (decoded) {
2488
+ throw this.createExtraByteError(this.totalPos);
2489
+ }
2490
+ this.appendBuffer(buffer);
2491
+ try {
2492
+ object = this.doDecodeSync();
2493
+ decoded = true;
2494
+ }
2495
+ catch (e) {
2496
+ if (!(e instanceof DataViewIndexOutOfBoundsError)) {
2497
+ throw e; // rethrow
2498
+ }
2499
+ // fallthrough
2500
+ }
2501
+ this.totalPos += this.pos;
2502
+ _c.label = 4;
2503
+ case 4: return [3 /*break*/, 2];
2504
+ case 5: return [3 /*break*/, 12];
2505
+ case 6:
2506
+ e_1_1 = _c.sent();
2507
+ e_1 = { error: e_1_1 };
2508
+ return [3 /*break*/, 12];
2509
+ case 7:
2510
+ _c.trys.push([7, , 10, 11]);
2511
+ if (!(stream_1_1 && !stream_1_1.done && (_a = stream_1.return))) return [3 /*break*/, 9];
2512
+ return [4 /*yield*/, _a.call(stream_1)];
2513
+ case 8:
2514
+ _c.sent();
2515
+ _c.label = 9;
2516
+ case 9: return [3 /*break*/, 11];
2517
+ case 10:
2518
+ if (e_1) throw e_1.error;
2519
+ return [7 /*endfinally*/];
2520
+ case 11: return [7 /*endfinally*/];
2521
+ case 12:
2522
+ if (decoded) {
2523
+ if (this.hasRemaining(1)) {
2524
+ throw this.createExtraByteError(this.totalPos);
2525
+ }
2526
+ return [2 /*return*/, object];
2527
+ }
2528
+ _b = this, headByte = _b.headByte, pos = _b.pos, totalPos = _b.totalPos;
2529
+ throw new RangeError("Insufficient data in parsing ".concat((0,_utils_prettyByte_mjs__WEBPACK_IMPORTED_MODULE_4__.prettyByte)(headByte), " at ").concat(totalPos, " (").concat(pos, " in the current buffer)"));
2530
+ }
2531
+ });
2532
+ });
2533
+ };
2534
+ Decoder.prototype.decodeArrayStream = function (stream) {
2535
+ return this.decodeMultiAsync(stream, true);
2536
+ };
2537
+ Decoder.prototype.decodeStream = function (stream) {
2538
+ return this.decodeMultiAsync(stream, false);
2539
+ };
2540
+ Decoder.prototype.decodeMultiAsync = function (stream, isArray) {
2541
+ return __asyncGenerator(this, arguments, function decodeMultiAsync_1() {
2542
+ var isArrayHeaderRequired, arrayItemsLeft, stream_2, stream_2_1, buffer, e_2, e_3_1;
2543
+ var e_3, _a;
2544
+ return __generator(this, function (_b) {
2545
+ switch (_b.label) {
2546
+ case 0:
2547
+ isArrayHeaderRequired = isArray;
2548
+ arrayItemsLeft = -1;
2549
+ _b.label = 1;
2550
+ case 1:
2551
+ _b.trys.push([1, 13, 14, 19]);
2552
+ stream_2 = __asyncValues(stream);
2553
+ _b.label = 2;
2554
+ case 2: return [4 /*yield*/, __await(stream_2.next())];
2555
+ case 3:
2556
+ if (!(stream_2_1 = _b.sent(), !stream_2_1.done)) return [3 /*break*/, 12];
2557
+ buffer = stream_2_1.value;
2558
+ if (isArray && arrayItemsLeft === 0) {
2559
+ throw this.createExtraByteError(this.totalPos);
2560
+ }
2561
+ this.appendBuffer(buffer);
2562
+ if (isArrayHeaderRequired) {
2563
+ arrayItemsLeft = this.readArraySize();
2564
+ isArrayHeaderRequired = false;
2565
+ this.complete();
2566
+ }
2567
+ _b.label = 4;
2568
+ case 4:
2569
+ _b.trys.push([4, 9, , 10]);
2570
+ _b.label = 5;
2571
+ case 5:
2572
+ if (false) {}
2573
+ return [4 /*yield*/, __await(this.doDecodeSync())];
2574
+ case 6: return [4 /*yield*/, _b.sent()];
2575
+ case 7:
2576
+ _b.sent();
2577
+ if (--arrayItemsLeft === 0) {
2578
+ return [3 /*break*/, 8];
2579
+ }
2580
+ return [3 /*break*/, 5];
2581
+ case 8: return [3 /*break*/, 10];
2582
+ case 9:
2583
+ e_2 = _b.sent();
2584
+ if (!(e_2 instanceof DataViewIndexOutOfBoundsError)) {
2585
+ throw e_2; // rethrow
2586
+ }
2587
+ return [3 /*break*/, 10];
2588
+ case 10:
2589
+ this.totalPos += this.pos;
2590
+ _b.label = 11;
2591
+ case 11: return [3 /*break*/, 2];
2592
+ case 12: return [3 /*break*/, 19];
2593
+ case 13:
2594
+ e_3_1 = _b.sent();
2595
+ e_3 = { error: e_3_1 };
2596
+ return [3 /*break*/, 19];
2597
+ case 14:
2598
+ _b.trys.push([14, , 17, 18]);
2599
+ if (!(stream_2_1 && !stream_2_1.done && (_a = stream_2.return))) return [3 /*break*/, 16];
2600
+ return [4 /*yield*/, __await(_a.call(stream_2))];
2601
+ case 15:
2602
+ _b.sent();
2603
+ _b.label = 16;
2604
+ case 16: return [3 /*break*/, 18];
2605
+ case 17:
2606
+ if (e_3) throw e_3.error;
2607
+ return [7 /*endfinally*/];
2608
+ case 18: return [7 /*endfinally*/];
2609
+ case 19: return [2 /*return*/];
2610
+ }
2611
+ });
2612
+ });
2613
+ };
2614
+ Decoder.prototype.doDecodeSync = function () {
2615
+ DECODE: while (true) {
2616
+ var headByte = this.readHeadByte();
2617
+ var object = void 0;
2618
+ if (headByte >= 0xe0) {
2619
+ // negative fixint (111x xxxx) 0xe0 - 0xff
2620
+ object = headByte - 0x100;
2621
+ }
2622
+ else if (headByte < 0xc0) {
2623
+ if (headByte < 0x80) {
2624
+ // positive fixint (0xxx xxxx) 0x00 - 0x7f
2625
+ object = headByte;
2626
+ }
2627
+ else if (headByte < 0x90) {
2628
+ // fixmap (1000 xxxx) 0x80 - 0x8f
2629
+ var size = headByte - 0x80;
2630
+ if (size !== 0) {
2631
+ this.pushMapState(size);
2632
+ this.complete();
2633
+ continue DECODE;
2634
+ }
2635
+ else {
2636
+ object = {};
2637
+ }
2638
+ }
2639
+ else if (headByte < 0xa0) {
2640
+ // fixarray (1001 xxxx) 0x90 - 0x9f
2641
+ var size = headByte - 0x90;
2642
+ if (size !== 0) {
2643
+ this.pushArrayState(size);
2644
+ this.complete();
2645
+ continue DECODE;
2646
+ }
2647
+ else {
2648
+ object = [];
2649
+ }
2650
+ }
2651
+ else {
2652
+ // fixstr (101x xxxx) 0xa0 - 0xbf
2653
+ var byteLength = headByte - 0xa0;
2654
+ object = this.decodeUtf8String(byteLength, 0);
2655
+ }
2656
+ }
2657
+ else if (headByte === 0xc0) {
2658
+ // nil
2659
+ object = null;
2660
+ }
2661
+ else if (headByte === 0xc2) {
2662
+ // false
2663
+ object = false;
2664
+ }
2665
+ else if (headByte === 0xc3) {
2666
+ // true
2667
+ object = true;
2668
+ }
2669
+ else if (headByte === 0xca) {
2670
+ // float 32
2671
+ object = this.readF32();
2672
+ }
2673
+ else if (headByte === 0xcb) {
2674
+ // float 64
2675
+ object = this.readF64();
2676
+ }
2677
+ else if (headByte === 0xcc) {
2678
+ // uint 8
2679
+ object = this.readU8();
2680
+ }
2681
+ else if (headByte === 0xcd) {
2682
+ // uint 16
2683
+ object = this.readU16();
2684
+ }
2685
+ else if (headByte === 0xce) {
2686
+ // uint 32
2687
+ object = this.readU32();
2688
+ }
2689
+ else if (headByte === 0xcf) {
2690
+ // uint 64
2691
+ object = this.readU64();
2692
+ }
2693
+ else if (headByte === 0xd0) {
2694
+ // int 8
2695
+ object = this.readI8();
2696
+ }
2697
+ else if (headByte === 0xd1) {
2698
+ // int 16
2699
+ object = this.readI16();
2700
+ }
2701
+ else if (headByte === 0xd2) {
2702
+ // int 32
2703
+ object = this.readI32();
2704
+ }
2705
+ else if (headByte === 0xd3) {
2706
+ // int 64
2707
+ object = this.readI64();
2708
+ }
2709
+ else if (headByte === 0xd9) {
2710
+ // str 8
2711
+ var byteLength = this.lookU8();
2712
+ object = this.decodeUtf8String(byteLength, 1);
2713
+ }
2714
+ else if (headByte === 0xda) {
2715
+ // str 16
2716
+ var byteLength = this.lookU16();
2717
+ object = this.decodeUtf8String(byteLength, 2);
2718
+ }
2719
+ else if (headByte === 0xdb) {
2720
+ // str 32
2721
+ var byteLength = this.lookU32();
2722
+ object = this.decodeUtf8String(byteLength, 4);
2723
+ }
2724
+ else if (headByte === 0xdc) {
2725
+ // array 16
2726
+ var size = this.readU16();
2727
+ if (size !== 0) {
2728
+ this.pushArrayState(size);
2729
+ this.complete();
2730
+ continue DECODE;
2731
+ }
2732
+ else {
2733
+ object = [];
2734
+ }
2735
+ }
2736
+ else if (headByte === 0xdd) {
2737
+ // array 32
2738
+ var size = this.readU32();
2739
+ if (size !== 0) {
2740
+ this.pushArrayState(size);
2741
+ this.complete();
2742
+ continue DECODE;
2743
+ }
2744
+ else {
2745
+ object = [];
2746
+ }
2747
+ }
2748
+ else if (headByte === 0xde) {
2749
+ // map 16
2750
+ var size = this.readU16();
2751
+ if (size !== 0) {
2752
+ this.pushMapState(size);
2753
+ this.complete();
2754
+ continue DECODE;
2755
+ }
2756
+ else {
2757
+ object = {};
2758
+ }
2759
+ }
2760
+ else if (headByte === 0xdf) {
2761
+ // map 32
2762
+ var size = this.readU32();
2763
+ if (size !== 0) {
2764
+ this.pushMapState(size);
2765
+ this.complete();
2766
+ continue DECODE;
2767
+ }
2768
+ else {
2769
+ object = {};
2770
+ }
2771
+ }
2772
+ else if (headByte === 0xc4) {
2773
+ // bin 8
2774
+ var size = this.lookU8();
2775
+ object = this.decodeBinary(size, 1);
2776
+ }
2777
+ else if (headByte === 0xc5) {
2778
+ // bin 16
2779
+ var size = this.lookU16();
2780
+ object = this.decodeBinary(size, 2);
2781
+ }
2782
+ else if (headByte === 0xc6) {
2783
+ // bin 32
2784
+ var size = this.lookU32();
2785
+ object = this.decodeBinary(size, 4);
2786
+ }
2787
+ else if (headByte === 0xd4) {
2788
+ // fixext 1
2789
+ object = this.decodeExtension(1, 0);
2790
+ }
2791
+ else if (headByte === 0xd5) {
2792
+ // fixext 2
2793
+ object = this.decodeExtension(2, 0);
2794
+ }
2795
+ else if (headByte === 0xd6) {
2796
+ // fixext 4
2797
+ object = this.decodeExtension(4, 0);
2798
+ }
2799
+ else if (headByte === 0xd7) {
2800
+ // fixext 8
2801
+ object = this.decodeExtension(8, 0);
2802
+ }
2803
+ else if (headByte === 0xd8) {
2804
+ // fixext 16
2805
+ object = this.decodeExtension(16, 0);
2806
+ }
2807
+ else if (headByte === 0xc7) {
2808
+ // ext 8
2809
+ var size = this.lookU8();
2810
+ object = this.decodeExtension(size, 1);
2811
+ }
2812
+ else if (headByte === 0xc8) {
2813
+ // ext 16
2814
+ var size = this.lookU16();
2815
+ object = this.decodeExtension(size, 2);
2816
+ }
2817
+ else if (headByte === 0xc9) {
2818
+ // ext 32
2819
+ var size = this.lookU32();
2820
+ object = this.decodeExtension(size, 4);
2821
+ }
2822
+ else {
2823
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Unrecognized type byte: ".concat((0,_utils_prettyByte_mjs__WEBPACK_IMPORTED_MODULE_4__.prettyByte)(headByte)));
2824
+ }
2825
+ this.complete();
2826
+ var stack = this.stack;
2827
+ while (stack.length > 0) {
2828
+ // arrays and maps
2829
+ var state = stack[stack.length - 1];
2830
+ if (state.type === 0 /* State.ARRAY */) {
2831
+ state.array[state.position] = object;
2832
+ state.position++;
2833
+ if (state.position === state.size) {
2834
+ stack.pop();
2835
+ object = state.array;
2836
+ }
2837
+ else {
2838
+ continue DECODE;
2839
+ }
2840
+ }
2841
+ else if (state.type === 1 /* State.MAP_KEY */) {
2842
+ if (!isValidMapKeyType(object)) {
2843
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("The type of key must be string or number but " + typeof object);
2844
+ }
2845
+ if (object === "__proto__") {
2846
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("The key __proto__ is not allowed");
2847
+ }
2848
+ state.key = object;
2849
+ state.type = 2 /* State.MAP_VALUE */;
2850
+ continue DECODE;
2851
+ }
2852
+ else {
2853
+ // it must be `state.type === State.MAP_VALUE` here
2854
+ state.map[state.key] = object;
2855
+ state.readCount++;
2856
+ if (state.readCount === state.size) {
2857
+ stack.pop();
2858
+ object = state.map;
2859
+ }
2860
+ else {
2861
+ state.key = null;
2862
+ state.type = 1 /* State.MAP_KEY */;
2863
+ continue DECODE;
2864
+ }
2865
+ }
2866
+ }
2867
+ return object;
2868
+ }
2869
+ };
2870
+ Decoder.prototype.readHeadByte = function () {
2871
+ if (this.headByte === HEAD_BYTE_REQUIRED) {
2872
+ this.headByte = this.readU8();
2873
+ // console.log("headByte", prettyByte(this.headByte));
2874
+ }
2875
+ return this.headByte;
2876
+ };
2877
+ Decoder.prototype.complete = function () {
2878
+ this.headByte = HEAD_BYTE_REQUIRED;
2879
+ };
2880
+ Decoder.prototype.readArraySize = function () {
2881
+ var headByte = this.readHeadByte();
2882
+ switch (headByte) {
2883
+ case 0xdc:
2884
+ return this.readU16();
2885
+ case 0xdd:
2886
+ return this.readU32();
2887
+ default: {
2888
+ if (headByte < 0xa0) {
2889
+ return headByte - 0x90;
2890
+ }
2891
+ else {
2892
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Unrecognized array type byte: ".concat((0,_utils_prettyByte_mjs__WEBPACK_IMPORTED_MODULE_4__.prettyByte)(headByte)));
2893
+ }
2894
+ }
2895
+ }
2896
+ };
2897
+ Decoder.prototype.pushMapState = function (size) {
2898
+ if (size > this.maxMapLength) {
2899
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Max length exceeded: map length (".concat(size, ") > maxMapLengthLength (").concat(this.maxMapLength, ")"));
2900
+ }
2901
+ this.stack.push({
2902
+ type: 1 /* State.MAP_KEY */,
2903
+ size: size,
2904
+ key: null,
2905
+ readCount: 0,
2906
+ map: {},
2907
+ });
2908
+ };
2909
+ Decoder.prototype.pushArrayState = function (size) {
2910
+ if (size > this.maxArrayLength) {
2911
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Max length exceeded: array length (".concat(size, ") > maxArrayLength (").concat(this.maxArrayLength, ")"));
2912
+ }
2913
+ this.stack.push({
2914
+ type: 0 /* State.ARRAY */,
2915
+ size: size,
2916
+ array: new Array(size),
2917
+ position: 0,
2918
+ });
2919
+ };
2920
+ Decoder.prototype.decodeUtf8String = function (byteLength, headerOffset) {
2921
+ var _a;
2922
+ if (byteLength > this.maxStrLength) {
2923
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Max length exceeded: UTF-8 byte length (".concat(byteLength, ") > maxStrLength (").concat(this.maxStrLength, ")"));
2924
+ }
2925
+ if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {
2926
+ throw MORE_DATA;
2927
+ }
2928
+ var offset = this.pos + headerOffset;
2929
+ var object;
2930
+ if (this.stateIsMapKey() && ((_a = this.keyDecoder) === null || _a === void 0 ? void 0 : _a.canBeCached(byteLength))) {
2931
+ object = this.keyDecoder.decode(this.bytes, offset, byteLength);
2932
+ }
2933
+ else if (byteLength > _utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_6__.TEXT_DECODER_THRESHOLD) {
2934
+ object = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_6__.utf8DecodeTD)(this.bytes, offset, byteLength);
2935
+ }
2936
+ else {
2937
+ object = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_6__.utf8DecodeJs)(this.bytes, offset, byteLength);
2938
+ }
2939
+ this.pos += headerOffset + byteLength;
2940
+ return object;
2941
+ };
2942
+ Decoder.prototype.stateIsMapKey = function () {
2943
+ if (this.stack.length > 0) {
2944
+ var state = this.stack[this.stack.length - 1];
2945
+ return state.type === 1 /* State.MAP_KEY */;
2946
+ }
2947
+ return false;
2948
+ };
2949
+ Decoder.prototype.decodeBinary = function (byteLength, headOffset) {
2950
+ if (byteLength > this.maxBinLength) {
2951
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Max length exceeded: bin length (".concat(byteLength, ") > maxBinLength (").concat(this.maxBinLength, ")"));
2952
+ }
2953
+ if (!this.hasRemaining(byteLength + headOffset)) {
2954
+ throw MORE_DATA;
2955
+ }
2956
+ var offset = this.pos + headOffset;
2957
+ var object = this.bytes.subarray(offset, offset + byteLength);
2958
+ this.pos += headOffset + byteLength;
2959
+ return object;
2960
+ };
2961
+ Decoder.prototype.decodeExtension = function (size, headOffset) {
2962
+ if (size > this.maxExtLength) {
2963
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Max length exceeded: ext length (".concat(size, ") > maxExtLength (").concat(this.maxExtLength, ")"));
2964
+ }
2965
+ var extType = this.view.getInt8(this.pos + headOffset);
2966
+ var data = this.decodeBinary(size, headOffset + 1 /* extType */);
2967
+ return this.extensionCodec.decode(data, extType, this.context);
2968
+ };
2969
+ Decoder.prototype.lookU8 = function () {
2970
+ return this.view.getUint8(this.pos);
2971
+ };
2972
+ Decoder.prototype.lookU16 = function () {
2973
+ return this.view.getUint16(this.pos);
2974
+ };
2975
+ Decoder.prototype.lookU32 = function () {
2976
+ return this.view.getUint32(this.pos);
2977
+ };
2978
+ Decoder.prototype.readU8 = function () {
2979
+ var value = this.view.getUint8(this.pos);
2980
+ this.pos++;
2981
+ return value;
2982
+ };
2983
+ Decoder.prototype.readI8 = function () {
2984
+ var value = this.view.getInt8(this.pos);
2985
+ this.pos++;
2986
+ return value;
2987
+ };
2988
+ Decoder.prototype.readU16 = function () {
2989
+ var value = this.view.getUint16(this.pos);
2990
+ this.pos += 2;
2991
+ return value;
2992
+ };
2993
+ Decoder.prototype.readI16 = function () {
2994
+ var value = this.view.getInt16(this.pos);
2995
+ this.pos += 2;
2996
+ return value;
2997
+ };
2998
+ Decoder.prototype.readU32 = function () {
2999
+ var value = this.view.getUint32(this.pos);
3000
+ this.pos += 4;
3001
+ return value;
3002
+ };
3003
+ Decoder.prototype.readI32 = function () {
3004
+ var value = this.view.getInt32(this.pos);
3005
+ this.pos += 4;
3006
+ return value;
3007
+ };
3008
+ Decoder.prototype.readU64 = function () {
3009
+ var value = (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.getUint64)(this.view, this.pos);
3010
+ this.pos += 8;
3011
+ return value;
3012
+ };
3013
+ Decoder.prototype.readI64 = function () {
3014
+ var value = (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.getInt64)(this.view, this.pos);
3015
+ this.pos += 8;
3016
+ return value;
3017
+ };
3018
+ Decoder.prototype.readF32 = function () {
3019
+ var value = this.view.getFloat32(this.pos);
3020
+ this.pos += 4;
3021
+ return value;
3022
+ };
3023
+ Decoder.prototype.readF64 = function () {
3024
+ var value = this.view.getFloat64(this.pos);
3025
+ this.pos += 8;
3026
+ return value;
3027
+ };
3028
+ return Decoder;
3029
+ }());
3030
+
3031
+ //# sourceMappingURL=Decoder.mjs.map
3032
+
3033
+ /***/ }),
3034
+
3035
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs":
3036
+ /*!****************************************************************!*\
3037
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs ***!
3038
+ \****************************************************************/
3039
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3040
+
3041
+ __webpack_require__.r(__webpack_exports__);
3042
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3043
+ /* harmony export */ DEFAULT_INITIAL_BUFFER_SIZE: () => (/* binding */ DEFAULT_INITIAL_BUFFER_SIZE),
3044
+ /* harmony export */ DEFAULT_MAX_DEPTH: () => (/* binding */ DEFAULT_MAX_DEPTH),
3045
+ /* harmony export */ Encoder: () => (/* binding */ Encoder)
3046
+ /* harmony export */ });
3047
+ /* harmony import */ var _utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/utf8.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs");
3048
+ /* harmony import */ var _ExtensionCodec_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ExtensionCodec.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs");
3049
+ /* harmony import */ var _utils_int_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/int.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs");
3050
+ /* harmony import */ var _utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/typedArrays.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs");
3051
+
3052
+
3053
+
3054
+
3055
+ var DEFAULT_MAX_DEPTH = 100;
3056
+ var DEFAULT_INITIAL_BUFFER_SIZE = 2048;
3057
+ var Encoder = /** @class */ (function () {
3058
+ function Encoder(extensionCodec, context, maxDepth, initialBufferSize, sortKeys, forceFloat32, ignoreUndefined, forceIntegerToFloat) {
3059
+ if (extensionCodec === void 0) { extensionCodec = _ExtensionCodec_mjs__WEBPACK_IMPORTED_MODULE_0__.ExtensionCodec.defaultCodec; }
3060
+ if (context === void 0) { context = undefined; }
3061
+ if (maxDepth === void 0) { maxDepth = DEFAULT_MAX_DEPTH; }
3062
+ if (initialBufferSize === void 0) { initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE; }
3063
+ if (sortKeys === void 0) { sortKeys = false; }
3064
+ if (forceFloat32 === void 0) { forceFloat32 = false; }
3065
+ if (ignoreUndefined === void 0) { ignoreUndefined = false; }
3066
+ if (forceIntegerToFloat === void 0) { forceIntegerToFloat = false; }
3067
+ this.extensionCodec = extensionCodec;
3068
+ this.context = context;
3069
+ this.maxDepth = maxDepth;
3070
+ this.initialBufferSize = initialBufferSize;
3071
+ this.sortKeys = sortKeys;
3072
+ this.forceFloat32 = forceFloat32;
3073
+ this.ignoreUndefined = ignoreUndefined;
3074
+ this.forceIntegerToFloat = forceIntegerToFloat;
3075
+ this.pos = 0;
3076
+ this.view = new DataView(new ArrayBuffer(this.initialBufferSize));
3077
+ this.bytes = new Uint8Array(this.view.buffer);
3078
+ }
3079
+ Encoder.prototype.reinitializeState = function () {
3080
+ this.pos = 0;
3081
+ };
3082
+ /**
3083
+ * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.
3084
+ *
3085
+ * @returns Encodes the object and returns a shared reference the encoder's internal buffer.
3086
+ */
3087
+ Encoder.prototype.encodeSharedRef = function (object) {
3088
+ this.reinitializeState();
3089
+ this.doEncode(object, 1);
3090
+ return this.bytes.subarray(0, this.pos);
3091
+ };
3092
+ /**
3093
+ * @returns Encodes the object and returns a copy of the encoder's internal buffer.
3094
+ */
3095
+ Encoder.prototype.encode = function (object) {
3096
+ this.reinitializeState();
3097
+ this.doEncode(object, 1);
3098
+ return this.bytes.slice(0, this.pos);
3099
+ };
3100
+ Encoder.prototype.doEncode = function (object, depth) {
3101
+ if (depth > this.maxDepth) {
3102
+ throw new Error("Too deep objects in depth ".concat(depth));
3103
+ }
3104
+ if (object == null) {
3105
+ this.encodeNil();
3106
+ }
3107
+ else if (typeof object === "boolean") {
3108
+ this.encodeBoolean(object);
3109
+ }
3110
+ else if (typeof object === "number") {
3111
+ this.encodeNumber(object);
3112
+ }
3113
+ else if (typeof object === "string") {
3114
+ this.encodeString(object);
3115
+ }
3116
+ else {
3117
+ this.encodeObject(object, depth);
3118
+ }
3119
+ };
3120
+ Encoder.prototype.ensureBufferSizeToWrite = function (sizeToWrite) {
3121
+ var requiredSize = this.pos + sizeToWrite;
3122
+ if (this.view.byteLength < requiredSize) {
3123
+ this.resizeBuffer(requiredSize * 2);
3124
+ }
3125
+ };
3126
+ Encoder.prototype.resizeBuffer = function (newSize) {
3127
+ var newBuffer = new ArrayBuffer(newSize);
3128
+ var newBytes = new Uint8Array(newBuffer);
3129
+ var newView = new DataView(newBuffer);
3130
+ newBytes.set(this.bytes);
3131
+ this.view = newView;
3132
+ this.bytes = newBytes;
3133
+ };
3134
+ Encoder.prototype.encodeNil = function () {
3135
+ this.writeU8(0xc0);
3136
+ };
3137
+ Encoder.prototype.encodeBoolean = function (object) {
3138
+ if (object === false) {
3139
+ this.writeU8(0xc2);
3140
+ }
3141
+ else {
3142
+ this.writeU8(0xc3);
3143
+ }
3144
+ };
3145
+ Encoder.prototype.encodeNumber = function (object) {
3146
+ if (Number.isSafeInteger(object) && !this.forceIntegerToFloat) {
3147
+ if (object >= 0) {
3148
+ if (object < 0x80) {
3149
+ // positive fixint
3150
+ this.writeU8(object);
3151
+ }
3152
+ else if (object < 0x100) {
3153
+ // uint 8
3154
+ this.writeU8(0xcc);
3155
+ this.writeU8(object);
3156
+ }
3157
+ else if (object < 0x10000) {
3158
+ // uint 16
3159
+ this.writeU8(0xcd);
3160
+ this.writeU16(object);
3161
+ }
3162
+ else if (object < 0x100000000) {
3163
+ // uint 32
3164
+ this.writeU8(0xce);
3165
+ this.writeU32(object);
3166
+ }
3167
+ else {
3168
+ // uint 64
3169
+ this.writeU8(0xcf);
3170
+ this.writeU64(object);
3171
+ }
3172
+ }
3173
+ else {
3174
+ if (object >= -0x20) {
3175
+ // negative fixint
3176
+ this.writeU8(0xe0 | (object + 0x20));
3177
+ }
3178
+ else if (object >= -0x80) {
3179
+ // int 8
3180
+ this.writeU8(0xd0);
3181
+ this.writeI8(object);
3182
+ }
3183
+ else if (object >= -0x8000) {
3184
+ // int 16
3185
+ this.writeU8(0xd1);
3186
+ this.writeI16(object);
3187
+ }
3188
+ else if (object >= -0x80000000) {
3189
+ // int 32
3190
+ this.writeU8(0xd2);
3191
+ this.writeI32(object);
3192
+ }
3193
+ else {
3194
+ // int 64
3195
+ this.writeU8(0xd3);
3196
+ this.writeI64(object);
3197
+ }
3198
+ }
3199
+ }
3200
+ else {
3201
+ // non-integer numbers
3202
+ if (this.forceFloat32) {
3203
+ // float 32
3204
+ this.writeU8(0xca);
3205
+ this.writeF32(object);
3206
+ }
3207
+ else {
3208
+ // float 64
3209
+ this.writeU8(0xcb);
3210
+ this.writeF64(object);
3211
+ }
3212
+ }
3213
+ };
3214
+ Encoder.prototype.writeStringHeader = function (byteLength) {
3215
+ if (byteLength < 32) {
3216
+ // fixstr
3217
+ this.writeU8(0xa0 + byteLength);
3218
+ }
3219
+ else if (byteLength < 0x100) {
3220
+ // str 8
3221
+ this.writeU8(0xd9);
3222
+ this.writeU8(byteLength);
3223
+ }
3224
+ else if (byteLength < 0x10000) {
3225
+ // str 16
3226
+ this.writeU8(0xda);
3227
+ this.writeU16(byteLength);
3228
+ }
3229
+ else if (byteLength < 0x100000000) {
3230
+ // str 32
3231
+ this.writeU8(0xdb);
3232
+ this.writeU32(byteLength);
3233
+ }
3234
+ else {
3235
+ throw new Error("Too long string: ".concat(byteLength, " bytes in UTF-8"));
3236
+ }
3237
+ };
3238
+ Encoder.prototype.encodeString = function (object) {
3239
+ var maxHeaderSize = 1 + 4;
3240
+ var strLength = object.length;
3241
+ if (strLength > _utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.TEXT_ENCODER_THRESHOLD) {
3242
+ var byteLength = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.utf8Count)(object);
3243
+ this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
3244
+ this.writeStringHeader(byteLength);
3245
+ (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.utf8EncodeTE)(object, this.bytes, this.pos);
3246
+ this.pos += byteLength;
3247
+ }
3248
+ else {
3249
+ var byteLength = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.utf8Count)(object);
3250
+ this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
3251
+ this.writeStringHeader(byteLength);
3252
+ (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.utf8EncodeJs)(object, this.bytes, this.pos);
3253
+ this.pos += byteLength;
3254
+ }
3255
+ };
3256
+ Encoder.prototype.encodeObject = function (object, depth) {
3257
+ // try to encode objects with custom codec first of non-primitives
3258
+ var ext = this.extensionCodec.tryToEncode(object, this.context);
3259
+ if (ext != null) {
3260
+ this.encodeExtension(ext);
3261
+ }
3262
+ else if (Array.isArray(object)) {
3263
+ this.encodeArray(object, depth);
3264
+ }
3265
+ else if (ArrayBuffer.isView(object)) {
3266
+ this.encodeBinary(object);
3267
+ }
3268
+ else if (typeof object === "object") {
3269
+ this.encodeMap(object, depth);
3270
+ }
3271
+ else {
3272
+ // symbol, function and other special object come here unless extensionCodec handles them.
3273
+ throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(object)));
3274
+ }
3275
+ };
3276
+ Encoder.prototype.encodeBinary = function (object) {
3277
+ var size = object.byteLength;
3278
+ if (size < 0x100) {
3279
+ // bin 8
3280
+ this.writeU8(0xc4);
3281
+ this.writeU8(size);
3282
+ }
3283
+ else if (size < 0x10000) {
3284
+ // bin 16
3285
+ this.writeU8(0xc5);
3286
+ this.writeU16(size);
3287
+ }
3288
+ else if (size < 0x100000000) {
3289
+ // bin 32
3290
+ this.writeU8(0xc6);
3291
+ this.writeU32(size);
3292
+ }
3293
+ else {
3294
+ throw new Error("Too large binary: ".concat(size));
3295
+ }
3296
+ var bytes = (0,_utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_2__.ensureUint8Array)(object);
3297
+ this.writeU8a(bytes);
3298
+ };
3299
+ Encoder.prototype.encodeArray = function (object, depth) {
3300
+ var size = object.length;
3301
+ if (size < 16) {
3302
+ // fixarray
3303
+ this.writeU8(0x90 + size);
3304
+ }
3305
+ else if (size < 0x10000) {
3306
+ // array 16
3307
+ this.writeU8(0xdc);
3308
+ this.writeU16(size);
3309
+ }
3310
+ else if (size < 0x100000000) {
3311
+ // array 32
3312
+ this.writeU8(0xdd);
3313
+ this.writeU32(size);
3314
+ }
3315
+ else {
3316
+ throw new Error("Too large array: ".concat(size));
3317
+ }
3318
+ for (var _i = 0, object_1 = object; _i < object_1.length; _i++) {
3319
+ var item = object_1[_i];
3320
+ this.doEncode(item, depth + 1);
3321
+ }
3322
+ };
3323
+ Encoder.prototype.countWithoutUndefined = function (object, keys) {
3324
+ var count = 0;
3325
+ for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
3326
+ var key = keys_1[_i];
3327
+ if (object[key] !== undefined) {
3328
+ count++;
3329
+ }
3330
+ }
3331
+ return count;
3332
+ };
3333
+ Encoder.prototype.encodeMap = function (object, depth) {
3334
+ var keys = Object.keys(object);
3335
+ if (this.sortKeys) {
3336
+ keys.sort();
3337
+ }
3338
+ var size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
3339
+ if (size < 16) {
3340
+ // fixmap
3341
+ this.writeU8(0x80 + size);
3342
+ }
3343
+ else if (size < 0x10000) {
3344
+ // map 16
3345
+ this.writeU8(0xde);
3346
+ this.writeU16(size);
3347
+ }
3348
+ else if (size < 0x100000000) {
3349
+ // map 32
3350
+ this.writeU8(0xdf);
3351
+ this.writeU32(size);
3352
+ }
3353
+ else {
3354
+ throw new Error("Too large map object: ".concat(size));
3355
+ }
3356
+ for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) {
3357
+ var key = keys_2[_i];
3358
+ var value = object[key];
3359
+ if (!(this.ignoreUndefined && value === undefined)) {
3360
+ this.encodeString(key);
3361
+ this.doEncode(value, depth + 1);
3362
+ }
3363
+ }
3364
+ };
3365
+ Encoder.prototype.encodeExtension = function (ext) {
3366
+ var size = ext.data.length;
3367
+ if (size === 1) {
3368
+ // fixext 1
3369
+ this.writeU8(0xd4);
3370
+ }
3371
+ else if (size === 2) {
3372
+ // fixext 2
3373
+ this.writeU8(0xd5);
3374
+ }
3375
+ else if (size === 4) {
3376
+ // fixext 4
3377
+ this.writeU8(0xd6);
3378
+ }
3379
+ else if (size === 8) {
3380
+ // fixext 8
3381
+ this.writeU8(0xd7);
3382
+ }
3383
+ else if (size === 16) {
3384
+ // fixext 16
3385
+ this.writeU8(0xd8);
3386
+ }
3387
+ else if (size < 0x100) {
3388
+ // ext 8
3389
+ this.writeU8(0xc7);
3390
+ this.writeU8(size);
3391
+ }
3392
+ else if (size < 0x10000) {
3393
+ // ext 16
3394
+ this.writeU8(0xc8);
3395
+ this.writeU16(size);
3396
+ }
3397
+ else if (size < 0x100000000) {
3398
+ // ext 32
3399
+ this.writeU8(0xc9);
3400
+ this.writeU32(size);
3401
+ }
3402
+ else {
3403
+ throw new Error("Too large extension object: ".concat(size));
3404
+ }
3405
+ this.writeI8(ext.type);
3406
+ this.writeU8a(ext.data);
3407
+ };
3408
+ Encoder.prototype.writeU8 = function (value) {
3409
+ this.ensureBufferSizeToWrite(1);
3410
+ this.view.setUint8(this.pos, value);
3411
+ this.pos++;
3412
+ };
3413
+ Encoder.prototype.writeU8a = function (values) {
3414
+ var size = values.length;
3415
+ this.ensureBufferSizeToWrite(size);
3416
+ this.bytes.set(values, this.pos);
3417
+ this.pos += size;
3418
+ };
3419
+ Encoder.prototype.writeI8 = function (value) {
3420
+ this.ensureBufferSizeToWrite(1);
3421
+ this.view.setInt8(this.pos, value);
3422
+ this.pos++;
3423
+ };
3424
+ Encoder.prototype.writeU16 = function (value) {
3425
+ this.ensureBufferSizeToWrite(2);
3426
+ this.view.setUint16(this.pos, value);
3427
+ this.pos += 2;
3428
+ };
3429
+ Encoder.prototype.writeI16 = function (value) {
3430
+ this.ensureBufferSizeToWrite(2);
3431
+ this.view.setInt16(this.pos, value);
3432
+ this.pos += 2;
3433
+ };
3434
+ Encoder.prototype.writeU32 = function (value) {
3435
+ this.ensureBufferSizeToWrite(4);
3436
+ this.view.setUint32(this.pos, value);
3437
+ this.pos += 4;
3438
+ };
3439
+ Encoder.prototype.writeI32 = function (value) {
3440
+ this.ensureBufferSizeToWrite(4);
3441
+ this.view.setInt32(this.pos, value);
3442
+ this.pos += 4;
3443
+ };
3444
+ Encoder.prototype.writeF32 = function (value) {
3445
+ this.ensureBufferSizeToWrite(4);
3446
+ this.view.setFloat32(this.pos, value);
3447
+ this.pos += 4;
3448
+ };
3449
+ Encoder.prototype.writeF64 = function (value) {
3450
+ this.ensureBufferSizeToWrite(8);
3451
+ this.view.setFloat64(this.pos, value);
3452
+ this.pos += 8;
3453
+ };
3454
+ Encoder.prototype.writeU64 = function (value) {
3455
+ this.ensureBufferSizeToWrite(8);
3456
+ (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_3__.setUint64)(this.view, this.pos, value);
3457
+ this.pos += 8;
3458
+ };
3459
+ Encoder.prototype.writeI64 = function (value) {
3460
+ this.ensureBufferSizeToWrite(8);
3461
+ (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_3__.setInt64)(this.view, this.pos, value);
3462
+ this.pos += 8;
3463
+ };
3464
+ return Encoder;
3465
+ }());
3466
+
3467
+ //# sourceMappingURL=Encoder.mjs.map
3468
+
3469
+ /***/ }),
3470
+
3471
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs":
3472
+ /*!****************************************************************!*\
3473
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs ***!
3474
+ \****************************************************************/
3475
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3476
+
3477
+ __webpack_require__.r(__webpack_exports__);
3478
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3479
+ /* harmony export */ ExtData: () => (/* binding */ ExtData)
3480
+ /* harmony export */ });
3481
+ /**
3482
+ * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.
3483
+ */
3484
+ var ExtData = /** @class */ (function () {
3485
+ function ExtData(type, data) {
3486
+ this.type = type;
3487
+ this.data = data;
3488
+ }
3489
+ return ExtData;
3490
+ }());
3491
+
3492
+ //# sourceMappingURL=ExtData.mjs.map
3493
+
3494
+ /***/ }),
3495
+
3496
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs":
3497
+ /*!***********************************************************************!*\
3498
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs ***!
3499
+ \***********************************************************************/
3500
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3501
+
3502
+ __webpack_require__.r(__webpack_exports__);
3503
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3504
+ /* harmony export */ ExtensionCodec: () => (/* binding */ ExtensionCodec)
3505
+ /* harmony export */ });
3506
+ /* harmony import */ var _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ExtData.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs");
3507
+ /* harmony import */ var _timestamp_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./timestamp.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs");
3508
+ // ExtensionCodec to handle MessagePack extensions
3509
+
3510
+
3511
+ var ExtensionCodec = /** @class */ (function () {
3512
+ function ExtensionCodec() {
3513
+ // built-in extensions
3514
+ this.builtInEncoders = [];
3515
+ this.builtInDecoders = [];
3516
+ // custom extensions
3517
+ this.encoders = [];
3518
+ this.decoders = [];
3519
+ this.register(_timestamp_mjs__WEBPACK_IMPORTED_MODULE_0__.timestampExtension);
3520
+ }
3521
+ ExtensionCodec.prototype.register = function (_a) {
3522
+ var type = _a.type, encode = _a.encode, decode = _a.decode;
3523
+ if (type >= 0) {
3524
+ // custom extensions
3525
+ this.encoders[type] = encode;
3526
+ this.decoders[type] = decode;
3527
+ }
3528
+ else {
3529
+ // built-in extensions
3530
+ var index = 1 + type;
3531
+ this.builtInEncoders[index] = encode;
3532
+ this.builtInDecoders[index] = decode;
3533
+ }
3534
+ };
3535
+ ExtensionCodec.prototype.tryToEncode = function (object, context) {
3536
+ // built-in extensions
3537
+ for (var i = 0; i < this.builtInEncoders.length; i++) {
3538
+ var encodeExt = this.builtInEncoders[i];
3539
+ if (encodeExt != null) {
3540
+ var data = encodeExt(object, context);
3541
+ if (data != null) {
3542
+ var type = -1 - i;
3543
+ return new _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData(type, data);
3544
+ }
3545
+ }
3546
+ }
3547
+ // custom extensions
3548
+ for (var i = 0; i < this.encoders.length; i++) {
3549
+ var encodeExt = this.encoders[i];
3550
+ if (encodeExt != null) {
3551
+ var data = encodeExt(object, context);
3552
+ if (data != null) {
3553
+ var type = i;
3554
+ return new _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData(type, data);
3555
+ }
3556
+ }
3557
+ }
3558
+ if (object instanceof _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData) {
3559
+ // to keep ExtData as is
3560
+ return object;
3561
+ }
3562
+ return null;
3563
+ };
3564
+ ExtensionCodec.prototype.decode = function (data, type, context) {
3565
+ var decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
3566
+ if (decodeExt) {
3567
+ return decodeExt(data, type, context);
3568
+ }
3569
+ else {
3570
+ // decode() does not fail, returns ExtData instead.
3571
+ return new _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData(type, data);
3572
+ }
3573
+ };
3574
+ ExtensionCodec.defaultCodec = new ExtensionCodec();
3575
+ return ExtensionCodec;
3576
+ }());
3577
+
3578
+ //# sourceMappingURL=ExtensionCodec.mjs.map
3579
+
3580
+ /***/ }),
3581
+
3582
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs":
3583
+ /*!***************************************************************!*\
3584
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs ***!
3585
+ \***************************************************************/
3586
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3587
+
3588
+ __webpack_require__.r(__webpack_exports__);
3589
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3590
+ /* harmony export */ decode: () => (/* binding */ decode),
3591
+ /* harmony export */ decodeMulti: () => (/* binding */ decodeMulti),
3592
+ /* harmony export */ defaultDecodeOptions: () => (/* binding */ defaultDecodeOptions)
3593
+ /* harmony export */ });
3594
+ /* harmony import */ var _Decoder_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Decoder.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs");
3595
+
3596
+ var defaultDecodeOptions = {};
3597
+ /**
3598
+ * It decodes a single MessagePack object in a buffer.
3599
+ *
3600
+ * This is a synchronous decoding function.
3601
+ * See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.
3602
+ *
3603
+ * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.
3604
+ * @throws {@link DecodeError} if the buffer contains invalid data.
3605
+ */
3606
+ function decode(buffer, options) {
3607
+ if (options === void 0) { options = defaultDecodeOptions; }
3608
+ var decoder = new _Decoder_mjs__WEBPACK_IMPORTED_MODULE_0__.Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
3609
+ return decoder.decode(buffer);
3610
+ }
3611
+ /**
3612
+ * It decodes multiple MessagePack objects in a buffer.
3613
+ * This is corresponding to {@link decodeMultiStream()}.
3614
+ *
3615
+ * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.
3616
+ * @throws {@link DecodeError} if the buffer contains invalid data.
3617
+ */
3618
+ function decodeMulti(buffer, options) {
3619
+ if (options === void 0) { options = defaultDecodeOptions; }
3620
+ var decoder = new _Decoder_mjs__WEBPACK_IMPORTED_MODULE_0__.Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
3621
+ return decoder.decodeMulti(buffer);
3622
+ }
3623
+ //# sourceMappingURL=decode.mjs.map
3624
+
3625
+ /***/ }),
3626
+
3627
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs":
3628
+ /*!***************************************************************!*\
3629
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs ***!
3630
+ \***************************************************************/
3631
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3632
+
3633
+ __webpack_require__.r(__webpack_exports__);
3634
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3635
+ /* harmony export */ encode: () => (/* binding */ encode)
3636
+ /* harmony export */ });
3637
+ /* harmony import */ var _Encoder_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Encoder.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs");
3638
+
3639
+ var defaultEncodeOptions = {};
3640
+ /**
3641
+ * It encodes `value` in the MessagePack format and
3642
+ * returns a byte buffer.
3643
+ *
3644
+ * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.
3645
+ */
3646
+ function encode(value, options) {
3647
+ if (options === void 0) { options = defaultEncodeOptions; }
3648
+ var encoder = new _Encoder_mjs__WEBPACK_IMPORTED_MODULE_0__.Encoder(options.extensionCodec, options.context, options.maxDepth, options.initialBufferSize, options.sortKeys, options.forceFloat32, options.ignoreUndefined, options.forceIntegerToFloat);
3649
+ return encoder.encodeSharedRef(value);
3650
+ }
3651
+ //# sourceMappingURL=encode.mjs.map
3652
+
3653
+ /***/ }),
3654
+
3655
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs":
3656
+ /*!******************************************************************!*\
3657
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs ***!
3658
+ \******************************************************************/
3659
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3660
+
3661
+ __webpack_require__.r(__webpack_exports__);
3662
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3663
+ /* harmony export */ EXT_TIMESTAMP: () => (/* binding */ EXT_TIMESTAMP),
3664
+ /* harmony export */ decodeTimestampExtension: () => (/* binding */ decodeTimestampExtension),
3665
+ /* harmony export */ decodeTimestampToTimeSpec: () => (/* binding */ decodeTimestampToTimeSpec),
3666
+ /* harmony export */ encodeDateToTimeSpec: () => (/* binding */ encodeDateToTimeSpec),
3667
+ /* harmony export */ encodeTimeSpecToTimestamp: () => (/* binding */ encodeTimeSpecToTimestamp),
3668
+ /* harmony export */ encodeTimestampExtension: () => (/* binding */ encodeTimestampExtension),
3669
+ /* harmony export */ timestampExtension: () => (/* binding */ timestampExtension)
3670
+ /* harmony export */ });
3671
+ /* harmony import */ var _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DecodeError.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs");
3672
+ /* harmony import */ var _utils_int_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/int.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs");
3673
+ // https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
3674
+
3675
+
3676
+ var EXT_TIMESTAMP = -1;
3677
+ var TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int
3678
+ var TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int
3679
+ function encodeTimeSpecToTimestamp(_a) {
3680
+ var sec = _a.sec, nsec = _a.nsec;
3681
+ if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
3682
+ // Here sec >= 0 && nsec >= 0
3683
+ if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
3684
+ // timestamp 32 = { sec32 (unsigned) }
3685
+ var rv = new Uint8Array(4);
3686
+ var view = new DataView(rv.buffer);
3687
+ view.setUint32(0, sec);
3688
+ return rv;
3689
+ }
3690
+ else {
3691
+ // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }
3692
+ var secHigh = sec / 0x100000000;
3693
+ var secLow = sec & 0xffffffff;
3694
+ var rv = new Uint8Array(8);
3695
+ var view = new DataView(rv.buffer);
3696
+ // nsec30 | secHigh2
3697
+ view.setUint32(0, (nsec << 2) | (secHigh & 0x3));
3698
+ // secLow32
3699
+ view.setUint32(4, secLow);
3700
+ return rv;
3701
+ }
3702
+ }
3703
+ else {
3704
+ // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
3705
+ var rv = new Uint8Array(12);
3706
+ var view = new DataView(rv.buffer);
3707
+ view.setUint32(0, nsec);
3708
+ (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_0__.setInt64)(view, 4, sec);
3709
+ return rv;
3710
+ }
3711
+ }
3712
+ function encodeDateToTimeSpec(date) {
3713
+ var msec = date.getTime();
3714
+ var sec = Math.floor(msec / 1e3);
3715
+ var nsec = (msec - sec * 1e3) * 1e6;
3716
+ // Normalizes { sec, nsec } to ensure nsec is unsigned.
3717
+ var nsecInSec = Math.floor(nsec / 1e9);
3718
+ return {
3719
+ sec: sec + nsecInSec,
3720
+ nsec: nsec - nsecInSec * 1e9,
3721
+ };
3722
+ }
3723
+ function encodeTimestampExtension(object) {
3724
+ if (object instanceof Date) {
3725
+ var timeSpec = encodeDateToTimeSpec(object);
3726
+ return encodeTimeSpecToTimestamp(timeSpec);
3727
+ }
3728
+ else {
3729
+ return null;
3730
+ }
3731
+ }
3732
+ function decodeTimestampToTimeSpec(data) {
3733
+ var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
3734
+ // data may be 32, 64, or 96 bits
3735
+ switch (data.byteLength) {
3736
+ case 4: {
3737
+ // timestamp 32 = { sec32 }
3738
+ var sec = view.getUint32(0);
3739
+ var nsec = 0;
3740
+ return { sec: sec, nsec: nsec };
3741
+ }
3742
+ case 8: {
3743
+ // timestamp 64 = { nsec30, sec34 }
3744
+ var nsec30AndSecHigh2 = view.getUint32(0);
3745
+ var secLow32 = view.getUint32(4);
3746
+ var sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;
3747
+ var nsec = nsec30AndSecHigh2 >>> 2;
3748
+ return { sec: sec, nsec: nsec };
3749
+ }
3750
+ case 12: {
3751
+ // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
3752
+ var sec = (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_0__.getInt64)(view, 4);
3753
+ var nsec = view.getUint32(0);
3754
+ return { sec: sec, nsec: nsec };
3755
+ }
3756
+ default:
3757
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_1__.DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(data.length));
3758
+ }
3759
+ }
3760
+ function decodeTimestampExtension(data) {
3761
+ var timeSpec = decodeTimestampToTimeSpec(data);
3762
+ return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
3763
+ }
3764
+ var timestampExtension = {
3765
+ type: EXT_TIMESTAMP,
3766
+ encode: encodeTimestampExtension,
3767
+ decode: decodeTimestampExtension,
3768
+ };
3769
+ //# sourceMappingURL=timestamp.mjs.map
3770
+
3771
+ /***/ }),
3772
+
3773
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs":
3774
+ /*!******************************************************************!*\
3775
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs ***!
3776
+ \******************************************************************/
3777
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3778
+
3779
+ __webpack_require__.r(__webpack_exports__);
3780
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3781
+ /* harmony export */ UINT32_MAX: () => (/* binding */ UINT32_MAX),
3782
+ /* harmony export */ getInt64: () => (/* binding */ getInt64),
3783
+ /* harmony export */ getUint64: () => (/* binding */ getUint64),
3784
+ /* harmony export */ setInt64: () => (/* binding */ setInt64),
3785
+ /* harmony export */ setUint64: () => (/* binding */ setUint64)
3786
+ /* harmony export */ });
3787
+ // Integer Utility
3788
+ var UINT32_MAX = 4294967295;
3789
+ // DataView extension to handle int64 / uint64,
3790
+ // where the actual range is 53-bits integer (a.k.a. safe integer)
3791
+ function setUint64(view, offset, value) {
3792
+ var high = value / 4294967296;
3793
+ var low = value; // high bits are truncated by DataView
3794
+ view.setUint32(offset, high);
3795
+ view.setUint32(offset + 4, low);
3796
+ }
3797
+ function setInt64(view, offset, value) {
3798
+ var high = Math.floor(value / 4294967296);
3799
+ var low = value; // high bits are truncated by DataView
3800
+ view.setUint32(offset, high);
3801
+ view.setUint32(offset + 4, low);
3802
+ }
3803
+ function getInt64(view, offset) {
3804
+ var high = view.getInt32(offset);
3805
+ var low = view.getUint32(offset + 4);
3806
+ return high * 4294967296 + low;
3807
+ }
3808
+ function getUint64(view, offset) {
3809
+ var high = view.getUint32(offset);
3810
+ var low = view.getUint32(offset + 4);
3811
+ return high * 4294967296 + low;
3812
+ }
3813
+ //# sourceMappingURL=int.mjs.map
3814
+
3815
+ /***/ }),
3816
+
3817
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs":
3818
+ /*!*************************************************************************!*\
3819
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs ***!
3820
+ \*************************************************************************/
3821
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3822
+
3823
+ __webpack_require__.r(__webpack_exports__);
3824
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3825
+ /* harmony export */ prettyByte: () => (/* binding */ prettyByte)
3826
+ /* harmony export */ });
3827
+ function prettyByte(byte) {
3828
+ return "".concat(byte < 0 ? "-" : "", "0x").concat(Math.abs(byte).toString(16).padStart(2, "0"));
3829
+ }
3830
+ //# sourceMappingURL=prettyByte.mjs.map
3831
+
3832
+ /***/ }),
3833
+
3834
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs":
3835
+ /*!**************************************************************************!*\
3836
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs ***!
3837
+ \**************************************************************************/
3838
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3839
+
3840
+ __webpack_require__.r(__webpack_exports__);
3841
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3842
+ /* harmony export */ createDataView: () => (/* binding */ createDataView),
3843
+ /* harmony export */ ensureUint8Array: () => (/* binding */ ensureUint8Array)
3844
+ /* harmony export */ });
3845
+ function ensureUint8Array(buffer) {
3846
+ if (buffer instanceof Uint8Array) {
3847
+ return buffer;
3848
+ }
3849
+ else if (ArrayBuffer.isView(buffer)) {
3850
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
3851
+ }
3852
+ else if (buffer instanceof ArrayBuffer) {
3853
+ return new Uint8Array(buffer);
3854
+ }
3855
+ else {
3856
+ // ArrayLike<number>
3857
+ return Uint8Array.from(buffer);
3858
+ }
3859
+ }
3860
+ function createDataView(buffer) {
3861
+ if (buffer instanceof ArrayBuffer) {
3862
+ return new DataView(buffer);
3863
+ }
3864
+ var bufferView = ensureUint8Array(buffer);
3865
+ return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
3866
+ }
3867
+ //# sourceMappingURL=typedArrays.mjs.map
3868
+
3869
+ /***/ }),
3870
+
3871
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs":
3872
+ /*!*******************************************************************!*\
3873
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs ***!
3874
+ \*******************************************************************/
3875
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3876
+
3877
+ __webpack_require__.r(__webpack_exports__);
3878
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3879
+ /* harmony export */ TEXT_DECODER_THRESHOLD: () => (/* binding */ TEXT_DECODER_THRESHOLD),
3880
+ /* harmony export */ TEXT_ENCODER_THRESHOLD: () => (/* binding */ TEXT_ENCODER_THRESHOLD),
3881
+ /* harmony export */ utf8Count: () => (/* binding */ utf8Count),
3882
+ /* harmony export */ utf8DecodeJs: () => (/* binding */ utf8DecodeJs),
3883
+ /* harmony export */ utf8DecodeTD: () => (/* binding */ utf8DecodeTD),
3884
+ /* harmony export */ utf8EncodeJs: () => (/* binding */ utf8EncodeJs),
3885
+ /* harmony export */ utf8EncodeTE: () => (/* binding */ utf8EncodeTE)
3886
+ /* harmony export */ });
3887
+ /* harmony import */ var _int_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./int.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs");
3888
+ var _a, _b, _c;
3889
+ /* eslint-disable @typescript-eslint/no-unnecessary-condition */
3890
+
3891
+ var TEXT_ENCODING_AVAILABLE = (typeof process === "undefined" || ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a["TEXT_ENCODING"]) !== "never") &&
3892
+ typeof TextEncoder !== "undefined" &&
3893
+ typeof TextDecoder !== "undefined";
3894
+ function utf8Count(str) {
3895
+ var strLength = str.length;
3896
+ var byteLength = 0;
3897
+ var pos = 0;
3898
+ while (pos < strLength) {
3899
+ var value = str.charCodeAt(pos++);
3900
+ if ((value & 0xffffff80) === 0) {
3901
+ // 1-byte
3902
+ byteLength++;
3903
+ continue;
3904
+ }
3905
+ else if ((value & 0xfffff800) === 0) {
3906
+ // 2-bytes
3907
+ byteLength += 2;
3908
+ }
3909
+ else {
3910
+ // handle surrogate pair
3911
+ if (value >= 0xd800 && value <= 0xdbff) {
3912
+ // high surrogate
3913
+ if (pos < strLength) {
3914
+ var extra = str.charCodeAt(pos);
3915
+ if ((extra & 0xfc00) === 0xdc00) {
3916
+ ++pos;
3917
+ value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
3918
+ }
3919
+ }
3920
+ }
3921
+ if ((value & 0xffff0000) === 0) {
3922
+ // 3-byte
3923
+ byteLength += 3;
3924
+ }
3925
+ else {
3926
+ // 4-byte
3927
+ byteLength += 4;
3928
+ }
3929
+ }
3930
+ }
3931
+ return byteLength;
3932
+ }
3933
+ function utf8EncodeJs(str, output, outputOffset) {
3934
+ var strLength = str.length;
3935
+ var offset = outputOffset;
3936
+ var pos = 0;
3937
+ while (pos < strLength) {
3938
+ var value = str.charCodeAt(pos++);
3939
+ if ((value & 0xffffff80) === 0) {
3940
+ // 1-byte
3941
+ output[offset++] = value;
3942
+ continue;
3943
+ }
3944
+ else if ((value & 0xfffff800) === 0) {
3945
+ // 2-bytes
3946
+ output[offset++] = ((value >> 6) & 0x1f) | 0xc0;
3947
+ }
3948
+ else {
3949
+ // handle surrogate pair
3950
+ if (value >= 0xd800 && value <= 0xdbff) {
3951
+ // high surrogate
3952
+ if (pos < strLength) {
3953
+ var extra = str.charCodeAt(pos);
3954
+ if ((extra & 0xfc00) === 0xdc00) {
3955
+ ++pos;
3956
+ value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
3957
+ }
3958
+ }
3959
+ }
3960
+ if ((value & 0xffff0000) === 0) {
3961
+ // 3-byte
3962
+ output[offset++] = ((value >> 12) & 0x0f) | 0xe0;
3963
+ output[offset++] = ((value >> 6) & 0x3f) | 0x80;
3964
+ }
3965
+ else {
3966
+ // 4-byte
3967
+ output[offset++] = ((value >> 18) & 0x07) | 0xf0;
3968
+ output[offset++] = ((value >> 12) & 0x3f) | 0x80;
3969
+ output[offset++] = ((value >> 6) & 0x3f) | 0x80;
3970
+ }
3971
+ }
3972
+ output[offset++] = (value & 0x3f) | 0x80;
3973
+ }
3974
+ }
3975
+ var sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;
3976
+ var TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
3977
+ ? _int_mjs__WEBPACK_IMPORTED_MODULE_0__.UINT32_MAX
3978
+ : typeof process !== "undefined" && ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b["TEXT_ENCODING"]) !== "force"
3979
+ ? 200
3980
+ : 0;
3981
+ function utf8EncodeTEencode(str, output, outputOffset) {
3982
+ output.set(sharedTextEncoder.encode(str), outputOffset);
3983
+ }
3984
+ function utf8EncodeTEencodeInto(str, output, outputOffset) {
3985
+ sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
3986
+ }
3987
+ var utf8EncodeTE = (sharedTextEncoder === null || sharedTextEncoder === void 0 ? void 0 : sharedTextEncoder.encodeInto) ? utf8EncodeTEencodeInto : utf8EncodeTEencode;
3988
+ var CHUNK_SIZE = 4096;
3989
+ function utf8DecodeJs(bytes, inputOffset, byteLength) {
3990
+ var offset = inputOffset;
3991
+ var end = offset + byteLength;
3992
+ var units = [];
3993
+ var result = "";
3994
+ while (offset < end) {
3995
+ var byte1 = bytes[offset++];
3996
+ if ((byte1 & 0x80) === 0) {
3997
+ // 1 byte
3998
+ units.push(byte1);
3999
+ }
4000
+ else if ((byte1 & 0xe0) === 0xc0) {
4001
+ // 2 bytes
4002
+ var byte2 = bytes[offset++] & 0x3f;
4003
+ units.push(((byte1 & 0x1f) << 6) | byte2);
4004
+ }
4005
+ else if ((byte1 & 0xf0) === 0xe0) {
4006
+ // 3 bytes
4007
+ var byte2 = bytes[offset++] & 0x3f;
4008
+ var byte3 = bytes[offset++] & 0x3f;
4009
+ units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
4010
+ }
4011
+ else if ((byte1 & 0xf8) === 0xf0) {
4012
+ // 4 bytes
4013
+ var byte2 = bytes[offset++] & 0x3f;
4014
+ var byte3 = bytes[offset++] & 0x3f;
4015
+ var byte4 = bytes[offset++] & 0x3f;
4016
+ var unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
4017
+ if (unit > 0xffff) {
4018
+ unit -= 0x10000;
4019
+ units.push(((unit >>> 10) & 0x3ff) | 0xd800);
4020
+ unit = 0xdc00 | (unit & 0x3ff);
4021
+ }
4022
+ units.push(unit);
4023
+ }
4024
+ else {
4025
+ units.push(byte1);
4026
+ }
4027
+ if (units.length >= CHUNK_SIZE) {
4028
+ result += String.fromCharCode.apply(String, units);
4029
+ units.length = 0;
4030
+ }
4031
+ }
4032
+ if (units.length > 0) {
4033
+ result += String.fromCharCode.apply(String, units);
4034
+ }
4035
+ return result;
4036
+ }
4037
+ var sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;
4038
+ var TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
4039
+ ? _int_mjs__WEBPACK_IMPORTED_MODULE_0__.UINT32_MAX
4040
+ : typeof process !== "undefined" && ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c["TEXT_DECODER"]) !== "force"
4041
+ ? 200
4042
+ : 0;
4043
+ function utf8DecodeTD(bytes, inputOffset, byteLength) {
4044
+ var stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
4045
+ return sharedTextDecoder.decode(stringBytes);
4046
+ }
4047
+ //# sourceMappingURL=utf8.mjs.map
4048
+
4049
+ /***/ })
4050
+
4051
+ /******/ });
4052
+ /************************************************************************/
4053
+ /******/ // The module cache
4054
+ /******/ var __webpack_module_cache__ = {};
4055
+ /******/
4056
+ /******/ // The require function
4057
+ /******/ function __webpack_require__(moduleId) {
4058
+ /******/ // Check if module is in cache
4059
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
4060
+ /******/ if (cachedModule !== undefined) {
4061
+ /******/ return cachedModule.exports;
4062
+ /******/ }
4063
+ /******/ // Create a new module (and put it into the cache)
4064
+ /******/ var module = __webpack_module_cache__[moduleId] = {
4065
+ /******/ // no module.id needed
4066
+ /******/ // no module.loaded needed
4067
+ /******/ exports: {}
4068
+ /******/ };
4069
+ /******/
4070
+ /******/ // Execute the module function
4071
+ /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
4072
+ /******/
4073
+ /******/ // Return the exports of the module
4074
+ /******/ return module.exports;
4075
+ /******/ }
4076
+ /******/
4077
+ /************************************************************************/
4078
+ /******/ /* webpack/runtime/define property getters */
4079
+ /******/ (() => {
4080
+ /******/ // define getter functions for harmony exports
4081
+ /******/ __webpack_require__.d = (exports, definition) => {
4082
+ /******/ for(var key in definition) {
4083
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
4084
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
4085
+ /******/ }
4086
+ /******/ }
4087
+ /******/ };
4088
+ /******/ })();
4089
+ /******/
4090
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
4091
+ /******/ (() => {
4092
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
4093
+ /******/ })();
4094
+ /******/
4095
+ /******/ /* webpack/runtime/make namespace object */
4096
+ /******/ (() => {
4097
+ /******/ // define __esModule on exports
4098
+ /******/ __webpack_require__.r = (exports) => {
4099
+ /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
4100
+ /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4101
+ /******/ }
4102
+ /******/ Object.defineProperty(exports, '__esModule', { value: true });
4103
+ /******/ };
4104
+ /******/ })();
4105
+ /******/
4106
+ /************************************************************************/
4107
+ var __webpack_exports__ = {};
4108
+ /*!*********************************!*\
4109
+ !*** ./src/websocket-client.js ***!
4110
+ \*********************************/
4111
+ __webpack_require__.r(__webpack_exports__);
4112
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
4113
+ /* harmony export */ API_VERSION: () => (/* reexport safe */ _rpc_js__WEBPACK_IMPORTED_MODULE_0__.API_VERSION),
4114
+ /* harmony export */ RPC: () => (/* reexport safe */ _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC),
4115
+ /* harmony export */ connectToServer: () => (/* binding */ connectToServer),
4116
+ /* harmony export */ getRTCService: () => (/* reexport safe */ _webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__.getRTCService),
4117
+ /* harmony export */ loadRequirements: () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_1__.loadRequirements),
4118
+ /* harmony export */ login: () => (/* binding */ login),
4119
+ /* harmony export */ registerRTCService: () => (/* reexport safe */ _webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__.registerRTCService),
4120
+ /* harmony export */ setupLocalClient: () => (/* binding */ setupLocalClient)
4121
+ /* harmony export */ });
4122
+ /* harmony import */ var _rpc_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./rpc.js */ "./src/rpc.js");
4123
+ /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./src/utils.js");
4124
+ /* harmony import */ var _webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webrtc-client.js */ "./src/webrtc-client.js");
4125
+
4126
+
4127
+
4128
+
4129
+
4130
+
4131
+
4132
+
4133
+ const MAX_RETRY = 10000;
4134
+
4135
+ class WebsocketRPCConnection {
4136
+ constructor(
4137
+ server_url,
4138
+ client_id,
4139
+ workspace,
4140
+ token,
4141
+ timeout = 60,
4142
+ WebSocketClass = null,
4143
+ ) {
4144
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(server_url && client_id, "server_url and client_id are required");
4145
+ this._server_url = server_url;
4146
+ this._client_id = client_id;
4147
+ this._workspace = workspace;
4148
+ this._token = token;
4149
+ this._reconnection_token = null;
4150
+ this._websocket = null;
4151
+ this._handle_message = null;
4152
+ this._handle_connect = null; // Connection open event handler
4153
+ this._disconnect_handler = null; // Disconnection event handler
4154
+ this._timeout = timeout * 1000; // Convert seconds to milliseconds
4155
+ this._WebSocketClass = WebSocketClass || WebSocket; // Allow overriding the WebSocket class
4156
+ this._closing = false;
4157
+ this._legacy_auth = null;
4158
+ this.connection_info = null;
4159
+ }
4160
+
4161
+ on_message(handler) {
4162
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(handler, "handler is required");
4163
+ this._handle_message = handler;
4164
+ }
4165
+
4166
+ on_connect(handler) {
4167
+ this._handle_connect = handler;
4168
+ }
4169
+
4170
+ on_disconnected(handler) {
4171
+ this._disconnect_handler = handler;
4172
+ }
4173
+
4174
+ async _attempt_connection(server_url, attempt_fallback = true) {
4175
+ return new Promise((resolve, reject) => {
4176
+ this._legacy_auth = false;
4177
+ const websocket = new this._WebSocketClass(server_url);
4178
+ websocket.binaryType = "arraybuffer";
4179
+
4180
+ websocket.onopen = () => {
4181
+ console.info("WebSocket connection established");
4182
+ resolve(websocket);
4183
+ };
4184
+
4185
+ websocket.onerror = (event) => {
4186
+ console.error("WebSocket connection error:", event);
4187
+ reject(event);
4188
+ };
4189
+
4190
+ websocket.onclose = (event) => {
4191
+ if (event.code === 1003 && attempt_fallback) {
4192
+ console.info(
4193
+ "Received 1003 error, attempting connection with query parameters.",
4194
+ );
4195
+ this._attempt_connection_with_query_params(server_url)
4196
+ .then(resolve)
4197
+ .catch(reject);
4198
+ } else if (this._disconnect_handler) {
4199
+ this._disconnect_handler(this, event.reason);
4200
+ }
4201
+ };
4202
+ });
4203
+ }
4204
+
4205
+ async _attempt_connection_with_query_params(server_url) {
4206
+ // Initialize an array to hold parts of the query string
4207
+ const queryParamsParts = [];
4208
+
4209
+ // Conditionally add each parameter if it has a non-empty value
4210
+ if (this._client_id)
4211
+ queryParamsParts.push(`client_id=${encodeURIComponent(this._client_id)}`);
4212
+ if (this._workspace)
4213
+ queryParamsParts.push(`workspace=${encodeURIComponent(this._workspace)}`);
4214
+ if (this._token)
4215
+ queryParamsParts.push(`token=${encodeURIComponent(this._token)}`);
4216
+ if (this._reconnection_token)
4217
+ queryParamsParts.push(
4218
+ `reconnection_token=${encodeURIComponent(this._reconnection_token)}`,
4219
+ );
4220
+
4221
+ // Join the parts with '&' to form the final query string, prepend '?' if there are any parameters
4222
+ const queryString =
4223
+ queryParamsParts.length > 0 ? `?${queryParamsParts.join("&")}` : "";
4224
+
4225
+ // Construct the full URL by appending the query string if it exists
4226
+ const full_url = server_url + queryString;
4227
+
4228
+ this._legacy_auth = true; // Assuming this flag is needed for some other logic
4229
+ return await this._attempt_connection(full_url, false);
4230
+ }
4231
+
4232
+ async open() {
4233
+ if (this._closing || this._websocket) {
4234
+ return; // Avoid opening a new connection if closing or already open
4235
+ }
4236
+ try {
4237
+ this._websocket = await this._attempt_connection(this._server_url);
4238
+ if (!this._legacy_auth) {
4239
+ // Send authentication info as the first message if connected without query params
4240
+ const authInfo = JSON.stringify({
4241
+ client_id: this._client_id,
4242
+ workspace: this._workspace,
4243
+ token: this._token,
4244
+ reconnection_token: this._reconnection_token,
4245
+ });
4246
+ this._websocket.send(authInfo);
4247
+ // Wait for the first message from the server
4248
+ await (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.waitFor)(
4249
+ new Promise((resolve, reject) => {
4250
+ this._websocket.onmessage = (event) => {
4251
+ const data = event.data;
4252
+ const first_message = JSON.parse(data);
4253
+ if (!first_message.success) {
4254
+ const error = first_message.error || "Unknown error";
4255
+ console.error("Failed to connect, " + error);
4256
+ this.connection_info = null;
4257
+ reject(new Error(error));
4258
+ } else if (first_message) {
4259
+ console.log(
4260
+ "Successfully connected: " + JSON.stringify(first_message),
4261
+ );
4262
+ this.connection_info = first_message;
4263
+ if(this.connection_info.reconnection_token) {
4264
+ this._reconnection_token = this.connection_info.reconnection_token;
4265
+ };
4266
+ }
4267
+ resolve();
4268
+ };
4269
+ }),
4270
+ this._timeout / 1000.0,
4271
+ "Failed to receive the first message from the server",
4272
+ );
4273
+ }
4274
+
4275
+ this._websocket.onmessage = (event) => {
4276
+ this._handle_message(event.data);
4277
+ };
4278
+
4279
+ if (this._handle_connect) {
4280
+ await this._handle_connect(this);
4281
+ }
4282
+ } catch (error) {
4283
+ console.error("Failed to connect to", this._server_url, error);
4284
+ }
4285
+ }
4286
+
4287
+ async emit_message(data) {
4288
+ if (this._closing) {
4289
+ throw new Error("Connection is closing");
4290
+ }
4291
+ if (!this._websocket || this._websocket.readyState !== WebSocket.OPEN) {
4292
+ await this.open();
4293
+ }
4294
+ try {
4295
+ this._websocket.send(data);
4296
+ } catch (exp) {
4297
+ console.error(`Failed to send data, error: ${exp}`);
4298
+ throw exp;
4299
+ }
4300
+ }
4301
+
4302
+ disconnect(reason) {
4303
+ this._closing = true;
4304
+ if (this._websocket && this._websocket.readyState === WebSocket.OPEN) {
4305
+ this._websocket.close(1000, reason);
4306
+ console.info(`WebSocket connection disconnected (${reason})`);
4307
+ }
4308
+ }
4309
+ }
4310
+
4311
+ function normalizeServerUrl(server_url) {
4312
+ if (!server_url) throw new Error("server_url is required");
4313
+ if (server_url.startsWith("http://")) {
4314
+ server_url =
4315
+ server_url.replace("http://", "ws://").replace(/\/$/, "") + "/ws";
4316
+ } else if (server_url.startsWith("https://")) {
4317
+ server_url =
4318
+ server_url.replace("https://", "wss://").replace(/\/$/, "") + "/ws";
4319
+ }
4320
+ return server_url;
4321
+ }
4322
+
4323
+ async function login(config) {
4324
+ const service_id = config.login_service_id || "public/*:hypha-login";
4325
+ const timeout = config.login_timeout || 60;
4326
+ const callback = config.login_callback;
4327
+
4328
+ const server = await connectToServer({
4329
+ name: "initial login client",
4330
+ server_url: config.server_url,
4331
+ });
4332
+ try {
4333
+ const svc = await server.get_service(service_id);
4334
+ const context = await svc.start();
4335
+ if (callback) {
4336
+ await callback(context);
4337
+ } else {
4338
+ console.log(`Please open your browser and login at ${context.login_url}`);
4339
+ }
4340
+ return await svc.check(context.key, timeout);
4341
+ } catch (error) {
4342
+ throw error;
4343
+ } finally {
4344
+ await server.disconnect();
4345
+ }
4346
+ }
4347
+
4348
+ async function connectToServer(config) {
4349
+ if (config.server) {
4350
+ config.server_url = config.server_url || config.server.url;
4351
+ config.WebSocketClass =
4352
+ config.WebSocketClass || config.server.WebSocketClass;
4353
+ }
4354
+ let clientId = config.client_id;
4355
+ if (!clientId) {
4356
+ clientId = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.randId)();
4357
+ config.client_id = clientId;
4358
+ }
4359
+
4360
+ let server_url = normalizeServerUrl(config.server_url);
4361
+
4362
+ let connection = new WebsocketRPCConnection(
4363
+ server_url,
4364
+ clientId,
4365
+ config.workspace,
4366
+ config.token,
4367
+ config.method_timeout || 60,
4368
+ config.WebSocketClass,
4369
+ );
4370
+ await connection.open();
4371
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(connection.connection_info, "Failed to connect to the server");
4372
+ if(config.workspace && connection.connection_info.workspace !== config.workspace) {
4373
+ throw new Error(`Connected to the wrong workspace: ${connection.connection_info.workspace}, expected: ${config.workspace}`);
4374
+ }
4375
+ const workspace = connection.connection_info.workspace;
4376
+ const manager_id = connection.connection_info.manager_id;
4377
+ const rpc = new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC(connection, {
4378
+ client_id: clientId,
4379
+ workspace,
4380
+ manager_id,
4381
+ default_context: { connection_type: "websocket" },
4382
+ name: config.name,
4383
+ method_timeout: config.method_timeout,
4384
+ app_id: config.app_id,
4385
+ });
4386
+ const wm = await rpc.get_manager_service();
4387
+ wm.rpc = rpc;
4388
+
4389
+ async function _export(api) {
4390
+ api.id = "default";
4391
+ api.name = api.name || config.name || api.id;
4392
+ api.description = api.description || config.description;
4393
+ await rpc.register_service(api, true);
4394
+ }
4395
+
4396
+ async function getPlugin(query) {
4397
+ return await wm.get_service(query + ":default");
4398
+ }
4399
+
4400
+ async function disconnect() {
4401
+ await rpc.disconnect();
4402
+ await connection.disconnect();
4403
+ }
4404
+ if(connection.connection_info){
4405
+ wm.config = Object.assign(wm.config, connection.connection_info);
4406
+ }
4407
+ wm.export = _export;
4408
+ wm.getPlugin = getPlugin;
4409
+ wm.listPlugins = wm.listServices;
4410
+ wm.disconnect = disconnect;
4411
+ wm.registerCodec = rpc.register_codec.bind(rpc);
4412
+ wm.emit = rpc.emit;
4413
+ wm.on = rpc.on;
4414
+ if (rpc.manager_id) {
4415
+ rpc.on("force-exit", async (message) => {
4416
+ if (message.from === "*/" + rpc.manager_id) {
4417
+ console.log("Disconnecting from server, reason:", message.reason);
4418
+ await disconnect();
4419
+ }
4420
+ });
4421
+ }
4422
+ if (config.webrtc) {
4423
+ await (0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__.registerRTCService)(wm, clientId + "-rtc", config.webrtc_config);
4424
+ }
4425
+ if (wm.get_service || wm.getService) {
4426
+ const _get_service = wm.get_service || wm.getService;
4427
+ wm.get_service = async function (query, webrtc, webrtc_config) {
4428
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(
4429
+ [undefined, true, false, "auto"].includes(webrtc),
4430
+ "webrtc must be true, false or 'auto'",
4431
+ );
4432
+ const svc = await _get_service(query);
4433
+ if (webrtc === true || webrtc === "auto") {
4434
+ if (svc.id.includes(":") && svc.id.includes("/")) {
4435
+ const client = svc.id.split(":")[0];
4436
+ try {
4437
+ // Assuming that the client registered a webrtc service with the client_id + "-rtc"
4438
+ const peer = await (0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__.getRTCService)(
4439
+ wm,
4440
+ client + ":" + client.split("/")[1] + "-rtc",
4441
+ webrtc_config,
4442
+ );
4443
+ const rtcSvc = await peer.get_service(svc.id.split(":")[1]);
4444
+ rtcSvc._webrtc = true;
4445
+ rtcSvc._peer = peer;
4446
+ rtcSvc._service = svc;
4447
+ return rtcSvc;
4448
+ } catch (e) {
4449
+ console.warn(
4450
+ "Failed to get webrtc service, using websocket connection",
4451
+ e,
4452
+ );
4453
+ }
4454
+ }
4455
+ if (webrtc === true) {
4456
+ throw new Error("Failed to get the service via webrtc");
4457
+ }
4458
+ }
4459
+ return svc;
4460
+ };
4461
+ wm.getService = wm.get_service;
4462
+ }
4463
+ return wm;
4464
+ }
4465
+
4466
+ class LocalWebSocket {
4467
+ constructor(url, client_id, workspace) {
4468
+ this.url = url;
4469
+ this.onopen = () => {};
4470
+ this.onmessage = () => {};
4471
+ this.onclose = () => {};
4472
+ this.onerror = () => {};
4473
+ this.client_id = client_id;
4474
+ this.workspace = workspace;
4475
+ const context = typeof window !== "undefined" ? window : self;
4476
+ const isWindow = typeof window !== "undefined";
4477
+ this.postMessage = (message) => {
4478
+ if (isWindow) {
4479
+ window.parent.postMessage(message, "*");
4480
+ } else {
4481
+ self.postMessage(message);
4482
+ }
4483
+ };
4484
+
4485
+ this.readyState = WebSocket.CONNECTING;
4486
+ context.addEventListener(
4487
+ "message",
4488
+ (event) => {
4489
+ const { type, data, to } = event.data;
4490
+ if (to !== this.client_id) {
4491
+ console.debug("message not for me", to, this.client_id);
4492
+ return;
4493
+ }
4494
+ switch (type) {
4495
+ case "message":
4496
+ if (this.readyState === WebSocket.OPEN && this.onmessage) {
4497
+ this.onmessage({ data: data });
4498
+ }
4499
+ break;
4500
+ case "connected":
4501
+ this.readyState = WebSocket.OPEN;
4502
+ this.onopen(event);
4503
+ break;
4504
+ case "closed":
4505
+ this.readyState = WebSocket.CLOSED;
4506
+ this.onclose(event);
4507
+ break;
4508
+ default:
4509
+ break;
4510
+ }
4511
+ },
4512
+ false,
4513
+ );
4514
+
4515
+ if (!this.client_id) throw new Error("client_id is required");
4516
+ if (!this.workspace) throw new Error("workspace is required");
4517
+ this.postMessage({
4518
+ type: "connect",
4519
+ url: this.url,
4520
+ from: this.client_id,
4521
+ workspace: this.workspace,
4522
+ });
4523
+ }
4524
+
4525
+ send(data) {
4526
+ if (this.readyState === WebSocket.OPEN) {
4527
+ this.postMessage({
4528
+ type: "message",
4529
+ data: data,
4530
+ from: this.client_id,
4531
+ workspace: this.workspace,
4532
+ });
4533
+ }
4534
+ }
4535
+
4536
+ close() {
4537
+ this.readyState = WebSocket.CLOSING;
4538
+ this.postMessage({
4539
+ type: "close",
4540
+ from: this.client_id,
4541
+ workspace: this.workspace,
4542
+ });
4543
+ this.onclose();
4544
+ }
4545
+
4546
+ addEventListener(type, listener) {
4547
+ if (type === "message") {
4548
+ this.onmessage = listener;
4549
+ }
4550
+ if (type === "open") {
4551
+ this.onopen = listener;
4552
+ }
4553
+ if (type === "close") {
4554
+ this.onclose = listener;
4555
+ }
4556
+ if (type === "error") {
4557
+ this.onerror = listener;
4558
+ }
4559
+ }
4560
+ }
4561
+
4562
+ function setupLocalClient({
4563
+ enable_execution = false,
4564
+ on_ready = null,
4565
+ }) {
4566
+ return new Promise((resolve, reject) => {
4567
+ const context = typeof window !== "undefined" ? window : self;
4568
+ const isWindow = typeof window !== "undefined";
4569
+ context.addEventListener(
4570
+ "message",
4571
+ (event) => {
4572
+ const {
4573
+ type,
4574
+ server_url,
4575
+ workspace,
4576
+ client_id,
4577
+ token,
4578
+ method_timeout,
4579
+ name,
4580
+ config,
4581
+ } = event.data;
4582
+
4583
+ if (type === "initializeHyphaClient") {
4584
+ if (!server_url || !workspace || !client_id) {
4585
+ console.error("server_url, workspace, and client_id are required.");
4586
+ return;
4587
+ }
4588
+
4589
+ if (!server_url.startsWith("https://local-hypha-server:")) {
4590
+ console.error(
4591
+ "server_url should start with https://local-hypha-server:",
4592
+ );
4593
+ return;
4594
+ }
4595
+
4596
+ connectToServer({
4597
+ server_url,
4598
+ workspace,
4599
+ client_id,
4600
+ token,
4601
+ method_timeout,
4602
+ name,
4603
+ }).then(async (server) => {
4604
+ globalThis.api = server;
4605
+ try {
4606
+ // for iframe
4607
+ if (isWindow && enable_execution) {
4608
+ function loadScript(script) {
4609
+ return new Promise((resolve, reject) => {
4610
+ const scriptElement = document.createElement("script");
4611
+ scriptElement.innerHTML = script.content;
4612
+ scriptElement.lang = script.lang;
4613
+
4614
+ scriptElement.onload = () => resolve();
4615
+ scriptElement.onerror = (e) => reject(e);
4616
+
4617
+ document.head.appendChild(scriptElement);
4618
+ });
4619
+ }
4620
+ if (config.styles && config.styles.length > 0) {
4621
+ for (const style of config.styles) {
4622
+ const styleElement = document.createElement("style");
4623
+ styleElement.innerHTML = style.content;
4624
+ styleElement.lang = style.lang;
4625
+ document.head.appendChild(styleElement);
4626
+ }
4627
+ }
4628
+ if (config.links && config.links.length > 0) {
4629
+ for (const link of config.links) {
4630
+ const linkElement = document.createElement("a");
4631
+ linkElement.href = link.url;
4632
+ linkElement.innerText = link.text;
4633
+ document.body.appendChild(linkElement);
4634
+ }
4635
+ }
4636
+ if (config.windows && config.windows.length > 0) {
4637
+ for (const w of config.windows) {
4638
+ document.body.innerHTML = w.content;
4639
+ break;
4640
+ }
4641
+ }
4642
+ if (config.scripts && config.scripts.length > 0) {
4643
+ for (const script of config.scripts) {
4644
+ if (script.lang !== "javascript")
4645
+ throw new Error("Only javascript scripts are supported");
4646
+ await loadScript(script); // Await the loading of each script
4647
+ }
4648
+ }
4649
+ }
4650
+ // for web worker
4651
+ else if (
4652
+ !isWindow &&
4653
+ enable_execution &&
4654
+ config.scripts &&
4655
+ config.scripts.length > 0
4656
+ ) {
4657
+ for (const script of config.scripts) {
4658
+ if (script.lang !== "javascript")
4659
+ throw new Error("Only javascript scripts are supported");
4660
+ eval(script.content);
4661
+ }
4662
+ }
4663
+
4664
+ if (on_ready) {
4665
+ await on_ready(server, config);
4666
+ }
4667
+ resolve(server);
4668
+ } catch (e) {
4669
+ reject(e);
4670
+ }
4671
+ });
4672
+ }
4673
+ },
4674
+ false,
4675
+ );
4676
+ if (isWindow) {
4677
+ window.parent.postMessage({ type: "hyphaClientReady" }, "*");
4678
+ } else {
4679
+ self.postMessage({ type: "hyphaClientReady" });
4680
+ }
4681
+ });
4682
+ }
4683
+
4684
+ /******/ return __webpack_exports__;
4685
+ /******/ })()
4686
+ ;
4687
+ });
4688
+ //# sourceMappingURL=hypha-rpc-websocket.js.map