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
package/README.md
CHANGED
|
@@ -1,54 +1,190 @@
|
|
|
1
1
|
# PostalWorker
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Typed messaging between tabs, iframes, popups and a SharedWorker.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
- **Tabs** of the same site talk over a `BroadcastChannel`.
|
|
6
|
+
- A **SharedWorker** holds shared state (post boxes, packages) and runs scripts you load into it. Where SharedWorker is missing, one tab is elected to host a dedicated Worker for everyone, and another tab takes over when it closes.
|
|
7
|
+
- **Iframes, popups and other origins** talk over `window.postMessage`, sent only to exact, trusted origins.
|
|
8
|
+
- With a schema type, every message class, payload, box and package is checked by TypeScript.
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
```sh
|
|
11
|
+
npm install postalworker-es
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Serve `node_modules/postalworker-es/dist/PostalSharedWorker.js` from your site (copy it to your public folder, or import it with your bundler's "asset URL" feature).
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { createPostalWorker } from "postalworker-es";
|
|
8
20
|
|
|
9
|
-
|
|
21
|
+
type AppSchema = {
|
|
22
|
+
events: { "cart:updated": { items: number }; ping: number };
|
|
23
|
+
boxes: { volume: number };
|
|
24
|
+
packages: { avatar: Blob };
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export const postal = createPostalWorker<AppSchema>({
|
|
28
|
+
workerUrl: "/PostalSharedWorker.js",
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// any tab
|
|
32
|
+
const off = postal.on("cart:updated", (msg, { from }) => {
|
|
33
|
+
console.log(msg.items, "from", from);
|
|
34
|
+
});
|
|
10
35
|
|
|
36
|
+
// any tab
|
|
37
|
+
postal.fire("cart:updated", { items: 3 }); // ✅
|
|
38
|
+
postal.fire("cart:updated", { items: "3" }); // ❌ compile error
|
|
39
|
+
off();
|
|
11
40
|
```
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
41
|
+
|
|
42
|
+
Create one instance per tab and share it.
|
|
43
|
+
|
|
44
|
+
## Events and audiences
|
|
45
|
+
|
|
46
|
+
`fire(msgClass, message, audience?)` delivers to:
|
|
47
|
+
|
|
48
|
+
| audience | this tab | other tabs | worker |
|
|
49
|
+
|---|---|---|---|
|
|
50
|
+
| `"all"` (default) | ✓ | ✓ | ✓ |
|
|
51
|
+
| `"others"` | | ✓ | ✓ |
|
|
52
|
+
| `"local"` | ✓ | | |
|
|
53
|
+
| `"worker"` | | | ✓ |
|
|
54
|
+
| `{ to: id }` | only the tab whose `postal.id` is `id` | | |
|
|
55
|
+
|
|
56
|
+
`on()` allows any number of handlers per message class and returns an unsubscribe function. `off(msgClass, handler?)` removes one handler, or all of them. A throwing handler never stops the others. Every delivery is asynchronous, so a tab sees its own messages in the same order as everyone else.
|
|
57
|
+
|
|
58
|
+
## Post boxes: shared values
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
const close = postal.postBox("volume", ({ value, box, closed }) => {
|
|
62
|
+
// called with the current value (null if nothing was posted), then on every change
|
|
63
|
+
});
|
|
64
|
+
postal.post("volume", 11); // every tab with the box open is updated
|
|
65
|
+
postal.closeBox("volume"); // or close(): one last call with value null, closed true
|
|
19
66
|
```
|
|
20
67
|
|
|
21
|
-
|
|
68
|
+
Values live in the worker, so a tab opening the box later gets the current value.
|
|
22
69
|
|
|
23
|
-
|
|
24
|
-
|
|
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:
|
|
25
75
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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
|
|
29
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:
|
|
30
91
|
|
|
31
|
-
|
|
32
|
-
|
|
92
|
+
```ts
|
|
93
|
+
postal.pack("avatar", await canvas.convertToBlob());
|
|
94
|
+
```
|
|
33
95
|
|
|
34
|
-
|
|
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).
|
|
35
97
|
|
|
36
|
-
|
|
37
|
-
PostalWorker().crossOn(
|
|
38
|
-
"crossExample",
|
|
39
|
-
function (msg) {
|
|
40
|
-
window.console.info(msg);
|
|
41
|
-
},
|
|
42
|
-
"http://myurl", // This is where you specify the url you want to open to (it must have a copy of PostalWorker hosted too)
|
|
43
|
-
"MyURL", // This is where you name the new window if you want to interact with it directly with Javascript - limited by cross origin rules of course)
|
|
44
|
-
false // The last argument is optional and it includes more specific window parameters like width, height, etc...
|
|
45
|
-
);
|
|
98
|
+
## Worker scripts
|
|
46
99
|
|
|
47
|
-
|
|
48
|
-
PostalWorker().crossFire("crossExample", "This is a message for my url window");
|
|
100
|
+
Load classic scripts into the worker. They run once, however many tabs ask, and share the worker's state.
|
|
49
101
|
|
|
50
|
-
|
|
51
|
-
|
|
102
|
+
```ts
|
|
103
|
+
postal.load("/workers/echo.js");
|
|
52
104
|
```
|
|
53
105
|
|
|
54
|
-
|
|
106
|
+
```ts
|
|
107
|
+
// workers/echo.ts — bundle as an IIFE / classic script
|
|
108
|
+
import { defineWorkerScript } from "postalworker-es/worker-script";
|
|
109
|
+
import type { AppSchema } from "../schema";
|
|
110
|
+
|
|
111
|
+
defineWorkerScript<AppSchema>((pw) => {
|
|
112
|
+
pw.on("ping", (n, { from }) => pw.fire("ping", n + 1, { to: from }));
|
|
113
|
+
pw.subscribe("/events", (e) => pw.post("volume", Number(e.data))); // Server-Sent Events, shared by all tabs
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Plain JavaScript works too: `self.init = (pw) => { … }`. v4 scripts that call `PostalWorker().on(…)` keep working.
|
|
118
|
+
|
|
119
|
+
If a script fails to load, the tab that loaded it gets an error (see `onError`).
|
|
120
|
+
|
|
121
|
+
## Iframes, popups and other origins
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
// open a window and listen for its messages
|
|
125
|
+
postal.crossOn("chat", (msg, { origin }) => {}, "https://other.example/chat", { features: { popup: true, width: 400 } });
|
|
126
|
+
|
|
127
|
+
postal.crossFire("chat", "hello"); // to every connected iframe, parent, popup and opener
|
|
128
|
+
postal.backFire("chat", "hi parent"); // inside an iframe: to the parent only
|
|
129
|
+
postal.fireAll("chat", "everyone"); // fire("all") + crossFire
|
|
130
|
+
postal.closeWindows("https://other.example");
|
|
131
|
+
postal.windows(); // [{ id, origin, relation }]
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
The other window must run PostalWorker too. Windows connect with a short handshake, after which messages are sent to each window's exact origin, never `"*"`.
|
|
135
|
+
|
|
136
|
+
**Trusted by default:** your own origin, your parent (inside an iframe), your opener, iframes in your page (at their `src` origin) and windows you opened with `crossOn(url)` (at that url's origin). Messages from anything else are ignored with a console warning. To accept more, pass `allowedOrigins: ["https://partner.example"]`, or `"*"` to accept any origin.
|
|
137
|
+
|
|
138
|
+
## Configuration
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
createPostalWorker({
|
|
142
|
+
workerUrl: "/PostalSharedWorker.js", // or false to run without a worker
|
|
143
|
+
channelName: "PostalWorker", // instances with different names are isolated
|
|
144
|
+
fallback: "dedicated", // or "none" where SharedWorker is missing
|
|
145
|
+
allowedOrigins: [], // extra trusted origins, or "*"
|
|
146
|
+
readyTimeout: 5000, // ms before queued messages are sent anyway
|
|
147
|
+
onError: (error) => console.error(error),
|
|
148
|
+
});
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Other members: `postal.id`, `postal.mode` (`"shared" | "dedicated" | "none"`), `postal.workerOnline`, `await postal.ready()` (true once the worker answers), `postal.isFramed`, `postal.destroy()`.
|
|
152
|
+
|
|
153
|
+
Messages sent before the worker answers are queued and sent once it does. Without a worker, events and cross-window messaging still work; post boxes, packages and `load()` report an error.
|
|
154
|
+
|
|
155
|
+
On the server (SSR) `createPostalWorker` returns an instance that does nothing, so importing it is safe.
|
|
156
|
+
|
|
157
|
+
## Browser support
|
|
158
|
+
|
|
159
|
+
Needs `BroadcastChannel`. SharedWorker is used where available (current Chrome, Edge, Firefox, Safari 16+, including mobile). Elsewhere (e.g. Samsung Internet, iOS 15 and older) the dedicated-worker fallback needs Web Locks; without it the library runs without a worker.
|
|
160
|
+
|
|
161
|
+
## v4 compatibility
|
|
162
|
+
|
|
163
|
+
```ts
|
|
164
|
+
import PostalWorker from "postalworker-es";
|
|
165
|
+
|
|
166
|
+
PostalWorker({ PostalRoute: "/js/" }) // folder serving PostalSharedWorker.js
|
|
167
|
+
.on("example", (msg) => console.info(msg));
|
|
168
|
+
PostalWorker().fire("example", "Hello world");
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
The default export is the v4 API: a singleton with the v4 method names, arguments and return values. `PostalWorker().v5` gives you the v5 instance underneath. For a `<script>` tag, use `dist/PostalWorker.min.js`, which sets `window.PostalWorker` and `window.createPostalWorker`.
|
|
172
|
+
|
|
173
|
+
See [CHANGELOG.md](CHANGELOG.md) for what changed and how to migrate.
|
|
174
|
+
|
|
175
|
+
## Development
|
|
176
|
+
|
|
177
|
+
```sh
|
|
178
|
+
npm install
|
|
179
|
+
npm run build # dist/ (esbuild + tsc declarations)
|
|
180
|
+
npm test # typecheck, type tests, unit tests, browser tests
|
|
181
|
+
npm run demo:react # copy the build into demos/react, then `cd demos/react && npm start`
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
The browser tests run headless Chromium with Playwright (`npx playwright install chromium` the first time). They cover several tabs, the worker, the no-SharedWorker fallback including leader handover, cross-origin iframes, popups, origin trust and the v4 API.
|
|
185
|
+
|
|
186
|
+
The other folders in `demos/` are from v4 and have not been updated.
|
|
187
|
+
|
|
188
|
+
## License
|
|
189
|
+
|
|
190
|
+
MIT
|