diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs index 666f53e..2709812 100644 --- a/scripts/smoke.mjs +++ b/scripts/smoke.mjs @@ -147,27 +147,39 @@ async function smoke(testCase) { notes.push('bucket') } - run('npm', ['run', 'build'], dir) + // The reporter prints the first line of the message and `stderr`: tsc writes its diagnostics + // to stdout, so carry them across or a failure says nothing. + const withOutput = (message, error) => + Object.assign(new Error(message), { stderr: `${error.stdout ?? ''}${error.stderr ?? ''}` }) + + try { + run('npm', ['run', 'build'], dir) + } catch (error) { + throw withOutput('the generated project does not build', error) + } notes.push('built') // A Workers build is wrangler's bundler, which never typechecks. Without this, a project that - // opens in the editor full of type errors passes. (Node API and Studio builds run tsc; Node - // full-site builds run astro build, which does not typecheck either: Trokky/generator#12.) + // opens in the editor full of type errors passes. Every Node build ends in tsc already. if (workers) { try { run('npx', ['tsc', '--noEmit', '-p', 'tsconfig.json'], dir) } catch (error) { - // The reporter prints the first line of the message and `stderr`: tsc writes its - // diagnostics to stdout, so carry them across or the failure says nothing. - throw Object.assign(new Error('the generated project does not typecheck'), { - stderr: `${error.stdout ?? ''}${error.stderr ?? ''}`, - }) + throw withOutput('the generated project does not typecheck', error) } notes.push('typechecked') } if (testCase.skipBoot) return `${notes.join(', ')}, boot skipped (${testCase.skipBoot})` + // Build with everything installed, then start without the devDependencies, as the README's + // production steps do. Not airtight: tsx (through astro → vite) and typescript (through + // @trokky/trokky) survive as transitive dependencies, so a start that needs them still passes. + if (!workers) { + run('npm', ['prune', '--omit=dev', '--no-audit', '--no-fund'], dir) + notes.push('pruned') + } + const port = workers ? 8876 : 8877 const base = `http://127.0.0.1:${port}` // Piped, not ignored: a server that dies on its first import used to surface as @@ -176,7 +188,7 @@ async function smoke(testCase) { // tail so the failure says what happened. const child = workers ? spawn('npx', ['wrangler', 'dev', '--port', String(port), '--ip', '127.0.0.1'], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'] }) - // `npm start`, as the README says to run it in production: a wrong start path used to ship + // `npm start`, as the README's production steps run it: a wrong start path used to ship // with this matrix green, because it booted src/server.ts through tsx instead. : spawn('npm', ['start'], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, PORT: String(port), NODE_ENV: 'production' } }) diff --git a/src/emit.ts b/src/emit.ts index 75be439..7e853df 100644 --- a/src/emit.ts +++ b/src/emit.ts @@ -50,10 +50,13 @@ export function packageJson(config: ProjectConfig): string { if (hasFrontend(config)) { dependencies.astro = '^7.3.2' dependencies['@astrojs/node'] = '^11.1.5' - // The server imports the built Astro handler, so the site has to be built before it runs. - scripts.build = 'astro build' + // The server loads the built Astro handler, so the site is built first, then the server + // is compiled: production starts with node alone, since a host that installs with + // NODE_ENV=production has no tsx (a devDependency) to run TypeScript with. + scripts.build = 'astro build && tsc -p tsconfig.json' scripts.dev = 'astro build && tsx watch src/server.ts' - scripts.start = 'tsx src/server.ts' + // rootDir is the project, so tsc mirrors src/ under dist/, beside Astro's dist/server + scripts.start = 'node dist/src/server.js' scripts.check = 'astro check' } else { scripts.dev = 'tsx watch src/server.ts' @@ -357,8 +360,8 @@ import { startServer } from '${TROKKY}/express' import '${TROKKY}/adapters/${config.data}' import '${TROKKY}/adapters/${config.media}' ${hasStudio(config) ? `import { studioRouter } from '${STUDIO}/express'\n` : ''}${site ? `import express from 'express' -// Built by \`astro build\`; run the build before the server. -import { handler as ssrHandler } from '../dist/server/entry.mjs' +import type { NextFunction, Request, Response } from 'express' +import { pathToFileURL } from 'node:url' ` : ''}${seeds ? `import { readFile } from 'node:fs/promises' import path from 'node:path' import { seedSampleContent } from './trokky/seed.js' @@ -370,6 +373,13 @@ ${hasStudio(config) ? ` // Mount Studio before anything that could swallow it. server.app.use('/studio', studioRouter({ apiPath: '/api' })) ` : ''}${site ? ` +// Built by \`astro build\`; run the build before the server. Loaded from the working directory, +// like dist/client below, so the same line works from src/ under tsx and from dist/src/ once +// compiled: start the server from the project directory, or it stops here. Typed here: Astro +// emits no declarations for its entry. +type SsrHandler = (req: Request, res: Response, next: NextFunction, locals?: object) => void +const { handler: ssrHandler } = (await import(pathToFileURL('dist/server/entry.mjs').href)) as { handler: SsrHandler } + // Middleware mode does no file serving of its own, so the built client assets come first. server.app.use(express.static('dist/client')) // Then every remaining path is Astro's. The core goes in as locals, which is how a page reads @@ -569,6 +579,9 @@ export function tsconfig(config: ProjectConfig): string { outDir: 'dist', rootDir: '.', strict: true, skipLibCheck: true, esModuleInterop: true, types: ['node'], }, - include: ['src/**/*', 'trokky.config.ts'], + // The server's entry points only: tsc follows their imports. src/**/* would also pull in + // the site's own files (pages, endpoints), which use Astro's types (import.meta.env, + // astro:*) that a Node-only program lacks; astro check covers those. + include: ['src/server.ts', 'trokky.config.ts'], }, null, 2) + '\n' } diff --git a/src/generate.ts b/src/generate.ts index dc50626..e04d4aa 100644 --- a/src/generate.ts +++ b/src/generate.ts @@ -132,7 +132,22 @@ is in, the site answers, and an unset claim secret leaves the claim open. Wrangler provisions the D1 database and R2 bucket named in \`wrangler.jsonc\` on first deploy. \`database_id\` is intentionally empty: it is bound by name. -` : ''}## The first minute +` : `## Run it in production + +\`\`\` +npm ci +npm run build +NODE_ENV=production npm start +\`\`\` + +The build needs the devDependencies (TypeScript and its types), so install them: set +\`NODE_ENV=production\` for the start, not for the install. \`npm prune --omit=dev\` after the +build is safe. Start from the project directory, since the server reads \`.env\`, \`dist/\` and +\`public/\` from there, with \`TROKKY_JWT_SECRET\` and \`TROKKY_CLAIM_SECRET\` in the environment.${hasFrontend(config) ? ` +\`npm run dev\` rebuilds the site into \`dist/\` and clears the compiled server, so run +\`npm run build\` again before \`npm start\`.` : ''} + +`}## The first minute ${hasStudio(config) ? `Open \`/studio\`. Nobody owns this instance yet, so the first screen asks you to **claim** it: pick a username, an email and a password, and paste \`TROKKY_CLAIM_SECRET\`.` : `Nobody owns this instance yet. **Claim** it over HTTP (on a deployed site, use its URL instead of diff --git a/test/generate.test.ts b/test/generate.test.ts index 80edfad..f9f3bfb 100644 --- a/test/generate.test.ts +++ b/test/generate.test.ts @@ -223,11 +223,26 @@ describe('the site is portable: same pages, either runtime', () => { it('serves the built site from the Node server, assets first', () => { const server = text(node, 'src/server.ts') - expect(server).toContain("from '../dist/server/entry.mjs'") + // From the working directory: the compiled server sits one level deeper than src/ + expect(server).toContain("await import(pathToFileURL('dist/server/entry.mjs').href)") + expect(server).not.toContain('../dist/server/entry.mjs') expect(server).toContain("express.static('dist/client')") + expect(server.indexOf("express.static('dist/client')")).toBeLessThan(server.indexOf('ssrHandler(req, res, next')) expect(server).toContain('ssrHandler(req, res, next, { trokky: core })') - expect(JSON.parse(text(node, 'package.json')).dependencies['@astrojs/node']).toBeTruthy() - expect(JSON.parse(text(node, 'package.json')).scripts.build).toBe('astro build') + const pkg = JSON.parse(text(node, 'package.json')) + expect(pkg.dependencies['@astrojs/node']).toBeTruthy() + expect(pkg.scripts.build).toBe('astro build && tsc -p tsconfig.json') + }) + + it('starts the Node site with node alone, not tsx, which production installs drop', () => { + const pkg = JSON.parse(text(node, 'package.json')) + expect(pkg.scripts.start).toBe('node dist/src/server.js') + expect(pkg.dependencies.tsx).toBeUndefined() + // Entry points only, so the site's own Astro-typed files never reach the Node program + expect(JSON.parse(text(node, 'tsconfig.json')).include).toEqual(['src/server.ts', 'trokky.config.ts']) + const readme = text(node, 'README.md') + expect(readme).toContain('NODE_ENV=production npm start') + expect(readme).toContain('The build needs the devDependencies') }) it('gives a Node project without a site no Astro at all', () => {