CLI
@miiajs/cli creates MiiaJS projects (miia new, or bun create miia), adds features to them (miia add), generates modules, controllers, services, CRUD resources and Drizzle tables (miia g), and runs them on Bun, Node.js and Deno (miia dev, build, start, check).
Create a project
bun create miia my-app
npm create miia@latest my-app
pnpm create miia my-app
yarn create miia my-app
deno run -A npm:create-miia my-app
create-miia is a thin package that runs miia new with the same arguments; bunx @miiajs/cli new my-app does the same. The generated project lists @miiajs/cli as a devDependency, so its scripts call miia directly. Outside the scripts, run the project's own binary with bunx miia ... or npx miia ...; a project created with --pm deno gets a miia task for that, deno task miia ..., so it runs the project's CLI version rather than the latest from npm.
miia new
bun create miia my-app
bun create miia my-app --runtime node --pm pnpm --features jwt-auth,swagger --db drizzle-postgres
bun create miia my-app -y # defaults, no prompts
bun create miia . # in the current, empty folder
npm keeps flags before -- for itself: npm create miia@latest my-app -- --runtime node -y.
In a terminal the CLI asks for whatever the flags leave open: name, runtime, package manager (Node.js only), features and database. With -y, or without a terminal (CI, scripts), nothing is asked and the defaults apply; the name is then required.
| Flag | Default | Description |
|---|---|---|
[name] | prompt | npm package name (lower case, @scope/name allowed); the folder is its last segment. . uses the current folder and its name |
--runtime, -r | bun if installed, else node | bun, node, deno |
--pm | bun for Bun, deno for Deno; for Node.js the package manager that runs the command (npm create -> npm, pnpm create -> pnpm), else npm | bun, npm, pnpm, yarn, deno |
--features | none | Comma-separated add-ons, see miia add |
--db | none | One database add-on |
--yes, -y | false | No prompts |
--skip-install | false | Write the files, skip the install |
--dry-run | false | Print the files and dependencies without writing anything |
The folder must not exist or be empty. Nothing is written until every step has succeeded; a failed install leaves the files in place and says which command to run.
What you get
my-app/
├── .env # your local values, git-ignored
├── .env.example # every variable; secrets left empty
├── .gitignore
├── README.md
├── package.json
├── tsconfig.json
└── src/
├── main.ts
├── env.schema.ts
└── app/
├── app.module.ts
├── app.controller.ts
├── app.service.ts
└── app.test.ts
The project is laid out for strict module boundaries: ConfigModule is configured { global: true } and validates src/env.schema.ts (NODE_ENV, HOST, PORT), and main.ts reads the port and host through a typed ConfigService:
import { ConfigService } from '@miiajs/config'
import { Miia } from '@miiajs/core'
import { AppModule } from './app/app.module.js'
import type { Env } from './env.schema.js'
const app = new Miia().register(AppModule)
const config = app.get<ConfigService<Env>>(ConfigService)
await app.listen(config.get('PORT'), config.get('HOST'))
Per runtime:
| Runtime | Differences | test script |
|---|---|---|
| Bun | @types/bun | bun test |
| Node.js | @miiajs/node-server (serve passed to listen), tsx, tsconfig.build.json for miia build | node --import tsx --test "src/**/*.test.ts" |
| Deno | deno.json with "unstable": ["sloppy-imports"] (the .js specifiers point at .ts files) | deno test --no-check --allow-all src/ |
Every script pins the runtime (miia dev --runtime bun), so the project does not depend on runtime detection. The scripts are dev, build, start, check and test.
Tests sit next to the code (src/**/*.test.ts) and test their own module through TestApp, not the whole AppModule, so they pass without .env or a database. They are written for bun:test; on Node.js and Deno the import becomes node:test plus the expect package, which has the same API. Each test creates and closes its own TestApp: node:test on Deno has no before/after hooks.
miia add
Adds features to an existing project. miia new --features ... --db ... applies the same add-ons the same way.
bunx miia add jwt-auth swagger
bunx miia add drizzle-sqlite --dry-run
bunx miia add # pick from a list (in a terminal)
| Add-on | What it adds | Runtimes |
|---|---|---|
jwt-auth | @miiajs/auth + @miiajs/jwt: a global AuthModule (exports JwtAuth) with POST /auth/register, POST /auth/login, GET /auth/me, the LocalAuth and JwtAuth providers, zod schemas in src/auth/schemas/, a UsersModule with UsersService and the User types in src/users/ (both go into the imports of the root module, UsersModule first; AuthModule imports it too), users kept in the project's database or, without one, in memory (below), ctx.user typing in src/types/core.d.ts, JWT_SECRET (a random value in .env, empty in .env.example, so a copied example does not start with a known secret) and a test. Passwords go through PasswordService (src/auth/password.service.ts): Bun.password on Bun, scrypt from node:crypto elsewhere | all |
swagger | SwaggerModule: the spec at /docs/json, the UI at /docs | all |
cors | app.use(cors({ origin: config.get('CORS_ORIGIN') })) in main.ts, CORS_ORIGIN (default *) | all |
serve-static | serveStatic(app, '/static', './public') and public/index.html | all |
rate-limit | RateLimitModule (100 requests a minute per client) and the global RateLimitGuard | all |
biome | biome.json, format and lint scripts; generated files are formatted from then on | all |
drizzle-postgres | DrizzleModule with postgres, src/db.schema.ts (an empty barrel: tables come from miia g table), src/db.ts (the typed drizzleDb() handle), drizzle.config.ts, db:generate and db:migrate, DATABASE_URL | all |
drizzle-mysql | The same with mysql2 | all |
drizzle-sqlite | The same on bun:sqlite (Bun; db:migrate runs src/db.migrate.ts) or better-sqlite3 (Node.js). data.db is git-ignored | Bun, Node.js |
papr | PaprModule with papr and mongodb, MONGODB_URL | all |
mongoose | MongooseModule with mongoose, MONGODB_URL | all |
Modules that the rest of the app injects from (JWT, rate limit, databases) are registered { global: true } in the root module, and their factories read config as resolve<ConfigService<Env>>(ConfigService).getOrThrow('JWT_SECRET'). A project has one database add-on: adding a second one is refused. It runs before the other add-ons, whatever the order of the ids, so miia add jwt-auth drizzle-sqlite and miia add drizzle-sqlite jwt-auth give the same project.
A database add-on also adds a ## Database section to README.md, before ## Next steps (nothing when the project has no README or already has that heading): where the connection URL comes from, a docker run line that starts PostgreSQL, MySQL or MongoDB with the project's database, and for Drizzle how to add a table (miia g table, db:generate, db:migrate) and query it through the typed db handle. miia new lists the short version in its next steps, before the dev command; miia add prints it after the list of added add-ons:
Next:
start PostgreSQL with a "my_app" database (see README)
bunx miia g table posts
The commands use the project's package manager (npx miia, pnpm exec miia, deno task miia, ...). SQLite has no server to start, so its list is only the g table line. With jwt-auth in the same run there is a table already, and the app needs it before anyone can register: db:generate and db:migrate take the place of g table, in this list and in the README, which creates the tables before it starts the app.
What miia add does:
- Finds the files to edit: the root module (
src/app/app.module.ts, or the modulesrc/main.tsregisters),src/main.ts(statements go beforeapp.listen()), the env schema (src/env.schema.ts, or the firstsrc/**/env.schema.ts),.env.exampleand.env. The runtime comes from--runtimein thedevscript, else from detection; the package manager from the lockfile. - Edits code in place. Imports and module entries are inserted at the right spot through the TypeScript compiler API; the rest of each file stays byte for byte, line endings and indentation included. When it cannot edit something safely (
importsheld in a variable, a spread, abootstrap()function aroundlisten, noConfigModule), it prints what to add by hand instead of guessing. - Skips what is installed.
swagger is already installed; running the samemiia addtwice changes nothing. - Refuses conflicting files.
jwt-authcreatessrc/users/*andsrc/types/core.d.ts. If such a file exists with other content (for example aftermiia g resource users, ormiia g table usersbeforejwt-authon Drizzle), the command lists every conflict and writes nothing. - Checks git first. On a dirty working tree it warns and, in a terminal, asks before going on (
-yskips the question). - Installs and formats. After writing, it runs the install when dependencies changed (
--skip-installto skip) and formats the changed files with the project's formatter.
| Flag | Default | Description |
|---|---|---|
[add-ons...] | prompt in a terminal, error without one | Add-on ids |
--yes, -y | false | Do not ask about a dirty git tree |
--skip-install | false | Skip the install |
--dry-run | false | Print the changed files and new dependencies without writing |
Where jwt-auth keeps users
The add-on looks at the database the project has, in the same run or from before:
| Database | Users live in | Files in src/users/ |
|---|---|---|
| Drizzle | A users table with UUID ids, for the dialect in drizzle.config.ts. The table goes into the schema file that config names, and the next steps are db:generate and db:migrate | users.table.ts, users.service.ts, users.types.ts |
| Papr | A users collection with the native ObjectId _id; User.id is its string. UsersService.onInit() creates the unique index on email | users.model.ts, users.service.ts, users.module.ts |
| Mongoose | A User model with the native ObjectId _id; User.id is its string. The schema declares email unique | users.model.ts, users.service.ts, users.module.ts |
| None | A Map with UUID ids in UsersService, gone on restart | users.service.ts, users.types.ts |
The API of UsersService is the same in all four, and so is the rest of src/auth/. The generated auth.test.ts replaces UsersService with a fake over a Map, so it needs neither a database nor DATABASE_URL, and does not exercise the real store.
Warnings instead of guesses:
miia add jwt-authwhendrizzle.config.tsis missing or names another dialect: users stay in memory, and the warning says so. Aschemathat is not one file (an array, a glob) leaves theuserstable for you to add to the schema by hand, and withoutsrc/db.tsthe warning says thatusers.service.tsimports the typed handle from../db.js.miia add <database>in a project whosejwt-authkeeps users in memory:users.service.tsis not rewritten, the warning sayssrc/users/users.service.ts keeps users in memory: move it to the database, and the README and the next steps are those of a project without auth.
miia generate
Generates artifacts inside a project. Alias: miia g.
bunx miia g resource posts
bunx miia g service audit --export
bunx miia g c admin/users
bunx miia g table posts
UPDATE src/app/app.module.ts
CREATE src/posts/posts.controller.ts
CREATE src/posts/posts.module.ts
CREATE src/posts/posts.service.ts
CREATE src/posts/posts.test.ts
CREATE src/posts/posts.types.ts
CREATE src/posts/schemas/create-posts.schema.ts
CREATE src/posts/schemas/posts-id-params.schema.ts
CREATE src/posts/schemas/update-posts.schema.ts
| Schematic | Alias | Generates | Registered in the parent module |
|---|---|---|---|
module | m | @Module class | imports |
controller | c | @Controller with GET / | controllers |
service | s | @Injectable class | providers; also exports with --export |
resource | r | Module, controller, service, an entity type, schemas and a test | imports; the resource module exports its service |
guard | - | CanActivate class | nowhere: a guard no module declares is built for the controller that uses it, so it works from any module |
middleware | - | Middleware function | nowhere: use it with app.use() or @Use() |
table | - | Drizzle table for the project's dialect, with its types | nowhere: its line goes into the Drizzle schema file |
Resource. A working CRUD module: zod route schemas (Create<Name>Schema, Update<Name>Schema, <Name>IdParamsSchema with id: z.uuid()), POST with @Status(201), GET, GET :id, PATCH :id, DELETE :id with @Status(204), NotFoundException for a missing id, a service on a Map with crypto.randomUUID() ids to replace with your database, and a TestApp test covering 201, 404, 422 and 204. A malformed id answers 422. check and test pass right after generation, without a database. Each schema has its own file in schemas/ with its z.infer type next to it (create-<name>.schema.ts exports Create<Name>Schema and Create<Name>Input), the entity interface is in <name>.types.ts, and there are no barrel files: the files import each other directly.
Table. miia g table user-profile reads the dialect and the schema file from drizzle.config.ts and writes src/user-profile/user-profile.table.ts for that dialect: export const userProfile with the SQL name user_profile, a UUID id, name, createdAt and updatedAt, plus the UserProfile and NewUserProfile types. It adds export * from './user-profile/user-profile.table.js' to the schema file (src/db.schema.ts in a generated project) and prints db:generate and db:migrate as the next steps, for the scripts the project has. Nothing is written without a drizzle.config.ts, or with a dialect other than postgresql, mysql and sqlite. When schema in the config is an array, a glob or a path outside the project, or the file does not exist, the table is still written and a warning says to add it to the schema yourself. The table is a top-level const, so a reserved word (class) and a name the table file imports (text, uuid, integer) are refused before anything is written. Two tables with one name in different folders (g table posts, g table admin/posts) export the same names, and miia check reports that in the schema file.
Names. Letters, digits, - and _, starting with a letter; / separates folders. Classes are PascalCase and files kebab-case, acronyms included: HTTPServer becomes HttpServerService in http-server.service.ts. A table's constant is camelCase and its SQL name snake_case (user-profile gives userProfile and user_profile). A dot or any other character is an error.
Placement. By default src/<name>/<name>.<kind>.ts. --flat drops the folder, a name with a path (admin/users) uses that folder as is, and --path core puts everything under src/core/. A table follows these rules like a service: src/posts/posts.table.ts, with --flat src/posts.table.ts, admin/posts gives src/admin/posts.table.ts, --path core gives src/core/posts/posts.table.ts. A resource always gets its own folder. A guard or middleware never gets one: without a folder in the name and without --path it goes to src/common/guards/ or src/common/middleware/, otherwise straight into that folder (g guard admin --path users writes src/users/admin.guard.ts), and --flat changes nothing. An existing file stops the command before anything is written.
Parent module. The CLI walks up from the target folder toward src/ and takes the nearest *.module.ts (the one named after the folder when there are several), falling back to src/app/app.module.ts. Registration adds the import and the array entry and keeps the rest of the file as it was. Without a parent module, or with a shape it cannot edit, the files are still created and you get a warning to register the class yourself.
Formatting. New and changed files go through the project's formatter: biome.json / biome.jsonc -> node_modules/.bin/biome, .prettierrc* / prettier.config.js -> node_modules/.bin/prettier. Only the project's own binaries are used; a formatter that fails prints one warning.
| Flag | Default | Description |
|---|---|---|
--path | - | Folder under src/ |
--flat | false | No folder for the artifact (a guard or middleware never gets one) |
--export | false | service only: also add it to exports |
--dry-run | false | Print the changes without writing |
Without a schematic or a name the command asks for them in a terminal and prints the usage otherwise.
miia dev, build, start, check
miia dev
Runs the runtime's own watcher and tsc --noEmit --watch side by side:
| Runtime | Server |
|---|---|
| Bun | bun --watch src/main.ts |
| Deno | deno run --allow-all --sloppy-imports --watch src/main.ts |
| Node.js | node --import tsx --watch src/main.ts |
When the app crashes, the watcher waits for the next file change; when tsc stops, the CLI prints a warning and the server keeps running. NODE_ENV is development unless you set it. On Linux and macOS the watcher runs in its own process group, so stopping dev also stops the app that node --watch runs as a separate process.
miia build
| Runtime | Runs |
|---|---|
| Bun / Deno | tsc --noEmit (the runtime executes TypeScript directly) |
| Node.js | tsc -p tsconfig.build.json when the file exists (generated projects have it; tests are left out of dist/), else tsc. A config with "noEmit": true is refused: it would build nothing for miia start |
miia start
| Runtime | Runs |
|---|---|
| Bun | bun src/main.ts |
| Deno | deno run --allow-all --sloppy-imports src/main.ts |
| Node.js | node --enable-source-maps dist/main.js |
NODE_ENV is production unless you set it. start does not need tsc, so a production image can leave TypeScript out.
miia check
tsc --noEmit. No flags.
Flags
| Flag | Commands | Default | Description |
|---|---|---|---|
--runtime, -r | dev, build, start | detected | bun, deno, node |
--entry | dev, start | src/main.ts | Entry file |
--dist | start | dist/main.js | Compiled entry (Node.js) |
--env-file | dev, start | .env when it exists | Passed to the runtime as --env-file |
tsc is the project's own (node_modules/.bin, walking up), else the one in PATH.
Exit codes and signals
startanddevexit with the code the app exited with, so 0 after a clean shutdown on Ctrl+C orSIGTERM. When a signal ended the app, the code is128 + signal: 143 for an app with noSIGTERMhandler, 137 afterSIGKILL.- The first
SIGINT,SIGTERMorSIGHUPis forwarded to the app asSIGTERM, and the CLI waits for the app's graceful shutdown however long it takes. A repeat within a second is ignored: Ctrl+C underbun runornpm rundelivers two. A signal after that kills the app (SIGKILL).devalso kills anything still running 10 seconds after the first signal. - A command that fails (a missing runtime,
tscnot installed, an invalid flag) prints one line and exits with 1.
Runtime detection
dev, build, start and miia add pick the runtime in this order:
--runtime.- Walking up from the current folder, on each level:
deno.json/deno.jsonc-> Deno; then a lockfile:bun.lock/bun.lockb-> Bun,deno.lock-> Deno,package-lock.json/yarn.lock/pnpm-lock.yaml-> Node.js. The first level with a match wins, so a Deno project installed with pnpm still runs on Deno, and a package in a monorepo finds the lockfile at the root. bun, thendenoinPATH.- Node.js.
Versions
@miiajs/* packages in a generated project get ^ of the CLI version: the CLI and every @miiajs/* package release together at one version. Third-party versions live in the CLI's templates, and a test checks them against the peer ranges of the @miiajs/* packages and that every required peer (jose, swagger-ui-dist, drizzle-orm, ...) is there.
Prerequisites
| Tool | Needed for |
|---|---|
typescript 6 | A peer dependency of the CLI: new, add and g edit files through its compiler API; dev, build and check run tsc. Generated projects have it |
tsx | miia dev on Node.js. Generated Node.js projects have it |
bun / deno / node | The runtime you run on. Deno 2.4 or newer |
Windows is handled in code (executables found through PATHEXT, including .cmd shims; CRLF files keep their line endings), but the end-to-end run that generates and starts projects runs on macOS and Linux only.