@broberg/pwa 0.4.0 → 0.4.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/README.md +65 -0
- package/dist/index.cjs +18 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +18 -6
- package/dist/index.js.map +1 -1
- package/dist/preact.cjs +18 -6
- package/dist/preact.cjs.map +1 -1
- package/dist/preact.js +18 -6
- package/dist/preact.js.map +1 -1
- package/dist/react.cjs +18 -6
- package/dist/react.cjs.map +1 -1
- package/dist/react.js +18 -6
- package/dist/react.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -8,6 +8,21 @@ as one small, framework- and bundler-agnostic package instead of a fifth copy.
|
|
|
8
8
|
npm i @broberg/pwa
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
+
## 0.4.1 — «Update now» now always updates (F054.9)
|
|
12
|
+
|
|
13
|
+
**Take 0.4.1 if you show an update button.** In 0.4.0 a press could do nothing,
|
|
14
|
+
forever: on a page opened WITHOUT an active service worker (a shift-reload, or
|
|
15
|
+
the first page after registration) while a new worker was waiting, the guard
|
|
16
|
+
that stops a first install from reloading a new visitor also swallowed the
|
|
17
|
+
takeover the press caused. No reload, and every later press went to a worker
|
|
18
|
+
that was already active. Reported by the owner after 30 presses in helpdesk.
|
|
19
|
+
|
|
20
|
+
Now: after `applyUpdate()` the next takeover always reloads; a press whose
|
|
21
|
+
worker already activated reloads directly; and an SW without `clientsClaim`
|
|
22
|
+
reloads when the worker reaches `activated`. One reload, never two.
|
|
23
|
+
`reloadOnControllerChange: false` still means you reload yourself. No API
|
|
24
|
+
change; a first install still never reloads on its own.
|
|
25
|
+
|
|
11
26
|
## 0.4.0 — READ, don't remember (F054.8)
|
|
12
27
|
|
|
13
28
|
**Take 0.4.0.** Before it, `updateReady` could only ever go **up**, and only from
|
|
@@ -40,6 +55,56 @@ const { updateReady, applyUpdate, snooze } = usePwaUpdate();
|
|
|
40
55
|
// "Update" → applyUpdate() "Later" → snooze(), NOT a local setState(false)
|
|
41
56
|
```
|
|
42
57
|
|
|
58
|
+
**The pattern to look for in your own code**, named by cardmem when they read
|
|
59
|
+
this report against their adoption — it is not hypothetical, it is what a
|
|
60
|
+
consumer writes when the flag can only ever rise:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
// ⚠️ the 0.3.x shape: a local mirror, reset only on dismiss
|
|
64
|
+
const [needRefresh, setNeedRefresh] = useState(false);
|
|
65
|
+
useEffect(() => { if (updateReady) setNeedRefresh(true); }, [updateReady]);
|
|
66
|
+
const onDismiss = () => setNeedRefresh(false); // ← the only way down
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
That mirror cannot fall when `updateReady` does, and dismissing it is permanent
|
|
70
|
+
— which is the original defect, reproduced one layer up. Drop the mirror and
|
|
71
|
+
render from `updateReady` directly; wire "Later" to `snooze()`.
|
|
72
|
+
|
|
73
|
+
So an upgrade here is a small **migration**, not a free version bump. It is the
|
|
74
|
+
one place 0.4.0 asks anything of you.
|
|
75
|
+
|
|
76
|
+
### Upgrading does NOT fix this on its own if you have your own dismissal
|
|
77
|
+
|
|
78
|
+
fd-sundhed found this by reading their own installed code rather than this
|
|
79
|
+
report, and it is the half that would otherwise produce a green claim and an
|
|
80
|
+
unchanged user. Their banner carries a second dismissal on top of the hook:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
const [dismissed] = useState(() => sessionStorage.getItem(KEY) === "1");
|
|
84
|
+
if (!updateReady || dismissed) return null; // "Later" hides it for the whole tab
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
The defect is **doubled** — ours in the hook, theirs in the component — and only
|
|
88
|
+
ours goes away with a `pnpm up`. Upgrade, report it fixed, and the person still
|
|
89
|
+
never sees the banner again.
|
|
90
|
+
|
|
91
|
+
**So before you upgrade, grep your own component for a second way the banner can
|
|
92
|
+
be hidden**: a `sessionStorage`/`localStorage` flag, a `dismissed` state, a
|
|
93
|
+
`useRef` that latches. Whatever holds it down has to become the snooze, or the
|
|
94
|
+
snooze is decorative.
|
|
95
|
+
|
|
96
|
+
### If you need something stricter than 30 minutes
|
|
97
|
+
|
|
98
|
+
`snoozeMs` is a plain number, so a large one is available and this package will
|
|
99
|
+
not stop you. The honest statement is therefore narrower than "a mute is
|
|
100
|
+
impossible": there is no OPTION named mute, and the default comes back.
|
|
101
|
+
|
|
102
|
+
If the policy you actually want is *"gone for the rest of this tab"*, express it
|
|
103
|
+
as scope rather than duration — `snoozeStorage: sessionStorage` with a long
|
|
104
|
+
`snoozeMs`. It dies with the tab instead of pretending to be permanent, so a
|
|
105
|
+
person who closes and reopens the app is asked again, and nobody has to reason
|
|
106
|
+
about a timestamp in the year 2255.
|
|
107
|
+
|
|
43
108
|
`snooze()` is deliberately not a mute, and there is no option to make it one: a
|
|
44
109
|
banner that can be silenced forever is the defect above, made official. The
|
|
45
110
|
snooze is persisted (`localStorage` by default, `snoozeStorage: null` for
|
package/dist/index.cjs
CHANGED
|
@@ -27,7 +27,6 @@ function createPwaUpdater(options = {}) {
|
|
|
27
27
|
} = options;
|
|
28
28
|
const listeners = /* @__PURE__ */ new Set();
|
|
29
29
|
let updateReady = false;
|
|
30
|
-
let waitingWorker = null;
|
|
31
30
|
const getState = () => ({ updateReady });
|
|
32
31
|
const emit = () => {
|
|
33
32
|
const state = getState();
|
|
@@ -83,7 +82,6 @@ function createPwaUpdater(options = {}) {
|
|
|
83
82
|
};
|
|
84
83
|
const check = () => {
|
|
85
84
|
const waiting = registrationRef?.waiting ?? null;
|
|
86
|
-
waitingWorker = waiting;
|
|
87
85
|
const next = shouldOfferUpdate({
|
|
88
86
|
waiting,
|
|
89
87
|
snoozedUntil: readSnooze(),
|
|
@@ -95,14 +93,19 @@ function createPwaUpdater(options = {}) {
|
|
|
95
93
|
}
|
|
96
94
|
};
|
|
97
95
|
let hadController = !!container.controller;
|
|
96
|
+
let applied = false;
|
|
97
|
+
const reloadOnce = () => {
|
|
98
|
+
if (!reloadOnControllerChange || reloading) return;
|
|
99
|
+
reloading = true;
|
|
100
|
+
if (typeof location !== "undefined") location.reload();
|
|
101
|
+
};
|
|
98
102
|
const onControllerChange = () => {
|
|
99
103
|
if (!reloadOnControllerChange || reloading) return;
|
|
100
|
-
if (!hadController) {
|
|
104
|
+
if (!hadController && !applied) {
|
|
101
105
|
hadController = true;
|
|
102
106
|
return;
|
|
103
107
|
}
|
|
104
|
-
|
|
105
|
-
if (typeof location !== "undefined") location.reload();
|
|
108
|
+
reloadOnce();
|
|
106
109
|
};
|
|
107
110
|
container.addEventListener("controllerchange", onControllerChange);
|
|
108
111
|
const watchInstalling = (registration) => {
|
|
@@ -156,7 +159,16 @@ function createPwaUpdater(options = {}) {
|
|
|
156
159
|
subscribe,
|
|
157
160
|
getState,
|
|
158
161
|
applyUpdate() {
|
|
159
|
-
|
|
162
|
+
const waiting = registrationRef?.waiting ?? null;
|
|
163
|
+
if (waiting) {
|
|
164
|
+
applied = true;
|
|
165
|
+
waiting.addEventListener("statechange", () => {
|
|
166
|
+
if (waiting.state === "activated") reloadOnce();
|
|
167
|
+
});
|
|
168
|
+
waiting.postMessage(SKIP_WAITING_MESSAGE);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (updateReady) reloadOnce();
|
|
160
172
|
},
|
|
161
173
|
snooze() {
|
|
162
174
|
writeSnooze(Date.now() + snoozeMs);
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/message.ts","../src/should-offer.ts","../src/index.ts"],"names":[],"mappings":";;;AAKO,IAAM,YAAA,GAAe;AAErB,IAAM,oBAAA,GAAuB,EAAE,IAAA,EAAM,YAAA;;;AC4CrC,SAAS,iBAAA,CAAkB,EAAE,OAAA,EAAS,YAAA,EAAc,KAAI,EAA8B;AAC3F,EAAA,IAAI,CAAC,SAAS,OAAO,KAAA;AACrB,EAAA,IA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AAe,MAAM,eAAA,CAAgB,YAAY,CAAC,CAAA;AAChF,IAAA,IAAI,iBAAiB,CAAA,EAAG;AACtB,MAAA,MAAA,GAAS,YAAY,MAAM;AACzB,QAAA,KAAA,EAAM;AACN,QAAA,YAAA,CACG,MAAA,EAAO,CACP,KAAA,CAAM,MAAM;AAAA,QAEb,CAAC,CAAA,CACA,IAAA,CAAK,KAAA,EAAO,KAAK,CAAA;AAAA,MACtB,GAAG,cAAc,CAAA;AAAA,IACnB;AACA,IAAA,eAAA,CAAgB,YAAY,CAAA;AAAA,EAC9B,CAAC,CAAA,CACA,KAAA,CAAM,MAAM;AAAA,EAEb,CAAC,CAAA;AAEH,EAAA,OAAO;AAAA,IACL,SAAA;AAAA,IACA,QAAA;AAAA,IACA,WAAA,GAAc;AACZ,MAAA,IAAI,aAAA,EAAe,aAAA,CAAc,WAAA,CAAY,oBAAoB,CAAA;AAAA,IACnE,CAAA;AAAA,IACA,MAAA,GAAS;AACP,MAAA,WAAA,CAAY,IAAA,CAAK,GAAA,EAAI,GAAI,QAAQ,CAAA;AACjC,MAAA,KAAA,EAAM;AAAA,IACR,CAAA;AAAA,IACA,KAAA;AAAA,IACA,OAAA,GAAU;AACR,MAAA,SAAA,GAAY,IAAA;AACZ,MAAA,IAAI,MAAA,KAAW,IAAA,EAAM,aAAA,CAAc,MAAM,CAAA;AACzC,MAAA,oBAAA,IAAuB;AACvB,MAAA,SAAA,CAAU,mBAAA,CAAoB,oBAAoB,kBAAkB,CAAA;AACpE,MAAA,SAAA,CAAU,KAAA,EAAM;AAAA,IAClB;AAAA,GACF;AACF","file":"index.cjs","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"]}
|
|
1
|
+
{"version":3,"sources":["../src/message.ts","../src/should-offer.ts","../src/index.ts"],"names":[],"mappings":";;;AAKO,IAAM,YAAA,GAAe;AAErB,IAAM,oBAAA,GAAuB,EAAE,IAAA,EAAM,YAAA;;;AC4CrC,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;;;ACqBA,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,MAAM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AAA,IACA,QAAA;AAAA,IACA,WAAA,GAAc;AAGZ,MAAA,MAAM,OAAA,GAAU,iBAAiB,OAAA,IAAW,IAAA;AAC5C,MAAA,IAAI,OAAA,EAAS;AACX,QAAA,OAAA,GAAU,IAAA;AAIV,QAAA,OAAA,CAAQ,gBAAA,CAAiB,eAAe,MAAM;AAC5C,UAAA,IAAI,OAAA,CAAQ,KAAA,KAAU,WAAA,EAAa,UAAA,EAAW;AAAA,QAChD,CAAC,CAAA;AACD,QAAA,OAAA,CAAQ,YAAY,oBAAoB,CAAA;AACxC,QAAA;AAAA,MACF;AAGA,MAAA,IAAI,aAAa,UAAA,EAAW;AAAA,IAC9B,CAAA;AAAA,IACA,MAAA,GAAS;AACP,MAAA,WAAA,CAAY,IAAA,CAAK,GAAA,EAAI,GAAI,QAAQ,CAAA;AACjC,MAAA,KAAA,EAAM;AAAA,IACR,CAAA;AAAA,IACA,KAAA;AAAA,IACA,OAAA,GAAU;AACR,MAAA,SAAA,GAAY,IAAA;AACZ,MAAA,IAAI,MAAA,KAAW,IAAA,EAAM,aAAA,CAAc,MAAM,CAAA;AACzC,MAAA,oBAAA,IAAuB;AACvB,MAAA,SAAA,CAAU,mBAAA,CAAoB,oBAAoB,kBAAkB,CAAA;AACpE,MAAA,SAAA,CAAU,KAAA,EAAM;AAAA,IAClB;AAAA,GACF;AACF","file":"index.cjs","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 /**\n * Tell the waiting worker to activate (posts SKIP_WAITING); the page reloads\n * when it takes over. If an update was offered but nothing waits any more\n * (it already activated), reloads directly. No-op when nothing was offered.\n */\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\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 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 //\n // F054.9 — BUT THE GUARD CANNOT TELL A FIRST CLAIM FROM ONE THE USER ASKED FOR.\n // A page opened with no controller (shift-reload bypasses the SW, or the first\n // page after registration) while a worker waits shows the banner; pressing it\n // activates the worker, whose controllerchange the guard then swallowed. Every\n // later press posted SKIP_WAITING to a worker that was already active. The\n // owner pressed «Opdatér nu» 30 times in helpdesk and nothing happened.\n // `applied` is the missing fact: after an explicit applyUpdate() the next\n // takeover is the update, whatever the page was controlled by before.\n let hadController = !!container.controller;\n let applied = false;\n const reloadOnce = (): void => {\n if (!reloadOnControllerChange || reloading) return;\n reloading = true; // guard against a reload-loop\n if (typeof location !== \"undefined\") location.reload();\n };\n const onControllerChange = (): void => {\n if (!reloadOnControllerChange || reloading) return;\n if (!hadController && !applied) {\n hadController = true; // first claim of an uncontrolled page — not an update\n return;\n }\n reloadOnce();\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 // Re-read, never the cached reference: the cached one can be a worker\n // that has since ACTIVATED, and posting to it does nothing (F054.9).\n const waiting = registrationRef?.waiting ?? null;\n if (waiting) {\n applied = true;\n // Without clientsClaim an uncontrolled page never gets controllerchange,\n // so the worker's own activation is the second signal. reloadOnce()\n // makes the two paths safe to both fire.\n waiting.addEventListener(\"statechange\", () => {\n if (waiting.state === \"activated\") reloadOnce();\n });\n waiting.postMessage(SKIP_WAITING_MESSAGE);\n return;\n }\n // Nothing waits, yet an update was offered: the worker already took over\n // (an earlier press whose reload was lost). Reloading IS the update.\n if (updateReady) reloadOnce();\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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -101,7 +101,11 @@ interface PwaUpdater {
|
|
|
101
101
|
/** Subscribe to state changes. Returns an unsubscribe fn. */
|
|
102
102
|
subscribe(listener: (state: PwaUpdaterState) => void): () => void;
|
|
103
103
|
getState(): PwaUpdaterState;
|
|
104
|
-
/**
|
|
104
|
+
/**
|
|
105
|
+
* Tell the waiting worker to activate (posts SKIP_WAITING); the page reloads
|
|
106
|
+
* when it takes over. If an update was offered but nothing waits any more
|
|
107
|
+
* (it already activated), reloads directly. No-op when nothing was offered.
|
|
108
|
+
*/
|
|
105
109
|
applyUpdate(): void;
|
|
106
110
|
/**
|
|
107
111
|
* "Later". Holds the offer down for `snoozeMs`, then it comes back on the
|
package/dist/index.d.ts
CHANGED
|
@@ -101,7 +101,11 @@ interface PwaUpdater {
|
|
|
101
101
|
/** Subscribe to state changes. Returns an unsubscribe fn. */
|
|
102
102
|
subscribe(listener: (state: PwaUpdaterState) => void): () => void;
|
|
103
103
|
getState(): PwaUpdaterState;
|
|
104
|
-
/**
|
|
104
|
+
/**
|
|
105
|
+
* Tell the waiting worker to activate (posts SKIP_WAITING); the page reloads
|
|
106
|
+
* when it takes over. If an update was offered but nothing waits any more
|
|
107
|
+
* (it already activated), reloads directly. No-op when nothing was offered.
|
|
108
|
+
*/
|
|
105
109
|
applyUpdate(): void;
|
|
106
110
|
/**
|
|
107
111
|
* "Later". Holds the offer down for `snoozeMs`, then it comes back on the
|
package/dist/index.js
CHANGED
|
@@ -24,7 +24,6 @@ function createPwaUpdater(options = {}) {
|
|
|
24
24
|
} = options;
|
|
25
25
|
const listeners = /* @__PURE__ */ new Set();
|
|
26
26
|
let updateReady = false;
|
|
27
|
-
let waitingWorker = null;
|
|
28
27
|
const getState = () => ({ updateReady });
|
|
29
28
|
const emit = () => {
|
|
30
29
|
const state = getState();
|
|
@@ -80,7 +79,6 @@ function createPwaUpdater(options = {}) {
|
|
|
80
79
|
};
|
|
81
80
|
const check = () => {
|
|
82
81
|
const waiting = registrationRef?.waiting ?? null;
|
|
83
|
-
waitingWorker = waiting;
|
|
84
82
|
const next = shouldOfferUpdate({
|
|
85
83
|
waiting,
|
|
86
84
|
snoozedUntil: readSnooze(),
|
|
@@ -92,14 +90,19 @@ function createPwaUpdater(options = {}) {
|
|
|
92
90
|
}
|
|
93
91
|
};
|
|
94
92
|
let hadController = !!container.controller;
|
|
93
|
+
let applied = false;
|
|
94
|
+
const reloadOnce = () => {
|
|
95
|
+
if (!reloadOnControllerChange || reloading) return;
|
|
96
|
+
reloading = true;
|
|
97
|
+
if (typeof location !== "undefined") location.reload();
|
|
98
|
+
};
|
|
95
99
|
const onControllerChange = () => {
|
|
96
100
|
if (!reloadOnControllerChange || reloading) return;
|
|
97
|
-
if (!hadController) {
|
|
101
|
+
if (!hadController && !applied) {
|
|
98
102
|
hadController = true;
|
|
99
103
|
return;
|
|
100
104
|
}
|
|
101
|
-
|
|
102
|
-
if (typeof location !== "undefined") location.reload();
|
|
105
|
+
reloadOnce();
|
|
103
106
|
};
|
|
104
107
|
container.addEventListener("controllerchange", onControllerChange);
|
|
105
108
|
const watchInstalling = (registration) => {
|
|
@@ -153,7 +156,16 @@ function createPwaUpdater(options = {}) {
|
|
|
153
156
|
subscribe,
|
|
154
157
|
getState,
|
|
155
158
|
applyUpdate() {
|
|
156
|
-
|
|
159
|
+
const waiting = registrationRef?.waiting ?? null;
|
|
160
|
+
if (waiting) {
|
|
161
|
+
applied = true;
|
|
162
|
+
waiting.addEventListener("statechange", () => {
|
|
163
|
+
if (waiting.state === "activated") reloadOnce();
|
|
164
|
+
});
|
|
165
|
+
waiting.postMessage(SKIP_WAITING_MESSAGE);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (updateReady) reloadOnce();
|
|
157
169
|
},
|
|
158
170
|
snooze() {
|
|
159
171
|
writeSnooze(Date.now() + snoozeMs);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/should-offer.ts","../src/index.ts"],"names":[],"mappings":";;;;AAmDO,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,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YAAY,MAAM;AACzB,QAAA,KAAA,EAAM;AACN,QAAA,YAAA,CACG,MAAA,EAAO,CACP,KAAA,CAAM,MAAM;AAAA,QAEb,CAAC,CAAA,CACA,IAAA,CAAK,KAAA,EAAO,KAAK,CAAA;AAAA,MACtB,GAAG,cAAc,CAAA;AAAA,IACnB;AACA,IAAA,eAAA,CAAgB,YAAY,CAAA;AAAA,EAC9B,CAAC,CAAA,CACA,KAAA,CAAM,MAAM;AAAA,EAEb,CAAC,CAAA;AAEH,EAAA,OAAO;AAAA,IACL,SAAA;AAAA,IACA,QAAA;AAAA,IACA,WAAA,GAAc;AACZ,MAAA,IAAI,aAAA,EAAe,aAAA,CAAc,WAAA,CAAY,oBAAoB,CAAA;AAAA,IACnE,CAAA;AAAA,IACA,MAAA,GAAS;AACP,MAAA,WAAA,CAAY,IAAA,CAAK,GAAA,EAAI,GAAI,QAAQ,CAAA;AACjC,MAAA,KAAA,EAAM;AAAA,IACR,CAAA;AAAA,IACA,KAAA;AAAA,IACA,OAAA,GAAU;AACR,MAAA,SAAA,GAAY,IAAA;AACZ,MAAA,IAAI,MAAA,KAAW,IAAA,EAAM,aAAA,CAAc,MAAM,CAAA;AACzC,MAAA,oBAAA,IAAuB;AACvB,MAAA,SAAA,CAAU,mBAAA,CAAoB,oBAAoB,kBAAkB,CAAA;AACpE,MAAA,SAAA,CAAU,KAAA,EAAM;AAAA,IAClB;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\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"]}
|
|
1
|
+
{"version":3,"sources":["../src/should-offer.ts","../src/index.ts"],"names":[],"mappings":";;;;AAmDO,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;;;ACqBA,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,MAAM,SAAA,uBAAgB,GAAA,EAAsC;AAC5D,EAAA,IAAI,WAAA,GAAc,KAAA;AAElB,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,QAAA,KAA6D;AAC9E,IAAA,SAAA,CAAU,IAAI,QAAQ,CAAA;AACtB,IAAA,OAAO,MAAM,SAAA,CAAU,MAAA,CAAO,QAAQ,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,MAAA,GAAS;AACP,MAAA,WAAA,CAAY,IAAA,CAAK,GAAA,EAAI,GAAI,QAAQ,CAAA;AACjC,MAAA,KAAA,EAAM;AAAA,IACR,CAAA;AAAA,IACA,KAAA;AAAA,IACA,OAAA,GAAU;AACR,MAAA,SAAA,GAAY,IAAA;AACZ,MAAA,IAAI,MAAA,KAAW,IAAA,EAAM,aAAA,CAAc,MAAM,CAAA;AACzC,MAAA,oBAAA,IAAuB;AACvB,MAAA,SAAA,CAAU,mBAAA,CAAoB,oBAAoB,kBAAkB,CAAA;AACpE,MAAA,SAAA,CAAU,KAAA,EAAM;AAAA,IAClB;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\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 /**\n * Tell the waiting worker to activate (posts SKIP_WAITING); the page reloads\n * when it takes over. If an update was offered but nothing waits any more\n * (it already activated), reloads directly. No-op when nothing was offered.\n */\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\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 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 //\n // F054.9 — BUT THE GUARD CANNOT TELL A FIRST CLAIM FROM ONE THE USER ASKED FOR.\n // A page opened with no controller (shift-reload bypasses the SW, or the first\n // page after registration) while a worker waits shows the banner; pressing it\n // activates the worker, whose controllerchange the guard then swallowed. Every\n // later press posted SKIP_WAITING to a worker that was already active. The\n // owner pressed «Opdatér nu» 30 times in helpdesk and nothing happened.\n // `applied` is the missing fact: after an explicit applyUpdate() the next\n // takeover is the update, whatever the page was controlled by before.\n let hadController = !!container.controller;\n let applied = false;\n const reloadOnce = (): void => {\n if (!reloadOnControllerChange || reloading) return;\n reloading = true; // guard against a reload-loop\n if (typeof location !== \"undefined\") location.reload();\n };\n const onControllerChange = (): void => {\n if (!reloadOnControllerChange || reloading) return;\n if (!hadController && !applied) {\n hadController = true; // first claim of an uncontrolled page — not an update\n return;\n }\n reloadOnce();\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 // Re-read, never the cached reference: the cached one can be a worker\n // that has since ACTIVATED, and posting to it does nothing (F054.9).\n const waiting = registrationRef?.waiting ?? null;\n if (waiting) {\n applied = true;\n // Without clientsClaim an uncontrolled page never gets controllerchange,\n // so the worker's own activation is the second signal. reloadOnce()\n // makes the two paths safe to both fire.\n waiting.addEventListener(\"statechange\", () => {\n if (waiting.state === \"activated\") reloadOnce();\n });\n waiting.postMessage(SKIP_WAITING_MESSAGE);\n return;\n }\n // Nothing waits, yet an update was offered: the worker already took over\n // (an earlier press whose reload was lost). Reloading IS the update.\n if (updateReady) reloadOnce();\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"]}
|
package/dist/preact.cjs
CHANGED
|
@@ -32,7 +32,6 @@ function createPwaUpdater(options = {}) {
|
|
|
32
32
|
} = options;
|
|
33
33
|
const listeners = /* @__PURE__ */ new Set();
|
|
34
34
|
let updateReady = false;
|
|
35
|
-
let waitingWorker = null;
|
|
36
35
|
const getState = () => ({ updateReady });
|
|
37
36
|
const emit = () => {
|
|
38
37
|
const state = getState();
|
|
@@ -88,7 +87,6 @@ function createPwaUpdater(options = {}) {
|
|
|
88
87
|
};
|
|
89
88
|
const check = () => {
|
|
90
89
|
const waiting = registrationRef?.waiting ?? null;
|
|
91
|
-
waitingWorker = waiting;
|
|
92
90
|
const next = shouldOfferUpdate({
|
|
93
91
|
waiting,
|
|
94
92
|
snoozedUntil: readSnooze(),
|
|
@@ -100,14 +98,19 @@ function createPwaUpdater(options = {}) {
|
|
|
100
98
|
}
|
|
101
99
|
};
|
|
102
100
|
let hadController = !!container.controller;
|
|
101
|
+
let applied = false;
|
|
102
|
+
const reloadOnce = () => {
|
|
103
|
+
if (!reloadOnControllerChange || reloading) return;
|
|
104
|
+
reloading = true;
|
|
105
|
+
if (typeof location !== "undefined") location.reload();
|
|
106
|
+
};
|
|
103
107
|
const onControllerChange = () => {
|
|
104
108
|
if (!reloadOnControllerChange || reloading) return;
|
|
105
|
-
if (!hadController) {
|
|
109
|
+
if (!hadController && !applied) {
|
|
106
110
|
hadController = true;
|
|
107
111
|
return;
|
|
108
112
|
}
|
|
109
|
-
|
|
110
|
-
if (typeof location !== "undefined") location.reload();
|
|
113
|
+
reloadOnce();
|
|
111
114
|
};
|
|
112
115
|
container.addEventListener("controllerchange", onControllerChange);
|
|
113
116
|
const watchInstalling = (registration) => {
|
|
@@ -161,7 +164,16 @@ function createPwaUpdater(options = {}) {
|
|
|
161
164
|
subscribe,
|
|
162
165
|
getState,
|
|
163
166
|
applyUpdate() {
|
|
164
|
-
|
|
167
|
+
const waiting = registrationRef?.waiting ?? null;
|
|
168
|
+
if (waiting) {
|
|
169
|
+
applied = true;
|
|
170
|
+
waiting.addEventListener("statechange", () => {
|
|
171
|
+
if (waiting.state === "activated") reloadOnce();
|
|
172
|
+
});
|
|
173
|
+
waiting.postMessage(SKIP_WAITING_MESSAGE);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (updateReady) reloadOnce();
|
|
165
177
|
},
|
|
166
178
|
snooze() {
|
|
167
179
|
writeSnooze(Date.now() + snoozeMs);
|