@cslug/cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/docs/README.md +17 -0
- package/docs/api.md +44 -0
- package/package.json +39 -4
- package/src/bin.ts +27 -0
- package/src/commands/builtin.ts +177 -0
- package/src/config.ts +12 -0
- package/src/index.ts +13 -0
- package/src/io.ts +50 -0
- package/src/kernel.ts +166 -0
- package/src/supervisor.ts +252 -0
- package/stubs/command.stub +14 -0
- package/stubs/event.stub +5 -0
- package/stubs/listener.stub +7 -0
- package/stubs/provider.stub +9 -0
- package/stubs/service.stub +4 -0
- package/stubs/test.stub +10 -0
package/README.md
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cslug/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The `cslug` command. It runs built-in commands, the commands your installed packages contribute (`migrate`
|
|
4
|
+
with @cslug/database, `serve` with @cslug/http, …) and your own in `app/commands/`.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
cslug list
|
|
8
|
+
cslug make:controller admin/Claim --resource
|
|
9
|
+
cslug migrate --force && cslug start
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
|
|
13
|
+
[guide 20](../../guides/20-cli.md).
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# @cslug/cli
|
|
2
|
+
|
|
3
|
+
`bin: cslug`. Finds the app (the nearest folder with `bootstrap/app.ts`), calls `createApp()`, registers the
|
|
4
|
+
providers (no connections yet) and runs the command. Commands with `static boot = false` (generators,
|
|
5
|
+
`key:generate`, `start`, `dev`) never boot the providers, so they work without a database.
|
|
6
|
+
|
|
7
|
+
Where commands come from:
|
|
8
|
+
|
|
9
|
+
| Source | How |
|
|
10
|
+
|---|---|
|
|
11
|
+
| built-in | `list`, `about`, `config:show`, `key:generate`, `start`, `dev`, `make:command/provider/event/listener/service/test` |
|
|
12
|
+
| packages | their provider calls `this.commands([...])` in `register()`. @cslug/http: `serve`, `routes`, `make:controller/validator/middleware`. @cslug/database: `migrate`, `migrate:status/rollback/fresh`, `db:seed`, `make:migration/table/repository/factory/seeder` |
|
|
13
|
+
| your app | classes exported from `app/commands/**/*-command.ts`, imported only when needed. A file that fails to import is skipped with a warning |
|
|
14
|
+
|
|
15
|
+
`cslug start` runs each role as a child process (`serve`, `queue:work`, `schedule:work`), restarts crashed
|
|
16
|
+
ones with backoff, forwards SIGTERM and exits 0 once they have all drained. `cslug dev` runs the same processes
|
|
17
|
+
under `bun --watch`. Roles whose command is not installed are skipped with a warning.
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# @cslug/cli: API
|
|
2
|
+
|
|
3
|
+
## Writing a command
|
|
4
|
+
|
|
5
|
+
`Command`, `arg` and `flag` come from @cslug/core (so packages can contribute commands) and are re-exported
|
|
6
|
+
here.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
@inject(DocumentRepository)
|
|
10
|
+
export class ExpireDocumentsCommand extends Command {
|
|
11
|
+
static signature = 'operators:expire-documents'
|
|
12
|
+
static description = 'Mark expired operator documents'
|
|
13
|
+
static args = { before: arg.date().optional(), dryRun: flag.boolean().alias('n') }
|
|
14
|
+
constructor(private documents: DocumentRepository) { super() }
|
|
15
|
+
async handle({ before, dryRun }: Command.Args<typeof ExpireDocumentsCommand>) { … }
|
|
16
|
+
}
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
| Static | |
|
|
20
|
+
|---|---|
|
|
21
|
+
| `signature` | `group:name` |
|
|
22
|
+
| `description` | shown by `list` and `--help` |
|
|
23
|
+
| `args` | `arg.string/number/date()` (positional, in order), `flag.boolean/string/number/date/list()`; modifiers `.optional()`, `.default(v)`, `.describe()`, `.alias('x')`, `.choices(...)`. camelCase keys are written in kebab-case (`--dry-run`); `--no-x` negates a boolean |
|
|
24
|
+
| `boot` | `false`: don't boot providers (no connections) |
|
|
25
|
+
| `longRunning` | the process stays up until a signal (`serve`, `queue:work`) |
|
|
26
|
+
|
|
27
|
+
`handle(args)` may return an exit code. Usage errors exit 2 with the help text; other errors exit 1.
|
|
28
|
+
|
|
29
|
+
Helpers: `line`, `info`, `success`, `warn`, `error`, `table(rows)`, `confirm(q, fallback)`, `ask`, `choose`,
|
|
30
|
+
`progress(n)`, `generate(stubDir, stub, target, vars, force)` (for generators: the app's `stubs/<stub>` wins),
|
|
31
|
+
plus `app`, `clock`, `log`, `io`. When the session is not interactive, prompts return the fallback.
|
|
32
|
+
|
|
33
|
+
`names('admin/Claim', 'controller')` gives the generator names (`ClaimController`, `admin/claim-controller`, …).
|
|
34
|
+
|
|
35
|
+
## Exports
|
|
36
|
+
|
|
37
|
+
| | |
|
|
38
|
+
|---|---|
|
|
39
|
+
| `CliKernel(app)` | `.run(argv)` → exit code; `.commands()` |
|
|
40
|
+
| `Supervisor(specs, options)` | `.start()`, `.stop(signal)` → exit code; `plannedProcesses(config, flags)` |
|
|
41
|
+
| `generator(kind, dir, description)` | a `make:<kind>` command from `stubs/<kind>.stub` |
|
|
42
|
+
| `BufferedIO(answers?)` | capture output in tests: `app.instance(ConsoleIO, io)` |
|
|
43
|
+
| `defineCslugConfig()` | `cslug.config.ts`: `processes` (`web.instances`, `worker[]`, `scheduler`), `shutdownTimeout`, `assets` |
|
|
44
|
+
| `commandHelp(cmd)` | |
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The cslug command: generators, dev server, start supervisor, REPL.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/cslugts/cslug.git",
|
|
10
|
+
"directory": "packages/cli"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/cslugts/cslug/tree/main/packages/cli",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"cslug",
|
|
15
|
+
"bun",
|
|
16
|
+
"framework"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./src/index.ts"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"src",
|
|
23
|
+
"docs",
|
|
24
|
+
"stubs",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"bun": ">=1.3.14"
|
|
29
|
+
},
|
|
30
|
+
"bin": {
|
|
31
|
+
"cslug": "src/bin.ts"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@cslug/core": "0.1.0"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@cslug/database": "workspace:*",
|
|
38
|
+
"@cslug/http": "workspace:*",
|
|
39
|
+
"@cslug/validation": "workspace:*"
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/bin.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { existsSync } from 'node:fs'
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
|
+
import { Application } from '@cslug/core'
|
|
5
|
+
import { CliKernel } from './kernel'
|
|
6
|
+
|
|
7
|
+
/** The app root: the nearest folder (from the cwd up) with bootstrap/app.ts. */
|
|
8
|
+
function findRoot(from: string): string | undefined {
|
|
9
|
+
for (let dir = from; ; dir = dirname(dir)) {
|
|
10
|
+
if (existsSync(join(dir, 'bootstrap/app.ts'))) return dir
|
|
11
|
+
if (dirname(dir) === dir) return undefined
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const root = findRoot(process.cwd())
|
|
16
|
+
let app: Application
|
|
17
|
+
try {
|
|
18
|
+
app = root ? (await import(join(root, 'bootstrap/app.ts'))).createApp() : new Application({ root: process.cwd() })
|
|
19
|
+
} catch (error) {
|
|
20
|
+
// usually env validation (EnvError lists every problem)
|
|
21
|
+
console.error(error instanceof Error ? error.message : error)
|
|
22
|
+
process.exit(1)
|
|
23
|
+
}
|
|
24
|
+
const kernel = new CliKernel(app)
|
|
25
|
+
const code = await kernel.run(process.argv.slice(2))
|
|
26
|
+
// long-running commands (serve, start, queue:work) keep the process alive until a signal
|
|
27
|
+
if (!kernel.keepAlive) process.exit(code)
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { arg, Command, type CommandClass, flag, names } from '@cslug/core'
|
|
4
|
+
import { DevCommand, StartCommand } from '../supervisor'
|
|
5
|
+
|
|
6
|
+
export const STUBS = join(import.meta.dir, '../../stubs')
|
|
7
|
+
|
|
8
|
+
/** `cslug list`: commands grouped by prefix. */
|
|
9
|
+
export class ListCommand extends Command {
|
|
10
|
+
static signature = 'list'
|
|
11
|
+
static description = 'List the commands'
|
|
12
|
+
static boot = false
|
|
13
|
+
static args = { json: flag.boolean().describe('Machine-readable output') }
|
|
14
|
+
|
|
15
|
+
async handle({ json }: Command.Args<typeof ListCommand>) {
|
|
16
|
+
const { CliKernel } = await import('../kernel')
|
|
17
|
+
const group = (c: CommandClass) => (c.signature.includes(':') ? (c.signature.split(':')[0] as string) : '')
|
|
18
|
+
// ungrouped commands first, then by group and name
|
|
19
|
+
const commands = [...(await this.app.resolve(CliKernel).commands()).values()].sort(
|
|
20
|
+
(a, b) => (group(a) ? 1 : 0) - (group(b) ? 1 : 0) || a.signature.localeCompare(b.signature),
|
|
21
|
+
)
|
|
22
|
+
if (json)
|
|
23
|
+
return this.line(JSON.stringify(commands.map((c) => ({ name: c.signature, description: c.description ?? '' }))))
|
|
24
|
+
this.line('Usage: cslug <command> [arguments] [options] (cslug <command> --help)')
|
|
25
|
+
let current = ''
|
|
26
|
+
this.line()
|
|
27
|
+
for (const c of commands) {
|
|
28
|
+
const g = group(c)
|
|
29
|
+
if (g !== current) {
|
|
30
|
+
current = g
|
|
31
|
+
this.line()
|
|
32
|
+
this.info(g)
|
|
33
|
+
}
|
|
34
|
+
this.line(` ${c.signature.padEnd(24)}${c.description ?? ''}`)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** `cslug about`: versions and environment. */
|
|
40
|
+
export class AboutCommand extends Command {
|
|
41
|
+
static signature = 'about'
|
|
42
|
+
static description = 'Versions of Bun and the @cslug packages; environment'
|
|
43
|
+
static boot = false
|
|
44
|
+
static args = { json: flag.boolean() }
|
|
45
|
+
|
|
46
|
+
handle({ json }: Command.Args<typeof AboutCommand>) {
|
|
47
|
+
const pkg = (p: string) => {
|
|
48
|
+
try {
|
|
49
|
+
return JSON.parse(readFileSync(join(this.app.rootDir, 'node_modules', p, 'package.json'), 'utf8'))
|
|
50
|
+
.version as string
|
|
51
|
+
} catch {
|
|
52
|
+
return undefined
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const scoped = [
|
|
56
|
+
'core',
|
|
57
|
+
'validation',
|
|
58
|
+
'http',
|
|
59
|
+
'vue',
|
|
60
|
+
'database',
|
|
61
|
+
'redis',
|
|
62
|
+
'queue',
|
|
63
|
+
'auth',
|
|
64
|
+
'mail',
|
|
65
|
+
'notification',
|
|
66
|
+
'storage',
|
|
67
|
+
'webhook',
|
|
68
|
+
'ai',
|
|
69
|
+
'cli',
|
|
70
|
+
'testing',
|
|
71
|
+
]
|
|
72
|
+
const versions = Object.fromEntries(scoped.map((p) => [`@cslug/${p}`, pkg(`@cslug/${p}`)]).filter(([, v]) => v))
|
|
73
|
+
const info = {
|
|
74
|
+
bun: Bun.version,
|
|
75
|
+
env: this.app.config('app.env') ?? 'development',
|
|
76
|
+
root: this.app.rootDir,
|
|
77
|
+
packages: versions,
|
|
78
|
+
}
|
|
79
|
+
if (json) return this.line(JSON.stringify(info))
|
|
80
|
+
this.table([{ bun: info.bun, env: String(info.env), root: info.root }])
|
|
81
|
+
this.line()
|
|
82
|
+
this.table(Object.entries(versions).map(([name, version]) => ({ package: name, version })))
|
|
83
|
+
if (new Set(Object.values(versions)).size > 1)
|
|
84
|
+
this.warn('The @cslug packages have different versions: install the same version of all of them.')
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const SECRET = /key|secret|password|token|credential|dsn/i
|
|
89
|
+
const redact = (value: unknown, key = ''): unknown => {
|
|
90
|
+
if (typeof value === 'string' && SECRET.test(key)) return value ? '••••••' : ''
|
|
91
|
+
if (typeof value === 'string' && /^[a-z]+:\/\/[^/]*:[^@/]+@/.test(value))
|
|
92
|
+
return value.replace(/:\/\/([^:/]*):[^@/]+@/, '://$1:••••••@')
|
|
93
|
+
if (typeof value === 'bigint') return `${value}n`
|
|
94
|
+
if (Array.isArray(value)) return value.map((v) => redact(v))
|
|
95
|
+
if (value && typeof value === 'object' && !(value instanceof Date))
|
|
96
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, redact(v, k)]))
|
|
97
|
+
return value
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** `cslug config:show [section]`, secrets hidden. */
|
|
101
|
+
export class ConfigShowCommand extends Command {
|
|
102
|
+
static signature = 'config:show'
|
|
103
|
+
static description = 'Show the resolved configuration (secrets hidden)'
|
|
104
|
+
static boot = false
|
|
105
|
+
static args = { section: arg.string().optional().describe('A section or dotted path, e.g. database or app.url') }
|
|
106
|
+
|
|
107
|
+
handle({ section }: Command.Args<typeof ConfigShowCommand>) {
|
|
108
|
+
const value = section ? this.app.config(section) : this.app.configs
|
|
109
|
+
if (value === undefined) {
|
|
110
|
+
this.error(`No config at "${section}"`)
|
|
111
|
+
return 1
|
|
112
|
+
}
|
|
113
|
+
this.line(JSON.stringify(redact(value, section?.split('.').at(-1)), null, 2))
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** `cslug key:generate`: a random APP_KEY, printed or written to `.env`. */
|
|
118
|
+
export class KeyGenerateCommand extends Command {
|
|
119
|
+
static signature = 'key:generate'
|
|
120
|
+
static description = 'Generate APP_KEY (printed, or written to .env with --write)'
|
|
121
|
+
static boot = false
|
|
122
|
+
static args = { write: flag.boolean().describe('Write it to .env (replacing an existing APP_KEY)') }
|
|
123
|
+
|
|
124
|
+
handle({ write }: Command.Args<typeof KeyGenerateCommand>) {
|
|
125
|
+
const key = `base64:${Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64')}`
|
|
126
|
+
if (!write) return this.line(key)
|
|
127
|
+
const path = join(this.app.rootDir, '.env')
|
|
128
|
+
const text = existsSync(path) ? readFileSync(path, 'utf8') : ''
|
|
129
|
+
writeFileSync(
|
|
130
|
+
path,
|
|
131
|
+
/^APP_KEY=.*$/m.test(text)
|
|
132
|
+
? text.replace(/^APP_KEY=.*$/m, `APP_KEY=${key}`)
|
|
133
|
+
: `${text}${text && !text.endsWith('\n') ? '\n' : ''}APP_KEY=${key}\n`,
|
|
134
|
+
)
|
|
135
|
+
this.success('APP_KEY written to .env')
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const makeArgs = {
|
|
140
|
+
name: arg.string().describe('Name, optionally in a folder: admin/Claim'),
|
|
141
|
+
force: flag.boolean().describe('Overwrite'),
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** A generator: `make:<kind> Name` → `<dir>/<name>-<suffix>.ts` from `stubs/<kind>.stub`. */
|
|
145
|
+
export function generator(
|
|
146
|
+
kind: string,
|
|
147
|
+
dir: string,
|
|
148
|
+
description: string,
|
|
149
|
+
suffix = kind,
|
|
150
|
+
stubDir = STUBS,
|
|
151
|
+
): CommandClass {
|
|
152
|
+
return class extends Command {
|
|
153
|
+
static signature = `make:${kind}`
|
|
154
|
+
static description = description
|
|
155
|
+
static boot = false
|
|
156
|
+
static args = makeArgs
|
|
157
|
+
handle({ name, force }: Command.Args<{ args: typeof makeArgs }>) {
|
|
158
|
+
const n = names(name, suffix)
|
|
159
|
+
return this.generate(stubDir, `${kind}.stub`, `${dir}/${n.file}.ts`, { ...n, class: n.class }, force) ? 0 : 1
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export const builtinCommands: CommandClass[] = [
|
|
165
|
+
ListCommand,
|
|
166
|
+
AboutCommand,
|
|
167
|
+
ConfigShowCommand,
|
|
168
|
+
KeyGenerateCommand,
|
|
169
|
+
StartCommand,
|
|
170
|
+
DevCommand,
|
|
171
|
+
generator('command', 'app/commands', 'Create a command class'),
|
|
172
|
+
generator('provider', 'app/providers', 'Create a service provider'),
|
|
173
|
+
generator('event', 'app/events', 'Create an event'),
|
|
174
|
+
generator('listener', 'app/listeners', 'Create an event listener'),
|
|
175
|
+
generator('service', 'app/services', 'Create a service class'),
|
|
176
|
+
generator('test', 'tests', 'Create a test file', 'test'),
|
|
177
|
+
]
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** `cslug.config.ts`: framework-level settings (assets, processes for `cslug start`). */
|
|
2
|
+
export type CslugConfig = {
|
|
3
|
+
assets?: { entries?: Record<string, string>; scss?: boolean; tailwind?: boolean }
|
|
4
|
+
processes?: {
|
|
5
|
+
web?: { instances?: number } | false
|
|
6
|
+
worker?: { queues?: string[]; concurrency?: number }[] | false
|
|
7
|
+
scheduler?: boolean
|
|
8
|
+
}
|
|
9
|
+
/** Seconds a child gets to finish after SIGTERM before it is killed (default 30). */
|
|
10
|
+
shutdownTimeout?: number
|
|
11
|
+
}
|
|
12
|
+
export const defineCslugConfig = (config: CslugConfig): CslugConfig => config
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/cli: the `cslug` binary. Runs built-in commands, those your installed packages contribute
|
|
3
|
+
* (`migrate` with @cslug/database, `serve` with @cslug/http …) and yours in `app/commands/`; generators;
|
|
4
|
+
* `start` (a supervisor for web, workers and scheduler) and `dev`.
|
|
5
|
+
*
|
|
6
|
+
* `Command`, `arg` and `flag` live in @cslug/core (so packages can contribute commands) and are re-exported here.
|
|
7
|
+
*/
|
|
8
|
+
export { arg, Command, type CommandClass, ConsoleIO, flag, names } from '@cslug/core'
|
|
9
|
+
export { generator, STUBS } from './commands/builtin'
|
|
10
|
+
export { type CslugConfig, defineCslugConfig } from './config'
|
|
11
|
+
export { BufferedIO, commandHelp } from './io'
|
|
12
|
+
export { CliKernel } from './kernel'
|
|
13
|
+
export { type ProcessSpec, plannedProcesses, Supervisor } from './supervisor'
|
package/src/io.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type ArgSpec, type CommandClass, ConsoleIO, kebab } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
/** Help text for one command. */
|
|
4
|
+
export function commandHelp(cmd: CommandClass): string {
|
|
5
|
+
const entries = Object.entries(cmd.args ?? {})
|
|
6
|
+
const usage = entries
|
|
7
|
+
.filter(([, s]) => s.positional)
|
|
8
|
+
.map(([k, s]) => (s.opts.optional ? `[${kebab(k)}]` : `<${kebab(k)}>`))
|
|
9
|
+
const lines = [
|
|
10
|
+
cmd.description ?? '',
|
|
11
|
+
'',
|
|
12
|
+
`Usage: cslug ${cmd.signature} ${usage.join(' ')}${entries.some(([, s]) => !s.positional) ? ' [options]' : ''}`,
|
|
13
|
+
]
|
|
14
|
+
const row = (left: string, s: ArgSpec) =>
|
|
15
|
+
` ${left.padEnd(26)}${s.opts.description ?? ''}${s.opts.choices ? ` (${s.opts.choices.join('|')})` : ''}${s.opts.fallback !== undefined && s.kind !== 'boolean' && s.kind !== 'list' ? ` [default: ${s.opts.fallback}]` : ''}`
|
|
16
|
+
const args = entries.filter(([, s]) => s.positional)
|
|
17
|
+
if (args.length) lines.push('', 'Arguments:', ...args.map(([k, s]) => row(kebab(k), s)))
|
|
18
|
+
const flags = entries.filter(([, s]) => !s.positional)
|
|
19
|
+
if (flags.length) {
|
|
20
|
+
lines.push(
|
|
21
|
+
'',
|
|
22
|
+
'Options:',
|
|
23
|
+
...flags.map(([k, s]) =>
|
|
24
|
+
row(`${s.opts.alias ? `-${s.opts.alias}, ` : ''}--${kebab(k)}${s.kind === 'boolean' ? '' : ' <value>'}`, s),
|
|
25
|
+
),
|
|
26
|
+
)
|
|
27
|
+
}
|
|
28
|
+
return lines.join('\n').trim()
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Captures output; answers questions from a list. */
|
|
32
|
+
export class BufferedIO extends ConsoleIO {
|
|
33
|
+
override readonly color = false
|
|
34
|
+
override readonly interactive: boolean
|
|
35
|
+
out = ''
|
|
36
|
+
constructor(private readonly answers: string[] = []) {
|
|
37
|
+
super()
|
|
38
|
+
this.interactive = answers.length > 0
|
|
39
|
+
}
|
|
40
|
+
override write(text: string): void {
|
|
41
|
+
this.out += text
|
|
42
|
+
}
|
|
43
|
+
override error(text: string): void {
|
|
44
|
+
this.out += text
|
|
45
|
+
}
|
|
46
|
+
override async ask(question: string): Promise<string> {
|
|
47
|
+
this.out += question
|
|
48
|
+
return this.answers.shift() ?? ''
|
|
49
|
+
}
|
|
50
|
+
}
|
package/src/kernel.ts
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { existsSync, readdirSync, statSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import {
|
|
4
|
+
type Application,
|
|
5
|
+
COMMANDS,
|
|
6
|
+
Command,
|
|
7
|
+
type CommandClass,
|
|
8
|
+
ConsoleIO,
|
|
9
|
+
CslugError,
|
|
10
|
+
parseArgs,
|
|
11
|
+
runInContext,
|
|
12
|
+
UsageError,
|
|
13
|
+
} from '@cslug/core'
|
|
14
|
+
import { builtinCommands } from './commands/builtin'
|
|
15
|
+
import { commandHelp } from './io'
|
|
16
|
+
|
|
17
|
+
const isCommandClass = (v: unknown): v is CommandClass =>
|
|
18
|
+
typeof v === 'function' && v.prototype instanceof Command && typeof (v as CommandClass).signature === 'string'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Runs `cslug <command> [args]`: built-in commands, those the providers contribute (`this.commands([...])`), and
|
|
22
|
+
* the app's own in `app/commands/`. Returns the exit code.
|
|
23
|
+
*/
|
|
24
|
+
export class CliKernel {
|
|
25
|
+
private found?: Map<string, CommandClass>
|
|
26
|
+
/** True after a long-running command started (`serve`, `start`): the process must stay alive. */
|
|
27
|
+
keepAlive = false
|
|
28
|
+
|
|
29
|
+
constructor(
|
|
30
|
+
readonly app: Application,
|
|
31
|
+
private readonly extra: readonly CommandClass[] = [],
|
|
32
|
+
) {
|
|
33
|
+
app.instance(CliKernel, this)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private get io(): ConsoleIO {
|
|
37
|
+
return this.app.resolve(ConsoleIO)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Built-in and package commands (no file imports). */
|
|
41
|
+
private known(): Map<string, CommandClass> {
|
|
42
|
+
this.app.registerProviders()
|
|
43
|
+
const map = new Map<string, CommandClass>()
|
|
44
|
+
for (const c of [...builtinCommands, ...(this.app.taggedTokens(COMMANDS) as CommandClass[]), ...this.extra])
|
|
45
|
+
map.set(c.signature, c)
|
|
46
|
+
return map
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Every command, by signature, including the app's (later wins: the app can replace a built-in). */
|
|
50
|
+
async commands(): Promise<Map<string, CommandClass>> {
|
|
51
|
+
if (this.found) return this.found
|
|
52
|
+
this.found = this.known()
|
|
53
|
+
for (const c of await this.discover()) this.found.set(c.signature, c)
|
|
54
|
+
return this.found
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Command classes exported from `app/commands/**` (files named `*-command.ts`). */
|
|
58
|
+
private async discover(): Promise<CommandClass[]> {
|
|
59
|
+
const dir = join(this.app.rootDir, 'app/commands')
|
|
60
|
+
if (!existsSync(dir)) return []
|
|
61
|
+
const files: string[] = []
|
|
62
|
+
const walk = (d: string) => {
|
|
63
|
+
for (const f of readdirSync(d)) {
|
|
64
|
+
const p = join(d, f)
|
|
65
|
+
if (statSync(p).isDirectory()) walk(p)
|
|
66
|
+
else if (/-command\.ts$/.test(f)) files.push(p)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
walk(dir)
|
|
70
|
+
const found: CommandClass[] = []
|
|
71
|
+
for (const f of files) {
|
|
72
|
+
try {
|
|
73
|
+
for (const v of Object.values(await import(f))) if (isCommandClass(v)) found.push(v)
|
|
74
|
+
} catch (error) {
|
|
75
|
+
// one broken command must not take down the others (or the generator you need to fix it)
|
|
76
|
+
this.io.error(
|
|
77
|
+
`! skipped ${f.slice(this.app.rootDir.length + 1)}: ${error instanceof Error ? error.message : String(error)}\n`,
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return found
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async run(argv: readonly string[]): Promise<number> {
|
|
85
|
+
try {
|
|
86
|
+
return await this.dispatch(argv)
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (error instanceof UsageError) {
|
|
89
|
+
this.io.error(`✗ ${error.message}\n`)
|
|
90
|
+
return 2
|
|
91
|
+
}
|
|
92
|
+
const message =
|
|
93
|
+
error instanceof CslugError
|
|
94
|
+
? error.message
|
|
95
|
+
: error instanceof Error
|
|
96
|
+
? (error.stack ?? error.message)
|
|
97
|
+
: String(error)
|
|
98
|
+
this.io.error(`✗ ${message}\n`)
|
|
99
|
+
return 1
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
private async dispatch(argv: readonly string[]): Promise<number> {
|
|
104
|
+
const [first, ...rest] = argv
|
|
105
|
+
// app commands are imported only when needed: built-ins and package commands work even if one is broken
|
|
106
|
+
const commands = first && this.known().has(first) && first !== 'list' ? this.known() : await this.commands()
|
|
107
|
+
if (first === undefined || first === '--help' || first === '-h') return this.dispatch(['list'])
|
|
108
|
+
if (first === '--version' || first === '-v') return this.dispatch(['about'])
|
|
109
|
+
const cmd = commands.get(first)
|
|
110
|
+
if (!cmd) {
|
|
111
|
+
const close = [...commands.keys()].filter(
|
|
112
|
+
(k) => k.startsWith(first.split(':')[0] ?? first) || distance(k, first) <= 2,
|
|
113
|
+
)
|
|
114
|
+
throw new UsageError(
|
|
115
|
+
`Unknown command "${first}".${close.length ? ` Did you mean: ${close.slice(0, 5).join(', ')}?` : ''} Run \`cslug list\`.`,
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
if (rest.includes('--help') || rest.includes('-h')) {
|
|
119
|
+
this.io.write(`${commandHelp(cmd)}\n`)
|
|
120
|
+
return 0
|
|
121
|
+
}
|
|
122
|
+
let args: Record<string, unknown>
|
|
123
|
+
try {
|
|
124
|
+
args = parseArgs(cmd.args ?? {}, rest)
|
|
125
|
+
} catch (e) {
|
|
126
|
+
if (e instanceof UsageError) this.io.error(`✗ ${e.message}\n\n${commandHelp(cmd)}\n`)
|
|
127
|
+
if (e instanceof UsageError) return 2
|
|
128
|
+
throw e
|
|
129
|
+
}
|
|
130
|
+
if (cmd.boot !== false) await this.app.start({ signals: !!cmd.longRunning })
|
|
131
|
+
const scope = this.app.createScope()
|
|
132
|
+
try {
|
|
133
|
+
const code = await runInContext({ app: this.app, scope, requestId: `cli:${cmd.signature}` }, async () => {
|
|
134
|
+
const instance = scope.build(cmd as never) as { handle?: (args: unknown) => unknown }
|
|
135
|
+
if (typeof instance.handle !== 'function')
|
|
136
|
+
throw new CslugError('cli.no_handle', `${cmd.name} has no handle(args) method`)
|
|
137
|
+
return instance.handle(args)
|
|
138
|
+
})
|
|
139
|
+
if (cmd.longRunning && (typeof code !== 'number' || code === 0)) this.keepAlive = true
|
|
140
|
+
return typeof code === 'number' ? code : 0
|
|
141
|
+
} finally {
|
|
142
|
+
if (!cmd.longRunning) {
|
|
143
|
+
await scope.dispose()
|
|
144
|
+
await this.app.shutdown()
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Levenshtein distance, for "did you mean". */
|
|
151
|
+
function distance(a: string, b: string): number {
|
|
152
|
+
const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array<number>(b.length).fill(0)])
|
|
153
|
+
for (let j = 1; j <= b.length; j++) (d[0] as number[])[j] = j
|
|
154
|
+
for (let i = 1; i <= a.length; i++) {
|
|
155
|
+
for (let j = 1; j <= b.length; j++) {
|
|
156
|
+
const row = d[i] as number[]
|
|
157
|
+
const prev = d[i - 1] as number[]
|
|
158
|
+
row[j] = Math.min(
|
|
159
|
+
(prev[j] as number) + 1,
|
|
160
|
+
(row[j - 1] as number) + 1,
|
|
161
|
+
(prev[j - 1] as number) + (a[i - 1] === b[j - 1] ? 0 : 1),
|
|
162
|
+
)
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return (d[a.length] as number[])[b.length] as number
|
|
166
|
+
}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { COMMANDS, Command, type CommandClass, flag } from '@cslug/core'
|
|
4
|
+
import type { CslugConfig } from './config'
|
|
5
|
+
|
|
6
|
+
/** One child process: its role label and the `cslug` arguments it runs. */
|
|
7
|
+
export type ProcessSpec = { name: string; argv: string[] }
|
|
8
|
+
|
|
9
|
+
const BIN = join(import.meta.dir, 'bin.ts')
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The processes `cslug start` runs, from flags (when given) or `cslug.config.ts`. Roles whose command is not
|
|
13
|
+
* installed (worker without @cslug/queue) are skipped with a warning by the caller.
|
|
14
|
+
*/
|
|
15
|
+
export function plannedProcesses(
|
|
16
|
+
config: CslugConfig['processes'] = {},
|
|
17
|
+
flags: { web?: boolean; worker?: string[]; scheduler?: boolean } = {},
|
|
18
|
+
): ProcessSpec[] {
|
|
19
|
+
const explicit = flags.web || flags.scheduler || (flags.worker?.length ?? 0) > 0
|
|
20
|
+
const web = explicit ? (flags.web ? { instances: 1 } : false) : (config.web ?? { instances: 1 })
|
|
21
|
+
const workers = explicit
|
|
22
|
+
? (flags.worker ?? []).flatMap(parseWorker)
|
|
23
|
+
: config.worker === false
|
|
24
|
+
? []
|
|
25
|
+
: (config.worker ?? [{ queues: ['default'] }])
|
|
26
|
+
const scheduler = explicit ? !!flags.scheduler : (config.scheduler ?? true)
|
|
27
|
+
|
|
28
|
+
const out: ProcessSpec[] = []
|
|
29
|
+
const instances = web ? (web.instances ?? 1) : 0
|
|
30
|
+
for (let i = 1; i <= instances; i++)
|
|
31
|
+
out.push({ name: instances > 1 ? `web#${i}` : 'web', argv: ['serve', ...(instances > 1 ? ['--reuse-port'] : [])] })
|
|
32
|
+
workers.forEach((w, i) => {
|
|
33
|
+
out.push({
|
|
34
|
+
name: workers.length > 1 ? `worker#${i + 1}` : 'worker',
|
|
35
|
+
argv: [
|
|
36
|
+
'queue:work',
|
|
37
|
+
...(w.queues?.length ? [`--queues=${w.queues.join(',')}`] : []),
|
|
38
|
+
...(w.concurrency ? [`--concurrency=${w.concurrency}`] : []),
|
|
39
|
+
],
|
|
40
|
+
})
|
|
41
|
+
})
|
|
42
|
+
if (scheduler) out.push({ name: 'scheduler', argv: ['schedule:work'] })
|
|
43
|
+
return out
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** `--worker=2` → two default workers; `--worker=payments:1` → queues payments, concurrency 1. */
|
|
47
|
+
function parseWorker(spec: string): { queues?: string[]; concurrency?: number }[] {
|
|
48
|
+
if (/^\d+$/.test(spec)) return Array.from({ length: Number(spec) }, () => ({ queues: ['default'] }))
|
|
49
|
+
const [queues, concurrency] = spec.split(':')
|
|
50
|
+
return [
|
|
51
|
+
{
|
|
52
|
+
queues: (queues ?? 'default').split(',').filter(Boolean),
|
|
53
|
+
concurrency: concurrency ? Number(concurrency) : undefined,
|
|
54
|
+
},
|
|
55
|
+
]
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type Child = { spec: ProcessSpec; proc?: Bun.Subprocess; startedAt: number; restarts: number; exited?: number | null }
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Runs each role as a child process, restarts crashed ones with backoff (1s, 2s, 4s … 30s; reset after a minute
|
|
62
|
+
* up), forwards SIGTERM/SIGINT, waits for them to drain (then kills what is left), and resolves with the exit code.
|
|
63
|
+
*/
|
|
64
|
+
export class Supervisor {
|
|
65
|
+
private readonly children: Child[]
|
|
66
|
+
private stopping = false
|
|
67
|
+
private done!: (code: number) => void
|
|
68
|
+
readonly finished = new Promise<number>((r) => {
|
|
69
|
+
this.done = r
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
constructor(
|
|
73
|
+
specs: ProcessSpec[],
|
|
74
|
+
private readonly options: {
|
|
75
|
+
cwd: string
|
|
76
|
+
/** Extra `bun` flags (`--watch` for `cslug dev`). */
|
|
77
|
+
bunFlags?: string[]
|
|
78
|
+
/** Extra environment for the children (`CSLUG_DEV=1` under `cslug dev`). */
|
|
79
|
+
env?: Record<string, string>
|
|
80
|
+
/** Seconds a child gets after SIGTERM (default 30). */
|
|
81
|
+
shutdownTimeout?: number
|
|
82
|
+
log?: (line: string) => void
|
|
83
|
+
/** Prefix child output with its role (default: when stdout is a terminal; plain JSON lines otherwise). */
|
|
84
|
+
prefix?: boolean
|
|
85
|
+
bin?: string
|
|
86
|
+
},
|
|
87
|
+
) {
|
|
88
|
+
this.children = specs.map((spec) => ({ spec, startedAt: 0, restarts: 0 }))
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private get log() {
|
|
92
|
+
return this.options.log ?? ((l: string) => process.stdout.write(`${l}\n`))
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
start(): this {
|
|
96
|
+
for (const c of this.children) this.spawn(c)
|
|
97
|
+
return this
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
get pids(): Record<string, number | undefined> {
|
|
101
|
+
return Object.fromEntries(this.children.map((c) => [c.spec.name, c.proc?.pid]))
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private spawn(child: Child): void {
|
|
105
|
+
const prefix = this.options.prefix ?? !!process.stdout.isTTY
|
|
106
|
+
child.startedAt = Date.now()
|
|
107
|
+
child.exited = undefined
|
|
108
|
+
const proc = Bun.spawn(
|
|
109
|
+
[process.execPath, ...(this.options.bunFlags ?? []), this.options.bin ?? BIN, ...child.spec.argv],
|
|
110
|
+
{
|
|
111
|
+
cwd: this.options.cwd,
|
|
112
|
+
env: { ...process.env, ...this.options.env, CSLUG_ROLE: child.spec.name },
|
|
113
|
+
stdout: prefix ? 'pipe' : 'inherit',
|
|
114
|
+
stderr: prefix ? 'pipe' : 'inherit',
|
|
115
|
+
stdin: 'ignore',
|
|
116
|
+
},
|
|
117
|
+
)
|
|
118
|
+
child.proc = proc
|
|
119
|
+
if (prefix) {
|
|
120
|
+
this.pipe(proc.stdout as ReadableStream<Uint8Array>, child.spec.name, process.stdout)
|
|
121
|
+
this.pipe(proc.stderr as ReadableStream<Uint8Array>, child.spec.name, process.stderr)
|
|
122
|
+
}
|
|
123
|
+
this.log(` ➜ ${child.spec.name.padEnd(10)} pid ${proc.pid} cslug ${child.spec.argv.join(' ')}`)
|
|
124
|
+
proc.exited.then((code) => this.onExit(child, proc, code))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
private async pipe(stream: ReadableStream<Uint8Array>, name: string, out: NodeJS.WriteStream): Promise<void> {
|
|
128
|
+
const decoder = new TextDecoder()
|
|
129
|
+
let buffer = ''
|
|
130
|
+
for await (const chunk of stream) {
|
|
131
|
+
buffer += decoder.decode(chunk, { stream: true })
|
|
132
|
+
const lines = buffer.split('\n')
|
|
133
|
+
buffer = lines.pop() ?? ''
|
|
134
|
+
for (const line of lines) out.write(`[${name}] ${line}\n`)
|
|
135
|
+
}
|
|
136
|
+
if (buffer) out.write(`[${name}] ${buffer}\n`)
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private onExit(child: Child, proc: Bun.Subprocess, code: number | null): void {
|
|
140
|
+
if (child.proc !== proc) return
|
|
141
|
+
child.exited = code
|
|
142
|
+
if (this.stopping) {
|
|
143
|
+
if (this.children.every((c) => c.exited !== undefined))
|
|
144
|
+
this.done(this.children.every((c) => c.exited === 0) ? 0 : 1)
|
|
145
|
+
return
|
|
146
|
+
}
|
|
147
|
+
// a child that stayed up for a minute starts over with a short delay
|
|
148
|
+
if (Date.now() - child.startedAt > 60_000) child.restarts = 0
|
|
149
|
+
const delay = Math.min(30_000, 1000 * 2 ** child.restarts++)
|
|
150
|
+
this.log(` ✗ ${child.spec.name} exited (${code ?? 'signal'}); restarting in ${delay / 1000}s`)
|
|
151
|
+
setTimeout(() => {
|
|
152
|
+
if (!this.stopping) this.spawn(child)
|
|
153
|
+
}, delay)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Forward SIGTERM to every child; kill the ones still running after the timeout. */
|
|
157
|
+
async stop(signal: NodeJS.Signals = 'SIGTERM'): Promise<number> {
|
|
158
|
+
if (this.stopping) return this.finished
|
|
159
|
+
this.stopping = true
|
|
160
|
+
const running = this.children.filter((c) => c.proc && c.exited === undefined)
|
|
161
|
+
for (const c of this.children) if (!running.includes(c)) c.exited = 0 // crashed and waiting to restart: nothing to stop
|
|
162
|
+
if (!running.length) this.done(0)
|
|
163
|
+
for (const c of running) c.proc?.kill(signal)
|
|
164
|
+
const timeout = (this.options.shutdownTimeout ?? 30) * 1000
|
|
165
|
+
const timer = setTimeout(() => {
|
|
166
|
+
for (const c of running) if (c.exited === undefined) c.proc?.kill('SIGKILL')
|
|
167
|
+
}, timeout)
|
|
168
|
+
const code = await this.finished
|
|
169
|
+
clearTimeout(timer)
|
|
170
|
+
return code
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const commandExists = async (app: Command['app'], signature: string): Promise<boolean> => {
|
|
175
|
+
const { builtinCommands } = await import('./commands/builtin')
|
|
176
|
+
return [...builtinCommands, ...(app.taggedTokens(COMMANDS) as CommandClass[])].some((c) => c.signature === signature)
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function loadConfig(root: string): Promise<CslugConfig> {
|
|
180
|
+
const path = join(root, 'cslug.config.ts')
|
|
181
|
+
return existsSync(path) ? (((await import(path)).default as CslugConfig | undefined) ?? {}) : {}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const roleFlags = {
|
|
185
|
+
web: flag.boolean().describe('Run the web server'),
|
|
186
|
+
worker: flag.list().describe('Workers: 2 | payments:1 | default,mail:5 (repeatable)'),
|
|
187
|
+
scheduler: flag.boolean().describe('Run the scheduler'),
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function supervise(
|
|
191
|
+
cmd: Command,
|
|
192
|
+
flags: Command.Args<{ args: typeof roleFlags }>,
|
|
193
|
+
bunFlags: string[],
|
|
194
|
+
banner: string,
|
|
195
|
+
env: Record<string, string> = {},
|
|
196
|
+
): Promise<number> {
|
|
197
|
+
const config = await loadConfig(cmd.app.rootDir)
|
|
198
|
+
const planned = plannedProcesses(config.processes, flags)
|
|
199
|
+
const specs: ProcessSpec[] = []
|
|
200
|
+
for (const p of planned) {
|
|
201
|
+
if (await commandExists(cmd.app, p.argv[0] as string)) specs.push(p)
|
|
202
|
+
else
|
|
203
|
+
cmd.warn(
|
|
204
|
+
`${p.name}: \`cslug ${p.argv[0]}\` is not installed (${p.argv[0] === 'serve' ? '@cslug/http' : '@cslug/queue'}); skipped`,
|
|
205
|
+
)
|
|
206
|
+
}
|
|
207
|
+
if (!specs.length) {
|
|
208
|
+
cmd.error('Nothing to run')
|
|
209
|
+
return 1
|
|
210
|
+
}
|
|
211
|
+
cmd.line(` cslug ${banner} (supervisor pid ${process.pid})`)
|
|
212
|
+
const supervisor = new Supervisor(specs, {
|
|
213
|
+
cwd: cmd.app.rootDir,
|
|
214
|
+
env,
|
|
215
|
+
bunFlags,
|
|
216
|
+
shutdownTimeout: config.shutdownTimeout,
|
|
217
|
+
log: (l) => cmd.line(l),
|
|
218
|
+
}).start()
|
|
219
|
+
const onSignal = (signal: NodeJS.Signals) => {
|
|
220
|
+
cmd.line(` ${signal}: stopping ${specs.length} process(es)…`)
|
|
221
|
+
supervisor.stop(signal).then((code) => process.exit(code))
|
|
222
|
+
}
|
|
223
|
+
process.once('SIGTERM', onSignal)
|
|
224
|
+
process.once('SIGINT', onSignal)
|
|
225
|
+
return 0
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** `cslug start`: production supervisor. */
|
|
229
|
+
export class StartCommand extends Command {
|
|
230
|
+
static signature = 'start'
|
|
231
|
+
static description = 'Run web, workers and scheduler as supervised child processes (cslug.config.ts processes)'
|
|
232
|
+
static boot = false
|
|
233
|
+
static longRunning = true
|
|
234
|
+
static args = roleFlags
|
|
235
|
+
|
|
236
|
+
handle(flags: Command.Args<typeof StartCommand>) {
|
|
237
|
+
return supervise(this, flags, [], 'start')
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** `cslug dev`: the same processes, restarted by `bun --watch` when a file changes. */
|
|
242
|
+
export class DevCommand extends Command {
|
|
243
|
+
static signature = 'dev'
|
|
244
|
+
static description = 'Development: web, workers and scheduler, restarted when files change'
|
|
245
|
+
static boot = false
|
|
246
|
+
static longRunning = true
|
|
247
|
+
static args = roleFlags
|
|
248
|
+
|
|
249
|
+
handle(flags: Command.Args<typeof DevCommand>) {
|
|
250
|
+
return supervise(this, flags, ['--watch', '--no-clear-screen'], 'dev', { CSLUG_DEV: '1' })
|
|
251
|
+
}
|
|
252
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Command, arg, flag } from '@cslug/cli'
|
|
2
|
+
|
|
3
|
+
export class {{ class }} extends Command {
|
|
4
|
+
static signature = '{{ kebab }}'
|
|
5
|
+
static description = ''
|
|
6
|
+
static args = {
|
|
7
|
+
// name: arg.string().describe('…'),
|
|
8
|
+
dryRun: flag.boolean().describe('Show what would change'),
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
async handle({ dryRun }: Command.Args<typeof {{ class }}>) {
|
|
12
|
+
this.info(dryRun ? 'Dry run' : 'Running')
|
|
13
|
+
}
|
|
14
|
+
}
|
package/stubs/event.stub
ADDED