Repository navigation
fix(create-blocks-app,core): let the framework adapter build an existing SSR project - #1669
osama-rizk wants to merge 6 commits into
Conversation
| async function fitHostingToFramework(indexCdk: string, framework: string): Promise<void> { | ||
| if (framework === 'spa' || !(await exists(indexCdk))) return; | ||
| const source = await readFile(indexCdk, 'utf-8'); | ||
| const updated = source.replace(TEMPLATE_BUILD_SETTINGS, `\n framework: '${framework}',\n`); | ||
| if (updated !== source) await writeFile(indexCdk, updated); | ||
| } |
There was a problem hiding this comment.
[minor] If TEMPLATE_BUILD_SETTINGS stops matching, this does nothing and says nothing. That can happen after a template edit (reordering props, changing indentation, a new template under --template), or when the repo templates have CRLF endings (a Windows checkout with core.autocrlf, which the local-monorepo path copies from). The project then gets the Vite buildCommand/dist again, which is the bug this PR fixes. Two suggestions: (1) make the newline \r?\n and keep the matched line ending; (2) when framework !== 'spa', the file contains new Hosting(, and nothing matched, print a warning that names the file and the edit to make by hand (framework: '<fw>', no buildCommand/buildOutputDir). Also add a test that loops over every templates/*/aws-blocks/index.cdk.ts containing new Hosting( and asserts the regex matches. Today only the default template is pinned, through the existing-project tests, so a drift in auth, react, demo and the others would go unnoticed.
There was a problem hiding this comment.
Fixed in 5bbac90. The pattern now accepts \r?\n and the replacement keeps the matched line ending. When framework !== 'spa', the file has a new Hosting( and nothing matched, the CLI leaves the file alone and prints the file path plus the edit to make by hand (framework: '<fw>', no buildCommand/buildOutputDir). The matching is now a pure fitHostingSource(), and a new test runs it over every templates/*/aws-blocks/index.cdk.ts that contains new Hosting( (agent, auth, auth-oidc, bare, default, demo, nextjs, react), with LF and with CRLF endings, and asserts that it matches, writes no mixed endings and removes buildCommand/buildOutputDir. The create-blocks-app README mentions the warning.
| * `detectFramework` in `@aws-blocks/hosting/adapters` (which this CLI doesn't load: the | ||
| * project may not have installed it yet). A test checks that the two agree. | ||
| */ | ||
| export function detectProjectFramework(pkg: PackageDeps & { peerDependencies?: Record<string, unknown> }): string { |
There was a problem hiding this comment.
[nit] Could the return type be 'nextjs' | 'nitro' | 'astro' | 'sveltekit' | 'spa' instead of string? fitHostingToFramework interpolates the value into generated source, so a closed union documents that only these literals reach it and lets the compiler check the 'spa' comparison.
There was a problem hiding this comment.
Done in 5bbac90: detectProjectFramework now returns ProjectFramework = 'nextjs' | 'nitro' | 'astro' | 'sveltekit' | 'spa', and fitHostingSource takes Exclude<ProjectFramework, 'spa'>, so only those literals reach the generated source.
| // An adapter that builds the app itself (SvelteKit, Astro, Nuxt/Nitro, Next.js) | ||
| // needs no build before it runs: with no buildCommand, the missing output dir | ||
| // is the adapter's to build, not a synth error. Each adapter here stops at its | ||
| // version check (no framework is installed), which proves it ran. | ||
| for (const [framework, dependency, adapterError] of [ | ||
| ['sveltekit', '@sveltejs/kit', 'UnsupportedSvelteKitVersionError'], | ||
| ['astro', 'astro', 'UnsupportedAstroVersionError'], | ||
| ] as const) { | ||
| it(`runs the ${framework} adapter, which builds the app, when there is no build output and no buildCommand`, () => { | ||
| fs.writeFileSync( | ||
| path.join(tmpDir, 'package.json'), | ||
| JSON.stringify({ name: 'test', dependencies: { [dependency]: '*' } }), | ||
| ); | ||
| const app = new App(); | ||
| const stack = new Stack(app, `NoBuildYet-${framework}`); | ||
| assert.throws( | ||
| () => new Hosting(stack, 'Hosting', { root: tmpDir, framework, api: MOCK_API }), | ||
| (err: Error) => { | ||
| assert.ok(!err.message.includes('Build output directory not found'), `Expected the adapter to run, got: ${err.message}`); | ||
| assert.strictEqual(err.name, adapterError); | ||
| return true; | ||
| }, | ||
| ); | ||
| }); | ||
| } |
There was a problem hiding this comment.
[minor] These tests cover the positive path for two of the four frameworks. The adapterBuilds condition has other branches, and none of them is tested:
BLOCKS_SKIP_FRONTEND_BUILD=1+framework: 'sveltekit'(or'astro') + nobuildCommand+ no output should still throwBuild output directory not foundand name the variable. The existing SKIP tests near line 4460 all passbuildCommand, so they never reach thereuseBuild !== 'required'term.customAdapter+framework: 'astro'+ no output should still throwBuild output directory not found.framework: 'astro'+ abuildCommandthat writes nothing should still throwBuild output directory not found.nitroandnextjs: the comment lists them, but the loop doesn't include them. Nitro with nobuildscript inpackage.jsonfails in the adapter'snpm run build(NitroBuildError), which would also prove the adapter ran.
The version-check assertion also depends on where the tmp dir is. The repo root node_modules contains astro (and next, nuxt), and tmpDir comes from os.tmpdir(). If TMPDIR points inside the checkout, getProjectPackageInfo('astro', tmpDir) can find the root install, and the test then runs a real astro build and fails with a different error.
There was a problem hiding this comment.
Added in 764371b:
- The loop now covers all four frameworks plus the
nuxtalias. Nitro and nuxt stop atNitroBuildError(nobuildscript). Next.js stops atNextBuildError, from its edge-route pre-build (the fixture has anapp/page.tsxwithruntime = 'edge'), so OpenNext is never fetched. BLOCKS_SKIP_FRONTEND_BUILD=1+framework: 'sveltekit'+ nobuildCommand+ no output still throwsBuild output directory not foundand names the variable (in the skip-build describe, which saves and restores the env).customAdapter+framework: 'astro'+ no output still throws.framework: 'astro'+ abuildCommandthat writes nothing still throws.- For the tmp dir: each adapter test now skips with a message when the framework resolves from a
node_modulesin a parent of the tmp dir (TMPDIR inside the checkout), instead of running a real framework build.
While doing this I found that framework: 'nuxt' (the alias the registry keeps) wasn't in the self-building set and defaulted to dist. It now matches nitro (.output), with a test.
| * Can be omitted for `nextjs`, `nitro`, `astro` and `sveltekit` too: their | ||
| * adapters build the app themselves, so a missing build output dir is not an | ||
| * error then (the adapter builds it). |
There was a problem hiding this comment.
[nit] Please add the two exceptions the code makes: the output still has to exist with a customAdapter, or under BLOCKS_SKIP_FRONTEND_BUILD=1. It would also help to mention, here or on buildOutputDir, that these four adapters read their own output dir (getAdapter passes buildOutputDir only to spa/static). Setting buildOutputDir for them only changes the existence check, and without a buildCommand it now has no effect at all.
There was a problem hiding this comment.
Done in 764371b. The buildCommand JSDoc now names both exceptions (a customAdapter, or BLOCKS_SKIP_FRONTEND_BUILD=1: the output dir still has to exist). buildOutputDir now says that only the spa and static adapters deploy from it, that nextjs/nitro/astro/sveltekit read their own output dir, so for them it only sets the dir that gets checked, and that without a buildCommand it has no effect.
| @@ -492,7 +492,11 @@ new Hosting(stack, 'Web', { | |||
|
|
|||
| The `framework` option selects the frontend type: `'spa' | 'static' | 'nextjs'`. When omitted, the framework is auto-detected by reading your app's OWN `package.json` (not `node_modules`): a `next` dependency → `nextjs`; otherwise `spa`; and `static` when there is no `package.json`. Set `framework: 'spa'` explicitly to override auto-detection — e.g. when a stray `next` dependency would otherwise trigger an unwanted Next.js/OpenNext build. Full reference lives in the source JSDoc. | |||
There was a problem hiding this comment.
[minor] This line is not changed by the PR, but the new paragraph below it and the create-blocks-app README ("which the CLI detects from package.json as Hosting does") now contradict it. detectFramework also returns nitro (nuxt, nitropack, @solidjs/start, @analogjs/platform-server, @tanstack/start), astro and sveltekit (@sveltejs/kit), in the order next → Nitro → astro → sveltekit → spa, and the option accepts those values. Suggest listing the full union and the detection order here, so a reader of the new paragraph knows when the "leave buildCommand out" behaviour applies without setting framework.
There was a problem hiding this comment.
Done in 764371b. That paragraph now lists the full union ('nextjs' | 'nitro' | 'nuxt' | 'astro' | 'sveltekit' | 'spa' | 'static', with nuxt as an alias of nitro) and the detection order: next → nuxt/nitropack/@solidjs/start/@analogjs/platform-server/@tanstack/start → astro → @sveltejs/kit → spa. It also fixes an older inaccuracy: with no package.json, detectFramework returns spa, not static (readProjectDeps returns {}), so the README now says static is never detected.
| `buildCommand` runs during synth, with `BLOCKS_API_URL` set to the backend the frontend talks to, and then the framework adapter runs its own build (OpenNext, Nitro, Astro, SvelteKit). Two synths skip both: | ||
| `buildCommand` runs during synth, with `BLOCKS_API_URL` set to the backend the frontend talks to, and then the framework adapter runs its own build (OpenNext, Nitro, Astro, SvelteKit). | ||
|
|
||
| The Next.js, Nuxt (Nitro), Astro and SvelteKit adapters build the app themselves, so their apps can leave `buildCommand` out: `Hosting` then runs the adapter even when no build output exists yet, and the adapter's build adds what the deploy needs (OpenNext, Astro's and SvelteKit's Node server adapter). An Astro app without a server adapter needs this, because its own `npm run build` fails before the adapter can add one. With a `buildCommand`, or for `spa` and `static`, the build output dir (`buildOutputDir`, else `dist`, `.next` for Next.js, `.output` for Nitro, `build` for SvelteKit) has to exist when the build has run. |
There was a problem hiding this comment.
[nit] "With a buildCommand, or for spa and static": please add "or with a customAdapter". The code (!props.customAdapter) requires the output dir in that case too.
There was a problem hiding this comment.
Done in 764371b. It now reads "With a buildCommand, with a customAdapter, on a deploy with BLOCKS_SKIP_FRONTEND_BUILD=1, or for spa and static", and the paragraph adds that only spa/static deploy from buildOutputDir.
4ff62e6 to
db2ef5a
Compare
|
I rebased onto main to pick up the |
…ing SSR project Adding AWS Blocks to an existing Next.js, Nuxt, Astro or SvelteKit project wrote Vite's buildCommand and buildOutputDir into Hosting. The added backend now names the framework and leaves the build to the adapter, and Hosting runs a self-building adapter when there is no buildCommand and no build output yet.
… be fitted, type the detected framework Every template with a Hosting is now checked against the build settings the CLI replaces, with LF and CRLF line endings.
…ll need the build output Adds the nuxt alias to the self-building frameworks, and documents the customAdapter and BLOCKS_SKIP_FRONTEND_BUILD exceptions, which output dir each adapter reads, and the full framework detection order.
…its new line; note the nuxt alias in the changeset
…e in the new test, comments and changeset
Problem
Running
npx @aws-blocks/create-blocks-app .in an existing project copies the default template's backend, whoseHostinghas a Vite app's build settings, for every framework:In a Next.js, Nuxt, Astro or SvelteKit project the first
npm run deployfails:Hostingrunsnpm run buildbefore the Astro adapter, so the build fails with[NoAdapterInstalled] Cannot use server-rendered pages without an adapter. The adapter's own build would have added@astrojs/nodethrough its config bridge, but it never gets to run..output/,build/or.next/, neverdist/, so the synth fails withBuild output directory not found: <app>/dist.Leaving out
buildCommanddoesn't help.Hostingchecks that the build output dir exists before it runs the adapter (packages/core/src/hosting.ts), so a fresh checkout fails withBuild output directory not found … Provide a buildCommand, even though these four adapters build the app themselves. The default output dir for a Nitro app was alsodistrather than.output.To reproduce:
npm create astro@latest(minimal), add a page withexport const prerender = false, then runnpx @aws-blocks/create-blocks-app . --yesandnpm run deploy.Changes
packages/create-blocks-app/src/index.ts: adding AWS Blocks to an existing project detects the framework from itspackage.json(detectProjectFramework, using the same rules asdetectFrameworkin@aws-blocks/hosting/adapters). Fornextjs,nitro,astroandsveltekitit replaces the template'sbuildCommand/buildOutputDir(or the Next.js template'sbuildCommand) inaws-blocks/index.cdk.tswithframework: '<framework>'. Every other project keeps the Vite settings. The match accepts LF or CRLF template line endings and keeps them. If a template'sHostingdoesn't have the expected build settings, the CLI leaves the file alone and prints the edit to make by hand. A test checks that the CLI's detection agrees with Hosting's for each rule.packages/core/src/hosting.ts: withframeworknextjs,nitro(or its aliasnuxt),astroorsveltekit, nobuildCommandand nocustomAdapter, a missing build output dir no longer fails the synth before the adapter runs: the adapter builds the app and reports its own missing-output error if its build produced nothing. UnderBLOCKS_SKIP_FRONTEND_BUILD=1the output still has to exist, as before.nitroandnuxtnow default to.outputandastrotodist.packages/core/README.md(Hosting) and thebuildCommand/buildOutputDirJSDoc say whenbuildCommandcan be omitted, thecustomAdapterandBLOCKS_SKIP_FRONTEND_BUILD=1exceptions, the default output dirs, that onlyspa/staticdeploy frombuildOutputDir, and the fullframeworkunion and detection order.packages/create-blocks-app/README.md(Add to Existing Project) says whatHostingthe CLI writes for each kind of project.@aws-blocks/create-blocks-appand@aws-blocks/core.Tests
packages/core/src/hosting.test.ts:Hostingwithframeworksveltekit,astro,nitro,nuxtornextjs, no build output and nobuildCommandruns the adapter. The adapter stops at its first step that needs the framework (the SvelteKit/Astro version check, or thenpm run buildof Nitro and of Next.js's edge pre-build), which proves it ran; before this change the synth failed withBuild output directory not found. The output is still required withBLOCKS_SKIP_FRONTEND_BUILD=1, with acustomAdapter, and when abuildCommandwrites nothing.packages/create-blocks-app/src/cli.test.ts: an existing Astro, Nuxt, SvelteKit and Next.js project getsframework: '<framework>'and nobuildCommand/buildOutputDir; a Vite project gets the template'sindex.cdk.tsunchanged;detectProjectFrameworkmatches Hosting'sdetectFrameworkfor every Nitro package, precedence case and peer dependency; every template with aHostingis matched by the rewrite, with LF and CRLF endings.Before the fix 7 of these fail; with it all pass. The full
coreandcreate-blocks-appsuites,npm run build,npm run lint:depsandnpm run check:apipass.