postalworker-es 5.0.0 → 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 +23 -4
- package/dist/PostalSharedWorker.js +115 -3
- package/dist/PostalSharedWorker.js.map +2 -2
- package/dist/PostalWorker.min.js +1 -1
- package/dist/PostalWorker.min.js.map +3 -3
- package/dist/core.d.ts +10 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +44 -3
- package/dist/index.js.map +2 -2
- package/dist/protocol.d.ts +31 -2
- package/dist/types.d.ts +15 -0
- package/dist/worker-script.d.ts +5 -1
- package/dist/worker-script.js.map +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -67,14 +67,33 @@ postal.closeBox("volume"); // or close(): one last call with value null, close
|
|
|
67
67
|
|
|
68
68
|
Values live in the worker, so a tab opening the box later gets the current value.
|
|
69
69
|
|
|
70
|
-
## Packages: shared content
|
|
70
|
+
## Packages: shared content and a media cache
|
|
71
|
+
|
|
72
|
+
A package is content the worker keeps for every tab: media, large arrays, parsed JSON.
|
|
73
|
+
|
|
74
|
+
Let the worker fetch it. However many tabs ask, the url is downloaded once, and a tab that subscribes later gets the cached copy:
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
// in each window that shows the waveform or video
|
|
78
|
+
const off = postal.package("take-1", ({ content }) => {
|
|
79
|
+
if (content) video.src = URL.createObjectURL(content); // revoke it when you're done
|
|
80
|
+
});
|
|
81
|
+
postal.fetchPackage("take-1", "/media/take-1.mp4");
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
- Content goes only to tabs subscribed with `package()`; other tabs never receive it.
|
|
85
|
+
- `as` picks the format: `"blob"` (default), `"arrayBuffer"`, `"json"`, `"text"`. Also `headers`, `credentials`, and `refresh: true` to download again.
|
|
86
|
+
- **Blobs are cheap to share**: sending a Blob to a tab passes a handle to the same data, not a copy, so three windows playing the same video hold it once. Each tab makes its own object URL. Other formats (ArrayBuffer, JSON) are parsed once in the worker but copied into each subscribing tab, since windows do not share memory.
|
|
87
|
+
- The cache lives in the worker's memory until `postal.unpack(address)`; subscribers then get `content: null`. If the url fails, the tabs that asked get an error (see `onError`).
|
|
88
|
+
- Unsubscribing does not empty the cache, so the next window opens instantly.
|
|
89
|
+
|
|
90
|
+
You can also pack content yourself; it replaces anything fetched:
|
|
71
91
|
|
|
72
92
|
```ts
|
|
73
|
-
postal.
|
|
74
|
-
postal.pack("avatar", await (await fetch("/me.png")).blob());
|
|
93
|
+
postal.pack("avatar", await canvas.convertToBlob());
|
|
75
94
|
```
|
|
76
95
|
|
|
77
|
-
Content can be anything structured-cloneable (Blob, ArrayBuffer, objects…).
|
|
96
|
+
Content can be anything structured-cloneable (Blob, ArrayBuffer, objects…). Worker scripts have the same `pw.fetchPackage()`, `pw.pack()` and `pw.unpack()`, so a script can prefetch or post-process (for example, decode audio once and pack the waveform peaks).
|
|
78
97
|
|
|
79
98
|
## Worker scripts
|
|
80
99
|
|
|
@@ -64,7 +64,10 @@
|
|
|
64
64
|
"box-update",
|
|
65
65
|
"box-closed",
|
|
66
66
|
"package-open",
|
|
67
|
+
"package-close",
|
|
67
68
|
"package-pack",
|
|
69
|
+
"package-fetch",
|
|
70
|
+
"package-unpack",
|
|
68
71
|
"package-update",
|
|
69
72
|
"load",
|
|
70
73
|
"error"
|
|
@@ -80,6 +83,9 @@
|
|
|
80
83
|
function envelope(from, body) {
|
|
81
84
|
return { __postal: PROTOCOL, from, ...body };
|
|
82
85
|
}
|
|
86
|
+
function inboxName(channelName, tabId) {
|
|
87
|
+
return `${channelName}#inbox#${tabId}`;
|
|
88
|
+
}
|
|
83
89
|
function reachesWorker(audience) {
|
|
84
90
|
if (audience === "all" || audience === "others" || audience === "worker") return true;
|
|
85
91
|
return audience.to === WORKER_ID;
|
|
@@ -91,7 +97,11 @@
|
|
|
91
97
|
// src/worker/hub.ts
|
|
92
98
|
var Hub = class {
|
|
93
99
|
instance = randomId();
|
|
100
|
+
#channelName;
|
|
94
101
|
#channel;
|
|
102
|
+
/** private channels to individual tabs, opened on first use */
|
|
103
|
+
#inboxes = /* @__PURE__ */ new Map();
|
|
104
|
+
#fetchToken = 0;
|
|
95
105
|
#events = new Registry();
|
|
96
106
|
#boxes = /* @__PURE__ */ new Map();
|
|
97
107
|
#packages = /* @__PURE__ */ new Map();
|
|
@@ -100,6 +110,7 @@
|
|
|
100
110
|
#streams = /* @__PURE__ */ new Map();
|
|
101
111
|
api;
|
|
102
112
|
constructor(channelName) {
|
|
113
|
+
this.#channelName = channelName;
|
|
103
114
|
this.#channel = new BroadcastChannel(channelName);
|
|
104
115
|
this.#channel.addEventListener("message", (e) => this.#handle(e.data));
|
|
105
116
|
this.api = this.#createApi();
|
|
@@ -126,6 +137,9 @@
|
|
|
126
137
|
box.members.delete(from);
|
|
127
138
|
this.#dropIfUnused(address, box);
|
|
128
139
|
}
|
|
140
|
+
for (const pkg of this.#packages.values()) pkg.members.delete(from);
|
|
141
|
+
this.#inboxes.get(from)?.close();
|
|
142
|
+
this.#inboxes.delete(from);
|
|
129
143
|
return;
|
|
130
144
|
case "fire":
|
|
131
145
|
if (reachesWorker(data.audience)) this.#events.emit(data.msgClass, data.message, { from });
|
|
@@ -153,13 +167,26 @@
|
|
|
153
167
|
return;
|
|
154
168
|
}
|
|
155
169
|
case "package-open": {
|
|
170
|
+
this.#members.add(from);
|
|
156
171
|
const pkg = this.#package(data.address);
|
|
157
|
-
|
|
172
|
+
pkg.members.add(from);
|
|
173
|
+
this.#postTo(from, { kind: "package-update", address: data.address, content: pkg.content, reply: true });
|
|
158
174
|
return;
|
|
159
175
|
}
|
|
176
|
+
case "package-close":
|
|
177
|
+
this.#packages.get(data.address)?.members.delete(from);
|
|
178
|
+
return;
|
|
160
179
|
case "package-pack":
|
|
161
180
|
this.#setPackage(data.address, data.content);
|
|
162
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;
|
|
163
190
|
case "load":
|
|
164
191
|
this.#load(data.url, from);
|
|
165
192
|
return;
|
|
@@ -200,17 +227,85 @@
|
|
|
200
227
|
#package(address) {
|
|
201
228
|
let pkg = this.#packages.get(address);
|
|
202
229
|
if (!pkg) {
|
|
203
|
-
pkg = { content: null, handlers: /* @__PURE__ */ new Set() };
|
|
230
|
+
pkg = { content: null, handlers: /* @__PURE__ */ new Set(), members: /* @__PURE__ */ new Set() };
|
|
204
231
|
this.#packages.set(address, pkg);
|
|
205
232
|
}
|
|
206
233
|
return pkg;
|
|
207
234
|
}
|
|
235
|
+
/** Content packed by hand replaces any fetched content (and cancels a fetch in flight). */
|
|
208
236
|
#setPackage(address, content) {
|
|
209
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) {
|
|
210
243
|
pkg.content = content;
|
|
211
|
-
this.#
|
|
244
|
+
for (const tab of pkg.members) this.#postTo(tab, { kind: "package-update", address, content });
|
|
212
245
|
for (const h of [...pkg.handlers]) safeCall(() => h({ address, content }));
|
|
213
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 });
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
}
|
|
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;
|
|
306
|
+
}
|
|
307
|
+
this.#deliver(address, pkg, null);
|
|
308
|
+
}
|
|
214
309
|
#load(url, from) {
|
|
215
310
|
if (this.#loaded.has(url)) return;
|
|
216
311
|
const scope2 = globalThis;
|
|
@@ -235,6 +330,15 @@
|
|
|
235
330
|
#post(body) {
|
|
236
331
|
this.#channel.postMessage(envelope(WORKER_ID, body));
|
|
237
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
|
+
}
|
|
238
342
|
#createApi() {
|
|
239
343
|
const api = {
|
|
240
344
|
id: WORKER_ID,
|
|
@@ -275,6 +379,14 @@
|
|
|
275
379
|
return () => pkg.handlers.delete(h);
|
|
276
380
|
},
|
|
277
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),
|
|
278
390
|
subscribe: (url, onMessage, onError) => {
|
|
279
391
|
let stream = this.#streams.get(url);
|
|
280
392
|
if (!stream) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/emitter.ts", "../src/protocol.ts", "../src/worker/hub.ts", "../src/worker/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Minimal handler registry: any number of handlers per key.\n * Shared by the window library and the worker. A throwing handler is\n * reported but never stops the other handlers.\n */\nexport type AnyHandler = (...args: never[]) => void;\n\nexport class Registry<H extends AnyHandler> {\n readonly #handlers = new Map<string, Set<H>>();\n\n add(key: string, handler: H): () => void {\n let set = this.#handlers.get(key);\n if (!set) {\n set = new Set();\n this.#handlers.set(key, set);\n }\n set.add(handler);\n return () => this.remove(key, handler);\n }\n\n remove(key: string, handler?: H): void {\n if (!handler) {\n this.#handlers.delete(key);\n return;\n }\n const set = this.#handlers.get(key);\n if (!set) return;\n set.delete(handler);\n if (set.size === 0) this.#handlers.delete(key);\n }\n\n has(key: string): boolean {\n return this.#handlers.has(key);\n }\n\n keys(): string[] {\n return [...this.#handlers.keys()];\n }\n\n clear(): void {\n this.#handlers.clear();\n }\n\n emit(key: string, ...args: Parameters<H>): void {\n const set = this.#handlers.get(key);\n if (!set) return;\n // copy so handlers may unsubscribe while we iterate\n for (const handler of [...set]) {\n try {\n (handler as (...a: Parameters<H>) => void)(...args);\n } catch (error) {\n reportHandlerError(key, error);\n }\n }\n }\n}\n\nfunction reportHandlerError(key: string, error: unknown): void {\n // Surface the error without breaking delivery to other handlers.\n queueMicrotask(() => {\n throw error instanceof Error\n ? Object.assign(error, { message: `PostalWorker handler for \"${key}\" threw: ${error.message}` })\n : error;\n });\n}\n", "/**\n * Wire protocol shared by windows and the worker.\n * Messages are plain objects sent with structured clone (no JSON strings),\n * tagged with `__postal` so foreign traffic is ignored.\n * This file must stay free of DOM- or worker-only types.\n */\n\nexport const PROTOCOL = 5 as const;\n\n/** id the worker uses as `from` */\nexport const WORKER_ID = \"worker\" as const;\n\n/** Audience values that travel over the channel (`\"local\"` never does). */\nexport type WireAudience = \"all\" | \"others\" | \"worker\" | { to: string };\n\ninterface Base {\n __postal: typeof PROTOCOL;\n from: string;\n}\n\n// ---- Channel messages (BroadcastChannel: windows <-> worker <-> windows) ----\n\nexport interface FireMsg extends Base {\n kind: \"fire\";\n msgClass: string;\n message: unknown;\n audience: WireAudience;\n}\nexport interface HelloMsg extends Base {\n kind: \"hello\";\n}\nexport interface WorkerReadyMsg extends Base {\n kind: \"worker-ready\";\n /** changes whenever a new worker instance starts (e.g. fallback leader handover) */\n instance: string;\n}\nexport interface JoinMsg extends Base {\n kind: \"join\";\n}\nexport interface LeaveMsg extends Base {\n kind: \"leave\";\n}\nexport interface BoxOpenMsg extends Base {\n kind: \"box-open\";\n address: string;\n /** value to restore if the worker has none (used after a worker restart) */\n seed?: { value: unknown };\n}\nexport interface BoxPostMsg extends Base {\n kind: \"box-post\";\n address: string;\n value: unknown;\n}\nexport interface BoxCloseMsg extends Base {\n kind: \"box-close\";\n address: string;\n}\nexport interface BoxUpdateMsg extends Base {\n kind: \"box-update\";\n address: string;\n value: unknown;\n box: Record<string, unknown>;\n /** when set, only this tab should handle it */\n to?: string;\n}\nexport interface BoxClosedMsg extends Base {\n kind: \"box-closed\";\n address: string;\n box: Record<string, unknown>;\n to: string;\n}\nexport interface PackageOpenMsg extends Base {\n kind: \"package-open\";\n address: string;\n}\nexport interface PackagePackMsg extends Base {\n kind: \"package-pack\";\n address: string;\n content: unknown;\n}\nexport interface PackageUpdateMsg extends Base {\n kind: \"package-update\";\n address: string;\n content: unknown;\n to?: string;\n}\nexport interface LoadMsg extends Base {\n kind: \"load\";\n url: string;\n}\nexport interface ErrorMsg extends Base {\n kind: \"error\";\n message: string;\n to?: string;\n}\n\nexport type ChannelMsg =\n | FireMsg\n | HelloMsg\n | WorkerReadyMsg\n | JoinMsg\n | LeaveMsg\n | BoxOpenMsg\n | BoxPostMsg\n | BoxCloseMsg\n | BoxUpdateMsg\n | BoxClosedMsg\n | PackageOpenMsg\n | PackagePackMsg\n | PackageUpdateMsg\n | LoadMsg\n | ErrorMsg;\n\n/** Distributive Omit so each union member keeps its own fields. */\nexport type Body<T> = T extends unknown ? Omit<T, \"__postal\" | \"from\"> : never;\n\n// ---- Cross-window messages (window.postMessage: iframes, popups, other origins) ----\n\nexport interface CrossHelloMsg extends Base {\n kind: \"cross-hello\";\n}\nexport interface CrossAckMsg extends Base {\n kind: \"cross-ack\";\n}\nexport interface CrossProbeMsg extends Base {\n kind: \"cross-probe\";\n}\nexport interface CrossByeMsg extends Base {\n kind: \"cross-bye\";\n}\nexport interface CrossMsg extends Base {\n kind: \"cross\";\n msgClass: string;\n message: unknown;\n /** sent with backFire (child -> parent) */\n back: boolean;\n}\n\nexport type CrossWindowMsg = CrossHelloMsg | CrossAckMsg | CrossProbeMsg | CrossByeMsg | CrossMsg;\n\nconst CHANNEL_KINDS: ReadonlySet<string> = new Set<ChannelMsg[\"kind\"]>([\n \"fire\",\n \"hello\",\n \"worker-ready\",\n \"join\",\n \"leave\",\n \"box-open\",\n \"box-post\",\n \"box-close\",\n \"box-update\",\n \"box-closed\",\n \"package-open\",\n \"package-pack\",\n \"package-update\",\n \"load\",\n \"error\",\n]);\n\nconst CROSS_KINDS: ReadonlySet<string> = new Set<CrossWindowMsg[\"kind\"]>([\n \"cross-hello\",\n \"cross-ack\",\n \"cross-probe\",\n \"cross-bye\",\n \"cross\",\n]);\n\nfunction isEnvelope(data: unknown): data is { __postal: 5; from: string; kind: string } {\n if (typeof data !== \"object\" || data === null) return false;\n const d = data as Record<string, unknown>;\n return d[\"__postal\"] === PROTOCOL && typeof d[\"from\"] === \"string\" && typeof d[\"kind\"] === \"string\";\n}\n\nexport function isChannelMsg(data: unknown): data is ChannelMsg {\n return isEnvelope(data) && CHANNEL_KINDS.has(data.kind);\n}\n\nexport function isCrossWindowMsg(data: unknown): data is CrossWindowMsg {\n return isEnvelope(data) && CROSS_KINDS.has(data.kind);\n}\n\nexport function envelope<T extends ChannelMsg | CrossWindowMsg>(from: string, body: Body<T>): T {\n return { __postal: PROTOCOL, from, ...body } as T;\n}\n\n/** Does a channel `fire` with this audience reach the tab `selfId`? (The sender handles itself locally.) */\nexport function reachesTab(audience: WireAudience, selfId: string): boolean {\n if (audience === \"all\" || audience === \"others\") return true;\n if (audience === \"worker\") return false;\n return audience.to === selfId;\n}\n\n/** Does a channel `fire` with this audience reach the worker? */\nexport function reachesWorker(audience: WireAudience): boolean {\n if (audience === \"all\" || audience === \"others\" || audience === \"worker\") return true;\n return audience.to === WORKER_ID;\n}\n\n/** Throw on an exhaustive switch's impossible branch. */\nexport function assertNever(x: never): never {\n throw new Error(`PostalWorker: unexpected value ${JSON.stringify(x)}`);\n}\n", "/**\n * The worker side of PostalWorker. Runs inside the SharedWorker, or inside\n * the single dedicated Worker hosted by the elected tab (fallback mode).\n * Owns shared state (boxes, packages, loaded scripts) and talks to every tab\n * over the BroadcastChannel.\n */\nimport { Registry } from \"../emitter\";\nimport {\n WORKER_ID,\n assertNever,\n envelope,\n isChannelMsg,\n reachesWorker,\n type Body,\n type ChannelMsg,\n} from \"../protocol\";\nimport type { BoxItem, MessageMeta, PackageItem, Unsubscribe } from \"../types\";\nimport type { WorkerApi, WorkerAudience, WorkerScriptApi } from \"../worker-script\";\n\ntype AnyHandler = (message: unknown, meta: MessageMeta) => void;\ntype BoxHandler = (item: BoxItem<Record<string, unknown>, string>) => void;\ntype PackageHandler = (item: PackageItem<Record<string, unknown>, string>) => void;\n\ninterface Box {\n members: Set<string>;\n value: unknown;\n handlers: Set<BoxHandler>;\n}\ninterface Package {\n content: unknown;\n handlers: Set<PackageHandler>;\n}\n\nexport class Hub {\n readonly instance = randomId();\n readonly #channel: BroadcastChannel;\n readonly #events = new Registry<AnyHandler>();\n readonly #boxes = new Map<string, Box>();\n readonly #packages = new Map<string, Package>();\n readonly #loaded = new Set<string>();\n readonly #members = new Set<string>();\n readonly #streams = new Map<string, EventSource>();\n readonly api: WorkerScriptApi;\n\n constructor(channelName: string) {\n this.#channel = new BroadcastChannel(channelName);\n this.#channel.addEventListener(\"message\", (e: MessageEvent) => this.#handle(e.data));\n this.api = this.#createApi();\n }\n\n /** Tell every tab this worker instance is up. */\n announce(): void {\n this.#post({ kind: \"worker-ready\", instance: this.instance });\n }\n\n // ---------------------------------------------------------------------------\n\n #handle(data: unknown): void {\n if (!isChannelMsg(data) || data.from === WORKER_ID) return;\n const from = data.from;\n switch (data.kind) {\n case \"hello\":\n this.#members.add(from);\n this.announce();\n return;\n case \"join\":\n this.#members.add(from);\n return;\n case \"leave\":\n this.#members.delete(from);\n for (const [address, box] of this.#boxes) {\n box.members.delete(from);\n this.#dropIfUnused(address, box);\n }\n return;\n case \"fire\":\n if (reachesWorker(data.audience)) this.#events.emit(data.msgClass, data.message, { from });\n return;\n case \"box-open\": {\n this.#members.add(from);\n const box = this.#box(data.address);\n box.members.add(from);\n if (data.seed && (box.value === null || box.value === undefined) && data.seed.value !== null) {\n this.#setBox(data.address, box, data.seed.value);\n }\n this.#post({ kind: \"box-update\", address: data.address, value: box.value, box: this.#snapshot(), to: from });\n return;\n }\n case \"box-post\":\n this.#setBox(data.address, this.#box(data.address), data.value);\n return;\n case \"box-close\": {\n const box = this.#boxes.get(data.address);\n if (box) {\n box.members.delete(from);\n this.#dropIfUnused(data.address, box);\n }\n this.#post({ kind: \"box-closed\", address: data.address, box: this.#snapshot(), to: from });\n return;\n }\n case \"package-open\": {\n const pkg = this.#package(data.address);\n this.#post({ kind: \"package-update\", address: data.address, content: pkg.content, to: from });\n return;\n }\n case \"package-pack\":\n this.#setPackage(data.address, data.content);\n return;\n case \"load\":\n this.#load(data.url, from);\n return;\n // messages meant for tabs\n case \"worker-ready\":\n case \"box-update\":\n case \"box-closed\":\n case \"package-update\":\n case \"error\":\n return;\n default:\n assertNever(data);\n }\n }\n\n #box(address: string): Box {\n let box = this.#boxes.get(address);\n if (!box) {\n box = { members: new Set(), value: null, handlers: new Set() };\n this.#boxes.set(address, box);\n }\n return box;\n }\n\n #setBox(address: string, box: Box, value: unknown): void {\n box.value = value;\n const snapshot = this.#snapshot();\n this.#post({ kind: \"box-update\", address, value, box: snapshot });\n for (const h of [...box.handlers]) safeCall(() => h({ address, value, box: snapshot, closed: false }));\n }\n\n /** Forget a box nobody uses (no tab has it open and no worker handler). Values posted to unopened boxes are kept. */\n #dropIfUnused(address: string, box: Box): void {\n if (box.members.size === 0 && box.handlers.size === 0) this.#boxes.delete(address);\n }\n\n #snapshot(): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [address, box] of this.#boxes) out[address] = box.value;\n return out;\n }\n\n #package(address: string): Package {\n let pkg = this.#packages.get(address);\n if (!pkg) {\n pkg = { content: null, handlers: new Set() };\n this.#packages.set(address, pkg);\n }\n return pkg;\n }\n\n #setPackage(address: string, content: unknown): void {\n const pkg = this.#package(address);\n pkg.content = content;\n this.#post({ kind: \"package-update\", address, content });\n for (const h of [...pkg.handlers]) safeCall(() => h({ address, content }));\n }\n\n #load(url: string, from: string): void {\n if (this.#loaded.has(url)) return;\n const scope = globalThis as { init?: unknown };\n delete scope.init;\n try {\n importScripts(url);\n const init = scope.init;\n delete scope.init;\n if (typeof init !== \"function\") {\n throw new Error(`${url} did not define self.init = (pw) => { \u2026 }`);\n }\n this.#loaded.add(url);\n (init as (pw: WorkerScriptApi) => void)(this.api);\n } catch (error) {\n this.#post({\n kind: \"error\",\n message: `PostalWorker: could not load ${url} into the worker: ${error instanceof Error ? error.message : String(error)}`,\n to: from,\n });\n }\n }\n\n #post(body: Body<ChannelMsg>): void {\n this.#channel.postMessage(envelope(WORKER_ID, body));\n }\n\n #createApi(): WorkerScriptApi {\n const api: WorkerApi = {\n id: WORKER_ID,\n on: (msgClass, handler) => this.#events.add(msgClass, handler as AnyHandler),\n off: (msgClass, handler) => this.#events.remove(msgClass, handler as AnyHandler | undefined),\n fire: (msgClass, message, audience: WorkerAudience = \"all\") => {\n if (audience === \"all\" || audience.to === WORKER_ID) {\n queueMicrotask(() => this.#events.emit(msgClass, message, { from: WORKER_ID }));\n }\n if (typeof audience === \"object\" && audience.to === WORKER_ID) return;\n this.#post({ kind: \"fire\", msgClass, message, audience });\n },\n postBox: (address, handler) => {\n const box = this.#box(address);\n const h = handler as BoxHandler;\n box.handlers.add(h);\n queueMicrotask(() => safeCall(() => h({ address, value: box.value, box: this.#snapshot(), closed: false })));\n return () => {\n box.handlers.delete(h);\n this.#dropIfUnused(address, box);\n };\n },\n post: (address, value) => this.#setBox(address, this.#box(address), value),\n closeBox: (address) => {\n const box = this.#boxes.get(address);\n if (!box) return;\n const handlers = [...box.handlers];\n box.handlers.clear();\n this.#dropIfUnused(address, box);\n const snapshot = this.#snapshot();\n for (const h of handlers) safeCall(() => h({ address, value: null, box: snapshot, closed: true }));\n },\n package: (address, handler): Unsubscribe => {\n const pkg = this.#package(address);\n const h = handler as PackageHandler;\n pkg.handlers.add(h);\n queueMicrotask(() => safeCall(() => h({ address, content: pkg.content })));\n return () => pkg.handlers.delete(h);\n },\n pack: (address, content) => this.#setPackage(address, content),\n subscribe: (url, onMessage, onError) => {\n let stream = this.#streams.get(url);\n if (!stream) {\n stream = new EventSource(url);\n this.#streams.set(url, stream);\n }\n const s = stream;\n const msg = (e: MessageEvent<string>): void => onMessage(e);\n s.addEventListener(\"message\", msg);\n const err = onError ? (e: Event): void => onError(e) : undefined;\n if (err) s.addEventListener(\"error\", err);\n return () => {\n s.removeEventListener(\"message\", msg);\n if (err) s.removeEventListener(\"error\", err);\n };\n },\n members: () => [...this.#members],\n };\n // v4 scripts call PostalWorker().on(\u2026); v5 scripts call pw.on(\u2026). Support both.\n return Object.assign(() => api, api) as WorkerScriptApi;\n }\n}\n\nfunction safeCall(fn: () => void): void {\n try {\n fn();\n } catch (error) {\n queueMicrotask(() => {\n throw error;\n });\n }\n}\n\nfunction randomId(): string {\n return typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\"\n ? crypto.randomUUID()\n : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n", "/**\n * Worker entry: build this file as a classic (IIFE) script, dist/PostalSharedWorker.js.\n * The same file runs as a SharedWorker or as the fallback dedicated Worker.\n * The worker name (set by the library) is the BroadcastChannel name.\n */\nimport { Hub } from \"./hub\";\n\nconst scope = self as unknown as { name?: string; onconnect?: ((e: MessageEvent) => void) | null };\nconst hub = new Hub(scope.name || \"PostalWorker\");\n\n// SharedWorker: tabs connect through ports, but all traffic uses the BroadcastChannel.\n// Starting the port keeps the connection (and so the worker) alive for that tab.\nscope.onconnect = (e: MessageEvent) => {\n e.ports[0]?.start();\n hub.announce();\n};\n\nhub.announce();\n"],
|
|
5
|
-
"mappings": ";;;AAOO,MAAM,WAAN,MAAqC;AAAA,IACjC,YAAY,oBAAI,IAAoB;AAAA,IAE7C,IAAI,KAAa,SAAwB;AACvC,UAAI,MAAM,KAAK,UAAU,IAAI,GAAG;AAChC,UAAI,CAAC,KAAK;AACR,cAAM,oBAAI,IAAI;AACd,aAAK,UAAU,IAAI,KAAK,GAAG;AAAA,MAC7B;AACA,UAAI,IAAI,OAAO;AACf,aAAO,MAAM,KAAK,OAAO,KAAK,OAAO;AAAA,IACvC;AAAA,IAEA,OAAO,KAAa,SAAmB;AACrC,UAAI,CAAC,SAAS;AACZ,aAAK,UAAU,OAAO,GAAG;AACzB;AAAA,MACF;AACA,YAAM,MAAM,KAAK,UAAU,IAAI,GAAG;AAClC,UAAI,CAAC,IAAK;AACV,UAAI,OAAO,OAAO;AAClB,UAAI,IAAI,SAAS,EAAG,MAAK,UAAU,OAAO,GAAG;AAAA,IAC/C;AAAA,IAEA,IAAI,KAAsB;AACxB,aAAO,KAAK,UAAU,IAAI,GAAG;AAAA,IAC/B;AAAA,IAEA,OAAiB;AACf,aAAO,CAAC,GAAG,KAAK,UAAU,KAAK,CAAC;AAAA,IAClC;AAAA,IAEA,QAAc;AACZ,WAAK,UAAU,MAAM;AAAA,IACvB;AAAA,IAEA,KAAK,QAAgB,MAA2B;AAC9C,YAAM,MAAM,KAAK,UAAU,IAAI,GAAG;AAClC,UAAI,CAAC,IAAK;AAEV,iBAAW,WAAW,CAAC,GAAG,GAAG,GAAG;AAC9B,YAAI;AACF,UAAC,QAA0C,GAAG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B,SAAS,GAAG;AACxC,iBAAO,MAAM;AACX,cAAE,oBAAoB,WAAW,GAAG;AACpC,gBAAI,IAAK,GAAE,oBAAoB,SAAS,GAAG;AAAA,UAC7C;AAAA,QACF;AAAA,QACA,SAAS,MAAM,CAAC,GAAG,KAAK,QAAQ;AAAA,MAClC;AAEA,aAAO,OAAO,OAAO,MAAM,KAAK,GAAG;AAAA,IACrC;AAAA,EACF;AAEA,WAAS,SAAS,IAAsB;AACtC,QAAI;AACF,SAAG;AAAA,IACL,SAAS,OAAO;AACd,qBAAe,MAAM;AACnB,cAAM;AAAA,MACR,CAAC;AAAA,IACH;AAAA,EACF;AAEA,WAAS,WAAmB;AAC1B,WAAO,OAAO,WAAW,eAAe,OAAO,OAAO,eAAe,aACjE,OAAO,WAAW,IAClB,GAAG,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC;AAAA,EACvE;;;ACtQA,MAAM,QAAQ;AACd,MAAM,MAAM,IAAI,IAAI,MAAM,QAAQ,cAAc;AAIhD,QAAM,YAAY,CAAC,MAAoB;AACrC,MAAE,MAAM,CAAC,GAAG,MAAM;AAClB,QAAI,SAAS;AAAA,EACf;AAEA,MAAI,SAAS;",
|
|
4
|
+
"sourcesContent": ["/**\n * Minimal handler registry: any number of handlers per key.\n * Shared by the window library and the worker. A throwing handler is\n * reported but never stops the other handlers.\n */\nexport type AnyHandler = (...args: never[]) => void;\n\nexport class Registry<H extends AnyHandler> {\n readonly #handlers = new Map<string, Set<H>>();\n\n add(key: string, handler: H): () => void {\n let set = this.#handlers.get(key);\n if (!set) {\n set = new Set();\n this.#handlers.set(key, set);\n }\n set.add(handler);\n return () => this.remove(key, handler);\n }\n\n remove(key: string, handler?: H): void {\n if (!handler) {\n this.#handlers.delete(key);\n return;\n }\n const set = this.#handlers.get(key);\n if (!set) return;\n set.delete(handler);\n if (set.size === 0) this.#handlers.delete(key);\n }\n\n has(key: string): boolean {\n return this.#handlers.has(key);\n }\n\n keys(): string[] {\n return [...this.#handlers.keys()];\n }\n\n clear(): void {\n this.#handlers.clear();\n }\n\n emit(key: string, ...args: Parameters<H>): void {\n const set = this.#handlers.get(key);\n if (!set) return;\n // copy so handlers may unsubscribe while we iterate\n for (const handler of [...set]) {\n try {\n (handler as (...a: Parameters<H>) => void)(...args);\n } catch (error) {\n reportHandlerError(key, error);\n }\n }\n }\n}\n\nfunction reportHandlerError(key: string, error: unknown): void {\n // Surface the error without breaking delivery to other handlers.\n queueMicrotask(() => {\n throw error instanceof Error\n ? Object.assign(error, { message: `PostalWorker handler for \"${key}\" threw: ${error.message}` })\n : error;\n });\n}\n", "/**\n * Wire protocol shared by windows and the worker.\n * Messages are plain objects sent with structured clone (no JSON strings),\n * tagged with `__postal` so foreign traffic is ignored.\n * This file must stay free of DOM- or worker-only types.\n */\n\nexport const PROTOCOL = 5 as const;\n\n/** id the worker uses as `from` */\nexport const WORKER_ID = \"worker\" as const;\n\n/** Audience values that travel over the channel (`\"local\"` never does). */\nexport type WireAudience = \"all\" | \"others\" | \"worker\" | { to: string };\n\ninterface Base {\n __postal: typeof PROTOCOL;\n from: string;\n}\n\n// ---- Channel messages (BroadcastChannel: windows <-> worker <-> windows) ----\n\nexport interface FireMsg extends Base {\n kind: \"fire\";\n msgClass: string;\n message: unknown;\n audience: WireAudience;\n}\nexport interface HelloMsg extends Base {\n kind: \"hello\";\n}\nexport interface WorkerReadyMsg extends Base {\n kind: \"worker-ready\";\n /** changes whenever a new worker instance starts (e.g. fallback leader handover) */\n instance: string;\n}\nexport interface JoinMsg extends Base {\n kind: \"join\";\n}\nexport interface LeaveMsg extends Base {\n kind: \"leave\";\n}\nexport interface BoxOpenMsg extends Base {\n kind: \"box-open\";\n address: string;\n /** value to restore if the worker has none (used after a worker restart) */\n seed?: { value: unknown };\n}\nexport interface BoxPostMsg extends Base {\n kind: \"box-post\";\n address: string;\n value: unknown;\n}\nexport interface BoxCloseMsg extends Base {\n kind: \"box-close\";\n address: string;\n}\nexport interface BoxUpdateMsg extends Base {\n kind: \"box-update\";\n address: string;\n value: unknown;\n box: Record<string, unknown>;\n /** when set, only this tab should handle it */\n to?: string;\n}\nexport interface BoxClosedMsg extends Base {\n kind: \"box-closed\";\n address: string;\n box: Record<string, unknown>;\n to: string;\n}\nexport interface PackageOpenMsg extends Base {\n kind: \"package-open\";\n address: string;\n}\nexport interface PackageCloseMsg extends Base {\n kind: \"package-close\";\n address: string;\n}\nexport interface PackagePackMsg extends Base {\n kind: \"package-pack\";\n address: string;\n content: unknown;\n}\n/** How the worker reads a fetched response before caching it. */\nexport type PackageFormat = \"blob\" | \"arrayBuffer\" | \"json\" | \"text\";\nexport interface PackageFetchMsg extends Base {\n kind: \"package-fetch\";\n address: string;\n /** absolute URL */\n url: string;\n as: PackageFormat;\n headers?: Record<string, string>;\n credentials?: \"omit\" | \"same-origin\" | \"include\";\n /** fetch again even if this url is already cached */\n refresh?: boolean;\n}\nexport interface PackageUnpackMsg extends Base {\n kind: \"package-unpack\";\n address: string;\n}\n/**\n * Package content. Sent only on a subscribing tab's private inbox channel\n * (see `inboxName`), never on the shared channel, so tabs that did not\n * subscribe never receive (or deserialize) large content.\n */\nexport interface PackageUpdateMsg extends Base {\n kind: \"package-update\";\n address: string;\n content: unknown;\n /** answer to this tab's package-open (as opposed to a new pack/fetch/unpack) */\n reply?: boolean;\n}\nexport interface LoadMsg extends Base {\n kind: \"load\";\n url: string;\n}\nexport interface ErrorMsg extends Base {\n kind: \"error\";\n message: string;\n to?: string;\n}\n\nexport type ChannelMsg =\n | FireMsg\n | HelloMsg\n | WorkerReadyMsg\n | JoinMsg\n | LeaveMsg\n | BoxOpenMsg\n | BoxPostMsg\n | BoxCloseMsg\n | BoxUpdateMsg\n | BoxClosedMsg\n | PackageOpenMsg\n | PackageCloseMsg\n | PackagePackMsg\n | PackageFetchMsg\n | PackageUnpackMsg\n | PackageUpdateMsg\n | LoadMsg\n | ErrorMsg;\n\n/** Distributive Omit so each union member keeps its own fields. */\nexport type Body<T> = T extends unknown ? Omit<T, \"__postal\" | \"from\"> : never;\n\n// ---- Cross-window messages (window.postMessage: iframes, popups, other origins) ----\n\nexport interface CrossHelloMsg extends Base {\n kind: \"cross-hello\";\n}\nexport interface CrossAckMsg extends Base {\n kind: \"cross-ack\";\n}\nexport interface CrossProbeMsg extends Base {\n kind: \"cross-probe\";\n}\nexport interface CrossByeMsg extends Base {\n kind: \"cross-bye\";\n}\nexport interface CrossMsg extends Base {\n kind: \"cross\";\n msgClass: string;\n message: unknown;\n /** sent with backFire (child -> parent) */\n back: boolean;\n}\n\nexport type CrossWindowMsg = CrossHelloMsg | CrossAckMsg | CrossProbeMsg | CrossByeMsg | CrossMsg;\n\nconst CHANNEL_KINDS: ReadonlySet<string> = new Set<ChannelMsg[\"kind\"]>([\n \"fire\",\n \"hello\",\n \"worker-ready\",\n \"join\",\n \"leave\",\n \"box-open\",\n \"box-post\",\n \"box-close\",\n \"box-update\",\n \"box-closed\",\n \"package-open\",\n \"package-close\",\n \"package-pack\",\n \"package-fetch\",\n \"package-unpack\",\n \"package-update\",\n \"load\",\n \"error\",\n]);\n\nconst CROSS_KINDS: ReadonlySet<string> = new Set<CrossWindowMsg[\"kind\"]>([\n \"cross-hello\",\n \"cross-ack\",\n \"cross-probe\",\n \"cross-bye\",\n \"cross\",\n]);\n\nfunction isEnvelope(data: unknown): data is { __postal: 5; from: string; kind: string } {\n if (typeof data !== \"object\" || data === null) return false;\n const d = data as Record<string, unknown>;\n return d[\"__postal\"] === PROTOCOL && typeof d[\"from\"] === \"string\" && typeof d[\"kind\"] === \"string\";\n}\n\nexport function isChannelMsg(data: unknown): data is ChannelMsg {\n return isEnvelope(data) && CHANNEL_KINDS.has(data.kind);\n}\n\nexport function isCrossWindowMsg(data: unknown): data is CrossWindowMsg {\n return isEnvelope(data) && CROSS_KINDS.has(data.kind);\n}\n\nexport function envelope<T extends ChannelMsg | CrossWindowMsg>(from: string, body: Body<T>): T {\n return { __postal: PROTOCOL, from, ...body } as T;\n}\n\n/** Name of a tab's private BroadcastChannel, used for content meant for that tab only. */\nexport function inboxName(channelName: string, tabId: string): string {\n return `${channelName}#inbox#${tabId}`;\n}\n\n/** Does a channel `fire` with this audience reach the tab `selfId`? (The sender handles itself locally.) */\nexport function reachesTab(audience: WireAudience, selfId: string): boolean {\n if (audience === \"all\" || audience === \"others\") return true;\n if (audience === \"worker\") return false;\n return audience.to === selfId;\n}\n\n/** Does a channel `fire` with this audience reach the worker? */\nexport function reachesWorker(audience: WireAudience): boolean {\n if (audience === \"all\" || audience === \"others\" || audience === \"worker\") return true;\n return audience.to === WORKER_ID;\n}\n\n/** Throw on an exhaustive switch's impossible branch. */\nexport function assertNever(x: never): never {\n throw new Error(`PostalWorker: unexpected value ${JSON.stringify(x)}`);\n}\n", "/**\n * The worker side of PostalWorker. Runs inside the SharedWorker, or inside\n * the single dedicated Worker hosted by the elected tab (fallback mode).\n * Owns shared state (boxes, packages, loaded scripts) and talks to every tab\n * over the BroadcastChannel.\n */\nimport { Registry } from \"../emitter\";\nimport {\n WORKER_ID,\n assertNever,\n envelope,\n inboxName,\n isChannelMsg,\n reachesWorker,\n type Body,\n type ChannelMsg,\n type PackageFetchMsg,\n} from \"../protocol\";\nimport type { BoxItem, FetchPackageOptions, MessageMeta, PackageItem, Unsubscribe } from \"../types\";\nimport type { WorkerApi, WorkerAudience, WorkerScriptApi } from \"../worker-script\";\n\ntype AnyHandler = (message: unknown, meta: MessageMeta) => void;\ntype BoxHandler = (item: BoxItem<Record<string, unknown>, string>) => void;\ntype PackageHandler = (item: PackageItem<Record<string, unknown>, string>) => void;\n\ninterface Box {\n members: Set<string>;\n value: unknown;\n handlers: Set<BoxHandler>;\n}\ninterface Package {\n content: unknown;\n handlers: Set<PackageHandler>;\n /** tabs subscribed to this package; only they receive its content */\n members: Set<string>;\n /** where the cached content came from, when it was fetched by the worker */\n source?: { url: string; as: string };\n /** a fetch in flight, and who asked for it (to report errors) */\n pending?: { token: number; requesters: Set<string> };\n}\n\ntype FetchRequest = Omit<Body<PackageFetchMsg>, \"kind\" | \"address\">;\n\nexport class Hub {\n readonly instance = randomId();\n readonly #channelName: string;\n readonly #channel: BroadcastChannel;\n /** private channels to individual tabs, opened on first use */\n readonly #inboxes = new Map<string, BroadcastChannel>();\n #fetchToken = 0;\n readonly #events = new Registry<AnyHandler>();\n readonly #boxes = new Map<string, Box>();\n readonly #packages = new Map<string, Package>();\n readonly #loaded = new Set<string>();\n readonly #members = new Set<string>();\n readonly #streams = new Map<string, EventSource>();\n readonly api: WorkerScriptApi;\n\n constructor(channelName: string) {\n this.#channelName = channelName;\n this.#channel = new BroadcastChannel(channelName);\n this.#channel.addEventListener(\"message\", (e: MessageEvent) => this.#handle(e.data));\n this.api = this.#createApi();\n }\n\n /** Tell every tab this worker instance is up. */\n announce(): void {\n this.#post({ kind: \"worker-ready\", instance: this.instance });\n }\n\n // ---------------------------------------------------------------------------\n\n #handle(data: unknown): void {\n if (!isChannelMsg(data) || data.from === WORKER_ID) return;\n const from = data.from;\n switch (data.kind) {\n case \"hello\":\n this.#members.add(from);\n this.announce();\n return;\n case \"join\":\n this.#members.add(from);\n return;\n case \"leave\":\n this.#members.delete(from);\n for (const [address, box] of this.#boxes) {\n box.members.delete(from);\n this.#dropIfUnused(address, box);\n }\n for (const pkg of this.#packages.values()) pkg.members.delete(from);\n this.#inboxes.get(from)?.close();\n this.#inboxes.delete(from);\n return;\n case \"fire\":\n if (reachesWorker(data.audience)) this.#events.emit(data.msgClass, data.message, { from });\n return;\n case \"box-open\": {\n this.#members.add(from);\n const box = this.#box(data.address);\n box.members.add(from);\n if (data.seed && (box.value === null || box.value === undefined) && data.seed.value !== null) {\n this.#setBox(data.address, box, data.seed.value);\n }\n this.#post({ kind: \"box-update\", address: data.address, value: box.value, box: this.#snapshot(), to: from });\n return;\n }\n case \"box-post\":\n this.#setBox(data.address, this.#box(data.address), data.value);\n return;\n case \"box-close\": {\n const box = this.#boxes.get(data.address);\n if (box) {\n box.members.delete(from);\n this.#dropIfUnused(data.address, box);\n }\n this.#post({ kind: \"box-closed\", address: data.address, box: this.#snapshot(), to: from });\n return;\n }\n case \"package-open\": {\n this.#members.add(from);\n const pkg = this.#package(data.address);\n pkg.members.add(from);\n this.#postTo(from, { kind: \"package-update\", address: data.address, content: pkg.content, reply: true });\n return;\n }\n case \"package-close\":\n // the content stays cached for the next subscriber; unpack() releases it\n this.#packages.get(data.address)?.members.delete(from);\n return;\n case \"package-pack\":\n this.#setPackage(data.address, data.content);\n return;\n case \"package-fetch\": {\n const { kind: _kind, address, ...request } = data;\n this.#fetchPackage(address, request, from);\n return;\n }\n case \"package-unpack\":\n this.#unpack(data.address);\n return;\n case \"load\":\n this.#load(data.url, from);\n return;\n // messages meant for tabs\n case \"worker-ready\":\n case \"box-update\":\n case \"box-closed\":\n case \"package-update\":\n case \"error\":\n return;\n default:\n assertNever(data);\n }\n }\n\n #box(address: string): Box {\n let box = this.#boxes.get(address);\n if (!box) {\n box = { members: new Set(), value: null, handlers: new Set() };\n this.#boxes.set(address, box);\n }\n return box;\n }\n\n #setBox(address: string, box: Box, value: unknown): void {\n box.value = value;\n const snapshot = this.#snapshot();\n this.#post({ kind: \"box-update\", address, value, box: snapshot });\n for (const h of [...box.handlers]) safeCall(() => h({ address, value, box: snapshot, closed: false }));\n }\n\n /** Forget a box nobody uses (no tab has it open and no worker handler). Values posted to unopened boxes are kept. */\n #dropIfUnused(address: string, box: Box): void {\n if (box.members.size === 0 && box.handlers.size === 0) this.#boxes.delete(address);\n }\n\n #snapshot(): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [address, box] of this.#boxes) out[address] = box.value;\n return out;\n }\n\n #package(address: string): Package {\n let pkg = this.#packages.get(address);\n if (!pkg) {\n pkg = { content: null, handlers: new Set(), members: new Set() };\n this.#packages.set(address, pkg);\n }\n return pkg;\n }\n\n /** Content packed by hand replaces any fetched content (and cancels a fetch in flight). */\n #setPackage(address: string, content: unknown): void {\n const pkg = this.#package(address);\n delete pkg.source;\n delete pkg.pending;\n this.#deliver(address, pkg, content);\n }\n\n #deliver(address: string, pkg: Package, content: unknown): void {\n pkg.content = content;\n for (const tab of pkg.members) this.#postTo(tab, { kind: \"package-update\", address, content });\n for (const h of [...pkg.handlers]) safeCall(() => h({ address, content }));\n }\n\n /**\n * Fetch `url` once and cache it at `address`. Repeated requests for the same\n * url (while in flight or after it arrived) do not fetch again unless `refresh`.\n */\n #fetchPackage(address: string, request: FetchRequest, from: string): void {\n const pkg = this.#package(address);\n const same = pkg.source?.url === request.url && pkg.source.as === request.as;\n if (same && !request.refresh) {\n if (pkg.pending) {\n pkg.pending.requesters.add(from);\n return;\n }\n if (pkg.content !== null && pkg.content !== undefined) return; // cached; subscribers already have it\n }\n const token = ++this.#fetchToken;\n const pending = { token, requesters: new Set([from]) };\n pkg.source = { url: request.url, as: request.as };\n pkg.pending = pending;\n const init: RequestInit = {};\n if (request.headers) init.headers = request.headers;\n if (request.credentials) init.credentials = request.credentials;\n fetch(request.url, init)\n .then(async (response) => {\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n switch (request.as) {\n case \"blob\":\n return response.blob();\n case \"arrayBuffer\":\n return response.arrayBuffer();\n case \"json\":\n return response.json() as Promise<unknown>;\n case \"text\":\n return response.text();\n default:\n return assertNever(request.as);\n }\n })\n .then((content) => {\n // superseded by pack(), unpack() or a refresh\n if (pkg.pending !== pending || this.#packages.get(address) !== pkg) return;\n delete pkg.pending;\n this.#deliver(address, pkg, content);\n })\n .catch((error: unknown) => {\n if (pkg.pending !== pending) return;\n delete pkg.pending;\n delete pkg.source;\n const message = `PostalWorker: fetchPackage(\"${address}\", \"${request.url}\") failed: ${error instanceof Error ? error.message : String(error)}`;\n for (const tab of pending.requesters) {\n if (tab === WORKER_ID) console.error(message);\n else this.#post({ kind: \"error\", message, to: tab });\n }\n });\n }\n\n /** Release cached content. Subscribers get `content: null`. */\n #unpack(address: string): void {\n const pkg = this.#packages.get(address);\n if (!pkg) return;\n delete pkg.source;\n delete pkg.pending;\n if (pkg.members.size === 0 && pkg.handlers.size === 0) {\n this.#packages.delete(address);\n return;\n }\n this.#deliver(address, pkg, null);\n }\n\n #load(url: string, from: string): void {\n if (this.#loaded.has(url)) return;\n const scope = globalThis as { init?: unknown };\n delete scope.init;\n try {\n importScripts(url);\n const init = scope.init;\n delete scope.init;\n if (typeof init !== \"function\") {\n throw new Error(`${url} did not define self.init = (pw) => { \u2026 }`);\n }\n this.#loaded.add(url);\n (init as (pw: WorkerScriptApi) => void)(this.api);\n } catch (error) {\n this.#post({\n kind: \"error\",\n message: `PostalWorker: could not load ${url} into the worker: ${error instanceof Error ? error.message : String(error)}`,\n to: from,\n });\n }\n }\n\n #post(body: Body<ChannelMsg>): void {\n this.#channel.postMessage(envelope(WORKER_ID, body));\n }\n\n /** Send to one tab only, on its private inbox channel. */\n #postTo(tab: string, body: Body<ChannelMsg>): void {\n let inbox = this.#inboxes.get(tab);\n if (!inbox) {\n inbox = new BroadcastChannel(inboxName(this.#channelName, tab));\n this.#inboxes.set(tab, inbox);\n }\n inbox.postMessage(envelope(WORKER_ID, body));\n }\n\n #createApi(): WorkerScriptApi {\n const api: WorkerApi = {\n id: WORKER_ID,\n on: (msgClass, handler) => this.#events.add(msgClass, handler as AnyHandler),\n off: (msgClass, handler) => this.#events.remove(msgClass, handler as AnyHandler | undefined),\n fire: (msgClass, message, audience: WorkerAudience = \"all\") => {\n if (audience === \"all\" || audience.to === WORKER_ID) {\n queueMicrotask(() => this.#events.emit(msgClass, message, { from: WORKER_ID }));\n }\n if (typeof audience === \"object\" && audience.to === WORKER_ID) return;\n this.#post({ kind: \"fire\", msgClass, message, audience });\n },\n postBox: (address, handler) => {\n const box = this.#box(address);\n const h = handler as BoxHandler;\n box.handlers.add(h);\n queueMicrotask(() => safeCall(() => h({ address, value: box.value, box: this.#snapshot(), closed: false })));\n return () => {\n box.handlers.delete(h);\n this.#dropIfUnused(address, box);\n };\n },\n post: (address, value) => this.#setBox(address, this.#box(address), value),\n closeBox: (address) => {\n const box = this.#boxes.get(address);\n if (!box) return;\n const handlers = [...box.handlers];\n box.handlers.clear();\n this.#dropIfUnused(address, box);\n const snapshot = this.#snapshot();\n for (const h of handlers) safeCall(() => h({ address, value: null, box: snapshot, closed: true }));\n },\n package: (address, handler): Unsubscribe => {\n const pkg = this.#package(address);\n const h = handler as PackageHandler;\n pkg.handlers.add(h);\n queueMicrotask(() => safeCall(() => h({ address, content: pkg.content })));\n return () => pkg.handlers.delete(h);\n },\n pack: (address, content) => this.#setPackage(address, content),\n fetchPackage: (address, url, options: FetchPackageOptions = {}) => {\n const request: FetchRequest = { url: new URL(url, self.location.href).href, as: options.as ?? \"blob\" };\n if (options.headers) request.headers = options.headers;\n if (options.credentials) request.credentials = options.credentials;\n if (options.refresh) request.refresh = true;\n this.#fetchPackage(address, request, WORKER_ID);\n },\n unpack: (address) => this.#unpack(address),\n subscribe: (url, onMessage, onError) => {\n let stream = this.#streams.get(url);\n if (!stream) {\n stream = new EventSource(url);\n this.#streams.set(url, stream);\n }\n const s = stream;\n const msg = (e: MessageEvent<string>): void => onMessage(e);\n s.addEventListener(\"message\", msg);\n const err = onError ? (e: Event): void => onError(e) : undefined;\n if (err) s.addEventListener(\"error\", err);\n return () => {\n s.removeEventListener(\"message\", msg);\n if (err) s.removeEventListener(\"error\", err);\n };\n },\n members: () => [...this.#members],\n };\n // v4 scripts call PostalWorker().on(\u2026); v5 scripts call pw.on(\u2026). Support both.\n return Object.assign(() => api, api) as WorkerScriptApi;\n }\n}\n\nfunction safeCall(fn: () => void): void {\n try {\n fn();\n } catch (error) {\n queueMicrotask(() => {\n throw error;\n });\n }\n}\n\nfunction randomId(): string {\n return typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\"\n ? crypto.randomUUID()\n : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n}\n", "/**\n * Worker entry: build this file as a classic (IIFE) script, dist/PostalSharedWorker.js.\n * The same file runs as a SharedWorker or as the fallback dedicated Worker.\n * The worker name (set by the library) is the BroadcastChannel name.\n */\nimport { Hub } from \"./hub\";\n\nconst scope = self as unknown as { name?: string; onconnect?: ((e: MessageEvent) => void) | null };\nconst hub = new Hub(scope.name || \"PostalWorker\");\n\n// SharedWorker: tabs connect through ports, but all traffic uses the BroadcastChannel.\n// Starting the port keeps the connection (and so the worker) alive for that tab.\nscope.onconnect = (e: MessageEvent) => {\n e.ports[0]?.start();\n hub.announce();\n};\n\nhub.announce();\n"],
|
|
5
|
+
"mappings": ";;;AAOO,MAAM,WAAN,MAAqC;AAAA,IACjC,YAAY,oBAAI,IAAoB;AAAA,IAE7C,IAAI,KAAa,SAAwB;AACvC,UAAI,MAAM,KAAK,UAAU,IAAI,GAAG;AAChC,UAAI,CAAC,KAAK;AACR,cAAM,oBAAI,IAAI;AACd,aAAK,UAAU,IAAI,KAAK,GAAG;AAAA,MAC7B;AACA,UAAI,IAAI,OAAO;AACf,aAAO,MAAM,KAAK,OAAO,KAAK,OAAO;AAAA,IACvC;AAAA,IAEA,OAAO,KAAa,SAAmB;AACrC,UAAI,CAAC,SAAS;AACZ,aAAK,UAAU,OAAO,GAAG;AACzB;AAAA,MACF;AACA,YAAM,MAAM,KAAK,UAAU,IAAI,GAAG;AAClC,UAAI,CAAC,IAAK;AACV,UAAI,OAAO,OAAO;AAClB,UAAI,IAAI,SAAS,EAAG,MAAK,UAAU,OAAO,GAAG;AAAA,IAC/C;AAAA,IAEA,IAAI,KAAsB;AACxB,aAAO,KAAK,UAAU,IAAI,GAAG;AAAA,IAC/B;AAAA,IAEA,OAAiB;AACf,aAAO,CAAC,GAAG,KAAK,UAAU,KAAK,CAAC;AAAA,IAClC;AAAA,IAEA,QAAc;AACZ,WAAK,UAAU,MAAM;AAAA,IACvB;AAAA,IAEA,KAAK,QAAgB,MAA2B;AAC9C,YAAM,MAAM,KAAK,UAAU,IAAI,GAAG;AAClC,UAAI,CAAC,IAAK;AAEV,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AO,MAAM,KAAK,GAAG;AAAA,IACrC;AAAA,EACF;AAEA,WAAS,SAAS,IAAsB;AACtC,QAAI;AACF,SAAG;AAAA,IACL,SAAS,OAAO;AACd,qBAAe,MAAM;AACnB,cAAM;AAAA,MACR,CAAC;AAAA,IACH;AAAA,EACF;AAEA,WAAS,WAAmB;AAC1B,WAAO,OAAO,WAAW,eAAe,OAAO,OAAO,eAAe,aACjE,OAAO,WAAW,IAClB,GAAG,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC;AAAA,EACvE;;;ACnYA,MAAM,QAAQ;AACd,MAAM,MAAM,IAAI,IAAI,MAAM,QAAQ,cAAc;AAIhD,QAAM,YAAY,CAAC,MAAoB;AACrC,MAAE,MAAM,CAAC,GAAG,MAAM;AAClB,QAAI,SAAS;AAAA,EACf;AAEA,MAAI,SAAS;",
|
|
6
6
|
"names": ["scope"]
|
|
7
7
|
}
|
package/dist/PostalWorker.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";(()=>{var S=new Set(["fire","hello","worker-ready","join","leave","box-open","box-post","box-close","box-update","box-closed","package-open","package-pack","package-update","load","error"]),B=new Set(["cross-hello","cross-ack","cross-probe","cross-bye","cross"]);function w(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.__postal===5&&typeof e.from=="string"&&typeof e.kind=="string"}function m(t){return w(t)&&S.has(t.kind)}function y(t){return w(t)&&B.has(t.kind)}function d(t,e){return{__postal:5,from:t,...e}}function v(t,e){return t==="all"||t==="others"?!0:t==="worker"?!1:t.to===e}function x(t){throw new Error(`PostalWorker: unexpected value ${JSON.stringify(t)}`)}var E=2e3,g=class{#e;#r=new Map;#t=new Map;#a=new Set;#o=[];#d;#l=e=>this.#c(e);constructor(e){if(this.#e=e,this.#a.add(window.location.origin),e.allowedOrigins!=="*")for(let i of e.allowedOrigins)this.#a.add(b(i));let r=this.isFramed?K():void 0;r&&this.#a.add(r);let s=u(),n=s?O():void 0;n&&this.#a.add(n),window.addEventListener("message",this.#l);let o=!1;this.isFramed&&(this.#i(window.parent,"*",{kind:"cross-hello"}),o=!0),s&&(this.#i(s,"*",{kind:"cross-hello"}),o=!0),o&&(this.#d=setTimeout(()=>this.#k(),E)),this.probeFrames()}get isFramed(){try{return window.self!==window.top}catch{return!0}}probeFrames(){for(let e=0;e<window.frames.length;e++){let r=window.frames[e];r&&this.#i(r,"*",{kind:"cross-probe"})}}open(e,r,s){let n=new URL(e,window.location.href),o=window.open(n.href,r,s);return o?(this.#t.set(o,n.origin),o):(console.warn(`PostalWorker: window.open("${n.href}") returned null (popup blocked, or "noopener" was set). That window cannot be messaged.`),null)}send(e,r){let s=()=>{this.#f();for(let n of this.#r.values())this.#i(n.win,n.origin,{kind:"cross",msgClass:e,message:r,back:!1})};this.#p(s)}sendBack(e,r){return this.isFramed?(this.#p(()=>{let s=[...this.#r.values()].find(n=>n.relation==="parent");s?this.#i(s.win,s.origin,{kind:"cross",msgClass:e,message:r,back:!0}):console.warn("PostalWorker: backFire dropped, the parent window never answered (is PostalWorker running there, and does it trust this origin?)")}),!0):!1}closeOrigin(e){let r=b(e);for(let[s,n]of this.#r)if(n.origin===r){if(n.relation==="opened")try{n.win.close()}catch{}this.#r.delete(s)}for(let[s,n]of this.#t)if(n===r){try{s.close()}catch{}this.#t.delete(s)}}targets(){return this.#f(),[...this.#r.values()]}sayGoodbye(){for(let e of this.#r.values())this.#i(e.win,e.origin,{kind:"cross-bye"})}destroy(){this.sayGoodbye(),window.removeEventListener("message",this.#l),clearTimeout(this.#d),this.#r.clear(),this.#t.clear(),this.#o=[]}#c(e){let r=e.data;if(!y(r))return;let s=e.source;if(L(s)&&r.from!==this.#e.selfId){if(!this.#h(e.origin,s)){console.warn(`PostalWorker: ignored a message from untrusted origin ${e.origin}. Add it to "allowedOrigins" to accept it.`);return}switch(r.kind){case"cross-probe":this.#i(s,e.origin,{kind:"cross-hello"});return;case"cross-hello":this.#n(r.from,s,e.origin),this.#i(s,e.origin,{kind:"cross-ack"});return;case"cross-ack":this.#n(r.from,s,e.origin),(s===window.parent||s===u())&&this.#k();return;case"cross-bye":this.#r.delete(r.from);return;case"cross":this.#r.has(r.from)||this.#n(r.from,s,e.origin),this.#e.onMessage(r.msgClass,r.message,r.from,e.origin,r.back);return}}}#n(e,r,s){let n="peer";this.isFramed&&r===window.parent?n="parent":r===u()?n="opener":this.#t.has(r)?n="opened":R(r)&&(n="child");for(let[o,i]of this.#r)i.win===r&&o!==e&&this.#r.delete(o);this.#r.set(e,{id:e,win:r,origin:s,relation:n})}#h(e,r){if(this.#e.allowedOrigins==="*"||this.#a.has(e))return!0;let s=this.#t.get(r);return s&&s===e?!0:A(r,e)}#p(e){this.#d===void 0?e():this.#o.push(e)}#k(){clearTimeout(this.#d),this.#d=void 0;let e=this.#o;this.#o=[];for(let r of e)r()}#f(){for(let[e,r]of this.#r)r.win.closed&&this.#r.delete(e);for(let e of this.#t.keys())e.closed&&this.#t.delete(e)}#i(e,r,s){try{e.postMessage(d(this.#e.selfId,s),r)}catch(n){console.warn("PostalWorker: cross-window postMessage failed",n)}}};function L(t){return t!==null&&typeof t.postMessage=="function"&&"closed"in t}function u(){try{let t=window.opener;return t&&t!==window?t:null}catch{return null}}function b(t){try{return new URL(t,window.location.href).origin}catch{return String(t)}}function O(){if(document.referrer)try{return new URL(document.referrer).origin}catch{return}}function K(){let t=window.location.ancestorOrigins;return t&&t.length>0?t[0]:O()}function W(){return Array.from(document.querySelectorAll("iframe"))}function R(t){return W().some(e=>e.contentWindow===t)}function A(t,e){for(let r of W())if(r.contentWindow===t)try{return new URL(r.src,window.location.href).origin===e}catch{return!1}return!1}function C(t){return t?typeof t=="string"?t:Object.entries(t).map(([e,r])=>`${e}=${r===!0?"yes":r===!1?"no":String(r)}`).join(","):""}var l=class{#e=new Map;add(e,r){let s=this.#e.get(e);return s||(s=new Set,this.#e.set(e,s)),s.add(r),()=>this.remove(e,r)}remove(e,r){if(!r){this.#e.delete(e);return}let s=this.#e.get(e);s&&(s.delete(r),s.size===0&&this.#e.delete(e))}has(e){return this.#e.has(e)}keys(){return[...this.#e.keys()]}clear(){this.#e.clear()}emit(e,...r){let s=this.#e.get(e);if(s)for(let n of[...s])try{n(...r)}catch(o){T(e,o)}}};function T(t,e){queueMicrotask(()=>{throw e instanceof Error?Object.assign(e,{message:`PostalWorker handler for "${t}" threw: ${e.message}`}):e})}var U="PostalWorker";function h(t){return new p(t)}var p=class{id;#e="none";#r=!1;#t=!1;#a=!1;#o;#d;#l;#c;#n;#h;#p;#k;#f;#i=[];#M=[];#w=new l;#x=new l;#g=new Map;#u=new Map;#P=new Set;#S=e=>this.#R(e.data);#b=()=>{this.#s({kind:"leave"}),this.#n?.sayGoodbye()};#B=e=>{e.persisted&&(this.#s({kind:"join"}),this.#s({kind:"hello"}),this.#n?.probeFrames())};constructor(e){this.#o=e,this.#d=e.channelName??U,this.id=H(),this.#l=typeof window>"u"||typeof BroadcastChannel>"u",!this.#l&&(this.#c=new BroadcastChannel(this.#d),this.#c.addEventListener("message",this.#S),this.#n=new g({selfId:this.id,allowedOrigins:e.allowedOrigins??[],onMessage:(r,s,n,o)=>this.#x.emit(r,s,{from:n,origin:o})}),window.addEventListener("pagehide",this.#b),window.addEventListener("pageshow",this.#B),this.#s({kind:"join"}),this.#K())}get mode(){return this.#e}get workerOnline(){return this.#r}get isFramed(){return this.#n?.isFramed??!1}ready(){return this.#r?Promise.resolve(!0):this.#t||this.#l||this.#a?Promise.resolve(!1):new Promise(e=>this.#M.push(e))}on(e,r){return this.#w.add(e,r)}off(e,r){this.#w.remove(e,r)}fire(e,r,s="all"){(s==="all"||s==="local"||typeof s=="object"&&s.to===this.id)&&queueMicrotask(()=>this.#w.emit(e,r,{from:this.id})),s!=="local"&&(typeof s=="object"&&s.to===this.id||this.#s({kind:"fire",msgClass:e,message:r,audience:s}))}crossOn(e,r,s,n={}){let o=this.#x.add(e,r);return s!==void 0&&this.#n&&this.#n.open(s,n.name??"_blank",C(n.features)),o}crossOff(e,r){this.#x.remove(e,r)}crossFire(e,r){this.#n?.send(e,r)}backFire(e,r){this.#n&&!this.#n.sendBack(e,r)&&console.warn("PostalWorker: backFire() only works inside an iframe")}fireAll(e,r){this.fire(e,r,"all"),this.crossFire(e,r)}closeWindows(e){this.#n?.closeOrigin(e)}windows(){return(this.#n?.targets()??[]).map(({id:e,origin:r,relation:s})=>({id:e,origin:r,relation:s}))}load(e){let r=this.#l?String(e):new URL(e,window.location.href).href;this.#y("load()")&&(this.#P.add(r),this.#s({kind:"load",url:r}))}postBox(e,r){let s=this.#g.get(e);if(!s||s.closing)s={handlers:new Set,closing:!1},this.#g.set(e,s),s.handlers.add(r),this.#y("postBox()")&&this.#s({kind:"box-open",address:e});else{s.handlers.add(r);let o=s.last;o&&queueMicrotask(()=>r({address:e,value:o.value,box:o.box,closed:!1}))}let n=s;return()=>{n.handlers.delete(r),n.handlers.size===0&&this.#g.get(e)===n&&this.closeBox(e)}}post(e,r){this.#y("post()")&&this.#s({kind:"box-post",address:e,value:r})}closeBox(e){let r=this.#g.get(e);if(!(!r||r.closing)){if(r.closing=!0,this.#e==="none"||this.#t){this.#L(e,r.last?.box??{});return}this.#s({kind:"box-close",address:e})}}package(e,r){let s=this.#u.get(e);if(!s)s={handlers:new Set},this.#u.set(e,s),s.handlers.add(r),this.#y("package()")&&this.#s({kind:"package-open",address:e});else{s.handlers.add(r);let o=s.last;o&&queueMicrotask(()=>r({address:e,content:o.content}))}let n=s;return()=>{n.handlers.delete(r),n.handlers.size===0&&this.#u.get(e)===n&&this.#u.delete(e)}}pack(e,r){this.#y("pack()")&&this.#s({kind:"package-pack",address:e,content:r})}destroy(){this.#a||(this.#a=!0,!this.#l&&(this.#b(),this.#W(),window.removeEventListener("pagehide",this.#b),window.removeEventListener("pageshow",this.#B),this.#c?.removeEventListener("message",this.#S),this.#c?.close(),this.#n?.destroy(),this.#h instanceof Worker&&this.#h.terminate(),this.#h=void 0,this.#p?.(),clearTimeout(this.#f),this.#C(!1),this.#w.clear(),this.#x.clear(),this.#g.clear(),this.#u.clear()))}#K(){let{workerUrl:e}=this.#o;if(e===!1){this.#e="none",this.#m();return}let r=new URL(e,window.location.href).href,s={name:this.#d};if(typeof SharedWorker=="function")try{let n=new SharedWorker(r,s);n.addEventListener("error",()=>this.#O(`could not start SharedWorker ${r}`)),n.port.start(),this.#h=n,this.#e="shared",this.#s({kind:"hello"}),this.#E();return}catch(n){console.warn("PostalWorker: SharedWorker failed to start, trying the fallback",n)}if((this.#o.fallback??"dedicated")==="none"||typeof Worker!="function"){this.#e="none",this.#m();return}if(!navigator.locks){this.#e="none",this.#v(new Error("PostalWorker: no SharedWorker or Web Locks here; running without a worker")),this.#m();return}this.#e="dedicated",this.#s({kind:"hello"}),this.#E(),navigator.locks.request(`${this.#d}:worker-leader`,()=>{if(!this.#a){try{let n=new Worker(r,s);n.addEventListener("error",()=>this.#O(`could not start Worker ${r}`)),this.#h=n}catch(n){this.#O(`could not start Worker ${r}: ${String(n)}`);return}return new Promise(n=>{this.#p=n})}})}#E(){clearTimeout(this.#f),this.#f=setTimeout(()=>{this.#r||(this.#v(new Error(`PostalWorker: worker did not answer within ${this.#o.readyTimeout??5e3}ms`)),this.#m())},this.#o.readyTimeout??5e3)}#O(e){this.#r||(this.#e="none",this.#v(new Error(`PostalWorker: ${e}`)),this.#m())}#m(){this.#r||(this.#t=!0,clearTimeout(this.#f),this.#W(),this.#C(!1))}#y(e){return this.#l?!1:this.#e==="none"?(this.#v(new Error(`PostalWorker: ${e} needs the worker, but this instance has none`)),!1):!0}#R(e){if(!(!m(e)||e.from===this.id))switch(e.kind){case"fire":v(e.audience,this.id)&&this.#w.emit(e.msgClass,e.message,{from:e.from});return;case"worker-ready":this.#A(e.instance);return;case"box-update":{if(e.to!==void 0&&e.to!==this.id)return;let r=this.#g.get(e.address);if(!r||r.closing)return;r.last={value:e.value,box:e.box};for(let s of[...r.handlers])f(()=>s({address:e.address,value:e.value,box:e.box,closed:!1}));return}case"box-closed":e.to===this.id&&this.#L(e.address,e.box);return;case"package-update":{if(e.to!==void 0&&e.to!==this.id)return;let r=this.#u.get(e.address);if(!r||e.to!==void 0&&e.content===null&&r.last)return;r.last={content:e.content};for(let s of[...r.handlers])f(()=>s({address:e.address,content:e.content}));return}case"error":(e.to===void 0||e.to===this.id)&&this.#v(new Error(e.message));return;case"hello":case"join":case"leave":case"box-open":case"box-post":case"box-close":case"package-open":case"package-pack":case"load":return;default:x(e)}}#A(e){let r=this.#k;if(r!==e){if(this.#k=e,clearTimeout(this.#f),this.#s({kind:"join"},!0),r!==void 0){for(let s of this.#P)this.#s({kind:"load",url:s},!0);for(let[s,n]of this.#g){if(n.closing)continue;let o=n.last?.value;this.#s(o==null?{kind:"box-open",address:s}:{kind:"box-open",address:s,seed:{value:o}},!0)}for(let s of this.#u.keys())this.#s({kind:"package-open",address:s},!0)}this.#r=!0,this.#t=!1,this.#W(),this.#C(!0)}}#L(e,r){let s=this.#g.get(e);if(s){this.#g.delete(e);for(let n of[...s.handlers])f(()=>n({address:e,value:null,box:r,closed:!0}))}}#s(e,r=!1){if(!this.#c||this.#a&&e.kind!=="leave")return;if(this.#e!=="none"&&!this.#r&&!this.#t&&!r&&e.kind!=="hello"&&e.kind!=="join"){this.#i.push(e);return}this.#c.postMessage(d(this.id,e))}#W(){let e=this.#i;this.#i=[];for(let r of e)this.#c?.postMessage(d(this.id,r))}#C(e){for(let r of this.#M.splice(0))r(e)}#v(e){this.#o.onError?f(()=>this.#o.onError?.(e)):console.error(e)}};function f(t){try{t()}catch(e){queueMicrotask(()=>{throw e})}}function H(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}var M;function k(t){return M??=F(t??{}),M}function F(t){let e=t.PostalRoute??_(),r=h({workerUrl:$(e,"PostalSharedWorker.js"),allowedOrigins:t.allowedOrigins??"*",...t.channelName!==void 0&&{channelName:t.channelName},...t.onError!==void 0&&{onError:t.onError}}),s={get id(){return r.id},get sharedWorkerSupported(){return typeof SharedWorker=="function"},get workerOnline(){return r.workerOnline},on(n,o){return r.on(n,i=>o(i)),s},un(n){return r.off(n),!0},fire(n,o,i){return r.fire(n,o,I(i)),!0},crossOn(n,o,i,a,c){return r.crossOn(n,P=>o(P),i,{...a!==void 0&&{name:a},...c?{features:c}:{}}),s},unCross(n,o){return r.crossOff(n),o&&r.closeWindows(o),s},crossFire(n,o){return r.crossFire(n,o),s},fireAll(n,o){return r.fireAll(n,o),s},backFire(n,o){return r.backFire(n,o),s},load(n){r.load(n)},postBox(n,o){r.postBox(n,({address:i,value:a,box:c})=>o({address:i,value:a,box:c}))},post(n,o){r.post(n,o)},closeBox(n){r.closeBox(n)},package(n,o){r.package(n,({address:i,content:a})=>o({address:i,content:a}))},pack(n,o){fetch(o).then(i=>{if(!i.ok)throw new Error(`HTTP ${i.status}`);return i.blob()}).then(j).then(i=>r.pack(n,i)).catch(i=>console.error(`PostalWorker: pack("${n}", "${o}") failed`,i))},get v5(){return r}};return s}function I(t){return t===void 0||t==="ALL"?"all":t==="PUBLIC"?"others":t}function $(t,e){return t?t.endsWith("/")?t+e:`${t}/${e}`:e}function _(){if(typeof document>"u")return"";let t=Array.from(document.querySelectorAll("script[src]")).filter(n=>/PostalWorker[^/]*\.js(\?|#|$)/.test(n.src));t.length>1&&console.warn('PostalWorker: found more than one script tag matching "PostalWorker"; using the first');let e=t[0];if(!e)return"";let r=new URL(e.src,window.location.href),s=r.searchParams.get("PostalRoute");return s!==null?s:r.href.slice(0,r.href.length-r.pathname.length)+r.pathname.replace(/[^/]*$/,"")}function j(t){return new Promise((e,r)=>{let s=new FileReader;s.onload=()=>e(String(s.result)),s.onerror=()=>r(s.error??new Error("FileReader failed")),s.readAsDataURL(t)})}Object.assign(globalThis,{PostalWorker:k,createPostalWorker:h});})();
|
|
1
|
+
"use strict";(()=>{var B=new Set(["fire","hello","worker-ready","join","leave","box-open","box-post","box-close","box-update","box-closed","package-open","package-close","package-pack","package-fetch","package-unpack","package-update","load","error"]),L=new Set(["cross-hello","cross-ack","cross-probe","cross-bye","cross"]);function w(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.__postal===5&&typeof e.from=="string"&&typeof e.kind=="string"}function m(t){return w(t)&&B.has(t.kind)}function y(t){return w(t)&&L.has(t.kind)}function d(t,e){return{__postal:5,from:t,...e}}function v(t,e){return`${t}#inbox#${e}`}function x(t,e){return t==="all"||t==="others"?!0:t==="worker"?!1:t.to===e}function b(t){throw new Error(`PostalWorker: unexpected value ${JSON.stringify(t)}`)}var E=2e3,g=class{#e;#s=new Map;#n=new Map;#a=new Set;#i=[];#d;#l=e=>this.#c(e);constructor(e){if(this.#e=e,this.#a.add(window.location.origin),e.allowedOrigins!=="*")for(let i of e.allowedOrigins)this.#a.add(O(i));let s=this.isFramed?R():void 0;s&&this.#a.add(s);let r=u(),n=r?P():void 0;n&&this.#a.add(n),window.addEventListener("message",this.#l);let o=!1;this.isFramed&&(this.#o(window.parent,"*",{kind:"cross-hello"}),o=!0),r&&(this.#o(r,"*",{kind:"cross-hello"}),o=!0),o&&(this.#d=setTimeout(()=>this.#p(),E)),this.probeFrames()}get isFramed(){try{return window.self!==window.top}catch{return!0}}probeFrames(){for(let e=0;e<window.frames.length;e++){let s=window.frames[e];s&&this.#o(s,"*",{kind:"cross-probe"})}}open(e,s,r){let n=new URL(e,window.location.href),o=window.open(n.href,s,r);return o?(this.#n.set(o,n.origin),o):(console.warn(`PostalWorker: window.open("${n.href}") returned null (popup blocked, or "noopener" was set). That window cannot be messaged.`),null)}send(e,s){let r=()=>{this.#w();for(let n of this.#s.values())this.#o(n.win,n.origin,{kind:"cross",msgClass:e,message:s,back:!1})};this.#f(r)}sendBack(e,s){return this.isFramed?(this.#f(()=>{let r=[...this.#s.values()].find(n=>n.relation==="parent");r?this.#o(r.win,r.origin,{kind:"cross",msgClass:e,message:s,back:!0}):console.warn("PostalWorker: backFire dropped, the parent window never answered (is PostalWorker running there, and does it trust this origin?)")}),!0):!1}closeOrigin(e){let s=O(e);for(let[r,n]of this.#s)if(n.origin===s){if(n.relation==="opened")try{n.win.close()}catch{}this.#s.delete(r)}for(let[r,n]of this.#n)if(n===s){try{r.close()}catch{}this.#n.delete(r)}}targets(){return this.#w(),[...this.#s.values()]}sayGoodbye(){for(let e of this.#s.values())this.#o(e.win,e.origin,{kind:"cross-bye"})}destroy(){this.sayGoodbye(),window.removeEventListener("message",this.#l),clearTimeout(this.#d),this.#s.clear(),this.#n.clear(),this.#i=[]}#c(e){let s=e.data;if(!y(s))return;let r=e.source;if(K(r)&&s.from!==this.#e.selfId){if(!this.#t(e.origin,r)){console.warn(`PostalWorker: ignored a message from untrusted origin ${e.origin}. Add it to "allowedOrigins" to accept it.`);return}switch(s.kind){case"cross-probe":this.#o(r,e.origin,{kind:"cross-hello"});return;case"cross-hello":this.#h(s.from,r,e.origin),this.#o(r,e.origin,{kind:"cross-ack"});return;case"cross-ack":this.#h(s.from,r,e.origin),(r===window.parent||r===u())&&this.#p();return;case"cross-bye":this.#s.delete(s.from);return;case"cross":this.#s.has(s.from)||this.#h(s.from,r,e.origin),this.#e.onMessage(s.msgClass,s.message,s.from,e.origin,s.back);return}}}#h(e,s,r){let n="peer";this.isFramed&&s===window.parent?n="parent":s===u()?n="opener":this.#n.has(s)?n="opened":A(s)&&(n="child");for(let[o,i]of this.#s)i.win===s&&o!==e&&this.#s.delete(o);this.#s.set(e,{id:e,win:s,origin:r,relation:n})}#t(e,s){if(this.#e.allowedOrigins==="*"||this.#a.has(e))return!0;let r=this.#n.get(s);return r&&r===e?!0:T(s,e)}#f(e){this.#d===void 0?e():this.#i.push(e)}#p(){clearTimeout(this.#d),this.#d=void 0;let e=this.#i;this.#i=[];for(let s of e)s()}#w(){for(let[e,s]of this.#s)s.win.closed&&this.#s.delete(e);for(let e of this.#n.keys())e.closed&&this.#n.delete(e)}#o(e,s,r){try{e.postMessage(d(this.#e.selfId,r),s)}catch(n){console.warn("PostalWorker: cross-window postMessage failed",n)}}};function K(t){return t!==null&&typeof t.postMessage=="function"&&"closed"in t}function u(){try{let t=window.opener;return t&&t!==window?t:null}catch{return null}}function O(t){try{return new URL(t,window.location.href).origin}catch{return String(t)}}function P(){if(document.referrer)try{return new URL(document.referrer).origin}catch{return}}function R(){let t=window.location.ancestorOrigins;return t&&t.length>0?t[0]:P()}function C(){return Array.from(document.querySelectorAll("iframe"))}function A(t){return C().some(e=>e.contentWindow===t)}function T(t,e){for(let s of C())if(s.contentWindow===t)try{return new URL(s.src,window.location.href).origin===e}catch{return!1}return!1}function M(t){return t?typeof t=="string"?t:Object.entries(t).map(([e,s])=>`${e}=${s===!0?"yes":s===!1?"no":String(s)}`).join(","):""}var l=class{#e=new Map;add(e,s){let r=this.#e.get(e);return r||(r=new Set,this.#e.set(e,r)),r.add(s),()=>this.remove(e,s)}remove(e,s){if(!s){this.#e.delete(e);return}let r=this.#e.get(e);r&&(r.delete(s),r.size===0&&this.#e.delete(e))}has(e){return this.#e.has(e)}keys(){return[...this.#e.keys()]}clear(){this.#e.clear()}emit(e,...s){let r=this.#e.get(e);if(r)for(let n of[...r])try{n(...s)}catch(o){U(e,o)}}};function U(t,e){queueMicrotask(()=>{throw e instanceof Error?Object.assign(e,{message:`PostalWorker handler for "${t}" threw: ${e.message}`}):e})}var F="PostalWorker";function f(t){return new k(t)}var k=class{id;#e="none";#s=!1;#n=!1;#a=!1;#i;#d;#l;#c;#h;#t;#f;#p;#w;#o;#P=[];#B=[];#m=new l;#b=new l;#g=new Map;#u=new Map;#y=new Map;#L=new Set;#O=e=>this.#T(e.data);#C=()=>{this.#r({kind:"leave"}),this.#t?.sayGoodbye()};#E=e=>{if(e.persisted){this.#r({kind:"join"}),this.#r({kind:"hello"});for(let s of this.#u.keys())this.#r({kind:"package-open",address:s});this.#t?.probeFrames()}};constructor(e){this.#i=e,this.#d=e.channelName??F,this.id=H(),this.#l=typeof window>"u"||typeof BroadcastChannel>"u",!this.#l&&(this.#c=new BroadcastChannel(this.#d),this.#c.addEventListener("message",this.#O),this.#h=new BroadcastChannel(v(this.#d,this.id)),this.#h.addEventListener("message",this.#O),this.#t=new g({selfId:this.id,allowedOrigins:e.allowedOrigins??[],onMessage:(s,r,n,o)=>this.#b.emit(s,r,{from:n,origin:o})}),window.addEventListener("pagehide",this.#C),window.addEventListener("pageshow",this.#E),this.#r({kind:"join"}),this.#A())}get mode(){return this.#e}get workerOnline(){return this.#s}get isFramed(){return this.#t?.isFramed??!1}ready(){return this.#s?Promise.resolve(!0):this.#n||this.#l||this.#a?Promise.resolve(!1):new Promise(e=>this.#B.push(e))}on(e,s){return this.#m.add(e,s)}off(e,s){this.#m.remove(e,s)}fire(e,s,r="all"){(r==="all"||r==="local"||typeof r=="object"&&r.to===this.id)&&queueMicrotask(()=>this.#m.emit(e,s,{from:this.id})),r!=="local"&&(typeof r=="object"&&r.to===this.id||this.#r({kind:"fire",msgClass:e,message:s,audience:r}))}crossOn(e,s,r,n={}){let o=this.#b.add(e,s);return r!==void 0&&this.#t&&this.#t.open(r,n.name??"_blank",M(n.features)),o}crossOff(e,s){this.#b.remove(e,s)}crossFire(e,s){this.#t?.send(e,s)}backFire(e,s){this.#t&&!this.#t.sendBack(e,s)&&console.warn("PostalWorker: backFire() only works inside an iframe")}fireAll(e,s){this.fire(e,s,"all"),this.crossFire(e,s)}closeWindows(e){this.#t?.closeOrigin(e)}windows(){return(this.#t?.targets()??[]).map(({id:e,origin:s,relation:r})=>({id:e,origin:s,relation:r}))}load(e){let s=this.#l?String(e):new URL(e,window.location.href).href;this.#k("load()")&&(this.#L.add(s),this.#r({kind:"load",url:s}))}postBox(e,s){let r=this.#g.get(e);if(!r||r.closing)r={handlers:new Set,closing:!1},this.#g.set(e,r),r.handlers.add(s),this.#k("postBox()")&&this.#r({kind:"box-open",address:e});else{r.handlers.add(s);let o=r.last;o&&queueMicrotask(()=>s({address:e,value:o.value,box:o.box,closed:!1}))}let n=r;return()=>{n.handlers.delete(s),n.handlers.size===0&&this.#g.get(e)===n&&this.closeBox(e)}}post(e,s){this.#k("post()")&&this.#r({kind:"box-post",address:e,value:s})}closeBox(e){let s=this.#g.get(e);if(!(!s||s.closing)){if(s.closing=!0,this.#e==="none"||this.#n){this.#R(e,s.last?.box??{});return}this.#r({kind:"box-close",address:e})}}package(e,s){let r=this.#u.get(e);if(!r)r={handlers:new Set},this.#u.set(e,r),r.handlers.add(s),this.#k("package()")&&this.#r({kind:"package-open",address:e});else{r.handlers.add(s);let o=r.last;o&&queueMicrotask(()=>s({address:e,content:o.content}))}let n=r;return()=>{n.handlers.delete(s),n.handlers.size===0&&this.#u.get(e)===n&&(this.#u.delete(e),this.#e!=="none"&&this.#r({kind:"package-close",address:e}))}}pack(e,s){this.#k("pack()")&&(this.#y.delete(e),this.#r({kind:"package-pack",address:e,content:s}))}fetchPackage(e,s,r={}){if(!this.#k("fetchPackage()"))return;let n={kind:"package-fetch",address:e,url:new URL(s,window.location.href).href,as:r.as??"blob"};r.headers&&(n.headers=r.headers),r.credentials&&(n.credentials=r.credentials),this.#y.set(e,n),this.#r(r.refresh?{...n,refresh:!0}:n)}unpack(e){this.#k("unpack()")&&(this.#y.delete(e),this.#r({kind:"package-unpack",address:e}))}destroy(){this.#a||(this.#a=!0,!this.#l&&(this.#C(),this.#W(),window.removeEventListener("pagehide",this.#C),window.removeEventListener("pageshow",this.#E),this.#c?.removeEventListener("message",this.#O),this.#c?.close(),this.#h?.removeEventListener("message",this.#O),this.#h?.close(),this.#t?.destroy(),this.#f instanceof Worker&&this.#f.terminate(),this.#f=void 0,this.#p?.(),clearTimeout(this.#o),this.#S(!1),this.#m.clear(),this.#b.clear(),this.#g.clear(),this.#u.clear(),this.#y.clear()))}#A(){let{workerUrl:e}=this.#i;if(e===!1){this.#e="none",this.#v();return}let s=new URL(e,window.location.href).href,r={name:this.#d};if(typeof SharedWorker=="function")try{let n=new SharedWorker(s,r);n.addEventListener("error",()=>this.#M(`could not start SharedWorker ${s}`)),n.port.start(),this.#f=n,this.#e="shared",this.#r({kind:"hello"}),this.#K();return}catch(n){console.warn("PostalWorker: SharedWorker failed to start, trying the fallback",n)}if((this.#i.fallback??"dedicated")==="none"||typeof Worker!="function"){this.#e="none",this.#v();return}if(!navigator.locks){this.#e="none",this.#x(new Error("PostalWorker: no SharedWorker or Web Locks here; running without a worker")),this.#v();return}this.#e="dedicated",this.#r({kind:"hello"}),this.#K(),navigator.locks.request(`${this.#d}:worker-leader`,()=>{if(!this.#a){try{let n=new Worker(s,r);n.addEventListener("error",()=>this.#M(`could not start Worker ${s}`)),this.#f=n}catch(n){this.#M(`could not start Worker ${s}: ${String(n)}`);return}return new Promise(n=>{this.#p=n})}})}#K(){clearTimeout(this.#o),this.#o=setTimeout(()=>{this.#s||(this.#x(new Error(`PostalWorker: worker did not answer within ${this.#i.readyTimeout??5e3}ms`)),this.#v())},this.#i.readyTimeout??5e3)}#M(e){this.#s||(this.#e="none",this.#x(new Error(`PostalWorker: ${e}`)),this.#v())}#v(){this.#s||(this.#n=!0,clearTimeout(this.#o),this.#W(),this.#S(!1))}#k(e){return this.#l?!1:this.#e==="none"?(this.#x(new Error(`PostalWorker: ${e} needs the worker, but this instance has none`)),!1):!0}#T(e){if(!(!m(e)||e.from===this.id))switch(e.kind){case"fire":x(e.audience,this.id)&&this.#m.emit(e.msgClass,e.message,{from:e.from});return;case"worker-ready":this.#U(e.instance);return;case"box-update":{if(e.to!==void 0&&e.to!==this.id)return;let s=this.#g.get(e.address);if(!s||s.closing)return;s.last={value:e.value,box:e.box};for(let r of[...s.handlers])h(()=>r({address:e.address,value:e.value,box:e.box,closed:!1}));return}case"box-closed":e.to===this.id&&this.#R(e.address,e.box);return;case"package-update":{let s=this.#u.get(e.address);if(!s||e.reply&&e.content===null&&s.last)return;s.last={content:e.content};for(let r of[...s.handlers])h(()=>r({address:e.address,content:e.content}));return}case"error":(e.to===void 0||e.to===this.id)&&this.#x(new Error(e.message));return;case"hello":case"join":case"leave":case"box-open":case"box-post":case"box-close":case"package-open":case"package-close":case"package-pack":case"package-fetch":case"package-unpack":case"load":return;default:b(e)}}#U(e){let s=this.#w;if(s!==e){if(this.#w=e,clearTimeout(this.#o),this.#r({kind:"join"},!0),s!==void 0){for(let r of this.#L)this.#r({kind:"load",url:r},!0);for(let[r,n]of this.#g){if(n.closing)continue;let o=n.last?.value;this.#r(o==null?{kind:"box-open",address:r}:{kind:"box-open",address:r,seed:{value:o}},!0)}for(let r of this.#u.keys())this.#r({kind:"package-open",address:r},!0);for(let r of this.#y.values())this.#r(r,!0)}this.#s=!0,this.#n=!1,this.#W(),this.#S(!0)}}#R(e,s){let r=this.#g.get(e);if(r){this.#g.delete(e);for(let n of[...r.handlers])h(()=>n({address:e,value:null,box:s,closed:!0}))}}#r(e,s=!1){if(!this.#c||this.#a&&e.kind!=="leave")return;if(this.#e!=="none"&&!this.#s&&!this.#n&&!s&&e.kind!=="hello"&&e.kind!=="join"){this.#P.push(e);return}this.#c.postMessage(d(this.id,e))}#W(){let e=this.#P;this.#P=[];for(let s of e)this.#c?.postMessage(d(this.id,s))}#S(e){for(let s of this.#B.splice(0))s(e)}#x(e){this.#i.onError?h(()=>this.#i.onError?.(e)):console.error(e)}};function h(t){try{t()}catch(e){queueMicrotask(()=>{throw e})}}function H(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}var W;function p(t){return W??=$(t??{}),W}function $(t){let e=t.PostalRoute??j(),s=f({workerUrl:N(e,"PostalSharedWorker.js"),allowedOrigins:t.allowedOrigins??"*",...t.channelName!==void 0&&{channelName:t.channelName},...t.onError!==void 0&&{onError:t.onError}}),r={get id(){return s.id},get sharedWorkerSupported(){return typeof SharedWorker=="function"},get workerOnline(){return s.workerOnline},on(n,o){return s.on(n,i=>o(i)),r},un(n){return s.off(n),!0},fire(n,o,i){return s.fire(n,o,I(i)),!0},crossOn(n,o,i,a,c){return s.crossOn(n,S=>o(S),i,{...a!==void 0&&{name:a},...c?{features:c}:{}}),r},unCross(n,o){return s.crossOff(n),o&&s.closeWindows(o),r},crossFire(n,o){return s.crossFire(n,o),r},fireAll(n,o){return s.fireAll(n,o),r},backFire(n,o){return s.backFire(n,o),r},load(n){s.load(n)},postBox(n,o){s.postBox(n,({address:i,value:a,box:c})=>o({address:i,value:a,box:c}))},post(n,o){s.post(n,o)},closeBox(n){s.closeBox(n)},package(n,o){s.package(n,({address:i,content:a})=>o({address:i,content:a}))},pack(n,o){fetch(o).then(i=>{if(!i.ok)throw new Error(`HTTP ${i.status}`);return i.blob()}).then(_).then(i=>s.pack(n,i)).catch(i=>console.error(`PostalWorker: pack("${n}", "${o}") failed`,i))},get v5(){return s}};return r}function I(t){return t===void 0||t==="ALL"?"all":t==="PUBLIC"?"others":t}function N(t,e){return t?t.endsWith("/")?t+e:`${t}/${e}`:e}function j(){if(typeof document>"u")return"";let t=Array.from(document.querySelectorAll("script[src]")).filter(n=>/PostalWorker[^/]*\.js(\?|#|$)/.test(n.src));t.length>1&&console.warn('PostalWorker: found more than one script tag matching "PostalWorker"; using the first');let e=t[0];if(!e)return"";let s=new URL(e.src,window.location.href),r=s.searchParams.get("PostalRoute");return r!==null?r:s.href.slice(0,s.href.length-s.pathname.length)+s.pathname.replace(/[^/]*$/,"")}function _(t){return new Promise((e,s)=>{let r=new FileReader;r.onload=()=>e(String(r.result)),r.onerror=()=>s(r.error??new Error("FileReader failed")),r.readAsDataURL(t)})}Object.assign(globalThis,{PostalWorker:p,createPostalWorker:f});})();
|
|
2
2
|
//# sourceMappingURL=PostalWorker.min.js.map
|