Files
TREK/client/vite.config.js
T
jubnl d7c4324afc chore(capacitor): base files for capacitor (#2020)
* chore(capacitor): base files for capacitor

* chore(capacitor): base plugins

* feat(auth): hand a browser sign-in over to the native app

The native apps show the server's own UI in a WebView, where neither SSO nor
passkeys can run. They sign in through the system browser instead and need a
way to carry that session back.

The app keeps a random verifier and sends only its sha256 into the browser.
Once signed in there, the browser trades that challenge for a one-time code
(cookie session only, so an API or MCP token cannot mint itself a browser
session), and the WebView redeems the code together with the verifier. The
code rides through a URL scheme any app could claim, so on its own it is
worthless; it is single use and good for a minute.

Also: /api/health/features reports nativeApp so the apps can refuse servers
that predate this, and hashed files under assets/ are served immutable,
which the iOS app needs to start offline without a service worker.

* feat(native): the apps load the server's own UI

The apps ship only an address screen now. Once a server is picked, the
native side points the WebView at it: TrekBridgeViewController on iOS and a
config copy with server.url on Android. The UI then comes from that server,
in the version it runs and on its own origin, so the session cookie,
uploads, /ws and plugins work exactly as in a browser and no app release
has to keep pace with the servers out there.

The address screen (native-shell/, built into native-dist/) probes
/api/health/features through native HTTP, tries https before http when no
scheme was typed, and refuses servers without the nativeApp flag. It also
serves as the error page when the remembered server does not load: retry,
change server, or on iOS the stored copy of the server's start page.

TrekShell is the app's own plugin for all of that: remember, change and
reload the server, sign in through ASWebAuthenticationSession or a Custom
Tab, and on iOS keep and open the offline copy of the start page, because
WKWebView runs no service worker for a domain the app does not list.

Plugins the frame does not use are gone (push, camera, geolocation,
calendar, file transfer, in-app browser and more): the WebView covers the
camera and location itself, and push needs a relay before it is worth
shipping. With them go the push entitlement, the calendar usage strings
and the Firebase bits. The iOS scheme falls back to capacitor://, since
Capacitor drops an iosScheme of https, and the arm64 capability replaces
armv7.

* feat(native): the UI knows when it runs inside the app

Everything the server's UI does differently inside the iOS and Android app
lives under src/native and is inert in a browser.

Sign-in: SSO and the passkey button go through the system browser
(signInThroughBrowser), because identity providers refuse embedded
browsers and WebAuthn needs a domain association no build can have for
every server. The browser end is the new /native-handoff page: it signs
the user in if needed and hands the session over only after an explicit
tap, so a link carrying somebody else's challenge cannot pass a session
on silently. The verifier is hashed with @noble/hashes because
crypto.subtle is missing on the plain-http servers many home networks
use. An OIDC-only install no longer bounces to the IdP inside the
WebView, and passkey management is hidden in the app.

Downloads: the WebView cannot save a blob, so downloadBlob, downloadFile
and openFile write to the app cache and open the share sheet. The eight
places that built their own download anchor now use downloadBlob, which
they should have anyway.

The rest: "Change server" on the login page and in the account settings,
the splash hides after the first frame, Android's back button walks
history before it leaves the app, the status bar follows the scheme, and
on iOS the start page is refreshed and every chunk of the build (listed
in the new asset-manifest.json) is pulled into WebKit's cache so the app
can start without network.

* ci(native): build the Android and iOS shells on every change to them

Compiles the Swift side on a macOS runner so nobody needs a Mac to know it
still builds, and leaves a debug APK on every run to install on a phone.
Unsigned: signing and store uploads need secrets fork PRs do not get.

* feat(native): offline vector maps in the iOS app

In a browser the service worker answers MapLibre from the gl-map-offline
cache that glPrefetcher fills for trips marked for offline. The iOS app has
no service worker, so nothing read that cache there and the map went blank
without network.

A trek-offline:// protocol takes the service worker's place. Inside the iOS
app the MapLibre style URL is rewritten to it, the handler rewrites every
https URL inside the style and its TileJSON the same way, and then serves
documents network first and tiles, glyphs and sprites cache first. Outside
the iOS app nothing changes. The default OpenFreeMap basemap is covered;
Mapbox GL has no protocol hook and stays online-only in the app, as does a
custom raster template, whose opaque responses only a service worker can
store.

* fix(native): keep the iOS offline copy inside the app

loadSimulatedRequest went to the server URL without its trailing slash, and
Capacitor keeps a navigation in the WebView only when it starts with the
bridge's serverURL, slash included. The offline start page would have
opened in Safari instead. Also covers the platform helpers and the
hand-off API module.

* feat(native): the small things that give a WebView away

- A short haptic tap on success, warning and error toasts, which is where
  every save and delete already reports. Info toasts stay silent.
- No "‹ › Done" strip above the iOS keyboard.
- No Safari preview when a link is long-pressed.
- The swipe from the left edge goes back on iOS, through the same history
  Android's back button walks.

* test(mobile): the backup-code download revokes its URL after the shared delay

The mobile twin of the AccountTab test still expected the object URL to be
revoked in the same tick. Since both screens download through downloadBlob,
the revoke happens after its 100 ms grace period.

* fix(native): remember the login by default inside the app

With the switch off the app got a session cookie, which dies with the app
process, so every time the phone unloaded TREK the user had to sign in
again. Found while running the Android build in the emulator.

* fix(native): no overscroll stretch on Android

The UI asks for no overscroll effect with overscroll-behavior: none on html,
and Chrome honours it. The Android WebView draws the stretch on its root
scroller natively, though, and it scales the whole view, so the top bar and
the bottom dock were pulled along with the page. Found in the emulator.

* fix(native): Android shows "server not reachable" instead of a blank page

Capacitor injects its bridge on Android only into the server's origin once
server.url is set, so the local error page it switches to when the server
does not load had no bridge. It could neither retry nor change the server
and stayed blank.

TrekWebViewClient now catches a failed page load (a network error, or a 5xx
from a proxy while TREK restarts) and the app starts over on the bundled
address screen, where the bridge is present and the screen offers exactly
those two choices. The server config no longer carries errorPath.

Two traps on the way, both found in the emulator: a restart during launch
has to be a fresh task, since recreate() leaves the system splash lying over
the new page; and a restart shows no launch splash at all, because the
splash plugin cannot take it down again when the page hides it early.

* feat(native): TREK's own app icon and launch screen, named just TREK

The shells still carried Capacitor's placeholder icon and splash, the blue
X on a grid. They now show the white TREK mark on a dark, slightly glassy
tile: a soft light from the top left and a sheen over the upper half, in
the app's launch colour #09090b. Android 12+ draws its launch screen on the
same colour instead of light grey.

scripts/generate-app-icons.mjs renders the sources into assets/ from
public/icons/icon-white.svg, and `npm run icons:app` turns them into every
size both platforms ask for through @capacitor/assets. The Android
foreground mark is sized for the adaptive icon's round mask.

The home screen label is TREK: the old "TREK - Plan your trips!" was cut
off under the icon, and the longer title belongs to the store listings.

* fix(native): new lint warnings and the MapLibre protocol type after the dev merge

Awaits that sat in loops in the native-auth tests run together, the hand-off hook marks its navigations as ignored, the native tests drop their non-null assertions, and the offline protocol answers with the data type MapLibre 6.15 expects.

* fix(native): strict types in the address screen, Prettier on the native-auth e2e suite, file-local exports

The address screen's element helper returns the plain element instead of Object.assign's intersection, which strict mode could not represent; the haptics test reads an optional argument as optional; three exports only their own file used are local now.

* fix(native): Prettier on the native client files, rate-limit e2e requests in sequence

Formats the files the client formatting gate listed, and NATIVE-E2E-005 sends its twenty exchange attempts one after another: all at once they reset the test server's connections.

* fix(native): hide passkeys in the app through usePasskeys

The flag in useAccountSettings grew the identical destructuring in both account views past the duplication threshold; the shared passkeys hook already decides when its card is hidden, so the app check lives there now.

* feat(native): everything the App Store and Google Play submissions need

- iOS: microphone usage text for "Take Video", no-export-compliance flag,
  ExportOptions.plist for App Store Connect uploads, the unused push
  forwarders gone; CI builds with Xcode 26 and lints the property lists.
- Android: version and signing from Gradle properties (unsigned without
  them), R8 with keep rules for TREK's and Capacitor's reflective classes,
  no Auto Backup of the session cookie, no external file provider path,
  template and Firebase leftovers removed, keystores and service accounts
  ignored, full-size adaptive icon layers with a monochrome layer; CI also
  builds the release APK.
- native-release.yml: signed bundle to a Play testing track and archive to
  TestFlight, by hand or on a v* tag, behind the store environment.
- Version handshake: the server reports nativeApi 1, the app refuses a
  server below its minimum and tolerates an app older than the offline copy.
- Address screen: privacy policy link, "Try the demo" and "What is a TREK
  server?"; the privacy link also in the app's server settings. Three new
  native strings in all 27 locales.
- Donation links and the notices asking for one are hidden in the app.
- Store listings for "TREK Travel Planner" in client/fastlane: texts, review
  notes with placeholders, privacy and account deletion page drafts, the
  feature graphic and icon, a length and image check in CI, and a Playwright
  store project with the scripts that turn its captures into screenshots.
- Docs: wiki/Native-Apps.md, README no longer says there is no store app.

* fix(native): read a notice button's href without a weak type

An action button carries no href, so a parameter typed as only an optional href refused the notice DTO; the button type now names its kind as well.

* feat(native): a welcoming onboarding for the address screen

The app's own screen now opens on a welcome: the TREK mark, a line about what
TREK is, and two clear paths — connect the TREK you already open in the browser,
or get TREK Cloud. Both lead to polished screens: the address field with live
validation, a shake and haptic on a bad address and a success tick before the
server takes over; and a TREK Cloud intro with what it offers and a way in.
Screens slide and stagger in, buttons give a tap, and it all respects the safe
areas, light and dark, and reduced motion. Self-hosters are unaffected: cloud is
its own path, never in the way. New native strings are added across all locales
(English placeholders outside en/de, to translate).

* feat(native): a plan picker for TREK Cloud, with live prices

The Get TREK Cloud path now leads to a plan picker that reads the live plans
from the site (/api/plans), so the prices and quotas always match the website.
Monthly and yearly in a segmented toggle, the year marked with its saving, each
plan a card with its price and what it includes. Subscribe is wired to finish on
the web order for now; it becomes an Apple/Google in-app purchase once the store
products exist. New strings across all locales (en and de translated).

* feat(native): light status bar and a Go key on the address screen

The address screen sits on the near-black surface, so set the status bar to draw
its clock and icons in light while it is up; the server's own UI takes over the
style once it loads. The address field's on-screen return key now reads Go. Both
fail quietly where there is no native status bar (web, the simulator).

* i18n(native): translate the onboarding into es, fr, it, nl and pl

The welcome, TREK Cloud and plan-picker strings were English placeholders in
every locale but en and de. The five largest remaining European languages are
now translated in full; the others still carry the English text and are a
follow-up for native speakers.

* feat(native): the in-app TREK Cloud subscription flow

After picking a plan, the app now carries the whole purchase itself when the build
can take one: choose your address (checked for free as you type, against the same
endpoint the website uses), your email, and subscribe. The receipt goes to
/api/iap/redeem, and a Setting up your TREK screen waits on the new address and
loads it the moment it answers.

The purchase sits behind an IapClient seam (src/native/iap.ts): a fake drives the
whole flow in development and preview, the native client reports itself
unavailable until the store plugin and products exist, and until then the plan
picker still finishes on the web, so nothing half-wired faces a customer. New
claim and provisioning strings across all locales (en, de and the five largest
European languages translated).

* i18n(native): translate the app into the remaining 20 languages

The onboarding, plan picker, claim and provisioning strings were English
placeholders outside en, de and the five largest European languages. They are
now translated in full across the other 20 locales (ar, az, br, ca, cs, et, gr,
hu, id, ja, ko, ru, sk, sv, th, tr, uk, vi, zh, zh-TW), placeholders and brand
kept. The app now speaks every language TREK does.

* fix(i18n): add the Hebrew native strings, and correct the LoginPage size baseline

The he locale had every domain but native.ts, which broke i18n parity, the shared
coverage specs and the client parity test once the native strings existed. Add
he/native.ts with all native keys translated. Also correct the LoginPage size
baseline to its current line count.

* i18n(native): excuse the TREK Cloud brand, mark Email same-as-en, exempt the quota counts

The strict i18n checks, which the feature-branch CI does not run, catch three
things now that the native strings exist in every locale: TREK Cloud read as an
untranslated English phrase (it is a product name, like Vacay and Atlas, so add
it to the brand list); Email left identical in Italian, Indonesian and
Vietnamese, where it is the local word too (mark same-as-en) and in Greek (give
it a Greek term); and the GB and AI-document quota strings carrying {n} without
being plural groups (both are figures that never show a singular, like the other
unit-symbol counts in NOT_PLURAL).

* fix(native): typecheck, lint and knip on the native code; wire he's native bundle

The full suite, which the feature-branch CI does not run, catches four things the
native work still had: a non-narrowed union in the claim flow (tsc), a helper
named useFake that the react-hooks rule read as a hook (eslint), two iap types
exported but used only inside the file (knip), and the Hebrew native strings
present as a file but never spread into he's merged bundle (the aggregated key
parity test). All four fixed.

* fix(native): a flat redeem result, so the claim flow typechecks

The discriminated union did not narrow under the native-shell tsconfig, so the
failure code read as absent on the whole type. Use a flat result with optional
instanceUrl and code instead: both are always present on the type, no narrowing
needed, and the ok plus instanceUrl guard still routes success from refusal.

* style: prettier-format the native and i18n changes

The feature-branch CI does not run the formatting check, so the conflict-resolved
files (AboutTab, useAccountSettings, useTripExport), the native shell and iap
module, and the i18n files touched by the translation scripts were never run
through Prettier. Format them all; no behaviour changes.

* chore(native): re-trigger CI on the formatted tree

---------

Co-authored-by: Maurice <mauriceboe@icloud.com>
2026-11-05 21:09:04 +01:00

425 lines
20 KiB
JavaScript

import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
import { visualizer } from 'rollup-plugin-visualizer';
import { rtlTextAlias, plyrSpriteAlias } from './rtlTextAlias.js';
import { withoutRuntimeFonts } from './bookFontPrecache.js';
import { readFileSync } from 'node:fs';
// The version this bundle is built as, baked in at build time. The Docker build
// passes APP_VERSION, which the prerelease images need because they do not bump
// package.json; a source checkout matches the server's own package.json.
// The server hands the release notice only to a bundle built for its version.
const BUILD_VERSION = process.env.APP_VERSION && process.env.APP_VERSION !== 'dev' ? process.env.APP_VERSION : null;
const UI_VERSION = BUILD_VERSION ?? JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version;
// `npm run build:analyze` writes dist/stats.html — a treemap of what actually ended
// up in each chunk. The plain build only reports chunk sizes, which tells you a chunk
// is too big but not which dependency made it so.
// Mehrere Worktrees laufen hier parallel. Ohne diese beiden Variablen streiten
// sie sich um 5173 und 3001; mit ihnen bekommt jeder seinen eigenen Satz.
const DEV_PORT = Number(process.env.TREK_DEV_PORT) || 5173;
const API_TARGET = process.env.TREK_DEV_API || 'http://localhost:3001';
export default defineConfig(({ mode }) => ({
define: { __TREK_UI_VERSION__: JSON.stringify(UI_VERSION) },
plugins: [
react(),
mode === 'analyze' &&
visualizer({ filename: 'dist/stats.html', gzipSize: true, brotliSize: true }),
VitePWA({
registerType: 'autoUpdate',
// Serve the generated manifest (+ dev SW) in development too, so the installed
// PWA can be tested against the dev server. Without this, dev ships no
// <link rel="manifest">, so iOS falls back to legacy standalone
// (apple-mobile-web-app-capable only) and pops the Safari chrome on every
// in-app navigation away from the start URL. Prod already serves the manifest.
devOptions: {
enabled: true,
type: 'module',
suppressWarnings: true,
/*
* No navigation fallback from the dev service worker.
*
* `workbox.navigateFallback` below is right for production: offline, a
* deep link has to be answered by the cached shell. In development it
* means the worker answers a reload with the index.html it cached
* earlier, whose <script> tags point at module URLs from before the last
* restart — so the browser faithfully re-runs the previous version of
* the app while the editor shows the new one, and every explanation for
* that is wrong until someone thinks of the service worker. It cost
* several rounds of "I don't see the change" to find.
*/
navigateFallback: undefined,
},
workbox: {
// The Web Push handlers (push, notificationclick, pushsubscriptionchange).
// Workbox writes importScripts('sw-push.js') at the top of the generated
// worker, in dev too. The file lives in public/: were it missing,
// importScripts would get no script (the server answers a missing build
// file with a 404) and the new worker would fail to install, which
// tests/unit/pwa/swPush.test.ts guards against.
importScripts: ['sw-push.js'],
// Anything above this is dropped from the precache manifest. The build does
// not fail over it, it only prints "won't be precached", so the ceiling has
// to sit close to the real bundle or an accidental heavyweight goes
// offline-broken unnoticed. Largest precached entry is the heic-to chunk at
// 3.0 MB, which leaves about 670 kB of headroom; the entry chunk is 258 kB.
maximumFileSizeToCacheInBytes: 3.5 * 1024 * 1024,
// Every route chunk is precached alongside the shell, deliberately: for an
// offline-first travel planner a route the user never opened before losing
// signal still has to work. The trade is that splitting buys first paint and
// not install size: 107 entries / 17,795 KiB before any of it, 463 /
// 23,292 KiB now (measured, not estimated).
//
// Keep this figure honest. #2228 traced PWA boot failures to the browser
// evicting this origin's whole bucket, precached shell included, and this
// comment is the only record of what the install actually costs. Anything
// matching the globs below is fetched at service-worker install by every
// user, whether or not they ever reach the code.
globPatterns: ['**/*.{js,css,html,svg,png,woff,woff2,ttf}'],
// Except most of the book's typefaces: of thirty four families only the
// latin files of the seven the book first shipped with are installed,
// the rest wait in the book-fonts rule below for a book that uses them
// (bookFontPrecache.js).
manifestTransforms: [withoutRuntimeFonts],
// build:analyze drops a treemap next to the app; it must never end up in a
// precache manifest if someone ships that build by accident.
// The assistant's chat (@assistant-ui, about 110 kB gzip) only runs online, so
// installing it for every user offline would be pure cost; it loads when opened.
globIgnores: ['**/stats.html', '**/AssistantSurface-*.js'],
navigateFallback: 'index.html',
navigateFallbackDenylist: [
/^\/api/,
/^\/uploads/,
/^\/mcp/,
/^\/oauth\//,
/^\/.well-known\//,
/^\/plugin-frame\//,
],
runtimeCaching: [
{
// The book's typefaces the precache leaves out (bookFontPrecache.js):
// fetched the first time a page is set in them, and up front for
// every face of a book the Studio opens (bookFontWarm.ts), so the
// book still reads in its own type offline. Same-origin build
// assets only; the files are content-hashed, so a cached one never
// goes stale. First in the list so no broader rule takes them.
urlPattern: /\/assets\/[^/?#]+\.woff2?(?:\?.*)?$/i,
handler: 'CacheFirst',
options: {
cacheName: 'book-fonts',
expiration: { maxEntries: 600, maxAgeSeconds: 365 * 24 * 60 * 60 },
cacheableResponse: { statuses: [200] },
},
},
{
// Carto map tiles (default provider)
// maxEntries MUST stay >= MAX_TILES in src/sync/tilePrefetcher.ts
// (both are 12288) so prefetched tiles aren't evicted on arrival.
// The apex host counts too: a template without {s} points straight at
// basemaps.cartocdn.com, and matching only the shards left those tiles
// uncached, so the map went blank offline.
urlPattern: /^https:\/\/(?:[a-d]\.)?basemaps\.cartocdn\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'map-tiles',
expiration: { maxEntries: 12288, maxAgeSeconds: 30 * 24 * 60 * 60 },
cacheableResponse: { statuses: [0, 200] },
},
},
{
// OpenStreetMap tiles (fallback / alternative)
// Shares the 'map-tiles' cache; keep maxEntries equal to the Carto
// rule above and MAX_TILES in src/sync/tilePrefetcher.ts (12288).
// Both spellings have to stay in the pattern: templates are rewritten
// onto the apex host (src/utils/tileUrl.ts), but caches filled before
// that still hold a/b/c URLs and must keep serving offline.
urlPattern: /^https:\/\/(?:[a-c]\.)?tile\.openstreetmap\.org\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'map-tiles',
expiration: { maxEntries: 12288, maxAgeSeconds: 30 * 24 * 60 * 60 },
cacheableResponse: { statuses: [0, 200] },
},
},
{
// OpenStreetMap DE — a shipped preset that matched no rule at all, so
// "Store map tiles offline" fetched thousands of tiles and stored none
// of them (#2180). Same cache, same limits as the rules above.
urlPattern: /^https:\/\/tile\.openstreetmap\.de\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'map-tiles',
expiration: { maxEntries: 12288, maxAgeSeconds: 30 * 24 * 60 * 60 },
cacheableResponse: { statuses: [0, 200] },
},
},
{
// Stadia Smooth — the other shipped raster preset with the same hole (#2180).
urlPattern: /^https:\/\/tiles\.stadiamaps\.com\/tiles\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'map-tiles',
expiration: { maxEntries: 12288, maxAgeSeconds: 30 * 24 * 60 * 60 },
cacheableResponse: { statuses: [0, 200] },
},
},
{
// Tours-only OpenTopoMap raster tiles. Same bounded cache as the
// other Leaflet sources; opaque tile responses are valid here.
urlPattern: /^https:\/\/(?:[a-c]\.)?tile\.opentopomap\.org\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'map-tiles',
expiration: { maxEntries: 1000, maxAgeSeconds: 60 * 60 * 24 * 30 },
cacheableResponse: { statuses: [0, 200] },
},
},
{
// Amap road and satellite presets, served from the shard hosts under
// is.autonavi.com (src/constants/mapDefaults.ts). Without a rule here
// they would be the #2180 hole all over again.
urlPattern: /^https:\/\/(?:[a-z0-9]+\.)?is\.autonavi\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'map-tiles',
expiration: { maxEntries: 12288, maxAgeSeconds: 30 * 24 * 60 * 60 },
cacheableResponse: { statuses: [0, 200] },
},
},
{
// The GL style DOCUMENT, for both providers. It has to be matched
// before the tile rules below, because Workbox takes the first route
// that matches and the broad tile patterns cover this URL too (#1924).
//
// A style is not a tile. It is one small document that changes the
// moment the user edits it in Mapbox Studio, and it decides how every
// tile is drawn — including which `name_*` field the labels read.
// Under StaleWhileRevalidate the map was built from the PREVIOUS
// revision on every load, with the refresh landing one load too late,
// so a style republished with different label languages kept rendering
// the old ones. The network tab showed a 200 throughout, because the
// service worker's own answer is a real 200.
//
// NetworkFirst rather than NetworkOnly: the map still has to open
// offline. Its own small cache rather than the tile cache: sharing
// an LRU with thousands of tiles made eviction, and therefore the
// staleness, look random.
urlPattern: /^https:\/\/(api\.mapbox\.com\/styles\/v1\/|tiles\.openfreemap\.org\/styles\/)/i,
handler: 'NetworkFirst',
options: {
cacheName: 'gl-map-styles',
networkTimeoutSeconds: 5,
expiration: { maxEntries: 20, maxAgeSeconds: 30 * 24 * 60 * 60 },
cacheableResponse: { statuses: [200] },
},
},
{
// Mapbox GL glyphs, sprites and vector tiles (the style itself is
// handled by the rule above). Best-effort offline only:
// opportunistically caches what the user has already
// viewed online. Full pre-download offline maps require the Leaflet
// renderer (raster prefetch in tilePrefetcher.ts) — the GL vector
// pipeline is not prefetched. StaleWhileRevalidate keeps the basemap
// fresh online while still serving from cache when offline. Mapbox
// sends CORS, so responses are non-opaque (real 200s, no quota pad).
urlPattern: /^https:\/\/(api\.mapbox\.com|[a-d]\.tiles\.mapbox\.com)\/.*/i,
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'mapbox-tiles',
expiration: { maxEntries: 3000, maxAgeSeconds: 30 * 24 * 60 * 60 },
cacheableResponse: { statuses: [200] },
},
},
{
// OpenFreeMap MapLibre glyphs, sprites and vector tiles (the style
// itself is handled by the style rule above).
//
// CacheFirst, and sharing its cache with the prefetcher: OpenFreeMap
// serves tiles under a versioned planet path, so a cached tile is
// never stale — a new planet is a new URL. StaleWhileRevalidate
// would revalidate every tile of a pre-downloaded region on the next
// online visit for nothing.
//
// cacheName matches sync/glPrefetcher.ts, which writes here directly:
// one cache means normal browsing tops the offline region up instead
// of filling a second copy beside it. maxEntries is above the
// prefetcher's own cap so a browsing session cannot evict a region
// the user asked to keep.
urlPattern: /^https:\/\/tiles\.openfreemap\.org\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'gl-map-offline',
expiration: { maxEntries: 6000, maxAgeSeconds: 90 * 24 * 60 * 60 },
cacheableResponse: { statuses: [200] },
},
},
{
// API calls — network only. We deliberately do NOT cache API
// responses in the Service Worker: Workbox keys entries by URL and
// cannot vary on the httpOnly session cookie, so a shared device
// could serve one user's cached data to the next (cross-user leak).
// Offline reads are served from the per-user IndexedDB cache via the
// repo layer instead. The urlPattern is kept so these requests still
// bypass the SPA navigation fallback.
urlPattern: /\/api\/(?!auth|admin|backup|settings|health).*/i,
handler: 'NetworkOnly',
},
{
// Uploaded files (photos, covers — public assets only)
urlPattern: /\/uploads\/(?:covers|avatars)\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'user-uploads',
expiration: { maxEntries: 300, maxAgeSeconds: 7 * 24 * 60 * 60 },
cacheableResponse: { statuses: [200] },
},
},
],
},
manifest: {
name: 'TREK \u2014 Travel Planner',
short_name: 'TREK',
description: 'Travel Resource & Exploration Kit',
theme_color: '#111827',
background_color: '#0f172a',
display: 'standalone',
scope: '/',
start_url: '/',
categories: ['travel', 'navigation'],
icons: [
{ src: 'icons/apple-touch-icon-180x180.png', sizes: '180x180', type: 'image/png' },
{ src: 'icons/icon-192x192.png', sizes: '192x192', type: 'image/png' },
{ src: 'icons/icon-512x512.png', sizes: '512x512', type: 'image/png' },
// Dedicated safe-zone renders: the full-bleed icon under a maskable
// purpose filled the whole Android launcher tile without any padding.
{ src: 'icons/icon-maskable-192x192.png', sizes: '192x192', type: 'image/png', purpose: 'maskable' },
{ src: 'icons/icon-maskable-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
{ src: 'icons/icon.svg', sizes: 'any', type: 'image/svg+xml' },
],
},
}),
].filter(Boolean),
resolve: { alias: [rtlTextAlias, plyrSpriteAlias] },
build: {
// Pin the output level instead of inheriting whatever the current Vite default
// is, so a toolchain bump can't silently change which browsers still work.
target: 'es2022',
sourcemap: false,
// Served as /asset-manifest.json. The iOS app, which runs no service worker,
// walks it to pull every chunk into WebKit's cache so TREK can start offline
// (src/native/offlineShell.ts).
manifest: 'asset-manifest.json',
modulePreload: { polyfill: true },
// Vite 8 bundles with rolldown, not rollup. `rollupOptions` is only an alias
// onto `rolldownOptions`, and both `manualChunks` and `advancedChunks` are
// deprecated in favour of `codeSplitting.groups` — a config mixing them still
// builds green and simply has no effect.
//
// `tags: ['$initial']` is not optional here. Without it a group also collects
// modules that today hang behind React.lazy, which turns the group chunk into
// a static import of the entry: measured, that put the 2.8 MB GL chunk into
// the index.html modulepreload and took eager JS from 1.48 MB to 4.61 MB.
//
// Deliberately no groups for mapbox-gl/maplibre-gl, leaflet or react-markdown.
// Those already sit in async chunks of their own with hashes that survive a
// release; a group would only rename them, and at worst make them eager.
rolldownOptions: {
output: {
codeSplitting: {
groups: [
{
name: 'vendor-react',
priority: 40,
tags: ['$initial'],
// react-dom/server is pulled dynamically by TripPDF and lives in an
// async chunk. Excluding it keeps a later static import from lifting
// ~170 kB of Fizz into the eager vendor chunk.
test: (id) =>
/[\\/]node_modules[\\/](react|react-dom|react-router|scheduler)[\\/]/.test(id) &&
!/react-dom[\\/](server|static)|react-dom-server/.test(id),
},
{
name: 'vendor-core',
priority: 30,
// zod and dompurify arrive through @trek/shared but live in
// node_modules themselves, so they are caught here. @trek/shared is
// not: it resolves to shared/dist without a node_modules segment,
// and its contract code changes with every release anyway.
tags: ['$initial'],
test: /[\\/]node_modules[\\/](zustand|dexie|axios|zod|dompurify|isomorphic-dompurify)[\\/]/,
},
],
},
},
},
},
/*
* Never pre-bundle the workspace's own contracts.
*
* `@trek/shared` resolves to shared/dist, which is a build output that changes
* whenever a Zod schema does. Pre-bundled, the dev server keeps serving the
* copy it optimised at startup: a field added to the document contract is
* missing in the browser, `normalizeBookDocument` strips it on load, and the
* change you just made vanishes on reload with nothing in the console. It
* cost an afternoon twice before anyone worked out it was not the code.
*/
optimizeDeps: {
exclude: ['@trek/shared'],
},
server: {
port: DEV_PORT,
// And watch the build output, so rebuilding shared reloads the page rather
// than leaving a stale module graph behind.
watch: {
ignored: ['!**/shared/dist/**'],
},
proxy: {
'/api': {
target: API_TARGET,
changeOrigin: true,
},
'/plugin-frame': {
target: API_TARGET,
changeOrigin: true,
},
'/uploads': {
target: API_TARGET,
changeOrigin: true,
},
'/ws': {
target: API_TARGET,
ws: true,
},
'/mcp': {
target: API_TARGET,
changeOrigin: true,
},
// OAuth 2.1 endpoints handled by backend (SDK authorize handler + token/revoke)
// /oauth/authorize goes to backend so the SDK can redirect to /oauth/consent
// /oauth/consent is served by Vite as a SPA route (no proxy entry needed)
'/oauth/authorize': {
target: API_TARGET,
changeOrigin: true,
},
'/oauth/token': {
target: API_TARGET,
changeOrigin: true,
},
'/oauth/register': {
target: API_TARGET,
changeOrigin: true,
},
'/oauth/revoke': {
target: API_TARGET,
changeOrigin: true,
},
'/.well-known': {
target: API_TARGET,
changeOrigin: true,
},
},
},
}));