# Commands

> A release step or a worker is the same app started differently — ./app migrate.

A command is your app's code started without the server: a migration before a
deploy, a queue worker, a nightly cleanup. Put a file in `src/commands`:

```ts title="src/commands/migrate.ts"
import { db } from '@repo/database'

export const description = 'Apply the database migrations'
export const register = true

export default async function (args: string[]) {
  const applied = await db.migrate({ dryRun: args.includes('--dry-run') })

  console.log(`${applied} migrations applied`)
}
```

```sh
./app migrate --dry-run                              # the compiled binary
node .output/server/commands.mjs migrate --dry-run   # a plain build, node or bun
```

`./app` with no arguments starts the server. Anything else runs a command, and
the server is not started, so a release step beside the running version doesn't
try to bind its port.

Commands are built into the same bundle as the pages. `@repo/database` and the
logger are the same packages the pages use, and a binary carries the commands
inside it.

A Laravel app's commands are artisan's. See [Laravel commands](/hosts/laravel/commands).

## Writing a command

A command is a file directly in `src/commands` with a default export. Wrap it in
`defineCommand` to get the types without writing them:

```ts title="src/commands/seed.ts"
import { parseArgs } from 'node:util'
import { defineCommand } from '@rsc-kit/core/commands'
import { db } from '@repo/database'

export const description = 'Fill the database with sample data'
export const register = true

export default defineCommand(async (args) => {
  const { values } = parseArgs({ args, options: { count: { type: 'string', default: '10' } } })

  await db.seed({ count: Number(values.count) })
})
```

```sh
./app seed --count 50
```

The full signature, if you prefer to annotate it yourself:

```ts
import type { CommandContext } from '@rsc-kit/core/commands'

export default async function (args: string[], context: CommandContext): Promise<number | void>
```

- **`args`** is everything after the name, untouched. `./app migrate --help`
  gives `migrate` the `--help`. Parsing is yours.
- **`context`** is `{ signal, deadline }`, for knowing when to stop. See
  [a worker](#a-worker).
- **`description`**, an optional exported string, is what `./app --help` shows
  beside the name. It must be a plain string literal: the build reads it from
  the source, so listing never loads a command.

The name is the file name without its extension. These are not commands:

- declaration files and tests (`*.test.ts`, `*.spec.ts`);
- anything starting with `_` or `.`, so `_shared.ts` is how two commands share
  a helper;
- a file in a folder. `src/commands/db/seed.ts` is not `db:seed`, and the build
  says so rather than leaving it out silently.

## Exit codes

The return value is the exit code:

```ts title="src/commands/check-links.ts"
export default async function () {
  const broken = await findBrokenLinks()

  for (const link of broken) console.error(link)

  return broken.length > 0 ? 1 : 0
}
```

- Returning nothing exits `0`. A number from `0` to `255` exits with itself.
- A command that throws exits `1`, printing the error and every `cause` under
  it, each on a `[cause]:` line. A library that wraps an error, as Drizzle does
  a failed query, keeps the reason there.
- Returning anything else (a string, `256`) exits `1` and says what was
  returned, rather than reporting success for a mistake.
- An unknown name exits `2`, as any misused tool does.

```
$ ./app --help
Usage: ./app <command> [args]

Commands:
  migrate  Apply the database migrations
  work

$ ./app migrat
Not a command: migrat
…
$ echo $?
2
```

A deploy that runs `./app migrate` and stops on a non-zero exit is right in
both failure cases.

## Running one

Anywhere that can run the binary or the build. One image serves the server and
every command:

```dockerfile
FROM oven/bun:1
COPY dist/app /app
ENTRYPOINT ["/app"]
CMD []
```

```sh
docker run --rm myapp           # the server
docker run --rm myapp migrate   # a release step
docker run --rm myapp work      # a worker
```

The same shape is a Kubernetes Job's `args: ["migrate"]`, a platform's release
command, or a process type. Nothing in `src/commands` names a platform.

From a plain build, run the commands entry:

```sh
node .output/server/commands.mjs migrate
bun  .output/server/commands.mjs migrate
```

<Aside type="caution" title="Not .output/server/index.mjs">
  `index.mjs` is the server, and it does not read its arguments:
  `node .output/server/index.mjs migrate` starts the server and migrates
  nothing. `commands.mjs` is the entry for a command. The binary has both
  behind one file because it knows from `argv` which was meant.
</Aside>

The build lists the commands in `.output/rsc-kit.json` as `commands`, for a
deploy that wants to check before running one.

## Using the server's setup

`src/instrumentation.ts` [validates the environment at import and connects in
`register()`](/guides/instrumentation/). A command doesn't load it unless it
asks:

```ts
export const register = true
```

- **By default it is not imported.** The command runs from a bundle of its own,
  without instrumentation.ts, so a queue drain doesn't fail on the web's Stripe key.
  What the command imports still runs: one that imports `@repo/env/worker`
  validates the worker's schema, and only that one.
- **With `export const register = true`**, the command runs from the server's bundle. instrumentation.ts is
  imported, so its environment is validated, and `register()` runs before the
  command. It has to be the literal `true`: the build reads it from the source
  to choose the bundle, and refuses a computed one that is true.

A command that opted in gets `register()` first and `shutdown()` after it
returns, or after it throws, so the pool `register()` opened is closed. Both are
bounded by `RSC_SHUTDOWN_TIMEOUT` (10 seconds). A `shutdown()` that fails is
reported without changing the command's exit code.

## A worker

A command that runs until it is told to stop is a worker. `signal` tells it:

```ts title="src/commands/work.ts"
import { defineCommand } from '@rsc-kit/core/commands'
import { queue } from '@repo/queue'

export const register = true

export default defineCommand(async (_args, { signal }) => {
  while (!signal.aborted) await queue.processNext({ signal })
})
```

The first `SIGTERM` or `SIGINT` aborts `signal` and gives the command
`RSC_SHUTDOWN_TIMEOUT` seconds to return. If it does, the process runs
`shutdown()` and exits with the command's code, `0` for a clean stop. A command
that doesn't stop in time exits `1` and says so. A second signal doesn't wait.

### Catching a stop that came early

A stop can arrive before the command starts, while the app loads or while
`register()` runs. Then `signal` is already aborted, and the `abort` event fired
before the command could listen. So a command that waits needs both: it checks
`signal.aborted` as it starts, and listens for `abort` after that, or passes
`signal` to something that does.

The worker above does both: the loop tests `signal.aborted`, and
`queue.processNext({ signal })` returns when the signal aborts. A command that
only waits does it by hand:

```ts
export default defineCommand(async (_args, { signal }) => {
  if (signal.aborted) return
  await new Promise<void>((resolve) => signal.addEventListener('abort', () => resolve(), { once: true }))
})
```

Checking alone misses a stop during a long `await`. Listening alone waits for
ever on a stop that came first. The runner gives the event loop one turn before
it calls the command, so a waiting stop is delivered first, on Node, on Bun and
in a binary.

### Finishing the current job

`deadline` is when the runner stops waiting, as a `Date.now()` time. It is
`undefined` until the command has been told to stop:

```ts
export default defineCommand(async (_args, context) => {
  while (!context.signal.aborted) {
    const job = await queue.next()
    const budget = context.deadline ? context.deadline - Date.now() : Infinity

    await job.run({ timeout: budget })
  }
})
```

<Aside type="caution" title="Do not destructure deadline">
  `deadline` is a getter, because what it answers changes. Destructuring it,
  as in `({ signal, deadline }) => …`, reads it once, as the command starts,
  when it is always `undefined`, and keeps that. Read `context.deadline` at the
  moment you need it. `signal` is a plain property and can be destructured.
</Aside>

The process stays alive for as long as the command runs, whether or not it holds
a socket, on Node as on Bun.

## Running on a schedule

A scheduler is a worker that runs whatever is due every minute, the way
Laravel's `schedule:work` does:

```ts title="src/commands/schedule.ts"
import { setTimeout as sleep } from 'node:timers/promises'
import { defineCommand } from '@rsc-kit/core/commands'

export const register = true

export default defineCommand(async (_args, { signal }) => {
  while (!signal.aborted) {
    await runDueJobs()

    // Wakes at once when told to stop, instead of finishing the minute.
    await sleep(60_000, undefined, { signal }).catch(() => {})
  }
})
```

```sh
./app schedule
```

Run **one** of it. Two would run every job twice, which is also why the web
server is not the place for a schedule: it runs as many copies as you scale it
to.

A job that runs once a day doesn't need a process waiting for it. Let the
platform's cron run an ordinary command, such as `./app cleanup`, and let it
exit.

## While developing

`vite dev` has no build to run a command from. Run the file instead:

```sh
bun src/commands/migrate.ts
```

Bun runs TypeScript and follows the app's `tsconfig` paths.

## Where commands aren't built

Commands are built for the `bun` and `node` presets, whose output is a process.

- **A Worker.** The bundle targets workerd, where a database driver or
  `node:child_process` is a different build of the package or not there at all.
  The build leaves `src/commands` out and says so. Run the file in CI before the
  deploy, or use `wrangler` for D1.
- **Any other preset** (Vercel, Netlify, Deno): the build says so and leaves
  `src/commands` out. Run the file from CI.

## Common mistakes

**`process.exit()` inside a command skips `shutdown()`.** Return the code
instead. The runner exits for you, after closing what `register()` opened.

**A package with an import side effect runs it for the server too, if a page
imports it.** The command's own module runs only when it is named. What it
imports is the bundle's, shared with the pages.

**A command is not a route.** It isn't prerendered and has no request, so
`headers()` and `cookies()` have nothing to read.

## How it works

### Listing needs no environment

`./app --help` and a name that isn't a command are answered before the app
loads, from a list the build wrote into the entry. A build machine or a CI step
with no database URL can list the commands. A real command loads the app,
validates the environment, and fails there with the schema's own message.

### Where a stop is held from

The entry holds `SIGTERM` and `SIGINT` from its first line, however long the app
takes to load, and hands them to the command. Before that line, a stop is the
operating system's and ends the process with `143`.

In a plain build that window is tiny: `commands.mjs` is a few lines and loads
the app after it holds the signals. A compiled binary has one more step. Bun
parses every module in the file before running the first line of any, so a stop
while a large app is parsed (about 170 ms for a production app of 580 modules
and 119 MB) ends the process.

`--splitting` makes the entry its own chunk, which runs first and loads the rest
after. The scaffold's `compile` script has it:

```sh
bun build --compile --splitting .output/server/compile.mjs --outfile dist/app
```

- An app made before the flag was added keeps its old script until you add it.
- An app with no `src/commands` has nothing to split, so the flag changes
  nothing there.
- `dist/app` is still the only file the binary needs.
- A Bun that doesn't accept the pair fails the compile loudly. 1.2 says
  `cannot use --compile with --splitting`.

The same stop, 250 ms into starting an 80 MB binary, exits `143` without the
flag and `0` with it, and `./app --help` answers without loading the app.
Nothing else about the binary changes.

<Aside type="note" title="--sourcemap writes files beside the binary">
  With `--compile`, `--sourcemap` embeds the map in the binary, and Bun also
  writes `.map` files next to the output: one for a plain compile, and one per
  chunk with `--splitting` (46 for the example, about 224 for a large app, and a
  `dist` that grew to 201 MB). The binary does not read them. A stack trace is
  the same with them deleted, so ship the binary alone and remove them
  (`rm -f dist/*.map`), or leave `--sourcemap` off, which is what the scaffold
  does. `--sourcemap=inline` does not prevent them under `--compile`. What
  a trace shows either way is in [reading a stack trace](/hosts/where-it-runs/#reading-a-stack-trace).
</Aside>
