@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/README.md CHANGED
@@ -8,6 +8,44 @@ 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.0 — READ, don't remember (F054.8)
12
+
13
+ **Take 0.4.0.** Before it, `updateReady` could only ever go **up**, and only from
14
+ an event: one read of `registration.waiting` at attach, plus `updatefound`. The
15
+ interval and focus checks called `registration.update()` and never looked at
16
+ `registration.waiting` at all. So the banner got **exactly one chance to be
17
+ seen** — dismiss it once, or miss the seconds it was up, and nothing in the
18
+ package could raise it again for that tab. The client then sat on the old bundle
19
+ indefinitely.
20
+
21
+ It fails in the reassuring direction: deploy green, server on the new build,
22
+ feature live — and the only symptom available to anyone is a person saying a
23
+ feature is missing. That is how cardmem found it, in their own copy of this
24
+ pattern.
25
+
26
+ **What changes for you:**
27
+
28
+ | | 0.3.x | 0.4.0 |
29
+ |---|---|---|
30
+ | `updateReady` | rises once, ever | re-derived from `registration.waiting` on every interval / focus / visibility tick |
31
+ | `subscribe()` | emits at most **once** | emits whenever the answer moves, **in both directions** |
32
+ | "Later" | your problem | `snooze()` — 30 min by default, persisted, then it comes back |
33
+
34
+ **`updateReady` CAN NOW GO FALSE.** If your code assumes it only ever rises — a
35
+ `useState` you never reset, a banner you unmount by hand — read that line before
36
+ upgrading. Everything else is additive.
37
+
38
+ ```ts
39
+ const { updateReady, applyUpdate, snooze } = usePwaUpdate();
40
+ // "Update" → applyUpdate() "Later" → snooze(), NOT a local setState(false)
41
+ ```
42
+
43
+ `snooze()` is deliberately not a mute, and there is no option to make it one: a
44
+ banner that can be silenced forever is the defect above, made official. The
45
+ snooze is persisted (`localStorage` by default, `snoozeStorage: null` for
46
+ memory-only) so the reload the banner is *asking for* cannot defeat it.
47
+
48
+
11
49
  - **`@broberg/pwa`** — `createPwaUpdater()`, a zero-dependency controller for the
12
50
  service-worker update lifecycle (works with Serwist, Workbox or a hand-rolled SW).
13
51
  - **`@broberg/pwa/react`** — `usePwaUpdate()` hook + an **unstyled** `<PwaUpdateBanner>`
package/dist/index.cjs CHANGED
@@ -4,8 +4,17 @@
4
4
  var SKIP_WAITING = "SKIP_WAITING";
5
5
  var SKIP_WAITING_MESSAGE = { type: SKIP_WAITING };
6
6
 
7
+ // src/should-offer.ts
8
+ function shouldOfferUpdate({ waiting, snoozedUntil, now }) {
9
+ if (!waiting) return false;
10
+ if (snoozedUntil !== null && snoozedUntil > now) return false;
11
+ return true;
12
+ }
13
+
7
14
  // src/index.ts
8
15
  var DEFAULT_POLL_MS = 60 * 60 * 1e3;
16
+ var DEFAULT_SNOOZE_MS = 30 * 60 * 1e3;
17
+ var SNOOZE_KEY = "broberg-pwa:snoozed-until";
9
18
  function createPwaUpdater(options = {}) {
10
19
  const {
11
20
  swUrl = "/sw.js",
@@ -13,6 +22,7 @@ function createPwaUpdater(options = {}) {
13
22
  pollIntervalMs = DEFAULT_POLL_MS,
14
23
  updateOnFocus = true,
15
24
  reloadOnControllerChange = true,
25
+ snoozeMs = DEFAULT_SNOOZE_MS,
16
26
  disabled = false
17
27
  } = options;
18
28
  const listeners = /* @__PURE__ */ new Set();
@@ -34,6 +44,10 @@ function createPwaUpdater(options = {}) {
34
44
  getState,
35
45
  applyUpdate() {
36
46
  },
47
+ snooze() {
48
+ },
49
+ check() {
50
+ },
37
51
  destroy() {
38
52
  listeners.clear();
39
53
  }
@@ -44,10 +58,39 @@ function createPwaUpdater(options = {}) {
44
58
  let removeFocusListeners = null;
45
59
  let reloading = false;
46
60
  let destroyed = false;
47
- const markReady = (worker) => {
48
- waitingWorker = worker;
49
- if (!updateReady) {
50
- updateReady = true;
61
+ let registrationRef = null;
62
+ const storage = options.snoozeStorage !== void 0 ? options.snoozeStorage : typeof localStorage !== "undefined" ? localStorage : null;
63
+ let snoozedUntil = null;
64
+ const readSnooze = () => {
65
+ if (!storage) return snoozedUntil;
66
+ try {
67
+ const raw = storage.getItem(SNOOZE_KEY);
68
+ if (!raw) return null;
69
+ const n = Number(raw);
70
+ return Number.isFinite(n) ? n : null;
71
+ } catch {
72
+ return snoozedUntil;
73
+ }
74
+ };
75
+ const writeSnooze = (until) => {
76
+ snoozedUntil = until;
77
+ if (!storage) return;
78
+ try {
79
+ if (until === null) storage.removeItem(SNOOZE_KEY);
80
+ else storage.setItem(SNOOZE_KEY, String(until));
81
+ } catch {
82
+ }
83
+ };
84
+ const check = () => {
85
+ const waiting = registrationRef?.waiting ?? null;
86
+ waitingWorker = waiting;
87
+ const next = shouldOfferUpdate({
88
+ waiting,
89
+ snoozedUntil: readSnooze(),
90
+ now: Date.now()
91
+ });
92
+ if (next !== updateReady) {
93
+ updateReady = next;
51
94
  emit();
52
95
  }
53
96
  };
@@ -66,21 +109,20 @@ function createPwaUpdater(options = {}) {
66
109
  const installing = registration.installing;
67
110
  if (!installing) return;
68
111
  installing.addEventListener("statechange", () => {
69
- if (installing.state === "installed" && container.controller) {
70
- markReady(installing);
71
- }
112
+ if (installing.state === "installed") check();
72
113
  });
73
114
  };
74
115
  const wireFocusChecks = (registration) => {
75
116
  if (!updateOnFocus) return;
76
- const check = () => {
117
+ const tick = () => {
118
+ check();
77
119
  registration.update().catch(() => {
78
- });
120
+ }).then(check, check);
79
121
  };
80
- const onFocus = () => check();
122
+ const onFocus = () => tick();
81
123
  const onVisibility = () => {
82
124
  if (typeof document !== "undefined" && document.visibilityState === "visible") {
83
- check();
125
+ tick();
84
126
  }
85
127
  };
86
128
  if (typeof window !== "undefined") window.addEventListener("focus", onFocus);
@@ -97,12 +139,14 @@ function createPwaUpdater(options = {}) {
97
139
  const registrationPromise = register ? container.register(swUrl) : container.ready;
98
140
  registrationPromise.then((registration) => {
99
141
  if (destroyed) return;
100
- if (registration.waiting) markReady(registration.waiting);
142
+ registrationRef = registration;
143
+ check();
101
144
  registration.addEventListener("updatefound", () => watchInstalling(registration));
102
145
  if (pollIntervalMs > 0) {
103
146
  pollId = setInterval(() => {
147
+ check();
104
148
  registration.update().catch(() => {
105
- });
149
+ }).then(check, check);
106
150
  }, pollIntervalMs);
107
151
  }
108
152
  wireFocusChecks(registration);
@@ -114,6 +158,11 @@ function createPwaUpdater(options = {}) {
114
158
  applyUpdate() {
115
159
  if (waitingWorker) waitingWorker.postMessage(SKIP_WAITING_MESSAGE);
116
160
  },
161
+ snooze() {
162
+ writeSnooze(Date.now() + snoozeMs);
163
+ check();
164
+ },
165
+ check,
117
166
  destroy() {
118
167
  destroyed = true;
119
168
  if (pollId !== null) clearInterval(pollId);
@@ -127,5 +176,6 @@ function createPwaUpdater(options = {}) {
127
176
  exports.SKIP_WAITING = SKIP_WAITING;
128
177
  exports.SKIP_WAITING_MESSAGE = SKIP_WAITING_MESSAGE;
129
178
  exports.createPwaUpdater = createPwaUpdater;
179
+ exports.shouldOfferUpdate = shouldOfferUpdate;
130
180
  //# sourceMappingURL=index.cjs.map
131
181
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/message.ts","../src/index.ts"],"names":[],"mappings":";;;AAKO,IAAM,YAAA,GAAe;AAErB,IAAM,oBAAA,GAAuB,EAAE,IAAA,EAAM,YAAA;;;ACyC5C,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,GAAs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AAM,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","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"]}
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;;;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,MAAM,SAAA,uBAAgB,GAAA,EAAsC;AAC5D,EAAA,IAAI,WAAA,GAAc,KAAA;AAClB,EAAA,IAAI,aAAA,GAAsC,IAAA;AAE1C,EAAA,MAAM,QAAA,GAAW,OAAwB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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"]}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,57 @@
1
1
  export { S as SKIP_WAITING, a as SKIP_WAITING_MESSAGE, b as SkipWaitingMessage } from './message-CBBmtYuB.cjs';
2
2
 
3
+ /**
4
+ * F054.8 — the decision, as a pure function.
5
+ *
6
+ * Split out so it can be proven with NO service worker, NO DOM and no fake
7
+ * container: every branch is reachable from three plain values. The rest of the
8
+ * updater is plumbing around this.
9
+ *
10
+ * Why it is a function and not a flag: the old updater REMEMBERED whether an
11
+ * update was ready instead of READING whether one is waiting, so the answer
12
+ * could only ever be given once.
13
+ */
14
+ interface ShouldOfferInput {
15
+ /** `registration.waiting` — read fresh at the moment of the decision. */
16
+ waiting: unknown;
17
+ /** Epoch ms until which the user has snoozed the offer, or null. */
18
+ snoozedUntil: number | null;
19
+ /** Epoch ms now. Passed in so the function stays pure and testable. */
20
+ now: number;
21
+ }
22
+ /**
23
+ * Should the consumer be offered the update right now?
24
+ *
25
+ * WHY `controller` IS NOT A TERM HERE, though the sketch we were shown had one
26
+ * and the old code checked it on one of its two paths.
27
+ *
28
+ * The old updater answered this question inconsistently: the attach path
29
+ * (`if (registration.waiting)`) offered with no controller check, while the
30
+ * `updatefound` path required `container.controller` to suppress a first
31
+ * install. Same situation, two answers, depending on which path happened to see
32
+ * it. Making them agree is part of this fix — the question is which way.
33
+ *
34
+ * Requiring a controller would be the tighter rule, and it would REMOVE a banner
35
+ * that some consumer sees today: a page that is not yet controlled (no
36
+ * `clientsClaim`, or a hard reload) but has a genuine update waiting. With
37
+ * fd-sundhed live to 16,838 people on the current version, a change in that
38
+ * direction is not one to make on an unverified reading.
39
+ *
40
+ * And the reading in question is this: a worker only enters `waiting` when
41
+ * another worker is already ACTIVE — on a first install there is nothing to wait
42
+ * behind, so it activates directly. If that is right, `registration.waiting`
43
+ * being non-null already implies this is not a first install, and the controller
44
+ * term is redundant rather than protective. **I have not verified that against a
45
+ * real service worker.** So the old, more permissive behaviour stays as the
46
+ * floor, and first-install suppression rides on the same fact rather than on a
47
+ * second guard that could disagree with it.
48
+ *
49
+ * If someone later measures that a first-install worker CAN sit in `waiting`,
50
+ * this is the function to add the term to — and the test to write first is the
51
+ * one that fails today.
52
+ */
53
+ declare function shouldOfferUpdate({ waiting, snoozedUntil, now }: ShouldOfferInput): boolean;
54
+
3
55
  interface PwaUpdaterOptions {
4
56
  /** Service-worker script URL to register. Default `/sw.js`. */
5
57
  swUrl?: string;
@@ -20,6 +72,20 @@ interface PwaUpdaterOptions {
20
72
  updateOnFocus?: boolean;
21
73
  /** Reload the page once the new worker takes control. Default `true`. */
22
74
  reloadOnControllerChange?: boolean;
75
+ /**
76
+ * How long `snooze()` holds the offer down (ms). Default 30 min.
77
+ *
78
+ * F054.8 — "Later" is a SNOOZE, never a mute. The defect this replaced was a
79
+ * banner that got exactly one chance to be seen; a permanent dismiss is that
80
+ * defect made official.
81
+ */
82
+ snoozeMs?: number;
83
+ /**
84
+ * Where a snooze is remembered, so it survives the reload the banner is
85
+ * asking for. Defaults to `localStorage` when available; pass `null` to keep
86
+ * the snooze in memory only.
87
+ */
88
+ snoozeStorage?: Pick<Storage, "getItem" | "setItem" | "removeItem"> | null;
23
89
  /**
24
90
  * Consumer guard. When `true` the updater is an inert no-op (registers
25
91
  * nothing). Pass your own policy, e.g. `disabled: isNativeCapacitor || isDev`
@@ -37,6 +103,13 @@ interface PwaUpdater {
37
103
  getState(): PwaUpdaterState;
38
104
  /** Tell the waiting worker to activate (posts SKIP_WAITING). No-op if none waits. */
39
105
  applyUpdate(): void;
106
+ /**
107
+ * "Later". Holds the offer down for `snoozeMs`, then it comes back on the
108
+ * next tick — this is NOT a mute, and it deliberately cannot be made one.
109
+ */
110
+ snooze(): void;
111
+ /** Re-read `registration.waiting` right now and emit if the answer moved. */
112
+ check(): void;
40
113
  /** Stop polling + remove all listeners. */
41
114
  destroy(): void;
42
115
  }
@@ -52,4 +125,4 @@ interface PwaUpdater {
52
125
  */
53
126
  declare function createPwaUpdater(options?: PwaUpdaterOptions): PwaUpdater;
54
127
 
55
- export { type PwaUpdater, type PwaUpdaterOptions, type PwaUpdaterState, createPwaUpdater };
128
+ export { type PwaUpdater, type PwaUpdaterOptions, type PwaUpdaterState, type ShouldOfferInput, createPwaUpdater, shouldOfferUpdate };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,57 @@
1
1
  export { S as SKIP_WAITING, a as SKIP_WAITING_MESSAGE, b as SkipWaitingMessage } from './message-CBBmtYuB.js';
2
2
 
3
+ /**
4
+ * F054.8 — the decision, as a pure function.
5
+ *
6
+ * Split out so it can be proven with NO service worker, NO DOM and no fake
7
+ * container: every branch is reachable from three plain values. The rest of the
8
+ * updater is plumbing around this.
9
+ *
10
+ * Why it is a function and not a flag: the old updater REMEMBERED whether an
11
+ * update was ready instead of READING whether one is waiting, so the answer
12
+ * could only ever be given once.
13
+ */
14
+ interface ShouldOfferInput {
15
+ /** `registration.waiting` — read fresh at the moment of the decision. */
16
+ waiting: unknown;
17
+ /** Epoch ms until which the user has snoozed the offer, or null. */
18
+ snoozedUntil: number | null;
19
+ /** Epoch ms now. Passed in so the function stays pure and testable. */
20
+ now: number;
21
+ }
22
+ /**
23
+ * Should the consumer be offered the update right now?
24
+ *
25
+ * WHY `controller` IS NOT A TERM HERE, though the sketch we were shown had one
26
+ * and the old code checked it on one of its two paths.
27
+ *
28
+ * The old updater answered this question inconsistently: the attach path
29
+ * (`if (registration.waiting)`) offered with no controller check, while the
30
+ * `updatefound` path required `container.controller` to suppress a first
31
+ * install. Same situation, two answers, depending on which path happened to see
32
+ * it. Making them agree is part of this fix — the question is which way.
33
+ *
34
+ * Requiring a controller would be the tighter rule, and it would REMOVE a banner
35
+ * that some consumer sees today: a page that is not yet controlled (no
36
+ * `clientsClaim`, or a hard reload) but has a genuine update waiting. With
37
+ * fd-sundhed live to 16,838 people on the current version, a change in that
38
+ * direction is not one to make on an unverified reading.
39
+ *
40
+ * And the reading in question is this: a worker only enters `waiting` when
41
+ * another worker is already ACTIVE — on a first install there is nothing to wait
42
+ * behind, so it activates directly. If that is right, `registration.waiting`
43
+ * being non-null already implies this is not a first install, and the controller
44
+ * term is redundant rather than protective. **I have not verified that against a
45
+ * real service worker.** So the old, more permissive behaviour stays as the
46
+ * floor, and first-install suppression rides on the same fact rather than on a
47
+ * second guard that could disagree with it.
48
+ *
49
+ * If someone later measures that a first-install worker CAN sit in `waiting`,
50
+ * this is the function to add the term to — and the test to write first is the
51
+ * one that fails today.
52
+ */
53
+ declare function shouldOfferUpdate({ waiting, snoozedUntil, now }: ShouldOfferInput): boolean;
54
+
3
55
  interface PwaUpdaterOptions {
4
56
  /** Service-worker script URL to register. Default `/sw.js`. */
5
57
  swUrl?: string;
@@ -20,6 +72,20 @@ interface PwaUpdaterOptions {
20
72
  updateOnFocus?: boolean;
21
73
  /** Reload the page once the new worker takes control. Default `true`. */
22
74
  reloadOnControllerChange?: boolean;
75
+ /**
76
+ * How long `snooze()` holds the offer down (ms). Default 30 min.
77
+ *
78
+ * F054.8 — "Later" is a SNOOZE, never a mute. The defect this replaced was a
79
+ * banner that got exactly one chance to be seen; a permanent dismiss is that
80
+ * defect made official.
81
+ */
82
+ snoozeMs?: number;
83
+ /**
84
+ * Where a snooze is remembered, so it survives the reload the banner is
85
+ * asking for. Defaults to `localStorage` when available; pass `null` to keep
86
+ * the snooze in memory only.
87
+ */
88
+ snoozeStorage?: Pick<Storage, "getItem" | "setItem" | "removeItem"> | null;
23
89
  /**
24
90
  * Consumer guard. When `true` the updater is an inert no-op (registers
25
91
  * nothing). Pass your own policy, e.g. `disabled: isNativeCapacitor || isDev`
@@ -37,6 +103,13 @@ interface PwaUpdater {
37
103
  getState(): PwaUpdaterState;
38
104
  /** Tell the waiting worker to activate (posts SKIP_WAITING). No-op if none waits. */
39
105
  applyUpdate(): void;
106
+ /**
107
+ * "Later". Holds the offer down for `snoozeMs`, then it comes back on the
108
+ * next tick — this is NOT a mute, and it deliberately cannot be made one.
109
+ */
110
+ snooze(): void;
111
+ /** Re-read `registration.waiting` right now and emit if the answer moved. */
112
+ check(): void;
40
113
  /** Stop polling + remove all listeners. */
41
114
  destroy(): void;
42
115
  }
@@ -52,4 +125,4 @@ interface PwaUpdater {
52
125
  */
53
126
  declare function createPwaUpdater(options?: PwaUpdaterOptions): PwaUpdater;
54
127
 
55
- export { type PwaUpdater, type PwaUpdaterOptions, type PwaUpdaterState, createPwaUpdater };
128
+ export { type PwaUpdater, type PwaUpdaterOptions, type PwaUpdaterState, type ShouldOfferInput, createPwaUpdater, shouldOfferUpdate };
package/dist/index.js CHANGED
@@ -1,8 +1,17 @@
1
1
  import { SKIP_WAITING_MESSAGE } from './chunk-ERNF6MZL.js';
2
2
  export { SKIP_WAITING, SKIP_WAITING_MESSAGE } from './chunk-ERNF6MZL.js';
3
3
 
4
+ // src/should-offer.ts
5
+ function shouldOfferUpdate({ waiting, snoozedUntil, now }) {
6
+ if (!waiting) return false;
7
+ if (snoozedUntil !== null && snoozedUntil > now) return false;
8
+ return true;
9
+ }
10
+
4
11
  // src/index.ts
5
12
  var DEFAULT_POLL_MS = 60 * 60 * 1e3;
13
+ var DEFAULT_SNOOZE_MS = 30 * 60 * 1e3;
14
+ var SNOOZE_KEY = "broberg-pwa:snoozed-until";
6
15
  function createPwaUpdater(options = {}) {
7
16
  const {
8
17
  swUrl = "/sw.js",
@@ -10,6 +19,7 @@ function createPwaUpdater(options = {}) {
10
19
  pollIntervalMs = DEFAULT_POLL_MS,
11
20
  updateOnFocus = true,
12
21
  reloadOnControllerChange = true,
22
+ snoozeMs = DEFAULT_SNOOZE_MS,
13
23
  disabled = false
14
24
  } = options;
15
25
  const listeners = /* @__PURE__ */ new Set();
@@ -31,6 +41,10 @@ function createPwaUpdater(options = {}) {
31
41
  getState,
32
42
  applyUpdate() {
33
43
  },
44
+ snooze() {
45
+ },
46
+ check() {
47
+ },
34
48
  destroy() {
35
49
  listeners.clear();
36
50
  }
@@ -41,10 +55,39 @@ function createPwaUpdater(options = {}) {
41
55
  let removeFocusListeners = null;
42
56
  let reloading = false;
43
57
  let destroyed = false;
44
- const markReady = (worker) => {
45
- waitingWorker = worker;
46
- if (!updateReady) {
47
- updateReady = true;
58
+ let registrationRef = null;
59
+ const storage = options.snoozeStorage !== void 0 ? options.snoozeStorage : typeof localStorage !== "undefined" ? localStorage : null;
60
+ let snoozedUntil = null;
61
+ const readSnooze = () => {
62
+ if (!storage) return snoozedUntil;
63
+ try {
64
+ const raw = storage.getItem(SNOOZE_KEY);
65
+ if (!raw) return null;
66
+ const n = Number(raw);
67
+ return Number.isFinite(n) ? n : null;
68
+ } catch {
69
+ return snoozedUntil;
70
+ }
71
+ };
72
+ const writeSnooze = (until) => {
73
+ snoozedUntil = until;
74
+ if (!storage) return;
75
+ try {
76
+ if (until === null) storage.removeItem(SNOOZE_KEY);
77
+ else storage.setItem(SNOOZE_KEY, String(until));
78
+ } catch {
79
+ }
80
+ };
81
+ const check = () => {
82
+ const waiting = registrationRef?.waiting ?? null;
83
+ waitingWorker = waiting;
84
+ const next = shouldOfferUpdate({
85
+ waiting,
86
+ snoozedUntil: readSnooze(),
87
+ now: Date.now()
88
+ });
89
+ if (next !== updateReady) {
90
+ updateReady = next;
48
91
  emit();
49
92
  }
50
93
  };
@@ -63,21 +106,20 @@ function createPwaUpdater(options = {}) {
63
106
  const installing = registration.installing;
64
107
  if (!installing) return;
65
108
  installing.addEventListener("statechange", () => {
66
- if (installing.state === "installed" && container.controller) {
67
- markReady(installing);
68
- }
109
+ if (installing.state === "installed") check();
69
110
  });
70
111
  };
71
112
  const wireFocusChecks = (registration) => {
72
113
  if (!updateOnFocus) return;
73
- const check = () => {
114
+ const tick = () => {
115
+ check();
74
116
  registration.update().catch(() => {
75
- });
117
+ }).then(check, check);
76
118
  };
77
- const onFocus = () => check();
119
+ const onFocus = () => tick();
78
120
  const onVisibility = () => {
79
121
  if (typeof document !== "undefined" && document.visibilityState === "visible") {
80
- check();
122
+ tick();
81
123
  }
82
124
  };
83
125
  if (typeof window !== "undefined") window.addEventListener("focus", onFocus);
@@ -94,12 +136,14 @@ function createPwaUpdater(options = {}) {
94
136
  const registrationPromise = register ? container.register(swUrl) : container.ready;
95
137
  registrationPromise.then((registration) => {
96
138
  if (destroyed) return;
97
- if (registration.waiting) markReady(registration.waiting);
139
+ registrationRef = registration;
140
+ check();
98
141
  registration.addEventListener("updatefound", () => watchInstalling(registration));
99
142
  if (pollIntervalMs > 0) {
100
143
  pollId = setInterval(() => {
144
+ check();
101
145
  registration.update().catch(() => {
102
- });
146
+ }).then(check, check);
103
147
  }, pollIntervalMs);
104
148
  }
105
149
  wireFocusChecks(registration);
@@ -111,6 +155,11 @@ function createPwaUpdater(options = {}) {
111
155
  applyUpdate() {
112
156
  if (waitingWorker) waitingWorker.postMessage(SKIP_WAITING_MESSAGE);
113
157
  },
158
+ snooze() {
159
+ writeSnooze(Date.now() + snoozeMs);
160
+ check();
161
+ },
162
+ check,
114
163
  destroy() {
115
164
  destroyed = true;
116
165
  if (pollId !== null) clearInterval(pollId);
@@ -121,6 +170,6 @@ function createPwaUpdater(options = {}) {
121
170
  };
122
171
  }
123
172
 
124
- export { createPwaUpdater };
173
+ export { createPwaUpdater, shouldOfferUpdate };
125
174
  //# sourceMappingURL=index.js.map
126
175
  //# sourceMappingURL=index.js.map