Files
it-tools/src/main.ts
T
0a1f5dc450 feat(docker): serve the app from any subpath with a runtime BASE_URL (#565)
* feat(docker): serve the app from any subpath with a runtime BASE_URL

BASE_URL was a build argument, so hosting under a subfolder meant building
your own image (or pulling the separate baseurl-it-tools tag, which is only
ever right for /it-tools/). Make it a runtime setting instead, so the regular
image works anywhere:

    docker run -e BASE_URL=/it-tools/ ghcr.io/sharevb/it-tools:latest

The build is now path-agnostic. Vite's base is relative, so hashed assets and
lazy chunks resolve against the chunk that imports them, and the single
absolute anchor left in the output is a `<base href="/">` injected into
index.html. nginx rewrites that one tag per request (sub_filter) from the
normalised BASE_URL, and the app reads its base back from it at runtime
(src/utils/base-url.ts) for the router and for every URL it builds into
public/ -- import.meta.env.BASE_URL is meaningless in a relative build.

Also handled:

- both reverse-proxy styles: the prefix may reach the container (stripped by
  the rewrite) or be stripped by the proxy first (nothing to do). The assets
  location matches with or without it, so a missing chunk is still a 404
  rather than the SPA shell.
- `/it-tools` redirects to `/it-tools/`, with a relative Location so the
  scheme of the proxy hop does not leak into it.
- the PWA: manifest URLs are relative to the manifest, workbox precache
  entries relative to the service worker, and the worker is registered
  against the runtime base rather than the build-time one.
- BASE_URL is normalised (`it-tools`, `/it-tools`, `/it-tools/` all work) and
  rejected if it is not a plain path, since it lands in an HTML attribute and
  in an nginx regex.

Defaults are unchanged: with BASE_URL unset the rendered config and the
served page are what they were, except that index.html loses ETag/Last-Modified
to sub_filter. On a read-only filesystem the template cannot be re-rendered,
so BASE_URL is ignored there and the container now says so, like it already
had to for PORT.

Building with --build-arg BASE_URL still works but only moves the image
default; the baseurl-it-tools tag is now just latest with that default.

Closes sharevb/it-tools#403

* fix(docker): restore the PWA update reload, escape BASE_URL in the nginx regexes

Follow-up from review of the runtime BASE_URL change.

- registerSW() in autoUpdate mode reloaded the page when a newly deployed
  worker took over (workbox-window's `activated` handler); hand-rolling the
  registration dropped that, so a tab kept running the previous bundle until
  it navigated. Reimplemented on `controllerchange`, guarded so a first
  install -- which also claims the page -- does not reload. Verified by
  counting document loads across an install and a simulated deploy: 1 load on
  first visit, exactly 1 reload when a new worker takes over.
- The comment justifying the hand-rolled registration was wrong: register()
  does resolve a relative URL against `<base href>`. The real reason is
  workbox-window's own urlsMatch(), which resolves against location.href, so
  a relative sw URL misidentifies the worker on a route deeper than one
  segment. Comment now says that.
- BASE_URL allows `.`, which is a metacharacter in the two nginx regexes it
  is spliced into: `/it.tools/` also matched `/itXtools/`. The entrypoint now
  exports regex-escaped forms for those, keeping the literal value for the
  sub_filter replacement and the redirect target.
- Dropped `$uri/` from try_files. Nothing in the build is a directory with an
  index, so the only thing it ever produced was nginx's trailing-slash
  redirect -- computed after the prefix rewrite, so `/it-tools/figlet-fonts`
  answered `301 /figlet-fonts/` and bounced the browser out of the app.
- The sub_filter comment claimed index.html was the only response losing
  ETag/Last-Modified; public/visualsubnetcalc/calc.html is HTML too and is
  equally affected. Comment corrected.
- README: in the prefix-stripping proxy setup, `/it-tools` without the
  trailing slash never reaches the container, so the proxy has to redirect it
  (as the sample does). Said so.
- The new e2e test reloaded a page that had just started pulling in a tool's
  chunks; WebKit cancelled the load ~1 run in 3 (the app reloads itself on an
  aborted chunk fetch). It opens the URL in a second tab instead: 8/8 on
  WebKit, 3/3 browsers green.

* fix(build): validate BASE_URL before it reaches the <base href>

From Copilot's review of #10.

The container validates its runtime BASE_URL, but the build-time one went
straight into an HTML attribute unchecked: a value carrying a quote rewrote
the tag around it, and one carrying a space or `..` quietly produced a page
that loads from the wrong place. Apply the same rule the entrypoint does --
a plain path of unreserved characters -- and fail the build otherwise.

Also: "can not" -> "cannot" in the read-only filesystem warning.

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-19 22:16:54 +02:00

100 lines
3.9 KiB
TypeScript

import { createApp } from 'vue';
import { createPinia } from 'pinia';
import { createHead } from '@vueuse/head';
import { LoadingPlugin } from 'vue-loading-overlay';
import { installAbortSignalPolyfill } from 'abort-signal-polyfill';
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';
import Vue3Katex from 'vue3-katex';
import 'katex/dist/katex.min.css';
import 'virtual:uno.css';
import { naive } from './plugins/naive.plugin';
import App from './App.vue';
import router from './router';
import { i18nPlugin } from './plugins/i18n.plugin';
import { toolsSettings } from './tools-settings';
import store from './tools/pomodoro-timer/app/store';
window.addEventListener('vite:preloadError', (event: Event) => {
console.error('Vite preload error, forcing page reload:', event);
event.preventDefault(); // Prevent the original error from being thrown again
// Deferred: Firefox also fires this event for preloads cancelled by a user
// navigation, and an immediate reload would race (and abort) that navigation.
// If the page is really navigating away, its timers die with it and no reload
// happens; on a genuine chunk-load failure the reload still runs.
setTimeout(() => window.location.reload(), 100);
});
installAbortSignalPolyfill();
// 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
// `<base href>` 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);
app.config.globalProperties.$itToolsSettings = toolsSettings;
app.use(LoadingPlugin);
app.use(createPinia());
app.use(createHead());
app.use(i18nPlugin);
app.use(router);
app.use(naive);
app.use(plausible);
app.use(shadow);
app.use(store, 'pomodoro-store');
app.use(Vue3Katex);
app.mount('#app');