chore(dev): add production preview launcher

This commit is contained in:
Tommaso Casaburi
2026-05-30 17:26:58 +07:00
parent ac95e58433
commit 8cc9c401d3
6 changed files with 317 additions and 159 deletions
@@ -0,0 +1,36 @@
{
"task": "dev-overhead-preview",
"last_updated": "2026-05-28",
"items": [
{
"id": "F001",
"priority": 1,
"status": "verified",
"description": "Add a production-like local preview launcher and make the normal dev launcher clearly identify its dev-mode overhead.",
"verification": [
"./scripts/agent-init.sh --smoke",
"BROWSER=none corepack yarn start",
"BROWSER=none corepack yarn start:preview",
"curl -k -I https://codex-chore-dev-overhead-preview.5chan.localhost",
"SMOKE_BASE_URL=https://codex-chore-dev-overhead-preview.5chan.localhost/#/ node scripts/smoke-web-app.js",
"playwright-cli Chrome /pol thread/back timing",
"playwright-cli Firefox/WebKit /pol load checks",
"PORTLESS=0 BROWSER=none PORT=4990 corepack yarn start:preview",
"curl -I http://127.0.0.1:4990",
"corepack yarn build",
"corepack yarn lint",
"corepack yarn type-check",
"corepack yarn knip"
],
"files": [
"package.json",
"scripts/start-dev.js",
"scripts/start-preview.js",
"scripts/local-server-utils.mjs",
"docs/agent-runs/dev-overhead-preview/feature-list.json",
"docs/agent-runs/dev-overhead-preview/progress.md"
],
"notes": "Handoff source: /var/folders/6_/_kkfxkkn33j830_dt_gj0zqh0000gn/T/5chan-dev-overhead-handoff-2026-05-28T23-25-32.md. Preview /pol browser-back-to-board timings in Chrome were 170ms, 125ms, and 120ms."
}
]
}
@@ -0,0 +1,21 @@
# Progress Log
Append one entry per session.
## 2026-05-28 23:31
- Item: F001
- Summary: Created the `codex/chore/dev-overhead-preview` worktree, read the dev-overhead handoff, and confirmed the baseline smoke flow passes before implementation.
- Files: `docs/agent-runs/dev-overhead-preview/feature-list.json`, `docs/agent-runs/dev-overhead-preview/progress.md`
- Verification: `./scripts/agent-init.sh --smoke`
- Blockers: none
- Next: Add the preview launcher and verify both dev and preview startup paths.
## 2026-05-28 23:44
- Item: F001
- Summary: Added `yarn start:preview`, refactored shared Portless launcher helpers, and added a concise `yarn start` terminal note that points performance checks to the preview launcher.
- Files: `package.json`, `scripts/start-dev.js`, `scripts/start-preview.js`, `scripts/local-server-utils.mjs`, `docs/agent-runs/dev-overhead-preview/feature-list.json`, `docs/agent-runs/dev-overhead-preview/progress.md`
- Verification: `corepack yarn install`; `node --check scripts/start-dev.js && node --check scripts/start-preview.js && node --check scripts/local-server-utils.mjs`; `BROWSER=none corepack yarn start`; `BROWSER=none corepack yarn start:preview`; `curl -k -I https://codex-chore-dev-overhead-preview.5chan.localhost`; `SMOKE_BASE_URL=https://codex-chore-dev-overhead-preview.5chan.localhost/#/ node scripts/smoke-web-app.js`; `playwright-cli` Chrome `/pol` thread/back timing (back: 170ms, 125ms, 120ms); `playwright-cli` Firefox/WebKit `/pol` load checks; `corepack yarn build`; `corepack yarn lint`; `corepack yarn type-check`; `corepack yarn knip`; `PORTLESS=0 BROWSER=none PORT=4990 corepack yarn start:preview`; `curl -I http://127.0.0.1:4990`
- Blockers: none
- Next: Review the diff and decide whether to also make dev-only `react-scan`/`element-source` opt-in in a separate, workflow-synced change.
+1
View File
@@ -64,6 +64,7 @@
"prebuild": "corepack yarn sync:directories && corepack yarn generate:assets",
"prestart": "corepack yarn sync:directories && corepack yarn generate:assets",
"start": "node scripts/start-dev.js",
"start:preview": "node scripts/start-preview.js",
"start:android-usb": "node scripts/start-android-usb.mjs",
"build": "cross-env PUBLIC_URL=./ GENERATE_SOURCEMAP=false vite build",
"build:fdroid": "cross-env PUBLIC_URL=./ GENERATE_SOURCEMAP=false VITE_APP_DISTRIBUTION=fdroid vite build",
+167
View File
@@ -0,0 +1,167 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { spawn, spawnSync } from 'node:child_process';
import { get as httpGet } from 'node:http';
import { get as httpsGet } from 'node:https';
export const isWindows = process.platform === 'win32';
export const usePortless = process.env.PORTLESS !== '0' && !isWindows;
export const binDir = join(process.cwd(), 'node_modules', '.bin');
export const executableSuffix = isWindows ? '.cmd' : '';
export const portlessBin = join(binDir, `portless${executableSuffix}`);
export const viteBin = join(binDir, `vite${executableSuffix}`);
export const fallbackHost = '127.0.0.1';
export const fallbackUrlHost = 'localhost';
export const portlessProxyPort = process.env.PORTLESS_PORT || '443';
export const portlessEnv = {
...process.env,
PORTLESS_PORT: portlessProxyPort,
PORTLESS_HTTPS: process.env.PORTLESS_HTTPS ?? '1',
PORTLESS_LAN: process.env.PORTLESS_LAN ?? '0',
};
export function getLocalServerCommand() {
return usePortless && existsSync(portlessBin) ? portlessBin : viteBin;
}
export function sanitizeLabel(value) {
return value
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.replace(/-{2,}/g, '-');
}
export function getCurrentBranch() {
const result = spawnSync('git', ['branch', '--show-current'], {
cwd: process.cwd(),
encoding: 'utf8',
});
if (result.status !== 0) {
return null;
}
const branch = result.stdout.trim();
return branch || null;
}
export function getActivePortlessRouteHosts() {
const result = spawnSync(portlessBin, ['list'], {
cwd: process.cwd(),
encoding: 'utf8',
env: process.env,
});
if (result.status !== 0) {
return new Set();
}
const matches = result.stdout.match(/https?:\/\/[a-z0-9.-]+\.localhost(?::\d+)?/g) || [];
return new Set(matches.map((url) => new URL(url).hostname));
}
export function isRouteBusy(activeRouteHosts, appName) {
return activeRouteHosts.has(`${appName}.localhost`);
}
export function getPreferredPortlessAppName(activeRouteHosts) {
const branch = getCurrentBranch();
const branchLabel = sanitizeLabel(branch || 'current');
if (branch && branch !== 'master' && branch !== 'main') {
return `${branchLabel}.5chan`;
}
if (isRouteBusy(activeRouteHosts, '5chan')) {
return `${branchLabel}.5chan`;
}
return '5chan';
}
export function getPortlessAppName() {
const activeRouteHosts = getActivePortlessRouteHosts();
const preferredAppName = getPreferredPortlessAppName(activeRouteHosts);
if (!isRouteBusy(activeRouteHosts, preferredAppName)) {
return preferredAppName;
}
for (let suffix = 2; suffix < 1000; suffix += 1) {
const candidate = `${preferredAppName}-${suffix}`;
if (!isRouteBusy(activeRouteHosts, candidate)) {
return candidate;
}
}
return `${preferredAppName}-${Date.now()}`;
}
export function ensurePortlessProxy() {
const result = spawnSync(portlessBin, ['proxy', 'start', '--port', portlessProxyPort, '--https'], {
cwd: process.cwd(),
env: portlessEnv,
stdio: 'inherit',
});
if (result.status !== 0) {
process.exit(result.status ?? 1);
}
}
export async function waitForUrlReady(url, timeoutMs) {
const startedAt = Date.now();
while (Date.now() - startedAt < timeoutMs) {
const ready = await new Promise((resolve) => {
const parsedUrl = new URL(url);
const getUrl = parsedUrl.protocol === 'https:' ? httpsGet : httpGet;
const onResponse = (response) => {
response.resume();
const statusCode = response.statusCode ?? 500;
resolve(statusCode >= 200 && statusCode < 400);
};
const request = parsedUrl.protocol === 'https:' ? getUrl(parsedUrl, { rejectUnauthorized: false }, onResponse) : getUrl(parsedUrl, onResponse);
request.on('error', () => resolve(false));
request.setTimeout(2_000, () => {
request.destroy();
resolve(false);
});
});
if (ready) {
return;
}
await new Promise((resolve) => setTimeout(resolve, 200));
}
throw new Error(`Timed out waiting for ${url}`);
}
export function openInBrowser(url) {
const opener =
process.platform === 'darwin'
? { cmd: 'open', args: [url] }
: process.platform === 'win32'
? { cmd: 'cmd', args: ['/c', 'start', '""', url] }
: { cmd: 'xdg-open', args: [url] };
spawn(opener.cmd, opener.args, { stdio: 'ignore', detached: true }).unref();
}
export function forwardChildExit(child) {
child.on('exit', (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 0);
});
}
+16 -159
View File
@@ -1,117 +1,23 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { spawn, spawnSync } from 'node:child_process';
import { get as httpGet } from 'node:http';
import { get as httpsGet } from 'node:https';
import { spawn } from 'node:child_process';
import {
ensurePortlessProxy,
fallbackHost,
fallbackUrlHost,
forwardChildExit,
getLocalServerCommand,
getPortlessAppName,
openInBrowser,
portlessBin,
portlessEnv,
waitForUrlReady,
} from './local-server-utils.mjs';
import { resolvePort } from './dev-server-utils.mjs';
const isWindows = process.platform === 'win32';
const usePortless = process.env.PORTLESS !== '0' && !isWindows;
const binDir = join(process.cwd(), 'node_modules', '.bin');
const executableSuffix = isWindows ? '.cmd' : '';
const portlessBin = join(binDir, `portless${executableSuffix}`);
const viteBin = join(binDir, `vite${executableSuffix}`);
const fallbackHost = '127.0.0.1';
const fallbackUrlHost = 'localhost';
const fallbackRequestedPort = Number(process.env.PORT) || 3000;
const portlessProxyPort = process.env.PORTLESS_PORT || '443';
const portlessEnv = {
...process.env,
PORTLESS_PORT: portlessProxyPort,
PORTLESS_HTTPS: process.env.PORTLESS_HTTPS ?? '1',
PORTLESS_LAN: process.env.PORTLESS_LAN ?? '0',
};
function sanitizeLabel(value) {
return value
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.replace(/-{2,}/g, '-');
}
console.log('Note: yarn start runs Vite/React in development mode. Use yarn start:preview for production-like local performance checks.');
function getCurrentBranch() {
const result = spawnSync('git', ['branch', '--show-current'], {
cwd: process.cwd(),
encoding: 'utf8',
});
if (result.status !== 0) {
return null;
}
const branch = result.stdout.trim();
return branch || null;
}
function getActivePortlessRouteHosts() {
const result = spawnSync(portlessBin, ['list'], {
cwd: process.cwd(),
encoding: 'utf8',
env: process.env,
});
if (result.status !== 0) {
return new Set();
}
const matches = result.stdout.match(/https?:\/\/[a-z0-9.-]+\.localhost(?::\d+)?/g) || [];
return new Set(matches.map((url) => new URL(url).hostname));
}
function isRouteBusy(activeRouteHosts, appName) {
return activeRouteHosts.has(`${appName}.localhost`);
}
function getPreferredPortlessAppName(activeRouteHosts) {
const branch = getCurrentBranch();
const branchLabel = sanitizeLabel(branch || 'current');
if (branch && branch !== 'master' && branch !== 'main') {
return `${branchLabel}.5chan`;
}
if (isRouteBusy(activeRouteHosts, '5chan')) {
return `${branchLabel}.5chan`;
}
return '5chan';
}
function getPortlessAppName() {
const activeRouteHosts = getActivePortlessRouteHosts();
const preferredAppName = getPreferredPortlessAppName(activeRouteHosts);
if (!isRouteBusy(activeRouteHosts, preferredAppName)) {
return preferredAppName;
}
for (let suffix = 2; suffix < 1000; suffix += 1) {
const candidate = `${preferredAppName}-${suffix}`;
if (!isRouteBusy(activeRouteHosts, candidate)) {
return candidate;
}
}
return `${preferredAppName}-${Date.now()}`;
}
function ensurePortlessProxy() {
const result = spawnSync(portlessBin, ['proxy', 'start', '--port', portlessProxyPort, '--https'], {
cwd: process.cwd(),
env: portlessEnv,
stdio: 'inherit',
});
if (result.status !== 0) {
process.exit(result.status ?? 1);
}
}
const command = usePortless && existsSync(portlessBin) ? portlessBin : viteBin;
const command = getLocalServerCommand();
let args;
let publicUrl = null;
@@ -158,53 +64,4 @@ if (publicUrl && process.env.BROWSER !== 'none') {
});
}
child.on('exit', (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 0);
});
async function waitForUrlReady(url, timeoutMs) {
const startedAt = Date.now();
while (Date.now() - startedAt < timeoutMs) {
const ready = await new Promise((resolve) => {
const parsedUrl = new URL(url);
const getUrl = parsedUrl.protocol === 'https:' ? httpsGet : httpGet;
const onResponse = (response) => {
response.resume();
const statusCode = response.statusCode ?? 500;
resolve(statusCode >= 200 && statusCode < 400);
};
const request = parsedUrl.protocol === 'https:' ? getUrl(parsedUrl, { rejectUnauthorized: false }, onResponse) : getUrl(parsedUrl, onResponse);
request.on('error', () => resolve(false));
request.setTimeout(2_000, () => {
request.destroy();
resolve(false);
});
});
if (ready) {
return;
}
await new Promise((resolve) => setTimeout(resolve, 200));
}
throw new Error(`Timed out waiting for ${url}`);
}
function openInBrowser(url) {
const opener =
process.platform === 'darwin'
? { cmd: 'open', args: [url] }
: process.platform === 'win32'
? { cmd: 'cmd', args: ['/c', 'start', '""', url] }
: { cmd: 'xdg-open', args: [url] };
spawn(opener.cmd, opener.args, { stdio: 'ignore', detached: true }).unref();
}
forwardChildExit(child);
+76
View File
@@ -0,0 +1,76 @@
import { spawn, spawnSync } from 'node:child_process';
import {
ensurePortlessProxy,
fallbackHost,
fallbackUrlHost,
forwardChildExit,
getLocalServerCommand,
getPortlessAppName,
openInBrowser,
portlessBin,
portlessEnv,
usePortless,
waitForUrlReady,
} from './local-server-utils.mjs';
import { resolvePort } from './dev-server-utils.mjs';
const fallbackRequestedPort = Number(process.env.PORT) || 4173;
console.log('Building production preview with corepack yarn build...');
const build = spawnSync('corepack', ['yarn', 'build'], {
cwd: process.cwd(),
env: process.env,
stdio: 'inherit',
});
if (build.status !== 0) {
process.exit(build.status ?? 1);
}
const command = getLocalServerCommand();
let args;
let publicUrl = null;
if (command === portlessBin) {
ensurePortlessProxy();
const appName = getPortlessAppName();
publicUrl = `https://${appName}.localhost`;
args = [appName, 'vite', 'preview'];
console.log(`Starting Portless production preview at ${publicUrl}`);
} else {
const port = await resolvePort(fallbackRequestedPort);
const fallbackUrl = `http://${fallbackUrlHost}:${port}`;
args = ['preview', '--host', fallbackHost, '--port', String(port), '--strictPort'];
if (usePortless) {
console.warn(`portless unavailable on this platform, using vite preview directly on ${fallbackUrl}`);
} else {
console.log(`Starting Vite production preview directly at ${fallbackUrl}`);
}
if (port !== fallbackRequestedPort) {
console.log(`Preferred preview port ${fallbackRequestedPort} is busy, so this run will use ${fallbackUrl}.`);
}
}
const child = spawn(command, args, {
stdio: 'inherit',
env: command === portlessBin ? portlessEnv : process.env,
});
if (publicUrl && process.env.BROWSER !== 'none') {
waitForUrlReady(publicUrl, 30_000)
.then(() => {
console.log(`Opening ${publicUrl} in browser...`);
openInBrowser(publicUrl);
})
.catch((error) => {
console.warn(`Could not auto-open ${publicUrl}: ${error.message}`);
});
}
forwardChildExit(child);