diff --git a/.github/workflows/sharevb-docker-realease-baseurl-it-tools.yml b/.github/workflows/sharevb-docker-realease-baseurl-it-tools.yml index 188b12d1..c27140c4 100644 --- a/.github/workflows/sharevb-docker-realease-baseurl-it-tools.yml +++ b/.github/workflows/sharevb-docker-realease-baseurl-it-tools.yml @@ -1,5 +1,10 @@ name: Build and Push Docker Image (baseurl-it-tools) +# Kept for the deployments already pulling the `baseurl-it-tools` tag. It is no longer a +# different build: BASE_URL is a runtime setting now, so this image is the same one as +# `latest` with the default moved to /it-tools/, and `latest` with `-e BASE_URL=/it-tools/` +# gets you exactly the same thing. + env: VITE_VERCEL_ENV: production diff --git a/Dockerfile b/Dockerfile index f92e3f67..56cb60dd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -13,8 +13,10 @@ COPY patches patches COPY stubs stubs RUN npm install -g pnpm@11 && pnpm i --ignore-scripts --frozen-lockfile COPY . . -ARG BASE_URL -ENV BASE_URL=${BASE_URL} +# Deliberately no BASE_URL here: the bundle is built path-agnostic (relative asset URLs +# plus a `` in index.html) so that one image can be served from any +# subpath. The path is a runtime setting instead -- see the BASE_URL environment variable +# on the production stage below. ARG VITE_AVAILABLE_LOCALES ENV VITE_AVAILABLE_LOCALES=${VITE_AVAILABLE_LOCALES} ENV VITE_VERCEL_ENV=production @@ -28,8 +30,15 @@ LABEL maintainer="ShareVB " \ LABEL org.opencontainers.image.source=github.com/sharevb/it-tools ENV VITE_VERCEL_ENV=production -ARG BASE_URL + +# The path the app is served under. Override it at run time -- `docker run -e +# BASE_URL=/it-tools/`, `environment: BASE_URL: /it-tools/` in a compose file -- and nginx +# rewrites the `` in index.html on the way out; nothing is baked in. The build +# arg only moves the default, for anyone who prefers to ship an image that is preconfigured +# for a subpath. See docker-entrypoint.d/18-resolve-base-url.envsh and nginx.conf. +ARG BASE_URL=/ ENV BASE_URL=${BASE_URL} + COPY --from=build-stage /app/dist /usr/share/nginx/html COPY nginx.conf /etc/nginx/templates/default.conf.template @@ -49,7 +58,10 @@ ENV NGINX_ENTRYPOINT_WORKER_PROCESSES_AUTOTUNE=1 # Without this the image would fall back to the stock welcome config from the # base image: no SPA fallback, so deep links 404 on refresh, and no COOP/COEP, # so the WebAssembly-backed tools stop working. -RUN envsubst '${PORT}' \ +# Sourcing the entrypoint's own resolver keeps the baked-in BASE_URL normalised and +# validated exactly the way a runtime one would be. +RUN . /docker-entrypoint.d/18-resolve-base-url.envsh \ + && envsubst '${PORT} ${BASE_URL} ${BASE_URL_REGEX} ${BASE_URL_NO_SLASH_REGEX}' \ < /etc/nginx/templates/default.conf.template \ > /etc/nginx/conf.d/default.conf diff --git a/README.md b/README.md index 970c508e..7bcbe7f2 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,10 @@ Since the _base image_ is now `nginx-unpriviledged` the container will now liste You can override listening port using environment variable `PORT` (docker option `-e PORT=8888`). +You can serve the app from a subfolder using environment variable `BASE_URL` (docker option +`-e BASE_URL=/it-tools/`), without rebuilding the image -- see +[Host in a subfolder](#host-in-a-subfolder-it-tools). + If the container needs to listen to IPv6, it needs to be enabled: https://serverfault.com/questions/1147296/how-to-enable-ipv6-on-ubuntu-20-04. Alternatively, you can mount your own `nginx.conf` own using docker option `-v "./nginx.conf:/etc/nginx/templates/default.conf.template"` (with `listen [::]:8080;` removed) ## Build requirements @@ -222,29 +226,39 @@ docker build -t it-tools-fr --build-arg VITE_LANGUAGE=fr . docker run -d --name it-tools-fr --restart unless-stopped -p 8080:8080 it-tools-fr ``` -## Build container image for a custom subfolder +## Host in a subfolder (`/it-tools/`) -According to https://github.com/sharevb/it-tools/pull/461#issuecomment-1602506049 and https://github.com/CorentinTh/it-tools/pull/461: +The container serves the app from whatever path you point `BASE_URL` at. Nothing is baked +into the image, so the regular `latest` image works for any subfolder -- no rebuild, no +subfolder-specific tag: -``` -docker build -t it-tools --build-arg BASE_URL="/my-folder/" . -docker run -d --name it-tools --restart unless-stopped -p 8080:8080 it-tools +```yaml +services: + it-tools: + image: ghcr.io/sharevb/it-tools:latest + restart: unless-stopped + environment: + BASE_URL: /it-tools/ + ports: + - 8080:8080 ``` -Then if you go to `http://localhost:8080` you'll get a blank page, but opening the DevTools (& refreshing) you'll notice in the Network tab that the app is trying to fetch assets from `/my-folder/...` +or `docker run -d --name it-tools -e BASE_URL=/it-tools/ -p 8080:8080 ghcr.io/sharevb/it-tools:latest`. -So you would need to put another server in front of it, like [Nginx Proxy Manager](https://nginxproxymanager.com/), [Traefik](https://traefik.io/traefik/), [caddy](https://caddyserver.com/) etc. Then setup a reverse proxy pass using `/my-folder` +`BASE_URL` accepts `it-tools`, `/it-tools` and `/it-tools/` alike; the default is `/`. -## Docker compose for hosting in a `/it-tools/` subfolder +You still want a reverse proxy in front -- [Nginx Proxy Manager](https://nginxproxymanager.com/), +[Traefik](https://traefik.io/traefik/), [caddy](https://caddyserver.com/) etc. -- passing +`/it-tools/` through to the container. It does not matter whether the proxy strips the +prefix before forwarding (`proxy_pass http://it-tools:8080/;`) or passes it on as-is +(`proxy_pass http://it-tools:8080;`): the container handles both. -For `/it-tools/` subfolder, you can use `baseurl-it-tools` tag. - -See [sample of docker-compose.yml and nginx.conf](https://github.com/sharevb/it-tools/tree/chore/all-my-stuffs/docker-subfolder-sample), this docker image needs to have another reverse proxy in front of it, like [Nginx Proxy Manager](https://nginxproxymanager.com/), [Traefik](https://traefik.io/traefik/), [caddy](https://caddyserver.com/) etc. - -Setup a reverse proxy pass using `/it-tools/`. And you should be able to access it-tools in `/it-tools/` of your server. - -An example of nginx reverse proxy configuration is available at: https://github.com/sharevb/it-tools/tree/chore/all-my-stuffs/docker-subfolder-sample +One thing only the proxy can do, in the stripping setup: `/it-tools` without the trailing +slash never reaches the container, so redirect it there -- the sample's +`location /it-tools { return 301 /it-tools/; }`. When the prefix is forwarded instead, the +container does that redirect itself. +See the [sample docker-compose.yml and nginx.conf](https://github.com/sharevb/it-tools/tree/chore/all-my-stuffs/docker-subfolder-sample). To run the sample: ```bash @@ -253,7 +267,15 @@ cd it-tools/docker-subfolder-sample/ docker compose up ``` -Then navigate to http://localhost:8080/it-tools/ +Then navigate to http://localhost/it-tools/ + +Two things worth knowing: + +- Building with `--build-arg BASE_URL=/it-tools/` still works, but it now only changes the + image's *default* -- the environment variable still wins at run time. +- On a read-only root filesystem the config template cannot be re-rendered at startup, so + `BASE_URL` (like `PORT`) has no effect unless `/etc/nginx/conf.d` is writable -- mount a + tmpfs or an emptyDir there. The container says so in its log. ## To build using a custom folder: diff --git a/docker-entrypoint.d/18-resolve-base-url.envsh b/docker-entrypoint.d/18-resolve-base-url.envsh new file mode 100755 index 00000000..9accb69c --- /dev/null +++ b/docker-entrypoint.d/18-resolve-base-url.envsh @@ -0,0 +1,54 @@ +# vim:sw=4:ts=4:et +# +# BASE_URL is the path the app is served under: `/` (the default) for a deployment at the +# root of a domain, `/it-tools/` for one behind a reverse proxy that mounts it on a +# subpath. It is a runtime setting, not a build one -- the image ships assets that work at +# any path, and nginx.conf rewrites the `` in index.html per request. +# +# Normalise it here, once, before 20-envsubst-on-templates.sh renders the config: +# +# - accept `it-tools`, `/it-tools` and `/it-tools/` alike, always emit `/it-tools/`. +# A missing trailing slash would otherwise silently move the app one directory up, +# because that is how the browser resolves relative URLs against ``. +# - reject anything that is not a plain path. The value is interpolated into an HTML +# attribute and into an nginx regex, so a stray quote or `..` is worth catching here +# rather than letting it land in the served page. +# +# Sourced, not executed, so the export reaches the envsubst step. + +_base_url=$(printf '%s' "${BASE_URL:-/}" | sed -e 's#^/*#/#' -e 's#/*$#/#') + +case "$_base_url" in + # `/` itself, or `/segment/segment/` made of unreserved URL characters. + /) ;; + */../* | *//*) + _base_url_invalid=1 + ;; + *[!A-Za-z0-9._~/-]*) + _base_url_invalid=1 + ;; +esac + +if [ -n "${_base_url_invalid:-}" ]; then + echo "18-resolve-base-url.envsh: error: BASE_URL='$BASE_URL' is not a plain path, falling back to /" >&2 + _base_url=/ +fi + +if [ "$_base_url" != "/" ] && [ -z "${NGINX_ENTRYPOINT_QUIET_LOGS:-}" ]; then + echo "18-resolve-base-url.envsh: info: serving the app under $_base_url" +fi + +BASE_URL="$_base_url" + +# Regex-safe forms of the same value, for the rewrites in nginx.conf. `.` is a legal +# character in a path and the validation above lets it through, but it is also the one +# regex metacharacter that survives that filter: unescaped, a BASE_URL of `/it.tools/` +# would strip the prefix from `/itXtools/...` too. +BASE_URL_REGEX=$(printf '%s' "$_base_url" | sed 's/\./\\./g') +# `/it-tools/` -> `/it-tools`, so nginx.conf can redirect the slash-less spelling to the +# real one. Empty for a deployment at the root, where there is nothing to redirect. +BASE_URL_NO_SLASH_REGEX="${BASE_URL_REGEX%/}" + +export BASE_URL BASE_URL_REGEX BASE_URL_NO_SLASH_REGEX + +unset _base_url _base_url_invalid diff --git a/docker-entrypoint.d/19-skip-envsubst-if-readonly.envsh b/docker-entrypoint.d/19-skip-envsubst-if-readonly.envsh index 802834c0..5200ced4 100755 --- a/docker-entrypoint.d/19-skip-envsubst-if-readonly.envsh +++ b/docker-entrypoint.d/19-skip-envsubst-if-readonly.envsh @@ -23,6 +23,13 @@ if [ -d "${NGINX_ENVSUBST_TEMPLATE_DIR:-/etc/nginx/templates}" ] \ if [ -z "${NGINX_ENTRYPOINT_QUIET_LOGS:-}" ]; then echo "19-skip-envsubst-if-readonly.envsh: info: $_envsubst_output_dir is not writable, keeping the config baked into the image" fi + # The baked config carries the image defaults, so anything that is only applied by + # rendering the template is quietly lost. $PORT has always had this caveat; say so for + # BASE_URL too, where the symptom (an app that loads from the wrong path) is a lot less + # obvious than a port that did not move. + if [ "${BASE_URL:-/}" != "/" ]; then + echo "19-skip-envsubst-if-readonly.envsh: warning: BASE_URL=$BASE_URL cannot be applied on a read-only filesystem; mount a writable $_envsubst_output_dir (a tmpfs or an emptyDir will do)" >&2 + fi export NGINX_ENVSUBST_TEMPLATE_DIR=/nonexistent-read-only-filesystem fi diff --git a/docker-subfolder-sample/docker-compose.yml b/docker-subfolder-sample/docker-compose.yml index 6c181e55..c041d272 100644 --- a/docker-subfolder-sample/docker-compose.yml +++ b/docker-subfolder-sample/docker-compose.yml @@ -1,9 +1,14 @@ services: it-tools: container_name: it-tools-subfolder - image: ghcr.io/sharevb/it-tools:baseurl-it-tools + image: ghcr.io/sharevb/it-tools:latest pull_policy: always restart: unless-stopped + environment: + # The path the app is served under. This is all a subfolder deployment needs -- the + # regular image works at any path, there is no subfolder-specific tag to pull and + # nothing to rebuild. + BASE_URL: /it-tools/ nginx-reverse-proxy: image: nginx:alpine depends_on: @@ -11,4 +16,4 @@ services: volumes: - "./nginx.conf:/etc/nginx/conf.d/default.conf" ports: - - 80:80 \ No newline at end of file + - 80:80 diff --git a/docker-subfolder-sample/nginx.conf b/docker-subfolder-sample/nginx.conf index 479178f4..30981c70 100644 --- a/docker-subfolder-sample/nginx.conf +++ b/docker-subfolder-sample/nginx.conf @@ -2,6 +2,9 @@ server { listen 80; server_name _; + # The trailing slash on proxy_pass strips /it-tools/ before the request reaches the + # container. It works the other way round too -- `proxy_pass http://it-tools-subfolder:8080;` + # forwards the prefix as-is -- because the app's own nginx.conf handles both. location /it-tools/ { proxy_pass http://it-tools-subfolder:8080/; } diff --git a/nginx.conf b/nginx.conf index 7094e4fb..cf18b407 100644 --- a/nginx.conf +++ b/nginx.conf @@ -21,15 +21,52 @@ server { application/javascript mjs; } - # Hashed build output. Without this, a missing chunk falls through to - # index.html below and is served as text/html with a 200, which the browser - # rejects with an opaque MIME error instead of a plain 404. - location /assets/ { - try_files $uri =404; + # `/it-tools` is the same place as `/it-tools/`, but only the second one gives the + # browser the right directory to resolve the app's relative URLs against, so send the + # first one there. Renders to `^$` -- which no request URI can match -- when the app is + # served from the root. Relative Location headers, because $scheme is whatever the + # reverse proxy used to reach the container, not what the browser used. + absolute_redirect off; + rewrite ^${BASE_URL_NO_SLASH_REGEX}$ ${BASE_URL} permanent; + + # Serving the app from a subpath (BASE_URL, normalised by + # docker-entrypoint.d/18-resolve-base-url.envsh, `/` by default). + # + # The build is path-agnostic: every asset is referenced relatively, and the one + # absolute anchor is a `` in index.html that the app itself reads its + # base from (src/utils/base-url.ts). Rewriting that single tag on the way out is + # therefore enough to move the whole app to another path -- no rebuild, no + # subpath-specific image. + # + # sub_filter drops Last-Modified/ETag from every response it touches, and text/html is + # always in scope (sub_filter_types can add types, not exclude HTML). So: index.html, + # which an SPA must not cache anyway and which the service worker precaches regardless, + # and the one other HTML document in the build -- the visual-subnet-calculator's iframe, + # public/visualsubnetcalc/calc.html -- which loses conditional revalidation and is + # refetched in full when that tool is opened. + sub_filter '' ''; + sub_filter_once on; + + # Hashed build output, with or without the deployment prefix in front of it: a reverse + # proxy may pass `/it-tools/assets/...` through as-is or strip the prefix first, and + # both have to land on the same file. Without this, a missing chunk falls through to + # index.html below and is served as text/html with a 200, which the browser rejects + # with an opaque MIME error instead of a plain 404. + location ~ ^/(?:.*/)?assets/(?.+)$ { + try_files /assets/$asset =404; } location / { - rewrite ^/it-tools/(.*) /$1 break; - try_files $uri $uri/ /index.html; + # Same story for everything else the app fetches by path (the JSON config files, + # the WASM helpers in public/): drop the deployment prefix when the proxy forwarded + # it instead of stripping it. Renders to `^/(.*)$` -- a no-op -- for the default + # BASE_URL of `/`. + rewrite ^${BASE_URL_REGEX}(.*)$ /$1 break; + # No `$uri/`: nothing in the build is a directory with an index in it, so the only + # thing matching one ever produced was nginx's own "add the trailing slash" + # redirect -- computed from the URI *after* the rewrite above, so under a subpath + # `/it-tools/figlet-fonts` bounced the browser out of the app to `/figlet-fonts/` + # (and then to a 403). Unknown paths belong to the SPA, which has a 404 page. + try_files $uri /index.html; } } diff --git a/src/base-url.e2e.spec.ts b/src/base-url.e2e.spec.ts new file mode 100644 index 00000000..9947791b --- /dev/null +++ b/src/base-url.e2e.spec.ts @@ -0,0 +1,168 @@ +import { createReadStream, existsSync, readFileSync, statSync } from 'node:fs'; +import { createServer } from 'node:http'; +import type { Server } from 'node:http'; +import { extname, join, normalize, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { expect, test } from '@playwright/test'; + +// The app is built once, for no particular path, and told where it lives at request time. +// This exercises that: a server that mounts `dist` under a subfolder the way the container +// does -- rewrite the one `` in index.html, serve everything else from the same +// files -- and then checks the app actually works from there. +// +// See nginx.conf (the real thing), vite.config.ts (`base` and the baseHref plugin) and +// src/utils/base-url.ts (how the app reads it back). + +const BASE_URL = '/it-tools/'; +const DIST = resolve(fileURLToPath(new URL('.', import.meta.url)), '../dist'); + +const CONTENT_TYPES: Record = { + '.css': 'text/css', + '.html': 'text/html', + '.ico': 'image/x-icon', + '.js': 'text/javascript', + '.json': 'application/json', + '.md': 'text/markdown', + '.mjs': 'text/javascript', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.wasm': 'application/wasm', + '.webmanifest': 'application/manifest+json', +}; + +function resolveInDist(pathname: string): string | undefined { + const candidate = join(DIST, normalize(pathname)); + + if (!candidate.startsWith(DIST) || !existsSync(candidate) || !statSync(candidate).isFile()) { + return undefined; + } + + return candidate; +} + +function serveDistUnder(base: string): Promise<{ server: Server; origin: string }> { + // What nginx.conf does with sub_filter, on every HTML response rather than only on the + // SPA fallback: the service worker precaches index.html by fetching it, and it has to + // get the same document a navigation would. + const withBaseHref = (html: string) => html.replace('', ``); + const indexHtml = withBaseHref(readFileSync(join(DIST, 'index.html'), 'utf-8')); + + const server = createServer((request, response) => { + const { pathname } = new URL(request.url ?? '/', 'http://localhost'); + // Everything below the mount point, with the prefix dropped -- the reverse proxy in + // front of a container may or may not have stripped it already, so nginx.conf copes + // with both and so does this. + const path = decodeURIComponent(pathname.startsWith(base) ? pathname.slice(base.length - 1) : pathname); + + const asset = path.match(/^\/(?:.*\/)?assets\/(.+)$/); + const file = asset ? resolveInDist(`/assets/${asset[1]}`) : resolveInDist(path); + + if (!file) { + // A missing hashed chunk is a 404, not the SPA shell: serving index.html in its + // place turns a plain 404 into an opaque MIME error in the browser. + if (asset) { + response.writeHead(404).end(); + return; + } + + response.writeHead(200, { 'content-type': 'text/html' }).end(indexHtml); + return; + } + + response.writeHead(200, { + 'content-type': CONTENT_TYPES[extname(file)] ?? 'application/octet-stream', + // Same headers the container sets; the WebAssembly-backed tools need them. + 'cross-origin-opener-policy': 'same-origin', + 'cross-origin-embedder-policy': 'require-corp', + }); + + if (extname(file) === '.html') { + response.end(withBaseHref(readFileSync(file, 'utf-8'))); + return; + } + + createReadStream(file).pipe(response); + }); + + return new Promise((done) => { + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + const port = typeof address === 'object' && address !== null ? address.port : 0; + + done({ server, origin: `http://127.0.0.1:${port}` }); + }); + }); +} + +test.describe('Deployment under a subfolder', () => { + let server: Server; + let origin: string; + + test.beforeAll(async () => { + ({ server, origin } = await serveDistUnder(BASE_URL)); + }); + + test.afterAll(async () => { + await new Promise((done) => server.close(done)); + }); + + test('loads the app, and everything it asks for, from the subfolder', async ({ page }) => { + const notFound: string[] = []; + page.on('response', (response) => { + if (response.status() === 404 && response.url().startsWith(origin)) { + notFound.push(response.url()); + } + }); + + await page.goto(`${origin}${BASE_URL}`); + + await expect(page).toHaveTitle(/IT Tools/); + // Router links carry the subfolder, so navigating inside the app stays inside it. + await expect(page.locator(`a[href^="${BASE_URL}"]`).first()).toBeVisible(); + expect(notFound).toEqual([]); + }); + + test('serves a deep link, whose assets are one directory further down', async ({ page }) => { + // The interesting case for a relative build: index.html is served for a path that is + // not the app root, so `./assets/...` would resolve one level too deep without the + // `` the server injected. + await page.goto(`${origin}${BASE_URL}json-to-yaml-converter`); + + await expect(page).toHaveTitle('JSON to YAML converter - IT Tools'); + + // Reaching the tool at all means its lazily imported chunk was resolved correctly. + await page.getByTestId('input').fill('{"foo":"bar"}'); + expect((await page.getByTestId('area-content').innerText()).trim()).toEqual('foo: bar'); + }); + + test('keeps the subfolder when navigating and reloading', async ({ page }) => { + await page.goto(`${origin}${BASE_URL}`); + + const homeTitle = await page.title(); + await page.locator('a.it-tool-link').first().click(); + + // The router was handed the runtime base, so an in-app navigation writes a URL that + // still points inside the subfolder -- and reloading it lands back on the same tool + // instead of on the app root or a 404. + await expect(page).not.toHaveURL(`${origin}${BASE_URL}`); + expect(page.url().startsWith(`${origin}${BASE_URL}`)).toBe(true); + + await expect(page).not.toHaveTitle(homeTitle); + + const url = page.url(); + const title = await page.title(); + + // Then load that URL from scratch, the way someone pasting the link would: it has to + // come back as the same tool rather than as the app root or a 404. In a second tab + // rather than by reloading this one -- navigating a page that has just pulled in a + // tool's chunks races with those requests, and the app answers an aborted chunk load + // by reloading itself (the vite:preloadError handler in src/main.ts), which cancels + // the navigation the test is waiting on. + const fresh = await page.context().newPage(); + await fresh.goto(url); + + await expect(fresh).toHaveURL(url); + await expect(fresh).toHaveTitle(title); + await fresh.close(); + }); +}); diff --git a/src/config.ts b/src/config.ts index fa2421ef..3b33d6df 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,4 +1,5 @@ import { figue } from 'figue'; +import { appBaseUrl } from '@/utils/base-url'; export const config = figue({ app: { @@ -18,6 +19,8 @@ export const config = figue({ doc: 'Application base url', format: 'string', default: '/', + // Not import.meta.env.BASE_URL: the bundle is built path-agnostic, so the real + // base only shows up at runtime. See src/utils/base-url.ts. env: 'BASE_URL', }, env: { @@ -70,6 +73,7 @@ export const config = figue({ ...import.meta.env, // Because the string 'import.meta.env.PACKAGE_VERSION' is statically replaced during build time (see 'define' in vite.config.ts) PACKAGE_VERSION: import.meta.env.PACKAGE_VERSION, + BASE_URL: appBaseUrl, }) .validate() .getConfig(); diff --git a/src/main.ts b/src/main.ts index f144a6be..7d43a046 100644 --- a/src/main.ts +++ b/src/main.ts @@ -5,9 +5,9 @@ import { LoadingPlugin } from 'vue-loading-overlay'; import { installAbortSignalPolyfill } from 'abort-signal-polyfill'; -import { registerSW } from 'virtual:pwa-register'; import shadow from 'vue-shadow-dom'; import { plausible } from './plugins/plausible.plugin'; +import { appBaseUrl } from '@/utils/base-url'; import '@/utils/json5-bigint'; import '@/utils/json5-bignum'; @@ -37,7 +37,49 @@ window.addEventListener('vite:preloadError', (event: Event) => { installAbortSignalPolyfill(); -registerSW(); +// Not `registerSW()` from virtual:pwa-register. With a relative build base it hands +// workbox-window a relative `./sw.js`, and while the browser resolves that against our +// `` correctly, workbox-window's own bookkeeping resolves it against +// `location.href` instead (urlsMatch() in workbox-window). On a route one level deeper +// than the app root the two disagree, workbox mistakes its own worker for an external one +// and reloads the page under the user. Every route is a single segment today, so nothing +// is broken right now; registering by absolute URL just takes the trap away. +// +// What that costs us is the update handling `registerType: 'autoUpdate'` would have wired +// up, so it is reimplemented below. +if (import.meta.env.PROD && 'serviceWorker' in navigator) { + // The worker calls skipWaiting()/clientsClaim() (see vite.config.ts), so a newly deployed + // one takes over this page while it is still showing the previous build. Reload when that + // happens -- otherwise the tab keeps running the old bundle until it navigates, and any + // lazily imported chunk it reaches for has already been swept from the cache. A first + // install claims the page too, and must not reload: only a *replacement* means the page + // and its worker have diverged. + const hadController = Boolean(navigator.serviceWorker.controller); + let reloading = false; + + navigator.serviceWorker.addEventListener('controllerchange', () => { + if (hadController && !reloading) { + reloading = true; + window.location.reload(); + } + }); + + const registerServiceWorker = () => { + navigator.serviceWorker + .register(`${appBaseUrl}sw.js`, { scope: appBaseUrl }) + .catch((error) => console.error('Service worker registration failed:', error)); + }; + + // Registering competes with the page's own loading, so it waits for `load` -- but this + // module sits behind top-level awaits (the config fetches in tools-settings.ts and + // tools/index.ts), so `load` has usually fired long before we get here and waiting for + // it again would mean never registering at all. + if (document.readyState === 'complete') { + registerServiceWorker(); + } else { + window.addEventListener('load', registerServiceWorker, { once: true }); + } +} const app = createApp(App); diff --git a/src/pages/Home.custom.vue b/src/pages/Home.custom.vue index b941757b..c1edee64 100644 --- a/src/pages/Home.custom.vue +++ b/src/pages/Home.custom.vue @@ -1,5 +1,6 @@