@rcooler/webpush 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Roman Derevianko
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # @rcooler/webpush
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Web Push for the page and the service worker: subscribe (`enablePush`), read the state
4
+ (`pushStatus`), resubscribe after a server key change (`refreshPush`), unsubscribe (`disablePush`),
5
+ and the worker handlers in `@rcooler/webpush/worker`, which show the message with its buttons, open
6
+ the page and hand an answer button's token to the app. No runtime dependencies.
7
+
8
+ Bundle `@rcooler/webpush/worker` into one classic worker file with a fixed name, such as `/sw.js`,
9
+ and serve it with `Cache-Control: no-cache`.
10
+
11
+ ```sh
12
+ npm install @rcooler/webpush
13
+ ```
14
+
15
+ ESM with type declarations. Part of [web-kit](https://github.com/RCooLeR/web-kit): the
16
+ [README](https://github.com/RCooLeR/web-kit#readme) there describes every package, and the
17
+ [changelog](https://github.com/RCooLeR/web-kit/blob/main/CHANGELOG.md) lists the changes.
18
+
19
+ ## Licence
20
+
21
+ [MIT](LICENSE)
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Where this browser stands:
3
+ * - `unsupported`: it has no notifications for websites, or the server sends none;
4
+ * - `blocked`: the user refused them for this site, and only the browser's settings undo that;
5
+ * - `off` and `on`: can be switched here.
6
+ */
7
+ export type PushStatus = "unsupported" | "blocked" | "off" | "on";
8
+ /** The app's own server, as far as notifications need it. */
9
+ export interface PushBackend {
10
+ /** The server's VAPID public key in URL-safe base64, or "" when the server sends no notifications. */
11
+ publicKey(): Promise<string>;
12
+ /** Stores this browser's subscription under the signed-in user; storing it again is harmless. */
13
+ subscribe(subscription: PushSubscriptionJSON): Promise<void>;
14
+ /** Forgets the subscription with this endpoint address. */
15
+ unsubscribe(endpoint: string): Promise<void>;
16
+ }
17
+ export interface PushOptions {
18
+ backend: PushBackend;
19
+ /** Address of the app's service worker script, such as "/sw.js". */
20
+ workerUrl: string;
21
+ /**
22
+ * How the worker is registered. The default fetches the worker and what it imports past the
23
+ * HTTP cache (`updateViaCache: "none"`), so a long browser cache cannot hold back an update; an
24
+ * app that registers a module worker passes `{ type: "module" }` here too.
25
+ */
26
+ registration?: RegistrationOptions;
27
+ }
28
+ /** What refreshPush needs; with workerUrl it also moves the browser to a renamed worker. */
29
+ export type RefreshOptions = Pick<PushOptions, "backend"> & Partial<Pick<PushOptions, "workerUrl" | "registration">>;
30
+ /**
31
+ * The browser cannot subscribe: it could not reach its push service, or has none (some private
32
+ * modes and embedded browsers). `code` maps to a text through the app's dictionary.
33
+ */
34
+ export declare class PushUnavailableError extends Error {
35
+ readonly code = "push_unavailable";
36
+ constructor();
37
+ }
38
+ export declare function isPushSupported(): boolean;
39
+ /** Turns the server's key (URL-safe base64, which the browser API does not take) into bytes. */
40
+ export declare function decodeKey(key: string): Uint8Array<ArrayBuffer>;
41
+ /** Whether a subscription was made with this key: one made with another cannot be sent to. */
42
+ export declare function isMadeWith(subscriptionKey: ArrayBuffer | null, key: Uint8Array): boolean;
43
+ /**
44
+ * Tells whether notifications reach this browser. A subscription made with a key the server no
45
+ * longer has counts as off: nothing sent with the new key arrives.
46
+ */
47
+ export declare function pushStatus(options: PushOptions): Promise<PushStatus>;
48
+ /**
49
+ * Turns notifications on in this browser: asks for the permission, subscribes and tells the
50
+ * server. Call it from a tap or click, which browsers require for the permission question. A
51
+ * subscription made with another server key is replaced, since it cannot be sent to any more.
52
+ * @throws PushUnavailableError when the browser cannot subscribe.
53
+ */
54
+ export declare function enablePush(options: PushOptions): Promise<PushStatus>;
55
+ /** Turns notifications off in this browser and tells the server to forget its address. */
56
+ export declare function disablePush(options: Pick<PushOptions, "backend">): Promise<void>;
57
+ /**
58
+ * Makes sure the server has this browser's subscription under the user who is signed in now: the
59
+ * browser may have replaced it, or somebody else signed in here. Call it after sign-in and at
60
+ * app start. A subscription made with a key the server no longer has is replaced, and the server
61
+ * told to forget the old address; the permission is still granted, so that needs no tap. When the
62
+ * browser cannot subscribe again, pushStatus reports "off" and enablePush starts over. Does
63
+ * nothing while notifications are off.
64
+ *
65
+ * With workerUrl, a browser that runs a worker under another address (the app renamed its worker
66
+ * file) is moved to the new one, and otherwise asked to look for an update of the worker now.
67
+ */
68
+ export declare function refreshPush(options: RefreshOptions): Promise<void>;
package/dist/index.js ADDED
@@ -0,0 +1,176 @@
1
+ // @rcooler/webpush: notifications in this browser. Three things have to agree: the browser's
2
+ // permission for the site, its subscription at the browser maker's push service, and the server
3
+ // knowing that subscription's address. This module keeps them in step.
4
+ //
5
+ // It does no HTTP itself. The app passes a `PushBackend` that talks to its own server, so the
6
+ // endpoints and their authentication stay with the app. The service worker side is in
7
+ // `@rcooler/webpush/worker`.
8
+ function registrationOptions(options) {
9
+ return { updateViaCache: "none", ...options.registration };
10
+ }
11
+ /**
12
+ * The browser cannot subscribe: it could not reach its push service, or has none (some private
13
+ * modes and embedded browsers). `code` maps to a text through the app's dictionary.
14
+ */
15
+ export class PushUnavailableError extends Error {
16
+ code = "push_unavailable";
17
+ constructor() {
18
+ super("push_unavailable");
19
+ this.name = "PushUnavailableError";
20
+ }
21
+ }
22
+ export function isPushSupported() {
23
+ return "serviceWorker" in navigator && "PushManager" in window && "Notification" in window;
24
+ }
25
+ /** Turns the server's key (URL-safe base64, which the browser API does not take) into bytes. */
26
+ export function decodeKey(key) {
27
+ const base64 = key.replace(/-/g, "+").replace(/_/g, "/");
28
+ const binary = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
29
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
30
+ }
31
+ /** Whether a subscription was made with this key: one made with another cannot be sent to. */
32
+ export function isMadeWith(subscriptionKey, key) {
33
+ if (!subscriptionKey)
34
+ return false;
35
+ const made = new Uint8Array(subscriptionKey);
36
+ return made.length === key.length && made.every((byte, index) => byte === key[index]);
37
+ }
38
+ async function currentSubscription() {
39
+ const registration = await navigator.serviceWorker.getRegistration();
40
+ return (await registration?.pushManager.getSubscription()) ?? null;
41
+ }
42
+ /** The server's key, or undefined when the server sends no notifications. */
43
+ async function serverKey(backend) {
44
+ const publicKey = await backend.publicKey();
45
+ return publicKey === "" ? undefined : decodeKey(publicKey);
46
+ }
47
+ /**
48
+ * Tells whether notifications reach this browser. A subscription made with a key the server no
49
+ * longer has counts as off: nothing sent with the new key arrives.
50
+ */
51
+ export async function pushStatus(options) {
52
+ if (!isPushSupported())
53
+ return "unsupported";
54
+ const key = await serverKey(options.backend);
55
+ if (key === undefined)
56
+ return "unsupported";
57
+ if (Notification.permission === "denied")
58
+ return "blocked";
59
+ if (Notification.permission !== "granted")
60
+ return "off";
61
+ const subscription = await currentSubscription();
62
+ return subscription && isMadeWith(subscription.options.applicationServerKey, key) ? "on" : "off";
63
+ }
64
+ /**
65
+ * Turns notifications on in this browser: asks for the permission, subscribes and tells the
66
+ * server. Call it from a tap or click, which browsers require for the permission question. A
67
+ * subscription made with another server key is replaced, since it cannot be sent to any more.
68
+ * @throws PushUnavailableError when the browser cannot subscribe.
69
+ */
70
+ export async function enablePush(options) {
71
+ if (!isPushSupported())
72
+ return "unsupported";
73
+ // Before anything that waits: some browsers show the question only while the tap is still fresh.
74
+ const permission = await Notification.requestPermission();
75
+ if (permission !== "granted")
76
+ return permission === "denied" ? "blocked" : "off";
77
+ const key = await serverKey(options.backend);
78
+ if (!key)
79
+ return "unsupported";
80
+ let subscription;
81
+ try {
82
+ const registration = await navigator.serviceWorker.register(options.workerUrl, registrationOptions(options));
83
+ await navigator.serviceWorker.ready;
84
+ const existing = await registration.pushManager.getSubscription();
85
+ const isCurrent = existing !== null && isMadeWith(existing.options.applicationServerKey, key);
86
+ if (existing && !isCurrent)
87
+ await existing.unsubscribe();
88
+ subscription = isCurrent
89
+ ? existing
90
+ : await registration.pushManager.subscribe({
91
+ userVisibleOnly: true,
92
+ applicationServerKey: key,
93
+ });
94
+ }
95
+ catch {
96
+ throw new PushUnavailableError();
97
+ }
98
+ await options.backend.subscribe(subscription.toJSON());
99
+ return "on";
100
+ }
101
+ /** Turns notifications off in this browser and tells the server to forget its address. */
102
+ export async function disablePush(options) {
103
+ if (!isPushSupported())
104
+ return;
105
+ const subscription = await currentSubscription();
106
+ if (!subscription)
107
+ return;
108
+ const { endpoint } = subscription;
109
+ // The browser first, because it decides: once it has dropped the subscription nothing arrives
110
+ // here, whatever the server still believes.
111
+ await subscription.unsubscribe();
112
+ // Telling the server only saves it a wasted attempt, so a failure here (offline, a session that
113
+ // just ran out) is not the user's problem: the push service reports the address as gone at the
114
+ // next notification, and the server forgets it then.
115
+ await options.backend.unsubscribe(endpoint).catch(() => undefined);
116
+ }
117
+ /**
118
+ * Makes sure the server has this browser's subscription under the user who is signed in now: the
119
+ * browser may have replaced it, or somebody else signed in here. Call it after sign-in and at
120
+ * app start. A subscription made with a key the server no longer has is replaced, and the server
121
+ * told to forget the old address; the permission is still granted, so that needs no tap. When the
122
+ * browser cannot subscribe again, pushStatus reports "off" and enablePush starts over. Does
123
+ * nothing while notifications are off.
124
+ *
125
+ * With workerUrl, a browser that runs a worker under another address (the app renamed its worker
126
+ * file) is moved to the new one, and otherwise asked to look for an update of the worker now.
127
+ */
128
+ export async function refreshPush(options) {
129
+ if (!isPushSupported() || Notification.permission !== "granted")
130
+ return;
131
+ let registration = await navigator.serviceWorker.getRegistration();
132
+ if (registration && options.workerUrl) {
133
+ registration = await currentWorker(registration, options.workerUrl, options);
134
+ }
135
+ let subscription = (await registration?.pushManager.getSubscription()) ?? null;
136
+ if (!registration || !subscription)
137
+ return;
138
+ const key = await serverKey(options.backend);
139
+ if (!key)
140
+ return;
141
+ if (!isMadeWith(subscription.options.applicationServerKey, key)) {
142
+ const replaced = subscription.endpoint;
143
+ try {
144
+ await subscription.unsubscribe();
145
+ subscription = await registration.pushManager.subscribe({
146
+ userVisibleOnly: true,
147
+ applicationServerKey: key,
148
+ });
149
+ }
150
+ catch {
151
+ return;
152
+ }
153
+ if (subscription.endpoint !== replaced) {
154
+ // As in disablePush: a failure only costs the server one wasted attempt.
155
+ await options.backend.unsubscribe(replaced).catch(() => undefined);
156
+ }
157
+ }
158
+ await options.backend.subscribe(subscription.toJSON());
159
+ }
160
+ /**
161
+ * Registers workerUrl when the browser runs a worker under another address, and otherwise asks
162
+ * for an update check. A failure keeps the registration the browser has.
163
+ */
164
+ async function currentWorker(registration, workerUrl, options) {
165
+ const running = registration.active?.scriptURL;
166
+ try {
167
+ if (running && new URL(workerUrl, running).href !== running) {
168
+ return await navigator.serviceWorker.register(workerUrl, registrationOptions(options));
169
+ }
170
+ await registration.update();
171
+ }
172
+ catch {
173
+ // Offline or refused: the worker the browser has still receives notifications.
174
+ }
175
+ return registration;
176
+ }
@@ -0,0 +1,150 @@
1
+ /** One button of a pushed message. */
2
+ export interface PushAction {
3
+ /** "open" opens `url`; "answer" hands `token` to the app, which forwards it to its server. */
4
+ kind: "open" | "answer";
5
+ title: string;
6
+ /** The single-use answer token, for kind "answer"; empty otherwise. */
7
+ token: string;
8
+ /** The page to open, for kind "open"; empty otherwise. */
9
+ url: string;
10
+ }
11
+ /** The message a server pushes, after validation. */
12
+ export interface PushMessage {
13
+ title: string;
14
+ body: string;
15
+ /** A later message with the same tag replaces the earlier one on the device. */
16
+ tag: string;
17
+ /** The page to open on tap; always a path or URL of this app. */
18
+ url: string;
19
+ /** The buttons, in order; at most MAX_ACTIONS. */
20
+ actions: PushAction[];
21
+ }
22
+ /** The most buttons a message keeps; browsers show two or three. */
23
+ export declare const MAX_ACTIONS = 3;
24
+ /** What to show when a message leaves a field out, and the app's icons. */
25
+ export interface PushDefaults {
26
+ title: string;
27
+ tag: string;
28
+ /** Page opened when a message names none; "/" when omitted. */
29
+ url?: string;
30
+ icon?: string;
31
+ badge?: string;
32
+ }
33
+ /**
34
+ * Reads a pushed payload. The payload is outside data: anything that is not a non-empty string
35
+ * falls back to the default, and a payload that is not an object gives the defaults alone, since
36
+ * the browser demands a notification for every push.
37
+ */
38
+ export declare function readPushMessage(payload: unknown, defaults: PushDefaults): PushMessage;
39
+ /**
40
+ * The address to open for a tapped notification. The address came in a message, so only pages
41
+ * of this app are opened: anything on another origin, or unparsable, becomes the app's start page.
42
+ */
43
+ export declare function clickTarget(url: unknown, origin: string): string;
44
+ /** An open window of the app, as the Clients API gives it. */
45
+ export interface WindowClientLike {
46
+ readonly url: string;
47
+ focus(): Promise<WindowClientLike>;
48
+ navigate(url: string): Promise<WindowClientLike | null>;
49
+ }
50
+ interface ExtendableEventLike {
51
+ waitUntil(work: Promise<unknown>): void;
52
+ }
53
+ export interface PushEventLike extends ExtendableEventLike {
54
+ readonly data: {
55
+ json(): unknown;
56
+ } | null;
57
+ }
58
+ export interface NotificationClickEventLike extends ExtendableEventLike {
59
+ readonly notification: {
60
+ close(): void;
61
+ readonly data?: unknown;
62
+ };
63
+ /** The id of the tapped button; empty or missing when the notification itself was tapped. */
64
+ readonly action?: string;
65
+ }
66
+ /** Notification options with buttons, which some DOM typings leave out. */
67
+ export type ShowNotificationOptions = NotificationOptions & {
68
+ actions?: {
69
+ action: string;
70
+ title: string;
71
+ }[];
72
+ };
73
+ /** The two forms of `pushsubscriptionchange`: browsers pass the new subscription, the old one, or neither. */
74
+ export interface SubscriptionChangeEventLike extends ExtendableEventLike {
75
+ readonly newSubscription?: {
76
+ toJSON(): PushSubscriptionJSON;
77
+ } | null;
78
+ readonly oldSubscription?: {
79
+ readonly options: PushSubscriptionOptionsInit;
80
+ } | null;
81
+ }
82
+ /** The parts of ServiceWorkerGlobalScope the handlers use. */
83
+ export interface WorkerScopeLike {
84
+ readonly location: {
85
+ readonly origin: string;
86
+ };
87
+ readonly registration: {
88
+ showNotification(title: string, options: ShowNotificationOptions): Promise<void>;
89
+ readonly pushManager: {
90
+ subscribe(options: PushSubscriptionOptionsInit): Promise<{
91
+ toJSON(): PushSubscriptionJSON;
92
+ }>;
93
+ };
94
+ };
95
+ readonly clients: {
96
+ matchAll(options: {
97
+ type: "window";
98
+ includeUncontrolled: boolean;
99
+ }): Promise<readonly WindowClientLike[]>;
100
+ openWindow(url: string): Promise<unknown>;
101
+ };
102
+ addEventListener(type: "push", listener: (event: PushEventLike) => void): void;
103
+ addEventListener(type: "notificationclick", listener: (event: NotificationClickEventLike) => void): void;
104
+ addEventListener(type: "pushsubscriptionchange", listener: (event: SubscriptionChangeEventLike) => void): void;
105
+ }
106
+ /**
107
+ * Shows the pushed message as a notification. Answer buttons are shown only when `canAnswer` is
108
+ * true, that is when the app hands their tokens on (`onAnswer`); a button's id is its position.
109
+ */
110
+ export declare function showPushed(scope: WorkerScopeLike, event: PushEventLike, defaults: PushDefaults, canAnswer?: boolean): void;
111
+ /**
112
+ * Handles a tap. An answer button hands its token to `onAnswer` and opens nothing, unless the
113
+ * answer did not get through: `onAnswer` rejected (offline) or resolved with a fetch response that
114
+ * is not ok (a session that ran out, a late tap), or the app hands no tokens on. The message's
115
+ * page then opens, so the user sees where things stand and can answer there. An open button opens
116
+ * its page, the notification itself the message's page: an open app window is brought forward
117
+ * and, when it shows another page, taken to the one asked for; without a window a new one is
118
+ * opened.
119
+ */
120
+ export declare function openClicked(scope: WorkerScopeLike, event: NotificationClickEventLike, onAnswer?: (token: string) => Promise<unknown>): void;
121
+ /**
122
+ * How long a tap waits for onAnswer before it opens the message's page instead. Browsers let a
123
+ * worker open a window only for a few seconds after the tap, so an answer that hangs on a bad
124
+ * connection must not use them up.
125
+ */
126
+ export declare const ANSWER_TIMEOUT_MS = 4000;
127
+ /**
128
+ * Handles a subscription the browser replaced: subscribes again when the browser did not, and
129
+ * hands the new subscription to `report`, which sends it to the app's server. Without this,
130
+ * notifications stop until the app is opened again.
131
+ */
132
+ export declare function resubscribe(scope: WorkerScopeLike, event: SubscriptionChangeEventLike, report: (subscription: PushSubscriptionJSON) => Promise<unknown>): void;
133
+ export interface PushHandlerOptions {
134
+ defaults: PushDefaults;
135
+ /** Sends a replaced subscription to the app's server, with the session cookie. */
136
+ onSubscriptionChange: (subscription: PushSubscriptionJSON) => Promise<unknown>;
137
+ /**
138
+ * Sends the token of a tapped answer button to the app's server, which forwards it to the
139
+ * notification service. It rejects, or resolves with a fetch response that is not ok, when the
140
+ * answer did not get through; the message's page then opens instead. Without it, answer buttons
141
+ * are not shown.
142
+ */
143
+ onAnswer?: (token: string) => Promise<unknown>;
144
+ }
145
+ /**
146
+ * Registers the three handlers on the service worker's global scope:
147
+ * `registerPushHandlers(self, { defaults, onSubscriptionChange })`.
148
+ */
149
+ export declare function registerPushHandlers(scope: WorkerScopeLike, options: PushHandlerOptions): void;
150
+ export {};
package/dist/worker.js ADDED
@@ -0,0 +1,201 @@
1
+ // @rcooler/webpush/worker: what a service worker does with a push. It shows the message the
2
+ // server sent with its action buttons, opens the app when the notification is tapped, hands the
3
+ // token of a tapped answer button to the app, and tells the server when the browser replaced its
4
+ // subscription.
5
+ //
6
+ // The types below describe only the parts of the service worker API that are used, so this file
7
+ // compiles without the WebWorker library and its handlers can be tested with plain objects. A
8
+ // real ServiceWorkerGlobalScope and its events fit them.
9
+ /** The most buttons a message keeps; browsers show two or three. */
10
+ export const MAX_ACTIONS = 3;
11
+ function text(value, fallback) {
12
+ return typeof value === "string" && value !== "" ? value : fallback;
13
+ }
14
+ /**
15
+ * Reads the buttons of a payload: `{"kind": "open", "title", "url"}` and
16
+ * `{"kind": "callback", "title", "action": <token>}`. Anything else (a reply, a button without a
17
+ * title, a token or a page) is left out, because a service worker cannot handle it.
18
+ */
19
+ function readActions(value) {
20
+ if (!Array.isArray(value))
21
+ return [];
22
+ const actions = [];
23
+ for (const entry of value) {
24
+ if (typeof entry !== "object" || entry === null)
25
+ continue;
26
+ const fields = { ...entry };
27
+ const title = text(fields.title, "");
28
+ if (title === "")
29
+ continue;
30
+ if (fields.kind === "open" && text(fields.url, "") !== "") {
31
+ actions.push({ kind: "open", title, token: "", url: text(fields.url, "") });
32
+ }
33
+ else if (fields.kind === "callback" && text(fields.action, "") !== "") {
34
+ actions.push({ kind: "answer", title, token: text(fields.action, ""), url: "" });
35
+ }
36
+ if (actions.length === MAX_ACTIONS)
37
+ break;
38
+ }
39
+ return actions;
40
+ }
41
+ /**
42
+ * Reads a pushed payload. The payload is outside data: anything that is not a non-empty string
43
+ * falls back to the default, and a payload that is not an object gives the defaults alone, since
44
+ * the browser demands a notification for every push.
45
+ */
46
+ export function readPushMessage(payload, defaults) {
47
+ const fields = typeof payload === "object" && payload !== null ? { ...payload } : {};
48
+ return {
49
+ title: text(fields.title, defaults.title),
50
+ body: text(fields.body, ""),
51
+ tag: text(fields.tag, defaults.tag),
52
+ url: text(fields.url, defaults.url ?? "/"),
53
+ actions: readActions(fields.actions),
54
+ };
55
+ }
56
+ /**
57
+ * The address to open for a tapped notification. The address came in a message, so only pages
58
+ * of this app are opened: anything on another origin, or unparsable, becomes the app's start page.
59
+ */
60
+ export function clickTarget(url, origin) {
61
+ try {
62
+ const target = new URL(text(url, "/"), origin);
63
+ return target.origin === origin ? target.href : `${origin}/`;
64
+ }
65
+ catch {
66
+ return `${origin}/`;
67
+ }
68
+ }
69
+ /**
70
+ * Shows the pushed message as a notification. Answer buttons are shown only when `canAnswer` is
71
+ * true, that is when the app hands their tokens on (`onAnswer`); a button's id is its position.
72
+ */
73
+ export function showPushed(scope, event, defaults, canAnswer = false) {
74
+ let payload;
75
+ try {
76
+ payload = event.data?.json();
77
+ }
78
+ catch {
79
+ // Not one of the server's messages; the defaults are shown.
80
+ }
81
+ const message = readPushMessage(payload, defaults);
82
+ const actions = message.actions.filter((action) => action.kind === "open" || canAnswer);
83
+ const options = {
84
+ body: message.body,
85
+ tag: message.tag,
86
+ data: { url: message.url, actions },
87
+ };
88
+ if (actions.length > 0) {
89
+ options.actions = actions.map((action, index) => ({
90
+ action: String(index),
91
+ title: action.title,
92
+ }));
93
+ }
94
+ if (defaults.icon !== undefined)
95
+ options.icon = defaults.icon;
96
+ if (defaults.badge !== undefined)
97
+ options.badge = defaults.badge;
98
+ event.waitUntil(scope.registration.showNotification(message.title, options));
99
+ }
100
+ function notificationUrl(data) {
101
+ return typeof data === "object" && data !== null && "url" in data ? data.url : undefined;
102
+ }
103
+ /** The button a click names, from the notification's data; undefined for the notification itself. */
104
+ function tappedAction(data, id) {
105
+ if (id === undefined ||
106
+ id === "" ||
107
+ typeof data !== "object" ||
108
+ data === null ||
109
+ !("actions" in data)) {
110
+ return undefined;
111
+ }
112
+ const actions = data.actions;
113
+ const index = Number(id);
114
+ if (!Array.isArray(actions) || !Number.isInteger(index) || index < 0 || index >= actions.length) {
115
+ return undefined;
116
+ }
117
+ return actions[index];
118
+ }
119
+ /**
120
+ * Handles a tap. An answer button hands its token to `onAnswer` and opens nothing, unless the
121
+ * answer did not get through: `onAnswer` rejected (offline) or resolved with a fetch response that
122
+ * is not ok (a session that ran out, a late tap), or the app hands no tokens on. The message's
123
+ * page then opens, so the user sees where things stand and can answer there. An open button opens
124
+ * its page, the notification itself the message's page: an open app window is brought forward
125
+ * and, when it shows another page, taken to the one asked for; without a window a new one is
126
+ * opened.
127
+ */
128
+ export function openClicked(scope, event, onAnswer) {
129
+ event.notification.close();
130
+ const action = tappedAction(event.notification.data, event.action);
131
+ const page = action?.kind === "open" ? action.url : notificationUrl(event.notification.data);
132
+ const url = clickTarget(page, scope.location.origin);
133
+ if (action?.kind === "answer") {
134
+ event.waitUntil((async () => {
135
+ if (onAnswer && (await answered(onAnswer, action.token)))
136
+ return;
137
+ await openPage(scope, url);
138
+ })());
139
+ return;
140
+ }
141
+ event.waitUntil(openPage(scope, url));
142
+ }
143
+ /**
144
+ * How long a tap waits for onAnswer before it opens the message's page instead. Browsers let a
145
+ * worker open a window only for a few seconds after the tap, so an answer that hangs on a bad
146
+ * connection must not use them up.
147
+ */
148
+ export const ANSWER_TIMEOUT_MS = 4000;
149
+ /** Whether onAnswer said the server took the answer within ANSWER_TIMEOUT_MS. */
150
+ async function answered(onAnswer, token) {
151
+ let timer;
152
+ const timeout = new Promise((resolve) => {
153
+ timer = setTimeout(() => resolve(false), ANSWER_TIMEOUT_MS);
154
+ });
155
+ try {
156
+ return await Promise.race([onAnswer(token).then(wasTaken, () => false), timeout]);
157
+ }
158
+ finally {
159
+ clearTimeout(timer);
160
+ }
161
+ }
162
+ /** Whether what onAnswer resolved with says the server took the answer: anything but a failed fetch. */
163
+ function wasTaken(result) {
164
+ return !(typeof result === "object" && result !== null && "ok" in result && result.ok === false);
165
+ }
166
+ async function openPage(scope, url) {
167
+ const windows = await scope.clients.matchAll({ type: "window", includeUncontrolled: true });
168
+ const open = windows.find((client) => client.url === url) ?? windows[0];
169
+ if (!open) {
170
+ await scope.clients.openWindow(url);
171
+ return;
172
+ }
173
+ const focused = await open.focus().catch(() => open);
174
+ if (focused.url !== url) {
175
+ await focused.navigate(url).catch(() => scope.clients.openWindow(url));
176
+ }
177
+ }
178
+ /**
179
+ * Handles a subscription the browser replaced: subscribes again when the browser did not, and
180
+ * hands the new subscription to `report`, which sends it to the app's server. Without this,
181
+ * notifications stop until the app is opened again.
182
+ */
183
+ export function resubscribe(scope, event, report) {
184
+ event.waitUntil((async () => {
185
+ const options = event.oldSubscription?.options;
186
+ const subscription = event.newSubscription ??
187
+ (options ? await scope.registration.pushManager.subscribe(options) : undefined);
188
+ if (subscription)
189
+ await report(subscription.toJSON());
190
+ })());
191
+ }
192
+ /**
193
+ * Registers the three handlers on the service worker's global scope:
194
+ * `registerPushHandlers(self, { defaults, onSubscriptionChange })`.
195
+ */
196
+ export function registerPushHandlers(scope, options) {
197
+ const canAnswer = options.onAnswer !== undefined;
198
+ scope.addEventListener("push", (event) => showPushed(scope, event, options.defaults, canAnswer));
199
+ scope.addEventListener("notificationclick", (event) => openClicked(scope, event, options.onAnswer));
200
+ scope.addEventListener("pushsubscriptionchange", (event) => resubscribe(scope, event, options.onSubscriptionChange));
201
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@rcooler/webpush",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Web Push in the browser: subscribe, resubscribe after a key change, and the service worker handlers.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "@rcooler/source": "./src/index.ts",
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./worker": {
15
+ "@rcooler/source": "./src/worker.ts",
16
+ "types": "./dist/worker.d.ts",
17
+ "default": "./dist/worker.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "engines": {
24
+ "node": ">=24"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/RCooLeR/web-kit.git",
29
+ "directory": "packages/webpush"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public",
33
+ "registry": "https://registry.npmjs.org"
34
+ },
35
+ "scripts": {
36
+ "build": "node ../../node_modules/@typescript/native/bin/tsc -p tsconfig.build.json",
37
+ "typecheck": "node ../../node_modules/@typescript/native/bin/tsc --noEmit -p tsconfig.json"
38
+ }
39
+ }