@statewalker/webrun-http-browser 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +321 -51
  3. package/demo/demo-1.html +109 -194
  4. package/demo/demo-2.html +118 -299
  5. package/dist/core/data-calls.d.ts +5 -0
  6. package/dist/core/data-calls.d.ts.map +1 -0
  7. package/dist/core/data-channels.d.ts +17 -0
  8. package/dist/core/data-channels.d.ts.map +1 -0
  9. package/dist/core/index.d.ts +6 -0
  10. package/dist/core/index.d.ts.map +1 -0
  11. package/dist/core/message-target.d.ts +16 -0
  12. package/dist/core/message-target.d.ts.map +1 -0
  13. package/dist/core/registry.d.ts +18 -0
  14. package/dist/core/registry.d.ts.map +1 -0
  15. package/dist/http/http-send-recieve.d.ts +23 -0
  16. package/dist/http/http-send-recieve.d.ts.map +1 -0
  17. package/dist/http/index.d.ts +4 -0
  18. package/dist/http/index.d.ts.map +1 -0
  19. package/dist/index.d.ts +4 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +2541 -807
  22. package/dist/relay/index-sw.d.ts +7 -0
  23. package/dist/relay/index-sw.d.ts.map +1 -0
  24. package/dist/relay/index.d.ts +69 -0
  25. package/dist/relay/index.d.ts.map +1 -0
  26. package/dist/relay/split-service-url.d.ts +13 -0
  27. package/dist/relay/split-service-url.d.ts.map +1 -0
  28. package/dist/relay-sw.d.ts +2 -0
  29. package/dist/relay-sw.d.ts.map +1 -0
  30. package/dist/relay-sw.js +878 -0
  31. package/dist/sw/http-sw-dispatcher.d.ts +28 -0
  32. package/dist/sw/http-sw-dispatcher.d.ts.map +1 -0
  33. package/dist/sw/index.d.ts +3 -0
  34. package/dist/sw/index.d.ts.map +1 -0
  35. package/dist/sw/sw-dispatcher.d.ts +74 -0
  36. package/dist/sw/sw-dispatcher.d.ts.map +1 -0
  37. package/dist/sw-worker.d.ts +2 -0
  38. package/dist/sw-worker.d.ts.map +1 -0
  39. package/dist/sw-worker.js +813 -0
  40. package/dist/sw.d.ts +2 -0
  41. package/dist/sw.d.ts.map +1 -0
  42. package/dist/sw.js +1076 -0
  43. package/package.json +50 -37
  44. package/public/index.html +61 -97
  45. package/public/index.js +7 -4
  46. package/public/sw-worker.js +4 -0
  47. package/public-relay/heartbeat.js +4 -3
  48. package/public-relay/relay-sw.js +4 -6
  49. package/public-relay/relay.html +16 -11
  50. package/src/core/data-calls.ts +46 -0
  51. package/src/core/data-channels.ts +224 -0
  52. package/src/core/index.ts +9 -0
  53. package/src/core/message-target.ts +18 -0
  54. package/src/core/registry.ts +54 -0
  55. package/src/http/http-send-recieve.ts +81 -0
  56. package/src/http/index.ts +7 -0
  57. package/src/index.ts +3 -0
  58. package/src/relay/index-sw.ts +145 -0
  59. package/src/relay/index.ts +261 -0
  60. package/src/relay/split-service-url.ts +30 -0
  61. package/src/relay-sw.ts +7 -0
  62. package/src/sw/http-sw-dispatcher.ts +122 -0
  63. package/src/sw/index.ts +2 -0
  64. package/src/sw/sw-dispatcher.ts +307 -0
  65. package/src/sw-worker.ts +7 -0
  66. package/src/sw.ts +1 -0
  67. package/CHANGELOG.md +0 -1
  68. package/demo/demo-2 copy.html +0 -598
  69. package/demo/demo-3.html +0 -167
  70. package/dist/index-sw-umd.js +0 -798
  71. package/dist/index-sw-umd.min.js +0 -2
  72. package/dist/index-sw.js +0 -791
  73. package/dist/index-sw.min.js +0 -2
  74. package/dist/index-umd.js +0 -853
  75. package/dist/index-umd.min.js +0 -2
  76. package/dist/index.min.js +0 -2
  77. package/index.js +0 -1
  78. package/src/core/data-calls.js +0 -36
  79. package/src/core/data-channels.js +0 -192
  80. package/src/core/data-send-recieve.js +0 -28
  81. package/src/core/errors.js +0 -13
  82. package/src/core/index.js +0 -4
  83. package/src/http/HttpError.js +0 -59
  84. package/src/http/http-send-recieve.js +0 -40
  85. package/src/http/http-stubs.js +0 -135
  86. package/src/http/index.js +0 -3
  87. package/src/http/readable-streams.js +0 -33
  88. package/src/index.js +0 -7
  89. package/src/relay/index-sw.js +0 -216
  90. package/src/relay/index.js +0 -263
  91. package/src/relay/splitServiceUrl.js +0 -24
  92. package/src/sw/http-sw-dispatcher.js +0 -128
  93. package/src/sw/sw-dispatcher.js +0 -264
package/dist/index-sw.js DELETED
@@ -1,791 +0,0 @@
1
- // @statewalker/webrun-http-browser v0.3.3 https://github.com/statewalker/statewalker-webrun-http-browser Copyright 2023 Mikhail Kotelnikov
2
- // See https://github.com/agenjs/agen-utils/blob/main/src/iterator.js
3
- async function* iterate(init, queue = []) {
4
- let promise, notify, push = async (error, value, done) => {
5
- const slot = { error, value, done };
6
- slot.promise = new Promise(n => slot.notify = n);
7
- await queue.push(slot);
8
- notify && notify();
9
- notify = null;
10
- return slot.promise;
11
- };
12
- const next = (value) => push(undefined, value, false);
13
- const complete = () => push(undefined, undefined, true);
14
- const error = err => push(err, undefined, true);
15
- const unsubscribe = init(Object.assign([next, complete, error], { next, complete, error }));
16
- let slot;
17
- try {
18
- while (true) {
19
- slot = await queue.shift();
20
- if (slot) {
21
- try {
22
- if (slot.error) { throw slot.error; }
23
- else if (slot.done) { break; }
24
- else { yield slot.value; }
25
- } finally {
26
- slot.notify(true);
27
- }
28
- } else {
29
- await (promise = notify ? promise : new Promise(n => notify = n));
30
- }
31
- }
32
- } finally {
33
- notify && notify();
34
- push = () => false; // Stop pushing in the queue...
35
- ((typeof unsubscribe === 'function') && (await unsubscribe()));
36
- while (slot = await queue.shift()) { slot.notify(false); }
37
- }
38
- }
39
-
40
- function newRegistry(onError = console.error) {
41
- let counter = 0;
42
- const registrations = {};
43
- const register = (action) => {
44
- const id = counter++;
45
- return (registrations[id] = Object.assign(
46
- function (skip) {
47
- try {
48
- delete registrations[id];
49
- return !skip && action && action();
50
- } catch (error) {
51
- onError(error);
52
- }
53
- },
54
- { action }
55
- ));
56
- };
57
- const unregister = (action) =>
58
- Object.values(registrations).forEach((r) => r.action === action && r(true));
59
- const clear = () => Object.values(registrations).forEach((r) => r());
60
- return Object.assign([register, clear, unregister], {
61
- register,
62
- clear,
63
- unregister
64
- });
65
- }
66
-
67
- function promisifyRequest(request) {
68
- return new Promise((resolve, reject) => {
69
- // @ts-ignore - file size hacks
70
- request.oncomplete = request.onsuccess = () => resolve(request.result);
71
- // @ts-ignore - file size hacks
72
- request.onabort = request.onerror = () => reject(request.error);
73
- });
74
- }
75
- function createStore(dbName, storeName) {
76
- const request = indexedDB.open(dbName);
77
- request.onupgradeneeded = () => request.result.createObjectStore(storeName);
78
- const dbp = promisifyRequest(request);
79
- return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
80
- }
81
- let defaultGetStoreFunc;
82
- function defaultGetStore() {
83
- if (!defaultGetStoreFunc) {
84
- defaultGetStoreFunc = createStore('keyval-store', 'keyval');
85
- }
86
- return defaultGetStoreFunc;
87
- }
88
- /**
89
- * Get a value by its key.
90
- *
91
- * @param key
92
- * @param customStore Method to get a custom store. Use with caution (see the docs).
93
- */
94
- function get(key, customStore = defaultGetStore()) {
95
- return customStore('readonly', (store) => promisifyRequest(store.get(key)));
96
- }
97
- /**
98
- * Set a value with a key.
99
- *
100
- * @param key
101
- * @param value
102
- * @param customStore Method to get a custom store. Use with caution (see the docs).
103
- */
104
- function set(key, value, customStore = defaultGetStore()) {
105
- return customStore('readwrite', (store) => {
106
- store.put(value, key);
107
- return promisifyRequest(store.transaction);
108
- });
109
- }
110
-
111
- function serializeError(error) {
112
- return Object.assign({
113
- message: error,
114
- stack: error.stack,
115
- }, error);
116
- }
117
-
118
- function deserializeError(error) {
119
- if (typeof error === "string") {
120
- error = { message: error };
121
- }
122
- return Object.assign(new Error(error.message), error);
123
- }
124
-
125
- async function callChannel(mainChannel, callType, params, ...transfers) {
126
- return new Promise((resolve, reject) => {
127
- const channel = new MessageChannel();
128
- channel.port1.onmessage = (ev) => {
129
- const { result, error } = ev.data;
130
- if (error) reject(deserializeError(error));
131
- else resolve(result);
132
- };
133
- mainChannel.postMessage({ type: callType, params }, [
134
- channel.port2,
135
- ...transfers,
136
- ]);
137
- });
138
- }
139
-
140
- function handleChannelCalls(mainChannel, callType, handler) {
141
- const messageListener = async (event) => {
142
- if (!event.data || event.data.type !== callType) return;
143
- const [port, ...transfers] = event.ports;
144
- let response = {};
145
- try {
146
- const params = event.data.params;
147
- response.result = await handler(event, params, ...transfers);
148
- } catch (error) {
149
- response.error = serializeError(error);
150
- }
151
- port.postMessage(response);
152
- };
153
- mainChannel.addEventListener("message", messageListener);
154
- try {
155
- mainChannel.start && mainChannel.start();
156
- } catch (e) {}
157
- return () => mainChannel.removeEventListener("message", messageListener);
158
- }
159
-
160
- async function* recieveData(onMessage) {
161
- yield* iterate((iterator) => {
162
- return onMessage(async ({ done = true, value, error } = {}) => {
163
- if (error) {
164
- await iterator.error(error);
165
- } else if (done) {
166
- await iterator.complete();
167
- } else {
168
- await iterator.next(value);
169
- }
170
- });
171
- });
172
- }
173
-
174
- async function sendData(send, it) {
175
- let error;
176
- try {
177
- for await (let value of it) {
178
- await send({ done: false, value });
179
- }
180
- } catch (err) {
181
- error = err;
182
- } finally {
183
- await send({ done: true, error });
184
- }
185
- }
186
-
187
- async function* sendStream(communicationPort, input, params = {}) {
188
- const messageChannel = new MessageChannel();
189
- communicationPort.postMessage({ type: "START_CALL", params }, [
190
- messageChannel.port2,
191
- ]);
192
-
193
- const channel = newChannel(messageChannel.port1);
194
- try {
195
- await channel.start();
196
- channel.sendAll(input);
197
- yield* channel.recieveAll();
198
- } finally {
199
- await channel.close();
200
- }
201
- }
202
-
203
- /**
204
- * This method creates and returns methods allowing to send and recieve data over the specified port.
205
- * The main characteristics of the returned methods is that they properly manage backpressure - sender
206
- * iterators are waiting to send the next value until the previous one is consumed on the other side.
207
- * @param {*} port
208
- * @returns an object with the following methods:
209
- * * `start` - starts the connection over the specified port
210
- * * `close`- stops all iterators and closes the port
211
- * * `recieveAll() : AsyncIterator` - returns an AsyncIterator over all values send by the peer
212
- * * `sendAll(it : AsyncIterator) : Promise<any>` - sends all values defined by the given
213
- * AsyncIterator to the peer
214
- */
215
- function newChannel(port) {
216
- let listeners = [];
217
- let iterators = [];
218
-
219
- const notifyAll = async (data) => {
220
- for (let listener of listeners) {
221
- await listener(data);
222
- }
223
- };
224
- const channel = newInvokationChannel({
225
- port,
226
- handler: notifyAll,
227
- });
228
-
229
- const start = () => channel.start();
230
-
231
- const close = async () => {
232
- await notifyAll({ done: true });
233
- [...iterators].forEach((it) => it.return && it.return());
234
- await channel.close();
235
- };
236
-
237
- async function* recieveAll() {
238
- yield* recieveData((listener) => {
239
- listeners.push(listener);
240
- return () => listeners = listeners.filter((l) => l !== listener);
241
- });
242
- }
243
-
244
- async function sendAll(it) {
245
- await sendData(
246
- channel.invoke,
247
- (async function* () {
248
- try {
249
- iterators.push(it);
250
- yield* it;
251
- } finally {
252
- iterators = iterators.filter((i) => i !== it);
253
- }
254
- })(),
255
- );
256
- }
257
- return {
258
- start,
259
- close,
260
- recieveAll,
261
- sendAll,
262
- };
263
- }
264
-
265
- function newInvokationChannel({
266
- port,
267
- handler = () => {
268
- throw new Error("Handler not implemented");
269
- },
270
- onError = console.error,
271
- newCallId = () =>
272
- newInvokationChannel.__counter = (newInvokationChannel.__counter || 0) + 1,
273
- }) {
274
- const MESSAGE_TYPE_REQUEST = "REQUEST";
275
- const MESSAGE_TYPE_RESPONSE = "RESPONSE";
276
- const EVENT_MESSAGE = "message";
277
-
278
- const requests = {};
279
- const listener = async (event) => {
280
- const data = event.data || {};
281
- const { type, callId } = data;
282
- if (type === MESSAGE_TYPE_REQUEST) {
283
- try {
284
- const { request } = data;
285
- let result = await handler(request, ...(event.ports || []));
286
- const [response, ...transfers] = Array.isArray(result)
287
- ? result
288
- : result !== undefined
289
- ? [result]
290
- : [];
291
- port.postMessage(
292
- { type: MESSAGE_TYPE_RESPONSE, callId, response },
293
- transfers,
294
- );
295
- } catch (error) {
296
- port.postMessage({
297
- type: MESSAGE_TYPE_RESPONSE,
298
- callId,
299
- error: serializeError(error),
300
- });
301
- }
302
- } else if (type === MESSAGE_TYPE_RESPONSE) {
303
- const { callId, response, error } = data;
304
- const request = requests[callId];
305
- delete requests[callId];
306
- if (request) {
307
- error
308
- ? request.reject(deserializeError(error))
309
- : request.resolve(response);
310
- }
311
- }
312
- };
313
-
314
- const start = async () => {
315
- try {
316
- port.addEventListener(EVENT_MESSAGE, listener);
317
- port.start && await port.start();
318
- } catch (e) {
319
- onError(e);
320
- }
321
- };
322
-
323
- const close = async () => {
324
- try {
325
- port.removeEventListener(EVENT_MESSAGE, listener);
326
- port.close && await port.close();
327
- } catch (e) {
328
- onError(e);
329
- }
330
- };
331
-
332
- const invoke = async function (request = {}, ...transfers) {
333
- const callId = newCallId();
334
- return new Promise((resolve, reject) => {
335
- try {
336
- requests[callId] = { resolve, reject };
337
- port.postMessage(
338
- { type: MESSAGE_TYPE_REQUEST, callId, request },
339
- transfers,
340
- );
341
- } catch (error) {
342
- reject(error);
343
- delete request[callId];
344
- }
345
- });
346
- };
347
-
348
- return {
349
- start,
350
- close,
351
- invoke,
352
- };
353
- }
354
-
355
- function toReadableStream(it) {
356
- return new ReadableStream({
357
- type: "bytes",
358
- async pull(controller) {
359
- let handled = false;
360
- try {
361
- while (true) {
362
- const slot = await it.next();
363
- if (!slot || slot.done) {
364
- break;
365
- }
366
- controller.enqueue(await slot.value);
367
- }
368
- } catch (error) {
369
- handled = true;
370
- controller.error(error);
371
- } finally {
372
- !handled && controller.close();
373
- }
374
- },
375
- });
376
- }
377
-
378
- async function* fromReadableStream(stream) {
379
- const reader = await stream.getReader();
380
- let done, value;
381
- while (({ done, value } = await reader.read())) {
382
- if (done) {
383
- break;
384
- }
385
- yield await value;
386
- }
387
- }
388
-
389
- /**
390
- * This method returns an HTTP handlers transforming
391
- * HTTP Request instances to binary representations and
392
- * sending them to a transport layer.
393
- * Results of these transport ivokations are deserialized
394
- * as meaningful Response instances and returned back to the caller.
395
- *
396
- * The specified `send` method is used to dispatch serialized
397
- * requests to return the serialized remote results.
398
- * This transport method accepts and returns objects with
399
- * the same structure:
400
- * * `options` - contains serialized request or response parameters
401
- * * `content` - an async iterator over binary blocks for
402
- * the request or response
403
- *
404
- * @param {*} send transport function accepting serialized requests
405
- * and returning back serialized responses
406
- * @returns an async handler accepting standard
407
- * HTTP `Request` instances and returning `Response` instances
408
- */
409
- function newHttpClientStub(send) {
410
- return async (request) => {
411
- request = await request;
412
- const fields = [
413
- "url",
414
- "method",
415
- "mode",
416
- "credentials",
417
- "cache",
418
- "redirect",
419
- "referrer",
420
- "referrerPolicy",
421
- "integrity",
422
- "keepalive"
423
- ];
424
- const headers = [...request.headers].map(([key, value]) => {
425
- return [key, value]
426
- });
427
- const requestOptions = fields.reduce((options, key) => {
428
- const val = request[key];
429
- if (val !== undefined) options[key] = val;
430
- return options;
431
- }, {
432
- headers
433
- });
434
- const requestContent = (request.body)
435
- ? fromReadableStream(request.body)
436
- : [];
437
- const result = await send({
438
- options: requestOptions,
439
- content: requestContent,
440
- });
441
- let responseBody = null;
442
- let responseOptions = {};
443
- if (!result) {
444
- responseOptions = {
445
- status: 404,
446
- statusText: "Error 404: Not Found",
447
- };
448
- } else {
449
- responseOptions = result.options;
450
- const responseContent = result.content;
451
- if (
452
- requestOptions.method !== "HEAD" &&
453
- requestOptions.method !== "OPTIONS"
454
- ) {
455
- responseBody = toReadableStream(responseContent);
456
- } else if (responseContent && responseContent.return) {
457
- responseContent.return();
458
- }
459
- }
460
- return new Response(responseBody, responseOptions);
461
- };
462
- }
463
-
464
- async function* httpToIterator(params) {
465
- const { options, content } = await params;
466
- const encoder = new TextEncoder();
467
- yield encoder.encode(JSON.stringify(options));
468
- yield* content;
469
- }
470
-
471
- async function httpFromIterator(it) {
472
- it = await it;
473
- const { done, value } = await it.next();
474
- let options = {};
475
- if (!done && value) {
476
- const decoder = new TextDecoder();
477
- const str = decoder.decode(value);
478
- options = JSON.parse(str);
479
- }
480
- return {
481
- options,
482
- content: it,
483
- };
484
- }
485
-
486
- async function sendHttpRequest(communicationPort, request) {
487
- const clientStub = newHttpClientStub(async (req) => {
488
- return await httpFromIterator(
489
- sendStream(communicationPort, httpToIterator(req)),
490
- );
491
- });
492
- return await clientStub(request);
493
- }
494
-
495
- function splitServiceUrl(url, separator = "~") {
496
- let key = "";
497
- let path = "";
498
- let str = url + "";
499
- const idx = str.indexOf(separator);
500
- let baseUrl = "";
501
- if (idx >= 0) {
502
- baseUrl = str.substring(0, idx + separator.length);
503
- str.substring(idx + separator.length)
504
- .replace(/^([^\/]+)/, (match, $1) => {
505
- baseUrl += match;
506
- if (baseUrl.length < str.length) baseUrl += "/";
507
- key = $1;
508
- path = str.substring(baseUrl.length);
509
- return "";
510
- });
511
- }
512
- return {
513
- url,
514
- key,
515
- baseUrl,
516
- path,
517
- };
518
- }
519
-
520
- class HttpError extends Error {
521
- constructor(options) {
522
- super(options.message);
523
- this.status = options.status;
524
- this.statusText = options.statusText;
525
- }
526
- getResponseOptions(options = {}) {
527
- return Object.assign(this.toJson(), options);
528
- }
529
- toJson() {
530
- return {
531
- status: this.status,
532
- statusText: this.statusText,
533
- message: this.message,
534
- };
535
- }
536
-
537
- static fromError(error) {
538
- if (!(error instanceof HttpError)) {
539
- error = new HttpError(Object.assign({
540
- status: 500,
541
- statusText: "Bad Request",
542
- reason: error.message,
543
- }));
544
- }
545
- return error;
546
- }
547
-
548
- static errorResourceNotFound(options = {}) {
549
- return new HttpError({
550
- status: 404,
551
- statusText: "Error 404: Resource not found",
552
- ...options,
553
- });
554
- }
555
- static errorForbidden(options = {}) {
556
- return new HttpError({
557
- status: 403,
558
- statusText: "Error 403: Forbidden",
559
- ...options,
560
- });
561
- }
562
-
563
- static errorResourceGone(options = {}) {
564
- return new HttpError({
565
- status: 410,
566
- statusText: "Error 410: Resource Gone",
567
- ...options,
568
- });
569
- }
570
-
571
- static errorInternalError(options) {
572
- return new HttpError({
573
- ...options,
574
- status: 500,
575
- statusText: "Error 500: Internal error",
576
- });
577
- }
578
- }
579
-
580
- function startRelayServiceWorker(self) {
581
- const [register, clear] = newRegistry();
582
-
583
- if (typeof self.skipWaiting === "function") {
584
- console.log("self.skipWaiting() is supported.");
585
- self.addEventListener("install", (e) => {
586
- // See https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-global-scope-skipwaiting
587
- e.waitUntil(self.skipWaiting());
588
- });
589
- } else {
590
- console.log("self.skipWaiting() is not supported.");
591
- }
592
-
593
- if (self.clients && (typeof self.clients.claim === "function")) {
594
- console.log("self.clients.claim() is supported.");
595
- self.addEventListener("activate", (e) => {
596
- // See https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#clients-claim-method
597
- e.waitUntil(self.clients.claim());
598
- });
599
- } else {
600
- console.log("self.clients.claim() is not supported.");
601
- }
602
-
603
- const clientsRegistry = newClientsRegistry({
604
- self,
605
- get,
606
- set,
607
- });
608
-
609
- // This listener handles the following message types:
610
- // * registration: registers new clients as service providers
611
- // * handles service calls rounting:
612
- // - it gets the clientKey defined in the call
613
- // - it uses the serviceKey to get the service-specifc channel
614
- // - it creates a new message channel and sent its ports to peers
615
-
616
- register(handleChannelCalls(self, "REGISTER", async (event, data) => {
617
- return await clientsRegistry.addClient(data.key, event.source);
618
- }));
619
- register(handleChannelCalls(self, "UNREGISTER", async (event, data) => {
620
- return await clientsRegistry.removeClient(data.key);
621
- }));
622
-
623
- // Transfers all parameters (and ports) to the target client.
624
- register(handleChannelCalls(self, "CONNECT", async (event, data, port) => {
625
- const { key } = data;
626
- const client = await clientsRegistry.getClient(key);
627
- if (!client) {
628
- throw new Error(`Target client was not found. Target key: "${key}".`);
629
- }
630
- return await callChannel(client, "CONNECT", data, port);
631
- }));
632
-
633
- const fetchListener = (event) => {
634
- const request = event.request;
635
- const params = splitServiceUrl(request.url);
636
- const { key } = params;
637
- if (key) {
638
- const handler = async () => {
639
- try {
640
- const channel = new MessageChannel();
641
- const client = await clientsRegistry.getClient(key);
642
- if (!client) {
643
- throw HttpError.errorResourceGone(params);
644
- }
645
- const data = {
646
- type: "http",
647
- key,
648
- };
649
- if (!await callChannel(client, "CONNECT", data, channel.port2)) {
650
- throw HttpError.errorForbidden(params);
651
- }
652
- return await sendHttpRequest(channel.port1, request);
653
- } catch (error) {
654
- error = HttpError.fromError(error);
655
- const options = error.getResponseOptions(params);
656
- return new Response(JSON.stringify(options), {
657
- ...options,
658
- headers: {
659
- "Content-Type": "text/javascript",
660
- },
661
- });
662
- }
663
- };
664
- event.respondWith(handler());
665
- }
666
- };
667
- self.addEventListener("fetch", fetchListener);
668
- register(() => self.removeEventListener("fetch", fetchListener));
669
-
670
- return clear;
671
- }
672
-
673
- // --------------------------------------------
674
- // errors.js
675
-
676
- // --------------------------------------------
677
-
678
- function newClientsRegistry({
679
- self,
680
- key = "clientsIds",
681
- get,
682
- set,
683
- }) {
684
- let _index;
685
- async function loadClientsIndex() {
686
- if (!_index) {
687
- const entries = (await get(key)) || [];
688
- _index = Object.fromEntries(entries);
689
- }
690
- return _index;
691
- }
692
- async function storeClientsIndex() {
693
- const index = await loadClientsIndex();
694
- const entries = Object.entries(index);
695
- await set(key, entries);
696
- return index;
697
- }
698
-
699
- async function addClient(clientKey, client) {
700
- const index = await loadClientsIndex();
701
- const clientId = client.id;
702
- let result = false;
703
- if (!(clientId in index)) {
704
- index[clientKey] = clientId;
705
- await storeClientsIndex();
706
- result = true;
707
- }
708
- return result;
709
- }
710
-
711
- async function removeClient(clientKey) {
712
- const index = await loadClientsIndex();
713
- let result = false;
714
- if (clientKey in index) {
715
- delete index[clientKey];
716
- await storeClientsIndex();
717
- result = true;
718
- }
719
- return result;
720
- }
721
-
722
- async function getClient(clientKey) {
723
- const index = await loadClientsIndex();
724
- const clientId = index[clientKey];
725
- const client = await self.clients.get(clientId);
726
- if (!client) {
727
- delete index[clientKey];
728
- await storeClientsIndex();
729
- }
730
- return client;
731
- }
732
-
733
- return {
734
- getClient,
735
- addClient,
736
- removeClient,
737
- };
738
- }
739
- // ----------------------------------------------------
740
- // Content of the "idb-keyval" package
741
- // import { get, set } from "idb-keyval";
742
-
743
- // function promisifyRequest(request) {
744
- // return new Promise((resolve, reject) => {
745
- // // @ts-ignore - file size hacks
746
- // request.oncomplete = request.onsuccess = () => resolve(request.result);
747
- // // @ts-ignore - file size hacks
748
- // request.onabort = request.onerror = () => reject(request.error);
749
- // });
750
- // }
751
- // function createStore(dbName, storeName) {
752
- // const request = indexedDB.open(dbName);
753
- // request.onupgradeneeded = () => request.result.createObjectStore(storeName);
754
- // const dbp = promisifyRequest(request);
755
- // return (txMode, callback) =>
756
- // dbp.then((db) =>
757
- // callback(db.transaction(storeName, txMode).objectStore(storeName))
758
- // );
759
- // }
760
- // let defaultGetStoreFunc;
761
- // function defaultGetStore() {
762
- // if (!defaultGetStoreFunc) {
763
- // defaultGetStoreFunc = createStore("keyval-store", "keyval");
764
- // }
765
- // return defaultGetStoreFunc;
766
- // }
767
- // /**
768
- // * Get a value by its key.
769
- // *
770
- // * @param key
771
- // * @param customStore Method to get a custom store. Use with caution (see the docs).
772
- // */
773
- // function get(key, customStore = defaultGetStore()) {
774
- // return customStore("readonly", (store) => promisifyRequest(store.get(key)));
775
- // }
776
- // /**
777
- // * Set a value with a key.
778
- // *
779
- // * @param key
780
- // * @param value
781
- // * @param customStore Method to get a custom store. Use with caution (see the docs).
782
- // */
783
- // function set(key, value, customStore = defaultGetStore()) {
784
- // return customStore("readwrite", (store) => {
785
- // store.put(value, key);
786
- // return promisifyRequest(store.transaction);
787
- // });
788
- // }
789
-
790
- startRelayServiceWorker(self);
791
- //