@broberg/pwa 0.2.2 → 0.4.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/dist/react.js CHANGED
@@ -7,8 +7,17 @@ import { jsxs, jsx } from 'react/jsx-runtime';
7
7
  var SKIP_WAITING = "SKIP_WAITING";
8
8
  var SKIP_WAITING_MESSAGE = { type: SKIP_WAITING };
9
9
 
10
+ // src/should-offer.ts
11
+ function shouldOfferUpdate({ waiting, snoozedUntil, now }) {
12
+ if (!waiting) return false;
13
+ if (snoozedUntil !== null && snoozedUntil > now) return false;
14
+ return true;
15
+ }
16
+
10
17
  // src/index.ts
11
18
  var DEFAULT_POLL_MS = 60 * 60 * 1e3;
19
+ var DEFAULT_SNOOZE_MS = 30 * 60 * 1e3;
20
+ var SNOOZE_KEY = "broberg-pwa:snoozed-until";
12
21
  function createPwaUpdater(options = {}) {
13
22
  const {
14
23
  swUrl = "/sw.js",
@@ -16,6 +25,7 @@ function createPwaUpdater(options = {}) {
16
25
  pollIntervalMs = DEFAULT_POLL_MS,
17
26
  updateOnFocus = true,
18
27
  reloadOnControllerChange = true,
28
+ snoozeMs = DEFAULT_SNOOZE_MS,
19
29
  disabled = false
20
30
  } = options;
21
31
  const listeners = /* @__PURE__ */ new Set();
@@ -37,6 +47,10 @@ function createPwaUpdater(options = {}) {
37
47
  getState,
38
48
  applyUpdate() {
39
49
  },
50
+ snooze() {
51
+ },
52
+ check() {
53
+ },
40
54
  destroy() {
41
55
  listeners.clear();
42
56
  }
@@ -47,10 +61,39 @@ function createPwaUpdater(options = {}) {
47
61
  let removeFocusListeners = null;
48
62
  let reloading = false;
49
63
  let destroyed = false;
50
- const markReady = (worker) => {
51
- waitingWorker = worker;
52
- if (!updateReady) {
53
- updateReady = true;
64
+ let registrationRef = null;
65
+ const storage = options.snoozeStorage !== void 0 ? options.snoozeStorage : typeof localStorage !== "undefined" ? localStorage : null;
66
+ let snoozedUntil = null;
67
+ const readSnooze = () => {
68
+ if (!storage) return snoozedUntil;
69
+ try {
70
+ const raw = storage.getItem(SNOOZE_KEY);
71
+ if (!raw) return null;
72
+ const n = Number(raw);
73
+ return Number.isFinite(n) ? n : null;
74
+ } catch {
75
+ return snoozedUntil;
76
+ }
77
+ };
78
+ const writeSnooze = (until) => {
79
+ snoozedUntil = until;
80
+ if (!storage) return;
81
+ try {
82
+ if (until === null) storage.removeItem(SNOOZE_KEY);
83
+ else storage.setItem(SNOOZE_KEY, String(until));
84
+ } catch {
85
+ }
86
+ };
87
+ const check = () => {
88
+ const waiting = registrationRef?.waiting ?? null;
89
+ waitingWorker = waiting;
90
+ const next = shouldOfferUpdate({
91
+ waiting,
92
+ snoozedUntil: readSnooze(),
93
+ now: Date.now()
94
+ });
95
+ if (next !== updateReady) {
96
+ updateReady = next;
54
97
  emit();
55
98
  }
56
99
  };
@@ -69,21 +112,20 @@ function createPwaUpdater(options = {}) {
69
112
  const installing = registration.installing;
70
113
  if (!installing) return;
71
114
  installing.addEventListener("statechange", () => {
72
- if (installing.state === "installed" && container.controller) {
73
- markReady(installing);
74
- }
115
+ if (installing.state === "installed") check();
75
116
  });
76
117
  };
77
118
  const wireFocusChecks = (registration) => {
78
119
  if (!updateOnFocus) return;
79
- const check = () => {
120
+ const tick = () => {
121
+ check();
80
122
  registration.update().catch(() => {
81
- });
123
+ }).then(check, check);
82
124
  };
83
- const onFocus = () => check();
125
+ const onFocus = () => tick();
84
126
  const onVisibility = () => {
85
127
  if (typeof document !== "undefined" && document.visibilityState === "visible") {
86
- check();
128
+ tick();
87
129
  }
88
130
  };
89
131
  if (typeof window !== "undefined") window.addEventListener("focus", onFocus);
@@ -100,12 +142,14 @@ function createPwaUpdater(options = {}) {
100
142
  const registrationPromise = register ? container.register(swUrl) : container.ready;
101
143
  registrationPromise.then((registration) => {
102
144
  if (destroyed) return;
103
- if (registration.waiting) markReady(registration.waiting);
145
+ registrationRef = registration;
146
+ check();
104
147
  registration.addEventListener("updatefound", () => watchInstalling(registration));
105
148
  if (pollIntervalMs > 0) {
106
149
  pollId = setInterval(() => {
150
+ check();
107
151
  registration.update().catch(() => {
108
- });
152
+ }).then(check, check);
109
153
  }, pollIntervalMs);
110
154
  }
111
155
  wireFocusChecks(registration);
@@ -117,6 +161,11 @@ function createPwaUpdater(options = {}) {
117
161
  applyUpdate() {
118
162
  if (waitingWorker) waitingWorker.postMessage(SKIP_WAITING_MESSAGE);
119
163
  },
164
+ snooze() {
165
+ writeSnooze(Date.now() + snoozeMs);
166
+ check();
167
+ },
168
+ check,
120
169
  destroy() {
121
170
  destroyed = true;
122
171
  if (pollId !== null) clearInterval(pollId);
@@ -126,17 +175,33 @@ function createPwaUpdater(options = {}) {
126
175
  }
127
176
  };
128
177
  }
178
+
179
+ // src/options-key.ts
180
+ var identities = /* @__PURE__ */ new WeakMap();
181
+ var nextIdentity = 0;
182
+ var identify = (value) => {
183
+ if (value === null || typeof value !== "object" && typeof value !== "function") {
184
+ return value;
185
+ }
186
+ const obj = value;
187
+ let tag = identities.get(obj);
188
+ if (tag === void 0) {
189
+ tag = `@ref:${nextIdentity++}`;
190
+ identities.set(obj, tag);
191
+ }
192
+ return tag;
193
+ };
194
+ function optionsKey(options) {
195
+ return JSON.stringify(
196
+ Object.entries(options).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, identify(v)])
197
+ );
198
+ }
129
199
  function usePwaUpdate(options = {}) {
130
- const { swUrl, pollIntervalMs, reloadOnControllerChange, disabled } = options;
200
+ const key = optionsKey(options);
131
201
  const [updateReady, setUpdateReady] = useState(false);
132
202
  const updaterRef = useRef(null);
133
203
  useEffect(() => {
134
- const updater = createPwaUpdater({
135
- swUrl,
136
- pollIntervalMs,
137
- reloadOnControllerChange,
138
- disabled
139
- });
204
+ const updater = createPwaUpdater(options);
140
205
  updaterRef.current = updater;
141
206
  setUpdateReady(updater.getState().updateReady);
142
207
  const unsubscribe = updater.subscribe((state) => setUpdateReady(state.updateReady));
@@ -145,10 +210,12 @@ function usePwaUpdate(options = {}) {
145
210
  updater.destroy();
146
211
  updaterRef.current = null;
147
212
  };
148
- }, [swUrl, pollIntervalMs, reloadOnControllerChange, disabled]);
213
+ }, [key]);
149
214
  return {
150
215
  updateReady,
151
- applyUpdate: () => updaterRef.current?.applyUpdate()
216
+ applyUpdate: () => updaterRef.current?.applyUpdate(),
217
+ snooze: () => updaterRef.current?.snooze(),
218
+ check: () => updaterRef.current?.check()
152
219
  };
153
220
  }
154
221
  var DEFAULT_LABELS = {
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/message.ts","../src/index.ts","../src/react.tsx"],"names":[],"mappings":";;;;;;AAKO,IAAM,YAAA,GAAe,cAAA;AAErB,IAAM,oBAAA,GAAuB,EAAE,IAAA,EAAM,YAAA,EAAa;;;ACyCzD,IAAM,eAAA,GAAkB,KAAK,EAAA,GAAK,GAAA;AAY3B,SAAS,gBAAA,CAAiB,OAAA,GAA6B,EAAC,EAAe;AAC5E,EAAA,MAAM;AAAA,IACJ,KAAA,GAAQ,QAAA;AAAA,IACR,QAAA,GAAW,IAAA;AAAA,IACX,cAAA,GAAiB,eAAA;AAAA,IACjB,aAAA,GAAgB,IAAA;AAAA,IAChB,wBAAA,GAA2B,IAAA;AAAA,IAC3B,QAAA,GAAW;AAAA,GACb,GAAI,OAAA;AAEJ,EAAA,MAAM,SAAA,uBAAgB,GAAA,EAAsC;AAC5D,EAAA,IAAI,WAAA,GAAc,KAAA;AAClB,EAAA,IAAI,aAAA,GAAsC,IAAA;AAE1C,EAAA,MAAM,QAAA,GAAW,OAAwB,EAAE,WAAA,EAAY,CAAA;AACvD,EAAA,MAAM,OAAO,MAAY;AACvB,IAAA,MAAM,QAAQ,QAAA,EAAS;AACvB,IAAA,KAAA,MAAW,QAAA,IAAY,SAAA,EAAW,QAAA,CAAS,KAAK,CAAA;AAAA,EAClD,CAAA;AACA,EAAA,MAAM,SAAA,GAAY,CAAC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EAAE,GAAG,cAAA,EAAgB,GAAG,MAAA,EAAO;AACzC,EAAA,MAAM,OAAA,GAAU,MAAM,SAAA,IAAY;AAClC,EAAA,uBACE,IAAA,CAAC,SAAI,IAAA,EAAK,QAAA,EAAS,aAAU,QAAA,EAAS,aAAA,EAAY,qBAAoB,SAAA,EACpE,QAAA,EAAA;AAAA,oBAAA,GAAA,CAAC,GAAA,EAAA,EAAE,aAAA,EAAY,kBAAA,EAAoB,QAAA,EAAA,CAAA,CAAE,KAAA,EAAM,CAAA;AAAA,IAC1C,CAAA,CAAE,uBAAO,GAAA,CAAC,GAAA,EAAA,EAAE,eAAY,iBAAA,EAAmB,QAAA,EAAA,CAAA,CAAE,MAAK,CAAA,GAAO,IAAA;AAAA,oBAC1D,GAAA,CAAC,YAAO,IAAA,EAAK,QAAA,EAAS,eAAY,oBAAA,EAAqB,OAAA,EAAS,QAAA,EAC7D,QAAA,EAAA,CAAA,CAAE,MAAA,EACL,CAAA;AAAA,oBACA,GAAA,CAAC,YAAO,IAAA,EAAK,QAAA,EAAS,eAAY,oBAAA,EAAqB,OAAA,EAAS,OAAA,EAC7D,QAAA,EAAA,CAAA,CAAE,OAAA,EACL,CAAA;AAAA,oBACA,GAAA;AAAA,MAAC,QAAA;AAAA,MAAA;AAAA,QACC,IAAA,EAAK,QAAA;AAAA,QACL,aAAA,EAAY,kBAAA;AAAA,QACZ,cAAY,CAAA,CAAE,KAAA;AAAA,QACd,OAAA,EAAS,OAAA;AAAA,QAER,QAAA,EAAA;AAAA;AAAA;AACH,GAAA,EACF,CAAA;AAEJ","file":"react.js","sourcesContent":["/**\n * The single source of the client↔service-worker \"activate the waiting worker\"\n * message. Both the client controller (`applyUpdate`) and the SW helper\n * (`listenForSkipWaiting`) import it so the contract can never drift.\n */\nexport const SKIP_WAITING = \"SKIP_WAITING\" as const;\n\nexport const SKIP_WAITING_MESSAGE = { type: SKIP_WAITING } as const;\n\nexport type SkipWaitingMessage = typeof SKIP_WAITING_MESSAGE;\n","import { SKIP_WAITING_MESSAGE } from \"./message.js\";\n\nexport { SKIP_WAITING, SKIP_WAITING_MESSAGE } from \"./message.js\";\nexport type { SkipWaitingMessage } from \"./message.js\";\n\nexport interface PwaUpdaterOptions {\n /** Service-worker script URL to register. Default `/sw.js`. */\n swUrl?: string;\n /**\n * Register `swUrl` ourselves (manual `sw.js` style). Set `false` when the\n * app already registers the SW (e.g. Serwist's `registerSW` / `@serwist/next`)\n * — the updater then attaches to the existing registration via\n * `navigator.serviceWorker.ready` instead of registering again. Default `true`.\n */\n register?: boolean;\n /** How often to poll `registration.update()` (ms). `0` disables. Default 60 min. */\n pollIntervalMs?: number;\n /**\n * Also check for an update when the tab regains focus / becomes visible.\n * A constantly-focused tab never fires `visibilitychange`, so `focus` is the\n * one that catches \"user came back to the app\". Default `true`.\n */\n updateOnFocus?: boolean;\n /** Reload the page once the new worker takes control. Default `true`. */\n reloadOnControllerChange?: boolean;\n /**\n * Consumer guard. When `true` the updater is an inert no-op (registers\n * nothing). Pass your own policy, e.g. `disabled: isNativeCapacitor || isDev`\n * — the package never hardcodes an environment or a `.native` check.\n */\n disabled?: boolean;\n}\n\nexport interface PwaUpdaterState {\n /** A new service worker is installed and waiting to activate. */\n updateReady: boolean;\n}\n\nexport interface PwaUpdater {\n /** Subscribe to state changes. Returns an unsubscribe fn. */\n subscribe(listener: (state: PwaUpdaterState) => void): () => void;\n getState(): PwaUpdaterState;\n /** Tell the waiting worker to activate (posts SKIP_WAITING). No-op if none waits. */\n applyUpdate(): void;\n /** Stop polling + remove all listeners. */\n destroy(): void;\n}\n\nconst DEFAULT_POLL_MS = 60 * 60 * 1000;\n\n/**\n * Framework- and bundler-agnostic controller for the PWA \"new version\n * available\" lifecycle: register (or attach) → detect a waiting worker\n * (suppressing the first install) → let the consumer activate it → reload on\n * takeover, re-checking on interval + focus/visibility.\n *\n * Distilled from the pattern hand-rolled across the fleet (fds, cardmem,\n * pitch-vault). Works with any service worker (Serwist, Workbox, hand-rolled)\n * as long as the SW answers a `SKIP_WAITING` message — see `@broberg/pwa/sw`.\n */\nexport function createPwaUpdater(options: PwaUpdaterOptions = {}): PwaUpdater {\n const {\n swUrl = \"/sw.js\",\n register = true,\n pollIntervalMs = DEFAULT_POLL_MS,\n updateOnFocus = true,\n reloadOnControllerChange = true,\n disabled = false,\n } = options;\n\n const listeners = new Set<(state: PwaUpdaterState) => void>();\n let updateReady = false;\n let waitingWorker: ServiceWorker | null = null;\n\n const getState = (): PwaUpdaterState => ({ updateReady });\n const emit = (): void => {\n const state = getState();\n for (const listener of listeners) listener(state);\n };\n const subscribe = (listener: (state: PwaUpdaterState) => void): (() => void) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n };\n\n const supported =\n typeof navigator !== \"undefined\" && \"serviceWorker\" in navigator;\n\n // Inert no-op: disabled by the consumer, or no service-worker support at all.\n if (disabled || !supported) {\n return {\n subscribe,\n getState,\n applyUpdate() {},\n destroy() {\n listeners.clear();\n },\n };\n }\n\n const container = navigator.serviceWorker;\n let pollId: ReturnType<typeof setInterval> | null = null;\n let removeFocusListeners: (() => void) | null = null;\n let reloading = false;\n let destroyed = false;\n\n const markReady = (worker: ServiceWorker): void => {\n waitingWorker = worker;\n if (!updateReady) {\n updateReady = true;\n emit();\n }\n };\n\n // With `clientsClaim: true` a brand-new worker claims a previously\n // uncontrolled page and fires `controllerchange` on the FIRST install — that\n // is not an update, so reloading there would yank a first-time visitor out of\n // whatever they are doing. Only a `controllerchange` that REPLACES an existing\n // controller is a real takeover worth reloading for.\n let hadController = !!container.controller;\n const onControllerChange = (): void => {\n if (!reloadOnControllerChange || reloading) return;\n if (!hadController) {\n hadController = true; // first claim of an uncontrolled page — not an update\n return;\n }\n reloading = true; // guard against a reload-loop\n if (typeof location !== \"undefined\") location.reload();\n };\n container.addEventListener(\"controllerchange\", onControllerChange);\n\n const watchInstalling = (registration: ServiceWorkerRegistration): void => {\n const installing = registration.installing;\n if (!installing) return;\n installing.addEventListener(\"statechange\", () => {\n // A new worker reaching `installed` WHILE a controller already exists is\n // an update. Reaching `installed` with no controller is the FIRST install\n // — nothing to update, so we stay quiet.\n if (installing.state === \"installed\" && container.controller) {\n markReady(installing);\n }\n });\n };\n\n const wireFocusChecks = (registration: ServiceWorkerRegistration): void => {\n if (!updateOnFocus) return;\n const check = (): void => {\n registration.update().catch(() => {});\n };\n const onFocus = (): void => check();\n const onVisibility = (): void => {\n if (typeof document !== \"undefined\" && document.visibilityState === \"visible\") {\n check();\n }\n };\n if (typeof window !== \"undefined\") window.addEventListener(\"focus\", onFocus);\n if (typeof document !== \"undefined\") {\n document.addEventListener(\"visibilitychange\", onVisibility);\n }\n removeFocusListeners = () => {\n if (typeof window !== \"undefined\") window.removeEventListener(\"focus\", onFocus);\n if (typeof document !== \"undefined\") {\n document.removeEventListener(\"visibilitychange\", onVisibility);\n }\n };\n };\n\n // Manual style registers swUrl; serwist/registerSW style attaches to the\n // registration the app already made via `.ready`.\n const registrationPromise = register ? container.register(swUrl) : container.ready;\n\n registrationPromise\n .then((registration) => {\n if (destroyed) return;\n if (registration.waiting) markReady(registration.waiting);\n registration.addEventListener(\"updatefound\", () => watchInstalling(registration));\n if (pollIntervalMs > 0) {\n pollId = setInterval(() => {\n registration.update().catch(() => {\n // ignore transient update-check network errors\n });\n }, pollIntervalMs);\n }\n wireFocusChecks(registration);\n })\n .catch(() => {\n // registration failed — stay inert rather than throw into the app\n });\n\n return {\n subscribe,\n getState,\n applyUpdate() {\n if (waitingWorker) waitingWorker.postMessage(SKIP_WAITING_MESSAGE);\n },\n destroy() {\n destroyed = true;\n if (pollId !== null) clearInterval(pollId);\n removeFocusListeners?.();\n container.removeEventListener(\"controllerchange\", onControllerChange);\n listeners.clear();\n },\n };\n}\n","import { useEffect, useRef, useState } from \"react\";\nimport { createPwaUpdater, type PwaUpdater, type PwaUpdaterOptions } from \"./index.js\";\n\n/**\n * React binding for {@link createPwaUpdater}. Returns whether an update is\n * ready plus the `applyUpdate` action. The controller is created once and\n * torn down on unmount.\n */\nexport function usePwaUpdate(options: PwaUpdaterOptions = {}): {\n updateReady: boolean;\n applyUpdate: () => void;\n} {\n const { swUrl, pollIntervalMs, reloadOnControllerChange, disabled } = options;\n const [updateReady, setUpdateReady] = useState(false);\n const updaterRef = useRef<PwaUpdater | null>(null);\n\n useEffect(() => {\n const updater = createPwaUpdater({\n swUrl,\n pollIntervalMs,\n reloadOnControllerChange,\n disabled,\n });\n updaterRef.current = updater;\n setUpdateReady(updater.getState().updateReady);\n const unsubscribe = updater.subscribe((state) => setUpdateReady(state.updateReady));\n return () => {\n unsubscribe();\n updater.destroy();\n updaterRef.current = null;\n };\n }, [swUrl, pollIntervalMs, reloadOnControllerChange, disabled]);\n\n return {\n updateReady,\n applyUpdate: () => updaterRef.current?.applyUpdate(),\n };\n}\n\nexport interface PwaUpdateBannerLabels {\n title?: string;\n body?: string;\n update?: string;\n dismiss?: string;\n close?: string;\n}\n\nconst DEFAULT_LABELS: Required<PwaUpdateBannerLabels> = {\n title: \"New version available\",\n body: \"Reload to get the latest version.\",\n update: \"Update\",\n dismiss: \"Later\",\n close: \"Close\",\n};\n\nexport interface PwaUpdateBannerProps {\n /** From `usePwaUpdate().updateReady`. Nothing renders when false. */\n updateReady: boolean;\n /** From `usePwaUpdate().applyUpdate`. */\n onUpdate: () => void;\n /** Optional dismiss handler (wired to both \"Later\" and the close ✕). */\n onDismiss?: () => void;\n /** Override any of the built-in strings (i18n). */\n labels?: PwaUpdateBannerLabels;\n /** Your class(es) — the skeleton carries NO colours or design-system styling. */\n className?: string;\n}\n\n/**\n * Unstyled, accessible \"new version available\" banner skeleton. It ships\n * structure + a11y + stable testids only; you own the look via `className`\n * and your design tokens. Prefer {@link usePwaUpdate} directly if you'd rather\n * build the UI yourself.\n */\nexport function PwaUpdateBanner({\n updateReady,\n onUpdate,\n onDismiss,\n labels,\n className,\n}: PwaUpdateBannerProps) {\n if (!updateReady) return null;\n const l = { ...DEFAULT_LABELS, ...labels };\n const dismiss = () => onDismiss?.();\n return (\n <div role=\"status\" aria-live=\"polite\" data-testid=\"pwa-update-banner\" className={className}>\n <p data-testid=\"pwa-update-title\">{l.title}</p>\n {l.body ? <p data-testid=\"pwa-update-body\">{l.body}</p> : null}\n <button type=\"button\" data-testid=\"pwa-update-confirm\" onClick={onUpdate}>\n {l.update}\n </button>\n <button type=\"button\" data-testid=\"pwa-update-dismiss\" onClick={dismiss}>\n {l.dismiss}\n </button>\n <button\n type=\"button\"\n data-testid=\"pwa-update-close\"\n aria-label={l.close}\n onClick={dismiss}\n >\n {\"×\"}\n </button>\n </div>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/message.ts","../src/should-offer.ts","../src/index.ts","../src/options-key.ts","../src/react.tsx"],"names":[],"mappings":";;;;;;AAKO,IAAM,YAAA,GAAe,cAAA;AAErB,IAAM,oBAAA,GAAuB,EAAE,IAAA,EAAM,YAAA,EAAa;;;AC4ClD,SAAS,iBAAA,CAAkB,EAAE,OAAA,EAAS,YAAA,EAAc,KAAI,EAA8B;AAC3F,EAAA,IAAI,CAAC,SAAS,OAAO,KAAA;AACrB,EAAA,IAAI,YAAA,KAAiB,IAAA,IAAQ,YAAA,GAAe,GAAA,EAAK,OAAO,KAAA;AACxD,EAAA,OAAO,IAAA;AACT;;;ACiBA,IAAM,eAAA,GAAkB,KAAK,EAAA,GAAK,GAAA;AAClC,IAAM,iBAAA,GAAoB,KAAK,EAAA,GAAK,GAAA;AACpC,IAAM,UAAA,GAAa,2BAAA;AAYZ,SAAS,gBAAA,CAAiB,OAAA,GAA6B,EAAC,EAAe;AAC5E,EAAA,MAAM;AAAA,IACJ,KAAA,GAAQ,QAAA;AAAA,IACR,QAAA,GAAW,IAAA;AAAA,IACX,cAAA,GAAiB,eAAA;AAAA,IACjB,aAAA,GAAgB,IAAA;AAAA,IAChB,wBAAA,GAA2B,IAAA;AAAA,IAC3B,QAAA,GAAW,iBAAA;AAAA,IACX,QAAA,GAAW;AAAA,GACb,GAAI,OAAA;AAEJ,EAAA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A,EACF,CAAA;AAEJ","file":"react.js","sourcesContent":["/**\n * The single source of the client↔service-worker \"activate the waiting worker\"\n * message. Both the client controller (`applyUpdate`) and the SW helper\n * (`listenForSkipWaiting`) import it so the contract can never drift.\n */\nexport const SKIP_WAITING = \"SKIP_WAITING\" as const;\n\nexport const SKIP_WAITING_MESSAGE = { type: SKIP_WAITING } as const;\n\nexport type SkipWaitingMessage = typeof SKIP_WAITING_MESSAGE;\n","/**\n * F054.8 — the decision, as a pure function.\n *\n * Split out so it can be proven with NO service worker, NO DOM and no fake\n * container: every branch is reachable from three plain values. The rest of the\n * updater is plumbing around this.\n *\n * Why it is a function and not a flag: the old updater REMEMBERED whether an\n * update was ready instead of READING whether one is waiting, so the answer\n * could only ever be given once.\n */\nexport interface ShouldOfferInput {\n /** `registration.waiting` — read fresh at the moment of the decision. */\n waiting: unknown;\n /** Epoch ms until which the user has snoozed the offer, or null. */\n snoozedUntil: number | null;\n /** Epoch ms now. Passed in so the function stays pure and testable. */\n now: number;\n}\n\n/**\n * Should the consumer be offered the update right now?\n *\n * WHY `controller` IS NOT A TERM HERE, though the sketch we were shown had one\n * and the old code checked it on one of its two paths.\n *\n * The old updater answered this question inconsistently: the attach path\n * (`if (registration.waiting)`) offered with no controller check, while the\n * `updatefound` path required `container.controller` to suppress a first\n * install. Same situation, two answers, depending on which path happened to see\n * it. Making them agree is part of this fix — the question is which way.\n *\n * Requiring a controller would be the tighter rule, and it would REMOVE a banner\n * that some consumer sees today: a page that is not yet controlled (no\n * `clientsClaim`, or a hard reload) but has a genuine update waiting. With\n * fd-sundhed live to 16,838 people on the current version, a change in that\n * direction is not one to make on an unverified reading.\n *\n * And the reading in question is this: a worker only enters `waiting` when\n * another worker is already ACTIVE — on a first install there is nothing to wait\n * behind, so it activates directly. If that is right, `registration.waiting`\n * being non-null already implies this is not a first install, and the controller\n * term is redundant rather than protective. **I have not verified that against a\n * real service worker.** So the old, more permissive behaviour stays as the\n * floor, and first-install suppression rides on the same fact rather than on a\n * second guard that could disagree with it.\n *\n * If someone later measures that a first-install worker CAN sit in `waiting`,\n * this is the function to add the term to — and the test to write first is the\n * one that fails today.\n */\nexport function shouldOfferUpdate({ waiting, snoozedUntil, now }: ShouldOfferInput): boolean {\n if (!waiting) return false;\n if (snoozedUntil !== null && snoozedUntil > now) return false;\n return true;\n}\n","import { SKIP_WAITING_MESSAGE } from \"./message.js\";\nimport { shouldOfferUpdate } from \"./should-offer.js\";\n\nexport { SKIP_WAITING, SKIP_WAITING_MESSAGE } from \"./message.js\";\nexport { shouldOfferUpdate } from \"./should-offer.js\";\nexport type { ShouldOfferInput } from \"./should-offer.js\";\nexport type { SkipWaitingMessage } from \"./message.js\";\n\nexport interface PwaUpdaterOptions {\n /** Service-worker script URL to register. Default `/sw.js`. */\n swUrl?: string;\n /**\n * Register `swUrl` ourselves (manual `sw.js` style). Set `false` when the\n * app already registers the SW (e.g. Serwist's `registerSW` / `@serwist/next`)\n * — the updater then attaches to the existing registration via\n * `navigator.serviceWorker.ready` instead of registering again. Default `true`.\n */\n register?: boolean;\n /** How often to poll `registration.update()` (ms). `0` disables. Default 60 min. */\n pollIntervalMs?: number;\n /**\n * Also check for an update when the tab regains focus / becomes visible.\n * A constantly-focused tab never fires `visibilitychange`, so `focus` is the\n * one that catches \"user came back to the app\". Default `true`.\n */\n updateOnFocus?: boolean;\n /** Reload the page once the new worker takes control. Default `true`. */\n reloadOnControllerChange?: boolean;\n /**\n * How long `snooze()` holds the offer down (ms). Default 30 min.\n *\n * F054.8 — \"Later\" is a SNOOZE, never a mute. The defect this replaced was a\n * banner that got exactly one chance to be seen; a permanent dismiss is that\n * defect made official.\n */\n snoozeMs?: number;\n /**\n * Where a snooze is remembered, so it survives the reload the banner is\n * asking for. Defaults to `localStorage` when available; pass `null` to keep\n * the snooze in memory only.\n */\n snoozeStorage?: Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\"> | null;\n /**\n * Consumer guard. When `true` the updater is an inert no-op (registers\n * nothing). Pass your own policy, e.g. `disabled: isNativeCapacitor || isDev`\n * — the package never hardcodes an environment or a `.native` check.\n */\n disabled?: boolean;\n}\n\nexport interface PwaUpdaterState {\n /** A new service worker is installed and waiting to activate. */\n updateReady: boolean;\n}\n\nexport interface PwaUpdater {\n /** Subscribe to state changes. Returns an unsubscribe fn. */\n subscribe(listener: (state: PwaUpdaterState) => void): () => void;\n getState(): PwaUpdaterState;\n /** Tell the waiting worker to activate (posts SKIP_WAITING). No-op if none waits. */\n applyUpdate(): void;\n /**\n * \"Later\". Holds the offer down for `snoozeMs`, then it comes back on the\n * next tick — this is NOT a mute, and it deliberately cannot be made one.\n */\n snooze(): void;\n /** Re-read `registration.waiting` right now and emit if the answer moved. */\n check(): void;\n /** Stop polling + remove all listeners. */\n destroy(): void;\n}\n\nconst DEFAULT_POLL_MS = 60 * 60 * 1000;\nconst DEFAULT_SNOOZE_MS = 30 * 60 * 1000;\nconst SNOOZE_KEY = \"broberg-pwa:snoozed-until\";\n\n/**\n * Framework- and bundler-agnostic controller for the PWA \"new version\n * available\" lifecycle: register (or attach) → detect a waiting worker\n * (suppressing the first install) → let the consumer activate it → reload on\n * takeover, re-checking on interval + focus/visibility.\n *\n * Distilled from the pattern hand-rolled across the fleet (fds, cardmem,\n * pitch-vault). Works with any service worker (Serwist, Workbox, hand-rolled)\n * as long as the SW answers a `SKIP_WAITING` message — see `@broberg/pwa/sw`.\n */\nexport function createPwaUpdater(options: PwaUpdaterOptions = {}): PwaUpdater {\n const {\n swUrl = \"/sw.js\",\n register = true,\n pollIntervalMs = DEFAULT_POLL_MS,\n updateOnFocus = true,\n reloadOnControllerChange = true,\n snoozeMs = DEFAULT_SNOOZE_MS,\n disabled = false,\n } = options;\n\n const listeners = new Set<(state: PwaUpdaterState) => void>();\n let updateReady = false;\n let waitingWorker: ServiceWorker | null = null;\n\n const getState = (): PwaUpdaterState => ({ updateReady });\n const emit = (): void => {\n const state = getState();\n for (const listener of listeners) listener(state);\n };\n const subscribe = (listener: (state: PwaUpdaterState) => void): (() => void) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n };\n\n const supported =\n typeof navigator !== \"undefined\" && \"serviceWorker\" in navigator;\n\n // Inert no-op: disabled by the consumer, or no service-worker support at all.\n if (disabled || !supported) {\n return {\n subscribe,\n getState,\n applyUpdate() {},\n snooze() {},\n check() {},\n destroy() {\n listeners.clear();\n },\n };\n }\n\n const container = navigator.serviceWorker;\n let pollId: ReturnType<typeof setInterval> | null = null;\n let removeFocusListeners: (() => void) | null = null;\n let reloading = false;\n let destroyed = false;\n\n // F054.8 — READ the answer, never remember it.\n //\n // This used to be markReady(worker), the only writer of `updateReady`, and it\n // was guarded by `if (!updateReady)` — so `emit()` fired AT MOST ONCE for the\n // life of the updater. Both adapters drive their state from subscribe(), so a\n // consumer who dismissed the banner had no channel that could ever raise it\n // again. cardmem measured the consequence in production: a client sat on an\n // old bundle indefinitely, and the only symptom anyone had was a person\n // saying a feature was missing.\n //\n // `registration` is captured once resolved so every tick can re-read\n // `.waiting` rather than wait to be told.\n let registrationRef: ServiceWorkerRegistration | null = null;\n\n const storage: PwaUpdaterOptions[\"snoozeStorage\"] =\n options.snoozeStorage !== undefined\n ? options.snoozeStorage\n : typeof localStorage !== \"undefined\"\n ? localStorage\n : null;\n\n let snoozedUntil: number | null = null;\n const readSnooze = (): number | null => {\n if (!storage) return snoozedUntil;\n try {\n const raw = storage.getItem(SNOOZE_KEY);\n if (!raw) return null;\n const n = Number(raw);\n return Number.isFinite(n) ? n : null;\n } catch {\n // A browser with site data blocked THROWS on read. That is not a reason to\n // stop offering updates — fall back to the in-memory value.\n return snoozedUntil;\n }\n };\n const writeSnooze = (until: number | null): void => {\n snoozedUntil = until;\n if (!storage) return;\n try {\n if (until === null) storage.removeItem(SNOOZE_KEY);\n else storage.setItem(SNOOZE_KEY, String(until));\n } catch {\n // in-memory only for this tab; already recorded above\n }\n };\n\n /**\n * Re-derive from what is true RIGHT NOW and emit only when the answer moved.\n * Emits in BOTH directions: false→true raises the banner, true→false takes it\n * down when the worker is gone or the user snoozed.\n */\n const check = (): void => {\n const waiting = registrationRef?.waiting ?? null;\n waitingWorker = waiting;\n const next = shouldOfferUpdate({\n waiting,\n snoozedUntil: readSnooze(),\n now: Date.now(),\n });\n if (next !== updateReady) {\n updateReady = next;\n emit();\n }\n };\n\n // With `clientsClaim: true` a brand-new worker claims a previously\n // uncontrolled page and fires `controllerchange` on the FIRST install — that\n // is not an update, so reloading there would yank a first-time visitor out of\n // whatever they are doing. Only a `controllerchange` that REPLACES an existing\n // controller is a real takeover worth reloading for.\n let hadController = !!container.controller;\n const onControllerChange = (): void => {\n if (!reloadOnControllerChange || reloading) return;\n if (!hadController) {\n hadController = true; // first claim of an uncontrolled page — not an update\n return;\n }\n reloading = true; // guard against a reload-loop\n if (typeof location !== \"undefined\") location.reload();\n };\n container.addEventListener(\"controllerchange\", onControllerChange);\n\n const watchInstalling = (registration: ServiceWorkerRegistration): void => {\n const installing = registration.installing;\n if (!installing) return;\n installing.addEventListener(\"statechange\", () => {\n // A new worker reaching `installed` WHILE a controller already exists is\n // an update. Reaching `installed` with no controller is the FIRST install\n // — nothing to update, so we stay quiet.\n if (installing.state === \"installed\") check();\n });\n };\n\n const wireFocusChecks = (registration: ServiceWorkerRegistration): void => {\n if (!updateOnFocus) return;\n // update() asks the SERVER for a new worker; check() reads whether one is\n // already WAITING. The second is the half that was missing — reg.update()\n // resolves without firing updatefound when a worker is already waiting, so\n // a tab that missed the original event could never learn about it.\n const tick = (): void => {\n check();\n registration.update().catch(() => {}).then(check, check);\n };\n const onFocus = (): void => tick();\n const onVisibility = (): void => {\n if (typeof document !== \"undefined\" && document.visibilityState === \"visible\") {\n tick();\n }\n };\n if (typeof window !== \"undefined\") window.addEventListener(\"focus\", onFocus);\n if (typeof document !== \"undefined\") {\n document.addEventListener(\"visibilitychange\", onVisibility);\n }\n removeFocusListeners = () => {\n if (typeof window !== \"undefined\") window.removeEventListener(\"focus\", onFocus);\n if (typeof document !== \"undefined\") {\n document.removeEventListener(\"visibilitychange\", onVisibility);\n }\n };\n };\n\n // Manual style registers swUrl; serwist/registerSW style attaches to the\n // registration the app already made via `.ready`.\n const registrationPromise = register ? container.register(swUrl) : container.ready;\n\n registrationPromise\n .then((registration) => {\n if (destroyed) return;\n registrationRef = registration;\n check();\n registration.addEventListener(\"updatefound\", () => watchInstalling(registration));\n if (pollIntervalMs > 0) {\n pollId = setInterval(() => {\n check();\n registration\n .update()\n .catch(() => {\n // ignore transient update-check network errors\n })\n .then(check, check);\n }, pollIntervalMs);\n }\n wireFocusChecks(registration);\n })\n .catch(() => {\n // registration failed — stay inert rather than throw into the app\n });\n\n return {\n subscribe,\n getState,\n applyUpdate() {\n if (waitingWorker) waitingWorker.postMessage(SKIP_WAITING_MESSAGE);\n },\n snooze() {\n writeSnooze(Date.now() + snoozeMs);\n check();\n },\n check,\n destroy() {\n destroyed = true;\n if (pollId !== null) clearInterval(pollId);\n removeFocusListeners?.();\n container.removeEventListener(\"controllerchange\", onControllerChange);\n listeners.clear();\n },\n };\n}\n","import type { PwaUpdaterOptions } from \"./index.js\";\n\n/**\n * A stable identity for an options object, for an adapter's effect dependency.\n *\n * F054.7 — WHY THIS EXISTS INSTEAD OF A DEPENDENCY LIST. Both adapters used to\n * destructure four named options and list those same four as their effect deps.\n * That is a second copy of the core's option list, and it had already drifted:\n * `register` and `updateOnFocus` were never forwarded, so a consumer writing\n * `register: false` got a service-worker registration anyway, with no error and\n * no warning. fd-sundhed found it by reading our shipped dist, which is not a\n * detector anyone should need.\n *\n * Deriving the key from the options the CALLER passed means a new core option\n * reaches both adapters with neither adapter edited. The list was the defect —\n * not the two names missing from it.\n *\n * Keys are SORTED so `{a, b}` and `{b, a}` are the same identity, and\n * `undefined` values are dropped so an explicitly-omitted option and an absent\n * one do not look like different configurations.\n *\n * THE ONE BOUNDARY, stated because the claim above is otherwise broader than\n * what is true: the identity is JSON, so a value JSON cannot express collapses.\n * Measured — `{onError: () => 1}` and `{onError: () => 2}` produce the byte-\n * identical key `[[\"onError\",null]]`, so a caller swapping the callback would\n * keep the first updater and never see the new one take effect. Every option\n * the core has today is a string, number or boolean, so nothing is affected;\n * this is here for whoever adds the first FUNCTION option (an `onUpdateReady`\n * is the obvious candidate). That option must be given its own identity here,\n * not merely added to the core.\n */\n/**\n * F054.8 — the boundary above is no longer hypothetical: `snoozeStorage` is an\n * object of functions, and `JSON.stringify` renders it `{}`. Two different\n * storages would produce the byte-identical key, so a caller swapping one would\n * keep the first updater and never see the new one — the exact collapse the\n * paragraph above predicted, arriving one option later.\n *\n * So a value JSON cannot express gets a stable identity of its own instead: the\n * same object gives the same tag for the life of the page, a different object a\n * different tag. Kept in a WeakMap so holding the tag cannot hold the object.\n */\nconst identities = new WeakMap<object, string>();\nlet nextIdentity = 0;\nconst identify = (value: unknown): unknown => {\n if (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) {\n return value;\n }\n const obj = value as object;\n let tag = identities.get(obj);\n if (tag === undefined) {\n tag = `@ref:${nextIdentity++}`;\n identities.set(obj, tag);\n }\n return tag;\n};\n\nexport function optionsKey(options: PwaUpdaterOptions): string {\n return JSON.stringify(\n Object.entries(options)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => [k, identify(v)]),\n );\n}\n","import { useEffect, useRef, useState } from \"react\";\nimport { createPwaUpdater, type PwaUpdater, type PwaUpdaterOptions } from \"./index.js\";\nimport { optionsKey } from \"./options-key.js\";\n\n/**\n * React binding for {@link createPwaUpdater}. Returns whether an update is\n * ready plus the `applyUpdate` action. The controller is created once and\n * torn down on unmount.\n */\nexport function usePwaUpdate(options: PwaUpdaterOptions = {}): {\n updateReady: boolean;\n applyUpdate: () => void;\n /** \"Later\" — F054.8. Holds the offer down for `snoozeMs`, then it returns. */\n snooze: () => void;\n /** Re-read `registration.waiting` now. Rarely needed; the ticks do it. */\n check: () => void;\n} {\n // The effect's identity comes from the options the CALLER passed, so a new\n // core option needs no edit here. eslint's exhaustive-deps cannot see\n // through `key`; that is the trade, and it is the right way round.\n const key = optionsKey(options);\n const [updateReady, setUpdateReady] = useState(false);\n const updaterRef = useRef<PwaUpdater | null>(null);\n\n useEffect(() => {\n // THE WHOLE OBJECT, not a hand-picked subset. See options-key.ts: the\n // subset is what silently dropped `register` and `updateOnFocus`.\n const updater = createPwaUpdater(options);\n updaterRef.current = updater;\n setUpdateReady(updater.getState().updateReady);\n const unsubscribe = updater.subscribe((state) => setUpdateReady(state.updateReady));\n return () => {\n unsubscribe();\n updater.destroy();\n updaterRef.current = null;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [key]);\n\n return {\n updateReady,\n applyUpdate: () => updaterRef.current?.applyUpdate(),\n snooze: () => updaterRef.current?.snooze(),\n check: () => updaterRef.current?.check(),\n };\n}\n\nexport interface PwaUpdateBannerLabels {\n title?: string;\n body?: string;\n update?: string;\n dismiss?: string;\n close?: string;\n}\n\nconst DEFAULT_LABELS: Required<PwaUpdateBannerLabels> = {\n title: \"New version available\",\n body: \"Reload to get the latest version.\",\n update: \"Update\",\n dismiss: \"Later\",\n close: \"Close\",\n};\n\nexport interface PwaUpdateBannerProps {\n /** From `usePwaUpdate().updateReady`. Nothing renders when false. */\n updateReady: boolean;\n /** From `usePwaUpdate().applyUpdate`. */\n onUpdate: () => void;\n /** Optional dismiss handler (wired to both \"Later\" and the close ✕). */\n onDismiss?: () => void;\n /** Override any of the built-in strings (i18n). */\n labels?: PwaUpdateBannerLabels;\n /** Your class(es) — the skeleton carries NO colours or design-system styling. */\n className?: string;\n}\n\n/**\n * Unstyled, accessible \"new version available\" banner skeleton. It ships\n * structure + a11y + stable testids only; you own the look via `className`\n * and your design tokens. Prefer {@link usePwaUpdate} directly if you'd rather\n * build the UI yourself.\n */\nexport function PwaUpdateBanner({\n updateReady,\n onUpdate,\n onDismiss,\n labels,\n className,\n}: PwaUpdateBannerProps) {\n if (!updateReady) return null;\n const l = { ...DEFAULT_LABELS, ...labels };\n const dismiss = () => onDismiss?.();\n return (\n <div role=\"status\" aria-live=\"polite\" data-testid=\"pwa-update-banner\" className={className}>\n <p data-testid=\"pwa-update-title\">{l.title}</p>\n {l.body ? <p data-testid=\"pwa-update-body\">{l.body}</p> : null}\n <button type=\"button\" data-testid=\"pwa-update-confirm\" onClick={onUpdate}>\n {l.update}\n </button>\n <button type=\"button\" data-testid=\"pwa-update-dismiss\" onClick={dismiss}>\n {l.dismiss}\n </button>\n <button\n type=\"button\"\n data-testid=\"pwa-update-close\"\n aria-label={l.close}\n onClick={dismiss}\n >\n {\"×\"}\n </button>\n </div>\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@broberg/pwa",
3
- "version": "0.2.2",
3
+ "version": "0.4.0",
4
4
  "description": "Fleet PWA primitive: a framework-agnostic service-worker update-detection controller (new-version-available lifecycle) + a React hook and unstyled banner skeleton + a service-worker skip-waiting helper. Zero runtime deps; ship-dark.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -37,11 +37,12 @@
37
37
  "types": "./dist/preact.d.ts",
38
38
  "import": "./dist/preact.js",
39
39
  "require": "./dist/preact.cjs"
40
- }
40
+ },
41
+ "./package.json": "./package.json"
41
42
  },
42
43
  "scripts": {
43
44
  "build": "rm -rf dist && tsup && node verify-exports.mjs",
44
- "test": "vitest run",
45
+ "test": "vitest run && node ../../scripts/mutations-if-changed.mjs test/mutations.mjs",
45
46
  "typecheck": "tsc --noEmit"
46
47
  },
47
48
  "peerDependencies": {