postalworker-es 4.0.8 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +171 -35
- package/dist/PostalSharedWorker.js +415 -511
- package/dist/PostalSharedWorker.js.map +7 -0
- package/dist/PostalWorker.min.js +2 -171
- package/dist/PostalWorker.min.js.map +7 -0
- package/dist/compat.d.ts +53 -0
- package/dist/core.d.ts +113 -0
- package/dist/cross.d.ts +32 -0
- package/dist/emitter.d.ts +15 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +901 -0
- package/dist/index.js.map +7 -0
- package/dist/protocol.d.ts +154 -0
- package/dist/types.d.ts +92 -0
- package/dist/worker-script.d.ts +48 -0
- package/dist/worker-script.js +8 -0
- package/dist/worker-script.js.map +7 -0
- package/package.json +47 -71
- package/dist/PolyfillSharedWorker.js +0 -525
- package/dist/PostalWorker.es.js +0 -408
|
@@ -1,529 +1,433 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
return '[Throws: ' + (err ? err.message : '?') + ']';
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function safeGetValueFromPropertyOnObject(obj, property) {
|
|
31
|
-
if (hasProp.call(obj, property)) {
|
|
32
|
-
try {
|
|
33
|
-
return obj[property];
|
|
34
|
-
}
|
|
35
|
-
catch (err) {
|
|
36
|
-
return throwsMessage(err);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
return obj[property];
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function ensureProperties(obj) {
|
|
44
|
-
var seen = [ ]; // store references to objects we have seen before
|
|
45
|
-
|
|
46
|
-
function visit(obj) {
|
|
47
|
-
if (obj === null || typeof obj !== 'object') {
|
|
48
|
-
return obj;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
if (seen.indexOf(obj) !== -1) {
|
|
52
|
-
return '[Circular]';
|
|
53
|
-
}
|
|
54
|
-
seen.push(obj);
|
|
55
|
-
|
|
56
|
-
if (typeof obj.toJSON === 'function') {
|
|
57
|
-
try {
|
|
58
|
-
var fResult = visit(obj.toJSON());
|
|
59
|
-
seen.pop();
|
|
60
|
-
return fResult;
|
|
61
|
-
} catch(err) {
|
|
62
|
-
return throwsMessage(err);
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
if (Array.isArray(obj)) {
|
|
67
|
-
var aResult = obj.map(visit);
|
|
68
|
-
seen.pop();
|
|
69
|
-
return aResult;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
var result = Object.keys(obj).reduce(function(result, prop) {
|
|
73
|
-
// prevent faulty defined getter properties
|
|
74
|
-
result[prop] = visit(safeGetValueFromPropertyOnObject(obj, prop));
|
|
75
|
-
return result;
|
|
76
|
-
}, {});
|
|
77
|
-
seen.pop();
|
|
78
|
-
return result;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
return visit(obj);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
var index = function(data, replacer, space) {
|
|
85
|
-
return JSON.stringify(ensureProperties(data), replacer, space);
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
var ensureProperties_1 = ensureProperties;
|
|
89
|
-
|
|
90
|
-
index.ensureProperties = ensureProperties_1;
|
|
91
|
-
|
|
92
|
-
/**
|
|
93
|
-
* Postal Worker - Shared Worker Thread Engine
|
|
94
|
-
* @Description: Use web worker threading to fork threads and use postMessage to pass serialized data between threads and windows
|
|
95
|
-
* @Author: Russ Stratfull
|
|
96
|
-
* @Contributors: Sakshi Dheer, & Francois Wauquier
|
|
97
|
-
*/
|
|
98
|
-
|
|
99
|
-
const _env = {
|
|
100
|
-
_id: "SharedWorker",
|
|
101
|
-
_members: {},
|
|
102
|
-
_stringify: index,
|
|
103
|
-
_events: new Map(),
|
|
104
|
-
_scripts: new Map(),
|
|
105
|
-
_channel: new BroadcastChannel(POSTAL_WORKER),
|
|
106
|
-
_subscriptions: new Map(),
|
|
107
|
-
_postBoxes: {},
|
|
108
|
-
_packages: {},
|
|
109
|
-
PostalWorker: {}
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* Load a library (script) into the worker
|
|
114
|
-
* @param {*} msg
|
|
115
|
-
*/
|
|
116
|
-
function _loadLibrary(msg) {
|
|
117
|
-
let scrpt = _env._scripts.get(msg.data);
|
|
118
|
-
// if script already exists, don't reload it
|
|
119
|
-
if (scrpt) {
|
|
120
|
-
// just add window id to it
|
|
121
|
-
if (!scrpt.includes(msg.id)) scrpt.push(msg.id);
|
|
122
|
-
} else {
|
|
123
|
-
try {
|
|
124
|
-
// Thank you chatGpt for this one
|
|
125
|
-
// Create a closure and importScripts in the closure
|
|
126
|
-
// this allows binding the imported script to the current scope
|
|
127
|
-
// and PostalWorker can be passed securely to it, a little like
|
|
128
|
-
// import in es modules
|
|
129
|
-
const closure = (() => {
|
|
130
|
-
importScripts(msg.data);
|
|
131
|
-
return () => {
|
|
132
|
-
return {
|
|
133
|
-
usePrivate: init
|
|
134
|
-
};
|
|
135
|
-
};
|
|
136
|
-
})();
|
|
137
|
-
const importedScript = closure();
|
|
138
|
-
// This is the magic
|
|
139
|
-
importedScript.usePrivate(PostalWorker);
|
|
140
|
-
|
|
141
|
-
_env._scripts.set(msg.data, [msg.id]);
|
|
142
|
-
} catch (e) {
|
|
143
|
-
console.error(e);
|
|
144
|
-
_env._channel.postMessage(
|
|
145
|
-
_env._stringify({
|
|
146
|
-
postal: true,
|
|
147
|
-
type: "ERROR",
|
|
148
|
-
data: `PostalWorkerWorker Error: Unable to load file ${msg.data}`
|
|
149
|
-
})
|
|
150
|
-
);
|
|
1
|
+
"use strict";
|
|
2
|
+
(() => {
|
|
3
|
+
// src/emitter.ts
|
|
4
|
+
var Registry = class {
|
|
5
|
+
#handlers = /* @__PURE__ */ new Map();
|
|
6
|
+
add(key, handler) {
|
|
7
|
+
let set = this.#handlers.get(key);
|
|
8
|
+
if (!set) {
|
|
9
|
+
set = /* @__PURE__ */ new Set();
|
|
10
|
+
this.#handlers.set(key, set);
|
|
11
|
+
}
|
|
12
|
+
set.add(handler);
|
|
13
|
+
return () => this.remove(key, handler);
|
|
14
|
+
}
|
|
15
|
+
remove(key, handler) {
|
|
16
|
+
if (!handler) {
|
|
17
|
+
this.#handlers.delete(key);
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
const set = this.#handlers.get(key);
|
|
21
|
+
if (!set) return;
|
|
22
|
+
set.delete(handler);
|
|
23
|
+
if (set.size === 0) this.#handlers.delete(key);
|
|
24
|
+
}
|
|
25
|
+
has(key) {
|
|
26
|
+
return this.#handlers.has(key);
|
|
151
27
|
}
|
|
28
|
+
keys() {
|
|
29
|
+
return [...this.#handlers.keys()];
|
|
30
|
+
}
|
|
31
|
+
clear() {
|
|
32
|
+
this.#handlers.clear();
|
|
33
|
+
}
|
|
34
|
+
emit(key, ...args) {
|
|
35
|
+
const set = this.#handlers.get(key);
|
|
36
|
+
if (!set) return;
|
|
37
|
+
for (const handler of [...set]) {
|
|
38
|
+
try {
|
|
39
|
+
handler(...args);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
reportHandlerError(key, error);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
function reportHandlerError(key, error) {
|
|
47
|
+
queueMicrotask(() => {
|
|
48
|
+
throw error instanceof Error ? Object.assign(error, { message: `PostalWorker handler for "${key}" threw: ${error.message}` }) : error;
|
|
49
|
+
});
|
|
152
50
|
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Add a node to the registry of members
|
|
157
|
-
* @param {*} msg
|
|
158
|
-
*/
|
|
159
|
-
function _addNode(msg) {
|
|
160
|
-
const { id, nodeType } = msg;
|
|
161
|
-
_env._members[id] = nodeType;
|
|
162
|
-
}
|
|
163
51
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
*/
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
if (
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
52
|
+
// src/protocol.ts
|
|
53
|
+
var PROTOCOL = 5;
|
|
54
|
+
var WORKER_ID = "worker";
|
|
55
|
+
var CHANNEL_KINDS = /* @__PURE__ */ new Set([
|
|
56
|
+
"fire",
|
|
57
|
+
"hello",
|
|
58
|
+
"worker-ready",
|
|
59
|
+
"join",
|
|
60
|
+
"leave",
|
|
61
|
+
"box-open",
|
|
62
|
+
"box-post",
|
|
63
|
+
"box-close",
|
|
64
|
+
"box-update",
|
|
65
|
+
"box-closed",
|
|
66
|
+
"package-open",
|
|
67
|
+
"package-close",
|
|
68
|
+
"package-pack",
|
|
69
|
+
"package-fetch",
|
|
70
|
+
"package-unpack",
|
|
71
|
+
"package-update",
|
|
72
|
+
"load",
|
|
73
|
+
"error"
|
|
74
|
+
]);
|
|
75
|
+
function isEnvelope(data) {
|
|
76
|
+
if (typeof data !== "object" || data === null) return false;
|
|
77
|
+
const d = data;
|
|
78
|
+
return d["__postal"] === PROTOCOL && typeof d["from"] === "string" && typeof d["kind"] === "string";
|
|
79
|
+
}
|
|
80
|
+
function isChannelMsg(data) {
|
|
81
|
+
return isEnvelope(data) && CHANNEL_KINDS.has(data.kind);
|
|
82
|
+
}
|
|
83
|
+
function envelope(from, body) {
|
|
84
|
+
return { __postal: PROTOCOL, from, ...body };
|
|
85
|
+
}
|
|
86
|
+
function inboxName(channelName, tabId) {
|
|
87
|
+
return `${channelName}#inbox#${tabId}`;
|
|
88
|
+
}
|
|
89
|
+
function reachesWorker(audience) {
|
|
90
|
+
if (audience === "all" || audience === "others" || audience === "worker") return true;
|
|
91
|
+
return audience.to === WORKER_ID;
|
|
92
|
+
}
|
|
93
|
+
function assertNever(x) {
|
|
94
|
+
throw new Error(`PostalWorker: unexpected value ${JSON.stringify(x)}`);
|
|
195
95
|
}
|
|
196
96
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
97
|
+
// src/worker/hub.ts
|
|
98
|
+
var Hub = class {
|
|
99
|
+
instance = randomId();
|
|
100
|
+
#channelName;
|
|
101
|
+
#channel;
|
|
102
|
+
/** private channels to individual tabs, opened on first use */
|
|
103
|
+
#inboxes = /* @__PURE__ */ new Map();
|
|
104
|
+
#fetchToken = 0;
|
|
105
|
+
#events = new Registry();
|
|
106
|
+
#boxes = /* @__PURE__ */ new Map();
|
|
107
|
+
#packages = /* @__PURE__ */ new Map();
|
|
108
|
+
#loaded = /* @__PURE__ */ new Set();
|
|
109
|
+
#members = /* @__PURE__ */ new Set();
|
|
110
|
+
#streams = /* @__PURE__ */ new Map();
|
|
111
|
+
api;
|
|
112
|
+
constructor(channelName) {
|
|
113
|
+
this.#channelName = channelName;
|
|
114
|
+
this.#channel = new BroadcastChannel(channelName);
|
|
115
|
+
this.#channel.addEventListener("message", (e) => this.#handle(e.data));
|
|
116
|
+
this.api = this.#createApi();
|
|
117
|
+
}
|
|
118
|
+
/** Tell every tab this worker instance is up. */
|
|
119
|
+
announce() {
|
|
120
|
+
this.#post({ kind: "worker-ready", instance: this.instance });
|
|
121
|
+
}
|
|
122
|
+
// ---------------------------------------------------------------------------
|
|
123
|
+
#handle(data) {
|
|
124
|
+
if (!isChannelMsg(data) || data.from === WORKER_ID) return;
|
|
125
|
+
const from = data.from;
|
|
126
|
+
switch (data.kind) {
|
|
127
|
+
case "hello":
|
|
128
|
+
this.#members.add(from);
|
|
129
|
+
this.announce();
|
|
130
|
+
return;
|
|
131
|
+
case "join":
|
|
132
|
+
this.#members.add(from);
|
|
133
|
+
return;
|
|
134
|
+
case "leave":
|
|
135
|
+
this.#members.delete(from);
|
|
136
|
+
for (const [address, box] of this.#boxes) {
|
|
137
|
+
box.members.delete(from);
|
|
138
|
+
this.#dropIfUnused(address, box);
|
|
139
|
+
}
|
|
140
|
+
for (const pkg of this.#packages.values()) pkg.members.delete(from);
|
|
141
|
+
this.#inboxes.get(from)?.close();
|
|
142
|
+
this.#inboxes.delete(from);
|
|
143
|
+
return;
|
|
144
|
+
case "fire":
|
|
145
|
+
if (reachesWorker(data.audience)) this.#events.emit(data.msgClass, data.message, { from });
|
|
146
|
+
return;
|
|
147
|
+
case "box-open": {
|
|
148
|
+
this.#members.add(from);
|
|
149
|
+
const box = this.#box(data.address);
|
|
150
|
+
box.members.add(from);
|
|
151
|
+
if (data.seed && (box.value === null || box.value === void 0) && data.seed.value !== null) {
|
|
152
|
+
this.#setBox(data.address, box, data.seed.value);
|
|
153
|
+
}
|
|
154
|
+
this.#post({ kind: "box-update", address: data.address, value: box.value, box: this.#snapshot(), to: from });
|
|
155
|
+
return;
|
|
213
156
|
}
|
|
214
|
-
|
|
157
|
+
case "box-post":
|
|
158
|
+
this.#setBox(data.address, this.#box(data.address), data.value);
|
|
159
|
+
return;
|
|
160
|
+
case "box-close": {
|
|
161
|
+
const box = this.#boxes.get(data.address);
|
|
162
|
+
if (box) {
|
|
163
|
+
box.members.delete(from);
|
|
164
|
+
this.#dropIfUnused(data.address, box);
|
|
165
|
+
}
|
|
166
|
+
this.#post({ kind: "box-closed", address: data.address, box: this.#snapshot(), to: from });
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
case "package-open": {
|
|
170
|
+
this.#members.add(from);
|
|
171
|
+
const pkg = this.#package(data.address);
|
|
172
|
+
pkg.members.add(from);
|
|
173
|
+
this.#postTo(from, { kind: "package-update", address: data.address, content: pkg.content, reply: true });
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
case "package-close":
|
|
177
|
+
this.#packages.get(data.address)?.members.delete(from);
|
|
178
|
+
return;
|
|
179
|
+
case "package-pack":
|
|
180
|
+
this.#setPackage(data.address, data.content);
|
|
181
|
+
return;
|
|
182
|
+
case "package-fetch": {
|
|
183
|
+
const { kind: _kind, address, ...request } = data;
|
|
184
|
+
this.#fetchPackage(address, request, from);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
case "package-unpack":
|
|
188
|
+
this.#unpack(data.address);
|
|
189
|
+
return;
|
|
190
|
+
case "load":
|
|
191
|
+
this.#load(data.url, from);
|
|
192
|
+
return;
|
|
193
|
+
// messages meant for tabs
|
|
194
|
+
case "worker-ready":
|
|
195
|
+
case "box-update":
|
|
196
|
+
case "box-closed":
|
|
197
|
+
case "package-update":
|
|
198
|
+
case "error":
|
|
199
|
+
return;
|
|
200
|
+
default:
|
|
201
|
+
assertNever(data);
|
|
202
|
+
}
|
|
215
203
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
function _postBox(msg) {
|
|
224
|
-
const { address, value } = msg;
|
|
225
|
-
let addr = _env._postBoxes[address];
|
|
226
|
-
if (addr) addr.value = value;
|
|
227
|
-
// todo: box not created case?
|
|
228
|
-
const box = Object.entries(_env._postBoxes).reduce((store, current) => {
|
|
229
|
-
store[current[0]] = current[1].value;
|
|
230
|
-
return store;
|
|
231
|
-
}, {});
|
|
232
|
-
PostalWorker().fire(COLLECT, { address, value, box });
|
|
233
|
-
// Is there a worker handler for this item?
|
|
234
|
-
for (const [key, bx] of Object.entries(_env._postBoxes)) {
|
|
235
|
-
if (key === address && bx.handlers.length) {
|
|
236
|
-
bx.handlers.forEach(handler => {
|
|
237
|
-
if (handler) handler({ address, value, box });
|
|
238
|
-
});
|
|
204
|
+
#box(address) {
|
|
205
|
+
let box = this.#boxes.get(address);
|
|
206
|
+
if (!box) {
|
|
207
|
+
box = { members: /* @__PURE__ */ new Set(), value: null, handlers: /* @__PURE__ */ new Set() };
|
|
208
|
+
this.#boxes.set(address, box);
|
|
209
|
+
}
|
|
210
|
+
return box;
|
|
239
211
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
* @param {*} msg
|
|
246
|
-
*/
|
|
247
|
-
function _closeBox(msg) {
|
|
248
|
-
const { id, address } = msg;
|
|
249
|
-
let addr = _env._postBoxes[address];
|
|
250
|
-
if (addr) {
|
|
251
|
-
addr.members = addr.members.filter(m => m !== id);
|
|
252
|
-
if (id === _env._id) addr.handlers = [];
|
|
253
|
-
if (!addr.members.length) {
|
|
254
|
-
delete _env._postBoxes[address];
|
|
212
|
+
#setBox(address, box, value) {
|
|
213
|
+
box.value = value;
|
|
214
|
+
const snapshot = this.#snapshot();
|
|
215
|
+
this.#post({ kind: "box-update", address, value, box: snapshot });
|
|
216
|
+
for (const h of [...box.handlers]) safeCall(() => h({ address, value, box: snapshot, closed: false }));
|
|
255
217
|
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
218
|
+
/** Forget a box nobody uses (no tab has it open and no worker handler). Values posted to unopened boxes are kept. */
|
|
219
|
+
#dropIfUnused(address, box) {
|
|
220
|
+
if (box.members.size === 0 && box.handlers.size === 0) this.#boxes.delete(address);
|
|
221
|
+
}
|
|
222
|
+
#snapshot() {
|
|
223
|
+
const out = {};
|
|
224
|
+
for (const [address, box] of this.#boxes) out[address] = box.value;
|
|
225
|
+
return out;
|
|
226
|
+
}
|
|
227
|
+
#package(address) {
|
|
228
|
+
let pkg = this.#packages.get(address);
|
|
229
|
+
if (!pkg) {
|
|
230
|
+
pkg = { content: null, handlers: /* @__PURE__ */ new Set(), members: /* @__PURE__ */ new Set() };
|
|
231
|
+
this.#packages.set(address, pkg);
|
|
232
|
+
}
|
|
233
|
+
return pkg;
|
|
234
|
+
}
|
|
235
|
+
/** Content packed by hand replaces any fetched content (and cancels a fetch in flight). */
|
|
236
|
+
#setPackage(address, content) {
|
|
237
|
+
const pkg = this.#package(address);
|
|
238
|
+
delete pkg.source;
|
|
239
|
+
delete pkg.pending;
|
|
240
|
+
this.#deliver(address, pkg, content);
|
|
241
|
+
}
|
|
242
|
+
#deliver(address, pkg, content) {
|
|
243
|
+
pkg.content = content;
|
|
244
|
+
for (const tab of pkg.members) this.#postTo(tab, { kind: "package-update", address, content });
|
|
245
|
+
for (const h of [...pkg.handlers]) safeCall(() => h({ address, content }));
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Fetch `url` once and cache it at `address`. Repeated requests for the same
|
|
249
|
+
* url (while in flight or after it arrived) do not fetch again unless `refresh`.
|
|
250
|
+
*/
|
|
251
|
+
#fetchPackage(address, request, from) {
|
|
252
|
+
const pkg = this.#package(address);
|
|
253
|
+
const same = pkg.source?.url === request.url && pkg.source.as === request.as;
|
|
254
|
+
if (same && !request.refresh) {
|
|
255
|
+
if (pkg.pending) {
|
|
256
|
+
pkg.pending.requesters.add(from);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
if (pkg.content !== null && pkg.content !== void 0) return;
|
|
260
|
+
}
|
|
261
|
+
const token = ++this.#fetchToken;
|
|
262
|
+
const pending = { token, requesters: /* @__PURE__ */ new Set([from]) };
|
|
263
|
+
pkg.source = { url: request.url, as: request.as };
|
|
264
|
+
pkg.pending = pending;
|
|
265
|
+
const init = {};
|
|
266
|
+
if (request.headers) init.headers = request.headers;
|
|
267
|
+
if (request.credentials) init.credentials = request.credentials;
|
|
268
|
+
fetch(request.url, init).then(async (response) => {
|
|
269
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
270
|
+
switch (request.as) {
|
|
271
|
+
case "blob":
|
|
272
|
+
return response.blob();
|
|
273
|
+
case "arrayBuffer":
|
|
274
|
+
return response.arrayBuffer();
|
|
275
|
+
case "json":
|
|
276
|
+
return response.json();
|
|
277
|
+
case "text":
|
|
278
|
+
return response.text();
|
|
279
|
+
default:
|
|
280
|
+
return assertNever(request.as);
|
|
281
|
+
}
|
|
282
|
+
}).then((content) => {
|
|
283
|
+
if (pkg.pending !== pending || this.#packages.get(address) !== pkg) return;
|
|
284
|
+
delete pkg.pending;
|
|
285
|
+
this.#deliver(address, pkg, content);
|
|
286
|
+
}).catch((error) => {
|
|
287
|
+
if (pkg.pending !== pending) return;
|
|
288
|
+
delete pkg.pending;
|
|
289
|
+
delete pkg.source;
|
|
290
|
+
const message = `PostalWorker: fetchPackage("${address}", "${request.url}") failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
291
|
+
for (const tab of pending.requesters) {
|
|
292
|
+
if (tab === WORKER_ID) console.error(message);
|
|
293
|
+
else this.#post({ kind: "error", message, to: tab });
|
|
321
294
|
}
|
|
322
295
|
});
|
|
323
296
|
}
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
if (!msg.postal) return;
|
|
334
|
-
// console.info(msg);
|
|
335
|
-
switch (msg.type) {
|
|
336
|
-
case FIRE:
|
|
337
|
-
if (_env._events.has(msg.data.msgClass)) {
|
|
338
|
-
_env._events.get(msg.data.msgClass)(msg.data.message, msg.id);
|
|
297
|
+
/** Release cached content. Subscribers get `content: null`. */
|
|
298
|
+
#unpack(address) {
|
|
299
|
+
const pkg = this.#packages.get(address);
|
|
300
|
+
if (!pkg) return;
|
|
301
|
+
delete pkg.source;
|
|
302
|
+
delete pkg.pending;
|
|
303
|
+
if (pkg.members.size === 0 && pkg.handlers.size === 0) {
|
|
304
|
+
this.#packages.delete(address);
|
|
305
|
+
return;
|
|
339
306
|
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
break;
|
|
353
|
-
case POST:
|
|
354
|
-
_postBox(msg);
|
|
355
|
-
break;
|
|
356
|
-
case CLOSEBOX:
|
|
357
|
-
_closeBox(msg);
|
|
358
|
-
break;
|
|
359
|
-
case PACKAGE:
|
|
360
|
-
_preparePackage(msg);
|
|
361
|
-
break;
|
|
362
|
-
case PACK:
|
|
363
|
-
_pack(msg);
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
const PostalWorker = () => ({
|
|
368
|
-
/**
|
|
369
|
-
*
|
|
370
|
-
* @param msgClass
|
|
371
|
-
* @param action
|
|
372
|
-
*/
|
|
373
|
-
on: (msgClass, action) => {
|
|
374
|
-
_env._events.set(msgClass, action);
|
|
375
|
-
},
|
|
376
|
-
|
|
377
|
-
/**
|
|
378
|
-
*
|
|
379
|
-
* @param msgClass
|
|
380
|
-
*/
|
|
381
|
-
un: msgClass => {
|
|
382
|
-
_env._events.delete(msgClass);
|
|
383
|
-
},
|
|
384
|
-
|
|
385
|
-
/**
|
|
386
|
-
*
|
|
387
|
-
* @param msgClass
|
|
388
|
-
* @param msg
|
|
389
|
-
*/
|
|
390
|
-
fire: (msgClass, msg) => {
|
|
391
|
-
_env._channel.postMessage(
|
|
392
|
-
_env._stringify({
|
|
393
|
-
postal: true,
|
|
394
|
-
type: FIRE,
|
|
395
|
-
id: POSTAL_SHARED_WORKER,
|
|
396
|
-
data: {
|
|
397
|
-
msgClass: msgClass,
|
|
398
|
-
message: msg
|
|
307
|
+
this.#deliver(address, pkg, null);
|
|
308
|
+
}
|
|
309
|
+
#load(url, from) {
|
|
310
|
+
if (this.#loaded.has(url)) return;
|
|
311
|
+
const scope2 = globalThis;
|
|
312
|
+
delete scope2.init;
|
|
313
|
+
try {
|
|
314
|
+
importScripts(url);
|
|
315
|
+
const init = scope2.init;
|
|
316
|
+
delete scope2.init;
|
|
317
|
+
if (typeof init !== "function") {
|
|
318
|
+
throw new Error(`${url} did not define self.init = (pw) => { \u2026 }`);
|
|
399
319
|
}
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
// message: msg,
|
|
409
|
-
// audience: audience
|
|
410
|
-
// },
|
|
411
|
-
// target
|
|
412
|
-
// );
|
|
413
|
-
},
|
|
414
|
-
|
|
415
|
-
/**
|
|
416
|
-
*
|
|
417
|
-
* @param {*} library
|
|
418
|
-
* @returns
|
|
419
|
-
*/
|
|
420
|
-
load: library => _loadLibrary(library),
|
|
421
|
-
|
|
422
|
-
/**
|
|
423
|
-
* Subscribe to Server Sent Events and create event source
|
|
424
|
-
* @param {*} endpoint
|
|
425
|
-
* @param {*} callback
|
|
426
|
-
* @param {*} errorCallback
|
|
427
|
-
*/
|
|
428
|
-
subscribe: (endpoint, callback, errorCallback) => {
|
|
429
|
-
if (!_env._subscriptions.get(endpoint)) {
|
|
430
|
-
_env._subscriptions.set(endpoint, new EventSource(endpoint));
|
|
431
|
-
_env._subscriptions.get(endpoint).onmessage = msg => {
|
|
432
|
-
callback(msg);
|
|
433
|
-
};
|
|
434
|
-
if (errorCallback) {
|
|
435
|
-
_env._subscriptions.get(endpoint).onerror = error => {
|
|
436
|
-
errorCallback(error);
|
|
437
|
-
};
|
|
320
|
+
this.#loaded.add(url);
|
|
321
|
+
init(this.api);
|
|
322
|
+
} catch (error) {
|
|
323
|
+
this.#post({
|
|
324
|
+
kind: "error",
|
|
325
|
+
message: `PostalWorker: could not load ${url} into the worker: ${error instanceof Error ? error.message : String(error)}`,
|
|
326
|
+
to: from
|
|
327
|
+
});
|
|
438
328
|
}
|
|
439
329
|
}
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
330
|
+
#post(body) {
|
|
331
|
+
this.#channel.postMessage(envelope(WORKER_ID, body));
|
|
332
|
+
}
|
|
333
|
+
/** Send to one tab only, on its private inbox channel. */
|
|
334
|
+
#postTo(tab, body) {
|
|
335
|
+
let inbox = this.#inboxes.get(tab);
|
|
336
|
+
if (!inbox) {
|
|
337
|
+
inbox = new BroadcastChannel(inboxName(this.#channelName, tab));
|
|
338
|
+
this.#inboxes.set(tab, inbox);
|
|
339
|
+
}
|
|
340
|
+
inbox.postMessage(envelope(WORKER_ID, body));
|
|
341
|
+
}
|
|
342
|
+
#createApi() {
|
|
343
|
+
const api = {
|
|
344
|
+
id: WORKER_ID,
|
|
345
|
+
on: (msgClass, handler) => this.#events.add(msgClass, handler),
|
|
346
|
+
off: (msgClass, handler) => this.#events.remove(msgClass, handler),
|
|
347
|
+
fire: (msgClass, message, audience = "all") => {
|
|
348
|
+
if (audience === "all" || audience.to === WORKER_ID) {
|
|
349
|
+
queueMicrotask(() => this.#events.emit(msgClass, message, { from: WORKER_ID }));
|
|
350
|
+
}
|
|
351
|
+
if (typeof audience === "object" && audience.to === WORKER_ID) return;
|
|
352
|
+
this.#post({ kind: "fire", msgClass, message, audience });
|
|
353
|
+
},
|
|
354
|
+
postBox: (address, handler) => {
|
|
355
|
+
const box = this.#box(address);
|
|
356
|
+
const h = handler;
|
|
357
|
+
box.handlers.add(h);
|
|
358
|
+
queueMicrotask(() => safeCall(() => h({ address, value: box.value, box: this.#snapshot(), closed: false })));
|
|
359
|
+
return () => {
|
|
360
|
+
box.handlers.delete(h);
|
|
361
|
+
this.#dropIfUnused(address, box);
|
|
362
|
+
};
|
|
363
|
+
},
|
|
364
|
+
post: (address, value) => this.#setBox(address, this.#box(address), value),
|
|
365
|
+
closeBox: (address) => {
|
|
366
|
+
const box = this.#boxes.get(address);
|
|
367
|
+
if (!box) return;
|
|
368
|
+
const handlers = [...box.handlers];
|
|
369
|
+
box.handlers.clear();
|
|
370
|
+
this.#dropIfUnused(address, box);
|
|
371
|
+
const snapshot = this.#snapshot();
|
|
372
|
+
for (const h of handlers) safeCall(() => h({ address, value: null, box: snapshot, closed: true }));
|
|
373
|
+
},
|
|
374
|
+
package: (address, handler) => {
|
|
375
|
+
const pkg = this.#package(address);
|
|
376
|
+
const h = handler;
|
|
377
|
+
pkg.handlers.add(h);
|
|
378
|
+
queueMicrotask(() => safeCall(() => h({ address, content: pkg.content })));
|
|
379
|
+
return () => pkg.handlers.delete(h);
|
|
380
|
+
},
|
|
381
|
+
pack: (address, content) => this.#setPackage(address, content),
|
|
382
|
+
fetchPackage: (address, url, options = {}) => {
|
|
383
|
+
const request = { url: new URL(url, self.location.href).href, as: options.as ?? "blob" };
|
|
384
|
+
if (options.headers) request.headers = options.headers;
|
|
385
|
+
if (options.credentials) request.credentials = options.credentials;
|
|
386
|
+
if (options.refresh) request.refresh = true;
|
|
387
|
+
this.#fetchPackage(address, request, WORKER_ID);
|
|
388
|
+
},
|
|
389
|
+
unpack: (address) => this.#unpack(address),
|
|
390
|
+
subscribe: (url, onMessage, onError) => {
|
|
391
|
+
let stream = this.#streams.get(url);
|
|
392
|
+
if (!stream) {
|
|
393
|
+
stream = new EventSource(url);
|
|
394
|
+
this.#streams.set(url, stream);
|
|
395
|
+
}
|
|
396
|
+
const s = stream;
|
|
397
|
+
const msg = (e) => onMessage(e);
|
|
398
|
+
s.addEventListener("message", msg);
|
|
399
|
+
const err = onError ? (e) => onError(e) : void 0;
|
|
400
|
+
if (err) s.addEventListener("error", err);
|
|
401
|
+
return () => {
|
|
402
|
+
s.removeEventListener("message", msg);
|
|
403
|
+
if (err) s.removeEventListener("error", err);
|
|
404
|
+
};
|
|
405
|
+
},
|
|
406
|
+
members: () => [...this.#members]
|
|
496
407
|
};
|
|
497
|
-
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
});
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
onconnect = () => {
|
|
513
|
-
// New messaging method using broadcast channel
|
|
514
|
-
if (!_env._channel.onmessage)
|
|
515
|
-
_env._channel.onmessage = event => {
|
|
516
|
-
const data = JSON.parse(event.data);
|
|
517
|
-
_processChannelMessage(data);
|
|
518
|
-
};
|
|
519
|
-
|
|
520
|
-
// Announce alive to broadcast channel
|
|
521
|
-
_env._channel.postMessage(
|
|
522
|
-
_env._stringify({
|
|
523
|
-
postal: true,
|
|
524
|
-
type: WORKERREGISTER
|
|
525
|
-
})
|
|
526
|
-
);
|
|
527
|
-
};
|
|
408
|
+
return Object.assign(() => api, api);
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
function safeCall(fn) {
|
|
412
|
+
try {
|
|
413
|
+
fn();
|
|
414
|
+
} catch (error) {
|
|
415
|
+
queueMicrotask(() => {
|
|
416
|
+
throw error;
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
function randomId() {
|
|
421
|
+
return typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
422
|
+
}
|
|
528
423
|
|
|
529
|
-
|
|
424
|
+
// src/worker/index.ts
|
|
425
|
+
var scope = self;
|
|
426
|
+
var hub = new Hub(scope.name || "PostalWorker");
|
|
427
|
+
scope.onconnect = (e) => {
|
|
428
|
+
e.ports[0]?.start();
|
|
429
|
+
hub.announce();
|
|
430
|
+
};
|
|
431
|
+
hub.announce();
|
|
432
|
+
})();
|
|
433
|
+
//# sourceMappingURL=PostalSharedWorker.js.map
|