diff --git a/.changeset/sveltekit-version-before-build.md b/.changeset/sveltekit-version-before-build.md new file mode 100644 index 0000000000..6d778d8afd --- /dev/null +++ b/.changeset/sveltekit-version-before-build.md @@ -0,0 +1,7 @@ +--- +"@aws-cdk-blocks/hosting": patch +"@aws-cdk-blocks/core": patch +"@aws-cdk-blocks/create-blocks-app": patch +--- + +A SvelteKit 3 project (what `npx sv create` scaffolds) is now refused before any build runs. `Hosting` checks the installed `@sveltejs/kit` before it runs `buildCommand`, and `UnsupportedSvelteKitVersionError` names the SvelteKit 2 versions to pin (`@sveltejs/kit@^2`, `@sveltejs/adapter-node@^5`, `@sveltejs/vite-plugin-svelte@^5`, `vite@^6`). `create-blocks-app .` stops before it writes anything in a SvelteKit 3 project and prints the same versions. The Hosting README now states the supported range: SvelteKit 2 (`>=2.0.0 <3.0.0`). The new `assertFrameworkSupported(framework, projectDir)` from `@aws-cdk-blocks/hosting/adapters` runs these build-free checks. diff --git a/packages/core/README.md b/packages/core/README.md index aa3bc9817b..16233d550b 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -491,7 +491,7 @@ 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. -`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). Before `buildCommand` runs, `Hosting` refuses a framework version its adapter doesn't support, so a deploy doesn't wait for a build that is then rejected: SvelteKit 3 fails with `UnsupportedSvelteKitVersionError` (Hosting supports SvelteKit 2; see the `@aws-cdk-blocks/hosting` README). Two synths skip both: - **Destroy.** `npm run destroy` and `npm run sandbox:destroy` don't deploy the frontend, so `Hosting` reuses the build output already on disk instead of building. It builds only when there is no output, for example on a fresh clone. Each framework adapter checks the output it deploys: a Next.js destroy reuses the `.open-next/` output of an earlier deploy, and with only `.next/` (after a plain `next build`) OpenNext still builds, because the synth needs its output. An exported `BLOCKS_SKIP_FRONTEND_BUILD=1` doesn't apply to a destroy. - **A deploy you ask to run on the existing build.** Set `BLOCKS_SKIP_FRONTEND_BUILD=1`, for example `BLOCKS_SKIP_FRONTEND_BUILD=1 npm run deploy`, to deploy what is already in the build output directory. Nothing is built, and a missing build output (the output directory, or the output the framework adapter deploys, such as Next.js's `.open-next/`) fails the synth with a message naming the variable. The build bakes in `BLOCKS_API_URL`, so only reuse a build made for the same backend; a deploy never reuses one on its own. diff --git a/packages/core/src/hosting.test.ts b/packages/core/src/hosting.test.ts index 1a56f167c9..d600109eb5 100644 --- a/packages/core/src/hosting.test.ts +++ b/packages/core/src/hosting.test.ts @@ -4473,6 +4473,57 @@ describe('Hosting — skipping the frontend build', () => { }); }); +// An unsupported framework version is refused before `buildCommand` runs, so +// the user doesn't wait for a full build that the adapter then rejects. +describe('Hosting — unsupported framework version', () => { + let tmpDir: string; + // Records that it ran, then writes the adapter-node output a real build would. + const BUILD = `node -e "const f=require('fs');f.writeFileSync('built.txt','1');f.mkdirSync('build',{recursive:true})"`; + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bb-hosting-kit3-')); + fs.writeFileSync( + path.join(tmpDir, 'package.json'), + JSON.stringify({ name: 'kit3', devDependencies: { '@sveltejs/kit': '^3.2.0' } }), + ); + const kitDir = path.join(tmpDir, 'node_modules', '@sveltejs', 'kit'); + fs.mkdirSync(kitDir, { recursive: true }); + fs.writeFileSync(path.join(kitDir, 'package.json'), JSON.stringify({ name: '@sveltejs/kit', version: '3.3.1' })); + }); + afterEach(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); + }); + + it('refuses SvelteKit 3 before running buildCommand', () => { + const stack = new Stack(new App(), 'Kit3Stack'); + assert.throws( + () => + new Hosting(stack, 'Hosting', { + root: tmpDir, + api: MOCK_API, + framework: 'sveltekit', + buildCommand: BUILD, + buildOutputDir: 'build', + }), + (err: Error) => { + assert.ok(err instanceof HostingError, 'expected a HostingError'); + assert.strictEqual(err.code, 'UnsupportedSvelteKitVersionError'); + return true; + }, + ); + assert.ok(!fs.existsSync(path.join(tmpDir, 'built.txt')), 'buildCommand should not run'); + }); + + it('refuses a detected SvelteKit 3 project the same way', () => { + const stack = new Stack(new App(), 'Kit3DetectStack'); + assert.throws( + () => new Hosting(stack, 'Hosting', { root: tmpDir, api: MOCK_API, buildCommand: BUILD }), + /UnsupportedSvelteKitVersionError|SvelteKit 3\.3\.1/, + ); + assert.ok(!fs.existsSync(path.join(tmpDir, 'built.txt')), 'buildCommand should not run'); + }); +}); + // A deploy synthesizes with `NODE_OPTIONS=--conditions=cdk`. `buildCommand` // must run without that condition, so a build that loads `@aws-cdk-blocks/*` // doesn't get their CDK constructs, but with the user's other NODE_OPTIONS. diff --git a/packages/core/src/hosting.ts b/packages/core/src/hosting.ts index d8d8ac29be..38eba2c172 100644 --- a/packages/core/src/hosting.ts +++ b/packages/core/src/hosting.ts @@ -8,6 +8,7 @@ import { basename, join, relative, resolve } from 'node:path'; import type { DeployManifest, FrameworkType, KindStoreOptions, RouteBehavior } from '@aws-cdk-blocks/hosting/constructs'; import { appBuildEnv, + assertFrameworkSupported, detectFramework, type FrameworkAdapterFn, getAdapter, @@ -1192,6 +1193,11 @@ export class Hosting extends Construct { // still reports the framework it was deploying. writeFrameworkSink(framework); + // Refuse an unsupported framework version (e.g. SvelteKit 3) before the + // build below, so the user doesn't wait for a build the adapter rejects. + // A custom adapter owns its own checks. + if (!props.customAdapter) assertFrameworkSupported(framework, root); + // ── 2. Optionally run the build ────────────────────────────── // A destroy reuses an existing build, and `BLOCKS_SKIP_FRONTEND_BUILD=1` // makes a deploy reuse it (see common/frontend-build.ts). The adapter gets diff --git a/packages/create-blocks-app/README.md b/packages/create-blocks-app/README.md index 89797ab552..6dea54aaf5 100644 --- a/packages/create-blocks-app/README.md +++ b/packages/create-blocks-app/README.md @@ -40,6 +40,8 @@ This writes `cdk-blocks/tsconfig.json`, a TypeScript project that checks the bac In an npm workspaces monorepo, the app's `cdk-blocks/` folder has to be a workspace of the monorepo root too: npm installs the app's dependencies at the root and does not read the app's own `"workspaces": ["cdk-blocks"]`. When the app is a workspace of an enclosing root that does not list `/cdk-blocks`, `create-blocks-app` stops before it writes anything and prints the `"workspaces"` entry to add; add it and run the command again. +A SvelteKit project must be on SvelteKit 2 (`@sveltejs/kit` `>=2.0.0 <3.0.0`), which the Hosting construct deploys. SvelteKit 3, which `npx sv create` scaffolds today, is not supported yet: `create-blocks-app` stops before it writes anything and prints the SvelteKit 2 versions to pin (`npm install -D @sveltejs/kit@^2 @sveltejs/adapter-node@^5 @sveltejs/vite-plugin-svelte@^5 vite@^6`, with the SvelteKit config in `svelte.config.js`). It reads the installed `@sveltejs/kit` when `node_modules` has it, and the lowest version of the `package.json` range otherwise. Support for SvelteKit 3 is tracked in [#984](https://github.com/aws/cdk-blocks/issues/984). + It also adds to your `.gitignore` (or creates one): the AWS CDK Blocks build and local-data paths, secret and key-material patterns such as `.env` and `*.pem`, and `node_modules` unless a line such as `node_modules`, `node_modules/` or `/node_modules` already ignores it. A `.gitignore` that un-ignores it (`!node_modules`) is left as it is. Lines you already have are kept, and the CLI prints the ones it adds. ### Add Blocks to an Amplify Gen 2 Project diff --git a/packages/create-blocks-app/src/cli.test.ts b/packages/create-blocks-app/src/cli.test.ts index fe4a43c148..00a43e43a5 100644 --- a/packages/create-blocks-app/src/cli.test.ts +++ b/packages/create-blocks-app/src/cli.test.ts @@ -1044,6 +1044,48 @@ describe('create-blocks-app auto-detection', () => { } }); + it('refuses an existing SvelteKit 3 project before it writes anything', () => { + // Hosting deploys SvelteKit 2 only; `npx sv create` scaffolds SvelteKit 3. + const tmpDir = mkdtempSync(join(tmpdir(), 'create-blocks-app-kit3-')); + const pkg = JSON.stringify({ name: 'my-svelte-app', version: '0.0.1', devDependencies: { '@sveltejs/kit': '^3.2.0', vite: '^8.0.0' } }); + writeFileSync(join(tmpDir, 'package.json'), pkg); + try { + const result = run(['.', '-y', '--skip-install'], tmpDir); + assert.strictEqual(result.exitCode, 1, result.stdout); + assert.match(result.stderr, /SvelteKit 3 is not supported yet/); + assert.ok(result.stderr.includes('@sveltejs/kit@^2 @sveltejs/adapter-node@^5 @sveltejs/vite-plugin-svelte@^5 vite@^6'), result.stderr); + assert.ok(result.stderr.includes('https://github.com/aws/cdk-blocks/issues/984'), result.stderr); + assert.match(result.stderr, /Nothing was written/); + assert.strictEqual(readFileSync(join(tmpDir, 'package.json'), 'utf-8'), pkg); + assert.deepStrictEqual(readdirSync(tmpDir), ['package.json'], 'nothing is written'); + } finally { + rmSync(tmpDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); + } + }); + + it('reads the installed SvelteKit version over the package.json range', () => { + const tmpDir = mkdtempSync(join(tmpdir(), 'create-blocks-app-kit-installed-')); + const kitDir = join(tmpDir, 'node_modules', '@sveltejs', 'kit'); + mkdirSync(kitDir, { recursive: true }); + try { + // A non-semver range: the installed 3.x decides. + writeFileSync(join(tmpDir, 'package.json'), JSON.stringify({ name: 'kit-latest', devDependencies: { '@sveltejs/kit': 'latest' } })); + writeFileSync(join(kitDir, 'package.json'), JSON.stringify({ name: '@sveltejs/kit', version: '3.3.1' })); + const refused = run(['.', '-y', '--skip-install'], tmpDir); + assert.strictEqual(refused.exitCode, 1, refused.stdout); + assert.match(refused.stderr, /SvelteKit 3 is not supported yet \(installed: 3\.3\.1\)/); + assert.ok(!existsSync(join(tmpDir, 'cdk-blocks'))); + + // SvelteKit 2 installed: the backend is added as usual. + writeFileSync(join(kitDir, 'package.json'), JSON.stringify({ name: '@sveltejs/kit', version: '2.70.3' })); + const added = run(['.', '-y', '--skip-install'], tmpDir); + assert.strictEqual(added.exitCode, 0, added.stderr); + assert.ok(existsSync(join(tmpDir, 'cdk-blocks', 'index.ts'))); + } finally { + rmSync(tmpDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); + } + }); + it('gives an Amplify app without Next.js the default template\'s backend tsconfig', () => { const tmpDir = join(__dirname, '../.test-amplify-tsconfig'); mkdirSync(join(tmpDir, 'amplify'), { recursive: true }); diff --git a/packages/create-blocks-app/src/index.ts b/packages/create-blocks-app/src/index.ts index e4f0df0a27..e4f4b9e68d 100644 --- a/packages/create-blocks-app/src/index.ts +++ b/packages/create-blocks-app/src/index.ts @@ -1083,10 +1083,48 @@ function backendDevConfig(blocks: unknown): Record | undefined return Object.keys(kept).length > 0 ? { dev: kept } : undefined; } +/** + * The major version of the project's `@sveltejs/kit`: the installed one when + * `node_modules` has it, else the lowest major its `package.json` range allows + * (`^3.2.0` is 3). `undefined` when the project doesn't use SvelteKit, or the + * range names no version (`latest`, `workspace:*`). + */ +async function svelteKitMajor(targetDir: string, pkg: PackageDeps): Promise<{ major: number; installed?: string } | undefined> { + const installed: unknown = await readFile(join(targetDir, 'node_modules', '@sveltejs', 'kit', 'package.json'), 'utf-8') + .then((text) => JSON.parse(text).version, () => undefined); + if (typeof installed === 'string' && /^\d+\./.test(installed)) { + return { major: Number.parseInt(installed, 10), installed }; + } + const range = pkg.devDependencies?.['@sveltejs/kit'] ?? pkg.dependencies?.['@sveltejs/kit']; + const match = typeof range === 'string' ? /^\s*(?:[~^]|>=?|=)?\s*v?(\d+)/.exec(range) : null; + return match ? { major: Number.parseInt(match[1], 10) } : undefined; +} + +/** + * Stops before anything is written when the project uses a SvelteKit version + * the Hosting construct can't deploy (SvelteKit 3, which `npx sv create` + * scaffolds). Synth would refuse it too, so adding the backend now would only + * leave the project half set up. Prints the versions to pin instead. + */ +async function refuseUnsupportedSvelteKit(targetDir: string): Promise { + const pkg: PackageDeps = JSON.parse(await readFile(join(targetDir, 'package.json'), 'utf-8')); + const kit = await svelteKitMajor(targetDir, pkg); + if (!kit || kit.major < 3) return; + console.error(`Error: SvelteKit ${kit.major} is not supported yet${kit.installed ? ` (installed: ${kit.installed})` : ''}.`); + console.error('AWS CDK Blocks Hosting deploys SvelteKit 2 (@sveltejs/kit >=2.0.0 <3.0.0) with'); + console.error('@sveltejs/adapter-node 5 and the SvelteKit config in svelte.config.js.'); + console.error(''); + console.error('Pin the SvelteKit 2 toolchain, move the config back to svelte.config.js, then run this command again:'); + console.error(' npm install -D @sveltejs/kit@^2 @sveltejs/adapter-node@^5 @sveltejs/vite-plugin-svelte@^5 vite@^6'); + console.error('SvelteKit 3 support is tracked in https://github.com/aws/cdk-blocks/issues/984. Nothing was written.'); + process.exit(1); +} + async function integrateWithExistingProject(targetDir: string, templateName = 'default', skipConfirm = false, skipInstall = false) { if (templateName === 'amplify') { throw new Error('The amplify template requires an existing Amplify Gen 2 project (amplify/backend.ts).'); } + await refuseUnsupportedSvelteKit(targetDir); const workspaceRoot = await enclosingWorkspaceRoot(targetDir); console.log('\n🔍 Detected existing project (package.json found)\n'); console.log('This will add an AWS CDK Blocks backend to your project:'); diff --git a/packages/hosting/README.md b/packages/hosting/README.md index ed49421bc3..cead3f1d4f 100644 --- a/packages/hosting/README.md +++ b/packages/hosting/README.md @@ -39,7 +39,7 @@ new HostingConstruct(stack, 'Hosting', { manifest }); | `nextjsAdapter` | `{ projectDir, configPath?, skipBuild? }` | A Next.js app, built with OpenNext. `configPath` is a custom `open-next.config.ts`, relative to `projectDir`. | | `nuxtAdapter`, `nitroAdapter` | `{ projectDir, preset?, buildCommand?, skipBuild? }` | A Nuxt app, or another Nitro app. `preset` overrides the Nitro preset. | | `astroAdapter` | `{ projectDir, buildCommand?, skipBuild?, bodySizeLimit? }` | An Astro app. `bodySizeLimit` is the largest request body in bytes (default 20 MB). | -| `sveltekitAdapter` | `{ projectDir, buildCommand?, skipBuild?, bodySizeLimit? }` | A SvelteKit app. `bodySizeLimit` as for Astro. | +| `sveltekitAdapter` | `{ projectDir, buildCommand?, skipBuild?, bodySizeLimit? }` | A SvelteKit 2 app (see [SvelteKit: the supported version](#sveltekit-the-supported-version)). `bodySizeLimit` as for Astro. | | `spaAdapter` | `projectDir, { buildOutputDir?, spaFallback? }` | An already built single-page app in `dist/`, `build/` or `out/`. `spaFallback: false` declares a multi-page static site. | `skipBuild: true` reuses an existing build output. @@ -625,6 +625,23 @@ const blocksStack = await BlocksStack.create(app, stackName, { - `npm run destroy` passes no stack selection, so the CDK CLI refuses to destroy an app with more than one top-level stack. +## SvelteKit: the supported version + +The SvelteKit adapter supports **SvelteKit 2 only**: `@sveltejs/kit` +`>=2.0.0 <3.0.0`, built with `@sveltejs/adapter-node` 5, with the SvelteKit +config in `svelte.config.js`. + +- SvelteKit 3, which `npx sv create` scaffolds today, is not supported yet. + Synth refuses it with `UnsupportedSvelteKitVersionError` before it runs the + app's build. Support is tracked in + [#984](https://github.com/aws/cdk-blocks/issues/984). +- To deploy a project scaffolded with SvelteKit 3, pin the SvelteKit 2 + toolchain and move the SvelteKit config back to `svelte.config.js`: + + ```bash + npm install -D @sveltejs/kit@^2 @sveltejs/adapter-node@^5 @sveltejs/vite-plugin-svelte@^5 vite@^6 + ``` + ## SSR compute: Lambda or Lambda Web Functions By default the SSR server runs on a Lambda function behind an API Gateway REST @@ -1332,6 +1349,7 @@ synth. `error.name` and `error.code` hold the name in the table, and | `UnsupportedComputeFrontDoorError` | `compute.type: 'web-function'` behind a door other than CloudFront. | | `UnsupportedFrontDoorError` | `frontDoor` is not a front door, `'none'` is set for an app with a server, or a custom door fails the wiring check. | | `UnsupportedFrontDoorSettingError` | The door kind doesn't implement a setting. | +| `UnsupportedSvelteKitVersionError` | The installed `@sveltejs/kit` is not SvelteKit 2 (`>=2.0.0 <3.0.0`). Thrown before the app's build runs. | | `UnsupportedRoutePatternError` | ALB: one pattern has more than six wildcards. API Gateway: a backend route has a wildcard other than one trailing `/*`. | | `WafRegionError` | A CloudFront-scoped WAF is enabled in a known region outside us-east-1 and region validation isn't skipped. | | `WebFunctionPolicyAlreadySetError` | `allowCloudFrontInvoke()` was called twice on the same Web Function. | diff --git a/packages/hosting/src/adapters/adapters.test.ts b/packages/hosting/src/adapters/adapters.test.ts index b7108ab9ad..99ebc15fb4 100644 --- a/packages/hosting/src/adapters/adapters.test.ts +++ b/packages/hosting/src/adapters/adapters.test.ts @@ -7,6 +7,7 @@ import * as fs from 'fs'; import * as path from 'path'; import * as os from 'os'; import { + assertFrameworkSupported, detectFramework, getAdapter, readProjectDeps, @@ -270,3 +271,43 @@ void describe('getAdapter', () => { ); }); }); + +void describe('assertFrameworkSupported', () => { + let tmp: string; + beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'adapters-supported-')); + }); + afterEach(() => { + fs.rmSync(tmp, { recursive: true, force: true }); + }); + + void it('refuses SvelteKit 3 without building anything', () => { + writePackageJson(tmp, { devDependencies: { '@sveltejs/kit': '^3.2.0' } }); + installFakePackage(tmp, '@sveltejs/kit', '3.3.1'); + assert.throws( + () => assertFrameworkSupported('sveltekit', tmp), + (error: Error) => { + assert.strictEqual(error.name, 'UnsupportedSvelteKitVersionError'); + assert.match(error.message, /3\.3\.1/); + return true; + }, + ); + assert.deepStrictEqual( + fs.readdirSync(tmp).sort(), + ['node_modules', 'package.json'], + 'the check writes nothing into the project', + ); + }); + + void it('accepts SvelteKit 2', () => { + writePackageJson(tmp, { devDependencies: { '@sveltejs/kit': '^2.15.0' } }); + installFakePackage(tmp, '@sveltejs/kit', '2.15.0'); + assert.doesNotThrow(() => assertFrameworkSupported('sveltekit', tmp)); + }); + + void it('does nothing for a framework without a version check', () => { + writePackageJson(tmp, { dependencies: { react: '^18.0.0' } }); + assert.doesNotThrow(() => assertFrameworkSupported('spa', tmp)); + assert.doesNotThrow(() => assertFrameworkSupported('static', tmp)); + }); +}); diff --git a/packages/hosting/src/adapters/index.ts b/packages/hosting/src/adapters/index.ts index a462a6f3e7..72af53310e 100644 --- a/packages/hosting/src/adapters/index.ts +++ b/packages/hosting/src/adapters/index.ts @@ -9,7 +9,7 @@ import { nextjsAdapter } from './nextjs.js'; import { nitroAdapter } from './nitro.js'; import { nuxtAdapter } from './nuxt.js'; import { astroAdapter } from './astro.js'; -import { sveltekitAdapter } from './sveltekit.js'; +import { assertSvelteKitVersion, sveltekitAdapter } from './sveltekit.js'; import { DeployManifest } from '../manifest/types.js'; export { spaAdapter } from './spa.js'; @@ -54,6 +54,11 @@ export type FrameworkAdapterFn = (projectDir: string) => DeployManifest; */ type AdapterRegistryEntry = { adapter: FrameworkAdapterFn; + /** + * Checks that need no build (an unsupported framework version). Run by + * {@link assertFrameworkSupported} before any build; must write nothing. + */ + preflight?: (projectDir: string) => void; }; /** @@ -72,12 +77,33 @@ const adapterRegistry = new Map([ ['astro', { adapter: (projectDir: string) => astroAdapter({ projectDir }) }], [ 'sveltekit', - { adapter: (projectDir: string) => sveltekitAdapter({ projectDir }) }, + { + adapter: (projectDir: string) => sveltekitAdapter({ projectDir }), + preflight: assertSvelteKitVersion, + }, ], ['spa', { adapter: spaAdapter }], ['static', { adapter: spaAdapter }], ]); +/** + * Fail fast when the project uses a framework version the built-in adapter + * does not support (e.g. SvelteKit 3). Runs only the adapter's build-free + * checks and writes nothing, so call it before running the app's build: + * otherwise the user waits for a full build that the adapter then refuses. + * Unknown frameworks and frameworks with no such check pass through (the + * adapter itself reports anything else). + * @param framework - the framework type (as passed to {@link getAdapter}) + * @param projectDir - absolute path to the project root + * @throws HostingError e.g. `UnsupportedSvelteKitVersionError` + */ +export const assertFrameworkSupported = ( + framework: string, + projectDir: string, +): void => { + adapterRegistry.get(framework)?.preflight?.(projectDir); +}; + /** * Read the merged dependency map from the project's `package.json`. * diff --git a/packages/hosting/src/adapters/sveltekit.test.ts b/packages/hosting/src/adapters/sveltekit.test.ts index 28d2c503ae..a3cf3b99a3 100644 --- a/packages/hosting/src/adapters/sveltekit.test.ts +++ b/packages/hosting/src/adapters/sveltekit.test.ts @@ -237,6 +237,25 @@ void describe('sveltekitAdapter — manifest from build/ (skipBuild)', () => { ); }); + void it('tells a SvelteKit 3 user which versions to pin', () => { + scaffoldBuild(tmp, { kitVersion: '3.3.1' }); + assert.throws( + () => sveltekitAdapter({ projectDir: tmp, skipBuild: true }), + (error: Error & { resolution?: string }) => { + assert.strictEqual(error.name, 'UnsupportedSvelteKitVersionError'); + assert.match(error.message, /SvelteKit 3\.3\.1 is not supported yet/); + const resolution = error.resolution ?? ''; + assert.match(resolution, /@sveltejs\/kit@\^2/); + assert.match(resolution, /@sveltejs\/adapter-node@\^5/); + assert.match(resolution, /@sveltejs\/vite-plugin-svelte@\^5/); + assert.match(resolution, /vite@\^6/); + assert.match(resolution, /svelte\.config\.js/); + assert.match(resolution, /github\.com\/aws\/cdk-blocks\/issues\/984/); + return true; + }, + ); + }); + void it('serves a prerendered root (/) from S3 instead of the SSR catch-all', () => { scaffoldBuild(tmp, { prerendered: { 'index.html': '

home

' } }); const m = sveltekitAdapter({ projectDir: tmp, skipBuild: true }); diff --git a/packages/hosting/src/adapters/sveltekit.ts b/packages/hosting/src/adapters/sveltekit.ts index a29da8c9e2..900338df38 100644 --- a/packages/hosting/src/adapters/sveltekit.ts +++ b/packages/hosting/src/adapters/sveltekit.ts @@ -235,7 +235,19 @@ export const sveltekitAdapter = ( // ---- version guard ---- -const assertSvelteKitVersion = (projectDir: string): void => { +/** Public issue tracking SvelteKit 3 support; named in the refusal so users can follow it. */ +const SVELTEKIT_3_ISSUE_URL = 'https://github.com/aws/cdk-blocks/issues/984'; + +/** + * Throw `UnsupportedSvelteKitVersionError` unless the installed `@sveltejs/kit` + * is within {@link VERIFIED_SVELTEKIT_RANGE}. Reads the installed version (not + * the `package.json` range) and writes nothing, so it is safe to call before + * any build: core `Hosting` calls it (through `assertFrameworkSupported`) + * before it runs the app's `buildCommand`, and the adapter calls it again + * before its own build. + * @param projectDir - absolute path to the SvelteKit project root + */ +export const assertSvelteKitVersion = (projectDir: string): void => { const info = getProjectPackageInfo('@sveltejs/kit', projectDir); const version = info?.version; // Enforce the FULL verified range — both the floor (< 2.0 rejected) and the @@ -243,6 +255,19 @@ const assertSvelteKitVersion = (projectDir: string): void => { // `build/` layout the manifest builder depends on, so we refuse it until the // range is deliberately bumped after re-verification. `satisfies` honors the // `<` bound the version_pins.test.ts asserts on. + if (version && semver.valid(version) && semver.major(version) >= 3) { + // SvelteKit 3 (what `npx sv create` scaffolds) moved its config into the + // `sveltekit()` Vite plugin and needs Vite 8; the bridge and the build + // layout are only verified on SvelteKit 2. Say exactly what to pin. + throw new HostingError('UnsupportedSvelteKitVersionError', { + message: `SvelteKit ${version} is not supported yet: Hosting supports SvelteKit 2 (${VERIFIED_SVELTEKIT_RANGE}).`, + resolution: + 'Pin the SvelteKit 2 toolchain and keep the SvelteKit config in svelte.config.js: ' + + '`npm install -D @sveltejs/kit@^2 @sveltejs/adapter-node@^5 @sveltejs/vite-plugin-svelte@^5 vite@^6` ' + + '(or your package manager equivalent). SvelteKit 3 support is tracked in ' + + `${SVELTEKIT_3_ISSUE_URL}.`, + }); + } if (!version || !semver.satisfies(version, VERIFIED_SVELTEKIT_RANGE)) { throw new HostingError('UnsupportedSvelteKitVersionError', { message: `SvelteKit version ${