diff --git a/AGENTS.md b/AGENTS.md index d4b8c022..e9938fbc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,7 @@ src/ docs/ # VitePress site. Prose in guide/ and concepts/ examples/ # runnable examples, gh/ and pwsh-demo/ workspaces scripts/ # build, release, package checks, gh-project -skills/cli-creation/ # published consumer skill +skills/dreamcli/ # published consumer skill ``` ## WHERE TO LOOK diff --git a/README.md b/README.md index f213a9af..8c85c5a9 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,44 @@ deno add jsr:@kjanat/dreamcli # or npm:@kjanat/dreamcli ## Quick start +Create a TypeScript CLI project in a new or empty directory: + +```sh +npx @kjanat/dreamcli create mycli +cd mycli +npm install +npm start -- hello Jalapeño +npm test +npm run typecheck +npm run build +node dist/cli.mjs --help +``` + +Edit `src/commands/hello.ts` to change the greeting and register new commands in +`src/cli.ts`. The generated README covers development and packaging. GitHub +Actions checks types, tests, and the built executable. `npm pack` rebuilds it. +At creation, the generator looks up the latest tsdown release on npm and pins +it; offline it uses the version tested with DreamCLI. + +In a terminal, `npx @kjanat/dreamcli` prompts for the directory. `init` is an +alias for `create`. Supply a path in scripts. Use `--name` to override the +package name, `--no-test` to omit the starter test, or `--no-git` to skip Git +initialization. The manifest uses the configured Git author and infers a GitHub +repository from the owner and folder name. A new local repository gets that +`origin` and an initial commit. Review the inferred URL before pushing. + +Use `dreamcli create mycli --out .` to add a standalone entry and test to an +existing package. Both layouts add `AGENTS.md`, `CLAUDE.md`, and the bundled +[DreamCLI skill](skills/dreamcli/SKILL.md) under `.agents/skills/dreamcli/` +in the destination. Existing guidance is preserved even when `--force` replaces +the entry and test. The synchronous `scaffold()` API in `@kjanat/dreamcli/create` +accepts project metadata and a local skill directory without running Git or +fetching dependencies. + +[Framework guides](https://dreamcli.kjanat.dev/guide/getting-started) · +[JSR API reference](https://jsr.io/@kjanat/dreamcli/doc) · +[Markdown index](https://dreamcli.kjanat.dev/llms.txt) + ### Single command ```ts @@ -102,96 +140,24 @@ cli('greet').default(greet).run(); DreamCLI migration progress demo -```ts -import { - cli, - command, - group, - flag, - arg, -} from '@kjanat/dreamcli'; - -const deploy = command('deploy') - .description('Deploy to an environment') - .arg('target', arg.string()) - .flag('force', flag.boolean().alias('f')) - .flag( - 'region', - flag.enum(['us', 'eu', 'ap']).env('DEPLOY_REGION'), - ) - .action(({ args, flags, out }) => { - out.log( - `Deploying ${args.target} to ${flags.region ?? 'default'}`, - ); - }); - -const login = command('login') - .description('Authenticate with the service') - .flag('token', flag.string().describe('Auth token')) - .action(({ flags, out }) => { - out.log( - flags.token - ? 'Authenticated via token' - : 'Authenticated interactively', - ); - }); - -// Nested command groups -const migrate = command('migrate') - .description('Run migrations') - .flag('steps', flag.number()) - .action(async ({ flags, meta, out }) => { - const steps = flags.steps ?? 3; - - out.log(`${meta.name} ${meta.version ?? ''}`.trim()); - out.log(`Command: ${meta.command}`); - - const spinner = out.spinner('Preparing migrations'); - await new Promise((resolve) => - setTimeout(resolve, 1000), - ); - spinner.succeed(`Ready to run ${steps} steps`); - - const progress = out.progress({ - label: 'Migrating', - total: steps, - }); - - for (let step = 1; step <= steps; step++) { - await new Promise((resolve) => - setTimeout(resolve, 700), - ); - progress.update(step); - } +Register named commands with `.command()`. Nest related commands with `group()`: - progress.done(`Migrated ${steps} steps`); - }); - -const seed = command('seed') - .description('Seed database') - .action(({ out }) => { - out.log('seeding'); - }); +```ts +import { cli, command, group } from '@kjanat/dreamcli'; +const migrate = command('migrate').action(({ out }) => + out.log('Migrating'), +); const db = group('db') .description('Database operations') - .command(migrate) - .command(seed); - -cli('mycli') - .version('1.0.0') - .description('My awesome tool') - .command(deploy) - .command(login) - .command(db) - .run(); - -// mycli deploy production --force -// mycli login --token abc123 -// mycli db migrate --steps 3 -// mycli db seed + .command(migrate); +await cli('mycli').command(db).run(); // mycli db migrate ``` +For flags, nested help, and progress reporting, see the +[walkthrough](https://dreamcli.kjanat.dev/guide/walkthrough) and +[runnable examples](https://github.com/kjanat/dreamcli/tree/master/examples). + ## Why dreamcli Most TypeScript CLI frameworks treat the type system like decoration. diff --git a/bin/dreamcli.mjs b/bin/dreamcli.mjs new file mode 100755 index 00000000..3547200e --- /dev/null +++ b/bin/dreamcli.mjs @@ -0,0 +1,138 @@ +#!/usr/bin/env node + +/** DreamCLI's package executable. @module */ + +import { basename, relative, resolve, sep } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { arg, CLIError, cli, command, flag } from '@kjanat/dreamcli'; +import { scaffold } from '@kjanat/dreamcli/create'; +import { prompt } from '@kjanat/dreamcli/prompt'; +import { createAdapter, detectRuntime } from '@kjanat/dreamcli/runtime'; +import { DREAMCLI_REVISION, DREAMCLI_VERSION } from '@kjanat/dreamcli/version'; +import { initGit, projectIdentity } from './git.mjs'; +import { latestTsdown } from './project.mjs'; + +const adapter = createAdapter(); +const ci = adapter.env.CI; +const inCI = ci && ci !== 'false' && ci !== '0'; +const terminal = !inCI && adapter.stdinIsTTY && adapter.isTTY && adapter.stderrIsTTY; + +function nextSteps(directory, test) { + const commands = []; + const path = relative(adapter.cwd, directory); + if (path) { + if (sep === '\\') { + // PowerShell recognizes typographic single quotes as delimiters too. + commands.push(`Set-Location -LiteralPath '${directory.replace(/['‘’‚‛]/gu, "'$&")}'`); + } else { + commands.push(`cd './${path.replaceAll("'", "'\\''")}'`); + } + } + if (detectRuntime() === 'bun') { + // Bun treats '?' in the absolute entry path as a query. The Node start script handles it. + const start = directory.includes('?') ? 'bun run start' : 'bun src/cli.ts'; + commands.push('bun install', `${start} hello Jalapeño`); + if (test) commands.push('bun run test'); + } else { + commands.push('npm install', 'npm start -- hello Jalapeño'); + if (test) commands.push('npm test'); + } + return commands.join('\n'); +} + +const create = command('create') + .alias('init') + .description('Generate a DreamCLI starter') + .arg('directory', arg.string().optional().describe('Project directory (or CLI name with --out)')) + .flag('name', flag.string().describe('Override the project name')) + .flag('yes', flag.boolean().alias('y').describe('Use defaults without prompting')) + .flag( + 'out', + flag.path().describe('Write files into this directory instead of creating a project'), + ) + .flag('git', flag.boolean().default(true).negatable().describe('Create the initial Git commit')) + .flag('test', flag.boolean().default(true).negatable().describe('Generate a starter test')) + .flag( + 'force', + flag.boolean().default(false).describe('Replace existing starter files when using --out'), + ) + .action(async ({ args, flags, out, ask }) => { + const { git: useGit, name: explicitName, yes, ...options } = flags; + const project = options.out === undefined; + const interactive = project && !yes && !out.jsonMode && terminal; + + let target = args.directory; + if (target === undefined && interactive) { + target = await ask( + prompt.input({ + message: 'Where should I create your CLI?', + empty: 'accept', + trim: false, + }), + ); + } + if (!target?.trim()) { + throw new CLIError( + project ? 'Provide a project directory.' : 'Provide a CLI name with --out.', + { + code: 'SCAFFOLD_DIRECTORY_REQUIRED', + exitCode: 2, + suggest: project + ? 'For example: dreamcli create ./my-cli' + : 'For example: dreamcli create my-cli --out .', + }, + ); + } + + const directory = resolve(adapter.cwd, target); + const name = explicitName ?? (project ? basename(directory) : target); + if (interactive && relative(adapter.cwd, directory) === '') { + if (!(await ask(prompt.confirm({ message: 'Create here?', default: false })))) return; + } + + const metadata = project + ? { + ...projectIdentity(directory, adapter.env), + tsdownVersion: await latestTsdown(adapter.env), + } + : undefined; + const result = scaffold({ + ...options, + name, + directory, + metadata, + skillDirectory: fileURLToPath(new URL('../skills/dreamcli/', import.meta.url)), + }); + const git = + project && useGit + ? initGit( + directory, + result.files.map((path) => relative(directory, path).split(sep).join('/')), + DREAMCLI_VERSION, + DREAMCLI_REVISION, + adapter.env, + metadata?.repository, + ) + : undefined; + if (out.jsonMode) { + out.json({ ...result, ...(git && { git }) }); + return; + } + const destination = project ? directory : result.entry; + const label = out.color.cyan(project ? target : relative(adapter.cwd, destination)); + out.log(`Created ${out.color.link(pathToFileURL(destination), label)}`); + if (git?.error) out.warn(`Git: ${git.error}`); + if (project && !metadata?.tsdownVersion) { + out.status("Using DreamCLI's tested tsdown version because the npm lookup was unavailable."); + } + if (project) out.status(`\n${nextSteps(directory, result.test)}`); + }); + +const app = cli('dreamcli') + .manifest({ from: import.meta }) + .links() + .help({ commandHeader: true }) + .description('Create a project with DreamCLI'); + +const program = terminal && adapter.argv.length === 2 ? app.default(create) : app.command(create); +await program.run({ adapter }); diff --git a/bin/git.mjs b/bin/git.mjs new file mode 100644 index 00000000..3661c17e --- /dev/null +++ b/bin/git.mjs @@ -0,0 +1,61 @@ +/** Initialize a standalone starter without touching a surrounding repository. @module */ + +import { spawnSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { basename, dirname } from 'node:path'; + +export function projectIdentity(directory, env) { + let cwd = directory; + while (!existsSync(cwd) && dirname(cwd) !== cwd) cwd = dirname(cwd); + const config = (key) => { + const result = spawnSync('git', ['config', '--get', key], { cwd, env, encoding: 'utf8' }); + return result.status === 0 ? result.stdout.trim() : ''; + }; + const name = env.GIT_AUTHOR_NAME || config('user.name'); + const email = env.GIT_AUTHOR_EMAIL || config('user.email'); + const owner = + config('github.user') || + /^(?:\d+\+)?([\w-]+)@users\.noreply\.github\.com$/i.exec(email)?.[1] || + name.trim().replace(/\s+/g, '-'); + const folder = basename(directory) + .replace(/[^A-Za-z0-9_.-]+/g, '-') + .replace(/^-+|-+$/g, ''); + const repository = + /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(owner) && folder && !/^\.+$/.test(folder) + ? `https://github.com/${owner}/${folder}` + : undefined; + return { + ...((name || email) && { author: { ...(name && { name }), ...(email && { email }) } }), + ...(repository && { repository }), + }; +} + +export function initGit(cwd, files, version, revision, env, remote) { + const options = { cwd, encoding: 'utf8', env: { ...env, LC_ALL: 'C' } }; + const run = (...args) => spawnSync('git', args, options); + const local = run('rev-parse', '--local-env-vars'); + if (local.status !== 0) return failure(local); + for (const key of local.stdout.trim().split(/\s+/)) delete options.env[key]; + + const repository = run('rev-parse', '--git-dir'); + if (repository.status === 0) return { skipped: 'existing-repository' }; + if (!repository.stderr?.includes('not a git repository')) return failure(repository); + + const message = ['-m', `Initialize with dreamcli create ${version}`]; + if (revision !== 'dev') message.push('-m', `DreamCLI-Revision: ${revision}`); + for (const args of [ + ['init', '--template='], + ...(remote ? [['remote', 'add', 'origin', `${remote}.git`]] : []), + ['add', '--', ...files], + ['commit', ...message, '--', ...files], + ]) { + const result = run(...args); + if (result.status !== 0) return failure(result); + } + const head = run('rev-parse', 'HEAD'); + return head.status === 0 ? { commit: head.stdout.trim() } : failure(head); +} + +function failure(result) { + return { error: result.stderr?.trim() || result.error?.message || 'Git exited unsuccessfully.' }; +} diff --git a/bin/project.mjs b/bin/project.mjs new file mode 100644 index 00000000..13c80ac0 --- /dev/null +++ b/bin/project.mjs @@ -0,0 +1,20 @@ +/** Resolve the npm dist-tag at init time; offline scaffolds use the tested build version. @module */ + +export async function latestTsdown(env) { + if ((env.npm_config_offline ?? env.NPM_CONFIG_OFFLINE) === 'true') return undefined; + try { + const registry = + env.npm_config_registry || env.NPM_CONFIG_REGISTRY || 'https://registry.npmjs.org/'; + const response = await fetch(new URL('tsdown/latest', registry.replace(/\/?$/, '/')), { + signal: AbortSignal.timeout(8000), + headers: { Accept: 'application/json' }, + }); + if (!response.ok) return undefined; + const { version } = await response.json(); + return typeof version === 'string' && /^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(version) + ? version + : undefined; + } catch { + return undefined; + } +} diff --git a/deno.json b/deno.json index 5689b1d9..70f40d56 100644 --- a/deno.json +++ b/deno.json @@ -6,7 +6,7 @@ "tasks": { "check": { "description": "Type-check source with Deno's checker (may conflict with @types/node)", - "command": "deno check src/index.ts src/completion.ts src/config.ts src/json-schema.ts src/prompt.ts src/runtime.ts src/schema.ts src/testkit.ts src/version.ts" + "command": "deno check src/index.ts src/completion.ts src/config.ts src/create.ts src/json-schema.ts src/prompt.ts src/runtime.ts src/schema.ts src/testkit.ts src/version.ts" }, "smoke": { "description": "Run Deno adapter smoke test against source via import map", @@ -42,6 +42,7 @@ "./version": "./src/version.ts", "./completion": "./src/completion.ts", "./config": "./src/config.ts", + "./create": "./src/create.ts", "./json-schema": "./src/json-schema.ts", "./prompt": "./src/prompt.ts" }, @@ -57,6 +58,7 @@ "@kjanat/dreamcli/package.json": ["./package.json"], "@kjanat/dreamcli/completion": ["./src/completion.ts"], "@kjanat/dreamcli/config": ["./src/config.ts"], + "@kjanat/dreamcli/create": ["./src/create.ts"], "@kjanat/dreamcli/json-schema": ["./src/json-schema.ts"], "@kjanat/dreamcli/prompt": ["./src/prompt.ts"] } diff --git a/docs/.vitepress/data/api-index.test.ts b/docs/.vitepress/data/api-index.test.ts index 56052823..55bf3247 100644 --- a/docs/.vitepress/data/api-index.test.ts +++ b/docs/.vitepress/data/api-index.test.ts @@ -17,6 +17,7 @@ describe('api-index', () => { '@kjanat/dreamcli', '@kjanat/dreamcli/completion', '@kjanat/dreamcli/config', + '@kjanat/dreamcli/create', '@kjanat/dreamcli/json-schema', '@kjanat/dreamcli/prompt', '@kjanat/dreamcli/runtime', @@ -40,7 +41,7 @@ describe('api-index', () => { expect(root?.kindGroups.find((group) => group.kind === 'function')?.symbols).toContainEqual({ name: 'isMainModule', kind: 'function', - sourcePath: 'src/core/cli/index.ts', + sourcePath: 'src/runtime/main-module.ts', }); expect(root?.kindGroups.find((group) => group.kind === 'interface')?.symbols).toContainEqual({ name: 'CLIOptions', diff --git a/docs/.vitepress/data/deno-doc.test.ts b/docs/.vitepress/data/deno-doc.test.ts index b694a578..1bffe001 100644 --- a/docs/.vitepress/data/deno-doc.test.ts +++ b/docs/.vitepress/data/deno-doc.test.ts @@ -169,6 +169,18 @@ describe('deno doc normalization', () => { exportIds: expect.arrayContaining(['@kjanat/dreamcli/config:discoverConfig']), missingExports: [], }, + { + entrypoint: '@kjanat/dreamcli/create', + subpath: './create', + sourcePath: 'src/create.ts', + hasDocumentation: true, + exportIds: expect.arrayContaining([ + '@kjanat/dreamcli/create:scaffold', + '@kjanat/dreamcli/create:ScaffoldOptions', + '@kjanat/dreamcli/create:ScaffoldResult', + ]), + missingExports: [], + }, { entrypoint: '@kjanat/dreamcli/json-schema', subpath: './json-schema', diff --git a/docs/guide/help.md b/docs/guide/help.md index b0b29317..9d9e8012 100644 --- a/docs/guide/help.md +++ b/docs/guide/help.md @@ -199,9 +199,8 @@ The root-help header can wrap the program name and version in OSC 8 terminal hyperlinks (pointing at the repository and release tag). Explicit `--no-hyperlinks` / `--hyperlinks` flags take precedence, followed by `NO_HYPERLINKS`, then `FORCE_HYPERLINKS`, and finally TTY detection. When both -environment variables are set, `NO_HYPERLINKS` wins. The same resolved decision is exposed to handlers as -`out.isHyperlinkSupported`, so code rendering its own `out.color.link(...)` -output can gate on it and keep escapes out of piped or opted-out contexts. +environment variables are set, `NO_HYPERLINKS` wins. Handlers can format a link with `out.color.link(url, label)`. It follows +the same hyperlink policy and returns the label alone when links are disabled. Set `.help({ commandHeader: true })` to show that same program and version header in command help and help topics. The header uses the URLs from diff --git a/docs/guide/output.md b/docs/guide/output.md index 21954f7b..1611c35b 100644 --- a/docs/guide/output.md +++ b/docs/guide/output.md @@ -327,7 +327,7 @@ if (!ctx.jsonMode && ctx.verbosity !== 'quiet') The returned `color` is the same gated palette the channel will expose as `out.color` (`ctx.color.isColorSupported` is the boolean form), and -`ctx.isHyperlinkSupported` uses the same precedence as the help header: explicit +`ctx.isHyperlinkSupported` is false in JSON mode. Otherwise it follows the help header: explicit `--no-hyperlinks` / `--hyperlinks` flags, then `NO_HYPERLINKS`, then `FORCE_HYPERLINKS`, and finally TTY detection. diff --git a/docs/reference/main.md b/docs/reference/main.md index 5dc0365d..409ea4b5 100644 --- a/docs/reference/main.md +++ b/docs/reference/main.md @@ -161,8 +161,7 @@ cli('mycli').manifest(denoCfg).command(deploy).run(); ### `isMainModule(meta)` -Node, Bun, and Deno expose the conventional entrypoint guard directly. Use it when the runtime's -ambient types are available: +Use the native entrypoint guard when both the runtime and its ambient types support it: ```ts twoslash import { cli, command } from '@kjanat/dreamcli'; @@ -175,9 +174,9 @@ if (import.meta.main) { } ``` -`isMainModule(import.meta)` is the compatibility form for projects whose ambient `ImportMeta` -interface omits `main`. It performs the same check without direct property access or global -augmentation, keeping cross-runtime JSR packages type-checkable and publishable: +Use `isMainModule(import.meta)` across the full supported Node range or when the ambient +`ImportMeta` interface omits `main`. On Node versions without the native guard, the helper +compares the module filename with the entry script: ```ts twoslash import { diff --git a/package.json b/package.json index 7f3a3047..3c0ffc6f 100644 --- a/package.json +++ b/package.json @@ -35,6 +35,7 @@ "#dreamcli": "./src/index.ts", "#dreamcli/completion": "./src/completion.ts", "#dreamcli/config": "./src/config.ts", + "#dreamcli/create": "./src/create.ts", "#dreamcli/json-schema": "./src/json-schema.ts", "#dreamcli/prompt": "./src/prompt.ts", "#dreamcli/runtime": "./src/runtime.ts", @@ -57,6 +58,10 @@ "types": "./dist/config.d.mts", "default": "./dist/config.mjs" }, + "./create": { + "types": "./dist/create.d.mts", + "default": "./dist/create.mjs" + }, "./json-schema": { "types": "./dist/json-schema.d.mts", "default": "./dist/json-schema.mjs" @@ -80,7 +85,11 @@ "./package.json": "./package.json", "./schema": "./dreamcli.schema.json" }, + "bin": { + "dreamcli": "./bin/dreamcli.mjs" + }, "files": [ + "bin", "dist", "dreamcli.schema.json", "skills", diff --git a/skills/cli-creation/agents/openai.yaml b/skills/cli-creation/agents/openai.yaml deleted file mode 100644 index 277eb701..00000000 --- a/skills/cli-creation/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "CLI Creation" - short_description: "Build typed DreamCLI consumer CLIs quickly" - default_prompt: "Use $cli-creation to scaffold a Bun-first DreamCLI CLI with tests." diff --git a/skills/cli-creation/assets/templates/multi-command.bun-test.ts.tpl b/skills/cli-creation/assets/templates/multi-command.bun-test.ts.tpl deleted file mode 100644 index 5f9b6a30..00000000 --- a/skills/cli-creation/assets/templates/multi-command.bun-test.ts.tpl +++ /dev/null @@ -1,20 +0,0 @@ -import { partyStart } from '__ENTRY_FILE__'; -import { runCommand } from '@kjanat/dreamcli/testkit'; -import { describe, expect, it } from 'bun:test'; - -describe('party start command', () => { - it('applies sparkle middleware when --sparkle is set', async () => { - const result = await runCommand(partyStart, ['--theme', 'midnight', '--sparkle']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['✨ Party started with midnight theme! ✨\n']); - expect(result.stderr).toEqual([]); - }); - - it('renders help text', async () => { - const result = await runCommand(partyStart, ['--help']); - - expect(result.exitCode).toBe(0); - expect(result.stdout.join('')).toContain('Start the pony party'); - }); -}); diff --git a/skills/cli-creation/assets/templates/multi-command.test.ts.tpl b/skills/cli-creation/assets/templates/multi-command.test.ts.tpl deleted file mode 100644 index e53a4b66..00000000 --- a/skills/cli-creation/assets/templates/multi-command.test.ts.tpl +++ /dev/null @@ -1,20 +0,0 @@ -import { partyStart } from '__ENTRY_FILE__'; -import { runCommand } from '@kjanat/dreamcli/testkit'; -import { describe, expect, it } from 'vitest'; - -describe('party start command', () => { - it('applies sparkle middleware when --sparkle is set', async () => { - const result = await runCommand(partyStart, ['--theme', 'midnight', '--sparkle']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['✨ Party started with midnight theme! ✨\n']); - expect(result.stderr).toEqual([]); - }); - - it('renders help text', async () => { - const result = await runCommand(partyStart, ['--help']); - - expect(result.exitCode).toBe(0); - expect(result.stdout.join('')).toContain('Start the pony party'); - }); -}); diff --git a/skills/cli-creation/assets/templates/multi-command.ts.tpl b/skills/cli-creation/assets/templates/multi-command.ts.tpl deleted file mode 100644 index 50026d7c..00000000 --- a/skills/cli-creation/assets/templates/multi-command.ts.tpl +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env bun -/** - * __CLI_NAME__ - multi-command DreamCLI starter (pony party edition). - * - * Bun: - * bun __CLI_NAME__.ts snack cupcake --count 3 - * bun __CLI_NAME__.ts story "rainbow heist" --mood legendary --sparkle - * bun __CLI_NAME__.ts party start --theme midnight - * bun __CLI_NAME__.ts --help - * - * npm/tsx: - * npx tsx __CLI_NAME__.ts party playlist --genre chaos - * - * Deno: - * deno run -A __CLI_NAME__.ts snack donut --count 2 - */ - -import { arg, cli, command, flag, group, middleware } from '@kjanat/dreamcli'; - -const sparkle = middleware<{ sparkle: (message: string) => string }>(async ({ flags, next }) => { - const sparkleEnabled = flags.sparkle === true; - return next({ - sparkle: (message: string) => (sparkleEnabled ? `✨ ${message} ✨` : message), - }); -}); - -const sparkleFlag = () => flag.boolean().alias('s').env('SPARKLE').describe('Add extra sparkle'); - -export const snack = command('snack') - .description('Serve snacks to the crew') - .arg('treat', arg.string().default('cupcake').describe('Snack to serve')) - .flag('count', flag.number().default(1).alias('c').describe('How many snacks')) - .flag('sparkle', sparkleFlag()) - .middleware(sparkle) - .action(({ args, flags, ctx, out }) => { - const { treat } = args; - const { count } = flags; - out.log(ctx.sparkle(`Serving ${count} ${treat}(s)!`)); - }); - -export const story = command('story') - .description('Tell a dramatic story') - .arg('topic', arg.string().default('the great cupcake rescue').describe('Story topic')) - .flag('mood', flag.enum(['calm', 'chaos', 'legendary']) - .prompt({ kind: 'select', message: 'Set the mood!' }) - .default('calm').describe('Story mood')) - .flag('sparkle', sparkleFlag()) - .middleware(sparkle) - .action(({ args, flags, ctx, out }) => { - const { topic } = args; - const { mood } = flags; - out.log(ctx.sparkle(`Story time: ${topic} (${mood})`)); - out.log(ctx.sparkle('Dramatic glitter intensifies')); - }); - -export const partyStart = command('start') - .description('Start the pony party') - .flag('theme', flag.enum(['rainbow', 'midnight', 'glitter']).default('rainbow').describe('Party theme')) - .flag('sparkle', sparkleFlag()) - .middleware(sparkle) - .action(({ flags, ctx, out }) => { - out.log(ctx.sparkle(`Party started with ${flags.theme} theme!`)); - }); - -export const partyPlaylist = command('playlist') - .description('Pick a party playlist vibe') - .flag('genre', flag.enum(['pop', 'ballad', 'chaos']).default('pop').describe('Playlist genre')) - .flag('sparkle', sparkleFlag()) - .middleware(sparkle) - .action(({ flags, ctx, out }) => { - out.log(ctx.sparkle(`Now playing: ${flags.genre}`)); - }); - -export const party = group('party') - .description('Party controls') - .command(partyStart) - .command(partyPlaylist); - -export const app = cli('__CLI_NAME__') - .version('0.1.0') - .description('Fun DreamCLI starter app') - .command(snack) - .command(story) - .command(party) - .completions(); - -if (import.meta.main) { - app.run(); -} diff --git a/skills/cli-creation/assets/templates/single-command.bun-test.ts.tpl b/skills/cli-creation/assets/templates/single-command.bun-test.ts.tpl deleted file mode 100644 index 6a2c3d28..00000000 --- a/skills/cli-creation/assets/templates/single-command.bun-test.ts.tpl +++ /dev/null @@ -1,29 +0,0 @@ -import { hello } from '__ENTRY_FILE__'; -import { runCommand } from '@kjanat/dreamcli/testkit'; -import { describe, expect, it } from 'bun:test'; - -describe('hello command', () => { - it('prints sparkly greeting when --sparkle is set', async () => { - const result = await runCommand(hello, ['Twilight', '--sparkle', '--times', '2']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['✨ Hello, Twilight! ✨\n', '✨ Hello, Twilight! ✨\n']); - // out.status() writes to stderr so stdout stays pipe-clean. - expect(result.stderr).toEqual(['Greeted Twilight 2 time(s)\n']); - }); - - it('suppresses status output with --quiet', async () => { - const result = await runCommand(hello, ['Twilight', '--quiet']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['Hello, Twilight!\n']); - expect(result.stderr).toEqual([]); - }); - - it('renders help text', async () => { - const result = await runCommand(hello, ['--help']); - - expect(result.exitCode).toBe(0); - expect(result.stdout.join('')).toContain('Say hello with optional sparkle'); - }); -}); diff --git a/skills/cli-creation/assets/templates/single-command.test.ts.tpl b/skills/cli-creation/assets/templates/single-command.test.ts.tpl deleted file mode 100644 index bd48df6d..00000000 --- a/skills/cli-creation/assets/templates/single-command.test.ts.tpl +++ /dev/null @@ -1,29 +0,0 @@ -import { hello } from '__ENTRY_FILE__'; -import { runCommand } from '@kjanat/dreamcli/testkit'; -import { describe, expect, it } from 'vitest'; - -describe('hello command', () => { - it('prints sparkly greeting when --sparkle is set', async () => { - const result = await runCommand(hello, ['Twilight', '--sparkle', '--times', '2']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['✨ Hello, Twilight! ✨\n', '✨ Hello, Twilight! ✨\n']); - // out.status() writes to stderr so stdout stays pipe-clean. - expect(result.stderr).toEqual(['Greeted Twilight 2 time(s)\n']); - }); - - it('suppresses status output with --quiet', async () => { - const result = await runCommand(hello, ['Twilight', '--quiet']); - - expect(result.exitCode).toBe(0); - expect(result.stdout).toEqual(['Hello, Twilight!\n']); - expect(result.stderr).toEqual([]); - }); - - it('renders help text', async () => { - const result = await runCommand(hello, ['--help']); - - expect(result.exitCode).toBe(0); - expect(result.stdout.join('')).toContain('Say hello with optional sparkle'); - }); -}); diff --git a/skills/cli-creation/assets/templates/single-command.ts.tpl b/skills/cli-creation/assets/templates/single-command.ts.tpl deleted file mode 100644 index 634e8e5a..00000000 --- a/skills/cli-creation/assets/templates/single-command.ts.tpl +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env bun -/** - * __CLI_NAME__ - hello-world DreamCLI starter. - * - * Bun: - * bun __CLI_NAME__.ts - * bun __CLI_NAME__.ts Twilight --sparkle --times 2 - * bun __CLI_NAME__.ts --help - * - * npm/tsx: - * npx tsx __CLI_NAME__.ts Twilight --sparkle --times 2 - * - * Deno: - * deno run -A __CLI_NAME__.ts Twilight --sparkle --times 2 - */ - -import { arg, cli, command, flag, middleware } from '@kjanat/dreamcli'; - -const sparkle = middleware<{ sparkle: (message: string) => string }>(async ({ flags, next }) => { - const sparkleEnabled = flags.sparkle === true; - return next({ - sparkle: (message: string) => (sparkleEnabled ? `✨ ${message} ✨` : message), - }); -}); - -export const hello = command('hello') - .description('Say hello with optional sparkle') - .example(({ name }) => `${name} Twilight --sparkle --times 2`, 'Sparkly double greeting') - .arg('name', arg.string().default('World').describe('Who to greet')) - .flag('sparkle', flag.boolean().alias('s').env('SPARKLE').describe('Add sparkles')) - // Constraints are enforced at every source, so the action needs no clamping. - .flag('times', flag.number({ int: true, min: 0, max: 100 }).default(1).alias('n').describe('Repeat count')) - .middleware(sparkle) - .action(({ args, flags, ctx, out }) => { - for (let i = 0; i < flags.times; i++) { - out.log(ctx.sparkle(`Hello, ${args.name}!`)); - } - - // stderr, and silenced by --quiet: keeps stdout pipe-clean. - out.status(`Greeted ${args.name} ${flags.times} time(s)`); - }); - -export const app = cli('__CLI_NAME__').default(hello); - -if (import.meta.main) { - app.run(); -} diff --git a/skills/cli-creation/scripts/scaffold_cli.py b/skills/cli-creation/scripts/scaffold_cli.py deleted file mode 100755 index 2ef21422..00000000 --- a/skills/cli-creation/scripts/scaffold_cli.py +++ /dev/null @@ -1,368 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.13" -# dependencies = [] -# /// -""" -Generate DreamCLI starter files from bundled templates. -""" - -import argparse -import json -import re -import sys -from pathlib import Path - -MANIFEST_FILENAMES = ( - "package.json", - "package.json5", - "package.yaml", - "package.yml", -) - -LOCKFILE_TO_MANAGER = ( - ("bun.lock", "bun"), - ("bun.lockb", "bun"), - ("pnpm-lock.yaml", "pnpm"), - ("pnpm-lock.yml", "pnpm"), - ("pnpm-workspace.yaml", "pnpm"), - ("pnpm-workspace.yml", "pnpm"), - ("yarn.lock", "yarn"), - ("package-lock.json", "npm"), - ("npm-shrinkwrap.json", "npm"), -) - - -def normalize_name(raw: str) -> str: - name = raw.strip().lower() - name = re.sub(r"[^a-z0-9]+", "-", name) - name = name.strip("-") - name = re.sub(r"-{2,}", "-", name) - return name - - -def read_template(path: Path) -> str: - if not path.exists(): - raise FileNotFoundError(f"Template not found: {path}") - return path.read_text() - - -def render_template(template: str, replacements: dict[str, str]) -> str: - rendered = template - for key, value in replacements.items(): - rendered = rendered.replace(key, value) - if not rendered.endswith("\n"): - rendered += "\n" - return rendered - - -def write_file(path: Path, content: str, force: bool) -> None: - if path.exists() and not force: - raise FileExistsError( - f"Refusing to overwrite existing file: {path}. Use --force to overwrite." - ) - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(content) - - -def iter_ancestors(path: Path): - current = path.resolve() - while True: - yield current - if current.parent == current: - break - current = current.parent - - -def lockfiles_for_directory(directory: Path) -> list[Path]: - lockfiles: list[Path] = [] - for lockfile, _ in LOCKFILE_TO_MANAGER: - candidate = directory / lockfile - if candidate.exists(): - lockfiles.append(candidate) - - pnpm_globs = ( - "pnpm-*.yaml", - "pnpm-*.yml", - ) - for pattern in pnpm_globs: - for candidate in sorted(directory.glob(pattern)): - if candidate not in lockfiles: - lockfiles.append(candidate) - return lockfiles - - -def manifests_for_directory(directory: Path) -> list[Path]: - manifests: list[Path] = [] - for filename in MANIFEST_FILENAMES: - candidate = directory / filename - if candidate.exists(): - manifests.append(candidate) - return manifests - - -def package_manager_from_lockfiles(directory: Path) -> str | None: - for candidate in lockfiles_for_directory(directory): - if candidate.name.startswith("pnpm-") and candidate.suffix in {".yaml", ".yml"}: - return "pnpm" - for lockfile, manager in LOCKFILE_TO_MANAGER: - if candidate.name == lockfile: - return manager - return None - - -def package_manager_from_manifest(manifest: dict) -> str | None: - raw_value = manifest.get("packageManager") - if not isinstance(raw_value, str) or not raw_value.strip(): - return None - manager = raw_value.split("@", 1)[0].strip().lower() - if manager in {"bun", "pnpm", "npm", "yarn"}: - return manager - return None - - -def read_text_file(path: Path) -> str | None: - try: - return path.read_text(errors="ignore") - except OSError: - return None - - -def package_manager_from_text(raw_text: str) -> str | None: - match = re.search( - r'(?mi)^[ \t]*["\']?packageManager["\']?[ \t]*:[ \t]*["\']?([^"\',\n\r#]+)', - raw_text, - ) - if match is None: - return None - - value = match.group(1).strip() - manager = value.split("@", 1)[0].strip().lower() - if manager in {"bun", "pnpm", "npm", "yarn"}: - return manager - return None - - -def manifest_text_uses_vitest(raw_text: str) -> bool: - return re.search(r"\bvitest\b", raw_text) is not None - - -def detect_package_manager_with_root(start: Path) -> tuple[str | None, Path | None]: - for directory in iter_ancestors(start): - for manifest_path in manifests_for_directory(directory): - if manifest_path.name == "package.json": - manifest = read_package_json(manifest_path) - if manifest is not None: - from_manifest = package_manager_from_manifest(manifest) - if from_manifest is not None: - return (from_manifest, directory) - - raw_text = read_text_file(manifest_path) - if raw_text is not None: - from_text = package_manager_from_text(raw_text) - if from_text is not None: - return (from_text, directory) - - from_lockfile = package_manager_from_lockfiles(directory) - if from_lockfile is not None: - return (from_lockfile, directory) - return (None, None) - - -def read_package_json(path: Path) -> dict | None: - try: - raw = path.read_text() - parsed = json.loads(raw) - except (OSError, json.JSONDecodeError): - return None - if isinstance(parsed, dict): - return parsed - return None - - -def manifest_uses_vitest(manifest: dict) -> bool: - dependency_fields = ( - "dependencies", - "devDependencies", - "peerDependencies", - "optionalDependencies", - ) - for field in dependency_fields: - deps = manifest.get(field) - if isinstance(deps, dict) and "vitest" in deps: - return True - - scripts = manifest.get("scripts") - if isinstance(scripts, dict): - for script in scripts.values(): - if isinstance(script, str) and "vitest" in script: - return True - - return False - - -def find_project_root(start: Path) -> Path | None: - for directory in iter_ancestors(start): - if package_manager_from_lockfiles(directory) is not None: - return directory - if manifests_for_directory(directory): - return directory - return None - - -def iter_to_ancestor(start: Path, ancestor: Path): - current = start.resolve() - target = ancestor.resolve() - while True: - yield current - if current == target: - break - if current.parent == current: - break - current = current.parent - - -def detect_vitest_usage_in_project(project_root: Path, manager_root: Path | None) -> bool: - stop_at = manager_root.resolve() if manager_root is not None else project_root.resolve() - for directory in iter_to_ancestor(project_root, stop_at): - for manifest_path in manifests_for_directory(directory): - if manifest_path.name == "package.json": - manifest = read_package_json(manifest_path) - if manifest and manifest_uses_vitest(manifest): - return True - - raw_text = read_text_file(manifest_path) - if raw_text is not None and manifest_text_uses_vitest(raw_text): - return True - - if (stop_at / "node_modules" / "vitest" / "package.json").exists(): - return True - - for lockfile in lockfiles_for_directory(stop_at): - try: - if "vitest" in lockfile.read_text(errors="ignore"): - return True - except OSError: - continue - - return False - - -def choose_test_template( - mode: str, package_manager: str | None, uses_vitest: bool -) -> tuple[str, str]: - if package_manager == "bun" and not uses_vitest: - return (f"{mode}-command.bun-test.ts.tpl", "bun:test") - return (f"{mode}-command.test.ts.tpl", "vitest") - - -def choose_test_command(package_manager: str | None, test_framework: str, test_path: str) -> str: - if test_framework == "bun:test": - return f"bun test {test_path}" - if package_manager == "bun": - return f"bun test {test_path}" - if package_manager == "pnpm": - return f"pnpm vitest run {test_path}" - if package_manager == "yarn": - return f"yarn vitest run {test_path}" - return f"npx vitest run {test_path}" - - -def format_run_path(path: Path, cwd: Path) -> str: - try: - relative = path.relative_to(cwd).as_posix() - if not relative.startswith((".", "..")): - return f"./{relative}" - return relative - except ValueError: - return path.as_posix() - - -def main() -> int: - parser = argparse.ArgumentParser( - description="Scaffold Bun-first DreamCLI starter files from templates." - ) - parser.add_argument("--name", required=True, help="CLI name (e.g. mycli)") - parser.add_argument( - "--mode", - choices=["single", "multi"], - default="single", - help="Starter shape. single=one root command, multi=nested command groups.", - ) - parser.add_argument("--out", required=True, help="Output directory") - parser.add_argument( - "--no-test", - action="store_true", - help="Skip generating the starter test file.", - ) - parser.add_argument( - "--force", - action="store_true", - help="Overwrite existing files if present.", - ) - args = parser.parse_args() - - cli_name = normalize_name(args.name) - if not cli_name: - print("[ERROR] --name must include at least one letter or digit.") - return 1 - - output_dir = Path(args.out).resolve() - output_dir.mkdir(parents=True, exist_ok=True) - - skill_root = Path(__file__).resolve().parent.parent - templates_dir = skill_root / "assets" / "templates" - - entry_template_path = templates_dir / f"{args.mode}-command.ts.tpl" - test_template_path = templates_dir / f"{args.mode}-command.test.ts.tpl" - - entry_filename = f"{cli_name}.ts" - entry_path = output_dir / entry_filename - test_path = output_dir / f"{cli_name}.test.ts" - include_test = not args.no_test - project_root = find_project_root(output_dir) or find_project_root(Path.cwd()) or output_dir - package_manager, manager_root = detect_package_manager_with_root(project_root) - uses_vitest = detect_vitest_usage_in_project(project_root, manager_root) - test_framework = "none" - - replacements = { - "__CLI_NAME__": cli_name, - "__ENTRY_FILE__": f"./{entry_filename}", - } - - try: - entry_template = read_template(entry_template_path) - entry_content = render_template(entry_template, replacements) - write_file(entry_path, entry_content, args.force) - print(f"[OK] Wrote {entry_path}") - - if include_test: - test_template_name, test_framework = choose_test_template( - args.mode, package_manager, uses_vitest - ) - test_template_path = templates_dir / test_template_name - test_template = read_template(test_template_path) - test_content = render_template(test_template, replacements) - write_file(test_path, test_content, args.force) - print(f"[OK] Wrote {test_path}") - except (FileExistsError, FileNotFoundError) as error: - print(f"[ERROR] {error}") - return 1 - - print("\nNext steps:") - run_path = format_run_path(entry_path, Path.cwd()) - test_run_path = format_run_path(test_path, Path.cwd()) - print(f"1. Run: bun {run_path} --help") - if include_test: - test_command = choose_test_command(package_manager, test_framework, test_run_path) - print(f"2. Test: {test_command}") - if test_framework == "bun:test": - print(" Detected Bun without vitest; generated a bun:test starter test.") - else: - print("2. Re-run without --no-test to include a starter test file") - print("3. Adapt commands, flags, and prompts to the user request") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/skills/cli-creation/SKILL.md b/skills/dreamcli/SKILL.md similarity index 75% rename from skills/cli-creation/SKILL.md rename to skills/dreamcli/SKILL.md index f2406a86..58e3e793 100644 --- a/skills/cli-creation/SKILL.md +++ b/skills/dreamcli/SKILL.md @@ -1,9 +1,9 @@ --- -name: cli-creation +name: dreamcli 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. --- -# CLI Creation +# DreamCLI ## Overview @@ -11,26 +11,19 @@ Create runnable DreamCLI starter CLIs and extend them with typed command patterns. This skill covers user-facing app code built **on** DreamCLI, not DreamCLI framework internals. -The baseline examples target DreamCLI 4.0. For argv transforms, check the installed -`CLIPluginHooks` type for `transformArgv` before generating code. - -Version 3 removed the DSL, made the default command the -root surface, and added a large typed-flag surface. Version 4 gave both -factories the same sources, so `.stdin()`, `.env()`, `.config()`, and -`.prompt()` are available on flags and positionals alike. Snippets below assume -both. - ## Quick Start -1. Choose a starter mode: - - `single`: one root command (`cli(name).default(command)`). - - `multi`: grouped command surface (`group('...').command(...)`). -2. Generate starter files: - - `python scripts/scaffold_cli.py --name mycli --mode single --out .` - - Tests are generated by default; add `--no-test` only when explicitly requested. - - Test template is auto-detected: Bun without Vitest uses `bun:test`; otherwise Vitest. +1. Create a project: `bunx --bun --package @kjanat/dreamcli dreamcli create mycli`. + Enter the project and install its dependencies with `cd mycli && bun install`. +2. To add starter files to an existing project, install DreamCLI there with + `bun add @kjanat/dreamcli` and run + `bunx --bun --package @kjanat/dreamcli dreamcli create mycli --out .`. + Tests are generated by default. DreamCLI uses `bun:test` only if the project’s + `packageManager` (or its lockfile if none is declared) identifies Bun and no + Vitest usage is detected. The runtime running DreamCLI does not affect this. + Otherwise, install Vitest as a dev dependency if it isn’t already available. 3. Run and validate generated files: - - Use the printed path from the scaffolder output, for example `bun ./mycli.ts --help`. + - Run the generated entrypoint, for example `bun ./src/cli.ts --help` in a new project. - Run the generated test unless `--no-test` was used. 4. Extend behavior with references: - `references/pattern-cookbook.md` — copy-ready, type-checked snippets. @@ -39,39 +32,27 @@ both. ## Looking Things Up -Prefer these over recalling API shapes from memory; they reflect the installed -or published version rather than training data. - -**The API, offline-ish, no repo needed.** If `deno` is on the system this works -regardless of whether the project installed from npm or JSR: +Use JSR's source-level API docs for the exact installed release. DreamCLI ships +the same release version on npm and JSR. From the consuming project after install: -```bash -deno doc jsr:@kjanat/dreamcli 2>/dev/null # root entry: builders, parsing, help, errors, every public type -deno doc jsr:@kjanat/dreamcli/completion 2>/dev/null # one subpath at a time; also /config, /json-schema, /prompt, /testkit, /runtime, /version, /schema -deno doc --json jsr:@kjanat/dreamcli 2>/dev/null # machine-readable, for scripted lookups -deno doc --filter=CLIBuilder jsr:@kjanat/dreamcli 2>/dev/null # one symbol +```sh +version=$(node -p "require('@kjanat/dreamcli/package.json').version") +deno doc --quiet --filter=command "jsr:@kjanat/dreamcli@$version" +deno doc --quiet --filter=runCommand "jsr:@kjanat/dreamcli@$version/testkit" ``` -`2>/dev/null` matters: deno writes download and type-check progress to stderr, -which otherwise swamps the documentation output. +Use `--json` for structured documentation, or omit `--filter` to list exports. +For a JSR-only project, use the exact version resolved in `deno.lock`. -Pin a version with `jsr:@kjanat/dreamcli@5.1.0` when the project is not on -latest. `--filter` takes a declaration name; it prints nothing for a name that -does not exist, which is itself a useful signal. +The website tracks current guides. Find a page in the index, then request its +authored Markdown using content negotiation or the direct raw URL: -**The docs site, as markdown.** Every page is authored markdown served under -`/raw/`, and any page URL returns markdown under content negotiation: - -```bash -curl -s https://dreamcli.kjanat.dev/llms.txt # index of every page, one line each -curl -s https://dreamcli.kjanat.dev/llms-full.txt # every page concatenated (~250 kB) -curl -s https://dreamcli.kjanat.dev/raw/guide/flags # one page, authored markdown -curl -sH 'Accept: text/markdown' https://dreamcli.kjanat.dev/guide/flags +```sh +curl -fsSL https://dreamcli.kjanat.dev/llms.txt +curl -fsSL -H 'Accept: text/markdown' https://dreamcli.kjanat.dev/guide/flags +curl -fsSL https://dreamcli.kjanat.dev/raw/guide/flags ``` -Start from `llms.txt` to find the right page, then fetch that page rather than -pulling `llms-full.txt` into context. - ## Grounding Sources Paths are relative to the dreamcli repository root. @@ -93,8 +74,7 @@ Paths are relative to the dreamcli repository root. ## Workflow Decision Tree -- Simple one-command utility → `--mode single`. -- Nested command groups (git/gh style) → `--mode multi`. +- Start with the generated command. Add new commands under `src/commands/` and register them in `src/cli.ts`. - Tests wanted from the start → do nothing, they are scaffolded by default. - Tests explicitly unwanted → add `--no-test`. - npm/tsx or Deno instructions → keep generated code unchanged and give the @@ -189,8 +169,7 @@ Assert output including trailing newlines. ## Resource Map -- `scripts/scaffold_cli.py` — generate Bun-first starter files and tests. -- `assets/templates/*.tpl` — source templates used by the scaffolder. +- `dreamcli create` (alias `dreamcli init`) — create a TypeScript CLI project or add starter files to an existing project. - `references/pattern-cookbook.md` — snippets by topic; all type-checked. - `references/consumer-workflow.md` — end-to-end flow from request to validation. - `references/runtime-notes.md` — runtime and package-manager execution guidance. diff --git a/skills/dreamcli/agents/openai.yaml b/skills/dreamcli/agents/openai.yaml new file mode 100644 index 00000000..04ac3fde --- /dev/null +++ b/skills/dreamcli/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "DreamCLI" + short_description: "Build typed DreamCLI consumer CLIs quickly" + default_prompt: "Use $dreamcli to scaffold a Bun-first DreamCLI CLI with tests." diff --git a/skills/cli-creation/references/consumer-workflow.md b/skills/dreamcli/references/consumer-workflow.md similarity index 77% rename from skills/cli-creation/references/consumer-workflow.md rename to skills/dreamcli/references/consumer-workflow.md index 3bd6c5c3..dbe2ed31 100644 --- a/skills/cli-creation/references/consumer-workflow.md +++ b/skills/dreamcli/references/consumer-workflow.md @@ -2,28 +2,30 @@ ## Goal -Build a consumer-facing CLI app with DreamCLI 3.x, starting from a working +Build a consumer-facing CLI app with DreamCLI, starting from a working template and ending with validated behavior. ## Inputs to confirm -- CLI name (`--name`). +- CLI name (positional argument). - Surface shape (`single` or `multi`). - Whether tests should be skipped (`--no-test`). -- Runtime the user runs on (Bun, npm/tsx, Deno). +- Runtime the user runs on (Bun, Node, Deno). - Whether the CLI needs machine-readable output, config files, or prompts — each adds declarations to the schema rather than code to the action. ## Implementation flow -1. Scaffold starter files. +1. Install DreamCLI in the existing project and scaffold starter files. ```bash - python scripts/scaffold_cli.py --name mycli --mode single --out . + bun add @kjanat/dreamcli + bunx --bun --package @kjanat/dreamcli dreamcli create mycli --out . ``` The scaffolder detects the package manager and Vitest usage to choose either - a `bun:test` or Vitest starter test template. + a `bun:test` or Vitest starter test template. If the test imports `vitest` + and the project does not already declare it, run `bun add -d vitest`. 2. Shape the command surface. @@ -53,7 +55,8 @@ template and ending with validated behavior. ```bash bun ./mycli.ts --help bun ./mycli.ts --json | jq . # stdout must parse - bun test ./mycli.test.ts + bun test ./mycli.test.ts # for bun:test + bunx --bun vitest run ./mycli.test.ts # for a standalone Vitest file ``` ## Done criteria diff --git a/skills/cli-creation/references/pattern-cookbook.md b/skills/dreamcli/references/pattern-cookbook.md similarity index 100% rename from skills/cli-creation/references/pattern-cookbook.md rename to skills/dreamcli/references/pattern-cookbook.md diff --git a/skills/cli-creation/references/runtime-notes.md b/skills/dreamcli/references/runtime-notes.md similarity index 50% rename from skills/cli-creation/references/runtime-notes.md rename to skills/dreamcli/references/runtime-notes.md index 84ee1bab..1d7e7a71 100644 --- a/skills/cli-creation/references/runtime-notes.md +++ b/skills/dreamcli/references/runtime-notes.md @@ -1,22 +1,33 @@ # Runtime Notes -## Bun-first commands +After `dreamcli create mycli`, enter the generated project and install its dependencies: -- Run CLI entrypoint: `bun mycli.ts --help` -- Run tests: `bun test mycli.test.ts` +```sh +cd mycli +npm install +npm start -- hello Jalapeño +npm test +npm run typecheck +``` + +With Bun, use `bun install`, `bun src/cli.ts hello Jalapeño`, and `bun run test` in that directory. Build the executable with `bun run build`. + +## Files added with `--out` + +For `dreamcli create mycli --out tools`, run `bun tools/mycli.ts --help`. +Run `bun test tools/mycli.test.ts` for `bun:test`, or `bunx --bun vitest run tools/mycli.test.ts` for Vitest. +With `--json`, the result contains absolute paths in `entry` and `test`; `--no-test` omits the latter. +The examples below use `--out .`. -The scaffolder prints path-aware run commands; use those exact printed paths when `--out` is not `.`. The scaffolder auto-detects test style: - Bun project + no detected Vitest usage: generate `bun:test` template. - Otherwise: generate Vitest template. - Package manager detection checks lockfiles (including `pnpm-*.yaml/.yml`) and manifest `packageManager` entries in `package.json`, `package.json5`, and `package.yaml/.yml`. -If Vitest template is generated inside a Bun project, `bun test` still runs those tests in this workflow. - ## npm/Node alternative -- Run CLI entrypoint: `npx tsx mycli.ts --help` +- Run CLI entrypoint in an ESM package (`"type": "module"`): `node mycli.ts --help` - Run tests: `npx vitest run mycli.test.ts` ## Deno alternative diff --git a/src/core/cli/cli-manifest.test.ts b/src/core/cli/cli-manifest.test.ts index ccdf8d2e..1fd7c332 100644 --- a/src/core/cli/cli-manifest.test.ts +++ b/src/core/cli/cli-manifest.test.ts @@ -785,6 +785,13 @@ describe('isMainModule', () => { expect(isMainModule(import.meta)).toBe(false); }); + it('recognizes the Node entry script when the runtime omits import.meta.main', () => { + const meta = { ...import.meta, filename: process.argv[1] }; + Reflect.deleteProperty(meta, 'main'); + expect(isMainModule(meta as ImportMeta)).toBe(true); + expect(isMainModule({ ...meta, filename: '/different/module.ts' } as ImportMeta)).toBe(false); + }); + it('is true when import.meta.main is set', () => { const meta: ImportMeta = { ...import.meta, main: true }; expect(isMainModule(meta)).toBe(true); diff --git a/src/core/cli/index.ts b/src/core/cli/index.ts index 7355c0fb..9a7640b3 100644 --- a/src/core/cli/index.ts +++ b/src/core/cli/index.ts @@ -53,6 +53,7 @@ import { acceptsArgv } from '#internals/core/schema/stdin.ts'; import type { RuntimeAdapter } from '#internals/runtime/adapter.ts'; import { exitAfterFlush } from '#internals/runtime/adapter.ts'; import { createAdapter } from '#internals/runtime/auto.ts'; +import { isMainModule } from '#internals/runtime/main-module.ts'; import { BACKSLASH, SLASH, stripTrailing } from '#internals/strings.ts'; import type { Builtins, BuiltinsConfig, BuiltinsDraft } from './builtins.ts'; import { normalizeBuiltins } from './builtins.ts'; @@ -2618,27 +2619,6 @@ function cli( }); } -/** - * Report whether the calling module is the process entrypoint, cross-runtime. - * - * Node, Bun, and Deno set `import.meta.main` on the module invoked directly; - * projects with the runtime's ambient types can read that property directly. - * This helper is a compatibility form for projects whose `tsconfig.json` `lib` - * override drops those `ImportMeta` extras: passing `import.meta` whole avoids - * a direct `.main` access without requiring global augmentation. - * - * @param meta - The calling module's `import.meta`. - * @returns `true` when the module was run as the entrypoint. - * - * @example - * ```ts - * if (isMainModule(import.meta)) cli('mycli').command(deploy).run(); - * ``` - */ -function isMainModule(meta: ImportMeta): boolean { - return meta.main === true; -} - // --- Exports export type { BuiltinMode, BuiltinName, Builtins, BuiltinsConfig } from './builtins.ts'; diff --git a/src/core/output/index.ts b/src/core/output/index.ts index 45b9f388..2c3f3d13 100644 --- a/src/core/output/index.ts +++ b/src/core/output/index.ts @@ -123,12 +123,12 @@ interface OutputOptions { /** * Resolved OSC 8 hyperlink support for `out.isHyperlinkSupported`. * - * When set, this wins over the `isTTY` fallback. Callers pass the + * JSON mode disables hyperlinks. Otherwise this overrides the `isTTY` fallback. Callers pass the * `NO_HYPERLINKS`/`FORCE_HYPERLINKS` (and `--no-hyperlinks`/`--hyperlinks`) * decision here via {@linkcode resolveHyperlinkOverride}, keeping `process` * access out of the output layer. * - * @defaultValue `isTTY` + * @defaultValue `!jsonMode && isTTY` */ readonly hyperlinks?: boolean; } @@ -215,9 +215,7 @@ function resolveOptions(options?: OutputOptions): ResolvedOutputOptions { // Explicit `color` wins; otherwise gate on TTY, JSON mode, and // environment support (NO_COLOR/FORCE_COLOR/--no-color/--color/CI). color: options?.color ?? (isTTY && !jsonMode && isColorSupported), - // Explicit `hyperlinks` (the caller-resolved env/argv override) wins; - // otherwise fall back to TTY. - isHyperlinkSupported: options?.hyperlinks ?? isTTY, + isHyperlinkSupported: !jsonMode && (options?.hyperlinks ?? isTTY), }; } @@ -292,7 +290,7 @@ class OutputChannel implements Out { this.verbosity = this.policy.verbosity; this.isTTY = options.isTTY; this.terminalSize = options.terminalSize; - this.color = createColors(options.color); + this.color = createColors(options.color, options.isHyperlinkSupported); this.isHyperlinkSupported = options.isHyperlinkSupported; // Bind methods to the instance so they keep working when destructured diff --git a/src/core/output/output.test.ts b/src/core/output/output.test.ts index 578dfa7e..02fb16b6 100644 --- a/src/core/output/output.test.ts +++ b/src/core/output/output.test.ts @@ -240,6 +240,23 @@ describe('isHyperlinkSupported', () => { expect(createOutput({ isTTY: false }).isHyperlinkSupported).toBe(false); }); + it.each([false, true])('applies the hyperlink policy to the palette with color=%s', (color) => { + const url = 'https://example.com/'; + const linked = createOutput({ color, isTTY: false, hyperlinks: true }); + const plain = createOutput({ color, isTTY: true, hyperlinks: false }); + expect(linked.color.link(url, 'docs')).toBe(`\x1b]8;;${url}\x1b\\docs\x1b]8;;\x1b\\`); + expect(plain.color.link(url, 'docs')).toBe('docs'); + }); + + it('keeps JSON string values plain on a TTY, including when links are forced', () => { + for (const options of [{}, { hyperlinks: true }]) { + const [out, captured] = createCaptureOutput({ isTTY: true, jsonMode: true, ...options }); + out.json({ name: out.color.link('https://example.com/', 'Scotch Bonnet') }); + expect(out.isHyperlinkSupported).toBe(false); + expect(JSON.parse(captured.stdout.join(''))).toEqual({ name: 'Scotch Bonnet' }); + } + }); + it('explicit hyperlinks option wins over isTTY', () => { expect(createOutput({ isTTY: false, hyperlinks: true }).isHyperlinkSupported).toBe(true); expect(createOutput({ isTTY: true, hyperlinks: false }).isHyperlinkSupported).toBe(false); diff --git a/src/core/prompt/prompt.test.ts b/src/core/prompt/prompt.test.ts index 91f06fc2..626d4230 100644 --- a/src/core/prompt/prompt.test.ts +++ b/src/core/prompt/prompt.test.ts @@ -265,6 +265,13 @@ describe('createTerminalPrompter', () => { expect(lines[0]).toContain('Name:'); }); + it('keeps a question mark as the input prompt delimiter', async () => { + const { write, lines } = captureWrite(); + const prompter = createTerminalPrompter(mockRead(['tools']), write); + await prompter.promptOne({ kind: 'input', message: 'Where should I create your CLI?' }); + expect(lines[0]).toBe('Where should I create your CLI? '); + }); + it('shows placeholder when set', async () => { const { write, lines } = captureWrite(); const prompter = createTerminalPrompter(mockRead(['test']), write); diff --git a/src/core/prompt/terminal.ts b/src/core/prompt/terminal.ts index 542ac272..a75c24d2 100644 --- a/src/core/prompt/terminal.ts +++ b/src/core/prompt/terminal.ts @@ -196,10 +196,11 @@ async function promptInput( if (config.kind === 'input' && config.placeholder !== undefined) hints.push(config.placeholder); if (config.kind === 'input' && config.default !== undefined && !config.sensitive) hints.push(`default: ${config.default}`); - const hint = hints.length > 0 ? ` (${hints.join(', ')})` : ''; + const label = hints.length > 0 ? `${config.message} (${hints.join(', ')})` : config.message; + const suffix = /[?:]$/.test(label) ? ' ' : ': '; while (retries < MAX_RETRIES) { - write(`${config.message}${hint}: `); + write(label + suffix); const line = await read(); if (line === null) return { answered: false }; diff --git a/src/core/schema/command.ts b/src/core/schema/command.ts index 9fbc1af6..b5ac19e1 100644 --- a/src/core/schema/command.ts +++ b/src/core/schema/command.ts @@ -253,10 +253,9 @@ interface Out { /** * Whether OSC 8 terminal hyperlinks should be emitted. * - * Honors explicit `--no-hyperlinks`/`--hyperlinks` argv flags first, then + * False in JSON mode. Otherwise honors explicit `--no-hyperlinks`/`--hyperlinks` flags, then * `NO_HYPERLINKS`, then `FORCE_HYPERLINKS`, falling back to `isTTY`. - * Handlers rendering their own `out.color.link(...)` output can gate on - * this to keep OSC 8 escapes out of piped or opted-out contexts. + * `out.color.link(url, label)` applies this policy automatically. */ readonly isHyperlinkSupported: boolean; diff --git a/src/create.test.ts b/src/create.test.ts new file mode 100644 index 00000000..7d1c8fe2 --- /dev/null +++ b/src/create.test.ts @@ -0,0 +1,281 @@ +/** Verify starter generation and destination safeguards. @module */ + +import { execFileSync } from 'node:child_process'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; +import { publishFiles } from './create/publish.ts'; +import type { ScaffoldOptions } from './create.ts'; +import { scaffold } from './create.ts'; + +function withProject(test: (directory: string) => void): void { + const directory = mkdtempSync(join(tmpdir(), 'dreamcli-create-')); + try { + test(directory); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +function runScaffold(cwd: string, options: ScaffoldOptions) { + return execFileSync( + process.execPath, + [ + ...(typeof Deno === 'undefined' ? ['-e'] : ['eval', '--ext=mjs']), + `import { scaffold } from ${JSON.stringify(new URL('./create.ts', import.meta.url).href)}; scaffold(${JSON.stringify(options)});`, + ], + { cwd, stdio: 'pipe' }, + ); +} + +describe('scaffold', () => { + it('creates a runnable npm project by default without touching an existing directory', () => { + withProject((directory) => { + runScaffold(directory, { name: 'My CLI' }); + const packageFile = join(directory, 'my-cli', 'package.json'); + const manifest = readFileSync(packageFile, 'utf8'); + expect(JSON.parse(manifest)).toMatchObject({ + name: 'my-cli', + type: 'module', + scripts: { start: 'node src/cli.ts', typecheck: 'tsc --noEmit', test: 'vitest run' }, + dependencies: { '@kjanat/dreamcli': expect.any(String) }, + devDependencies: { vitest: expect.any(String) }, + }); + expect(existsSync(join(directory, 'my-cli', 'src/commands/hello.test.ts'))).toBe(true); + expect(() => runScaffold(directory, { name: 'my-cli', force: true })).toThrow(/not empty/); + expect(readFileSync(packageFile, 'utf8')).toBe(manifest); + + runScaffold(directory, { name: 'no-test', test: false }); + const withoutTests = JSON.parse( + readFileSync(join(directory, 'no-test', 'package.json'), 'utf8'), + ); + expect(withoutTests.scripts).toMatchObject({ + start: 'node src/cli.ts', + typecheck: 'tsc --noEmit', + build: 'tsdown', + }); + expect(withoutTests.scripts.test).toBeUndefined(); + expect(withoutTests.devDependencies.vitest).toBeUndefined(); + expect(existsSync(join(directory, 'no-test', 'src/commands/hello.test.ts'))).toBe(false); + }); + }); + + it('writes build metadata, project guidance and the bundled skill together', () => { + withProject((directory) => { + const skillDirectory = fileURLToPath(new URL('../skills/dreamcli/', import.meta.url)); + const metadata = { + author: { name: 'Pepper Farmer', email: 'pepper@example.invalid' }, + repository: 'https://github.com/pepper-farmer/hot-sauce', + tsdownVersion: '1.2.3', + }; + const result = scaffold({ + directory, + name: 'hot-sauce', + metadata, + skillDirectory, + test: false, + }); + const read = (path: string) => readFileSync(join(directory, path), 'utf8'); + expect(JSON.parse(read('package.json'))).toMatchObject({ + author: metadata.author, + repository: { url: `git+${metadata.repository}.git` }, + bin: { 'hot-sauce': './dist/cli.mjs' }, + keywords: ['cli', 'dreamcli', 'ansispeck'], + devDependencies: { tsdown: '1.2.3' }, + scripts: { build: 'tsdown', prepack: 'npm run build' }, + }); + expect(read('CLAUDE.md')).toBe('@AGENTS.md\n'); + expect(read('AGENTS.md')).toContain('--filter=runCommand'); + expect(read('.github/workflows/ci.yml')).not.toContain('npm test'); + expect(read('README.md')).not.toContain('npm test'); + const skillPath = '.agents/skills/dreamcli/SKILL.md'; + expect(result.files).toContain(join(directory, skillPath)); + expect(read(skillPath)).toBe(readFileSync(join(skillDirectory, 'SKILL.md'), 'utf8')); + writeFileSync(join(directory, skillPath), 'custom'); + scaffold({ out: directory, name: 'other', force: true, skillDirectory }); + expect(read(skillPath)).toBe('custom'); + }); + }); + + it('uses native imports for Vitest in a project under a hash-marked parent directory', () => { + withProject((cwd) => { + const directory = join(cwd, 'Peppers #5', 'cli'); + scaffold({ name: 'peppers', directory }); + const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8')); + expect(manifest.scripts.test).toBe('vitest run --experimental.viteModuleRunner=false'); + }); + }); + + it('rejects a blank destination before resolving it to the working directory', () => { + withProject((cwd) => { + const entry = join(cwd, 'demo.ts'); + writeFileSync(entry, 'keep this file'); + for (const target of ['', ' ']) { + for (const destination of [{ out: target }, { directory: target }]) { + expect(() => runScaffold(cwd, { name: 'demo', ...destination, force: true })).toThrow( + /Provide a non-empty destination directory/, + ); + } + } + expect(readFileSync(entry, 'utf8')).toBe('keep this file'); + expect(readdirSync(cwd)).toEqual(['demo.ts']); + }); + }); + + it('uses an explicit project directory and keeps its existing parents', () => { + withProject((directory) => { + const target = join(directory, 'nested', 'My CLI'); + mkdirSync(target, { recursive: true }); + const result = scaffold({ name: 'My CLI', directory: target, test: false }); + expect(result.entry).toBe(join(target, 'src/cli.ts')); + expect(readFileSync(join(target, '.gitignore'), 'utf8')).toBe( + 'node_modules/\ncoverage/\ndist/\n*.tgz\n', + ); + expect(JSON.parse(readFileSync(join(target, 'package.json'), 'utf8')).name).toBe('my-cli'); + }); + }); + + it('leaves another publisher’s entry intact when a forced scaffold cannot acquire its lock', () => { + withProject((cwd) => { + const entry = join(cwd, 'demo.ts'); + const lock = `${entry}.dreamcli-lock`; + mkdirSync(lock); + writeFileSync(entry, 'first publisher'); + const options = { name: 'demo', out: cwd, force: true }; + expect(() => runScaffold(cwd, options)).toThrow(/destination is locked/); + expect(readFileSync(entry, 'utf8')).toBe('first publisher'); + expect(existsSync(join(cwd, 'demo.test.ts'))).toBe(false); + expect(existsSync(lock)).toBe(true); + + rmSync(lock, { recursive: true }); + expect(scaffold(options).files).toEqual([ + entry, + join(cwd, 'demo.test.ts'), + join(cwd, 'CLAUDE.md'), + join(cwd, 'AGENTS.md'), + ]); + }); + }); + + it('restores replaced files and removes new files when publication fails after staging', () => { + withProject((cwd) => { + const entry = join(cwd, 'demo.ts'); + writeFileSync(entry, 'original'); + // Staging the child creates its parent. Publishing a file at that same path must fail. + const paths = [entry, join(cwd, 'new.ts'), join(cwd, 'parent'), join(cwd, 'parent/child.ts')]; + const files = paths.map((path) => ({ path, content: 'replacement' })); + expect(() => publishFiles(files, true)).toThrow(/Refusing to overwrite existing file/); + expect(readdirSync(cwd)).toEqual(['demo.ts']); + expect(readFileSync(entry, 'utf8')).toBe('original'); + publishFiles(files.slice(0, 2), true); + expect(readFileSync(entry, 'utf8')).toBe('replacement'); + }); + }); + + it('cleans up newly created directories when staging is interrupted', () => { + withProject((cwd) => { + const occupied = join(cwd, 'occupied'); + mkdirSync(occupied); + expect(() => + publishFiles( + [ + { path: join(cwd, 'nested/deeper/entry.ts'), content: 'new' }, + { path: occupied, content: 'cannot replace a directory' }, + ], + true, + ), + ).toThrow(/regular file/); + expect(readdirSync(cwd)).toEqual(['occupied']); + }); + }); + + it('adds starter files under a nested destination in a Bun project', () => { + withProject((directory) => { + writeFileSync(join(directory, 'bun.lock'), '{}'); + const out = join(directory, 'src', 'cli'); + const result = scaffold({ name: ' My CLI! ', out }); + + expect(result).toEqual({ + name: 'my-cli', + entry: join(out, 'my-cli.ts'), + test: join(out, 'my-cli.test.ts'), + files: [ + join(out, 'my-cli.ts'), + join(out, 'my-cli.test.ts'), + join(out, 'CLAUDE.md'), + join(out, 'AGENTS.md'), + ], + testRunner: 'bun:test', + }); + const entry = readFileSync(result.entry, 'utf8'); + expect(entry).toContain("cli('my-cli')"); + expect(entry).toContain('.command(hello)'); + expect(readFileSync(join(out, 'my-cli.test.ts'), 'utf8')).toContain("from 'bun:test'"); + }); + }); + + it('uses Vitest for starter files when declared in a Bun workspace', () => { + withProject((directory) => { + writeFileSync( + join(directory, 'package.json'), + JSON.stringify({ packageManager: 'bun@1.4.5', devDependencies: { vitest: '^5.0.0' } }), + ); + const result = scaffold({ name: 'my-cli', out: directory }); + + expect(result.testRunner).toBe('vitest'); + expect(readFileSync(result.entry, 'utf8')).toContain("command('hello')"); + const test = readFileSync(join(directory, 'my-cli.test.ts'), 'utf8'); + expect(test).toContain("from 'vitest'"); + expect(test).toContain("import { hello } from './my-cli.ts'"); + }); + }); + + it('leaves the directory untouched when only the test file exists', () => { + withProject((directory) => { + const existing = join(directory, 'my-cli.test.ts'); + writeFileSync(existing, 'keep this'); + expect(() => scaffold({ name: 'my-cli', out: directory })).toThrow( + /--force|Refusing to overwrite/, + ); + expect(existsSync(join(directory, 'my-cli.ts'))).toBe(false); + expect(readFileSync(existing, 'utf8')).toBe('keep this'); + }); + }); + + it('replaces the entry with force and leaves the test alone when tests are disabled', () => { + withProject((directory) => { + const entry = join(directory, 'my-cli.ts'); + const test = join(directory, 'my-cli.test.ts'); + writeFileSync(entry, 'old entry'); + writeFileSync(test, 'keep this'); + for (const guide of ['CLAUDE.md', 'AGENTS.md']) + writeFileSync(join(directory, guide), 'team rules'); + const result = scaffold({ name: 'my-cli', out: directory, test: false, force: true }); + for (const guide of ['CLAUDE.md', 'AGENTS.md']) + expect(readFileSync(join(directory, guide), 'utf8')).toBe('team rules'); + expect(result).toEqual({ name: 'my-cli', entry, files: [entry] }); + expect(readFileSync(entry, 'utf8')).toContain("cli('my-cli')"); + expect(readFileSync(test, 'utf8')).toBe('keep this'); + }); + }); + + it('refuses to replace directories even with force', () => { + withProject((directory) => { + mkdirSync(join(directory, 'my-cli.test.ts')); + expect(() => scaffold({ name: 'my-cli', out: directory, force: true })).toThrow( + /regular file/, + ); + expect(existsSync(join(directory, 'my-cli.ts'))).toBe(false); + }); + }); +}); diff --git a/src/create.ts b/src/create.ts new file mode 100644 index 00000000..ade53ba6 --- /dev/null +++ b/src/create.ts @@ -0,0 +1,131 @@ +/** + * Generate DreamCLI starter files using the templates shipped with the package. + * + * @module @kjanat/dreamcli/create + */ + +import { lstatSync, readdirSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { CLIError } from './core/errors/index.ts'; +import { guidanceFiles } from './create/guidance.ts'; +import type { ProjectMetadata } from './create/project.ts'; +import { projectFiles } from './create/project.ts'; +import { publishFiles } from './create/publish.ts'; +import { + cliTemplate, + commandTemplate, + standaloneTemplate, + testTemplate, +} from './create/templates.ts'; +import { detectTestRunner } from './create/test-runner.ts'; + +export interface ScaffoldOptions { + /** CLI name. Converted to a lowercase, hyphen-separated filename. */ + readonly name: string; + /** Exact project directory. Defaults to a directory named after the CLI. */ + readonly directory?: string; + /** Write starter files into this directory instead of creating a named project. */ + readonly out?: string; + /** Generate a test file. Defaults to true. */ + readonly test?: boolean; + /** Replace existing starter files. Defaults to false. */ + readonly force?: boolean; + /** Project author, repository and resolved bundler version for a new project. */ + readonly metadata?: ProjectMetadata; + /** Copy this local DreamCLI skill directory into the destination. */ + readonly skillDirectory?: string; +} + +export interface ScaffoldResult { + /** Normalized CLI name. */ + readonly name: string; + /** Absolute path to the generated entrypoint. */ + readonly entry: string; + /** Absolute paths to all generated files. */ + readonly files: readonly string[]; + /** Absolute path to the generated test, when enabled. */ + readonly test?: string; + /** Import specifier for the generated test runner, when tests are enabled. */ + readonly testRunner?: 'bun:test' | 'vitest'; +} + +/** Normalize a project name for use as a package name and filename. */ +function normalizeProjectName(input: string): string | undefined { + const name = input + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, ''); + if (name === '' || name.length > 214 || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/.test(name)) { + return undefined; + } + + return name; +} + +/** Create a named npm project or add starter files to an explicit output directory. */ +export function scaffold(options: ScaffoldOptions): ScaffoldResult { + const name = normalizeProjectName(options.name); + if (name === undefined) { + throw new CLIError('Choose a CLI name that can be used as a filename.', { + code: 'SCAFFOLD_INVALID_NAME', + suggest: 'Use 1 to 214 letters, digits, or hyphens, such as my-cli.', + }); + } + + const project = options.out === undefined; + const target = options.out ?? options.directory ?? name; + if (target.trim() === '') { + throw new CLIError('Provide a non-empty destination directory.', { + code: 'SCAFFOLD_EMPTY_DIRECTORY', + exitCode: 2, + suggest: 'Use . to select the current directory explicitly.', + }); + } + const directory = resolve(target); + const entry = join(directory, project ? 'src/cli.ts' : `${name}.ts`); + const test = + options.test === false + ? undefined + : join(directory, project ? 'src/commands/hello.test.ts' : `${name}.test.ts`); + const testRunner = + test === undefined ? undefined : project ? 'vitest' : detectTestRunner(directory); + const files: { path: string; content: string }[] = [ + { + path: entry, + content: (project ? cliTemplate : standaloneTemplate).replace('__CLI_NAME__', name), + }, + ]; + if (project) + files.push({ path: join(directory, 'src/commands/hello.ts'), content: commandTemplate }); + if (test !== undefined && testRunner !== undefined) { + files.push({ + path: test, + content: testTemplate + .replace('__COMMAND_FILE__', project ? './hello.ts' : `./${name}.ts`) + .replace('__TEST_RUNNER__', testRunner), + }); + } + + if (project) { + files.push(...projectFiles(directory, name, test !== undefined, options.metadata ?? {})); + const existing = lstatSync(directory, { throwIfNoEntry: false }); + if (existing && (!existing.isDirectory() || readdirSync(directory).length > 0)) { + throw new CLIError(`Project directory is not empty or not a directory: ${directory}`, { + code: 'SCAFFOLD_PROJECT_EXISTS', + suggest: + 'Choose an empty directory or use --out to add starter files to an existing project.', + }); + } + } + + files.push(...guidanceFiles(directory, options.skillDirectory)); + publishFiles(files, !project && options.force === true); + + return { + name, + entry, + files: files.map(({ path }) => path), + ...(test !== undefined && { test }), + ...(testRunner !== undefined && { testRunner }), + }; +} diff --git a/src/create/git.test.ts b/src/create/git.test.ts new file mode 100644 index 00000000..2e361626 --- /dev/null +++ b/src/create/git.test.ts @@ -0,0 +1,62 @@ +/** Verify creation of the initial Git commit. @module */ + +import { execFileSync, spawnSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { expect, it } from 'vitest'; + +it.skipIf(spawnSync('git', ['--version']).status !== 0)( + 'commits only the starter files with generator provenance and skips an existing repository', + () => { + const root = mkdtempSync(join(tmpdir(), 'dreamcli-git-')); + try { + const config = join(root, 'gitconfig'); + writeFileSync(config, '[user]\n\tname = DreamCLI Test\n\temail = dreamcli@example.invalid\n'); + const inherited = Object.entries(process.env).filter( + ([key]) => !key.toUpperCase().startsWith('GIT_'), + ); + const env = { + ...Object.fromEntries(inherited), + GIT_CONFIG_GLOBAL: config, + GIT_CONFIG_NOSYSTEM: '1', + }; + const git = (cwd: string, ...args: string[]) => + execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim(); + const init = (cwd: string, extraEnv = {}) => + JSON.parse( + execFileSync( + typeof Deno === 'undefined' ? process.execPath : 'node', + [ + '-e', + `import { initGit } from ${JSON.stringify(new URL('../../bin/git.mjs', import.meta.url).href)}; console.log(JSON.stringify(initGit(process.cwd(), ['starter.ts'], '5.7.0', 'abc1234', process.env)));`, + ], + { cwd, env: { ...env, ...extraEnv }, encoding: 'utf8' }, + ), + ); + + const unrelated = join(root, 'unrelated'); + mkdirSync(unrelated); + git(unrelated, 'init'); + const project = join(root, 'project'); + mkdirSync(project); + writeFileSync(join(project, 'starter.ts'), 'export {};\n'); + writeFileSync(join(project, 'untracked.txt'), 'leave untracked\n'); + const result = init(project, { GIT_DIR: join(unrelated, '.git') }); + expect(result).toEqual({ commit: git(project, 'rev-parse', 'HEAD') }); + expect(git(project, 'log', '-1', '--format=%B')).toBe( + 'Initialize with dreamcli create 5.7.0\n\nDreamCLI-Revision: abc1234', + ); + expect(git(project, 'ls-tree', '--name-only', 'HEAD')).toBe('starter.ts'); + expect(git(unrelated, 'rev-list', '--all', '--count')).toBe('0'); + + const nested = join(project, 'nested'); + mkdirSync(nested); + expect(init(nested)).toEqual({ skipped: 'existing-repository' }); + expect(existsSync(join(nested, '.git'))).toBe(false); + expect(git(project, 'rev-list', '--count', 'HEAD')).toBe('1'); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }, +); diff --git a/src/create/guidance.ts b/src/create/guidance.ts new file mode 100644 index 00000000..e6fde732 --- /dev/null +++ b/src/create/guidance.ts @@ -0,0 +1,63 @@ +/** Agent instructions and the optional copy of the packaged DreamCLI skill. @module */ +import { lstatSync, readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +const instructions = `# Working with DreamCLI + +Use the JSR API reference for the version actually installed. DreamCLI releases +the same version on npm and JSR. From this project after installing dependencies: + +\`\`\`sh +version=$(node -p "require('@kjanat/dreamcli/package.json').version") +deno doc --quiet --filter=command "jsr:@kjanat/dreamcli@$version" +deno doc --quiet --filter=runCommand "jsr:@kjanat/dreamcli@$version/testkit" +\`\`\` + +Replace the filter with an exported symbol, omit it to list exports, or use +\`--json\` for structured API documentation. In a JSR-only project, use the exact +version in \`deno.lock\`. Browse the same version at +\`https://jsr.io/@kjanat/dreamcli@/doc\`. + +For usage examples, search the current guide index, then read one page as Markdown: + +\`\`\`sh +curl -fsSL https://dreamcli.kjanat.dev/llms.txt +curl -fsSL -H 'Accept: text/markdown' https://dreamcli.kjanat.dev/guide/flags +curl -fsSL https://dreamcli.kjanat.dev/raw/guide/flags +\`\`\` +`; + +export function guidanceFiles(directory: string, skillDirectory?: string) { + const files: { path: string; content: string; preserveExisting: boolean }[] = []; + const existing = (path: string) => lstatSync(path, { throwIfNoEntry: false }); + function add(path: string, content: string) { + if (!existing(path)) files.push({ path, content, preserveExisting: true }); + } + const agents = join(directory, 'AGENTS.md'); + const skill = join(directory, '.agents', 'skills', 'dreamcli'); + const installSkill = + skillDirectory !== undefined && + ['.agents', '.agents/skills', '.agents/skills/dreamcli'].every((part) => { + const item = existing(join(directory, part)); + return item === undefined || item.isDirectory(); + }); + const guide = + instructions + + (installSkill + ? '\nUse the [DreamCLI skill](.agents/skills/dreamcli/SKILL.md) for command design and testing patterns.\n' + : ''); + add(join(directory, 'CLAUDE.md'), existing(agents) ? guide : '@AGENTS.md\n'); + add(agents, guide); + function copySkill(from: string, to: string) { + for (const entry of readdirSync(from, { withFileTypes: true })) { + const source = join(from, entry.name); + const target = join(to, entry.name); + if (entry.isDirectory()) { + const item = existing(target); + if (item === undefined || item.isDirectory()) copySkill(source, target); + } else if (entry.isFile()) add(target, readFileSync(source, 'utf8')); + } + } + if (installSkill && skillDirectory !== undefined) copySkill(skillDirectory, skill); + return files; +} diff --git a/src/create/project.ts b/src/create/project.ts new file mode 100644 index 00000000..a75b5324 --- /dev/null +++ b/src/create/project.ts @@ -0,0 +1,127 @@ +/** Package, executable build and user documentation for a new CLI project. @module */ +import { join } from 'node:path'; +import { DREAMCLI_VERSION } from '../version.ts'; + +export interface ProjectMetadata { + readonly author?: { readonly name?: string; readonly email?: string }; + readonly repository?: string; + readonly tsdownVersion?: string; +} + +export function projectFiles( + directory: string, + name: string, + test: boolean, + metadata: ProjectMetadata, +) { + // Vite interprets these characters in module IDs. Native imports preserve the path. + const testScript = /[#?*]/.test(directory) + ? 'vitest run --experimental.viteModuleRunner=false' + : 'vitest run'; + const manifest = { + name, + version: '0.1.0', + private: true, + type: 'module', + keywords: ['cli', 'dreamcli', 'ansispeck'], + ...(metadata.author && { author: metadata.author }), + ...(metadata.repository && { + repository: { type: 'git', url: `git+${metadata.repository}.git` }, + }), + bin: { [name]: './dist/cli.mjs' }, + files: ['dist'], + scripts: { + start: 'node src/cli.ts', + typecheck: 'tsc --noEmit', + build: 'tsdown', + prepack: 'npm run build', + ...(test && { test: testScript }), + }, + engines: { node: '>=22.22.2' }, + dependencies: { '@kjanat/dreamcli': DREAMCLI_VERSION === 'dev' ? 'latest' : DREAMCLI_VERSION }, + devDependencies: { + '@types/node': '^22.0.0', + tsdown: metadata.tsdownVersion ?? '0.23.7', + typescript: '^6.0.3', + ...(test && { vitest: '^5.1.2' }), + }, + }; + const tsconfig = { + compilerOptions: { + target: 'ES2022', + module: 'NodeNext', + strict: true, + noEmit: true, + allowImportingTsExtensions: true, + types: ['node'], + }, + include: ['src', 'tsdown.config.ts'], + }; + const build = `import { defineConfig } from 'tsdown'; + +export default defineConfig({ + entry: ['src/cli.ts'], + platform: 'node', + format: 'esm', + fixedExtension: true, + dts: false, +}); +`; + const readme = `# ${name} + +A TypeScript CLI built with [DreamCLI](https://dreamcli.kjanat.dev/). + +## Run locally + +Use Node.js 24 LTS to develop and build the CLI. + +\`\`\`sh +npm install +npm start -- --help +npm start -- hello Jalapeño +\`\`\` + +Edit \`src/commands/hello.ts\` to change the greeting. Register additional +commands in \`src/cli.ts\`. Pass \`--json\` for machine-readable output. + +## Check and build + +\`\`\`sh +npm run typecheck +${test ? 'npm test\n' : ''}npm run build +node dist/cli.mjs --help +\`\`\` + +Commit your package lock after installing. GitHub Actions runs the checks on +pushes and pull requests. \`npm pack\` rebuilds the executable and produces +an installable tarball with the \`${name}\` command. + +See [AGENTS.md](./AGENTS.md) for version-matched framework documentation. +`; + const workflow = `name: CI +on: [push, pull_request] +permissions: + contents: read +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + package-manager-cache: false + - run: if [ -f package-lock.json ]; then npm ci; else npm install; fi + - run: npm run typecheck +${test ? ' - run: npm test\n' : ''} - run: npm run build + - run: node dist/cli.mjs --help +`; + return Object.entries({ + 'package.json': `${JSON.stringify(manifest, null, 2)}\n`, + 'tsconfig.json': `${JSON.stringify(tsconfig, null, 2)}\n`, + 'tsdown.config.ts': build, + '.gitignore': 'node_modules/\ncoverage/\ndist/\n*.tgz\n', + 'README.md': readme, + '.github/workflows/ci.yml': workflow, + }).map(([path, content]) => ({ path: join(directory, path), content })); +} diff --git a/src/create/publish.ts b/src/create/publish.ts new file mode 100644 index 00000000..1fe5444f --- /dev/null +++ b/src/create/publish.ts @@ -0,0 +1,131 @@ +/** Stage and publish scaffold files while holding exclusive locks on their destinations. @module */ + +import { + chmodSync, + linkSync, + lstatSync, + mkdirSync, + renameSync, + rmdirSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { dirname, join } from 'node:path'; +import { CLIError } from '../core/errors/index.ts'; + +function makeDirectory(path: string, created: string[]): void { + try { + mkdirSync(path); + created.push(path); + } catch (error) { + const { code } = error as NodeJS.ErrnoException; + if (code === 'EEXIST' && statSync(path, { throwIfNoEntry: false })?.isDirectory()) return; + if (code !== 'ENOENT' || dirname(path) === path) throw error; + makeDirectory(dirname(path), created); + makeDirectory(path, created); + } +} + +interface StagedFile { + path: string; + lock: string; + backup?: string; + published?: boolean; +} + +function lockFile(path: string): StagedFile { + const lock = `${path}.dreamcli-lock`; + try { + mkdirSync(lock, { mode: 0o700 }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; + throw new CLIError(`Scaffold destination is locked: ${path}`, { + code: 'SCAFFOLD_BUSY', + suggest: `Retry after the other scaffold finishes. If it was interrupted, inspect ${lock} before removing it.`, + }); + } + return { path, lock }; +} + +function stage(file: StagedFile, content: string, force: boolean): void { + const existing = lstatSync(file.path, { throwIfNoEntry: false }); + if (existing && !existing.isFile()) { + throw new CLIError(`Cannot replace a path that is not a regular file: ${file.path}`, { + code: 'SCAFFOLD_NOT_A_FILE', + }); + } + if (existing && !force) throw existingFile(file.path); + const source = join(file.lock, 'new'); + writeFileSync(source, content); + if (existing) { + chmodSync(source, existing.mode & 0o777); + file.backup = join(file.lock, 'original'); + linkSync(file.path, file.backup); + } +} + +function publish(file: StagedFile): void { + const source = join(file.lock, 'new'); + if (file.backup) renameSync(source, file.path); + else { + try { + linkSync(source, file.path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw existingFile(file.path); + throw error; + } + } + file.published = true; +} + +/** Acquire every destination before publishing. Retain its backup if a restore itself fails. */ +export function publishFiles( + files: readonly { path: string; content: string; preserveExisting?: boolean }[], + force: boolean, +): void { + const directories: string[] = []; + const staged: StagedFile[] = []; + const errors: unknown[] = []; + try { + for (const { path, content, preserveExisting } of files) { + makeDirectory(dirname(path), directories); + const file = lockFile(path); + staged.push(file); + stage(file, content, force && !preserveExisting); + } + for (const file of staged) publish(file); + } catch (error) { + errors.push(error); + } + const rollback = errors.length > 0; + for (const file of staged.reverse()) { + try { + if (rollback && file.published) { + if (file.backup) renameSync(file.backup, file.path); + else rmSync(file.path); + } + rmSync(file.lock, { recursive: true }); + } catch (error) { + errors.push(error); + } + } + if (rollback) { + for (const path of directories.reverse()) { + try { + rmdirSync(path); + } catch { + // A concurrent writer may have populated this directory. + } + } + } + if (errors.length === 1) throw errors[0]; + if (errors.length > 1) throw new AggregateError(errors, 'Could not clean up scaffold files.'); +} + +function existingFile(path: string): CLIError { + return new CLIError(`Refusing to overwrite existing file: ${path}`, { + code: 'SCAFFOLD_FILE_EXISTS', + suggest: 'Use --force to replace the existing starter file.', + }); +} diff --git a/src/create/templates.ts b/src/create/templates.ts new file mode 100644 index 00000000..60e1c76c --- /dev/null +++ b/src/create/templates.ts @@ -0,0 +1,74 @@ +/** Templates for a DreamCLI project and for adding starter files to an existing project. @module */ + +const hello = `export const hello = command('hello') + .description('Say hello') + .arg('name', arg.string().default('World').describe('Who to greet')) + .action(({ args, out }) => { + const message = \`Hello, \${args.name}!\`; + if (out.jsonMode) out.json({ message }); + else out.log(out.color.green(message)); + }); +`; + +export const commandTemplate = `import { arg, command } from '@kjanat/dreamcli'; + +${hello}`; + +export const cliTemplate = `#!/usr/bin/env node + +import { cli } from '@kjanat/dreamcli'; +import { hello } from './commands/hello.ts'; + +await cli('__CLI_NAME__') + .manifest({ from: import.meta }) + .links() + .help({ commandHeader: true }) + .command(hello) + .run(); +`; + +export const standaloneTemplate = `import { realpathSync } from 'node:fs'; +import { arg, cli, command, isMainModule } from '@kjanat/dreamcli'; +import { createAdapter } from '@kjanat/dreamcli/runtime'; + +${hello} +// DreamCLI 5.7.0 relies on import.meta.main, absent on early Node 24. +function isNodeEntry(): boolean { + const entry = createAdapter().argv[1]; + if (!entry) return false; + try { + return realpathSync(entry) === import.meta.filename; + } catch { + return false; + } +} + +if (isMainModule(import.meta) || (import.meta.main === undefined && isNodeEntry())) { + await cli('__CLI_NAME__') + .manifest({ from: import.meta }) + .links() + .help({ commandHeader: true }) + .command(hello) + .run(); +} +`; + +export const testTemplate = `import { runCommand } from '@kjanat/dreamcli/testkit'; +import { expect, it } from '__TEST_RUNNER__'; +import { hello } from '__COMMAND_FILE__'; + +it('greets the name passed on the command line', async () => { + const result = await runCommand(hello, ['Jalapeño']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toEqual(['Hello, Jalapeño!\\n']); +}); + +it('writes a JSON greeting to stdout with --json', async () => { + const result = await runCommand(hello, ['Jalapeño', '--json']); + + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout.join(''))).toEqual({ message: 'Hello, Jalapeño!' }); + expect(result.stderr).toEqual([]); +}); +`; diff --git a/src/create/test-runner.ts b/src/create/test-runner.ts new file mode 100644 index 00000000..3c33b0ba --- /dev/null +++ b/src/create/test-runner.ts @@ -0,0 +1,91 @@ +/** Select the starter test template for the destination project. @module */ + +import type { Dirent } from 'node:fs'; +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; + +const manifests = ['package.json', 'package.json5', 'package.yaml', 'package.yml']; +const lockfiles = [ + 'bun.lock', + 'bun.lockb', + 'pnpm-lock.yaml', + 'pnpm-lock.yml', + 'pnpm-workspace.yaml', + 'pnpm-workspace.yml', + 'yarn.lock', + 'package-lock.json', + 'npm-shrinkwrap.json', +]; + +function readOptional(path: string): string { + try { + return readFileSync(path, 'utf8'); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'EISDIR' || code === 'EACCES') + return ''; + throw error; + } +} + +function projectLocks(directory: string): string[] { + let names: Dirent[]; + try { + names = readdirSync(directory, { withFileTypes: true }); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'EACCES' || code === 'EPERM') return []; + throw error; + } + return [ + ...lockfiles.filter((name) => + names.some((entry) => !entry.isDirectory() && entry.name === name), + ), + ...names + .filter( + (entry) => + !entry.isDirectory() && + /^pnpm-.*\.ya?ml$/.test(entry.name) && + !lockfiles.includes(entry.name), + ) + .map((entry) => entry.name) + .sort(), + ]; +} + +function detectProject(start: string): 'bun:test' | 'vitest' | undefined { + let hasProject = false; + let hasVitest = false; + for (let directory = start; ; directory = dirname(directory)) { + const manifestPaths = manifests.map((name) => join(directory, name)).filter(existsSync); + const locks = projectLocks(directory); + const contents = manifestPaths.map(readOptional); + hasProject ||= contents.length > 0 || locks.length > 0; + hasVitest ||= + contents.some((content) => /\bvitest\b/.test(content)) || + existsSync(join(directory, 'node_modules', 'vitest', 'package.json')); + + const declared = contents + .map( + (content) => + /(?:^|[,{\n])\s*["']?packageManager["']?\s*:\s*["']?(bun|npm|pnpm|yarn)(?=[@\s"',}#]|$)/.exec( + content, + )?.[1], + ) + .find((manager) => manager !== undefined); + const lock = locks[0]; + if (declared !== undefined || lock !== undefined) { + const isBun = declared === undefined ? lock?.startsWith('bun.') : declared === 'bun'; + if (!isBun) return 'vitest'; + hasVitest ||= locks.some((filename) => + /\bvitest\b/.test(readOptional(join(directory, filename))), + ); + return hasVitest ? 'vitest' : 'bun:test'; + } + if (dirname(directory) === directory) return hasProject ? 'vitest' : undefined; + } +} + +export function detectTestRunner(directory: string): 'bun:test' | 'vitest' { + return detectProject(directory) ?? detectProject(resolve('.')) ?? 'vitest'; +} diff --git a/src/runtime/adapter.ts b/src/runtime/adapter.ts index b9a1c7a0..b1333b40 100644 --- a/src/runtime/adapter.ts +++ b/src/runtime/adapter.ts @@ -89,6 +89,9 @@ interface RuntimeAdapter { /** Whether stdin is connected to a TTY (used for prompt gating). */ readonly stdinIsTTY: boolean; + /** Whether prompts written to stderr are visible on a terminal. */ + readonly stderrIsTTY?: boolean; + /** Read current terminal dimensions for stdout, if available. */ readonly getTerminalSize: () => TerminalSize | undefined; @@ -245,6 +248,9 @@ interface TestAdapterOptions { /** TTY flag for stdin (defaults to `false`). */ readonly stdinIsTTY?: boolean; + /** Set the test adapter's stderr terminal state. Defaults to false. */ + readonly stderrIsTTY?: boolean; + /** Terminal dimensions returned by `getTerminalSize()`. */ readonly terminalSize?: TerminalSize; @@ -399,6 +405,7 @@ function createTestAdapter(options?: TestAdapterOptions): RuntimeAdapter { }, isTTY: options?.isTTY ?? false, stdinIsTTY, + stderrIsTTY: options?.stderrIsTTY ?? false, getTerminalSize: () => options?.terminalSize, onTerminalResize: (listener) => options?.onTerminalResize?.(listener), exit: diff --git a/src/runtime/deno.test.ts b/src/runtime/deno.test.ts index 20ec8b2f..30fff4fa 100644 --- a/src/runtime/deno.test.ts +++ b/src/runtime/deno.test.ts @@ -418,6 +418,15 @@ describe('createDenoAdapter', () => { expect(adapter.isTTY).toBe(false); }); + it('uses stderr.isTerminal for the prompt output stream when available', () => { + const adapter = createDenoAdapter( + mockDeno({ stderr: { isTerminal: () => true, writeSync: () => 0 } }), + ); + expect(adapter.isTTY).toBe(false); + expect(adapter.stderrIsTTY).toBe(true); + expect(createDenoAdapter(mockDeno()).stderrIsTTY).toBe(false); + }); + it('stdinIsTTY is true when stdin.isTerminal() returns true', () => { const ns = mockDeno({ stdin: { isTerminal: () => true, readable: mockReadableStream([]) }, diff --git a/src/runtime/deno.ts b/src/runtime/deno.ts index 33c5b9da..afae1ee6 100644 --- a/src/runtime/deno.ts +++ b/src/runtime/deno.ts @@ -101,6 +101,8 @@ interface DenoNamespace { /** Standard error — synchronous byte writer. */ readonly stderr: { + /** Whether stderr is connected to a terminal. */ + isTerminal?(): boolean; /** Write raw bytes to stderr synchronously. */ writeSync(p: Uint8Array): number; }; @@ -347,6 +349,7 @@ function createDenoAdapter(ns?: DenoNamespace): RuntimeAdapter { ...(input.readSecret !== undefined ? { readSecret: input.readSecret } : {}), readStdin: () => readDenoStdinAll(d, stdinIsTTY), isTTY: d.stdout.isTerminal(), + stderrIsTTY: d.stderr.isTerminal?.() ?? false, stdinIsTTY, getTerminalSize: () => readDenoTerminalSize(d), onTerminalResize: (listener) => onDenoTerminalResize(d, listener), diff --git a/src/runtime/main-module.ts b/src/runtime/main-module.ts new file mode 100644 index 00000000..20d4e07d --- /dev/null +++ b/src/runtime/main-module.ts @@ -0,0 +1,27 @@ +/** Detect direct module execution across supported runtimes. @module */ + +/** + * Report whether the calling module is the process entrypoint, cross-runtime. + * + * Uses the runtime's native `import.meta.main` when available. On older Node + * releases, compare the module filename with the resolved entry script. + * + * @param meta - The calling module's `import.meta`. + * @returns `true` when the module was run as the entrypoint. + * + * @example + * ```ts + * if (isMainModule(import.meta)) cli('mycli').command(deploy).run(); + * ``` + */ +export function isMainModule(meta: ImportMeta): boolean { + if (typeof meta.main === 'boolean') return meta.main; + const entry = globalThis.process?.argv[1]; + if (!entry || !meta.filename) return false; + if (entry === meta.filename) return true; + try { + return globalThis.process.getBuiltinModule('fs').realpathSync(entry) === meta.filename; + } catch { + return false; + } +} diff --git a/src/runtime/node.ts b/src/runtime/node.ts index 1d8d3dbd..84b47fdd 100644 --- a/src/runtime/node.ts +++ b/src/runtime/node.ts @@ -77,6 +77,7 @@ interface NodeProcess { }; /** Standard error stream with write. */ readonly stderr: { + readonly isTTY?: boolean; on?(event: 'error', listener: (error: Error) => void): unknown; write(data: string, callback?: (error?: Error | null) => void): unknown; }; @@ -279,6 +280,7 @@ function createNodeAdapter(proc?: NodeProcess): RuntimeAdapter { ...(input.readSecret !== undefined ? { readSecret: input.readSecret } : {}), readStdin: () => readNodeStdinAll(p, stdinIsTTY), isTTY: p.stdout.isTTY === true, + stderrIsTTY: p.stderr.isTTY === true, stdinIsTTY, getTerminalSize: () => readNodeTerminalSize(p), onTerminalResize: (listener) => onNodeTerminalResize(p, listener), diff --git a/src/runtime/runtime.test.ts b/src/runtime/runtime.test.ts index 89f3f76a..7332622d 100644 --- a/src/runtime/runtime.test.ts +++ b/src/runtime/runtime.test.ts @@ -290,6 +290,16 @@ describe('createNodeAdapter', () => { expect(adapter.stdinIsTTY).toBe(true); }); + it('reports the prompt output terminal independently of stdout', () => { + const adapter = createNodeAdapter( + mockNodeProcess({ stderr: { isTTY: true, write: immediateWrite } }), + ); + expect(adapter.isTTY).toBe(false); + expect(adapter.stderrIsTTY).toBe(true); + expect(createTestAdapter({ isTTY: true }).stderrIsTTY).toBe(false); + expect(createTestAdapter({ stderrIsTTY: true }).stderrIsTTY).toBe(true); + }); + it('routes stdout writes to process.stdout.write', () => { const writeFn = vi.fn(); const mockProc = mockNodeProcess({ stdout: { isTTY: false, write: writeFn } }); diff --git a/tsconfig.json b/tsconfig.json index 8b7d87e7..8e9f154c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -31,6 +31,7 @@ "@kjanat/dreamcli/package.json": ["./package.json"], "@kjanat/dreamcli/completion": ["./src/completion.ts"], "@kjanat/dreamcli/config": ["./src/config.ts"], + "@kjanat/dreamcli/create": ["./src/create.ts"], "@kjanat/dreamcli/json-schema": ["./src/json-schema.ts"], "@kjanat/dreamcli/prompt": ["./src/prompt.ts"], "@kjanat/dreamcli/version": ["./src/version.ts"] diff --git a/tsdown.config.ts b/tsdown.config.ts index afd5baae..dc43b1db 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -11,6 +11,7 @@ export const entries = { index: 'src/index.ts', completion: 'src/completion.ts', config: 'src/config.ts', + create: 'src/create.ts', 'json-schema': 'src/json-schema.ts', prompt: 'src/prompt.ts', runtime: 'src/runtime.ts',