@kjanat/dreamcli 3.0.0 → 3.0.1
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/CHANGELOG.md +16 -0
- package/README.md +2 -0
- package/dist/version.mjs +2 -2
- package/package.json +2 -1
- package/skills/cli-creation/SKILL.md +140 -0
- package/skills/cli-creation/agents/openai.yaml +4 -0
- package/skills/cli-creation/assets/templates/multi-command.bun-test.ts.tpl +20 -0
- package/skills/cli-creation/assets/templates/multi-command.test.ts.tpl +20 -0
- package/skills/cli-creation/assets/templates/multi-command.ts.tpl +89 -0
- package/skills/cli-creation/assets/templates/single-command.bun-test.ts.tpl +29 -0
- package/skills/cli-creation/assets/templates/single-command.test.ts.tpl +29 -0
- package/skills/cli-creation/assets/templates/single-command.ts.tpl +47 -0
- package/skills/cli-creation/references/consumer-workflow.md +65 -0
- package/skills/cli-creation/references/pattern-cookbook.md +293 -0
- package/skills/cli-creation/references/runtime-notes.md +29 -0
- package/skills/cli-creation/scripts/scaffold_cli.py +360 -0
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,22 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [3.0.1] - 2026-07-21
|
|
11
|
+
|
|
12
|
+
No library code changed; this release ships agent-facing material that was
|
|
13
|
+
being built but never published.
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- **The `cli-creation` skill now ships in the package** — `skills/` was absent
|
|
18
|
+
from npm's `files` and JSR's `publish.include`, so consumers installing from
|
|
19
|
+
either registry never received it.
|
|
20
|
+
- **Documentation lookup paths in the `cli-creation` skill** — `deno doc`
|
|
21
|
+
against JSR (works whether the consumer installed from npm or JSR, including
|
|
22
|
+
subpaths, `--json`, and `--filter`), plus the site's `llms.txt`,
|
|
23
|
+
`llms-full.txt`, and `/raw/` markdown endpoints, so API shapes are read from
|
|
24
|
+
the published package rather than recalled.
|
|
25
|
+
|
|
10
26
|
## [3.0.0] - 2026-07-21
|
|
11
27
|
|
|
12
28
|
The stable 3.0.0 release. It ships the code of 3.0.0-rc.20 plus the fix and
|
package/README.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[][npm]
|
|
4
4
|
[][jsr]
|
|
5
|
+
[][socket]
|
|
5
6
|
|
|
6
7
|
Schema-first, fully typed TypeScript CLI framework. Zero runtime dependencies.
|
|
7
8
|
|
|
@@ -584,3 +585,4 @@ handles the divergent edges (argv, env, filesystem, TTY detection, exit behavior
|
|
|
584
585
|
[LICENSE]: https://github.com/kjanat/dreamcli/blob/master/LICENSE
|
|
585
586
|
[npm]: https://npm.im/@kjanat/dreamcli
|
|
586
587
|
[jsr]: https://jsr.io/@kjanat/dreamcli
|
|
588
|
+
[socket]: https://socket.dev/npm/package/@kjanat/dreamcli
|
package/dist/version.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
//#region src/version.ts
|
|
2
2
|
/** Package version (e.g. `"0.9.1"`). `"dev"` when running unbundled. */
|
|
3
|
-
const DREAMCLI_VERSION = "3.0.
|
|
3
|
+
const DREAMCLI_VERSION = "3.0.1";
|
|
4
4
|
/** Git short SHA (e.g. `"f9b5f1a"`). `"dev"` when running unbundled. */
|
|
5
|
-
const DREAMCLI_REVISION = "
|
|
5
|
+
const DREAMCLI_REVISION = "7379236";
|
|
6
6
|
//#endregion
|
|
7
7
|
export { DREAMCLI_REVISION, DREAMCLI_VERSION };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kjanat/dreamcli",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.1",
|
|
4
4
|
"description": "Schema-first, fully typed TypeScript CLI framework",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dreamcli",
|
|
@@ -59,6 +59,7 @@
|
|
|
59
59
|
"dist",
|
|
60
60
|
"dreamcli.schema.json",
|
|
61
61
|
"examples",
|
|
62
|
+
"skills",
|
|
62
63
|
"!**/.cache",
|
|
63
64
|
"!**/AGENTS.md"
|
|
64
65
|
],
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: cli-creation
|
|
3
|
+
description: Build consumer-facing DreamCLI CLIs from scratch with Bun-first workflows and typed patterns. Use when asked to scaffold or implement a new @kjanat/dreamcli command-line app, add commands/flags/args/prompts/output/testing, or create starter files/tests for DreamCLI users.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# CLI Creation
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
Create runnable DreamCLI starter CLIs and extend them with typed command
|
|
11
|
+
patterns. This skill covers user-facing app code built **on** DreamCLI, not
|
|
12
|
+
DreamCLI framework internals.
|
|
13
|
+
|
|
14
|
+
Targets DreamCLI 3.x. Version 3 removed the DSL, made the default command the
|
|
15
|
+
root surface, and added a large typed-flag surface; snippets below assume it.
|
|
16
|
+
|
|
17
|
+
## Quick Start
|
|
18
|
+
|
|
19
|
+
1. Choose a starter mode:
|
|
20
|
+
- `single`: one root command (`cli(name).default(command)`).
|
|
21
|
+
- `multi`: grouped command surface (`group('...').command(...)`).
|
|
22
|
+
2. Generate starter files:
|
|
23
|
+
- `python scripts/scaffold_cli.py --name mycli --mode single --out .`
|
|
24
|
+
- Tests are generated by default; add `--no-test` only when explicitly requested.
|
|
25
|
+
- Test template is auto-detected: Bun without Vitest uses `bun:test`; otherwise Vitest.
|
|
26
|
+
3. Run and validate generated files:
|
|
27
|
+
- Use the printed path from the scaffolder output, for example `bun ./mycli.ts --help`.
|
|
28
|
+
- Run the generated test unless `--no-test` was used.
|
|
29
|
+
4. Extend behavior with references:
|
|
30
|
+
- `references/pattern-cookbook.md` — copy-ready, type-checked snippets.
|
|
31
|
+
- `references/consumer-workflow.md` — request to validated CLI.
|
|
32
|
+
- `references/runtime-notes.md` — Bun/Node/Deno execution.
|
|
33
|
+
|
|
34
|
+
## Looking Things Up
|
|
35
|
+
|
|
36
|
+
Prefer these over recalling API shapes from memory; they reflect the installed
|
|
37
|
+
or published version rather than training data.
|
|
38
|
+
|
|
39
|
+
**The API, offline-ish, no repo needed.** If `deno` is on the system this works
|
|
40
|
+
regardless of whether the project installed from npm or JSR:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
deno doc jsr:@kjanat/dreamcli 2>/dev/null # full public API (~4k lines)
|
|
44
|
+
deno doc jsr:@kjanat/dreamcli/testkit 2>/dev/null # subpath: testkit, runtime, schema, version
|
|
45
|
+
deno doc --json jsr:@kjanat/dreamcli 2>/dev/null # machine-readable, for scripted lookups
|
|
46
|
+
deno doc --filter=CLIBuilder jsr:@kjanat/dreamcli 2>/dev/null # one symbol
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`2>/dev/null` matters: deno writes download and type-check progress to stderr,
|
|
50
|
+
which otherwise swamps the documentation output.
|
|
51
|
+
|
|
52
|
+
Pin a version with `jsr:@kjanat/dreamcli@3.0.0` when the project is not on
|
|
53
|
+
latest. `--filter` takes a declaration name; it prints nothing for a name that
|
|
54
|
+
does not exist, which is itself a useful signal.
|
|
55
|
+
|
|
56
|
+
**The docs site, as markdown.** Every page is authored markdown served under
|
|
57
|
+
`/raw/`, and any page URL returns markdown under content negotiation:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
curl -s https://dreamcli.kjanat.dev/llms.txt # index of every page, one line each
|
|
61
|
+
curl -s https://dreamcli.kjanat.dev/llms-full.txt # every page concatenated (~250 kB)
|
|
62
|
+
curl -s https://dreamcli.kjanat.dev/raw/guide/flags # one page, authored markdown
|
|
63
|
+
curl -sH 'Accept: text/markdown' https://dreamcli.kjanat.dev/guide/flags
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Start from `llms.txt` to find the right page, then fetch that page rather than
|
|
67
|
+
pulling `llms-full.txt` into context.
|
|
68
|
+
|
|
69
|
+
## Grounding Sources
|
|
70
|
+
|
|
71
|
+
Paths are relative to the dreamcli repository root.
|
|
72
|
+
|
|
73
|
+
- `examples/basic.ts` — single-command defaults.
|
|
74
|
+
- `examples/multi-command.ts` — grouped-command defaults.
|
|
75
|
+
- `examples/testing.ts` — `runCommand()` patterns.
|
|
76
|
+
- `examples/flag-types.ts` — the v3 typed-flag family.
|
|
77
|
+
- `examples/parser-control.ts` — negation, duplicates, spelling parity.
|
|
78
|
+
- `examples/output-extras.ts` — colors, hyperlinks, `setExitCode`.
|
|
79
|
+
- `examples/standard-schema.ts` — Standard Schema validation.
|
|
80
|
+
- `examples/help-config.ts` — help themes, flag order, routable default.
|
|
81
|
+
- `examples/gh/` — a full multi-command app used as a walkthrough.
|
|
82
|
+
- `docs/guide/getting-started.md` — baseline consumer narrative.
|
|
83
|
+
- `docs/guide/walkthrough.md` — end-to-end CLI composition.
|
|
84
|
+
- `docs/guide/upgrading-v3.md` — what changed from 2.x, for migrations.
|
|
85
|
+
|
|
86
|
+
## Workflow Decision Tree
|
|
87
|
+
|
|
88
|
+
- Simple one-command utility → `--mode single`.
|
|
89
|
+
- Nested command groups (git/gh style) → `--mode multi`.
|
|
90
|
+
- Tests wanted from the start → do nothing, they are scaffolded by default.
|
|
91
|
+
- Tests explicitly unwanted → add `--no-test`.
|
|
92
|
+
- npm/tsx or Deno instructions → keep generated code unchanged and give the
|
|
93
|
+
runtime alternatives from `references/runtime-notes.md`.
|
|
94
|
+
- Migrating an existing 2.x CLI → read `docs/guide/upgrading-v3.md` first; the
|
|
95
|
+
default-command and `finite` changes silently alter behavior.
|
|
96
|
+
|
|
97
|
+
## Extend the Starter
|
|
98
|
+
|
|
99
|
+
**Values.** Add typed args with `arg.string()`, `arg.number()`, `arg.enum(...)`,
|
|
100
|
+
`arg.custom(...)`; `.variadic()` for repeated positionals. Prefer a purpose-built
|
|
101
|
+
flag kind over `flag.string()` plus parsing: `flag.url()`, `flag.path()`,
|
|
102
|
+
`flag.date()`, `flag.duration()`, `flag.bytes()`, `flag.count()`,
|
|
103
|
+
`flag.keyValue()`. Express validation declaratively with constraints
|
|
104
|
+
(`{ int, min, max }`, `{ nonEmpty, pattern }`) or a Standard Schema passed to
|
|
105
|
+
`flag.custom()`, not with hand-written checks in the action.
|
|
106
|
+
|
|
107
|
+
**Sources.** Declare `.env()`, `.config()`, `.prompt()`, `.default()` on the flag
|
|
108
|
+
and let resolution order (argv, env, config, prompt, default) do the work.
|
|
109
|
+
|
|
110
|
+
**Cross-flag rules.** Put them in `.derive()`, which runs after resolution and
|
|
111
|
+
before the action, and return derived state to widen `ctx`.
|
|
112
|
+
|
|
113
|
+
**Output.** `out.log()` for results, `out.status()` for progress notes (stderr,
|
|
114
|
+
suppressed by `--quiet`), `out.table()` for lists, `out.json()` behind
|
|
115
|
+
`out.jsonMode`, `out.color`/`osc8()` for styling, `out.setExitCode()` when a
|
|
116
|
+
command must report normally but exit non-zero.
|
|
117
|
+
|
|
118
|
+
**Testing.** `runCommand()` from `@kjanat/dreamcli/testkit`, with `answers` for
|
|
119
|
+
prompts and `stat`/`mkdir` when `flag.path()` checks must run. Assert output
|
|
120
|
+
including trailing newlines.
|
|
121
|
+
|
|
122
|
+
## Resource Map
|
|
123
|
+
|
|
124
|
+
- `scripts/scaffold_cli.py` — generate Bun-first starter files and tests.
|
|
125
|
+
- `assets/templates/*.tpl` — source templates used by the scaffolder.
|
|
126
|
+
- `references/pattern-cookbook.md` — snippets by topic; all type-checked.
|
|
127
|
+
- `references/consumer-workflow.md` — end-to-end flow from request to validation.
|
|
128
|
+
- `references/runtime-notes.md` — runtime and package-manager execution guidance.
|
|
129
|
+
|
|
130
|
+
## Guardrails
|
|
131
|
+
|
|
132
|
+
- Do not modify DreamCLI core internals for consumer-app requests.
|
|
133
|
+
- Keep generated imports on `@kjanat/dreamcli` and `@kjanat/dreamcli/testkit`;
|
|
134
|
+
never reach into `#internals/*` or `dist/`.
|
|
135
|
+
- Preserve the typed resolution flow: argv, env, config, prompt, default.
|
|
136
|
+
- Keep stdout machine-clean: progress and status go to stderr via `out.status()`,
|
|
137
|
+
never interleaved with `out.json()`.
|
|
138
|
+
- `.default(cmd)` is the root surface and is not routable by name; add
|
|
139
|
+
`{ route: true }` when a user expects `mycli <name>` to work too.
|
|
140
|
+
- Prefer Bun commands first; include npm/tsx and Deno alternatives when asked.
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { partyStart } from '__ENTRY_FILE__';
|
|
2
|
+
import { runCommand } from '@kjanat/dreamcli/testkit';
|
|
3
|
+
import { describe, expect, it } from 'bun:test';
|
|
4
|
+
|
|
5
|
+
describe('party start command', () => {
|
|
6
|
+
it('applies sparkle middleware when --sparkle is set', async () => {
|
|
7
|
+
const result = await runCommand(partyStart, ['--theme', 'midnight', '--sparkle']);
|
|
8
|
+
|
|
9
|
+
expect(result.exitCode).toBe(0);
|
|
10
|
+
expect(result.stdout).toEqual(['✨ Party started with midnight theme! ✨\n']);
|
|
11
|
+
expect(result.stderr).toEqual([]);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it('renders help text', async () => {
|
|
15
|
+
const result = await runCommand(partyStart, ['--help']);
|
|
16
|
+
|
|
17
|
+
expect(result.exitCode).toBe(0);
|
|
18
|
+
expect(result.stdout.join('')).toContain('Start the pony party');
|
|
19
|
+
});
|
|
20
|
+
});
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { partyStart } from '__ENTRY_FILE__';
|
|
2
|
+
import { runCommand } from '@kjanat/dreamcli/testkit';
|
|
3
|
+
import { describe, expect, it } from 'vitest';
|
|
4
|
+
|
|
5
|
+
describe('party start command', () => {
|
|
6
|
+
it('applies sparkle middleware when --sparkle is set', async () => {
|
|
7
|
+
const result = await runCommand(partyStart, ['--theme', 'midnight', '--sparkle']);
|
|
8
|
+
|
|
9
|
+
expect(result.exitCode).toBe(0);
|
|
10
|
+
expect(result.stdout).toEqual(['✨ Party started with midnight theme! ✨\n']);
|
|
11
|
+
expect(result.stderr).toEqual([]);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it('renders help text', async () => {
|
|
15
|
+
const result = await runCommand(partyStart, ['--help']);
|
|
16
|
+
|
|
17
|
+
expect(result.exitCode).toBe(0);
|
|
18
|
+
expect(result.stdout.join('')).toContain('Start the pony party');
|
|
19
|
+
});
|
|
20
|
+
});
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* __CLI_NAME__ - multi-command DreamCLI starter (pony party edition).
|
|
4
|
+
*
|
|
5
|
+
* Bun:
|
|
6
|
+
* bun __CLI_NAME__.ts snack cupcake --count 3
|
|
7
|
+
* bun __CLI_NAME__.ts story "rainbow heist" --mood legendary --sparkle
|
|
8
|
+
* bun __CLI_NAME__.ts party start --theme midnight
|
|
9
|
+
* bun __CLI_NAME__.ts --help
|
|
10
|
+
*
|
|
11
|
+
* npm/tsx:
|
|
12
|
+
* npx tsx __CLI_NAME__.ts party playlist --genre chaos
|
|
13
|
+
*
|
|
14
|
+
* Deno:
|
|
15
|
+
* deno run -A __CLI_NAME__.ts snack donut --count 2
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { arg, cli, command, flag, group, middleware } from '@kjanat/dreamcli';
|
|
19
|
+
|
|
20
|
+
const sparkle = middleware<{ sparkle: (message: string) => string }>(async ({ flags, next }) => {
|
|
21
|
+
const sparkleEnabled = flags.sparkle === true;
|
|
22
|
+
return next({
|
|
23
|
+
sparkle: (message: string) => (sparkleEnabled ? `✨ ${message} ✨` : message),
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const sparkleFlag = () => flag.boolean().alias('s').env('SPARKLE').describe('Add extra sparkle');
|
|
28
|
+
|
|
29
|
+
export const snack = command('snack')
|
|
30
|
+
.description('Serve snacks to the crew')
|
|
31
|
+
.arg('treat', arg.string().default('cupcake').describe('Snack to serve'))
|
|
32
|
+
.flag('count', flag.number().default(1).alias('c').describe('How many snacks'))
|
|
33
|
+
.flag('sparkle', sparkleFlag())
|
|
34
|
+
.middleware(sparkle)
|
|
35
|
+
.action(({ args, flags, ctx, out }) => {
|
|
36
|
+
const { treat } = args;
|
|
37
|
+
const { count } = flags;
|
|
38
|
+
out.log(ctx.sparkle(`Serving ${count} ${treat}(s)!`));
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
export const story = command('story')
|
|
42
|
+
.description('Tell a dramatic story')
|
|
43
|
+
.arg('topic', arg.string().default('the great cupcake rescue').describe('Story topic'))
|
|
44
|
+
.flag('mood', flag.enum(['calm', 'chaos', 'legendary'])
|
|
45
|
+
.prompt({ kind: 'select', message: 'Set the mood!' })
|
|
46
|
+
.default('calm').describe('Story mood'))
|
|
47
|
+
.flag('sparkle', sparkleFlag())
|
|
48
|
+
.middleware(sparkle)
|
|
49
|
+
.action(({ args, flags, ctx, out }) => {
|
|
50
|
+
const { topic } = args;
|
|
51
|
+
const { mood } = flags;
|
|
52
|
+
out.log(ctx.sparkle(`Story time: ${topic} (${mood})`));
|
|
53
|
+
out.log(ctx.sparkle('Dramatic glitter intensifies'));
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
export const partyStart = command('start')
|
|
57
|
+
.description('Start the pony party')
|
|
58
|
+
.flag('theme', flag.enum(['rainbow', 'midnight', 'glitter']).default('rainbow').describe('Party theme'))
|
|
59
|
+
.flag('sparkle', sparkleFlag())
|
|
60
|
+
.middleware(sparkle)
|
|
61
|
+
.action(({ flags, ctx, out }) => {
|
|
62
|
+
out.log(ctx.sparkle(`Party started with ${flags.theme} theme!`));
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
export const partyPlaylist = command('playlist')
|
|
66
|
+
.description('Pick a party playlist vibe')
|
|
67
|
+
.flag('genre', flag.enum(['pop', 'ballad', 'chaos']).default('pop').describe('Playlist genre'))
|
|
68
|
+
.flag('sparkle', sparkleFlag())
|
|
69
|
+
.middleware(sparkle)
|
|
70
|
+
.action(({ flags, ctx, out }) => {
|
|
71
|
+
out.log(ctx.sparkle(`Now playing: ${flags.genre}`));
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
export const party = group('party')
|
|
75
|
+
.description('Party controls')
|
|
76
|
+
.command(partyStart)
|
|
77
|
+
.command(partyPlaylist);
|
|
78
|
+
|
|
79
|
+
export const app = cli('__CLI_NAME__')
|
|
80
|
+
.version('0.1.0')
|
|
81
|
+
.description('Fun DreamCLI starter app')
|
|
82
|
+
.command(snack)
|
|
83
|
+
.command(story)
|
|
84
|
+
.command(party)
|
|
85
|
+
.completions();
|
|
86
|
+
|
|
87
|
+
if (import.meta.main) {
|
|
88
|
+
app.run();
|
|
89
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { hello } from '__ENTRY_FILE__';
|
|
2
|
+
import { runCommand } from '@kjanat/dreamcli/testkit';
|
|
3
|
+
import { describe, expect, it } from 'bun:test';
|
|
4
|
+
|
|
5
|
+
describe('hello command', () => {
|
|
6
|
+
it('prints sparkly greeting when --sparkle is set', async () => {
|
|
7
|
+
const result = await runCommand(hello, ['Twilight', '--sparkle', '--times', '2']);
|
|
8
|
+
|
|
9
|
+
expect(result.exitCode).toBe(0);
|
|
10
|
+
expect(result.stdout).toEqual(['✨ Hello, Twilight! ✨\n', '✨ Hello, Twilight! ✨\n']);
|
|
11
|
+
// out.status() writes to stderr so stdout stays pipe-clean.
|
|
12
|
+
expect(result.stderr).toEqual(['Greeted Twilight 2 time(s)\n']);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it('suppresses status output with --quiet', async () => {
|
|
16
|
+
const result = await runCommand(hello, ['Twilight', '--quiet']);
|
|
17
|
+
|
|
18
|
+
expect(result.exitCode).toBe(0);
|
|
19
|
+
expect(result.stdout).toEqual(['Hello, Twilight!\n']);
|
|
20
|
+
expect(result.stderr).toEqual([]);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('renders help text', async () => {
|
|
24
|
+
const result = await runCommand(hello, ['--help']);
|
|
25
|
+
|
|
26
|
+
expect(result.exitCode).toBe(0);
|
|
27
|
+
expect(result.stdout.join('')).toContain('Say hello with optional sparkle');
|
|
28
|
+
});
|
|
29
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { hello } from '__ENTRY_FILE__';
|
|
2
|
+
import { runCommand } from '@kjanat/dreamcli/testkit';
|
|
3
|
+
import { describe, expect, it } from 'vitest';
|
|
4
|
+
|
|
5
|
+
describe('hello command', () => {
|
|
6
|
+
it('prints sparkly greeting when --sparkle is set', async () => {
|
|
7
|
+
const result = await runCommand(hello, ['Twilight', '--sparkle', '--times', '2']);
|
|
8
|
+
|
|
9
|
+
expect(result.exitCode).toBe(0);
|
|
10
|
+
expect(result.stdout).toEqual(['✨ Hello, Twilight! ✨\n', '✨ Hello, Twilight! ✨\n']);
|
|
11
|
+
// out.status() writes to stderr so stdout stays pipe-clean.
|
|
12
|
+
expect(result.stderr).toEqual(['Greeted Twilight 2 time(s)\n']);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it('suppresses status output with --quiet', async () => {
|
|
16
|
+
const result = await runCommand(hello, ['Twilight', '--quiet']);
|
|
17
|
+
|
|
18
|
+
expect(result.exitCode).toBe(0);
|
|
19
|
+
expect(result.stdout).toEqual(['Hello, Twilight!\n']);
|
|
20
|
+
expect(result.stderr).toEqual([]);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('renders help text', async () => {
|
|
24
|
+
const result = await runCommand(hello, ['--help']);
|
|
25
|
+
|
|
26
|
+
expect(result.exitCode).toBe(0);
|
|
27
|
+
expect(result.stdout.join('')).toContain('Say hello with optional sparkle');
|
|
28
|
+
});
|
|
29
|
+
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* __CLI_NAME__ - hello-world DreamCLI starter.
|
|
4
|
+
*
|
|
5
|
+
* Bun:
|
|
6
|
+
* bun __CLI_NAME__.ts
|
|
7
|
+
* bun __CLI_NAME__.ts Twilight --sparkle --times 2
|
|
8
|
+
* bun __CLI_NAME__.ts --help
|
|
9
|
+
*
|
|
10
|
+
* npm/tsx:
|
|
11
|
+
* npx tsx __CLI_NAME__.ts Twilight --sparkle --times 2
|
|
12
|
+
*
|
|
13
|
+
* Deno:
|
|
14
|
+
* deno run -A __CLI_NAME__.ts Twilight --sparkle --times 2
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { arg, cli, command, flag, middleware } from '@kjanat/dreamcli';
|
|
18
|
+
|
|
19
|
+
const sparkle = middleware<{ sparkle: (message: string) => string }>(async ({ flags, next }) => {
|
|
20
|
+
const sparkleEnabled = flags.sparkle === true;
|
|
21
|
+
return next({
|
|
22
|
+
sparkle: (message: string) => (sparkleEnabled ? `✨ ${message} ✨` : message),
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export const hello = command('hello')
|
|
27
|
+
.description('Say hello with optional sparkle')
|
|
28
|
+
.example(({ name }) => `${name} Twilight --sparkle --times 2`, 'Sparkly double greeting')
|
|
29
|
+
.arg('name', arg.string().default('World').describe('Who to greet'))
|
|
30
|
+
.flag('sparkle', flag.boolean().alias('s').env('SPARKLE').describe('Add sparkles'))
|
|
31
|
+
// Constraints are enforced at every source, so the action needs no clamping.
|
|
32
|
+
.flag('times', flag.number({ int: true, min: 0, max: 100 }).default(1).alias('n').describe('Repeat count'))
|
|
33
|
+
.middleware(sparkle)
|
|
34
|
+
.action(({ args, flags, ctx, out }) => {
|
|
35
|
+
for (let i = 0; i < flags.times; i++) {
|
|
36
|
+
out.log(ctx.sparkle(`Hello, ${args.name}!`));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// stderr, and silenced by --quiet: keeps stdout pipe-clean.
|
|
40
|
+
out.status(`Greeted ${args.name} ${flags.times} time(s)`);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
export const app = cli('__CLI_NAME__').default(hello);
|
|
44
|
+
|
|
45
|
+
if (import.meta.main) {
|
|
46
|
+
app.run();
|
|
47
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Consumer Workflow
|
|
2
|
+
|
|
3
|
+
## Goal
|
|
4
|
+
|
|
5
|
+
Build a consumer-facing CLI app with DreamCLI 3.x, starting from a working
|
|
6
|
+
template and ending with validated behavior.
|
|
7
|
+
|
|
8
|
+
## Inputs to confirm
|
|
9
|
+
|
|
10
|
+
- CLI name (`--name`).
|
|
11
|
+
- Surface shape (`single` or `multi`).
|
|
12
|
+
- Whether tests should be skipped (`--no-test`).
|
|
13
|
+
- Runtime the user runs on (Bun, npm/tsx, Deno).
|
|
14
|
+
- Whether the CLI needs machine-readable output, config files, or prompts —
|
|
15
|
+
each adds declarations to the schema rather than code to the action.
|
|
16
|
+
|
|
17
|
+
## Implementation flow
|
|
18
|
+
|
|
19
|
+
1. Scaffold starter files.
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
python scripts/scaffold_cli.py --name mycli --mode single --out .
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The scaffolder detects the package manager and Vitest usage to choose either
|
|
26
|
+
a `bun:test` or Vitest starter test template.
|
|
27
|
+
|
|
28
|
+
2. Shape the command surface.
|
|
29
|
+
|
|
30
|
+
- `.description(...)` on every command; it is what `--help` shows.
|
|
31
|
+
- Function-form `.example()` so examples print the real program name.
|
|
32
|
+
- Typed `.arg(...)` and `.flag(...)` declarations before any logic.
|
|
33
|
+
- A single root command belongs in `.default(cmd)`; add `{ route: true }`
|
|
34
|
+
only if `mycli <name>` should also work.
|
|
35
|
+
|
|
36
|
+
3. Declare where values come from.
|
|
37
|
+
|
|
38
|
+
- `.env('...')`, `.config('...')`, `.prompt(...)`, `.default(...)`.
|
|
39
|
+
- Constraints (`{ int: true, min: 1 }`, `{ nonEmpty: true }`) or a Standard
|
|
40
|
+
Schema in `flag.custom(...)` instead of validation code in the action.
|
|
41
|
+
- Cross-flag rules go in `.derive()`, not the action.
|
|
42
|
+
|
|
43
|
+
4. Choose output behavior deliberately.
|
|
44
|
+
|
|
45
|
+
- `out.log()` for the result a user pipes.
|
|
46
|
+
- `out.status()` for progress notes — stderr, silenced by `--quiet`.
|
|
47
|
+
- `out.table()` for list-shaped data.
|
|
48
|
+
- `out.json(data)` behind `if (out.jsonMode)`, never mixed with prose.
|
|
49
|
+
- `out.setExitCode(code)` for check/status commands that must still print.
|
|
50
|
+
|
|
51
|
+
5. Validate behavior.
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
bun ./mycli.ts --help
|
|
55
|
+
bun ./mycli.ts --json | jq . # stdout must parse
|
|
56
|
+
bun test ./mycli.test.ts
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Done criteria
|
|
60
|
+
|
|
61
|
+
- `--help` renders expected command, flag, and example text.
|
|
62
|
+
- Happy-path execution exits `0`; failure paths exit non-zero with a `suggest`.
|
|
63
|
+
- `--json` stdout parses on its own — no human text, no progress lines.
|
|
64
|
+
- `--quiet` silences status output without hiding warnings or errors.
|
|
65
|
+
- Generated or custom tests pass, including trailing-newline assertions.
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
# Pattern Cookbook
|
|
2
|
+
|
|
3
|
+
Copy-ready snippets for DreamCLI 3.x. Every snippet type-checks against the
|
|
4
|
+
published types.
|
|
5
|
+
|
|
6
|
+
## Values
|
|
7
|
+
|
|
8
|
+
### Flag precedence chain
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
flag
|
|
12
|
+
.enum(['us', 'eu', 'ap'])
|
|
13
|
+
.env('DEPLOY_REGION')
|
|
14
|
+
.config('deploy.region')
|
|
15
|
+
.prompt({ kind: 'select', message: 'Which region?' })
|
|
16
|
+
.default('us');
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Resolution order is fixed: CLI argv, env, config, prompt, default. Declare the
|
|
20
|
+
sources a value may come from; never merge them by hand in the action.
|
|
21
|
+
|
|
22
|
+
### Rich flag types
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
flag.url({ protocols: ['https'] }); // URL
|
|
26
|
+
flag.path({ type: 'directory', create: true }); // string, mkdir -p when missing
|
|
27
|
+
flag.date({ min: new Date('2020-01-01') }); // Date, strict ISO-8601
|
|
28
|
+
flag.duration(); // number (ms) — '30s', '1h30m', '250ms'
|
|
29
|
+
flag.bytes(); // number — '512mb', '1.5gb'
|
|
30
|
+
flag.count().alias('v'); // number — -vvv is 3
|
|
31
|
+
flag.keyValue(); // Record<string, string> — repeated KEY=VALUE
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Prefer these over `flag.string()` plus hand-rolled parsing: they validate at
|
|
35
|
+
every source, feed help placeholders, and land in the exported JSON Schema.
|
|
36
|
+
|
|
37
|
+
`flag.path()` checks run through the runtime adapter after resolution. In
|
|
38
|
+
process-free execution pass `stat` (and `mkdir` for `create`) via run options,
|
|
39
|
+
or the checks are skipped.
|
|
40
|
+
|
|
41
|
+
### Constraints instead of hand-written validation
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
flag.number({ int: true, min: 1, max: 65535 }); // port
|
|
45
|
+
flag.string({ nonEmpty: true, pattern: /^[a-z][a-z0-9-]*$/ }); // slug
|
|
46
|
+
flag.number().finite(false); // opt back into Infinity
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Constraints are enforced on CLI parse (`INVALID_VALUE`) and on env/config/prompt
|
|
50
|
+
resolution (`CONSTRAINT_VIOLATED`), both exit code 2. `finite` defaults to
|
|
51
|
+
`true`, so `Infinity` is rejected unless you opt out.
|
|
52
|
+
|
|
53
|
+
### Standard Schema validation
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
import { z } from 'zod';
|
|
57
|
+
|
|
58
|
+
flag.custom(z.coerce.number().int().positive());
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Any Standard Schema v1 validator works (Zod, Valibot, ArkType) with the output
|
|
62
|
+
type inferred. Validation runs after source resolution, so every source is
|
|
63
|
+
checked identically; array flags validate per element.
|
|
64
|
+
|
|
65
|
+
### Array flags
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
flag
|
|
69
|
+
.array(flag.enum(['us', 'eu', 'ap']))
|
|
70
|
+
.separator(',')
|
|
71
|
+
.unique();
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`--region us,eu --region ap` and repetition both work. Put flag-level modifiers
|
|
75
|
+
(`.env()`, `.default()`, …) on the array, never on the element — that is a
|
|
76
|
+
compile error.
|
|
77
|
+
|
|
78
|
+
## Parser behavior
|
|
79
|
+
|
|
80
|
+
### Negatable booleans
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
flag.boolean().default(true).negatable(); // --sandbox / --no-sandbox
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
One logical flag with two spellings; help renders `--[no-]sandbox`. The negated
|
|
87
|
+
spelling is presence-only (`--no-sandbox=false` errors).
|
|
88
|
+
|
|
89
|
+
### Duplicate policy
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
flag.enum(['session', 'worktree']).duplicates('error');
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Config-style flags should reject repeats rather than silently taking the last
|
|
96
|
+
value. `'error'` throws `ParseError` code `DUPLICATE_FLAG`; `'first'` keeps the
|
|
97
|
+
first. Counted per logical flag, including aliases and negated spellings.
|
|
98
|
+
|
|
99
|
+
### Cross-flag rules
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
command('serve')
|
|
103
|
+
.flag('port', flag.number({ int: true }))
|
|
104
|
+
.flag('socket', flag.string())
|
|
105
|
+
.derive(({ flags }) => {
|
|
106
|
+
if (flags.port !== undefined && flags.socket !== undefined) {
|
|
107
|
+
throw new CLIError('--port and --socket are mutually exclusive', {
|
|
108
|
+
code: 'INVALID_FLAG_COMBINATION',
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
return { mode: flags.socket !== undefined ? 'socket' : 'tcp' } as const;
|
|
112
|
+
})
|
|
113
|
+
.action(({ ctx }) => {
|
|
114
|
+
ctx.mode; // typed, available to the action
|
|
115
|
+
});
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
`.derive()` runs after resolution and before the action. It is the home for
|
|
119
|
+
rules DreamCLI cannot express declaratively, and its return value widens `ctx`.
|
|
120
|
+
|
|
121
|
+
## Output
|
|
122
|
+
|
|
123
|
+
### Channels
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
.action(({ out }) => {
|
|
127
|
+
out.log('primary result'); // stdout (stderr in --json)
|
|
128
|
+
out.status('working on it'); // stderr, hidden by --quiet
|
|
129
|
+
out.warn('deprecated flag used');// stderr, always shown
|
|
130
|
+
out.error('could not reach api');// stderr, always shown
|
|
131
|
+
});
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Keep stdout free of progress chatter so pipes stay clean. `--quiet`/`-q` is a
|
|
135
|
+
global flag; it silences `status` and `info` but never warnings or errors.
|
|
136
|
+
|
|
137
|
+
### JSON mode branching
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
.action(({ out }) => {
|
|
141
|
+
const data = { service: 'api', healthy: true };
|
|
142
|
+
|
|
143
|
+
if (out.jsonMode) {
|
|
144
|
+
out.json(data);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
out.log('Service api is healthy');
|
|
149
|
+
});
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Never mix human text into stdout in the same branch as `out.json()`.
|
|
153
|
+
|
|
154
|
+
### Tables
|
|
155
|
+
|
|
156
|
+
```ts
|
|
157
|
+
out.table(rows, [
|
|
158
|
+
{ key: 'name', header: 'Service' },
|
|
159
|
+
{ key: 'status', header: 'Status' },
|
|
160
|
+
]);
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Text table for humans, array for `--json`. Columns are optional
|
|
164
|
+
(`out.table(rows)` infers them); pass `{ format: 'text', stream: 'stderr' }` to
|
|
165
|
+
force a human table alongside JSON stdout.
|
|
166
|
+
|
|
167
|
+
### Colors and hyperlinks
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
.action(({ out }) => {
|
|
171
|
+
out.log(out.color.green('✔ done'));
|
|
172
|
+
if (out.isHyperlinkSupported) out.log(osc8('https://example.com', 'docs'));
|
|
173
|
+
});
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Every `out.color` formatter is an identity function when color is off (piped,
|
|
177
|
+
`NO_COLOR`, `--json`), so no branching is needed. Hyperlinks garble piped
|
|
178
|
+
output, so gate them on `out.isHyperlinkSupported`.
|
|
179
|
+
|
|
180
|
+
### Exit code without an error
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
.action(({ out }) => {
|
|
184
|
+
out.log('3 of 5 checks failed');
|
|
185
|
+
out.setExitCode(1);
|
|
186
|
+
});
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
For check/status commands: keeps normal output, avoids an error payload in
|
|
190
|
+
`--json`, still signals scripts.
|
|
191
|
+
|
|
192
|
+
### Structured errors
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
throw new CLIError('Deployment target not found', {
|
|
196
|
+
code: 'NOT_FOUND',
|
|
197
|
+
exitCode: 1,
|
|
198
|
+
suggest: 'Run: mycli deploy --help',
|
|
199
|
+
details: { requested: name },
|
|
200
|
+
});
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Serializes cleanly in `--json` mode and prints a suggestion line otherwise.
|
|
204
|
+
|
|
205
|
+
## Surface
|
|
206
|
+
|
|
207
|
+
### Help configuration
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
cli('mycli').help({
|
|
211
|
+
flagOrder: 'declaration', // or a sortFlags comparator
|
|
212
|
+
theme: (c) => ({ sectionTitle: c.magenta }),
|
|
213
|
+
footer: false,
|
|
214
|
+
});
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
The theme factory receives the gated palette and never runs when color is off,
|
|
218
|
+
so a custom theme cannot leak escapes into piped output.
|
|
219
|
+
|
|
220
|
+
### Examples that know the program name
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
command('deploy').example(({ name }) => `${name} deploy production --force`, 'Force a deploy');
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
The builder form resolves at render time, so examples stay truthful under
|
|
227
|
+
symlinks, `inheritName`, and `npx` versus a global install.
|
|
228
|
+
|
|
229
|
+
### Default command
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
cli('mycli').default(serve); // root surface only: `mycli --port 80`
|
|
233
|
+
cli('mycli').default(serve, { route: true }); // also `mycli serve`
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
A plain `.default()` is the root surface and is not routable by name; the token
|
|
237
|
+
would be read as its first positional.
|
|
238
|
+
|
|
239
|
+
### Completions
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
cli('mycli').completions(); // mycli completions <shell>
|
|
243
|
+
cli('mycli').completions({ as: 'flag' }); // mycli --completions (shell auto-detected)
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
### Config discovery
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
cli('mycli')
|
|
250
|
+
.config('mycli')
|
|
251
|
+
.configLoader(configFormat(['yaml', 'yml'], parseYaml));
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
Discovery probes project scope (cwd and every ancestor: `.mycli.json`,
|
|
255
|
+
`mycli.config.json`, `.config/mycli.json`), then user scope (XDG/AppData, plus
|
|
256
|
+
`~/Library/Application Support` on macOS), then `/etc`. First match wins; files
|
|
257
|
+
are never merged. `--config <path>` overrides everything.
|
|
258
|
+
|
|
259
|
+
## Testing
|
|
260
|
+
|
|
261
|
+
### In-process command test
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
import { runCommand } from '@kjanat/dreamcli/testkit';
|
|
265
|
+
|
|
266
|
+
const result = await runCommand(deploy, ['production', '--force']);
|
|
267
|
+
expect(result.exitCode).toBe(0);
|
|
268
|
+
expect(result.stdout).toEqual(['Deploying production to us\n']);
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
Prefer `runCommand()` over subprocess tests: faster, deterministic, and it
|
|
272
|
+
captures stdout/stderr as arrays of written chunks — assert trailing newlines.
|
|
273
|
+
|
|
274
|
+
### Injecting the environment
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
await runCommand(deploy, ['--json'], {
|
|
278
|
+
env: { DEPLOY_REGION: 'eu' },
|
|
279
|
+
config: { deploy: { region: 'ap' } },
|
|
280
|
+
answers: ['production'], // queued prompt answers
|
|
281
|
+
stat: async (p) => (p === '/data' ? 'directory' : null),
|
|
282
|
+
});
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
Prompts are skipped in non-interactive contexts, so queue `answers` when a test
|
|
286
|
+
exercises one. Without `stat`, `flag.path()` checks are skipped entirely.
|
|
287
|
+
|
|
288
|
+
### Asserting JSON output
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
const result = await runCommand(status, ['--json']);
|
|
292
|
+
expect(JSON.parse(result.stdout.join(''))).toEqual({ healthy: true });
|
|
293
|
+
```
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Runtime Notes
|
|
2
|
+
|
|
3
|
+
## Bun-first commands
|
|
4
|
+
|
|
5
|
+
- Run CLI entrypoint: `bun mycli.ts --help`
|
|
6
|
+
- Run tests: `bun test mycli.test.ts`
|
|
7
|
+
|
|
8
|
+
The scaffolder prints path-aware run commands; use those exact printed paths when `--out` is not `.`.
|
|
9
|
+
The scaffolder auto-detects test style:
|
|
10
|
+
|
|
11
|
+
- Bun project + no detected Vitest usage: generate `bun:test` template.
|
|
12
|
+
- Otherwise: generate Vitest template.
|
|
13
|
+
- Package manager detection checks lockfiles (including `pnpm-*.yaml/.yml`) and manifest `packageManager` entries in `package.json`, `package.json5`, and `package.yaml/.yml`.
|
|
14
|
+
|
|
15
|
+
If Vitest template is generated inside a Bun project, `bun test` still runs those tests in this workflow.
|
|
16
|
+
|
|
17
|
+
## npm/Node alternative
|
|
18
|
+
|
|
19
|
+
- Run CLI entrypoint: `npx tsx mycli.ts --help`
|
|
20
|
+
- Run tests: `npx vitest run mycli.test.ts`
|
|
21
|
+
|
|
22
|
+
## Deno alternative
|
|
23
|
+
|
|
24
|
+
- Run CLI entrypoint: `deno run -A mycli.ts --help`
|
|
25
|
+
- Run tests: use Bun/Node test tooling unless the project already has Deno test wiring.
|
|
26
|
+
|
|
27
|
+
## Prompt behavior
|
|
28
|
+
|
|
29
|
+
DreamCLI skips prompts in non-interactive contexts (CI/piped input). When tests depend on prompts, inject answers with `runCommand(..., { answers: [...] })`.
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# /// script
|
|
3
|
+
# requires-python = ">=3.13"
|
|
4
|
+
# dependencies = []
|
|
5
|
+
# ///
|
|
6
|
+
"""
|
|
7
|
+
Generate DreamCLI starter files from bundled templates.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
MANIFEST_FILENAMES = (
|
|
17
|
+
"package.json",
|
|
18
|
+
"package.json5",
|
|
19
|
+
"package.yaml",
|
|
20
|
+
"package.yml",
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
LOCKFILE_TO_MANAGER = (
|
|
24
|
+
("bun.lock", "bun"),
|
|
25
|
+
("bun.lockb", "bun"),
|
|
26
|
+
("pnpm-lock.yaml", "pnpm"),
|
|
27
|
+
("pnpm-lock.yml", "pnpm"),
|
|
28
|
+
("pnpm-workspace.yaml", "pnpm"),
|
|
29
|
+
("pnpm-workspace.yml", "pnpm"),
|
|
30
|
+
("yarn.lock", "yarn"),
|
|
31
|
+
("package-lock.json", "npm"),
|
|
32
|
+
("npm-shrinkwrap.json", "npm"),
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def normalize_name(raw: str) -> str:
|
|
37
|
+
name = raw.strip().lower()
|
|
38
|
+
name = re.sub(r"[^a-z0-9]+", "-", name)
|
|
39
|
+
name = name.strip("-")
|
|
40
|
+
name = re.sub(r"-{2,}", "-", name)
|
|
41
|
+
return name
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def read_template(path: Path) -> str:
|
|
45
|
+
if not path.exists():
|
|
46
|
+
raise FileNotFoundError(f"Template not found: {path}")
|
|
47
|
+
return path.read_text()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def render_template(template: str, replacements: dict[str, str]) -> str:
|
|
51
|
+
rendered = template
|
|
52
|
+
for key, value in replacements.items():
|
|
53
|
+
rendered = rendered.replace(key, value)
|
|
54
|
+
if not rendered.endswith("\n"):
|
|
55
|
+
rendered += "\n"
|
|
56
|
+
return rendered
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def write_file(path: Path, content: str, force: bool) -> None:
|
|
60
|
+
if path.exists() and not force:
|
|
61
|
+
raise FileExistsError(f"Refusing to overwrite existing file: {path}. Use --force to overwrite.")
|
|
62
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
path.write_text(content)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def iter_ancestors(path: Path):
|
|
67
|
+
current = path.resolve()
|
|
68
|
+
while True:
|
|
69
|
+
yield current
|
|
70
|
+
if current.parent == current:
|
|
71
|
+
break
|
|
72
|
+
current = current.parent
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def lockfiles_for_directory(directory: Path) -> list[Path]:
|
|
76
|
+
lockfiles: list[Path] = []
|
|
77
|
+
for lockfile, _ in LOCKFILE_TO_MANAGER:
|
|
78
|
+
candidate = directory / lockfile
|
|
79
|
+
if candidate.exists():
|
|
80
|
+
lockfiles.append(candidate)
|
|
81
|
+
|
|
82
|
+
pnpm_globs = (
|
|
83
|
+
"pnpm-*.yaml",
|
|
84
|
+
"pnpm-*.yml",
|
|
85
|
+
)
|
|
86
|
+
for pattern in pnpm_globs:
|
|
87
|
+
for candidate in sorted(directory.glob(pattern)):
|
|
88
|
+
if candidate not in lockfiles:
|
|
89
|
+
lockfiles.append(candidate)
|
|
90
|
+
return lockfiles
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def manifests_for_directory(directory: Path) -> list[Path]:
|
|
94
|
+
manifests: list[Path] = []
|
|
95
|
+
for filename in MANIFEST_FILENAMES:
|
|
96
|
+
candidate = directory / filename
|
|
97
|
+
if candidate.exists():
|
|
98
|
+
manifests.append(candidate)
|
|
99
|
+
return manifests
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def package_manager_from_lockfiles(directory: Path) -> str | None:
|
|
103
|
+
for candidate in lockfiles_for_directory(directory):
|
|
104
|
+
if candidate.name.startswith("pnpm-") and candidate.suffix in {".yaml", ".yml"}:
|
|
105
|
+
return "pnpm"
|
|
106
|
+
for lockfile, manager in LOCKFILE_TO_MANAGER:
|
|
107
|
+
if candidate.name == lockfile:
|
|
108
|
+
return manager
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def package_manager_from_manifest(manifest: dict) -> str | None:
|
|
113
|
+
raw_value = manifest.get("packageManager")
|
|
114
|
+
if not isinstance(raw_value, str) or not raw_value.strip():
|
|
115
|
+
return None
|
|
116
|
+
manager = raw_value.split("@", 1)[0].strip().lower()
|
|
117
|
+
if manager in {"bun", "pnpm", "npm", "yarn"}:
|
|
118
|
+
return manager
|
|
119
|
+
return None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def read_text_file(path: Path) -> str | None:
|
|
123
|
+
try:
|
|
124
|
+
return path.read_text(errors="ignore")
|
|
125
|
+
except OSError:
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def package_manager_from_text(raw_text: str) -> str | None:
|
|
130
|
+
match = re.search(
|
|
131
|
+
r'(?mi)^[ \t]*["\']?packageManager["\']?[ \t]*:[ \t]*["\']?([^"\',\n\r#]+)',
|
|
132
|
+
raw_text,
|
|
133
|
+
)
|
|
134
|
+
if match is None:
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
value = match.group(1).strip()
|
|
138
|
+
manager = value.split("@", 1)[0].strip().lower()
|
|
139
|
+
if manager in {"bun", "pnpm", "npm", "yarn"}:
|
|
140
|
+
return manager
|
|
141
|
+
return None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def manifest_text_uses_vitest(raw_text: str) -> bool:
|
|
145
|
+
return re.search(r"\bvitest\b", raw_text) is not None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def detect_package_manager_with_root(start: Path) -> tuple[str | None, Path | None]:
|
|
149
|
+
for directory in iter_ancestors(start):
|
|
150
|
+
for manifest_path in manifests_for_directory(directory):
|
|
151
|
+
if manifest_path.name == "package.json":
|
|
152
|
+
manifest = read_package_json(manifest_path)
|
|
153
|
+
if manifest is not None:
|
|
154
|
+
from_manifest = package_manager_from_manifest(manifest)
|
|
155
|
+
if from_manifest is not None:
|
|
156
|
+
return (from_manifest, directory)
|
|
157
|
+
|
|
158
|
+
raw_text = read_text_file(manifest_path)
|
|
159
|
+
if raw_text is not None:
|
|
160
|
+
from_text = package_manager_from_text(raw_text)
|
|
161
|
+
if from_text is not None:
|
|
162
|
+
return (from_text, directory)
|
|
163
|
+
|
|
164
|
+
from_lockfile = package_manager_from_lockfiles(directory)
|
|
165
|
+
if from_lockfile is not None:
|
|
166
|
+
return (from_lockfile, directory)
|
|
167
|
+
return (None, None)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def read_package_json(path: Path) -> dict | None:
|
|
171
|
+
try:
|
|
172
|
+
raw = path.read_text()
|
|
173
|
+
parsed = json.loads(raw)
|
|
174
|
+
except (OSError, json.JSONDecodeError):
|
|
175
|
+
return None
|
|
176
|
+
if isinstance(parsed, dict):
|
|
177
|
+
return parsed
|
|
178
|
+
return None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def manifest_uses_vitest(manifest: dict) -> bool:
|
|
182
|
+
dependency_fields = (
|
|
183
|
+
"dependencies",
|
|
184
|
+
"devDependencies",
|
|
185
|
+
"peerDependencies",
|
|
186
|
+
"optionalDependencies",
|
|
187
|
+
)
|
|
188
|
+
for field in dependency_fields:
|
|
189
|
+
deps = manifest.get(field)
|
|
190
|
+
if isinstance(deps, dict) and "vitest" in deps:
|
|
191
|
+
return True
|
|
192
|
+
|
|
193
|
+
scripts = manifest.get("scripts")
|
|
194
|
+
if isinstance(scripts, dict):
|
|
195
|
+
for script in scripts.values():
|
|
196
|
+
if isinstance(script, str) and "vitest" in script:
|
|
197
|
+
return True
|
|
198
|
+
|
|
199
|
+
return False
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def find_project_root(start: Path) -> Path | None:
|
|
203
|
+
for directory in iter_ancestors(start):
|
|
204
|
+
if package_manager_from_lockfiles(directory) is not None:
|
|
205
|
+
return directory
|
|
206
|
+
if manifests_for_directory(directory):
|
|
207
|
+
return directory
|
|
208
|
+
return None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def iter_to_ancestor(start: Path, ancestor: Path):
|
|
212
|
+
current = start.resolve()
|
|
213
|
+
target = ancestor.resolve()
|
|
214
|
+
while True:
|
|
215
|
+
yield current
|
|
216
|
+
if current == target:
|
|
217
|
+
break
|
|
218
|
+
if current.parent == current:
|
|
219
|
+
break
|
|
220
|
+
current = current.parent
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def detect_vitest_usage_in_project(project_root: Path, manager_root: Path | None) -> bool:
|
|
224
|
+
stop_at = manager_root.resolve() if manager_root is not None else project_root.resolve()
|
|
225
|
+
for directory in iter_to_ancestor(project_root, stop_at):
|
|
226
|
+
for manifest_path in manifests_for_directory(directory):
|
|
227
|
+
if manifest_path.name == "package.json":
|
|
228
|
+
manifest = read_package_json(manifest_path)
|
|
229
|
+
if manifest and manifest_uses_vitest(manifest):
|
|
230
|
+
return True
|
|
231
|
+
|
|
232
|
+
raw_text = read_text_file(manifest_path)
|
|
233
|
+
if raw_text is not None and manifest_text_uses_vitest(raw_text):
|
|
234
|
+
return True
|
|
235
|
+
|
|
236
|
+
if (stop_at / "node_modules" / "vitest" / "package.json").exists():
|
|
237
|
+
return True
|
|
238
|
+
|
|
239
|
+
for lockfile in lockfiles_for_directory(stop_at):
|
|
240
|
+
try:
|
|
241
|
+
if "vitest" in lockfile.read_text(errors="ignore"):
|
|
242
|
+
return True
|
|
243
|
+
except OSError:
|
|
244
|
+
continue
|
|
245
|
+
|
|
246
|
+
return False
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def choose_test_template(mode: str, package_manager: str | None, uses_vitest: bool) -> tuple[str, str]:
|
|
250
|
+
if package_manager == "bun" and not uses_vitest:
|
|
251
|
+
return (f"{mode}-command.bun-test.ts.tpl", "bun:test")
|
|
252
|
+
return (f"{mode}-command.test.ts.tpl", "vitest")
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def choose_test_command(package_manager: str | None, test_framework: str, test_path: str) -> str:
|
|
256
|
+
if test_framework == "bun:test":
|
|
257
|
+
return f"bun test {test_path}"
|
|
258
|
+
if package_manager == "bun":
|
|
259
|
+
return f"bun test {test_path}"
|
|
260
|
+
if package_manager == "pnpm":
|
|
261
|
+
return f"pnpm vitest run {test_path}"
|
|
262
|
+
if package_manager == "yarn":
|
|
263
|
+
return f"yarn vitest run {test_path}"
|
|
264
|
+
return f"npx vitest run {test_path}"
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def format_run_path(path: Path, cwd: Path) -> str:
|
|
268
|
+
try:
|
|
269
|
+
relative = path.relative_to(cwd).as_posix()
|
|
270
|
+
if not relative.startswith((".", "..")):
|
|
271
|
+
return f"./{relative}"
|
|
272
|
+
return relative
|
|
273
|
+
except ValueError:
|
|
274
|
+
return path.as_posix()
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def main() -> int:
|
|
278
|
+
parser = argparse.ArgumentParser(description="Scaffold Bun-first DreamCLI starter files from templates.")
|
|
279
|
+
parser.add_argument("--name", required=True, help="CLI name (e.g. mycli)")
|
|
280
|
+
parser.add_argument(
|
|
281
|
+
"--mode",
|
|
282
|
+
choices=["single", "multi"],
|
|
283
|
+
default="single",
|
|
284
|
+
help="Starter shape. single=one root command, multi=nested command groups.",
|
|
285
|
+
)
|
|
286
|
+
parser.add_argument("--out", required=True, help="Output directory")
|
|
287
|
+
parser.add_argument(
|
|
288
|
+
"--no-test",
|
|
289
|
+
action="store_true",
|
|
290
|
+
help="Skip generating the starter test file.",
|
|
291
|
+
)
|
|
292
|
+
parser.add_argument(
|
|
293
|
+
"--force",
|
|
294
|
+
action="store_true",
|
|
295
|
+
help="Overwrite existing files if present.",
|
|
296
|
+
)
|
|
297
|
+
args = parser.parse_args()
|
|
298
|
+
|
|
299
|
+
cli_name = normalize_name(args.name)
|
|
300
|
+
if not cli_name:
|
|
301
|
+
print("[ERROR] --name must include at least one letter or digit.")
|
|
302
|
+
return 1
|
|
303
|
+
|
|
304
|
+
output_dir = Path(args.out).resolve()
|
|
305
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
306
|
+
|
|
307
|
+
skill_root = Path(__file__).resolve().parent.parent
|
|
308
|
+
templates_dir = skill_root / "assets" / "templates"
|
|
309
|
+
|
|
310
|
+
entry_template_path = templates_dir / f"{args.mode}-command.ts.tpl"
|
|
311
|
+
test_template_path = templates_dir / f"{args.mode}-command.test.ts.tpl"
|
|
312
|
+
|
|
313
|
+
entry_filename = f"{cli_name}.ts"
|
|
314
|
+
entry_path = output_dir / entry_filename
|
|
315
|
+
test_path = output_dir / f"{cli_name}.test.ts"
|
|
316
|
+
include_test = not args.no_test
|
|
317
|
+
project_root = find_project_root(output_dir) or find_project_root(Path.cwd()) or output_dir
|
|
318
|
+
package_manager, manager_root = detect_package_manager_with_root(project_root)
|
|
319
|
+
uses_vitest = detect_vitest_usage_in_project(project_root, manager_root)
|
|
320
|
+
test_framework = "none"
|
|
321
|
+
|
|
322
|
+
replacements = {
|
|
323
|
+
"__CLI_NAME__": cli_name,
|
|
324
|
+
"__ENTRY_FILE__": f"./{entry_filename}",
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
try:
|
|
328
|
+
entry_template = read_template(entry_template_path)
|
|
329
|
+
entry_content = render_template(entry_template, replacements)
|
|
330
|
+
write_file(entry_path, entry_content, args.force)
|
|
331
|
+
print(f"[OK] Wrote {entry_path}")
|
|
332
|
+
|
|
333
|
+
if include_test:
|
|
334
|
+
test_template_name, test_framework = choose_test_template(args.mode, package_manager, uses_vitest)
|
|
335
|
+
test_template_path = templates_dir / test_template_name
|
|
336
|
+
test_template = read_template(test_template_path)
|
|
337
|
+
test_content = render_template(test_template, replacements)
|
|
338
|
+
write_file(test_path, test_content, args.force)
|
|
339
|
+
print(f"[OK] Wrote {test_path}")
|
|
340
|
+
except (FileExistsError, FileNotFoundError) as error:
|
|
341
|
+
print(f"[ERROR] {error}")
|
|
342
|
+
return 1
|
|
343
|
+
|
|
344
|
+
print("\nNext steps:")
|
|
345
|
+
run_path = format_run_path(entry_path, Path.cwd())
|
|
346
|
+
test_run_path = format_run_path(test_path, Path.cwd())
|
|
347
|
+
print(f"1. Run: bun {run_path} --help")
|
|
348
|
+
if include_test:
|
|
349
|
+
test_command = choose_test_command(package_manager, test_framework, test_run_path)
|
|
350
|
+
print(f"2. Test: {test_command}")
|
|
351
|
+
if test_framework == "bun:test":
|
|
352
|
+
print(" Detected Bun without vitest; generated a bun:test starter test.")
|
|
353
|
+
else:
|
|
354
|
+
print("2. Re-run without --no-test to include a starter test file")
|
|
355
|
+
print("3. Adapt commands, flags, and prompts to the user request")
|
|
356
|
+
return 0
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
if __name__ == "__main__":
|
|
360
|
+
sys.exit(main())
|