@cslug/cli 0.2.0 → 0.4.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/docs/README.md +30 -1
- package/docs/api.md +3 -0
- package/package.json +2 -2
- package/src/commands/add.ts +151 -0
- package/src/commands/builtin.ts +6 -0
- package/src/commands/describe.ts +59 -0
- package/src/commands/repl.ts +111 -0
- package/src/index.ts +3 -0
- package/stubs/add/mail.config.stub +11 -0
- package/stubs/add/notification.config.stub +7 -0
- package/stubs/add/queue.config.stub +10 -0
- package/stubs/add/schedule.stub +6 -0
- package/stubs/add/storage.config.stub +9 -0
- package/stubs/add/tailwind.css.stub +1 -0
- package/stubs/add/webhooks.config.stub +6 -0
package/docs/README.md
CHANGED
|
@@ -8,10 +8,39 @@ Where commands come from:
|
|
|
8
8
|
|
|
9
9
|
| Source | How |
|
|
10
10
|
|---|---|
|
|
11
|
-
| built-in | `list`, `about`, `config:show`, `key:generate`, `start`, `dev`, `make:command/provider/event/listener/service/test` |
|
|
11
|
+
| built-in | `list`, `about`, `config:show`, `key:generate`, `add`, `describe`, `repl`, `start`, `dev`, `make:command/provider/event/listener/service/test` |
|
|
12
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
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
14
|
|
|
15
15
|
`cslug start` runs each role as a child process (`serve`, `queue:work`, `schedule:work`), restarts crashed
|
|
16
16
|
ones with backoff, forwards SIGTERM and exits 0 once they have all drained. `cslug dev` runs the same processes
|
|
17
17
|
under `bun --watch`. Roles whose command is not installed are skipped with a warning.
|
|
18
|
+
|
|
19
|
+
## `cslug add`
|
|
20
|
+
|
|
21
|
+
`cslug add queue` (or several: `cslug add queue,mail`) installs a package and wires it:
|
|
22
|
+
|
|
23
|
+
| Name | Installs | Wires |
|
|
24
|
+
|---|---|---|
|
|
25
|
+
| `queue` | `@cslug/queue` | `QueueProvider`, `ScheduleProvider`; `config/queue.ts`; `routes/schedule.ts`; a worker and the scheduler in `cslug.config.ts` |
|
|
26
|
+
| `mail` | `@cslug/mail` | `MailProvider`; `config/mail.ts` (log transport, SMTP for Mailpit) |
|
|
27
|
+
| `storage` | `@cslug/storage` | `StorageProvider`; `config/storage.ts` |
|
|
28
|
+
| `notification` | `@cslug/notification` | `NotificationProvider`; `config/notification.ts`; then `cslug migrate` |
|
|
29
|
+
| `webhook` | `@cslug/webhook` | `WebhookProvider`; `config/webhooks.ts`; then `cslug migrate` |
|
|
30
|
+
| `tailwind` | `tailwindcss`, `bun-plugin-tailwind` (dev) | `resources/styles/tailwind.css`, its import in `resources/client.ts`, `assets.tailwind: true` |
|
|
31
|
+
|
|
32
|
+
`@cslug/*` packages are installed at the CLI's own version (every package of a release shares it). Providers go into
|
|
33
|
+
`bootstrap/providers.ts` before `AppServiceProvider`; config files are written only when missing and listed in
|
|
34
|
+
`config/index.ts`. Running it again changes nothing. When a file does not have the shape `bun create cslug` writes,
|
|
35
|
+
it says what to add by hand. `--no-install` edits the files without running `bun add`.
|
|
36
|
+
|
|
37
|
+
## `cslug describe` and `cslug repl`
|
|
38
|
+
|
|
39
|
+
`cslug describe [section] [--json]` prints the app as data: a summary of the sections, one section, or everything
|
|
40
|
+
with `--json`. The CLI has `providers` and `config` (keys only); packages add theirs with `this.describe(name, fn)`
|
|
41
|
+
in a provider: `routes` (http), `tables` (database, from `app/tables/`), `jobs` and `schedules` (queue).
|
|
42
|
+
|
|
43
|
+
`cslug repl` boots the app and reads TypeScript lines: top-level `await`, declarations kept between lines, an open
|
|
44
|
+
brace continues on the next line. In scope: `app`, `resolve`, `config` and the exports of `app/tables/` and
|
|
45
|
+
`app/repositories/`. `evaluate(code, scope)` and `replScope(app)` are exported for tools.
|
|
46
|
+
|
package/docs/api.md
CHANGED
|
@@ -39,6 +39,9 @@ plus `app`, `clock`, `log`, `io`. When the session is not interactive, prompts r
|
|
|
39
39
|
| `CliKernel(app)` | `.run(argv)` → exit code; `.commands()` |
|
|
40
40
|
| `Supervisor(specs, options)` | `.start()`, `.stop(signal)` → exit code; `plannedProcesses(config, flags)` |
|
|
41
41
|
| `generator(kind, dir, description)` | a `make:<kind>` command from `stubs/<kind>.stub` |
|
|
42
|
+
| `AddCommand`, `ADDITIONS` | `cslug add <names>` and what each name installs and wires |
|
|
43
|
+
| `DescribeCommand` | `cslug describe [section] [--json]` |
|
|
44
|
+
| `ReplCommand`, `evaluate(code, scope)`, `replScope(app)` | `cslug repl` and its evaluator |
|
|
42
45
|
| `BufferedIO(answers?)` | capture output in tests: `app.instance(ConsoleIO, io)` |
|
|
43
46
|
| `defineCslugConfig()` | `cslug.config.ts`: `processes` (`web.instances`, `worker[]`, `scheduler`), `shutdownTimeout`, `assets` |
|
|
44
47
|
| `commandHelp(cmd)` | |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "The cslug command: generators, dev server, start supervisor, REPL.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -31,7 +31,7 @@
|
|
|
31
31
|
"cslug": "src/bin.ts"
|
|
32
32
|
},
|
|
33
33
|
"peerDependencies": {
|
|
34
|
-
"@cslug/core": "0.
|
|
34
|
+
"@cslug/core": "0.4.0"
|
|
35
35
|
},
|
|
36
36
|
"devDependencies": {
|
|
37
37
|
"@cslug/database": "workspace:*",
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { arg, Command, flag } from '@cslug/core'
|
|
4
|
+
|
|
5
|
+
const STUBS = join(import.meta.dir, '../../stubs/add')
|
|
6
|
+
|
|
7
|
+
/** What `cslug add <name>` installs and wires. `config`: the `config/<key>.ts` written from `<stub>.config.stub`. */
|
|
8
|
+
type Addition = {
|
|
9
|
+
packages: string[]
|
|
10
|
+
dev?: boolean
|
|
11
|
+
providers?: { from: string; names: string[] }
|
|
12
|
+
config?: string
|
|
13
|
+
files?: Record<string, string>
|
|
14
|
+
processes?: string
|
|
15
|
+
next?: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const ADDITIONS: Record<string, Addition> = {
|
|
19
|
+
queue: {
|
|
20
|
+
packages: ['@cslug/queue'],
|
|
21
|
+
providers: { from: '@cslug/queue', names: ['QueueProvider', 'ScheduleProvider'] },
|
|
22
|
+
config: 'queue',
|
|
23
|
+
files: { 'routes/schedule.ts': 'schedule.stub' },
|
|
24
|
+
processes: " worker: [{ queues: ['default'], concurrency: 5 }],\n scheduler: true,\n",
|
|
25
|
+
},
|
|
26
|
+
mail: { packages: ['@cslug/mail'], providers: { from: '@cslug/mail', names: ['MailProvider'] }, config: 'mail' },
|
|
27
|
+
storage: {
|
|
28
|
+
packages: ['@cslug/storage'],
|
|
29
|
+
providers: { from: '@cslug/storage', names: ['StorageProvider'] },
|
|
30
|
+
config: 'storage',
|
|
31
|
+
},
|
|
32
|
+
notification: {
|
|
33
|
+
packages: ['@cslug/notification'],
|
|
34
|
+
providers: { from: '@cslug/notification', names: ['NotificationProvider'] },
|
|
35
|
+
config: 'notification',
|
|
36
|
+
next: 'cslug migrate (creates cslug_notifications and cslug_notification_deliveries)',
|
|
37
|
+
},
|
|
38
|
+
webhook: {
|
|
39
|
+
packages: ['@cslug/webhook'],
|
|
40
|
+
providers: { from: '@cslug/webhook', names: ['WebhookProvider'] },
|
|
41
|
+
config: 'webhooks',
|
|
42
|
+
next: 'cslug migrate (creates cslug_webhook_inbox)',
|
|
43
|
+
},
|
|
44
|
+
tailwind: {
|
|
45
|
+
packages: ['tailwindcss@^4.0.0', 'bun-plugin-tailwind'],
|
|
46
|
+
dev: true,
|
|
47
|
+
files: { 'resources/styles/tailwind.css': 'tailwind.css.stub' },
|
|
48
|
+
},
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The version of every @cslug/* package of this release (they share one). */
|
|
52
|
+
const VERSION: string = JSON.parse(readFileSync(join(import.meta.dir, '../../package.json'), 'utf8')).version
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* `cslug add queue,mail`: installs the packages (at this CLI's version), adds their providers to
|
|
56
|
+
* `bootstrap/providers.ts`, writes their config file and lists it in `config/index.ts`. Running it twice changes
|
|
57
|
+
* nothing; a file it cannot edit is reported with what to add by hand.
|
|
58
|
+
*/
|
|
59
|
+
export class AddCommand extends Command {
|
|
60
|
+
static signature = 'add'
|
|
61
|
+
static description = `Add a package to the app: ${Object.keys(ADDITIONS).join(', ')}`
|
|
62
|
+
static boot = false
|
|
63
|
+
static args = {
|
|
64
|
+
names: arg.string().describe('One or more, comma-separated: queue,mail'),
|
|
65
|
+
install: flag.boolean().default(true).describe('Run bun add (--no-install to only edit files)'),
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async handle({ names, install }: Command.Args<typeof AddCommand>) {
|
|
69
|
+
const wanted = names
|
|
70
|
+
.split(',')
|
|
71
|
+
.map((n) => n.trim())
|
|
72
|
+
.filter(Boolean)
|
|
73
|
+
const unknown = wanted.filter((n) => !ADDITIONS[n])
|
|
74
|
+
if (unknown.length) {
|
|
75
|
+
this.error(`Unknown: ${unknown.join(', ')}. Available: ${Object.keys(ADDITIONS).join(', ')}`)
|
|
76
|
+
return 1
|
|
77
|
+
}
|
|
78
|
+
for (const name of wanted) if (!(await this.add(name, ADDITIONS[name] as Addition, install))) return 1
|
|
79
|
+
return 0
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private async add(name: string, a: Addition, install: boolean): Promise<boolean> {
|
|
83
|
+
if (install) {
|
|
84
|
+
const specs = a.packages.map((p) => (p.startsWith('@cslug/') ? `${p}@${VERSION}` : p))
|
|
85
|
+
const proc = Bun.spawn(['bun', 'add', ...(a.dev ? ['-d'] : []), ...specs], {
|
|
86
|
+
cwd: this.app.rootDir,
|
|
87
|
+
stdout: 'inherit',
|
|
88
|
+
stderr: 'inherit',
|
|
89
|
+
})
|
|
90
|
+
if ((await proc.exited) !== 0) {
|
|
91
|
+
this.error(`bun add failed for ${name}`)
|
|
92
|
+
return false
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (a.providers) this.addProviders(a.providers)
|
|
96
|
+
if (a.config) {
|
|
97
|
+
this.generate(STUBS, `${a.config}.config.stub`, `config/${a.config}.ts`, {})
|
|
98
|
+
this.addConfig(a.config)
|
|
99
|
+
}
|
|
100
|
+
for (const [target, stub] of Object.entries(a.files ?? {})) this.generate(STUBS, stub, target, {})
|
|
101
|
+
if (a.processes) this.edit('cslug.config.ts', /( *processes: \{\n(?:.*web.*\n)?)/, `$1${a.processes}`, 'worker:')
|
|
102
|
+
if (name === 'tailwind') {
|
|
103
|
+
this.edit('cslug.config.ts', /tailwind: false/, 'tailwind: true', 'tailwind: true')
|
|
104
|
+
this.edit(
|
|
105
|
+
'resources/client.ts',
|
|
106
|
+
/(import '.\/styles\/[^']+'\n)/,
|
|
107
|
+
"$1import './styles/tailwind.css'\n",
|
|
108
|
+
'tailwind.css',
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
this.success(`${name} added${a.next ? `; next: ${a.next}` : ''}`)
|
|
112
|
+
return true
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private addProviders({ from, names }: { from: string; names: string[] }) {
|
|
116
|
+
const missing = names.filter((n) => !this.read('bootstrap/providers.ts')?.includes(n))
|
|
117
|
+
if (!missing.length) return
|
|
118
|
+
const imported = `import { ${missing.join(', ')} } from '${from}'\n`
|
|
119
|
+
this.edit('bootstrap/providers.ts', /((?:^import .*\n)+)/m, `$1${imported}`, imported.trim())
|
|
120
|
+
// before the app's own provider (it may use what the package binds), else at the end of the list
|
|
121
|
+
const entries = missing.map((n) => ` ${n},\n`).join('')
|
|
122
|
+
const text = this.read('bootstrap/providers.ts') ?? ''
|
|
123
|
+
if (/^ *AppServiceProvider,/m.test(text))
|
|
124
|
+
this.edit('bootstrap/providers.ts', /^( *AppServiceProvider,)/m, `${entries}$1`)
|
|
125
|
+
else
|
|
126
|
+
this.edit('bootstrap/providers.ts', /(export const providers = \[[\s\S]*?)(\n\])/, `$1\n${entries.trimEnd()}$2`)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
private addConfig(key: string) {
|
|
130
|
+
if (new RegExp(`^import ${key} from`, 'm').test(this.read('config/index.ts') ?? '')) return
|
|
131
|
+
this.edit('config/index.ts', /((?:^import \w+ from ["']\.\/\w+["']\n)+)/m, `$1import ${key} from './${key}'\n`)
|
|
132
|
+
this.edit('config/index.ts', /(export const configs = \{[^}]*?)(\s*\})/, `$1, ${key}$2`)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private read(path: string): string | undefined {
|
|
136
|
+
const file = join(this.app.rootDir, path)
|
|
137
|
+
return existsSync(file) ? readFileSync(file, 'utf8') : undefined
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Replace `pattern` in `path` unless `done` is already there; when the pattern is not found, say what to add. */
|
|
141
|
+
private edit(path: string, pattern: RegExp, replacement: string, done?: string) {
|
|
142
|
+
const text = this.read(path)
|
|
143
|
+
if (text === undefined || (done && text.includes(done))) return
|
|
144
|
+
if (!pattern.test(text)) {
|
|
145
|
+
this.warn(`could not edit ${path}: add ${replacement.replace(/\$\d/g, '').trim()} by hand`)
|
|
146
|
+
return
|
|
147
|
+
}
|
|
148
|
+
writeFileSync(join(this.app.rootDir, path), text.replace(pattern, replacement))
|
|
149
|
+
this.info(`updated ${path}`)
|
|
150
|
+
}
|
|
151
|
+
}
|
package/src/commands/builtin.ts
CHANGED
|
@@ -2,6 +2,9 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
import { arg, Command, type CommandClass, flag, names } from '@cslug/core'
|
|
4
4
|
import { DevCommand, StartCommand } from '../supervisor'
|
|
5
|
+
import { AddCommand } from './add'
|
|
6
|
+
import { DescribeCommand } from './describe'
|
|
7
|
+
import { ReplCommand } from './repl'
|
|
5
8
|
|
|
6
9
|
export const STUBS = join(import.meta.dir, '../../stubs')
|
|
7
10
|
|
|
@@ -166,6 +169,9 @@ export const builtinCommands: CommandClass[] = [
|
|
|
166
169
|
AboutCommand,
|
|
167
170
|
ConfigShowCommand,
|
|
168
171
|
KeyGenerateCommand,
|
|
172
|
+
AddCommand,
|
|
173
|
+
DescribeCommand,
|
|
174
|
+
ReplCommand,
|
|
169
175
|
StartCommand,
|
|
170
176
|
DevCommand,
|
|
171
177
|
generator('command', 'app/commands', 'Create a command class'),
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { arg, Command, DESCRIBE, type DescribeSection, flag } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
const flat = (row: unknown): row is Record<string, unknown> =>
|
|
4
|
+
typeof row === 'object' && row !== null && !Array.isArray(row)
|
|
5
|
+
const cell = (value: unknown) =>
|
|
6
|
+
Array.isArray(value) && value.every((v) => typeof v !== 'object')
|
|
7
|
+
? value.join(', ')
|
|
8
|
+
: typeof value === 'object' && value !== null
|
|
9
|
+
? JSON.stringify(value)
|
|
10
|
+
: value
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* `cslug describe [section] [--json]`: the app as data, for people, scripts and AI coding agents. Sections come from
|
|
14
|
+
* the installed packages (routes, tables, jobs, schedules) plus `providers` and `config` (keys only, never values).
|
|
15
|
+
*/
|
|
16
|
+
export class DescribeCommand extends Command {
|
|
17
|
+
static signature = 'describe'
|
|
18
|
+
static description = 'The app as data: routes, tables, jobs, schedules, providers, config keys (--json)'
|
|
19
|
+
static args = {
|
|
20
|
+
section: arg.string().optional().describe('One section; without it, a summary (or everything with --json)'),
|
|
21
|
+
json: flag.boolean().describe('Machine-readable output'),
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async handle({ section, json }: Command.Args<typeof DescribeCommand>) {
|
|
25
|
+
const sections = new Map<string, () => unknown>([
|
|
26
|
+
['providers', () => this.app.providers.map((p) => p.name)],
|
|
27
|
+
[
|
|
28
|
+
'config',
|
|
29
|
+
() =>
|
|
30
|
+
Object.fromEntries(
|
|
31
|
+
Object.entries(this.app.configs).map(([name, value]) => [name, flat(value) ? Object.keys(value) : []]),
|
|
32
|
+
),
|
|
33
|
+
],
|
|
34
|
+
])
|
|
35
|
+
for (const s of this.app.tagged<DescribeSection>(DESCRIBE)) sections.set(s.name, s.collect)
|
|
36
|
+
|
|
37
|
+
if (!section) {
|
|
38
|
+
const all: Record<string, unknown> = {}
|
|
39
|
+
for (const [name, collect] of sections) all[name] = await collect()
|
|
40
|
+
if (json) return this.line(JSON.stringify(all))
|
|
41
|
+
return this.table(
|
|
42
|
+
Object.entries(all).map(([name, data]) => ({
|
|
43
|
+
section: name,
|
|
44
|
+
entries: Array.isArray(data) ? data.length : flat(data) ? Object.keys(data).length : 0,
|
|
45
|
+
})),
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
const collect = sections.get(section)
|
|
49
|
+
if (!collect) {
|
|
50
|
+
this.error(`No section "${section}". Sections: ${[...sections.keys()].join(', ')}`)
|
|
51
|
+
return 1
|
|
52
|
+
}
|
|
53
|
+
const data = await collect()
|
|
54
|
+
if (json) this.line(JSON.stringify(data))
|
|
55
|
+
else if (Array.isArray(data) && data.every(flat))
|
|
56
|
+
this.table(data.map((row) => Object.fromEntries(Object.entries(row).map(([k, v]) => [k, cell(v)]))))
|
|
57
|
+
else this.line(JSON.stringify(data, null, 2))
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { type Application, Command } from '@cslug/core'
|
|
4
|
+
|
|
5
|
+
type Scope = Record<string, unknown>
|
|
6
|
+
export type Evaluated = { value?: unknown; error?: unknown; incomplete?: boolean }
|
|
7
|
+
|
|
8
|
+
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new (
|
|
9
|
+
...args: string[]
|
|
10
|
+
) => (scope: Scope) => Promise<unknown>
|
|
11
|
+
const transpiler = new Bun.Transpiler({ loader: 'ts', trimUnusedImports: false })
|
|
12
|
+
|
|
13
|
+
/** Everything `app/tables/` and `app/repositories/` export, plus `app`, `resolve` and `config`. */
|
|
14
|
+
export async function replScope(app: Application): Promise<Scope> {
|
|
15
|
+
const scope: Scope = {
|
|
16
|
+
app,
|
|
17
|
+
resolve: app.resolve.bind(app),
|
|
18
|
+
config: (path: string) => app.config(path),
|
|
19
|
+
}
|
|
20
|
+
for (const folder of ['app/tables', 'app/repositories']) {
|
|
21
|
+
const dir = join(app.rootDir, folder)
|
|
22
|
+
if (!existsSync(dir)) continue
|
|
23
|
+
for (const file of (readdirSync(dir, { recursive: true }) as string[]).filter((f) => /(?<!\.test)\.ts$/.test(f)))
|
|
24
|
+
Object.assign(scope, await import(join(dir, file)))
|
|
25
|
+
}
|
|
26
|
+
return scope
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Run one input in the scope: TypeScript, top-level `await`; `const` / `let` / `var x = …`, functions and classes
|
|
31
|
+
* declared at the start of a line are kept for the next inputs. An expression's value is returned; input that ends
|
|
32
|
+
* early (an open brace) is `incomplete`.
|
|
33
|
+
*/
|
|
34
|
+
const DECLARATION = /^\s*(?:const|let|var|class|function|async\s+function|import|export)\b/
|
|
35
|
+
|
|
36
|
+
export async function evaluate(code: string, scope: Scope): Promise<Evaluated> {
|
|
37
|
+
let run: (scope: Scope) => Promise<unknown>
|
|
38
|
+
try {
|
|
39
|
+
run = (DECLARATION.test(code) ? undefined : asExpression(code)) ?? asStatements(code)
|
|
40
|
+
} catch (error) {
|
|
41
|
+
return /end of file|unexpected end/i.test(String(error)) ? { incomplete: true } : { error }
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
return { value: await run(scope) }
|
|
45
|
+
} catch (error) {
|
|
46
|
+
return { error }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// an expression's value is kept by assigning it (the transpiler drops expression statements without effects)
|
|
50
|
+
function asExpression(input: string) {
|
|
51
|
+
let js: string
|
|
52
|
+
try {
|
|
53
|
+
js = transpiler.transformSync(`__value = (${input}\n)`).trim()
|
|
54
|
+
} catch {
|
|
55
|
+
return undefined
|
|
56
|
+
}
|
|
57
|
+
const body = js.replace(/^__value\s*=\s*/, '').replace(/;\s*$/, '')
|
|
58
|
+
return new AsyncFunction('scope', `with (scope) { return (${body}\n) }`)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// a declaration at the start of a line becomes an assignment to the scope, so later inputs see it
|
|
62
|
+
function asStatements(input: string) {
|
|
63
|
+
const keep = (name: string) => {
|
|
64
|
+
scope[name] = undefined
|
|
65
|
+
return name
|
|
66
|
+
}
|
|
67
|
+
const js = transpiler
|
|
68
|
+
.transformSync(input)
|
|
69
|
+
.replace(/^(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/gm, (_m, name: string) => `${keep(name)} =`)
|
|
70
|
+
.replace(
|
|
71
|
+
/^((?:async\s+)?function\*?|class)\s+([A-Za-z_$][\w$]*)/gm,
|
|
72
|
+
(m, _kind, name: string) => `${keep(name)} = ${m}`,
|
|
73
|
+
)
|
|
74
|
+
return new AsyncFunction('scope', `with (scope) { ${js}\n}`)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** `cslug repl`: a TypeScript shell with the app booted. `.help` lists the names in scope, `.exit` leaves. */
|
|
79
|
+
export class ReplCommand extends Command {
|
|
80
|
+
static signature = 'repl'
|
|
81
|
+
static description = 'A TypeScript shell with the app booted (tables and repositories in scope)'
|
|
82
|
+
|
|
83
|
+
/** Where lines come from (stdin; tests pass their own). */
|
|
84
|
+
input: AsyncIterable<string> = console
|
|
85
|
+
|
|
86
|
+
async handle() {
|
|
87
|
+
const scope = await replScope(this.app)
|
|
88
|
+
const names = () => Object.keys(scope).sort().join(', ')
|
|
89
|
+
this.line(`cslug repl: top-level await; in scope: ${names()}. .help, .exit`)
|
|
90
|
+
let buffer = ''
|
|
91
|
+
this.io.write('cslug> ')
|
|
92
|
+
for await (const line of this.input) {
|
|
93
|
+
const command = buffer ? undefined : line.trim()
|
|
94
|
+
if (command === '.exit') break
|
|
95
|
+
if (command === '.help') this.line(`In scope: ${names()}. Other modules: await import(path).`)
|
|
96
|
+
else if (command !== '') {
|
|
97
|
+
buffer = buffer ? `${buffer}\n${line}` : line
|
|
98
|
+
const result = await evaluate(buffer, scope)
|
|
99
|
+
if (result.incomplete) {
|
|
100
|
+
this.io.write('... ')
|
|
101
|
+
continue
|
|
102
|
+
}
|
|
103
|
+
buffer = ''
|
|
104
|
+
if ('error' in result) this.error(result.error instanceof Error ? result.error.message : String(result.error))
|
|
105
|
+
else this.line(Bun.inspect(result.value, { colors: this.io.color }))
|
|
106
|
+
}
|
|
107
|
+
this.io.write('cslug> ')
|
|
108
|
+
}
|
|
109
|
+
return 0
|
|
110
|
+
}
|
|
111
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -6,7 +6,10 @@
|
|
|
6
6
|
* `Command`, `arg` and `flag` live in @cslug/core (so packages can contribute commands) and are re-exported here.
|
|
7
7
|
*/
|
|
8
8
|
export { arg, Command, type CommandClass, ConsoleIO, flag, names } from '@cslug/core'
|
|
9
|
+
export { ADDITIONS, AddCommand } from './commands/add'
|
|
9
10
|
export { generator, STUBS } from './commands/builtin'
|
|
11
|
+
export { DescribeCommand } from './commands/describe'
|
|
12
|
+
export { type Evaluated, evaluate, ReplCommand, replScope } from './commands/repl'
|
|
10
13
|
export { type CslugConfig, defineCslugConfig } from './config'
|
|
11
14
|
export { BufferedIO, commandHelp } from './io'
|
|
12
15
|
export { CliKernel } from './kernel'
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { defineConfig } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
export default defineConfig({
|
|
4
|
+
from: { address: 'hello@example.com' },
|
|
5
|
+
transport: 'log', // 'smtp' (Mailpit in development), 'resend', 'postmark' or 'brevo' in production
|
|
6
|
+
transports: {
|
|
7
|
+
log: {},
|
|
8
|
+
smtp: { host: 'localhost', port: 1025 },
|
|
9
|
+
},
|
|
10
|
+
queue: 'default',
|
|
11
|
+
})
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { defineConfig } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
export default defineConfig({
|
|
4
|
+
default: 'local',
|
|
5
|
+
disks: {
|
|
6
|
+
local: { driver: 'local', root: 'storage/app' },
|
|
7
|
+
// s3: { driver: 's3', bucket: env.S3_BUCKET, endpoint: env.S3_ENDPOINT, region: 'eu-west-3' },
|
|
8
|
+
},
|
|
9
|
+
})
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
@import "tailwindcss";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { defineConfig } from '@cslug/core'
|
|
2
|
+
|
|
3
|
+
/** One entry per sender: `verifySignature('payments')` on its route. */
|
|
4
|
+
export default defineConfig({
|
|
5
|
+
// payments: { secret: env.PAYMENTS_WEBHOOK_SECRET, header: 'X-Signature', format: 't={timestamp},v1={signature}' },
|
|
6
|
+
})
|