diff --git a/apps/cli/__tests__/preview/known-project.test.ts b/apps/cli/__tests__/preview/known-project.test.ts index b431fc99..699d70cb 100644 --- a/apps/cli/__tests__/preview/known-project.test.ts +++ b/apps/cli/__tests__/preview/known-project.test.ts @@ -32,7 +32,7 @@ const PASITO_PKG = { }; describe('detectKnownProject — Remix exports', () => { - it('a MOBILE export with a server → the Expo detection the agent returns, with a server note', () => { + it('a MOBILE export with a server → the Expo detection the agent returns (the server starts beside it)', () => { write('package.json', PASITO_PKG); write('remix.json', { kind: 'MOBILE', template: 'expo-app', server: { db: true }, env: [] }); write('index.js', "import { registerRootComponent } from 'expo';"); @@ -48,13 +48,6 @@ describe('detectKnownProject — Remix exports', () => { }); // Never --tunnel: the Expo bring-up runs our own cloudflared. expect(got?.detection.args).not.toContain('--tunnel'); - expect(got?.detection.notes).toMatch(/server/); - }); - - it('a MOBILE export without a server has no note', () => { - write('package.json', PASITO_PKG); - write('remix.json', { kind: 'MOBILE', template: 'expo-app' }); - expect(detectKnownProject(dir)?.detection.notes).toBeUndefined(); }); it('an old MOBILE export without an expo dependency is still Expo (registerRootComponent entry)', () => { diff --git a/apps/cli/__tests__/preview/remix-app-server.test.ts b/apps/cli/__tests__/preview/remix-app-server.test.ts new file mode 100644 index 00000000..285fe6b6 --- /dev/null +++ b/apps/cli/__tests__/preview/remix-app-server.test.ts @@ -0,0 +1,220 @@ +/** + * A Remix project's own server in the console Preview (owner 2026-11-23): the same bindings the + * platform gives it (D1 as DB, ROOMS, env), and the same `/_v//` base the player hands + * the app — served on the preview's own origin by the app-server proxy. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { + devArgs, + migrationFiles, + migrationsApplyArgs, + readRemixServer, + remixServerPaths, + wranglerBinary, + wranglerConfigFor, + wranglerVersionFor, + writeWranglerConfig, + REMIX_SERVER_COMPATIBILITY_DATE, +} from '../../src/services/preview/remix-app-server'; +import { + isBundleRequest, + publicOriginOf, + routeFor, + serverBasePrelude, + serverRequestHeaders, + startAppServerProxy, +} from '../../src/services/preview/app-server-proxy'; + +let dir: string; +const write = (rel: string, content: unknown): void => { + const file = path.join(dir, rel); + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content)); +}; + +beforeEach(() => { + dir = mkdtempSync(path.join(tmpdir(), 'remix-server-')); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe('readRemixServer', () => { + it('reads remix.json "server" + "env" when server/index.ts exists', () => { + write('remix.json', { + kind: 'MOBILE', + server: { db: true, rooms: true }, + env: [ + { name: 'STRIPE_SECRET_KEY', secret: true, for: 'cards' }, + { name: 'PUBLIC_URL', secret: false, for: 'links' }, + { name: 'bad name', for: 'x' }, + ], + }); + write('server/index.ts', 'export default {}'); + expect(readRemixServer(dir)).toEqual({ + db: true, + rooms: true, + env: [ + { name: 'STRIPE_SECRET_KEY', secret: true }, + { name: 'PUBLIC_URL', secret: false }, + ], + }); + }); + it('null without a server declaration, or without server/index.ts', () => { + write('remix.json', { kind: 'MOBILE' }); + write('server/index.ts', 'x'); + expect(readRemixServer(dir)).toBeNull(); + write('remix.json', { kind: 'MOBILE', server: { db: true } }); + rmSync(path.join(dir, 'server'), { recursive: true }); + expect(readRemixServer(dir)).toBeNull(); + }); +}); + +describe('wrangler config — the platform bindings (remix-cloudflare.ts)', () => { + it('D1 as DB with the project migrations, ROOMS + rooms-v1, compat date + nodejs_compat', () => { + expect(wranglerConfigFor({ db: true, rooms: true, env: [] }, { PUBLIC_URL: 'https://x' })).toEqual({ + name: 'remix-local', + main: '../../server/index.ts', + compatibility_date: REMIX_SERVER_COMPATIBILITY_DATE, + compatibility_flags: ['nodejs_compat'], + d1_databases: [ + { binding: 'DB', database_name: 'remix-local', database_id: 'remix-local', migrations_dir: '../../server/migrations' }, + ], + durable_objects: { bindings: [{ name: 'ROOMS', class_name: 'Room' }] }, + migrations: [{ tag: 'rooms-v1', new_sqlite_classes: ['Room'] }], + vars: { PUBLIC_URL: 'https://x' }, + }); + }); + it('no db / rooms / vars → none of their keys', () => { + expect(Object.keys(wranglerConfigFor({ db: false, rooms: false, env: [] })).sort()).toEqual( + ['compatibility_date', 'compatibility_flags', 'main', 'name'].sort(), + ); + }); + it('writes plain values into vars and secrets into a 0600 .dev.vars, from the project .env', () => { + write('.env', 'STRIPE_SECRET_KEY=sk_test_1\nPUBLIC_URL=https://x\nOTHER=1\n'); + const { missing } = writeWranglerConfig(dir, { + db: true, + rooms: false, + env: [ + { name: 'STRIPE_SECRET_KEY', secret: true }, + { name: 'PUBLIC_URL', secret: false }, + { name: 'UNSET_ONE', secret: true }, + ], + }); + expect(missing).toEqual(['UNSET_ONE']); + const p = remixServerPaths(dir); + const config = JSON.parse(readFileSync(p.config, 'utf8')) as { vars?: Record }; + expect(config.vars).toEqual({ PUBLIC_URL: 'https://x' }); + expect(readFileSync(p.config, 'utf8')).not.toContain('sk_test_1'); + expect(readFileSync(p.devVars, 'utf8')).toBe('STRIPE_SECRET_KEY="sk_test_1"\n'); + if (process.platform !== 'win32') expect(statSync(p.devVars).mode & 0o777).toBe(0o600); + }); + it('migrations in file-name order; persisted state under .wrangler/state; loopback dev', () => { + write('server/migrations/0002_b.sql', ''); + write('server/migrations/0001_a.sql', ''); + write('server/migrations/notes.md', ''); + expect(migrationFiles(dir)).toEqual(['0001_a.sql', '0002_b.sql']); + const p = remixServerPaths(dir); + expect(p.state).toBe(path.join(dir, '.wrangler', 'state')); + expect(migrationsApplyArgs(dir)).toEqual(['d1', 'migrations', 'apply', 'DB', '--local', '--config', p.config, '--persist-to', p.state]); + const args = devArgs(dir, 4321, 4322); + expect(args.slice(0, 7)).toEqual(['dev', '--config', p.config, '--ip', '127.0.0.1', '--port', '4321']); + expect(args).toContain(p.state); + }); + it('wrangler: the project one, else a pinned install by Node major', () => { + expect(wranglerVersionFor('22.3.0')).toBe('4.158.0'); + expect(wranglerVersionFor('20.18.0')).toBe('4.85.0'); + const home = path.join(dir, 'home'); + const tool = wranglerBinary(dir, home, '4.158.0'); + expect(tool.installPrefix).toBe(path.join(home, '.codeam', 'tools', 'wrangler-4.158.0')); + write('node_modules/.bin/wrangler', '#!/bin/sh'); + expect(wranglerBinary(dir, home)).toEqual({ bin: path.join(dir, 'node_modules', '.bin', 'wrangler'), installPrefix: null }); + }); +}); + +describe('app-server proxy — routing like the platform Worker (dispatch.ts)', () => { + it('routes /_v/local/ to the server with the prefix stripped', () => { + expect(routeFor('/_v/local/api/items?x=1', false)).toEqual({ to: 'server', path: '/api/items?x=1' }); + expect(routeFor('/_v/local/auth/login', false)).toEqual({ to: 'server', path: '/auth/login' }); + expect(routeFor('/_v/local/api/_db/x', false)).toEqual({ to: 'dev' }); // the platform's own data API + expect(routeFor('/_v/local/index.html', false)).toEqual({ to: 'dev' }); + expect(routeFor('/api/items', false)).toEqual({ to: 'dev' }); // phone apps call through the base + expect(routeFor('/api/items', true)).toEqual({ to: 'server', path: '/api/items' }); // web: relative + expect(routeFor('/index.bundle?platform=web', true)).toEqual({ to: 'dev' }); + }); + it('recognises Metro bundles and the public origin', () => { + expect(isBundleRequest('/index.bundle?platform=ios&dev=true')).toBe(true); + expect(isBundleRequest('/node_modules/expo/AppEntry.bundle')).toBe(true); + expect(isBundleRequest('/index.bundle.map?x')).toBe(false); + expect(publicOriginOf({ host: 'abc.trycloudflare.com' })).toBe('https://abc.trycloudflare.com'); + expect(publicOriginOf({ host: 'localhost:9000', 'x-forwarded-host': 'p.example.com' })).toBe('https://p.example.com'); + expect(publicOriginOf({ host: '127.0.0.1:9000' })).toBe('http://127.0.0.1:9000'); + expect(serverBasePrelude('https://abc.trycloudflare.com')).toBe( + 'globalThis.__REMIX_SERVER_BASE__="https://abc.trycloudflare.com/_v/local/";', + ); + }); + it("sets the platform's identity headers and drops a client's forged ones", () => { + const h = serverRequestHeaders({ host: 'x', 'x-remix-app': 'forged', accept: 'a' }, 9, 'https://x'); + expect(h).toMatchObject({ + host: '127.0.0.1:9', + accept: 'a', + 'x-remix-app': 'local', + 'x-remix-version': 'local', + 'x-remix-env': 'dev', + 'x-remix-origin': 'https://x', + }); + }); +}); + +describe('app-server proxy — live', () => { + const listen = (handler: http.RequestListener): Promise => + new Promise((resolve) => { + const s = http.createServer(handler); + s.listen(0, '127.0.0.1', () => resolve(s)); + }); + const portOf = (s: http.Server): number => (s.address() as AddressInfo).port; + + it('serves the server on the same origin and prepends the base to JS bundles only', async () => { + const seen: string[] = []; + const appServer = await listen((req, res) => { + seen.push(`${req.method} ${req.url} app=${req.headers['x-remix-app']}`); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end('{"ok":true}'); + }); + const dev = await listen((req, res) => { + if (req.url?.startsWith('/index.bundle')) { + res.writeHead(200, { 'content-type': 'application/javascript', 'content-length': '7' }); + res.end('var a=1'); + } else if (req.url?.startsWith('/hbc.bundle')) { + res.writeHead(200, { 'content-type': 'application/x-metro-bytecode-bundle' }); + res.end('BYTES'); + } else { + res.writeHead(200, { 'content-type': 'text/html' }); + res.end(''); + } + }); + const proxy = await startAppServerProxy({ + devPort: portOf(dev), + serverPort: portOf(appServer), + injectBase: true, + routeRoot: false, + }); + try { + const base = `http://127.0.0.1:${proxy.port}`; + const api = await fetch(`${base}/_v/local/api/health`, { headers: { 'X-Remix-App': 'forged' } }); + expect(await api.json()).toEqual({ ok: true }); + expect(seen).toEqual(['GET /api/health app=local']); + const bundle = await (await fetch(`${base}/index.bundle?platform=web`)).text(); + expect(bundle).toBe(`globalThis.__REMIX_SERVER_BASE__="${base}/_v/local/";var a=1`); + expect(await (await fetch(`${base}/hbc.bundle?platform=ios`)).text()).toBe('BYTES'); + expect(await (await fetch(`${base}/`)).text()).toBe(''); + } finally { + await proxy.close(); + appServer.close(); + dev.close(); + } + }); +}); diff --git a/apps/cli/src/services/preview/app-server-proxy.ts b/apps/cli/src/services/preview/app-server-proxy.ts new file mode 100644 index 00000000..a197bcd1 --- /dev/null +++ b/apps/cli/src/services/preview/app-server-proxy.ts @@ -0,0 +1,190 @@ +import * as http from 'http'; +import * as net from 'net'; +import type { AddressInfo } from 'net'; +import { publicLocation, upstreamRequestHeaders } from './inspector-proxy'; +import { LOCAL_SERVER_PREFIX, LOCAL_VERSION_ID, REMIX_SERVER_PATH_RE } from './remix-app-server'; + +/** + * Puts a Remix app's own server (`wrangler dev`, see `remix-app-server.ts`) behind the preview's + * OWN origin, the way the platform Worker does (remix-worker `dispatch.ts`): + * + * cloudflared ──► :PROXY ──┬─► /_v/local/api/… (and the other server paths) ──► wrangler /api/… + * └─► everything else ──────────────────────────────► the dev server + * + * Same origin as the page, so no CORS and no second tunnel. The forwarded request carries the + * platform's identity headers (`X-Remix-App/-Version/-Env/-Origin`), set here so a client can't + * forge them — exactly as on Remix. + * + * A PHONE app finds its server at `globalThis.__REMIX_SERVER_BASE__` (the Remix player's prelude + * sets it to `/_v//`). Metro serves the app as `*.bundle` JS (web and Expo Go alike), + * so with `injectBase` the proxy PREPENDS that one assignment to every bundle response: it runs + * before any module of the app, the app's code is never edited, and the base is the public origin + * the request came in on (the tunnel host). A WEB app calls `api/…` relative to its page, so its + * server paths are also routed at the root (`routeRoot`). + * + * Transparent otherwise: other responses are piped byte for byte, websockets (Metro / Vite HMR) + * are tunnelled raw — to the server when the path is a server path (`/ws`), else to the dev server. + */ + +export interface AppServerProxyOptions { + /** The dev server (Metro / Vite). */ + devPort: number; + devHost?: string; + /** `wrangler dev`. */ + serverPort: number; + /** Prepend `__REMIX_SERVER_BASE__` to Metro bundles (phone apps). */ + injectBase: boolean; + /** Also route the server paths at the root (`/api/…`), for a web app's relative calls. */ + routeRoot: boolean; +} + +export interface AppServerProxy { + readonly port: number; + close(): Promise; +} + +/** Where a request goes: the app's server (with the path it sees) or the dev server. */ +export function routeFor( + url: string, + routeRoot: boolean, +): { to: 'server'; path: string } | { to: 'dev' } { + const q = url.indexOf('?'); + const pathname = q === -1 ? url : url.slice(0, q); + const search = q === -1 ? '' : url.slice(q); + if (pathname.startsWith(`${LOCAL_SERVER_PREFIX}/`)) { + const rel = pathname.slice(LOCAL_SERVER_PREFIX.length); + if (REMIX_SERVER_PATH_RE.test(rel)) return { to: 'server', path: rel + search }; + } + if (routeRoot && REMIX_SERVER_PATH_RE.test(pathname)) return { to: 'server', path: pathname + search }; + return { to: 'dev' }; +} + +/** A Metro bundle request (`/index.bundle?platform=web…`, `/node_modules/expo/AppEntry.bundle?…`). */ +export function isBundleRequest(url: string): boolean { + const q = url.indexOf('?'); + return /\.bundle$/.test(q === -1 ? url : url.slice(0, q)); +} + +const one = (v: string | string[] | undefined): string | undefined => (Array.isArray(v) ? v[0] : v); + +/** The public origin a request came in on: the tunnel's host over https, a loopback host over http. */ +export function publicOriginOf(headers: http.IncomingHttpHeaders): string { + const host = one(headers['x-forwarded-host']) ?? one(headers.host) ?? 'localhost'; + const loopback = /^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/i.test(host); + const proto = one(headers['x-forwarded-proto']) ?? (loopback ? 'http' : 'https'); + return `${proto}://${host}`; +} + +/** The statement prepended to a bundle: the player's `__REMIX_SERVER_BASE__`, for this origin. */ +export function serverBasePrelude(origin: string): string { + return `globalThis.__REMIX_SERVER_BASE__=${JSON.stringify(`${origin}${LOCAL_SERVER_PREFIX}/`)};`; +} + +/** The headers the server receives: the platform Worker's identity headers, never the client's. */ +export function serverRequestHeaders( + headers: http.IncomingHttpHeaders, + serverPort: number, + origin: string, +): http.OutgoingHttpHeaders { + const out: http.OutgoingHttpHeaders = { ...headers, host: `127.0.0.1:${serverPort}` }; + for (const k of Object.keys(out)) if (/^x-remix-/i.test(k)) delete out[k]; + out['x-remix-app'] = LOCAL_VERSION_ID; + out['x-remix-version'] = LOCAL_VERSION_ID; + out['x-remix-env'] = 'dev'; + out['x-remix-origin'] = origin; + return out; +} + +export async function startAppServerProxy(opts: AppServerProxyOptions): Promise { + const devHost = opts.devHost ?? '127.0.0.1'; + const upgraded = new Set(); + + const server = http.createServer((req, res) => { + const url = req.url ?? '/'; + const route = routeFor(url, opts.routeRoot); + const origin = publicOriginOf(req.headers); + const toServer = route.to === 'server'; + const inject = !toServer && opts.injectBase && isBundleRequest(url); + const headers = toServer + ? serverRequestHeaders(req.headers, opts.serverPort, origin) + : upstreamRequestHeaders(req.headers, opts.devPort); + // Can't prepend into compressed bytes: bundles come uncompressed through the proxy. + if (inject) delete headers['accept-encoding']; + const upstream = http.request( + { + host: toServer ? '127.0.0.1' : devHost, + port: toServer ? opts.serverPort : opts.devPort, + method: req.method, + path: toServer ? route.path : url, + headers, + }, + (originRes) => { + const outHeaders = { ...originRes.headers }; + if (!toServer) { + const location = publicLocation(originRes.headers.location, opts.devPort); + if (location !== undefined) outHeaders.location = location; + } + // Only into JS: a Hermes bytecode bundle or an error page is passed through untouched. + const js = /javascript/i.test(String(originRes.headers['content-type'] ?? '')); + const prepend = inject && js && (originRes.statusCode ?? 500) < 400; + if (prepend) delete outHeaders['content-length']; + res.writeHead(originRes.statusCode ?? 502, outHeaders); + if (prepend) res.write(serverBasePrelude(origin)); + originRes.pipe(res); + }, + ); + upstream.on('error', () => { + if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain' }); + res.end(toServer ? "the app's server is unreachable" : 'preview origin unreachable'); + }); + req.pipe(upstream); + }); + + server.on('upgrade', (req, clientSocket, head) => { + upgraded.add(clientSocket); + const url = req.url ?? '/'; + const route = routeFor(url, opts.routeRoot); + const toServer = route.to === 'server'; + const port = toServer ? opts.serverPort : opts.devPort; + const headers = toServer + ? serverRequestHeaders(req.headers, opts.serverPort, publicOriginOf(req.headers)) + : upstreamRequestHeaders(req.headers, opts.devPort); + const upstream = net.connect(port, toServer ? '127.0.0.1' : devHost, () => { + const lines = [`${req.method} ${toServer ? route.path : url} HTTP/1.1`]; + for (const [k, v] of Object.entries(headers)) { + for (const value of Array.isArray(v) ? v : [v]) { + if (value !== undefined) lines.push(`${k}: ${value}`); + } + } + upstream.write(`${lines.join('\r\n')}\r\n\r\n`); + if (head?.length) upstream.write(head); + upstream.pipe(clientSocket); + clientSocket.pipe(upstream); + }); + const drop = (): void => { + upgraded.delete(clientSocket); + upstream.destroy(); + clientSocket.destroy(); + }; + upstream.on('error', drop); + upstream.on('close', drop); + clientSocket.on('error', drop); + clientSocket.on('close', drop); + }); + + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', () => resolve()); + }); + const port = (server.address() as AddressInfo).port; + return { + port, + close: () => + new Promise((resolve) => { + for (const s of upgraded) s.destroy(); + upgraded.clear(); + server.closeAllConnections?.(); + server.close(() => resolve()); + }), + }; +} diff --git a/apps/cli/src/services/preview/index.ts b/apps/cli/src/services/preview/index.ts index d38b00af..54c9d736 100644 --- a/apps/cli/src/services/preview/index.ts +++ b/apps/cli/src/services/preview/index.ts @@ -16,6 +16,7 @@ export * from './run-setup'; export * from './setup-deps'; export * from './script-candidates'; export * from './known-project'; +export * from './remix-app-server'; export * from './prewarm-deps'; export * from './tunnel-bringup'; export * from './port-registry'; @@ -67,6 +68,11 @@ export interface ActivePreview { * proceso si nadie los mata. */ inspector?: { close(): Promise } | null; + /** + * A Remix app's own server (`wrangler dev`) and the proxy that puts it on the preview's origin + * (`remix-app-server.ts`, `app-server-proxy.ts`). Stopped with the preview. + */ + appServer?: { process: ChildProcess; proxy: { close(): Promise } | null } | null; } export const activePreviews = new Map(); @@ -159,6 +165,12 @@ export async function killPreview(sessionId: string): Promise { } catch { /* nunca bloquear el apagado */ } + try { + await preview.appServer?.proxy?.close(); + } catch { + /* nunca bloquear el apagado */ + } + if (preview.appServer) killProcessTree(preview.appServer.process, 'SIGTERM'); // Adoptado (`devServer === null`) = no es nuestro y no se toca. Parar el // preview cierra el túnel y el proxy; el dev server del usuario sigue como @@ -168,6 +180,7 @@ export async function killPreview(sessionId: string): Promise { const sigkillTimer = setTimeout(() => { if (preview.devServer) killProcessTree(preview.devServer, 'SIGKILL'); if (preview.tunnel) killProcessTree(preview.tunnel, 'SIGKILL'); + if (preview.appServer) killProcessTree(preview.appServer.process, 'SIGKILL'); }, 250); // Don't block process exit on this safety timer. sigkillTimer.unref?.(); diff --git a/apps/cli/src/services/preview/known-project.ts b/apps/cli/src/services/preview/known-project.ts index ee4d1ec5..f4473eed 100644 --- a/apps/cli/src/services/preview/known-project.ts +++ b/apps/cli/src/services/preview/known-project.ts @@ -38,10 +38,10 @@ type Pkg = { workspaces?: unknown; }; -type RemixConfig = { kind?: unknown; template?: unknown; server?: unknown }; +type RemixConfig = { kind?: unknown; template?: unknown }; /** The detect prompt's Expo shape, minus `--tunnel` (the Expo bring-up runs OUR tunnel). */ -const EXPO_DETECTION: Omit = { +const EXPO_DETECTION: PreviewDetection = { framework: 'Expo', command: 'npx', args: ['expo', 'start'], @@ -135,24 +135,14 @@ function viteDetection(pkg: Pkg): PreviewDetection | null { } /** - * The app's own server (`server/`, remix.json "server") is a Hono app for - * Cloudflare Workers + D1 that the Remix platform deploys; the client reaches - * it through `__REMIX_SERVER_BASE__`, which only the Remix players inject. The - * Preview brings up the CLIENT; say so instead of letting calls fail silently. + * A Remix export. Its own server (`server/`, remix.json "server") is started beside the front by + * the Preview start itself (`remix-app-server.ts`), so the detection is the front's alone. */ -const REMIX_SERVER_NOTE = - "The app's server (server/) runs on Cloudflare Workers once the app is published on Remix; " + - "the preview doesn't start it, so screens that call it show their error state here."; - function remixDetection(cwd: string, pkg: Pkg, remix: RemixConfig): KnownProjectDetection | null { - const hasServer = - (remix.server !== undefined && remix.server !== null) || - fs.existsSync(path.join(cwd, 'server', 'index.ts')); - const notes = hasServer ? { notes: REMIX_SERVER_NOTE } : {}; const mobile = remix.kind === 'MOBILE' || remix.template === 'expo-app' || isExpoApp(cwd, pkg); - if (mobile) return { kind: 'remix-mobile', detection: { ...EXPO_DETECTION, ...notes } }; + if (mobile) return { kind: 'remix-mobile', detection: { ...EXPO_DETECTION } }; const vite = viteDetection(pkg); - return vite ? { kind: 'remix-web', detection: { ...vite, ...notes } } : null; + return vite ? { kind: 'remix-web', detection: vite } : null; } /** The deterministic detection for `cwd`, or `null` when the agent should decide. */ diff --git a/apps/cli/src/services/preview/remix-app-server.ts b/apps/cli/src/services/preview/remix-app-server.ts new file mode 100644 index 00000000..221b191e --- /dev/null +++ b/apps/cli/src/services/preview/remix-app-server.ts @@ -0,0 +1,246 @@ +import { spawn, type ChildProcess } from 'child_process'; +import * as fs from 'fs'; +import * as net from 'net'; +import * as os from 'os'; +import * as path from 'path'; +import { parseDotenv } from './dotenv'; + +/** + * A Remix project's OWN SERVER, run in the console Preview the way the Remix platform runs it + * (owner 2026-11-23: "the server must work in the console exactly as on the feed/player"). + * + * How the platform runs it (codeagent-mobile, api-v2 `remix-server-deploy.ts` + + * `remix-cloudflare.ts`, remix-worker `dispatch.ts` / `prelude.ts`): + * - `server/index.ts` is a Cloudflare Worker (Hono), bundled with the `workerd` conditions and + * put in the Remix dispatch namespace with compatibility date `2026-08-01` + `nodejs_compat`; + * - remix.json "server"."db" → its own D1 bound as `DB`, migrations `server/migrations/*.sql` + * applied in file-name order; "rooms" → the script's `Room` class bound as `ROOMS` (SQLite + * Durable Object, migration tag `rooms-v1`); "env" → each name bound as a secret / plain var; + * - the platform Worker forwards `/_v//{api,auth,webhooks,ws,__cron,__check-env}/…` + * to the script with the version prefix stripped and `X-Remix-App/-Version/-Env/-Origin` + * headers set; a phone app finds it at `globalThis.__REMIX_SERVER_BASE__` = `/_v//`. + * + * Here: the same script under `wrangler dev` (workerd + a local D1 via miniflare) with a + * generated config carrying THE SAME bindings, the migrations applied to the local D1 first, its + * state kept in `/.wrangler/state` (survives restarts). `app-server-proxy.ts` puts it + * behind the preview's own origin exactly like the platform Worker does. + */ + +/** api-v2 `remix-cloudflare.ts` — change both. */ +export const REMIX_SERVER_COMPATIBILITY_DATE = '2026-08-01'; +export const REMIX_SERVER_COMPATIBILITY_FLAGS = ['nodejs_compat']; +export const REMIX_ROOMS_MIGRATION_TAG = 'rooms-v1'; +/** remix-worker `dispatch.ts` SERVER_PATH_RE — the paths the platform forwards to the script. */ +export const REMIX_SERVER_PATH_RE = /^\/(?:api(?!\/_db(?:\/|$))|auth|webhooks|ws|__cron|__check-env)(?:\/|$)/; +/** The "version" of a console preview: the base is `/_v/local/`, like `/_v//`. */ +export const LOCAL_VERSION_ID = 'local'; +export const LOCAL_SERVER_PREFIX = `/_v/${LOCAL_VERSION_ID}`; + +/** + * Wrangler, pinned. Node 22 (the Box image) gets a current one; an older Node the last wrangler + * whose engines accept it (4.85.0: node >=20.3). Both are kept outside the project + * (`~/.codeam/tools/`): the user's package.json and lockfile are theirs. + */ +export const WRANGLER_VERSION_NODE22 = '4.158.0'; +export const WRANGLER_VERSION_NODE20 = '4.85.0'; + +export interface RemixServerDecl { + db: boolean; + rooms: boolean; + /** The configuration names remix.json "env" declares, split as the platform binds them. */ + env: { name: string; secret: boolean }[]; +} + +const isRecord = (v: unknown): v is Record => + typeof v === 'object' && v !== null && !Array.isArray(v); + +/** remix.json "server" + `server/index.ts`, or `null` when the project has no server of its own. */ +export function readRemixServer(cwd: string): RemixServerDecl | null { + let raw: unknown; + try { + raw = JSON.parse(fs.readFileSync(path.join(cwd, 'remix.json'), 'utf8')); + } catch { + return null; + } + if (!isRecord(raw) || !isRecord(raw.server)) return null; + if (!fs.existsSync(path.join(cwd, 'server', 'index.ts'))) return null; + const env = Array.isArray(raw.env) + ? raw.env.flatMap((e) => + isRecord(e) && typeof e.name === 'string' && /^[A-Z][A-Z0-9_]*$/.test(e.name) + ? [{ name: e.name, secret: e.secret !== false }] + : [], + ) + : []; + return { db: raw.server.db === true, rooms: raw.server.rooms === true, env }; +} + +/** Where the generated config, `.dev.vars` and the local state live. */ +export function remixServerPaths(cwd: string): { dir: string; config: string; devVars: string; state: string } { + const dir = path.join(cwd, '.codeam', 'remix-server'); + return { + dir, + config: path.join(dir, 'wrangler.json'), + devVars: path.join(dir, '.dev.vars'), + state: path.join(cwd, '.wrangler', 'state'), + }; +} + +/** + * The wrangler config with the platform's bindings. Paths are relative to the config's folder + * (`.codeam/remix-server/`), which is how wrangler resolves them. Plain (non-secret) env values + * go in `vars`; secrets go in `.dev.vars` (never in this file, never in argv). + */ +export function wranglerConfigFor( + decl: RemixServerDecl, + plainVars: Record = {}, +): Record { + return { + name: 'remix-local', + main: '../../server/index.ts', + compatibility_date: REMIX_SERVER_COMPATIBILITY_DATE, + compatibility_flags: REMIX_SERVER_COMPATIBILITY_FLAGS, + ...(decl.db + ? { + d1_databases: [ + { + binding: 'DB', + database_name: 'remix-local', + database_id: 'remix-local', + migrations_dir: '../../server/migrations', + }, + ], + } + : {}), + ...(decl.rooms + ? { + durable_objects: { bindings: [{ name: 'ROOMS', class_name: 'Room' }] }, + migrations: [{ tag: REMIX_ROOMS_MIGRATION_TAG, new_sqlite_classes: ['Room'] }], + } + : {}), + ...(Object.keys(plainVars).length > 0 ? { vars: plainVars } : {}), + }; +} + +/** A `.dev.vars` line: the value JSON-quoted (wrangler reads dotenv syntax). */ +function devVarsText(values: Record): string { + return Object.entries(values) + .map(([k, v]) => `${k}=${JSON.stringify(v)}`) + .join('\n'); +} + +/** + * Writes the config + `.dev.vars`. The declared env names take their values from the project's + * `.env` (what the Environment Variables screen edits) — on Remix the owner types them in the + * app's settings; here they live in the project. A name with no value stays unset, exactly as an + * unsaved one on the platform. Returns the names left unset. + */ +export function writeWranglerConfig(cwd: string, decl: RemixServerDecl): { missing: string[] } { + const p = remixServerPaths(cwd); + let dotenv: Record = {}; + try { + dotenv = Object.fromEntries( + parseDotenv(fs.readFileSync(path.join(cwd, '.env'), 'utf8')).map((v) => [v.key, v.value]), + ); + } catch { + /* no .env: every value unset */ + } + const plain: Record = {}; + const secret: Record = {}; + const missing: string[] = []; + for (const e of decl.env) { + const v = dotenv[e.name]; + if (v === undefined || v === '') missing.push(e.name); + else (e.secret ? secret : plain)[e.name] = v; + } + fs.mkdirSync(p.dir, { recursive: true }); + fs.writeFileSync(p.config, `${JSON.stringify(wranglerConfigFor(decl, plain), null, 2)}\n`); + fs.writeFileSync(p.devVars, `${devVarsText(secret)}\n`, { mode: 0o600 }); + fs.chmodSync(p.devVars, 0o600); + return { missing }; +} + +/** The migrations wrangler will apply, in order (file names carry the NNNN prefix). */ +export function migrationFiles(cwd: string): string[] { + try { + return fs + .readdirSync(path.join(cwd, 'server', 'migrations')) + .filter((f) => f.endsWith('.sql')) + .sort(); + } catch { + return []; + } +} + +export function wranglerVersionFor(nodeVersion: string = process.versions.node): string { + return Number(nodeVersion.split('.')[0]) >= 22 ? WRANGLER_VERSION_NODE22 : WRANGLER_VERSION_NODE20; +} + +/** The wrangler binary to run: the project's own when it has one, else our pinned tool install. */ +export function wranglerBinary( + cwd: string, + home: string = os.homedir(), + version: string = wranglerVersionFor(), +): { bin: string; installPrefix: string | null } { + const own = path.join(cwd, 'node_modules', '.bin', 'wrangler'); + if (fs.existsSync(own)) return { bin: own, installPrefix: null }; + const prefix = path.join(home, '.codeam', 'tools', `wrangler-${version}`); + const bin = path.join(prefix, 'node_modules', '.bin', 'wrangler'); + return { bin, installPrefix: fs.existsSync(bin) ? null : prefix }; +} + +/** A free loopback port (bind 0, read it, release it). */ +export function freePort(): Promise { + return new Promise((resolve, reject) => { + const srv = net.createServer(); + srv.once('error', reject); + srv.listen(0, '127.0.0.1', () => { + const port = (srv.address() as net.AddressInfo).port; + srv.close(() => resolve(port)); + }); + }); +} + +/** Env every wrangler call runs with: no telemetry prompt, no update banner. */ +export function wranglerEnv(): Record { + return { WRANGLER_SEND_METRICS: 'false', WRANGLER_HIDE_BANNER: 'true', CI: '1' }; +} + +/** `wrangler d1 migrations apply DB --local` against the persisted state. */ +export function migrationsApplyArgs(cwd: string): string[] { + const p = remixServerPaths(cwd); + return ['d1', 'migrations', 'apply', 'DB', '--local', '--config', p.config, '--persist-to', p.state]; +} + +/** `wrangler dev` on loopback:`port`, local runtime, persisted state. */ +export function devArgs(cwd: string, port: number, inspectorPort: number): string[] { + const p = remixServerPaths(cwd); + return [ + 'dev', + '--config', + p.config, + '--ip', + '127.0.0.1', + '--port', + String(port), + '--persist-to', + p.state, + '--show-interactive-dev-session=false', + '--inspector-port', + String(inspectorPort), + ]; +} + +/** Spawns `wrangler dev` detached (its own group: teardown kills workerd with it). */ +export function spawnWranglerDev( + bin: string, + cwd: string, + port: number, + inspectorPort: number, +): ChildProcess { + return spawn(bin, devArgs(cwd, port, inspectorPort), { + cwd, + env: { ...process.env, ...wranglerEnv() }, + stdio: ['ignore', 'pipe', 'pipe'], + detached: process.platform !== 'win32', + }); +} diff --git a/apps/cli/src/services/preview/start-orchestrator.ts b/apps/cli/src/services/preview/start-orchestrator.ts index 38a133f0..d4517bb2 100644 --- a/apps/cli/src/services/preview/start-orchestrator.ts +++ b/apps/cli/src/services/preview/start-orchestrator.ts @@ -38,6 +38,8 @@ import { type ServedAddress, } from './served-address'; import type { InspectorProxy } from './inspector-proxy'; +import { startAppServerProxy, type AppServerProxy } from './app-server-proxy'; +import * as remixServer from './remix-app-server'; import { fetchNamedPreviewTunnel } from '../pairing.service'; import { stopExportTunnel } from '../../scratch/export-tunnel'; @@ -108,6 +110,15 @@ interface StageCtx extends PreviewStartArgs { * to these on the per-user SSE bus and renders the HANDSHAKE_LOG card. */ emitProgress: (step: string, message: string) => void; + /** A Remix app's own server, when the project has one (`remix-app-server.ts`). */ + appServer?: AppServerUp; +} + +/** The app's own server under `wrangler dev`, and the proxy that puts it on the preview's origin. */ +interface AppServerUp { + process: ReturnType; + port: number; + proxy: AppServerProxy | null; } /** @@ -360,21 +371,143 @@ export async function runPreviewStart(args: PreviewStartArgs): Promise { if (!(await provisionDeps(ctx))) return; - // Expo inverts the order — tunnel FIRST, then the dev server — because Expo - // reads the public URL (`EXPO_PACKAGER_PROXY_URL`) from its env at startup. - // Every other framework keeps dev server → tunnel. See `./expo.ts`. - if (detection.framework === 'Expo') { - await runExpoBringUp(ctx); - return; + // A Remix project's own server (`server/`) runs beside the front, the way the platform runs it. + // Started BEFORE the dev server so the front's first request finds it; torn down below unless + // the preview was registered with it (every failure path after this point). + const decl = remixServer.readRemixServer(ctx.cwd); + if (decl) { + const up = await startAppServer(ctx, decl); + if (!up) return; + ctx.appServer = up; } + try { + // Expo inverts the order — tunnel FIRST, then the dev server — because Expo + // reads the public URL (`EXPO_PACKAGER_PROXY_URL`) from its env at startup. + // Every other framework keeps dev server → tunnel. See `./expo.ts`. + if (detection.framework === 'Expo') { + await runExpoBringUp(ctx); + return; + } + + const dev = await startDevServer(ctx); + if (!dev) return; + + const fronted = await frontWithAppServer(ctx, dev); + if (!fronted) return; + + const tun = await establishTunnel(ctx, fronted); + if (!tun) return; + + announceReady(ctx, dev, tun); + } finally { + const own = ctx.appServer; + if (own && previewSvc.activePreviews.get(sessionId)?.appServer !== own) stopAppServer(own); + } +} - const dev = await startDevServer(ctx); - if (!dev) return; +/** How long `wrangler dev` gets to bind its port (workerd's first start included). */ +const APP_SERVER_READY_TIMEOUT_MS = 90_000; + +/** + * The app's own server: config with the platform's bindings, the D1 migrations, then + * `wrangler dev` on a free loopback port. `null` after emitting the terminal `preview_error`. + */ +async function startAppServer( + ctx: StageCtx, + decl: remixServer.RemixServerDecl, +): Promise { + const { emit, emitProgress, cwd } = ctx; + const fail = (message: string): null => { + emit(USER_EVENTS.PREVIEW_ERROR, { stage: 'spawn', message }); + return null; + }; + const { missing } = remixServer.writeWranglerConfig(cwd, decl); + if (missing.length > 0) { + log.info('preview', `app server: ${missing.join(', ')} not set in .env — left unset, as on Remix`); + } + const { bin, installPrefix } = remixServer.wranglerBinary(cwd); + if (installPrefix) { + const version = remixServer.wranglerVersionFor(); + emitProgress('SETUP_RUN', `npm install wrangler@${version} (the app's server runtime)`); + const r = await previewSvc.runSetupCommand( + 'npm', + ['install', '--no-save', '--no-audit', '--no-fund', '--prefix', installPrefix, `wrangler@${version}`], + cwd, + undefined, + { timeoutMs: INSTALL_TIMEOUT_MS }, + ); + if (r.status !== 'ok' || !fs.existsSync(bin)) { + return fail(`The app's server needs wrangler, and installing it failed (${r.status}). Check the network and retry.`); + } + } + if (decl.db && remixServer.migrationFiles(cwd).length > 0) { + emitProgress('SETUP_RUN', 'wrangler d1 migrations apply DB --local'); + const r = await previewSvc.runSetupCommand( + bin, + remixServer.migrationsApplyArgs(cwd), + cwd, + remixServer.wranglerEnv(), + { timeoutMs: INSTALL_TIMEOUT_MS }, + ); + if (r.status !== 'ok') { + return fail( + `The app's database migrations (server/migrations) failed to apply (${r.status}). ` + + 'The debug log has the statement that failed.', + ); + } + } + const port = await remixServer.freePort(); + const inspectorPort = await remixServer.freePort(); + emitProgress('BOOT_SEQUENCE', `wrangler dev (the app's server) on :${port}`); + const child = remixServer.spawnWranglerDev(bin, cwd, port, inspectorPort); + let tail = ''; + const onChunk = (b: Buffer): void => { + tail = (tail + b.toString('utf8')).slice(-4_000); + }; + child.stdout?.on('data', onChunk); + child.stderr?.on('data', onChunk); + child.on('error', (err) => onChunk(Buffer.from(String(err)))); + const exited = new Promise<'exited'>((resolve) => child.once('exit', () => resolve('exited'))); + const ready = previewSvc + .waitForPortListening(port, { timeoutMs: APP_SERVER_READY_TIMEOUT_MS, intervalMs: 300 }) + .then((ok) => (ok ? ('ready' as const) : ('timeout' as const))); + const outcome = await Promise.race([ready, exited]); + if (outcome !== 'ready') { + previewSvc.killProcessTree(child, 'SIGKILL'); + log.info('preview', `app server failed (${outcome}):\n${tail}`); + const reason = stripAnsi(tail).trim().split('\n').slice(-6).join('\n'); + return fail(`The app's server (server/) didn't start${reason ? `:\n${reason}` : '.'}`); + } + log.info('preview', `app server: wrangler dev ready on :${port}`); + return { process: child, port, proxy: null }; +} - const tun = await establishTunnel(ctx, dev); - if (!tun) return; +function stopAppServer(up: AppServerUp): void { + void up.proxy?.close().catch(() => undefined); + previewSvc.killProcessTree(up.process, 'SIGTERM'); +} - announceReady(ctx, dev, tun); +/** + * A web app with its own server: the dev server is fronted by the app-server proxy, so the page's + * relative `api/…` calls reach the server on the same origin. Without a server, `dev` unchanged. + */ +async function frontWithAppServer(ctx: StageCtx, dev: DevServerUp): Promise { + const up = ctx.appServer; + if (!up) return dev; + try { + up.proxy = await startAppServerProxy({ + devPort: dev.served.port, + devHost: dev.served.host, + serverPort: up.port, + injectBase: false, + routeRoot: true, + }); + } catch (err) { + if (dev.devServer) previewSvc.killProcessTree(dev.devServer, 'SIGTERM'); + ctx.emit(USER_EVENTS.PREVIEW_ERROR, { stage: 'spawn', message: `The app's server proxy failed: ${String(err)}` }); + return null; + } + return { ...dev, served: { ...dev.served, host: '127.0.0.1', port: up.proxy.port } }; } /** @@ -411,14 +544,38 @@ async function runExpoBringUp(ctx: StageCtx): Promise { if (!web) emitProgress('SETUP_RUN', `web packages not installed (${r.status}) — Expo Go only`); } + // The app's own server: Metro behind the app-server proxy, which serves the server on the same + // origin and hands the app its `__REMIX_SERVER_BASE__` (prepended to every bundle). + let tunnelPort = detection.port; + if (ctx.appServer) { + try { + ctx.appServer.proxy = await startAppServerProxy({ + devPort: detection.port, + serverPort: ctx.appServer.port, + injectBase: true, + routeRoot: false, + }); + tunnelPort = ctx.appServer.proxy.port; + } catch (err) { + emit(USER_EVENTS.PREVIEW_ERROR, { stage: 'spawn', message: `The app's server proxy failed: ${String(err)}` }); + return; + } + } emitProgress('TUNNEL_STARTING', `cloudflared quick tunnel → Expo :${detection.port}`); - const pub = await bringUpPublicUrl(ctx, detection.port); + const pub = await bringUpPublicUrl(ctx, tunnelPort); if (!pub.ok) { emit(USER_EVENTS.PREVIEW_ERROR, { stage: 'tunnel', message: pub.message }); return; } - const dev = await startDevServer(ctx, { [previewSvc.EXPO_PACKAGER_PROXY_URL_ENV]: pub.url }); + const dev = await startDevServer(ctx, { + [previewSvc.EXPO_PACKAGER_PROXY_URL_ENV]: pub.url, + // A Remix MOBILE export has .tsx files and no `typescript` dependency: without this, a + // non-interactive `expo start` exits ("you're trying to use TypeScript but don't have the + // required dependencies installed"). Metro transpiles TS with Babel; the preview never + // type-checks, so the prerequisite is skipped instead of installing anything. + EXPO_NO_TYPESCRIPT_SETUP: '1', + }); if (!dev) { // Terminal event already emitted (error, or a `preview_ready` reuse that // has its own tunnel) — don't leak the connector we brought up first. @@ -446,6 +603,7 @@ function announceReady(ctx: StageCtx, dev: DevServerUp, tun: TunnelUp): void { devServer: dev.devServer, tunnel: tun.tunnel, inspector: tun.inspector, + appServer: ctx.appServer ?? null, url: tun.url, expoGoUrl: tun.expoGoUrl, framework: detection.framework,