// THE PACK-ASSET SEAM (runtime contract R20). A pack may ship bytes it serves byte-for-byte — // clerk's vendored clerk-js dist (136 files, 14.5 MB) — that are neither // committed text (size) nor world-state blobs (R11's seam is keyed under a world's state root // and filled by requests). They are PACK assets: read-only, versioned with the package, the // same on every world. This seam is how a pack reaches them without touching a host: the // pack declares them on its descriptor (`assets`), reads them through `getActivePackAssets()`, // and the SHELL binds the store — the Bun shell reads the pack's own tree, workerd the // static-assets binding. A pack that reads its tree // with Bun.file or import.meta is host-bound (R12b); one that reads through here is not. // No node builtins at module scope: `@volter/world-core`'s index re-exports this module and a browser // bundle pulls the index in, so a static `node:fs`/`node:url` import here would break it. The local store reads through Bun's file // API at call time; the worker store never touches a filesystem. import { existsSync, readFileSync, statSync } from 'node:fs'; export interface PackAssetStore { /** The asset at `relPath` inside the pack `vendor`'s directory (e.g. `client/clerk.browser.js`), * as a Response carrying the bytes and a content type — or null when the pack ships no such * file. `relPath` is confined to the pack's own tree: a traversal never resolves. */ fetch(vendor: string, relPath: string): Promise; } const CONTENT_TYPES: Record = { '.js': 'application/javascript; charset=utf-8', '.mjs': 'application/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.html': 'text/html; charset=utf-8', '.json': 'application/json; charset=utf-8', '.map': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.woff': 'font/woff', '.txt': 'text/plain; charset=utf-8', }; export function assetContentType(relPath: string): string { const dot = relPath.lastIndexOf('.'); return (dot >= 0 ? CONTENT_TYPES[relPath.slice(dot)] : undefined) ?? 'application/octet-stream'; } /** A relative path confined to a pack's tree: no absolute, no `..`, no empty segment. */ export function confinedAssetPath(relPath: string): string | null { if (relPath.startsWith('/') || relPath.includes('\\') || relPath.includes('\0')) return null; const segs = relPath.split('/'); if (segs.some((s) => s === '' || s === '.' || s === '..')) return null; return segs.join('/'); } /** The host's store: a pack-directory resolver, or a catalog root ending in a slash. */ export class LocalPackAssets implements PackAssetStore { constructor(private readonly twinDir: string | ((vendor: string) => string | undefined | Promise)) {} async fetch(vendor: string, relPath: string): Promise { const safe = confinedAssetPath(relPath); if (safe === null || !/^[a-z][a-z0-9-]*$/.test(vendor)) return null; const dir = typeof this.twinDir === 'string' ? `${this.twinDir}${vendor}` : await this.twinDir(vendor); if (dir === undefined) return null; const file = `${dir}/${safe}`; // confined: no `..`, no absolute, no empty segment (above) if (!existsSync(file) || !statSync(file).isFile()) { // a file of a package the pack pins (vendor//…) is the take's: absent, the take did not run, said by twin, // package and version, never the vendor's not-found and never a fallback const taken = /^vendor\/((?:@[^/]+\/)?[^/]+)\/(.+)$/.exec(safe); // the take placed the package's declared files or none of them: its folder absent is the take not run; a file the // package does not hold, with the folder there, is the vendor's not-found (the pack's own fallback answers it) if (taken && !existsSync(`${dir}/vendor/${taken[1]}`)) { // the pin is the pack's, or for a lane its vendor root's, as the take reads it (twin-standard take.ts pinnedVersion) let pin: string | undefined; for (let at = dir, i = 0; i < 3 && pin === undefined; at = at.replace(/\/[^/]+$/, ''), i++) { if (existsSync(`${at}/package.json`)) pin = (JSON.parse(readFileSync(`${at}/package.json`, 'utf8')) as { devDependencies?: Record }).devDependencies?.[taken[1]!]; } if (pin !== undefined) throw new Error(`twin ${vendor}: ${taken[1]}@${pin}'s ${taken[2]} is not at ${safe}: the take did not run (\`twin-standard take\`, run by the pack checkout's install and by \`twin-standard pack\`)`); } return null; } return new Response(readFileSync(file), { status: 200, headers: { 'content-type': assetContentType(safe) } }); } } let active: PackAssetStore | undefined; /** The bound store — the Bun shell's local tree unless a shell bound another. */ export function getActivePackAssets(): PackAssetStore { if (active === undefined) active = new LocalPackAssets(async (vendor) => { const { vendorPackageDir } = await import('./pack-paths.ts'); const { fileURLToPath } = await import('node:url'); return vendorPackageDir(process.cwd(), vendor) ?? vendorPackageDir(fileURLToPath(new URL('.', import.meta.url)), vendor); }); return active; } export function setActivePackAssets(store: PackAssetStore): PackAssetStore | undefined { const previous = active; active = store; return previous; } /** `getActivePackAssets().fetch(...)` with the pack's declared fallback: the first path that exists. */ export async function packAsset(vendor: string, ...candidates: string[]): Promise { const store = getActivePackAssets(); for (const c of candidates) { const r = await store.fetch(vendor, c); if (r !== null) return r; } return null; }