@devopsplaybook.io/common-web 0.15.0 → 0.16.0-beta.27.13832c8

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/CHANGELOG.md CHANGED
@@ -5,6 +5,40 @@ All notable changes to this project are documented here.
5
5
  This project follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
6
6
  and [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.16.0] - 2026-11-25
9
+
10
+ ### Added
11
+
12
+ - A shared, opt-in PWA app-update toolkit. Detection and prompting are shared;
13
+ each application keeps its own service worker and caching strategy, and the
14
+ toolkit never assumes a particular caching implementation.
15
+ - `BuildVersionProbe`: dependency-free `parseBuildManifest` / `parseShellBuildId`
16
+ parsers and `createBuildVersionProbe()`, which reads
17
+ `/_nuxt/builds/latest.json` (`cache: "no-store"`, abort timeout) and falls
18
+ back to `/index.html` only when the manifest is unavailable.
19
+ - `AppUpdateService`: framework-agnostic scheduler with a single in-flight
20
+ request, a hidden-tab pause, a 5 minute default interval, per-build dismissal
21
+ and an availability callback.
22
+ - `useAppUpdate()`: SSR-safe Vue wrapper that checks on load, tab-visible,
23
+ `online` and `focus`, pauses while hidden, and reloads exactly once after
24
+ awaiting a `beforeReload` hook (throwing from it vetoes the reload).
25
+ - `AppUpdateNotice`: presentational prompt driven only by props/events, so it
26
+ also works with `@vite-pwa/nuxt`'s `$pwa.needRefresh`. Keeps a polite
27
+ `role="status"` live region mounted at all times, is keyboard operable, uses
28
+ token CSS variables with fallbacks, and exposes stable `data-testid`s.
29
+ - `acceptServiceWorkerUpdate()`: posts `SKIP_WAITING`, waits for
30
+ `controllerchange`, then reloads exactly once, with a timeout fallback.
31
+ - `docs/pwa-playbook.md`: the portfolio standard — caching matrix, service-worker
32
+ strategy selection, update lifecycle, user-work protection, three copy-paste
33
+ integration recipes and testing guidance.
34
+ - README "App update notice" section and the new toolkit plus Vitest, SSR and
35
+ accessibility coverage.
36
+
37
+ ### Changed
38
+
39
+ - The published file set now includes `docs/`.
40
+ - No runtime dependency was added and no existing public API changed.
41
+
8
42
  ## [0.15.0] - 2026-11-25
9
43
 
10
44
  ### Added
package/README.md CHANGED
@@ -29,6 +29,7 @@ required. The `playground/` directory demonstrates a consuming app.
29
29
  | `<AlertMessages />` | Accessible live regions displaying messages emitted on `EventBus`, each with a per-message **Dismiss** button. |
30
30
  | `<AppNavigation :links="links" :link-component="NuxtLink" label="Primary" />` | Navigation shell with a named `brand` slot, configurable links (`label`, `to`, optional `icon` and `active`) and an optional accessible `label`. |
31
31
  | `<OfflineBanner message="You are offline." />` | Announces offline status and accepts replacement content through its default slot. |
32
+ | `<AppUpdateNotice :visible="updateAvailable" @reload="reload" @later="dismiss" />` | Accessible "new version available" prompt with **Reload**/**Later** buttons. Its polite `role="status"` live region stays mounted at all times; it is purely prop/emit driven, so it also works when driven by `@vite-pwa/nuxt`'s `$pwa.needRefresh`. |
32
33
  | `<LoginCodeInput v-model="code" :error="error" />` | Eight-character code entry: uppercases, strips spaces and hyphens, supports paste and Enter-to-submit, and exposes an accessible name that spells the code. |
33
34
  | `<LoginWithCodeCard :service="service" @approved="…" @use-password="…" @cancel="…" />` | Device-side flow: creates the request, shows and counts down the code, polls, and reports the redeemed session. |
34
35
  | `<AuthorizeDeviceCard :service="service" @approved="…" @cancel="…" />` | Approver-side flow: previews the requesting device and approves the code, with an optional password step-up. |
@@ -122,6 +123,18 @@ connectivity right after hydration. The default copy is the neutral
122
123
  `navigator.onLine` after mount and follows the `online`/`offline` events, so a
123
124
  page loaded offline shows the offline banner right after hydration without a
124
125
  hydration mismatch.
126
+ - `useAppUpdate({ currentBuildId, fetchLatestBuildId, intervalMs?, beforeReload?, reload?, autoStart? })`
127
+ is the shared PWA update wrapper. It returns reactive `updateAvailable`,
128
+ `dismissed` and `latestBuildId` refs plus the `checkNow`, `start`, `stop`,
129
+ `reload` and `dismiss` actions. It checks on mount, on tab-visible, on
130
+ `online` and on `focus`, and every `intervalMs` (default 5 minutes) while the
131
+ tab is visible; `reload()` awaits `beforeReload()` first (throwing from it
132
+ vetoes the reload) and reloads exactly once. See "App update notice" below.
133
+ - The update toolkit is also available as framework-agnostic services through
134
+ package deep imports: `BuildVersionProbe` (manifest probe with an
135
+ `/index.html` fallback), `AppUpdateService` (the scheduler behind the
136
+ composable) and `ServiceWorkerUpdate` (`acceptServiceWorkerUpdate`, which
137
+ posts `SKIP_WAITING`, waits for `controllerchange` and reloads once).
125
138
  - Services are available through package deep imports, for example
126
139
  `@devopsplaybook.io/common-web/services/AuthService`. `AuthService`,
127
140
  `PreferencesService` and `RefreshIntervalService` guard every `localStorage`
@@ -201,6 +214,65 @@ The session model of each application (validity, absolute cap, renewal
201
214
  mechanism) is documented in the
202
215
  [common-utils auth session policy](https://github.com/devopsplaybook-io/common-utils/blob/main/docs/auth-session-policy.md).
203
216
 
217
+ ## App update notice
218
+
219
+ The layer ships an opt-in, service-worker-agnostic toolkit for telling the user
220
+ a new version is available and reloading safely. It detects changes through
221
+ Nuxt's `/_nuxt/builds/latest.json` manifest (with an `/index.html` fallback),
222
+ checks on load, tab-visible, `online` and `focus` plus a 5 minute interval (no
223
+ polling in hidden tabs), shows an accessible prompt, and can activate a waiting
224
+ service worker. Each application keeps its own service worker and caching: the
225
+ toolkit assumes none.
226
+
227
+ - `createBuildVersionProbe()` from
228
+ `@devopsplaybook.io/common-web/services/BuildVersionProbe` resolves the latest
229
+ build id. Pass `manifestUrl`/`fallbackShellUrl` when an app customizes
230
+ `baseURL` or `buildAssetsDir`.
231
+ - `useAppUpdate()` schedules the checks and exposes the prompt state;
232
+ `AppUpdateNotice` renders it and is driven only by props and events.
233
+ - `acceptServiceWorkerUpdate()` (from
234
+ `@devopsplaybook.io/common-web/services/ServiceWorkerUpdate`) activates a
235
+ waiting worker and reloads exactly once.
236
+
237
+ ```vue
238
+ <script setup lang="ts">
239
+ import { createBuildVersionProbe } from "@devopsplaybook.io/common-web/services/BuildVersionProbe";
240
+
241
+ const config = useRuntimeConfig();
242
+ const { updateAvailable, reload, dismiss } = useAppUpdate({
243
+ currentBuildId: String(config.app.buildId ?? ""),
244
+ fetchLatestBuildId: createBuildVersionProbe(),
245
+ });
246
+ </script>
247
+
248
+ <template>
249
+ <AppUpdateNotice :visible="updateAvailable" @reload="reload" @later="dismiss" />
250
+ </template>
251
+ ```
252
+
253
+ Consumption has two modes:
254
+
255
+ - **Nuxt layer host.** `useAppUpdate` and `<AppUpdateNotice>` are auto-imported;
256
+ import the services from their deep paths as above.
257
+ - **Non-layer host** (plain Vue/Vite, or an app that does not extend the layer,
258
+ like Planner). Import the composable, component and services explicitly and
259
+ transpile the package with `build.transpile` /
260
+ `optimizeDeps.exclude` as shown in "Theming and non-layer hosts":
261
+
262
+ ```ts
263
+ import AppUpdateNotice from "@devopsplaybook.io/common-web/components/AppUpdateNotice.vue";
264
+ import { useAppUpdate } from "@devopsplaybook.io/common-web/composables/useAppUpdate";
265
+ import { createBuildVersionProbe } from "@devopsplaybook.io/common-web/services/BuildVersionProbe";
266
+ ```
267
+
268
+ The portfolio standard — caching matrix, service-worker strategy selection, the
269
+ update lifecycle, user-work protection and copy-paste integration recipes — is
270
+ in [`docs/pwa-playbook.md`](docs/pwa-playbook.md):
271
+
272
+ - (a) [custom service worker or no service worker](docs/pwa-playbook.md#a-custom-service-worker-or-no-service-worker);
273
+ - (b) [custom service worker with a waiting worker](docs/pwa-playbook.md#b-custom-service-worker-with-a-waiting-worker);
274
+ - (c) [`@vite-pwa/nuxt` with `registerType: "prompt"`](docs/pwa-playbook.md#c-vite-pwanuxt-with-registertype-prompt).
275
+
204
276
  ## Login with code
205
277
 
206
278
  The layer ships a client for the cross-device "login with a code" protocol of
@@ -664,6 +736,10 @@ composables guard their browser-only access.
664
736
  offline page shows the banner right after hydration instead of in server
665
737
  HTML.
666
738
  - `useAppHeight()` touches `window` only inside `onMounted`.
739
+ - `useAppUpdate()` registers its listeners and starts polling only in
740
+ `onMounted`; the server renders `updateAvailable: false` and schedules no
741
+ timers. `BuildVersionProbe` and `acceptServiceWorkerUpdate` guard their
742
+ browser access, so they are safe to import on the server.
667
743
  - `useLoginCode()` loads capabilities and starts polling only in `onMounted`, so
668
744
  the server renders `idle` (the card shows `Preparing a code…`); `LoginCodeService`
669
745
  touches no browser global and is safe to call from a server context.
@@ -0,0 +1,110 @@
1
+ <template>
2
+ <div
3
+ class="app-update-notice"
4
+ :class="{ 'app-update-notice-hidden': !visible }"
5
+ role="status"
6
+ aria-live="polite"
7
+ aria-atomic="true"
8
+ data-testid="app-update-notice"
9
+ >
10
+ <template v-if="visible">
11
+ <p class="app-update-notice-message" data-testid="app-update-message">
12
+ {{ message }}
13
+ </p>
14
+ <div class="app-update-notice-actions">
15
+ <button
16
+ type="button"
17
+ class="app-update-notice-button app-update-notice-reload"
18
+ data-testid="app-update-reload"
19
+ @click="emit('reload')"
20
+ >
21
+ {{ reloadLabel }}
22
+ </button>
23
+ <button
24
+ type="button"
25
+ class="app-update-notice-button app-update-notice-later"
26
+ data-testid="app-update-later"
27
+ @click="emit('later')"
28
+ >
29
+ {{ laterLabel }}
30
+ </button>
31
+ </div>
32
+ </template>
33
+ </div>
34
+ </template>
35
+
36
+ <script setup lang="ts">
37
+ withDefaults(
38
+ defineProps<{
39
+ visible?: boolean;
40
+ message?: string;
41
+ reloadLabel?: string;
42
+ laterLabel?: string;
43
+ }>(),
44
+ {
45
+ visible: false,
46
+ message: "New version available.",
47
+ reloadLabel: "Reload",
48
+ laterLabel: "Later",
49
+ },
50
+ );
51
+
52
+ const emit = defineEmits<{ reload: []; later: [] }>();
53
+ </script>
54
+
55
+ <style>
56
+ .app-update-notice {
57
+ display: flex;
58
+ flex-wrap: wrap;
59
+ align-items: center;
60
+ justify-content: space-between;
61
+ gap: var(--space-sm, 0.5rem);
62
+ padding: var(--space-sm, 0.5rem) var(--space-base, 1rem);
63
+ color: var(--color-text, #171717);
64
+ background: var(--color-surface-raised, #f5f5f5);
65
+ border-top: 1px solid var(--color-border, #d6d6d6);
66
+ font-size: var(--text-sm, 0.875rem);
67
+ }
68
+
69
+ .app-update-notice-message {
70
+ margin: 0;
71
+ }
72
+
73
+ .app-update-notice-actions {
74
+ display: flex;
75
+ gap: var(--space-sm, 0.5rem);
76
+ }
77
+
78
+ .app-update-notice-button {
79
+ font: inherit;
80
+ padding: var(--space-xs, 0.25rem) var(--space-sm, 0.5rem);
81
+ color: inherit;
82
+ background: transparent;
83
+ border: 1px solid var(--color-border, #d6d6d6);
84
+ border-radius: var(--radius-sm, 0.25rem);
85
+ cursor: pointer;
86
+ }
87
+
88
+ .app-update-notice-reload {
89
+ color: var(--color-on-primary, #fff);
90
+ background: var(--color-primary, #c62828);
91
+ border-color: var(--color-primary, #c62828);
92
+ }
93
+
94
+ .app-update-notice-button:focus-visible {
95
+ outline: 2px solid var(--color-primary, #c62828);
96
+ outline-offset: 2px;
97
+ }
98
+
99
+ .app-update-notice-hidden {
100
+ position: absolute;
101
+ width: 1px;
102
+ height: 1px;
103
+ padding: 0;
104
+ margin: -1px;
105
+ overflow: hidden;
106
+ clip: rect(0, 0, 0, 0);
107
+ white-space: nowrap;
108
+ border-width: 0;
109
+ }
110
+ </style>
@@ -0,0 +1,133 @@
1
+ import { onMounted, onUnmounted, ref, type Ref } from "vue";
2
+ import { AppUpdateService } from "../services/AppUpdateService";
3
+
4
+ export interface UseAppUpdateOptions {
5
+ currentBuildId?: string | null;
6
+ fetchLatestBuildId: () => Promise<string | null>;
7
+ intervalMs?: number;
8
+ /** Start polling on mount; defaults to `true`. */
9
+ autoStart?: boolean;
10
+ /** Runs before a reload; rejecting it vetoes the reload. */
11
+ beforeReload?: () => void | Promise<void>;
12
+ /** Defaults to `window.location.reload()`. */
13
+ reload?: () => void;
14
+ }
15
+
16
+ export interface UseAppUpdate {
17
+ updateAvailable: Ref<boolean>;
18
+ dismissed: Ref<boolean>;
19
+ latestBuildId: Ref<string | null>;
20
+ checkNow: () => Promise<void>;
21
+ start: () => () => void;
22
+ stop: () => void;
23
+ reload: () => Promise<void>;
24
+ dismiss: () => void;
25
+ }
26
+
27
+ /**
28
+ * Vue wrapper around {@link AppUpdateService}. Browser APIs are touched only
29
+ * after mount, so the composable is safe to call during SSR.
30
+ */
31
+ export function useAppUpdate(options: UseAppUpdateOptions): UseAppUpdate {
32
+ const updateAvailable = ref(false);
33
+ const dismissed = ref(false);
34
+ const latestBuildId = ref<string | null>(null);
35
+
36
+ const service = new AppUpdateService({
37
+ currentBuildId: options.currentBuildId,
38
+ fetchLatestBuildId: options.fetchLatestBuildId,
39
+ intervalMs: options.intervalMs,
40
+ onUpdateAvailable: (latest) => {
41
+ updateAvailable.value = true;
42
+ latestBuildId.value = latest;
43
+ dismissed.value = false;
44
+ },
45
+ });
46
+
47
+ let stopFn: (() => void) | null = null;
48
+ let reloadPromise: Promise<void> | null = null;
49
+
50
+ function syncFromService(): void {
51
+ updateAvailable.value = service.updateAvailable;
52
+ latestBuildId.value = service.latestBuildId;
53
+ }
54
+
55
+ async function checkNow(): Promise<void> {
56
+ await service.checkNow();
57
+ syncFromService();
58
+ }
59
+
60
+ function start(): () => void {
61
+ stopFn = service.start();
62
+ return stopFn;
63
+ }
64
+
65
+ function stop(): void {
66
+ const fn = stopFn;
67
+ stopFn = null;
68
+ fn?.();
69
+ updateAvailable.value = false;
70
+ dismissed.value = false;
71
+ latestBuildId.value = null;
72
+ }
73
+
74
+ function dismiss(): void {
75
+ service.dismiss();
76
+ updateAvailable.value = false;
77
+ dismissed.value = true;
78
+ }
79
+
80
+ function reload(): Promise<void> {
81
+ if (typeof window === "undefined") return Promise.resolve();
82
+ if (reloadPromise) return reloadPromise;
83
+
84
+ const reloadImpl =
85
+ options.reload ??
86
+ ((): void => {
87
+ if (typeof window !== "undefined") window.location.reload();
88
+ });
89
+
90
+ reloadPromise = (async () => {
91
+ try {
92
+ await options.beforeReload?.();
93
+ } catch {
94
+ return;
95
+ }
96
+ reloadImpl();
97
+ })();
98
+ return reloadPromise;
99
+ }
100
+
101
+ function onVisibilityChange(): void {
102
+ if (document.visibilityState === "visible") void checkNow();
103
+ }
104
+
105
+ function onOnlineOrFocus(): void {
106
+ void checkNow();
107
+ }
108
+
109
+ onMounted(() => {
110
+ document.addEventListener("visibilitychange", onVisibilityChange);
111
+ window.addEventListener("online", onOnlineOrFocus);
112
+ window.addEventListener("focus", onOnlineOrFocus);
113
+ if (options.autoStart !== false) start();
114
+ });
115
+
116
+ onUnmounted(() => {
117
+ document.removeEventListener("visibilitychange", onVisibilityChange);
118
+ window.removeEventListener("online", onOnlineOrFocus);
119
+ window.removeEventListener("focus", onOnlineOrFocus);
120
+ stop();
121
+ });
122
+
123
+ return {
124
+ updateAvailable,
125
+ dismissed,
126
+ latestBuildId,
127
+ checkNow,
128
+ start,
129
+ stop,
130
+ reload,
131
+ dismiss,
132
+ };
133
+ }
@@ -0,0 +1,372 @@
1
+ # PWA app-update playbook
2
+
3
+ The portfolio standard for detecting a new deployment and prompting the user
4
+ to update, shared by every `@devopsplaybook.io/common-web` `^0.16.0`
5
+ application.
6
+
7
+ ## Purpose and scope
8
+
9
+ Update **detection and prompting** is shared. Each application keeps its own
10
+ service worker and caching strategy: the toolkit is service-worker-agnostic and
11
+ never assumes a particular caching implementation.
12
+
13
+ - Adoption is **opt-in**. Nothing in the package auto-registers a plugin, polls
14
+ on import, or touches a service worker.
15
+ - The shared pieces are `BuildVersionProbe` (detection), `AppUpdateService`
16
+ (scheduling), `useAppUpdate` (Vue wrapper), `AppUpdateNotice` (accessible
17
+ prompt) and `acceptServiceWorkerUpdate` (activation helper).
18
+ - A prompt is the **default**. Silent `autoUpdate` reloads can discard form
19
+ input and are painful to reverse.
20
+
21
+ Detection prefers the framework signal: Nuxt 4 publishes
22
+ `/_nuxt/builds/latest.json` (`{ "id": "<buildId>" }`). Fall back to scraping
23
+ `/index.html` only when the manifest is unavailable.
24
+
25
+ ## Caching matrix
26
+
27
+ HTTP caching is what makes an update detectable immediately: the shell and the
28
+ build manifest must never be served stale, while hashed assets can be cached
29
+ forever.
30
+
31
+ | Path | Header | Notes |
32
+ | --- | --- | --- |
33
+ | `/_nuxt/*` (content-hashed) | `public, max-age=31536000, immutable` | Safe to cache forever: the filename changes per build. **Except** `/_nuxt/builds/*`. |
34
+ | `/_nuxt/builds/*` | `no-cache` | The update signal. Must revalidate on every request. |
35
+ | `/sw.js` | `no-cache` | Browsers bypass the HTTP cache for the SW script by default; be explicit anyway. |
36
+ | `/index.html` | `no-cache` | The shell must point at the current hashed assets. |
37
+ | API (`/api/*`) | `no-store` for auth and mutating responses | Never cache per-user data in the HTTP cache. |
38
+
39
+ A Nitro `routeRules` example (most specific first; Nitro matches the most
40
+ specific rule, the order here is for readability):
41
+
42
+ ```ts
43
+ // nuxt.config.ts
44
+ export default defineNuxtConfig({
45
+ routeRules: {
46
+ "/_nuxt/builds/**": { headers: { "cache-control": "no-cache" } },
47
+ "/sw.js": { headers: { "cache-control": "no-cache" } },
48
+ "/index.html": { headers: { "cache-control": "no-cache" } },
49
+ "/_nuxt/**": {
50
+ headers: { "cache-control": "public, max-age=31536000, immutable" },
51
+ },
52
+ "/api/**": { headers: { "cache-control": "no-store" } },
53
+ },
54
+ });
55
+ ```
56
+
57
+ ### Service-worker caching rules
58
+
59
+ - **Keep `/_nuxt/builds/*` out of every service-worker cache.** A cached
60
+ manifest can never report a new build. Use a network passthrough:
61
+
62
+ ```ts
63
+ // @vite-pwa/nuxt
64
+ pwa: {
65
+ workbox: {
66
+ globIgnores: ["**/_nuxt/builds/**"],
67
+ navigateFallbackDenylist: [/\/_nuxt\/builds\//],
68
+ runtimeCaching: [
69
+ { urlPattern: /\/_nuxt\/builds\//, handler: "NetworkOnly" },
70
+ ],
71
+ },
72
+ },
73
+ ```
74
+
75
+ - **Runtime caching for GETs only.** Use `NetworkFirst` for data that must be
76
+ fresh and `StaleWhileRevalidate` for non-critical reads. Never cache
77
+ mutating responses.
78
+
79
+ - **Partition per-user caches and clear them on logout or user switch.** Use a
80
+ per-user cache name such as `<app>-data-<userId>` and delete the private
81
+ caches when the session changes; never delete the precache:
82
+
83
+ ```ts
84
+ import {
85
+ EventBus,
86
+ EventTypes,
87
+ } from "@devopsplaybook.io/common-web/composables/EventBus";
88
+
89
+ const PRIVATE_CACHE_PREFIX = "my-app-data-";
90
+
91
+ EventBus.on(EventTypes.AUTH_UPDATED, async () => {
92
+ if (typeof caches === "undefined") return;
93
+ const names = await caches.keys();
94
+ await Promise.all(
95
+ names
96
+ .filter((name) => name.startsWith(PRIVATE_CACHE_PREFIX))
97
+ .map((name) => caches.delete(name)),
98
+ );
99
+ });
100
+ ```
101
+
102
+ `AUTH_UPDATED` fires on sign-in, sign-out and token refresh, so the filter
103
+ (not the event name) is what scopes this to private data caches.
104
+
105
+ ## Service-worker strategy selection
106
+
107
+ | Strategy | Use when | Apps |
108
+ | --- | --- | --- |
109
+ | Custom service worker | The app needs media, HTTP range requests or storage quotas. | `book-reader`, `chinesetextreader`, `feedwatcher` — keep them. |
110
+ | `@vite-pwa/nuxt` `generateSW` | Default for new and simple apps. | Most of the portfolio. |
111
+ | `@vite-pwa/nuxt` `injectManifest` | You need custom logic but still want Workbox precaching. | When `generateSW` is not enough. |
112
+
113
+ **Never migrate an application's service worker as part of adopting the update
114
+ toolkit.** The update PR changes detection and the prompt only; the service
115
+ worker implementation is out of scope.
116
+
117
+ ## Update lifecycle
118
+
119
+ 1. Keep the old service worker controlling until the user accepts. A waiting
120
+ worker stays parked until `SKIP_WAITING`.
121
+ 2. Detect via `/_nuxt/builds/latest.json`, not by scraping HTML.
122
+ 3. Check when the app loads, when the tab becomes visible, when the browser
123
+ comes back `online`, and on `focus`, plus a **5–15 minute interval**. Never
124
+ poll hidden tabs.
125
+ 4. When a new build is detected, call `registration.update()` so the browser
126
+ fetches the new service worker if one changed.
127
+ 5. Register the service worker with `updateViaCache: "none"` so the `sw.js`
128
+ fetch itself is not served from the HTTP cache.
129
+
130
+ `AppUpdateService`, `useAppUpdate` and `BuildVersionProbe` already implement
131
+ steps 2, 3 and 4 (the probe uses `cache: "no-store"` with a timeout and no
132
+ polling of hidden tabs).
133
+
134
+ ## Protecting user work
135
+
136
+ An update prompt must never silently discard what the user is doing.
137
+
138
+ - Preserve the URL and in-app state across the reload (hash routes, selected
139
+ item, scroll position — restore them on mount).
140
+ - **Flush offline queues before reloading.** Pass a `beforeReload` callback: it
141
+ is awaited before the reload, and throwing from it **vetoes** the reload so
142
+ the prompt can stay open.
143
+ - Do not reload when the app is offline and pending work cannot be flushed:
144
+
145
+ ```ts
146
+ const { updateAvailable, reload, dismiss } = useAppUpdate({
147
+ currentBuildId: buildId,
148
+ fetchLatestBuildId: createBuildVersionProbe(),
149
+ beforeReload: async () => {
150
+ if (!navigator.onLine) throw new Error("offline: pending work not flushed");
151
+ await flushOfflineQueue();
152
+ },
153
+ });
154
+ ```
155
+
156
+ ## Integration recipes
157
+
158
+ All three recipes use the same building blocks. Pick the one that matches your
159
+ service worker.
160
+
161
+ ### (a) Custom service worker or no service worker
162
+
163
+ Use the shared probe for detection, `useAppUpdate` for scheduling and
164
+ `AppUpdateNotice` for the prompt. Reloading is a plain reload.
165
+
166
+ ```vue
167
+ <!-- app.vue -->
168
+ <script setup lang="ts">
169
+ import { createBuildVersionProbe } from "@devopsplaybook.io/common-web/services/BuildVersionProbe";
170
+
171
+ // Nuxt layer: `useAppUpdate` and `AppUpdateNotice` are auto-imported.
172
+ // Non-layer hosts: import them from their deep paths instead (see README).
173
+ const config = useRuntimeConfig();
174
+
175
+ const { updateAvailable, reload, dismiss } = useAppUpdate({
176
+ currentBuildId: String(config.app.buildId ?? ""),
177
+ fetchLatestBuildId: createBuildVersionProbe(),
178
+ beforeReload: async () => {
179
+ await flushOfflineQueue();
180
+ },
181
+ });
182
+ </script>
183
+
184
+ <template>
185
+ <AppUpdateNotice
186
+ :visible="updateAvailable"
187
+ @reload="reload"
188
+ @later="dismiss"
189
+ />
190
+ </template>
191
+ ```
192
+
193
+ If the app customizes `baseURL` or `buildAssetsDir`, pass the matching URLs:
194
+ `createBuildVersionProbe({ manifestUrl, fallbackShellUrl })`.
195
+
196
+ ### (b) Custom service worker with a waiting worker
197
+
198
+ Register with `updateViaCache: "none"`, detect the new build with the shared
199
+ probe, and let the helper activate the waiting worker and reload once.
200
+
201
+ ```ts
202
+ // plugins/pwa-update.client.ts
203
+ import { createBuildVersionProbe } from "@devopsplaybook.io/common-web/services/BuildVersionProbe";
204
+ import { acceptServiceWorkerUpdate } from "@devopsplaybook.io/common-web/services/ServiceWorkerUpdate";
205
+
206
+ export default defineNuxtPlugin(async () => {
207
+ if (!("serviceWorker" in navigator)) return;
208
+
209
+ const registration = await navigator.serviceWorker.register("/sw.js", {
210
+ updateViaCache: "none",
211
+ });
212
+ return {
213
+ provide: { pwaRegistration: registration },
214
+ };
215
+ });
216
+ ```
217
+
218
+ ```vue
219
+ <!-- app.vue -->
220
+ <script setup lang="ts">
221
+ import { watch } from "vue";
222
+ import { createBuildVersionProbe } from "@devopsplaybook.io/common-web/services/BuildVersionProbe";
223
+ import { acceptServiceWorkerUpdate } from "@devopsplaybook.io/common-web/services/ServiceWorkerUpdate";
224
+
225
+ const { $pwaRegistration } = useNuxtApp();
226
+ const config = useRuntimeConfig();
227
+
228
+ const { updateAvailable, reload, dismiss } = useAppUpdate({
229
+ currentBuildId: String(config.app.buildId ?? ""),
230
+ fetchLatestBuildId: createBuildVersionProbe(),
231
+ beforeReload: async () => {
232
+ await flushOfflineQueue();
233
+ },
234
+ });
235
+
236
+ // A new build usually ships a new sw.js: ask the browser to fetch it now.
237
+ watch(updateAvailable, (available) => {
238
+ if (available) void $pwaRegistration?.update();
239
+ });
240
+
241
+ async function accept() {
242
+ await acceptServiceWorkerUpdate({
243
+ registration: $pwaRegistration,
244
+ reload: () => void reload(),
245
+ });
246
+ }
247
+ </script>
248
+
249
+ <template>
250
+ <AppUpdateNotice
251
+ :visible="updateAvailable"
252
+ @reload="accept"
253
+ @later="dismiss"
254
+ />
255
+ </template>
256
+ ```
257
+
258
+ `acceptServiceWorkerUpdate` posts `{ type: "SKIP_WAITING" }`, waits for
259
+ `controllerchange`, then reloads exactly once; it falls back to a plain reload
260
+ when there is no waiting worker or after a 10 s timeout.
261
+
262
+ ### (c) `@vite-pwa/nuxt` with `registerType: "prompt"`
263
+
264
+ Keep the PWA plugin in `prompt` mode, never precache `/_nuxt/builds/*`, and
265
+ drive the same banner from the shared probe **or** `$pwa.needRefresh`.
266
+
267
+ ```ts
268
+ // nuxt.config.ts
269
+ export default defineNuxtConfig({
270
+ modules: ["@vite-pwa/nuxt"],
271
+ pwa: {
272
+ registerType: "prompt",
273
+ workbox: {
274
+ globIgnores: ["**/_nuxt/builds/**"],
275
+ navigateFallbackDenylist: [/\/_nuxt\/builds\//],
276
+ runtimeCaching: [
277
+ { urlPattern: /\/_nuxt\/builds\//, handler: "NetworkOnly" },
278
+ ],
279
+ },
280
+ manifest: {
281
+ name: "My app",
282
+ short_name: "App",
283
+ display: "standalone",
284
+ },
285
+ },
286
+ });
287
+ ```
288
+
289
+ ```vue
290
+ <!-- app.vue -->
291
+ <script setup lang="ts">
292
+ import { createBuildVersionProbe } from "@devopsplaybook.io/common-web/services/BuildVersionProbe";
293
+ import { acceptServiceWorkerUpdate } from "@devopsplaybook.io/common-web/services/ServiceWorkerUpdate";
294
+
295
+ const { $pwa } = useNuxtApp();
296
+ const config = useRuntimeConfig();
297
+
298
+ const { updateAvailable, reload, dismiss } = useAppUpdate({
299
+ currentBuildId: String(config.app.buildId ?? ""),
300
+ fetchLatestBuildId: createBuildVersionProbe(),
301
+ beforeReload: async () => {
302
+ await flushOfflineQueue();
303
+ },
304
+ });
305
+
306
+ async function accept() {
307
+ if ($pwa?.updateServiceWorker) {
308
+ // Activate the new worker without letting the plugin reload: the shared
309
+ // reload flushes the offline queue first and reloads exactly once.
310
+ await $pwa.updateServiceWorker(false);
311
+ await reload();
312
+ return;
313
+ }
314
+ await acceptServiceWorkerUpdate({
315
+ registration: $pwa?.getSWRegistration?.() ?? null,
316
+ reload: () => void reload(),
317
+ });
318
+ }
319
+
320
+ function later() {
321
+ $pwa?.cancelPrompt?.();
322
+ dismiss();
323
+ }
324
+ </script>
325
+
326
+ <template>
327
+ <AppUpdateNotice
328
+ :visible="updateAvailable || Boolean($pwa?.needRefresh)"
329
+ @reload="accept"
330
+ @later="later"
331
+ />
332
+ </template>
333
+ ```
334
+
335
+ `updateServiceWorker(true)` would let the plugin reload for you; use it only
336
+ when there is nothing to flush, otherwise the offline queue is skipped.
337
+
338
+ ## Testing
339
+
340
+ - **Vitest with fake timers** for `AppUpdateService` and `useAppUpdate`:
341
+ intervals, hidden-tab pausing, single in-flight requests, dismissal per build
342
+ and the `beforeReload` veto.
343
+ - **Component tests**: render `AppUpdateNotice` visible and hidden, assert the
344
+ always-mounted `role="status"` / `aria-live="polite"` live region, the emitted
345
+ `reload`/`later` events and keyboard operability. Add an SSR render and an
346
+ axe accessibility check.
347
+ - **Playwright** with `serviceWorkers: "block"` and a faked manifest for
348
+ determinism:
349
+
350
+ ```ts
351
+ test.use({ serviceWorkers: "block" });
352
+
353
+ await page.route("**/_nuxt/builds/latest.json", (route) =>
354
+ route.fulfill({ json: { id: "build-2" } }),
355
+ );
356
+ ```
357
+
358
+ Then assert the banner appears, is announced and that **Later** dismisses it.
359
+ - Keep **one service-worker-enabled offline run** per app
360
+ (`context.setOffline(true)`) to prove the offline mode still works after
361
+ switching to a prompt.
362
+
363
+ ## Adoption checklist
364
+
365
+ 1. Bump the dependency to `^0.16.0`.
366
+ 2. Pick the recipe for your service worker (a, b or c).
367
+ 3. If the app uses `registerType: "autoUpdate"`, switch it to `"prompt"`.
368
+ 4. Add the cache headers from the matrix (shell, `sw.js`, `/_nuxt/builds/*`).
369
+ 5. Wire the banner into `app.vue` (or a layout) and mount it once.
370
+ 6. Verify with the Playwright pattern above and keep an offline run.
371
+ 7. **Do not change the service-worker implementation** in the adoption pull
372
+ request.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devopsplaybook.io/common-web",
3
- "version": "0.15.0",
3
+ "version": "0.16.0-beta.27.13832c8",
4
4
  "description": "Shared Nuxt layer for DevOpsPlaybook web applications",
5
5
  "license": "ISC",
6
6
  "repository": {
@@ -32,6 +32,7 @@
32
32
  "composables",
33
33
  "services",
34
34
  "stores",
35
+ "docs",
35
36
  "README.md",
36
37
  "CHANGELOG.md",
37
38
  "CONTRIBUTING.md",
@@ -0,0 +1,126 @@
1
+ export const APP_UPDATE_CHECK_INTERVAL_MS = 5 * 60 * 1000;
2
+
3
+ export interface AppUpdateServiceOptions {
4
+ currentBuildId?: string | null;
5
+ fetchLatestBuildId: () => Promise<string | null>;
6
+ intervalMs?: number;
7
+ isDocumentHidden?: () => boolean;
8
+ onUpdateAvailable?: (latestBuildId: string) => void;
9
+ }
10
+
11
+ function defaultIsDocumentHidden(): boolean {
12
+ return (
13
+ typeof document !== "undefined" && document.visibilityState === "hidden"
14
+ );
15
+ }
16
+
17
+ function sanitizeInterval(intervalMs: number | undefined): number {
18
+ return typeof intervalMs === "number" &&
19
+ Number.isFinite(intervalMs) &&
20
+ intervalMs > 0
21
+ ? intervalMs
22
+ : APP_UPDATE_CHECK_INTERVAL_MS;
23
+ }
24
+
25
+ function isPresent(value: string | null | undefined): value is string {
26
+ return typeof value === "string" && value.trim().length > 0;
27
+ }
28
+
29
+ /**
30
+ * Framework-agnostic build-update checker. It compares the running build id
31
+ * with the latest deployed one on a schedule and exposes a single availability
32
+ * flag. Browser globals are read lazily so the module imports cleanly in Node.
33
+ */
34
+ export class AppUpdateService {
35
+ private readonly currentBuildId: string | null;
36
+ private readonly fetchLatestBuildId: () => Promise<string | null>;
37
+ private readonly intervalMs: number;
38
+ private readonly isDocumentHidden: () => boolean;
39
+ private readonly onUpdateAvailable?: (latestBuildId: string) => void;
40
+
41
+ private available = false;
42
+ private latest: string | null = null;
43
+ private dismissedBuildId: string | null = null;
44
+ private inFlight: Promise<void> | null = null;
45
+ private stopFn: (() => void) | null = null;
46
+
47
+ constructor(options: AppUpdateServiceOptions) {
48
+ this.currentBuildId = options.currentBuildId ?? null;
49
+ this.fetchLatestBuildId = options.fetchLatestBuildId;
50
+ this.intervalMs = sanitizeInterval(options.intervalMs);
51
+ this.isDocumentHidden = options.isDocumentHidden ?? defaultIsDocumentHidden;
52
+ this.onUpdateAvailable = options.onUpdateAvailable;
53
+ }
54
+
55
+ get updateAvailable(): boolean {
56
+ return this.available;
57
+ }
58
+
59
+ get latestBuildId(): string | null {
60
+ return this.latest;
61
+ }
62
+
63
+ checkNow(): Promise<void> {
64
+ if (!isPresent(this.currentBuildId)) return Promise.resolve();
65
+ if (typeof navigator !== "undefined" && navigator.onLine === false) {
66
+ return Promise.resolve();
67
+ }
68
+ if (this.inFlight) return this.inFlight;
69
+
70
+ const promise = this.runCheck().finally(() => {
71
+ if (this.inFlight === promise) this.inFlight = null;
72
+ });
73
+ this.inFlight = promise;
74
+ return promise;
75
+ }
76
+
77
+ start(): () => void {
78
+ if (this.stopFn) return this.stopFn;
79
+
80
+ void this.checkNow();
81
+ const interval = setInterval(() => {
82
+ if (!this.isDocumentHidden()) void this.checkNow();
83
+ }, this.intervalMs);
84
+
85
+ const stop = (): void => {
86
+ if (this.stopFn !== stop) return;
87
+ clearInterval(interval);
88
+ this.stopFn = null;
89
+ this.available = false;
90
+ this.latest = null;
91
+ this.dismissedBuildId = null;
92
+ this.inFlight = null;
93
+ };
94
+ this.stopFn = stop;
95
+ return stop;
96
+ }
97
+
98
+ dismiss(): void {
99
+ this.available = false;
100
+ if (this.latest !== null) this.dismissedBuildId = this.latest;
101
+ }
102
+
103
+ private async runCheck(): Promise<void> {
104
+ let latest: string | null;
105
+ try {
106
+ latest = await this.fetchLatestBuildId();
107
+ } catch {
108
+ return;
109
+ }
110
+ if (!isPresent(latest)) return;
111
+
112
+ this.latest = latest;
113
+ if (latest === this.currentBuildId) {
114
+ this.available = false;
115
+ return;
116
+ }
117
+ if (latest === this.dismissedBuildId) {
118
+ this.available = false;
119
+ return;
120
+ }
121
+ if (!this.available) {
122
+ this.available = true;
123
+ this.onUpdateAvailable?.(latest);
124
+ }
125
+ }
126
+ }
@@ -0,0 +1,95 @@
1
+ export const BUILD_MANIFEST_URL = "/_nuxt/builds/latest.json";
2
+ export const SHELL_FALLBACK_URL = "/index.html";
3
+ export const BUILD_PROBE_TIMEOUT_MS = 10_000;
4
+
5
+ // Matches `buildId:"x"`, `"buildId": "x"` and `'buildId': 'x'`.
6
+ const SHELL_BUILD_ID_PATTERN = /buildId\s*["']?\s*:\s*["']([^"']+)["']/;
7
+
8
+ export interface BuildVersionProbeOptions {
9
+ fetchImpl?: typeof fetch;
10
+ manifestUrl?: string;
11
+ fallbackShellUrl?: string;
12
+ timeoutMs?: number;
13
+ }
14
+
15
+ export function parseBuildManifest(text: string): string | null {
16
+ let parsed: unknown;
17
+ try {
18
+ parsed = JSON.parse(text);
19
+ } catch {
20
+ return null;
21
+ }
22
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
23
+ return null;
24
+ }
25
+ const id = (parsed as { id?: unknown }).id;
26
+ if (typeof id !== "string") return null;
27
+ const trimmed = id.trim();
28
+ return trimmed.length > 0 ? trimmed : null;
29
+ }
30
+
31
+ export function parseShellBuildId(html: string): string | null {
32
+ const match = SHELL_BUILD_ID_PATTERN.exec(html);
33
+ if (!match) return null;
34
+ const id = match[1]?.trim();
35
+ return id && id.length > 0 ? id : null;
36
+ }
37
+
38
+ function sanitizeTimeout(timeoutMs: number | undefined): number {
39
+ return typeof timeoutMs === "number" &&
40
+ Number.isFinite(timeoutMs) &&
41
+ timeoutMs > 0
42
+ ? timeoutMs
43
+ : BUILD_PROBE_TIMEOUT_MS;
44
+ }
45
+
46
+ async function fetchText(
47
+ fetchImpl: (url: string, init?: RequestInit) => Promise<Response>,
48
+ url: string,
49
+ timeoutMs: number,
50
+ ): Promise<string | null> {
51
+ const controller =
52
+ typeof AbortController === "undefined" ? null : new AbortController();
53
+ let timeout: ReturnType<typeof setTimeout> | undefined;
54
+ try {
55
+ if (controller) {
56
+ timeout = setTimeout(() => controller.abort(), timeoutMs);
57
+ }
58
+ const response = await fetchImpl(url, {
59
+ cache: "no-store",
60
+ signal: controller?.signal,
61
+ });
62
+ if (!response.ok) return null;
63
+ return await response.text();
64
+ } catch {
65
+ return null;
66
+ } finally {
67
+ if (timeout !== undefined) clearTimeout(timeout);
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Build a function that resolves the latest deployed build id. It reads the
73
+ * Nuxt build manifest first and falls back to the shell HTML only when the
74
+ * manifest is unavailable. The returned function never rejects.
75
+ */
76
+ export function createBuildVersionProbe(
77
+ options: BuildVersionProbeOptions = {},
78
+ ): () => Promise<string | null> {
79
+ const manifestUrl = options.manifestUrl ?? BUILD_MANIFEST_URL;
80
+ const fallbackShellUrl = options.fallbackShellUrl ?? SHELL_FALLBACK_URL;
81
+ const timeoutMs = sanitizeTimeout(options.timeoutMs);
82
+
83
+ return async (): Promise<string | null> => {
84
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
85
+ if (typeof fetchImpl !== "function") return null;
86
+
87
+ const manifestText = await fetchText(fetchImpl, manifestUrl, timeoutMs);
88
+ const manifestId =
89
+ manifestText === null ? null : parseBuildManifest(manifestText);
90
+ if (manifestId !== null) return manifestId;
91
+
92
+ const shellText = await fetchText(fetchImpl, fallbackShellUrl, timeoutMs);
93
+ return shellText === null ? null : parseShellBuildId(shellText);
94
+ };
95
+ }
@@ -0,0 +1,66 @@
1
+ export const DEFAULT_SKIP_WAITING_MESSAGE = { type: "SKIP_WAITING" } as const;
2
+ export const SW_UPDATE_TIMEOUT_MS = 10_000;
3
+
4
+ export interface AcceptServiceWorkerUpdateOptions {
5
+ registration?: ServiceWorkerRegistration | null;
6
+ message?: unknown;
7
+ reload?: () => void;
8
+ timeoutMs?: number;
9
+ }
10
+
11
+ function sanitizeTimeout(timeoutMs: number | undefined): number {
12
+ return typeof timeoutMs === "number" &&
13
+ Number.isFinite(timeoutMs) &&
14
+ timeoutMs > 0
15
+ ? timeoutMs
16
+ : SW_UPDATE_TIMEOUT_MS;
17
+ }
18
+
19
+ function defaultReload(): void {
20
+ if (typeof window !== "undefined") window.location.reload();
21
+ }
22
+
23
+ /**
24
+ * Activate an installed waiting service worker: post `SKIP_WAITING`, wait for
25
+ * `controllerchange`, then reload. Falls back to a plain reload when there is
26
+ * no waiting worker or after the timeout. Reload happens exactly once.
27
+ */
28
+ export function acceptServiceWorkerUpdate(
29
+ options: AcceptServiceWorkerUpdateOptions = {},
30
+ ): Promise<void> {
31
+ return new Promise<void>((resolve) => {
32
+ const reload = options.reload ?? defaultReload;
33
+ const timeoutMs = sanitizeTimeout(options.timeoutMs);
34
+ const container =
35
+ typeof navigator !== "undefined" ? navigator.serviceWorker : undefined;
36
+ const waiting = options.registration?.waiting ?? null;
37
+
38
+ let done = false;
39
+ let timeout: ReturnType<typeof setTimeout> | undefined;
40
+ const onControllerChange = (): void => finish();
41
+
42
+ function finish(): void {
43
+ if (done) return;
44
+ done = true;
45
+ if (timeout !== undefined) clearTimeout(timeout);
46
+ container?.removeEventListener("controllerchange", onControllerChange);
47
+ reload();
48
+ resolve();
49
+ }
50
+
51
+ if (!container || !waiting) {
52
+ finish();
53
+ return;
54
+ }
55
+
56
+ try {
57
+ container.addEventListener("controllerchange", onControllerChange);
58
+ waiting.postMessage(options.message ?? DEFAULT_SKIP_WAITING_MESSAGE);
59
+ } catch {
60
+ finish();
61
+ return;
62
+ }
63
+
64
+ timeout = setTimeout(finish, timeoutMs);
65
+ });
66
+ }