@timber-js/app 0.1.25 → 0.1.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/nitro.d.ts +9 -0
- package/dist/adapters/nitro.d.ts.map +1 -1
- package/dist/adapters/nitro.js +171 -4
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/package.json +1 -1
- package/src/adapters/nitro.ts +178 -3
- package/src/cli.ts +1 -1
package/dist/adapters/nitro.d.ts
CHANGED
|
@@ -55,6 +55,15 @@ export declare function nitro(options?: NitroAdapterOptions): TimberPlatformAdap
|
|
|
55
55
|
export declare function generateNitroEntry(buildDir: string, outDir: string, preset: NitroPreset, hasManifestInit?: boolean): string;
|
|
56
56
|
/** @internal Exported for testing. */
|
|
57
57
|
export declare function generateNitroConfig(preset: NitroPreset, userConfig?: Record<string, unknown>): string;
|
|
58
|
+
/**
|
|
59
|
+
* Generate a standalone preview server script that uses Node's built-in
|
|
60
|
+
* HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports
|
|
61
|
+
* h3 which isn't available outside a Nitro build. For local preview we
|
|
62
|
+
* just need to serve static files and route requests to the RSC handler.
|
|
63
|
+
*
|
|
64
|
+
* @internal Exported for testing.
|
|
65
|
+
*/
|
|
66
|
+
export declare function generatePreviewScript(buildDir: string, preset: NitroPreset): string;
|
|
58
67
|
/** Command descriptor for Nitro preview — testable without spawning. */
|
|
59
68
|
export interface NitroPreviewCommand {
|
|
60
69
|
command: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nitro.d.ts","sourceRoot":"","sources":["../../src/adapters/nitro.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,qBAAqB,EAAgB,MAAM,SAAS,CAAC;AAqBnE;;;;;GAKG;AACH,MAAM,MAAM,WAAW,GACnB,QAAQ,GACR,aAAa,GACb,SAAS,GACT,cAAc,GACd,YAAY,GACZ,a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sD;IACtD,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAuED,qCAAqC;AACrC,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IAErB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACvC;AAID;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,KAAK,CAAC,OAAO,GAAE,mBAAwB,GAAG,qBAAqB,CAsE9E;AAID,sCAAsC;AACtC,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,WAAW,EACnB,eAAe,UAAQ,GACtB,MAAM,CA6CR;AAED,sCAAsC;AACtC,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,WAAW,EACnB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACnC,MAAM,CAwBR;AAOD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,MAAM,CA+JnF;AAED,wEAAwE;AACxE,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;CACb;AAED,sCAAsC;AACtC,wBAAgB,2BAA2B,CACzC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,WAAW,GAClB,mBAAmB,GAAG,IAAI,CAY5B;AAgBD;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,WAAW,GAAG,YAAY,CAEjE"}
|
package/dist/adapters/nitro.js
CHANGED
|
@@ -121,9 +121,10 @@ function nitro(options = {}) {
|
|
|
121
121
|
await writeFile(join(outDir, "nitro.config.ts"), nitroConfig);
|
|
122
122
|
},
|
|
123
123
|
preview: LOCALLY_PREVIEWABLE.has(preset) ? async (_config, buildDir) => {
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
await
|
|
124
|
+
const previewScript = generatePreviewScript(buildDir, preset);
|
|
125
|
+
const scriptPath = join(buildDir, "nitro", "_preview-server.mjs");
|
|
126
|
+
await writeFile(scriptPath, previewScript);
|
|
127
|
+
await spawnNitroPreview(preset === "bun" ? "bun" : "node", [scriptPath], join(buildDir, "nitro"));
|
|
127
128
|
} : void 0,
|
|
128
129
|
waitUntil: presetConfig.supportsWaitUntil ? (promise) => {
|
|
129
130
|
const tracked = promise.catch((err) => {
|
|
@@ -183,6 +184,172 @@ export default defineNitroConfig(${JSON.stringify(config, null, 2)})
|
|
|
183
184
|
}
|
|
184
185
|
/** Presets that produce a locally-runnable server entry. */
|
|
185
186
|
var LOCALLY_PREVIEWABLE = new Set(["node-server", "bun"]);
|
|
187
|
+
/**
|
|
188
|
+
* Generate a standalone preview server script that uses Node's built-in
|
|
189
|
+
* HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports
|
|
190
|
+
* h3 which isn't available outside a Nitro build. For local preview we
|
|
191
|
+
* just need to serve static files and route requests to the RSC handler.
|
|
192
|
+
*
|
|
193
|
+
* @internal Exported for testing.
|
|
194
|
+
*/
|
|
195
|
+
function generatePreviewScript(buildDir, preset) {
|
|
196
|
+
const rscEntryRelative = relative(join(buildDir, "nitro"), join(buildDir, "rsc", "index.js"));
|
|
197
|
+
const rscEntry = rscEntryRelative.startsWith(".") ? rscEntryRelative : "./" + rscEntryRelative;
|
|
198
|
+
const publicDir = "./public";
|
|
199
|
+
const manifestInitPath = "./_timber-manifest-init.js";
|
|
200
|
+
return `// Generated by @timber-js/app — standalone preview server.
|
|
201
|
+
// Uses Node's built-in HTTP server to serve static assets and route
|
|
202
|
+
// dynamic requests through the RSC handler. No Nitro/h3 dependency.
|
|
203
|
+
|
|
204
|
+
import { createServer } from 'node:http';
|
|
205
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
206
|
+
import { join, extname } from 'node:path';
|
|
207
|
+
import { fileURLToPath } from 'node:url';
|
|
208
|
+
import { existsSync } from 'node:fs';
|
|
209
|
+
|
|
210
|
+
// Set runtime before importing the handler.
|
|
211
|
+
process.env.TIMBER_RUNTIME = '${PRESET_CONFIGS[preset].runtimeName}';
|
|
212
|
+
|
|
213
|
+
// Load the build manifest if it exists.
|
|
214
|
+
const __dirname = fileURLToPath(new URL('.', import.meta.url));
|
|
215
|
+
const manifestPath = join(__dirname, '${manifestInitPath}');
|
|
216
|
+
if (existsSync(manifestPath)) {
|
|
217
|
+
await import('${manifestInitPath}');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Import the RSC handler (default export is the fetch-like handler).
|
|
221
|
+
const { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');
|
|
222
|
+
|
|
223
|
+
const MIME_TYPES = {
|
|
224
|
+
'.html': 'text/html',
|
|
225
|
+
'.js': 'application/javascript',
|
|
226
|
+
'.mjs': 'application/javascript',
|
|
227
|
+
'.css': 'text/css',
|
|
228
|
+
'.json': 'application/json',
|
|
229
|
+
'.png': 'image/png',
|
|
230
|
+
'.jpg': 'image/jpeg',
|
|
231
|
+
'.jpeg': 'image/jpeg',
|
|
232
|
+
'.gif': 'image/gif',
|
|
233
|
+
'.svg': 'image/svg+xml',
|
|
234
|
+
'.ico': 'image/x-icon',
|
|
235
|
+
'.woff': 'font/woff',
|
|
236
|
+
'.woff2': 'font/woff2',
|
|
237
|
+
'.ttf': 'font/ttf',
|
|
238
|
+
'.otf': 'font/otf',
|
|
239
|
+
'.webp': 'image/webp',
|
|
240
|
+
'.avif': 'image/avif',
|
|
241
|
+
'.webm': 'video/webm',
|
|
242
|
+
'.mp4': 'video/mp4',
|
|
243
|
+
'.txt': 'text/plain',
|
|
244
|
+
'.xml': 'application/xml',
|
|
245
|
+
'.wasm': 'application/wasm',
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
const publicDir = join(__dirname, '${publicDir}');
|
|
249
|
+
const port = parseInt(process.env.PORT || '3000', 10);
|
|
250
|
+
|
|
251
|
+
const server = createServer(async (req, res) => {
|
|
252
|
+
const url = new URL(req.url || '/', \`http://localhost:\${port}\`);
|
|
253
|
+
|
|
254
|
+
// Try serving static files from the public directory first.
|
|
255
|
+
const filePath = join(publicDir, url.pathname);
|
|
256
|
+
// Prevent path traversal.
|
|
257
|
+
if (filePath.startsWith(publicDir)) {
|
|
258
|
+
try {
|
|
259
|
+
const fileStat = await stat(filePath);
|
|
260
|
+
if (fileStat.isFile()) {
|
|
261
|
+
const ext = extname(filePath);
|
|
262
|
+
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
|
|
263
|
+
const body = await readFile(filePath);
|
|
264
|
+
// Hashed assets get immutable cache, others get short cache.
|
|
265
|
+
const cacheControl = url.pathname.startsWith('/assets/')
|
|
266
|
+
? 'public, max-age=31536000, immutable'
|
|
267
|
+
: 'public, max-age=3600, must-revalidate';
|
|
268
|
+
res.writeHead(200, {
|
|
269
|
+
'Content-Type': contentType,
|
|
270
|
+
'Content-Length': body.length,
|
|
271
|
+
'Cache-Control': cacheControl,
|
|
272
|
+
});
|
|
273
|
+
res.end(body);
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
} catch {
|
|
277
|
+
// File not found — fall through to the RSC handler.
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Convert Node request to Web Request.
|
|
282
|
+
const headers = new Headers();
|
|
283
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
284
|
+
if (value) {
|
|
285
|
+
if (Array.isArray(value)) {
|
|
286
|
+
for (const v of value) headers.append(key, v);
|
|
287
|
+
} else {
|
|
288
|
+
headers.set(key, value);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
let body = undefined;
|
|
294
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
295
|
+
body = await new Promise((resolve) => {
|
|
296
|
+
const chunks = [];
|
|
297
|
+
req.on('data', (chunk) => chunks.push(chunk));
|
|
298
|
+
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const webRequest = new Request(url.href, {
|
|
303
|
+
method: req.method,
|
|
304
|
+
headers,
|
|
305
|
+
body,
|
|
306
|
+
duplex: body ? 'half' : undefined,
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
try {
|
|
310
|
+
// Support 103 Early Hints when available.
|
|
311
|
+
const earlyHintsSender = (typeof res.writeEarlyHints === 'function')
|
|
312
|
+
? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }
|
|
313
|
+
: undefined;
|
|
314
|
+
|
|
315
|
+
const webResponse = earlyHintsSender && runWithEarlyHintsSender
|
|
316
|
+
? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))
|
|
317
|
+
: await handler(webRequest);
|
|
318
|
+
|
|
319
|
+
// Write the response back to the Node response.
|
|
320
|
+
res.writeHead(webResponse.status, Object.fromEntries(webResponse.headers.entries()));
|
|
321
|
+
|
|
322
|
+
if (webResponse.body) {
|
|
323
|
+
const reader = webResponse.body.getReader();
|
|
324
|
+
const pump = async () => {
|
|
325
|
+
while (true) {
|
|
326
|
+
const { done, value } = await reader.read();
|
|
327
|
+
if (done) { res.end(); return; }
|
|
328
|
+
res.write(value);
|
|
329
|
+
}
|
|
330
|
+
};
|
|
331
|
+
await pump();
|
|
332
|
+
} else {
|
|
333
|
+
res.end();
|
|
334
|
+
}
|
|
335
|
+
} catch (err) {
|
|
336
|
+
console.error('[timber preview] Request error:', err);
|
|
337
|
+
if (!res.headersSent) {
|
|
338
|
+
res.writeHead(500, { 'Content-Type': 'text/plain' });
|
|
339
|
+
}
|
|
340
|
+
res.end('Internal Server Error');
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
server.listen(port, () => {
|
|
345
|
+
console.log();
|
|
346
|
+
console.log(' ⚡ timber preview server running at:');
|
|
347
|
+
console.log();
|
|
348
|
+
console.log(\` ➜ http://localhost:\${port}\`);
|
|
349
|
+
console.log();
|
|
350
|
+
});
|
|
351
|
+
`;
|
|
352
|
+
}
|
|
186
353
|
/** @internal Exported for testing. */
|
|
187
354
|
function generateNitroPreviewCommand(buildDir, preset) {
|
|
188
355
|
if (!LOCALLY_PREVIEWABLE.has(preset)) return null;
|
|
@@ -213,6 +380,6 @@ function getPresetConfig(preset) {
|
|
|
213
380
|
return PRESET_CONFIGS[preset];
|
|
214
381
|
}
|
|
215
382
|
//#endregion
|
|
216
|
-
export { generateNitroConfig, generateNitroEntry, generateNitroPreviewCommand, getPresetConfig, nitro };
|
|
383
|
+
export { generateNitroConfig, generateNitroEntry, generateNitroPreviewCommand, generatePreviewScript, getPresetConfig, nitro };
|
|
217
384
|
|
|
218
385
|
//# sourceMappingURL=nitro.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nitro.js","names":[],"sources":["../../src/adapters/nitro.ts"],"sourcesContent":["// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { writeFile, mkdir, cp } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\n// Inlined from server/asset-headers.ts — adapters are loaded by Node at\n// Vite startup time, before Vite's module resolver is available, so cross-\n// directory .ts imports don't resolve.\nconst IMMUTABLE_CACHE = 'public, max-age=31536000, immutable';\nconst STATIC_CACHE = 'public, max-age=3600, must-revalidate';\n\nfunction generateHeadersFile(): string {\n return `# Auto-generated by @timber-js/app — static asset cache headers.\n# See design/25-production-deployments.md §\"CDN / Edge Cache\"\n\n/assets/*\n Cache-Control: ${IMMUTABLE_CACHE}\n\n/*\n Cache-Control: ${STATIC_CACHE}\n`;\n}\n\n// ─── Presets ─────────────────────────────────────────────────────────────────\n\n/**\n * Supported Nitro deployment presets.\n *\n * Each preset maps to a Nitro deployment target. The adapter generates\n * the appropriate configuration and entry point for the selected platform.\n */\nexport type NitroPreset =\n | 'vercel'\n | 'vercel-edge'\n | 'netlify'\n | 'netlify-edge'\n | 'aws-lambda'\n | 'deno-deploy'\n | 'azure-functions'\n | 'node-server'\n | 'bun';\n\n/** Preset-specific Nitro configuration. */\ninterface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nconst PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: true,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: true,\n runtimeName: 'bun',\n },\n};\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/** Options for the Nitro adapter. */\nexport interface NitroAdapterOptions {\n /**\n * Deployment preset. Determines the target platform.\n * @default 'node-server'\n */\n preset?: NitroPreset;\n\n /**\n * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: Record<string, unknown>;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const presetConfig = PRESET_CONFIGS[preset];\n const pendingPromises: Promise<unknown>[] = [];\n\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'nitro');\n await mkdir(outDir, { recursive: true });\n\n // Copy client assets to public directory.\n // When client JavaScript is disabled, skip .js files — only CSS,\n // fonts, images, and other static assets are needed.\n const clientDir = join(buildDir, 'client');\n const publicDir = join(outDir, 'public');\n await mkdir(publicDir, { recursive: true });\n await cp(clientDir, publicDir, {\n recursive: true,\n filter: config.clientJavascriptDisabled ? (src: string) => !src.endsWith('.js') : undefined,\n }).catch(() => {\n // Client dir may not exist when client JavaScript is disabled\n });\n\n // Write _headers file for platforms that support it (Netlify, etc.).\n // See design/25-production-deployments.md §\"CDN / Edge Cache\"\n await writeFile(join(publicDir, '_headers'), generateHeadersFile());\n\n // Write the build manifest init module (if manifest data was produced).\n if (config.manifestInit) {\n await writeFile(join(outDir, '_timber-manifest-init.js'), config.manifestInit);\n }\n\n // Generate the Nitro entry point\n const hasManifestInit = !!config.manifestInit;\n const entry = generateNitroEntry(buildDir, outDir, preset, hasManifestInit);\n await writeFile(join(outDir, 'entry.ts'), entry);\n\n // Generate the Nitro config with static asset cache rules\n const nitroConfig = generateNitroConfig(preset, options.nitroConfig);\n await writeFile(join(outDir, 'nitro.config.ts'), nitroConfig);\n },\n\n // Only presets that produce a locally-runnable server get preview().\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no\n // local runtime — Vite's built-in preview is the fallback.\n preview: LOCALLY_PREVIEWABLE.has(preset)\n ? async (_config: TimberConfig, buildDir: string) => {\n const cmd = generateNitroPreviewCommand(buildDir, preset);\n if (!cmd) return;\n await spawnNitroPreview(cmd.command, cmd.args, cmd.cwd);\n }\n : undefined,\n\n waitUntil: presetConfig.supportsWaitUntil\n ? (promise: Promise<unknown>) => {\n const tracked = promise.catch((err) => {\n console.error('[timber] waitUntil promise rejected:', err);\n });\n pendingPromises.push(tracked);\n }\n : undefined,\n };\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n buildDir: string,\n outDir: string,\n preset: NitroPreset,\n hasManifestInit = false\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // The Vite RSC plugin outputs it to rsc/index.js.\n let serverEntryRelative = relative(outDir, join(buildDir, 'rsc', 'index.js'));\n // Ensure the import path starts with ./ for ESM compatibility\n if (!serverEntryRelative.startsWith('.')) {\n serverEntryRelative = './' + serverEntryRelative;\n }\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n\n // Build manifest init must be imported before the handler so that\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set when the virtual module evaluates.\n const manifestImport = hasManifestInit ? \"import './_timber-manifest-init.js'\\n\" : '';\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n const handlerCall = earlyHints\n ? ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`\n : ` const webResponse = await handler(webRequest)`;\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\n${manifestImport}import { defineEventHandler, toWebRequest, sendWebResponse } from 'h3'\nimport handler, { runWithEarlyHintsSender } from '${serverEntryRelative}'\n\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\nexport default defineEventHandler(async (event) => {\n const webRequest = toWebRequest(event)\n${handlerCall}\n return sendWebResponse(event, webResponse)\n})\n`;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroConfig(\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): string {\n const presetConfig = PRESET_CONFIGS[preset];\n\n const config: Record<string, unknown> = {\n preset: presetConfig.nitroPreset,\n output: { dir: presetConfig.outputDir },\n // Static asset cache headers — hashed assets are immutable, others get 1h.\n // See design/25-production-deployments.md §\"CDN / Edge Cache\"\n routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n };\n\n const configJson = JSON.stringify(config, null, 2);\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport { defineNitroConfig } from 'nitropack/config'\n\nexport default defineNitroConfig(${configJson})\n`;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Presets that produce a locally-runnable server entry. */\nconst LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\n\n/** Command descriptor for Nitro preview — testable without spawning. */\nexport interface NitroPreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroPreviewCommand(\n buildDir: string,\n preset: NitroPreset\n): NitroPreviewCommand | null {\n if (!LOCALLY_PREVIEWABLE.has(preset)) return null;\n\n const nitroDir = join(buildDir, 'nitro');\n const entryPath = join(nitroDir, 'entry.ts');\n\n const command = preset === 'bun' ? 'bun' : 'node';\n return {\n command,\n args: [entryPath],\n cwd: nitroDir,\n };\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nfunction spawnNitroPreview(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Get the preset configuration for a given preset name.\n * @internal Exported for testing.\n */\nexport function getPresetConfig(preset: NitroPreset): PresetConfig {\n return PRESET_CONFIGS[preset];\n}\n"],"mappings":";;;;AAcA,IAAM,kBAAkB;AACxB,IAAM,eAAe;AAErB,SAAS,sBAA8B;AACrC,QAAO;;;;mBAIU,gBAAgB;;;mBAGhB,aAAa;;;AAuChC,IAAM,iBAAoD;CACxD,UAAU;EACR,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,o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,EAAE,KAAK,aAAa,WAAW;EAGvC,YAAY,EACV,cAAc,EAAE,SAAS,EAAE,iBAAiB,iBAAiB,EAAE,EAChE;EACD,GAAG,aAAa;EAChB,GAAG;EACJ;AAID,QAAO;;;;;mCAFY,KAAK,UAAU,QAAQ,MAAM,EAAE,CAON;;;;AAO9C,IAAM,sBAAsB,IAAI,IAAiB,CAAC,eAAe,MAAM,CAAC;;AAUxE,SAAgB,4BACd,UACA,QAC4B;AAC5B,KAAI,CAAC,oBAAoB,IAAI,OAAO,CAAE,QAAO;CAE7C,MAAM,WAAW,KAAK,UAAU,QAAQ;CACxC,MAAM,YAAY,KAAK,UAAU,WAAW;AAG5C,QAAO;EACL,SAFc,WAAW,QAAQ,QAAQ;EAGzC,MAAM,CAAC,UAAU;EACjB,KAAK;EACN;;;AAIH,SAAS,kBAAkB,SAAiB,MAAgB,KAA4B;AACtF,QAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,MAAM,QAAQ,SAAS,SAAS,MAAM,EAAE,KAAK,GAAG,QAAQ;AACtD,OAAI,IAAK,QAAO,IAAI;OACf,UAAS;IACd;AACF,QAAM,QAAQ,KAAK,QAAQ,OAAO;AAClC,QAAM,QAAQ,KAAK,QAAQ,OAAO;GAClC;;;;;;AASJ,SAAgB,gBAAgB,QAAmC;AACjE,QAAO,eAAe"}
|
|
1
|
+
{"version":3,"file":"nitro.js","names":[],"sources":["../../src/adapters/nitro.ts"],"sourcesContent":["// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { writeFile, mkdir, cp } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\n// Inlined from server/asset-headers.ts — adapters are loaded by Node at\n// Vite startup time, before Vite's module resolver is available, so cross-\n// directory .ts imports don't resolve.\nconst IMMUTABLE_CACHE = 'public, max-age=31536000, immutable';\nconst STATIC_CACHE = 'public, max-age=3600, must-revalidate';\n\nfunction generateHeadersFile(): string {\n return `# Auto-generated by @timber-js/app — static asset cache headers.\n# See design/25-production-deployments.md §\"CDN / Edge Cache\"\n\n/assets/*\n Cache-Control: ${IMMUTABLE_CACHE}\n\n/*\n Cache-Control: ${STATIC_CACHE}\n`;\n}\n\n// ─── Presets ─────────────────────────────────────────────────────────────────\n\n/**\n * Supported Nitro deployment presets.\n *\n * Each preset maps to a Nitro deployment target. The adapter generates\n * the appropriate configuration and entry point for the selected platform.\n */\nexport type NitroPreset =\n | 'vercel'\n | 'vercel-edge'\n | 'netlify'\n | 'netlify-edge'\n | 'aws-lambda'\n | 'deno-deploy'\n | 'azure-functions'\n | 'node-server'\n | 'bun';\n\n/** Preset-specific Nitro configuration. */\ninterface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nconst PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: true,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: true,\n runtimeName: 'bun',\n },\n};\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/** Options for the Nitro adapter. */\nexport interface NitroAdapterOptions {\n /**\n * Deployment preset. Determines the target platform.\n * @default 'node-server'\n */\n preset?: NitroPreset;\n\n /**\n * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: Record<string, unknown>;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const presetConfig = PRESET_CONFIGS[preset];\n const pendingPromises: Promise<unknown>[] = [];\n\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'nitro');\n await mkdir(outDir, { recursive: true });\n\n // Copy client assets to public directory.\n // When client JavaScript is disabled, skip .js files — only CSS,\n // fonts, images, and other static assets are needed.\n const clientDir = join(buildDir, 'client');\n const publicDir = join(outDir, 'public');\n await mkdir(publicDir, { recursive: true });\n await cp(clientDir, publicDir, {\n recursive: true,\n filter: config.clientJavascriptDisabled ? (src: string) => !src.endsWith('.js') : undefined,\n }).catch(() => {\n // Client dir may not exist when client JavaScript is disabled\n });\n\n // Write _headers file for platforms that support it (Netlify, etc.).\n // See design/25-production-deployments.md §\"CDN / Edge Cache\"\n await writeFile(join(publicDir, '_headers'), generateHeadersFile());\n\n // Write the build manifest init module (if manifest data was produced).\n if (config.manifestInit) {\n await writeFile(join(outDir, '_timber-manifest-init.js'), config.manifestInit);\n }\n\n // Generate the Nitro entry point\n const hasManifestInit = !!config.manifestInit;\n const entry = generateNitroEntry(buildDir, outDir, preset, hasManifestInit);\n await writeFile(join(outDir, 'entry.ts'), entry);\n\n // Generate the Nitro config with static asset cache rules\n const nitroConfig = generateNitroConfig(preset, options.nitroConfig);\n await writeFile(join(outDir, 'nitro.config.ts'), nitroConfig);\n },\n\n // Only presets that produce a locally-runnable server get preview().\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no\n // local runtime — Vite's built-in preview is the fallback.\n preview: LOCALLY_PREVIEWABLE.has(preset)\n ? async (_config: TimberConfig, buildDir: string) => {\n // Generate a standalone preview server that uses Node's built-in\n // HTTP server. The Nitro entry.ts can't be run directly because\n // it imports h3 (a Nitro dependency not available at runtime).\n const previewScript = generatePreviewScript(buildDir, preset);\n const scriptPath = join(buildDir, 'nitro', '_preview-server.mjs');\n await writeFile(scriptPath, previewScript);\n\n const command = preset === 'bun' ? 'bun' : 'node';\n await spawnNitroPreview(command, [scriptPath], join(buildDir, 'nitro'));\n }\n : undefined,\n\n waitUntil: presetConfig.supportsWaitUntil\n ? (promise: Promise<unknown>) => {\n const tracked = promise.catch((err) => {\n console.error('[timber] waitUntil promise rejected:', err);\n });\n pendingPromises.push(tracked);\n }\n : undefined,\n };\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n buildDir: string,\n outDir: string,\n preset: NitroPreset,\n hasManifestInit = false\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // The Vite RSC plugin outputs it to rsc/index.js.\n let serverEntryRelative = relative(outDir, join(buildDir, 'rsc', 'index.js'));\n // Ensure the import path starts with ./ for ESM compatibility\n if (!serverEntryRelative.startsWith('.')) {\n serverEntryRelative = './' + serverEntryRelative;\n }\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n\n // Build manifest init must be imported before the handler so that\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set when the virtual module evaluates.\n const manifestImport = hasManifestInit ? \"import './_timber-manifest-init.js'\\n\" : '';\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n const handlerCall = earlyHints\n ? ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`\n : ` const webResponse = await handler(webRequest)`;\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\n${manifestImport}import { defineEventHandler, toWebRequest, sendWebResponse } from 'h3'\nimport handler, { runWithEarlyHintsSender } from '${serverEntryRelative}'\n\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\nexport default defineEventHandler(async (event) => {\n const webRequest = toWebRequest(event)\n${handlerCall}\n return sendWebResponse(event, webResponse)\n})\n`;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroConfig(\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): string {\n const presetConfig = PRESET_CONFIGS[preset];\n\n const config: Record<string, unknown> = {\n preset: presetConfig.nitroPreset,\n output: { dir: presetConfig.outputDir },\n // Static asset cache headers — hashed assets are immutable, others get 1h.\n // See design/25-production-deployments.md §\"CDN / Edge Cache\"\n routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n };\n\n const configJson = JSON.stringify(config, null, 2);\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport { defineNitroConfig } from 'nitropack/config'\n\nexport default defineNitroConfig(${configJson})\n`;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Presets that produce a locally-runnable server entry. */\nconst LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and route requests to the RSC handler.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(buildDir: string, preset: NitroPreset): string {\n const rscEntryRelative = relative(join(buildDir, 'nitro'), join(buildDir, 'rsc', 'index.js'));\n const rscEntry = rscEntryRelative.startsWith('.') ? rscEntryRelative : './' + rscEntryRelative;\n const publicDir = './public';\n const manifestInitPath = './_timber-manifest-init.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Uses Node's built-in HTTP server to serve static assets and route\n// dynamic requests through the RSC handler. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { existsSync } from 'node:fs';\n\n// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = '${runtimeName}';\n\n// Load the build manifest if it exists.\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\nconst manifestPath = join(__dirname, '${manifestInitPath}');\nif (existsSync(manifestPath)) {\n await import('${manifestInitPath}');\n}\n\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');\n\nconst MIME_TYPES = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.wasm': 'application/wasm',\n};\n\nconst publicDir = join(__dirname, '${publicDir}');\nconst port = parseInt(process.env.PORT || '3000', 10);\n\nconst server = createServer(async (req, res) => {\n const url = new URL(req.url || '/', \\`http://localhost:\\${port}\\`);\n\n // Try serving static files from the public directory first.\n const filePath = join(publicDir, url.pathname);\n // Prevent path traversal.\n if (filePath.startsWith(publicDir)) {\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) {\n const ext = extname(filePath);\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n const body = await readFile(filePath);\n // Hashed assets get immutable cache, others get short cache.\n const cacheControl = url.pathname.startsWith('/assets/')\n ? 'public, max-age=31536000, immutable'\n : 'public, max-age=3600, must-revalidate';\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(body);\n return;\n }\n } catch {\n // File not found — fall through to the RSC handler.\n }\n }\n\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const webResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Write the response back to the Node response.\n res.writeHead(webResponse.status, Object.fromEntries(webResponse.headers.entries()));\n\n if (webResponse.body) {\n const reader = webResponse.body.getReader();\n const pump = async () => {\n while (true) {\n const { done, value } = await reader.read();\n if (done) { res.end(); return; }\n res.write(value);\n }\n };\n await pump();\n } else {\n res.end();\n }\n } catch (err) {\n console.error('[timber preview] Request error:', err);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n }\n res.end('Internal Server Error');\n }\n});\n\nserver.listen(port, () => {\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://localhost:\\${port}\\`);\n console.log();\n});\n`;\n}\n\n/** Command descriptor for Nitro preview — testable without spawning. */\nexport interface NitroPreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroPreviewCommand(\n buildDir: string,\n preset: NitroPreset\n): NitroPreviewCommand | null {\n if (!LOCALLY_PREVIEWABLE.has(preset)) return null;\n\n const nitroDir = join(buildDir, 'nitro');\n const entryPath = join(nitroDir, 'entry.ts');\n\n const command = preset === 'bun' ? 'bun' : 'node';\n return {\n command,\n args: [entryPath],\n cwd: nitroDir,\n };\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nfunction spawnNitroPreview(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Get the preset configuration for a given preset name.\n * @internal Exported for testing.\n */\nexport function getPresetConfig(preset: NitroPreset): PresetConfig {\n return PRESET_CONFIGS[preset];\n}\n"],"mappings":";;;;AAcA,IAAM,kBAAkB;AACxB,IAAM,eAAe;AAErB,SAAS,sBAA8B;AACrC,QAAO;;;;mBAIU,gBAAgB;;;mBAGhB,aAAa;;;AAuChC,IAAM,iBAAoD;CACxD,UAAU;EACR,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACb,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,IAAI,EAAE,EAAE;EAC5D;CACD,eAAe;EACb,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,WAAW;EACT,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,gBAAgB;EACd,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,cAAc;EACZ,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,eAAe;EACb,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EAC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C;CAC7F,MAAM,WAAW,iBAAiB,WAAW,IAAI,GAAG,mBAAmB,OAAO;CAC9E,MAAM,YAAY;CAClB,MAAM,mBAAmB;AAGzB,QAAO;;;;;;;;;;;gCAFa,eAAe,QAAQ,YAaD;;;;wCAIJ,iBAAiB;;kBAEvC,iBAAiB;;;;sEAImC,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;qCA2B1C,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkH/C,SAAgB,4BACd,UACA,QAC4B;AAC5B,KAAI,CAAC,oBAAoB,IAAI,OAAO,CAAE,QAAO;CAE7C,MAAM,WAAW,KAAK,UAAU,QAAQ;CACxC,MAAM,YAAY,KAAK,UAAU,WAAW;AAG5C,QAAO;EACL,SAFc,WAAW,QAAQ,QAAQ;EAGzC,MAAM,CAAC,UAAU;EACjB,KAAK;EACN;;;AAIH,SAAS,kBAAkB,SAAiB,MAAgB,KAA4B;AACtF,QAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,MAAM,QAAQ,SAAS,SAAS,MAAM,EAAE,KAAK,GAAG,QAAQ;AACtD,OAAI,IAAK,QAAO,IAAI;OACf,UAAS;IACd;AACF,QAAM,QAAQ,KAAK,QAAQ,OAAO;AAClC,QAAM,QAAQ,KAAK,QAAQ,OAAO;GAClC;;;;;;AASJ,SAAgB,gBAAgB,QAAmC;AACjE,QAAO,eAAe"}
|
package/dist/cli.js
CHANGED
|
@@ -84,7 +84,7 @@ async function runPreview(options) {
|
|
|
84
84
|
const config = await loadTimberConfig(root).catch(() => null);
|
|
85
85
|
const adapter = config?.adapter;
|
|
86
86
|
if (resolvePreviewStrategy(adapter) === "adapter") {
|
|
87
|
-
const buildDir = join(root, "
|
|
87
|
+
const buildDir = join(root, "dist");
|
|
88
88
|
const timberConfig = { output: config?.output ?? "server" };
|
|
89
89
|
await adapter.preview(timberConfig, buildDir);
|
|
90
90
|
return;
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// timber.js CLI\n//\n// Wraps Vite commands with timber-specific behavior.\n// See design/18-build-system.md §\"CLI\".\n//\n// Commands:\n// timber dev — Start Vite dev server with HMR\n// timber build — Run multi-environment build via createBuilder/buildApp\n// timber preview — Serve the production build\n// timber check — Validate types + routes without building\n\nconst COMMANDS = ['dev', 'build', 'preview', 'check'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nexport interface ParsedArgs {\n command: Command;\n config: string | undefined;\n}\n\nexport interface CommandOptions {\n config?: string;\n}\n\n/**\n * Parse CLI arguments into a structured command + options.\n * Accepts: timber <command> [--config|-c <path>]\n */\nexport function parseArgs(args: string[]): ParsedArgs {\n if (args.length === 0) {\n throw new Error(\n 'No command provided. Usage: timber <dev|build|preview|check> [--config <path>]'\n );\n }\n\n const command = args[0];\n if (!COMMANDS.includes(command as Command)) {\n throw new Error(`Unknown command: ${command}. Available commands: ${COMMANDS.join(', ')}`);\n }\n\n let config: string | undefined;\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--config' || args[i] === '-c') {\n config = args[++i];\n if (!config) {\n throw new Error('--config requires a path argument');\n }\n }\n }\n\n return { command: command as Command, config };\n}\n\n// ─── Command Implementations ─────────────────────────────────────────────────\n\n/**\n * Start the Vite dev server.\n * Middleware re-runs on file change via HMR wiring in timber-routing.\n */\nexport async function runDev(options: CommandOptions): Promise<void> {\n const { createServer } = await import('vite');\n const server = await createServer({\n configFile: options.config,\n });\n await server.listen();\n server.printUrls();\n}\n\n/**\n * Run the production build using createBuilder + buildApp.\n * Direct build() calls do NOT trigger the RSC plugin's multi-environment\n * pipeline — createBuilder/buildApp is required.\n */\nexport async function runBuild(options: CommandOptions): Promise<void> {\n const { createBuilder } = await import('vite');\n const builder = await createBuilder({\n configFile: options.config,\n });\n await builder.buildApp();\n}\n\n/**\n * Determine whether to use the adapter's preview or Vite's built-in preview.\n * Exported for testing — the actual runPreview function uses this internally.\n */\nexport function resolvePreviewStrategy(\n adapter: import('./adapters/types').TimberPlatformAdapter | undefined\n): 'adapter' | 'vite' {\n if (adapter && typeof adapter.preview === 'function') {\n return 'adapter';\n }\n return 'vite';\n}\n\n/**\n * Load timber.config.ts from the project root.\n * Returns the config object with adapter, output, etc.\n * Returns null if no config file is found.\n */\nasync function loadTimberConfig(\n root: string\n): Promise<{ adapter?: import('./adapters/types').TimberPlatformAdapter; output?: string } | null> {\n const { existsSync } = await import('node:fs');\n const { join } = await import('node:path');\n const { pathToFileURL } = await import('node:url');\n\n const configNames = ['timber.config.ts', 'timber.config.js', 'timber.config.mjs'];\n\n for (const name of configNames) {\n const configPath = join(root, name);\n if (existsSync(configPath)) {\n // Use Vite's built-in config loading to handle TypeScript\n const mod = await import(pathToFileURL(configPath).href);\n return mod.default ?? mod;\n }\n }\n return null;\n}\n\n/**\n * Serve the production build for local testing.\n * If the adapter provides a preview() method, it takes priority.\n * Otherwise falls back to Vite's built-in preview server.\n */\nexport async function runPreview(options: CommandOptions): Promise<void> {\n const { join } = await import('node:path');\n\n // Try to load timber config for adapter-specific preview\n const root = process.cwd();\n const config = await loadTimberConfig(root).catch(() => null);\n const adapter = config?.adapter as import('./adapters/types').TimberPlatformAdapter | undefined;\n\n if (resolvePreviewStrategy(adapter) === 'adapter') {\n const buildDir = join(root, '
|
|
1
|
+
{"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// timber.js CLI\n//\n// Wraps Vite commands with timber-specific behavior.\n// See design/18-build-system.md §\"CLI\".\n//\n// Commands:\n// timber dev — Start Vite dev server with HMR\n// timber build — Run multi-environment build via createBuilder/buildApp\n// timber preview — Serve the production build\n// timber check — Validate types + routes without building\n\nconst COMMANDS = ['dev', 'build', 'preview', 'check'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nexport interface ParsedArgs {\n command: Command;\n config: string | undefined;\n}\n\nexport interface CommandOptions {\n config?: string;\n}\n\n/**\n * Parse CLI arguments into a structured command + options.\n * Accepts: timber <command> [--config|-c <path>]\n */\nexport function parseArgs(args: string[]): ParsedArgs {\n if (args.length === 0) {\n throw new Error(\n 'No command provided. Usage: timber <dev|build|preview|check> [--config <path>]'\n );\n }\n\n const command = args[0];\n if (!COMMANDS.includes(command as Command)) {\n throw new Error(`Unknown command: ${command}. Available commands: ${COMMANDS.join(', ')}`);\n }\n\n let config: string | undefined;\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--config' || args[i] === '-c') {\n config = args[++i];\n if (!config) {\n throw new Error('--config requires a path argument');\n }\n }\n }\n\n return { command: command as Command, config };\n}\n\n// ─── Command Implementations ─────────────────────────────────────────────────\n\n/**\n * Start the Vite dev server.\n * Middleware re-runs on file change via HMR wiring in timber-routing.\n */\nexport async function runDev(options: CommandOptions): Promise<void> {\n const { createServer } = await import('vite');\n const server = await createServer({\n configFile: options.config,\n });\n await server.listen();\n server.printUrls();\n}\n\n/**\n * Run the production build using createBuilder + buildApp.\n * Direct build() calls do NOT trigger the RSC plugin's multi-environment\n * pipeline — createBuilder/buildApp is required.\n */\nexport async function runBuild(options: CommandOptions): Promise<void> {\n const { createBuilder } = await import('vite');\n const builder = await createBuilder({\n configFile: options.config,\n });\n await builder.buildApp();\n}\n\n/**\n * Determine whether to use the adapter's preview or Vite's built-in preview.\n * Exported for testing — the actual runPreview function uses this internally.\n */\nexport function resolvePreviewStrategy(\n adapter: import('./adapters/types').TimberPlatformAdapter | undefined\n): 'adapter' | 'vite' {\n if (adapter && typeof adapter.preview === 'function') {\n return 'adapter';\n }\n return 'vite';\n}\n\n/**\n * Load timber.config.ts from the project root.\n * Returns the config object with adapter, output, etc.\n * Returns null if no config file is found.\n */\nasync function loadTimberConfig(\n root: string\n): Promise<{ adapter?: import('./adapters/types').TimberPlatformAdapter; output?: string } | null> {\n const { existsSync } = await import('node:fs');\n const { join } = await import('node:path');\n const { pathToFileURL } = await import('node:url');\n\n const configNames = ['timber.config.ts', 'timber.config.js', 'timber.config.mjs'];\n\n for (const name of configNames) {\n const configPath = join(root, name);\n if (existsSync(configPath)) {\n // Use Vite's built-in config loading to handle TypeScript\n const mod = await import(pathToFileURL(configPath).href);\n return mod.default ?? mod;\n }\n }\n return null;\n}\n\n/**\n * Serve the production build for local testing.\n * If the adapter provides a preview() method, it takes priority.\n * Otherwise falls back to Vite's built-in preview server.\n */\nexport async function runPreview(options: CommandOptions): Promise<void> {\n const { join } = await import('node:path');\n\n // Try to load timber config for adapter-specific preview\n const root = process.cwd();\n const config = await loadTimberConfig(root).catch(() => null);\n const adapter = config?.adapter as import('./adapters/types').TimberPlatformAdapter | undefined;\n\n if (resolvePreviewStrategy(adapter) === 'adapter') {\n const buildDir = join(root, 'dist');\n const timberConfig = { output: (config?.output ?? 'server') as 'server' | 'static' };\n await adapter!.preview!(timberConfig, buildDir);\n return;\n }\n\n // Fallback: Vite's built-in preview server\n const { preview } = await import('vite');\n const server = await preview({\n configFile: options.config,\n });\n server.printUrls();\n}\n\n/**\n * Validate types and routes without producing build output.\n * Runs tsgo --noEmit for type checking.\n */\nexport async function runCheck(options: CommandOptions): Promise<void> {\n const { execFile } = await import('node:child_process');\n\n await new Promise<void>((resolve, reject) => {\n const configArgs = options.config ? ['--project', options.config] : [];\n execFile('tsgo', ['--noEmit', ...configArgs], (err, stdout, stderr) => {\n if (stdout) process.stdout.write(stdout);\n if (stderr) process.stderr.write(stderr);\n if (err) {\n reject(new Error(`Type check failed with exit code ${err.code}`));\n } else {\n resolve();\n }\n });\n });\n}\n\n// ─── Main Entry Point ────────────────────────────────────────────────────────\n\nasync function main(): Promise<void> {\n const parsed = parseArgs(process.argv.slice(2));\n const options: CommandOptions = { config: parsed.config };\n\n switch (parsed.command) {\n case 'dev':\n await runDev(options);\n break;\n case 'build':\n await runBuild(options);\n break;\n case 'preview':\n await runPreview(options);\n break;\n case 'check':\n await runCheck(options);\n break;\n }\n}\n\n// Run main when executed as a CLI (not imported in tests).\n// The bin shim (bin/timber.mjs) does `import '../dist/cli.js'`, so\n// process.argv[1] points to the shim, not this file. We check both:\n// direct execution AND being imported by the timber bin shim.\nconst isDirectExecution =\n typeof process !== 'undefined' &&\n process.argv[1] &&\n (import.meta.url.endsWith(process.argv[1]) ||\n process.argv[1].endsWith('bin/timber.mjs') ||\n process.argv[1].endsWith('bin/timber'));\n\nif (isDirectExecution) {\n main().catch((err) => {\n console.error(err.message);\n process.exit(1);\n });\n}\n"],"mappings":";;AAaA,IAAM,WAAW;CAAC;CAAO;CAAS;CAAW;CAAQ;;;;;AAgBrD,SAAgB,UAAU,MAA4B;AACpD,KAAI,KAAK,WAAW,EAClB,OAAM,IAAI,MACR,iFACD;CAGH,MAAM,UAAU,KAAK;AACrB,KAAI,CAAC,SAAS,SAAS,QAAmB,CACxC,OAAM,IAAI,MAAM,oBAAoB,QAAQ,wBAAwB,SAAS,KAAK,KAAK,GAAG;CAG5F,IAAI;AACJ,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,IAC/B,KAAI,KAAK,OAAO,cAAc,KAAK,OAAO,MAAM;AAC9C,WAAS,KAAK,EAAE;AAChB,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,oCAAoC;;AAK1D,QAAO;EAAW;EAAoB;EAAQ;;;;;;AAShD,eAAsB,OAAO,SAAwC;CACnE,MAAM,EAAE,iBAAiB,MAAM,OAAO;CACtC,MAAM,SAAS,MAAM,aAAa,EAChC,YAAY,QAAQ,QACrB,CAAC;AACF,OAAM,OAAO,QAAQ;AACrB,QAAO,WAAW;;;;;;;AAQpB,eAAsB,SAAS,SAAwC;CACrE,MAAM,EAAE,kBAAkB,MAAM,OAAO;AAIvC,QAHgB,MAAM,cAAc,EAClC,YAAY,QAAQ,QACrB,CAAC,EACY,UAAU;;;;;;AAO1B,SAAgB,uBACd,SACoB;AACpB,KAA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,IAAI,OAAO,CAAC;OAEjE,UAAS;IAEX;GACF;;AAKJ,eAAe,OAAsB;CACnC,MAAM,SAAS,UAAU,QAAQ,KAAK,MAAM,EAAE,CAAC;CAC/C,MAAM,UAA0B,EAAE,QAAQ,OAAO,QAAQ;AAEzD,SAAQ,OAAO,SAAf;EACE,KAAK;AACH,SAAM,OAAO,QAAQ;AACrB;EACF,KAAK;AACH,SAAM,SAAS,QAAQ;AACvB;EACF,KAAK;AACH,SAAM,WAAW,QAAQ;AACzB;EACF,KAAK;AACH,SAAM,SAAS,QAAQ;AACvB;;;AAeN,IANE,OAAO,YAAY,eACnB,QAAQ,KAAK,OACZ,OAAO,KAAK,IAAI,SAAS,QAAQ,KAAK,GAAG,IACxC,QAAQ,KAAK,GAAG,SAAS,iBAAiB,IAC1C,QAAQ,KAAK,GAAG,SAAS,aAAa,EAGxC,OAAM,CAAC,OAAO,QAAQ;AACpB,SAAQ,MAAM,IAAI,QAAQ;AAC1B,SAAQ,KAAK,EAAE;EACf"}
|
package/package.json
CHANGED
package/src/adapters/nitro.ts
CHANGED
|
@@ -213,9 +213,15 @@ export function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter
|
|
|
213
213
|
// local runtime — Vite's built-in preview is the fallback.
|
|
214
214
|
preview: LOCALLY_PREVIEWABLE.has(preset)
|
|
215
215
|
? async (_config: TimberConfig, buildDir: string) => {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
216
|
+
// Generate a standalone preview server that uses Node's built-in
|
|
217
|
+
// HTTP server. The Nitro entry.ts can't be run directly because
|
|
218
|
+
// it imports h3 (a Nitro dependency not available at runtime).
|
|
219
|
+
const previewScript = generatePreviewScript(buildDir, preset);
|
|
220
|
+
const scriptPath = join(buildDir, 'nitro', '_preview-server.mjs');
|
|
221
|
+
await writeFile(scriptPath, previewScript);
|
|
222
|
+
|
|
223
|
+
const command = preset === 'bun' ? 'bun' : 'node';
|
|
224
|
+
await spawnNitroPreview(command, [scriptPath], join(buildDir, 'nitro'));
|
|
219
225
|
}
|
|
220
226
|
: undefined,
|
|
221
227
|
|
|
@@ -320,6 +326,175 @@ export default defineNitroConfig(${configJson})
|
|
|
320
326
|
/** Presets that produce a locally-runnable server entry. */
|
|
321
327
|
const LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);
|
|
322
328
|
|
|
329
|
+
/**
|
|
330
|
+
* Generate a standalone preview server script that uses Node's built-in
|
|
331
|
+
* HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports
|
|
332
|
+
* h3 which isn't available outside a Nitro build. For local preview we
|
|
333
|
+
* just need to serve static files and route requests to the RSC handler.
|
|
334
|
+
*
|
|
335
|
+
* @internal Exported for testing.
|
|
336
|
+
*/
|
|
337
|
+
export function generatePreviewScript(buildDir: string, preset: NitroPreset): string {
|
|
338
|
+
const rscEntryRelative = relative(join(buildDir, 'nitro'), join(buildDir, 'rsc', 'index.js'));
|
|
339
|
+
const rscEntry = rscEntryRelative.startsWith('.') ? rscEntryRelative : './' + rscEntryRelative;
|
|
340
|
+
const publicDir = './public';
|
|
341
|
+
const manifestInitPath = './_timber-manifest-init.js';
|
|
342
|
+
const runtimeName = PRESET_CONFIGS[preset].runtimeName;
|
|
343
|
+
|
|
344
|
+
return `// Generated by @timber-js/app — standalone preview server.
|
|
345
|
+
// Uses Node's built-in HTTP server to serve static assets and route
|
|
346
|
+
// dynamic requests through the RSC handler. No Nitro/h3 dependency.
|
|
347
|
+
|
|
348
|
+
import { createServer } from 'node:http';
|
|
349
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
350
|
+
import { join, extname } from 'node:path';
|
|
351
|
+
import { fileURLToPath } from 'node:url';
|
|
352
|
+
import { existsSync } from 'node:fs';
|
|
353
|
+
|
|
354
|
+
// Set runtime before importing the handler.
|
|
355
|
+
process.env.TIMBER_RUNTIME = '${runtimeName}';
|
|
356
|
+
|
|
357
|
+
// Load the build manifest if it exists.
|
|
358
|
+
const __dirname = fileURLToPath(new URL('.', import.meta.url));
|
|
359
|
+
const manifestPath = join(__dirname, '${manifestInitPath}');
|
|
360
|
+
if (existsSync(manifestPath)) {
|
|
361
|
+
await import('${manifestInitPath}');
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// Import the RSC handler (default export is the fetch-like handler).
|
|
365
|
+
const { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');
|
|
366
|
+
|
|
367
|
+
const MIME_TYPES = {
|
|
368
|
+
'.html': 'text/html',
|
|
369
|
+
'.js': 'application/javascript',
|
|
370
|
+
'.mjs': 'application/javascript',
|
|
371
|
+
'.css': 'text/css',
|
|
372
|
+
'.json': 'application/json',
|
|
373
|
+
'.png': 'image/png',
|
|
374
|
+
'.jpg': 'image/jpeg',
|
|
375
|
+
'.jpeg': 'image/jpeg',
|
|
376
|
+
'.gif': 'image/gif',
|
|
377
|
+
'.svg': 'image/svg+xml',
|
|
378
|
+
'.ico': 'image/x-icon',
|
|
379
|
+
'.woff': 'font/woff',
|
|
380
|
+
'.woff2': 'font/woff2',
|
|
381
|
+
'.ttf': 'font/ttf',
|
|
382
|
+
'.otf': 'font/otf',
|
|
383
|
+
'.webp': 'image/webp',
|
|
384
|
+
'.avif': 'image/avif',
|
|
385
|
+
'.webm': 'video/webm',
|
|
386
|
+
'.mp4': 'video/mp4',
|
|
387
|
+
'.txt': 'text/plain',
|
|
388
|
+
'.xml': 'application/xml',
|
|
389
|
+
'.wasm': 'application/wasm',
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
const publicDir = join(__dirname, '${publicDir}');
|
|
393
|
+
const port = parseInt(process.env.PORT || '3000', 10);
|
|
394
|
+
|
|
395
|
+
const server = createServer(async (req, res) => {
|
|
396
|
+
const url = new URL(req.url || '/', \`http://localhost:\${port}\`);
|
|
397
|
+
|
|
398
|
+
// Try serving static files from the public directory first.
|
|
399
|
+
const filePath = join(publicDir, url.pathname);
|
|
400
|
+
// Prevent path traversal.
|
|
401
|
+
if (filePath.startsWith(publicDir)) {
|
|
402
|
+
try {
|
|
403
|
+
const fileStat = await stat(filePath);
|
|
404
|
+
if (fileStat.isFile()) {
|
|
405
|
+
const ext = extname(filePath);
|
|
406
|
+
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
|
|
407
|
+
const body = await readFile(filePath);
|
|
408
|
+
// Hashed assets get immutable cache, others get short cache.
|
|
409
|
+
const cacheControl = url.pathname.startsWith('/assets/')
|
|
410
|
+
? 'public, max-age=31536000, immutable'
|
|
411
|
+
: 'public, max-age=3600, must-revalidate';
|
|
412
|
+
res.writeHead(200, {
|
|
413
|
+
'Content-Type': contentType,
|
|
414
|
+
'Content-Length': body.length,
|
|
415
|
+
'Cache-Control': cacheControl,
|
|
416
|
+
});
|
|
417
|
+
res.end(body);
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
} catch {
|
|
421
|
+
// File not found — fall through to the RSC handler.
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// Convert Node request to Web Request.
|
|
426
|
+
const headers = new Headers();
|
|
427
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
428
|
+
if (value) {
|
|
429
|
+
if (Array.isArray(value)) {
|
|
430
|
+
for (const v of value) headers.append(key, v);
|
|
431
|
+
} else {
|
|
432
|
+
headers.set(key, value);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
let body = undefined;
|
|
438
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
439
|
+
body = await new Promise((resolve) => {
|
|
440
|
+
const chunks = [];
|
|
441
|
+
req.on('data', (chunk) => chunks.push(chunk));
|
|
442
|
+
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
const webRequest = new Request(url.href, {
|
|
447
|
+
method: req.method,
|
|
448
|
+
headers,
|
|
449
|
+
body,
|
|
450
|
+
duplex: body ? 'half' : undefined,
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
try {
|
|
454
|
+
// Support 103 Early Hints when available.
|
|
455
|
+
const earlyHintsSender = (typeof res.writeEarlyHints === 'function')
|
|
456
|
+
? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }
|
|
457
|
+
: undefined;
|
|
458
|
+
|
|
459
|
+
const webResponse = earlyHintsSender && runWithEarlyHintsSender
|
|
460
|
+
? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))
|
|
461
|
+
: await handler(webRequest);
|
|
462
|
+
|
|
463
|
+
// Write the response back to the Node response.
|
|
464
|
+
res.writeHead(webResponse.status, Object.fromEntries(webResponse.headers.entries()));
|
|
465
|
+
|
|
466
|
+
if (webResponse.body) {
|
|
467
|
+
const reader = webResponse.body.getReader();
|
|
468
|
+
const pump = async () => {
|
|
469
|
+
while (true) {
|
|
470
|
+
const { done, value } = await reader.read();
|
|
471
|
+
if (done) { res.end(); return; }
|
|
472
|
+
res.write(value);
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
await pump();
|
|
476
|
+
} else {
|
|
477
|
+
res.end();
|
|
478
|
+
}
|
|
479
|
+
} catch (err) {
|
|
480
|
+
console.error('[timber preview] Request error:', err);
|
|
481
|
+
if (!res.headersSent) {
|
|
482
|
+
res.writeHead(500, { 'Content-Type': 'text/plain' });
|
|
483
|
+
}
|
|
484
|
+
res.end('Internal Server Error');
|
|
485
|
+
}
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
server.listen(port, () => {
|
|
489
|
+
console.log();
|
|
490
|
+
console.log(' ⚡ timber preview server running at:');
|
|
491
|
+
console.log();
|
|
492
|
+
console.log(\` ➜ http://localhost:\${port}\`);
|
|
493
|
+
console.log();
|
|
494
|
+
});
|
|
495
|
+
`;
|
|
496
|
+
}
|
|
497
|
+
|
|
323
498
|
/** Command descriptor for Nitro preview — testable without spawning. */
|
|
324
499
|
export interface NitroPreviewCommand {
|
|
325
500
|
command: string;
|
package/src/cli.ts
CHANGED
|
@@ -132,7 +132,7 @@ export async function runPreview(options: CommandOptions): Promise<void> {
|
|
|
132
132
|
const adapter = config?.adapter as import('./adapters/types').TimberPlatformAdapter | undefined;
|
|
133
133
|
|
|
134
134
|
if (resolvePreviewStrategy(adapter) === 'adapter') {
|
|
135
|
-
const buildDir = join(root, '
|
|
135
|
+
const buildDir = join(root, 'dist');
|
|
136
136
|
const timberConfig = { output: (config?.output ?? 'server') as 'server' | 'static' };
|
|
137
137
|
await adapter!.preview!(timberConfig, buildDir);
|
|
138
138
|
return;
|