Skip to content

CLI: TypeScript AppHost top-level await fails in brownfield repos without type:module #16124

Closed

Description

Description

The TypeScript AppHost skeleton uses top-level await, which requires ESM. When aspire init runs in a brownfield repo that already has a package.json without "type": "module", the generated apphost.ts fails at runtime with:

ERROR: Top-level await is currently not supported with the "cjs" output format

Root Cause

TypeScriptLanguageSupport sets "type": "module" only for greenfield projects (when no package.json exists, line 155). For brownfield projects, it doesn't inject "type": "module" — and the PackageJsonMerger doesn't handle it either.

The separate tsconfig.apphost.json has "module": "NodeNext" but that alone doesn't make tsx treat the file as ESM — the package.json type field (or .mts extension) is what determines the module system.

Reproduction

  1. Have a repo with an existing package.json that does NOT have "type": "module" (common in repos with CJS build scripts using require())
  2. Run aspire init and select TypeScript
  3. Run aspire start
  4. The AppHost fails with the top-level await / CJS error

Why this is hard

Simply adding "type": "module" to the existing package.json breaks repos that have CJS scripts using require(). For example, the excalidraw monorepo has 11+ build scripts using require() — adding "type": "module" would break all of them.

The fix needs to ensure the apphost.ts file specifically is treated as ESM without affecting the rest of the project's module resolution. Possible approaches:

  • Have tsx/esbuild treat the file as ESM via CLI flags regardless of package.json type
  • Use Node.js --experimental-detect-module or --input-type=module
  • Other runtime-level solutions that don't modify the user's package.json

Workaround

The agent wrapped the AppHost code in an async IIFE to avoid top-level await:

` ypescript
import { createBuilder } from './.modules/aspire.js';

(async () => {
const builder = await createBuilder();
// ... resource definitions ...
await builder.build().run();
})();
`

Additional Context

Discovered during an aspire init session against the excalidraw monorepo. Session export: https://gist.github.com/maddymontaquila/98b78fbd39bba0c499ac723bda9bb8b8

Related: #16121 (npm install hardcoded for TypeScript AppHost)

Metadata

Metadata

Labels

area-polyglotIssues related to polyglot apphostsaspirifridaysBugs found during Aspiri-Friday

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions