Files
Rosea/apps/rosea/vite.config.ts

150 lines
6.6 KiB
TypeScript

import { svelte } from '@sveltejs/vite-plugin-svelte';
import { readdirSync, readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig, type Plugin } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
// A relative path, not '@rosea/schema', on purpose. Vite bundles a config's
// relative imports but externalises anything under node_modules, and Node cannot
// load a workspace package's .ts source, so `vite build` and `svelte-check` both
// failed to load this file. The constants module is pure and dependency-free.
import { PRODUCT_NAME, PRODUCT_SHORT_NAME } from '../../packages/schema/src/constants.js';
import { CSP } from './csp.js';
/**
* Two builds of one game (CLAUDE.md §2, *Four versions*; tauri-platforms.md D2).
* - the PWA (default mode): base `/Rosea/`, a service worker, the web manifest, the CSP
* in a <meta> tag, into `dist/`;
* - the Tauri shell's copy (`--mode tauri`): base `/`, because Tauri serves the game at the
* root of its own origin; no worker and no manifest, because the files are already on
* the device; no <meta> CSP, because Tauri delivers the same policy and a page that
* carries both obeys both; into `dist-tauri/`, so the two can never be mixed up.
*/
type Shell = 'web' | 'tauri';
/**
* GitHub Pages serves a project site at `/<repo>/`, not `/` (CLAUDE.md §8). Vite
* `base`, the manifest's `scope`/`start_url` and the service worker's scope all
* derive from this one value, so they cannot disagree. The e2e and offline
* suites serve the build under the same prefix.
*/
function baseFor(shell: Shell): string {
const base = process.env['ROSEA_BASE'] ?? (shell === 'tauri' ? '/' : '/Rosea/');
if (!base.startsWith('/') || !base.endsWith('/')) {
throw new Error(`ROSEA_BASE must start and end with '/', got '${base}'`);
}
return base;
}
/**
* The content-security policy (`csp.ts`). GitHub Pages cannot send headers, so the PWA
* carries it in a <meta> tag (CLAUDE.md §8). It is injected into the BUILT page only,
* because the dev server injects inline <style> for hot reload and `style-src 'self'`
* would blank it. E2E runs against the build, where the policy is real.
*/
function contentSecurityPolicy(): Plugin {
return {
name: 'rosea-csp',
apply: 'build',
transformIndexHtml: {
order: 'post',
handler: () => [
{ tag: 'meta', attrs: { 'http-equiv': 'Content-Security-Policy', content: CSP }, injectTo: 'head-prepend' }
]
}
};
}
/**
* The hope library, bundled at build time as `virtual:rosea-library`
* (day-sentence.md P5). The build script runs `validate:library` first and stops if
* it fails, so the app holds exactly what passed and never validates in the browser
* (GAP_ANALYSIS G0.12: Ajv needs `new Function`, which the CSP forbids).
* `ROSEA_LIBRARY_DIR` swaps the folder, for the e2e build only.
*/
const LIBRARY_DIR = resolve(fileURLToPath(new URL('../..', import.meta.url)), process.env['ROSEA_LIBRARY_DIR'] ?? 'content/library');
function hopeLibrary(): Plugin {
const id = 'virtual:rosea-library';
const resolved = `\0${id}`;
return {
name: 'rosea-library',
resolveId: (source) => (source === id ? resolved : undefined),
load(source) {
if (source !== resolved) return undefined;
const entries: unknown[] = [];
for (const file of readdirSync(LIBRARY_DIR).filter((f) => f.endsWith('.json')).sort()) {
const path = join(LIBRARY_DIR, file);
this.addWatchFile(path);
const data: unknown = JSON.parse(readFileSync(path, 'utf8'));
if (!Array.isArray(data)) throw new Error(`${path}: must be an array of entries`);
entries.push(...data);
}
return `export default ${JSON.stringify(entries)};`;
}
};
}
// Nothing binds to anything but 127.0.0.1 (CLAUDE.md §5.7).
export default defineConfig(({ mode }) => {
const shell: Shell = mode === 'tauri' ? 'tauri' : 'web';
const BASE = baseFor(shell);
return {
base: BASE,
// The one way the game knows which shell it is in, read in App.svelte only (CLAUDE.md §2).
define: { __ROSEA_SHELL__: JSON.stringify(shell) },
plugins: [
svelte(),
...(shell === 'web' ? [contentSecurityPolicy()] : []),
hopeLibrary(),
VitePWA({
// Off in the shell: `virtual:pwa-register` then gives a registerSW that does nothing,
// and no worker, manifest or register script is emitted (tauri-platforms.md D2).
disable: shell === 'tauri',
strategies: 'generateSW',
// Never swap a running app silently. A new worker waits until the player
// is offered a calm refresh control (CLAUDE.md §8, GAP_ANALYSIS G0.10).
registerType: 'prompt',
// The app registers the worker itself through virtual:pwa-register, so it hears
// when a new version is waiting (calm-refresh.md U1). Bundled, not inline: the
// CSP has no 'unsafe-inline' for scripts.
injectRegister: false,
manifest: {
// The web manifest: one of the three places the name lives, built from
// the constants in @rosea/schema so the strings exist only there.
name: PRODUCT_NAME,
short_name: PRODUCT_SHORT_NAME,
description: 'A rose to tend, a fox to befriend, and the time we give to people.',
id: BASE,
start_url: BASE,
scope: BASE,
display: 'standalone',
orientation: 'portrait',
background_color: '#fbf6f1',
theme_color: '#b4485e',
icons: [{ src: 'icon.svg', sizes: 'any', type: 'image/svg+xml', purpose: 'any' }]
},
workbox: {
// The cache name never contains the build hash; Workbox invalidates
// per entry from the precache manifest's revisions.
cacheId: 'rosea',
globPatterns: ['**/*.{js,css,html,svg,webmanifest}'],
navigateFallback: 'index.html',
// No runtime caching: the app makes no request it was not asked to make.
runtimeCaching: [],
cleanupOutdatedCaches: true,
// The first worker controls the page that registered it, so a player who
// opens the link once and loses signal still has the app.
clientsClaim: true,
skipWaiting: false
},
devOptions: { enabled: false }
})
],
server: { host: '127.0.0.1', strictPort: true },
preview: { host: '127.0.0.1', strictPort: true },
// The shell's copy has no source maps: they would ship inside every installer and APK.
build: { target: 'es2022', sourcemap: shell === 'web', outDir: shell === 'tauri' ? 'dist-tauri' : 'dist' }
};
});