[repo] Workspace: Scaffold Phase 0 with schema, engine, content, ui and the PWA shell
pnpm + turbo workspace with the commands from CLAUDE.md §3. The contracts from §6 as JSON Schemas with generated types; localDay as the one place a day is computed; the forbidden-word list shared by lint:copy and the library validator, with 13 negative fixtures; a Svelte 5 PWA shell built under /Rosea/ with a meta CSP. E2E and offline suites run against the built bundle; the offline one closes the server rather than emulating. Analysis: .agents/features/phase0-workspace.md
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { PRODUCT_NAME } from '@rosea/schema';
|
||||
import { en } from '@rosea/ui/copy';
|
||||
import { startStaticServer } from './static-server.js';
|
||||
|
||||
/**
|
||||
* The offline suite. CLAUDE.md §3 describes its full shape: tend the rose, walk
|
||||
* a planet, watch a sunset, close the tab, reopen, assert everything survived.
|
||||
* Phase 0 has no rose, so this proves the part everything else will stand on:
|
||||
* the app opens with no server anywhere, under its real base path.
|
||||
*
|
||||
* The server is genuinely CLOSED, not emulated: `context.setOffline` acts before
|
||||
* the service worker and would test the harness instead (imported from Ludus).
|
||||
*/
|
||||
test('the shell opens from the service worker with the server gone', async ({ browser }) => {
|
||||
const server = await startStaticServer();
|
||||
const context = await browser.newContext();
|
||||
let serverOpen = true;
|
||||
|
||||
try {
|
||||
const page = await context.newPage();
|
||||
await page.goto(server.url);
|
||||
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
|
||||
// `clientsClaim` makes the FIRST worker control the page that registered it.
|
||||
// Without it, a player who opens the link once and loses signal has nothing.
|
||||
await page.waitForFunction(() => navigator.serviceWorker.controller !== null, null, { timeout: 20_000 });
|
||||
await page.waitForFunction(
|
||||
async () => {
|
||||
for (const name of await caches.keys()) {
|
||||
const cache = await caches.open(name);
|
||||
if ((await cache.keys()).some((r) => r.url.includes('index.html'))) return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
null,
|
||||
{ timeout: 20_000 }
|
||||
);
|
||||
|
||||
await server.close();
|
||||
serverOpen = false;
|
||||
|
||||
// Proof the network is really gone, from outside the browser.
|
||||
await expect(fetch(server.url)).rejects.toThrow();
|
||||
|
||||
// 1. Reload the open tab.
|
||||
await page.reload();
|
||||
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
await expect(page.getByText(en.shell.preparing)).toBeVisible();
|
||||
|
||||
// 2. Close the tab and open a fresh one: a cold start, the shape of a player
|
||||
// coming back days later with no signal.
|
||||
await page.close();
|
||||
const again = await context.newPage();
|
||||
await again.goto(server.url);
|
||||
await expect(again.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
|
||||
// 3. A deep link inside the scope falls back to the shell, not an error page.
|
||||
await again.goto(`${server.url}somewhere/deeper`);
|
||||
await expect(again.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
} finally {
|
||||
// A test run leaves the machine as it found it (CLAUDE.md §5.7).
|
||||
await context.close();
|
||||
if (serverOpen) await server.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* The main e2e suite. Runs against the BUILT bundle (`pnpm test:e2e` builds it
|
||||
* first), served by a server each spec starts on a free port, so there is no
|
||||
* port table to keep and no dev server to mistake for the product (CLAUDE.md §3).
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: '.',
|
||||
testMatch: /shell\.spec\.ts/,
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
retries: 0,
|
||||
reporter: [['list']],
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
trace: 'retain-on-failure'
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* The offline suite — the product's central claim (CLAUDE.md §3). Separate
|
||||
* from the main suite because it asks a different question: not "does it
|
||||
* render" but "does it render with no server in the world".
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: '.',
|
||||
testMatch: /offline\.spec\.ts/,
|
||||
fullyParallel: false,
|
||||
workers: 1,
|
||||
retries: 0,
|
||||
reporter: [['list']],
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
trace: 'retain-on-failure'
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import AxeBuilder from '@axe-core/playwright';
|
||||
import { expect, test, type Page } from '@playwright/test';
|
||||
import { PRODUCT_NAME } from '@rosea/schema';
|
||||
import { en } from '@rosea/ui/copy';
|
||||
import { BASE, startStaticServer, type StaticServer } from './static-server.js';
|
||||
|
||||
let server: StaticServer;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
server = await startStaticServer();
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await server.close();
|
||||
});
|
||||
|
||||
/** Opens the app and records every request and every CSP violation on the way. */
|
||||
async function open(page: Page): Promise<{ requests: string[]; cspViolations: string[] }> {
|
||||
const requests: string[] = [];
|
||||
const cspViolations: string[] = [];
|
||||
page.on('request', (r) => requests.push(r.url()));
|
||||
page.on('console', (m) => {
|
||||
if (m.type() === 'error' && /Content Security Policy/i.test(m.text())) cspViolations.push(m.text());
|
||||
});
|
||||
await page.goto(server.url);
|
||||
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
|
||||
// Let the worker register and precache, so its requests are counted too.
|
||||
await page.waitForFunction(() => navigator.serviceWorker.ready.then(() => true), null, { timeout: 20_000 });
|
||||
return { requests, cspViolations };
|
||||
}
|
||||
|
||||
test('the built app renders its name and its one line, under the base path', async ({ page }) => {
|
||||
await open(page);
|
||||
await expect(page.getByText(en.shell.preparing)).toBeVisible();
|
||||
await expect(page).toHaveTitle(PRODUCT_NAME);
|
||||
});
|
||||
|
||||
test('nothing is requested from any other origin', async ({ page }) => {
|
||||
const { requests } = await open(page);
|
||||
expect(requests.length, 'the page must have made requests for this to mean anything').toBeGreaterThan(0);
|
||||
expect(requests.filter((url) => !url.startsWith(server.origin + '/'))).toEqual([]);
|
||||
});
|
||||
|
||||
test('nothing is written to cookies or Web Storage', async ({ page }) => {
|
||||
await open(page);
|
||||
const written = await page.evaluate(() => ({
|
||||
cookie: document.cookie,
|
||||
localStorage: localStorage.length,
|
||||
sessionStorage: sessionStorage.length
|
||||
}));
|
||||
expect(written).toEqual({ cookie: '', localStorage: 0, sessionStorage: 0 });
|
||||
expect(await page.context().cookies()).toEqual([]);
|
||||
});
|
||||
|
||||
test('the built page carries the CSP and no inline script, and nothing violates it', async ({ page }) => {
|
||||
const { cspViolations } = await open(page);
|
||||
const html = await (await fetch(server.url)).text();
|
||||
|
||||
// Read from the DOM, not the raw HTML: Vite escapes the quotes as '.
|
||||
const csp = await page.locator('meta[http-equiv="Content-Security-Policy"]').getAttribute('content');
|
||||
expect(csp, 'CSP meta tag in the built index.html').toBeTruthy();
|
||||
expect(csp).toContain("default-src 'self'");
|
||||
expect(csp).not.toContain('unsafe-inline');
|
||||
expect(csp).not.toContain('unsafe-eval');
|
||||
|
||||
const inline = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g)].filter(
|
||||
([, attrs, body]) => !/\bsrc=/.test(attrs ?? '') && (body ?? '').trim() !== ''
|
||||
);
|
||||
expect(inline.map(([tag]) => tag)).toEqual([]);
|
||||
expect(cspViolations).toEqual([]);
|
||||
});
|
||||
|
||||
test('manifest scope, start_url and the service worker scope all equal the base path', async ({ page }) => {
|
||||
await open(page);
|
||||
|
||||
const manifestHref = await page.locator('link[rel="manifest"]').getAttribute('href');
|
||||
expect(manifestHref, 'manifest link').toBeTruthy();
|
||||
const manifest = (await (await fetch(new URL(manifestHref!, server.url))).json()) as Record<string, unknown>;
|
||||
|
||||
expect(manifest['scope']).toBe(BASE);
|
||||
expect(manifest['start_url']).toBe(BASE);
|
||||
expect(manifest['name']).toBe(PRODUCT_NAME);
|
||||
|
||||
const swScope = await page.evaluate(async () => (await navigator.serviceWorker.ready).scope);
|
||||
expect(swScope).toBe(server.url);
|
||||
|
||||
// The icon the manifest names must exist where the manifest says it is.
|
||||
const icons = manifest['icons'] as { src: string }[];
|
||||
for (const icon of icons) {
|
||||
const res = await fetch(new URL(icon.src, new URL(manifestHref!, server.url)));
|
||||
expect(res.status, icon.src).toBe(200);
|
||||
}
|
||||
});
|
||||
|
||||
test('the shell has no accessibility violations', async ({ page }) => {
|
||||
await open(page);
|
||||
const results = await new AxeBuilder({ page }).analyze();
|
||||
expect(results.violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { createReadStream, statSync } from 'node:fs';
|
||||
import { createServer, type Server } from 'node:http';
|
||||
import { extname, join, normalize, sep } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
/**
|
||||
* A throwaway static server for the BUILT app, under the test's control.
|
||||
*
|
||||
* It serves `apps/rosea/dist` under the same base path GitHub Pages will use
|
||||
* (`/Rosea/` unless ROSEA_BASE says otherwise), and 404s everything outside it.
|
||||
* Serving at `/` would hide every base-path bug (CLAUDE.md §8).
|
||||
*
|
||||
* It exists for the offline suite too. Playwright's `context.setOffline` and
|
||||
* `route().abort()` both act before the service worker is consulted, so they
|
||||
* test the harness and not the cache (imported from Ludus). The only honest
|
||||
* "no network" is no server: start one, let the worker precache, close it.
|
||||
*
|
||||
* Binds 127.0.0.1 on port 0, so the OS picks a free port (CLAUDE.md §5.7).
|
||||
*/
|
||||
|
||||
export const BASE = process.env['ROSEA_BASE'] ?? '/Rosea/';
|
||||
const DIST = fileURLToPath(new URL('../apps/rosea/dist', import.meta.url));
|
||||
|
||||
const MIME: Record<string, string> = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.webmanifest': 'application/manifest+json; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.map': 'application/json; charset=utf-8'
|
||||
};
|
||||
|
||||
export interface StaticServer {
|
||||
/** The app's URL, base path included, e.g. http://127.0.0.1:53211/Rosea/ */
|
||||
readonly url: string;
|
||||
readonly origin: string;
|
||||
readonly close: () => Promise<void>;
|
||||
}
|
||||
|
||||
export async function startStaticServer(): Promise<StaticServer> {
|
||||
try {
|
||||
statSync(join(DIST, 'index.html'));
|
||||
} catch (error) {
|
||||
throw new Error(`No built app at ${DIST}. Run \`pnpm build\` first. (${String(error)})`);
|
||||
}
|
||||
|
||||
const server: Server = createServer((req, res) => {
|
||||
const path = decodeURIComponent((req.url ?? '/').split('?')[0] ?? '/');
|
||||
|
||||
if (!path.startsWith(BASE)) {
|
||||
res.writeHead(404, { 'content-type': 'text/plain' });
|
||||
res.end(`outside ${BASE}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const rel = normalize(path.slice(BASE.length) || 'index.html');
|
||||
const file = join(DIST, rel);
|
||||
// Confine to DIST: a test server is still a server.
|
||||
if (!file.startsWith(DIST + sep) && file !== DIST) {
|
||||
res.writeHead(403).end();
|
||||
return;
|
||||
}
|
||||
|
||||
let target = file;
|
||||
try {
|
||||
if (statSync(target).isDirectory()) target = join(target, 'index.html');
|
||||
statSync(target);
|
||||
} catch {
|
||||
// Not on disk: an honest 404, which is what Pages would send.
|
||||
res.writeHead(404, { 'content-type': 'text/plain' });
|
||||
res.end('not found');
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(200, {
|
||||
'content-type': MIME[extname(target)] ?? 'application/octet-stream',
|
||||
// No HTTP cache, so whatever loads after the server is gone came from the
|
||||
// service worker and not from the browser's own cache.
|
||||
'cache-control': 'no-store'
|
||||
});
|
||||
createReadStream(target).pipe(res);
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === 'string') throw new Error('static server did not bind a port');
|
||||
|
||||
const origin = `http://127.0.0.1:${address.port}`;
|
||||
return {
|
||||
origin,
|
||||
url: `${origin}${BASE}`,
|
||||
close: () =>
|
||||
new Promise<void>((resolve) => {
|
||||
server.closeAllConnections();
|
||||
server.close(() => resolve());
|
||||
})
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user