@rhythmjs/cli 0.0.12 → 0.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @rhythmjs/cli
2
2
 
3
- The command-line layer of Rhythm, the Bun-native backend framework: CLI command routing on top of the `@rhythmjs/rhythm` kernel. `RhythmCli` matches commands against argv positional tokens with a simple linear scan (appropriate for the handful-to-dozens of commands a real CLI has), supports prefixes and nested command groups, and mounts flat into a parent `Rhythm` app via `.use(cli.commands())`, so an unmatched command correctly falls through to whatever's registered after it.
3
+ The command-line layer of Rhythm, the Bun-native backend framework: CLI command routing on top of the `@rhythmjs/rhythm` kernel. `RhythmCli` matches commands against argv positional tokens with a simple linear scan (appropriate for the handful-to-dozens of commands a real CLI has), supports prefixes and nested command groups, and mounts flat into a parent `Rhythm` app via `.use(cli.middleware())`, so an unmatched command correctly falls through to whatever's registered after it.
4
4
 
5
- `RhythmCli` is not an app and does not extend `Rhythm`; it is a controller that compiles commands and middleware down to a single middleware (`.commands()`). It shares the core middleware contract (`compose`, `Middleware`, `next(extra)`), but has no `provide()` or `register()`, and it can't be served on its own: a `Rhythm` app is always the host that owns the lifecycle.
5
+ `RhythmCli` is not an app and does not extend `Rhythm`; it is a controller that compiles commands and middleware down to a single middleware (`.middleware()`). It shares the core middleware contract (`compose`, `Middleware`, `derive`; `next()` takes no arguments, extend the context with `derive()`), but has no `provide()` or `register()`, and it can't be served on its own: a `Rhythm` app is always the host that owns the lifecycle.
6
6
 
7
7
  ## Example
8
8
 
@@ -16,7 +16,7 @@ const cli = new RhythmCli().command("deploy :environment", (ctx) => {
16
16
  ctx.response.print(`deploying to ${ctx.args.environment}`);
17
17
  });
18
18
 
19
- const app = new Rhythm<RhythmCliContext>().use(cli.commands());
19
+ const app = new Rhythm<RhythmCliContext>().use(cli.middleware());
20
20
  process.exitCode = await toCliHandler(app)(process.argv.slice(2));
21
21
  ```
22
22
 
@@ -30,15 +30,16 @@ A fuller runnable version, including nested command groups and interactive promp
30
30
  - **`ctx.stdin`**: a `ReadableStream`, or `null` when stdin is a TTY (nothing piped in).
31
31
  - **Interactive prompts**: `createPrompt()` gives `text()`/`confirm()`/`select()`/`multiSelect()` (the latter two support an `allowCustom` option that adds a "type your own" choice). Wire it in via a `.provide()` on the host `Rhythm` app; see the example.
32
32
  - **Prefixes compose across nesting**: a child cli mounted into a prefixed parent via `.use(child)` gets the parent's prefix segments joined onto every one of its commands, at any nesting depth. Mounting copies the child's commands and middleware at that moment; commands added to the child afterwards don't appear in the parent, and the child keeps working standalone.
33
- - **Registration order is execution order**: a `.use()` middleware wraps only the commands registered after it; commands registered before it are untouched, and a matched command that doesn't call `next()` returns without reaching anything registered later. An unmatched command falls through, entry by entry, to the outer `next()`.
34
- - **A cli is a controller, not a module**: it has no `provide()` or `register()`, and it cannot be `register()`ed into a `Rhythm` app either; `register()` composes `Rhythm` modules only. A cli mounts into an app exactly one way: koa-style, via `.use(cli.commands())`.
33
+ - **Registration order is execution order**: a `.use()` middleware wraps only the commands registered after it, and runs only when one of them matches the argv (so a guard never answers `help` or another cli's commands); a mounted cli (`.use(child.middleware())`) always runs; commands registered before it are untouched, and a matched command that doesn't call `next()` returns without reaching anything registered later. An unmatched command falls through, entry by entry, to the outer `next()`.
34
+ - **A cli is a controller, not a module**: it has no `provide()` or `register()`, and it cannot be `register()`ed into a `Rhythm` app either; `register()` composes `Rhythm` modules only. A cli mounts into an app exactly one way: koa-style, via `.use(cli.middleware())`.
35
35
 
36
36
  ## API
37
37
 
38
38
  - `new RhythmCli(options?)`: `options.prefix` (space-separated, e.g. `"remote"`).
39
- - `.command(path, ...handlers)`: register a command; `path` is space-separated and may contain `:param` tokens (e.g. `"deploy :environment"`).
39
+ - `.command(path, ...handlers)`: register a command; `path` is space-separated and may contain `:param` tokens (e.g. `"deploy :environment"`). A trailing `:param?` is optional (e.g. `"new :name?"`): `ctx.args.param` is left out when the token is absent. Optional params must come last. A trailing `**` is a catch-all, like the router: it captures the remaining positionals into `ctx.args._`, joined by spaces, and is absent when there are none (e.g. `"run :script **"`). Order is required, then optional, then at most one catch-all.
40
40
  - `.use(fn)`: plain middleware. `.use(child)`: mount a nested `RhythmCli` (prefixes compose).
41
- - `.commands()`: this CLI as a plain middleware, for mounting into a `Rhythm` app via `.use()`; the cli's only way onto a runtime. Note: mounting a _cli_ into a _cli_ must use `.use(child)`, not `.use(child.commands())`, because an opaque middleware can't have the parent's prefix applied to its commands.
41
+ - `.middleware()`: this CLI as a plain middleware, for mounting into a `Rhythm` app via `.use()`; the cli's only way onto a runtime. Note: mounting a _cli_ into a _cli_ must use `.use(child)`, not `.use(child.commands())`, because an opaque middleware can't have the parent's prefix applied to its commands.
42
+ - `.entries`: a read-only snapshot of registered middlewares and commands, in order. `.middleware()` is tagged with the cli as its source, so a parent module lists it in `sources`.
42
43
  - `toCliHandler(app)`: bridges a `Rhythm` app to `(argv: string[]) => Promise<number>`.
43
44
  - `createPrompt()`: a `{ text, confirm, select, multiSelect }` prompt reading lines through Bun's async-iterable `console`, for use inside a `.provide()` on the host app.
44
45
 
@@ -6,12 +6,21 @@ export interface RhythmCliCommandContext {
6
6
  export interface RhythmCliOptions {
7
7
  prefix?: string;
8
8
  }
9
- export declare class RhythmCli<TContext extends RhythmCliContext = RhythmCliContext> {
9
+ export type CliEntry = {
10
+ readonly kind: "middleware";
11
+ readonly fn: Middleware<any>;
12
+ } | {
13
+ readonly kind: "command";
14
+ readonly segments: readonly string[];
15
+ readonly handlers: readonly Middleware<any>[];
16
+ };
17
+ export declare class RhythmCli<TContext extends RhythmCliContext = RhythmCliContext, TInput extends RhythmCliContext = TContext> {
10
18
  #private;
11
19
  constructor(options?: RhythmCliOptions);
12
- use<TExtra extends object>(fn: DeriveMiddleware<TContext, TExtra>): RhythmCli<TContext & TExtra>;
20
+ get entries(): readonly CliEntry[];
21
+ use<TExtra extends object>(fn: DeriveMiddleware<TContext, TExtra>): RhythmCli<TContext & TExtra, TInput>;
13
22
  use(fn: Middleware<TContext>): this;
14
23
  command<TExtra extends object>(path: string, middleware: DeriveMiddleware<TContext & RhythmCliCommandContext, TExtra>, ...handlers: Middleware<TContext & RhythmCliCommandContext & TExtra>[]): this;
15
24
  command(path: string, ...handlers: Middleware<TContext & RhythmCliCommandContext>[]): this;
16
- middleware(): Middleware<TContext>;
25
+ middleware(): Middleware<TInput>;
17
26
  }
@@ -5,24 +5,45 @@ import {
5
5
 
6
6
  // src/rhythm-cli.ts
7
7
  import { compose } from "@rhythmjs/rhythm/compose";
8
+ import { sourceOf, withSource } from "@rhythmjs/rhythm/source";
8
9
  function toSegments(command) {
9
10
  return command.trim().split(/\s+/).filter(Boolean);
10
11
  }
12
+ var isOptional = (segment) => segment.startsWith(":") && segment.endsWith("?");
13
+ var isCatchAll = (segment) => segment === "**";
11
14
  function matchCommand(pattern, positionals) {
12
- if (pattern.length !== positionals.length)
15
+ const catchAll = isCatchAll(pattern.at(-1));
16
+ const fixed = catchAll ? pattern.slice(0, -1) : pattern;
17
+ const required = fixed.filter((segment) => !isOptional(segment)).length;
18
+ if (positionals.length < required || !catchAll && positionals.length > fixed.length)
13
19
  return null;
14
20
  const params = {};
15
- for (let i = 0;i < pattern.length; i++) {
16
- const segment = pattern[i];
21
+ for (let i = 0;i < fixed.length; i++) {
22
+ const segment = fixed[i];
17
23
  const token = positionals[i];
18
24
  if (segment.startsWith(":")) {
19
- params[segment.slice(1)] = token;
25
+ if (token !== undefined)
26
+ params[segment.slice(1, isOptional(segment) ? -1 : undefined)] = token;
20
27
  } else if (segment !== token) {
21
28
  return null;
22
29
  }
23
30
  }
31
+ if (catchAll && positionals.length > fixed.length) {
32
+ params._ = positionals.slice(fixed.length).join(" ");
33
+ }
24
34
  return params;
25
35
  }
36
+ function assertValidPattern(path, segments) {
37
+ const rank = (segment) => isCatchAll(segment) ? 2 : isOptional(segment) ? 1 : 0;
38
+ for (let i = 1;i < segments.length; i++) {
39
+ if (rank(segments[i]) < rank(segments[i - 1])) {
40
+ throw new TypeError(`optional params and a catch-all must come last, in that order, in command "${path}"`);
41
+ }
42
+ }
43
+ if (segments.filter(isCatchAll).length > 1) {
44
+ throw new TypeError(`command "${path}" has more than one catch-all`);
45
+ }
46
+ }
26
47
 
27
48
  class RhythmCli {
28
49
  #options;
@@ -30,6 +51,9 @@ class RhythmCli {
30
51
  constructor(options = {}) {
31
52
  this.#options = options;
32
53
  }
54
+ get entries() {
55
+ return [...this.#entries];
56
+ }
33
57
  get #prefixSegments() {
34
58
  return this.#options.prefix ? toSegments(this.#options.prefix) : [];
35
59
  }
@@ -40,10 +64,21 @@ class RhythmCli {
40
64
  return this;
41
65
  }
42
66
  command(path, ...handlers) {
43
- this.#entries.push({ kind: "command", segments: [...this.#prefixSegments, ...toSegments(path)], handlers });
67
+ const segments = toSegments(path);
68
+ assertValidPattern(path, segments);
69
+ this.#entries.push({ kind: "command", segments: [...this.#prefixSegments, ...segments], handlers });
44
70
  return this;
45
71
  }
46
72
  #compile() {
73
+ const groups = [];
74
+ const reaches = (ctx, from) => {
75
+ const { positionals } = parseArgv2(ctx.argv);
76
+ for (let g = from;g < groups.length; g++) {
77
+ if (groups[g].some((command) => matchCommand(command.segments, positionals)))
78
+ return true;
79
+ }
80
+ return false;
81
+ };
47
82
  const dispatchFor = (compiled) => {
48
83
  return async (ctx, next) => {
49
84
  const { positionals } = parseArgv2(ctx.argv);
@@ -62,7 +97,9 @@ class RhythmCli {
62
97
  while (i < this.#entries.length) {
63
98
  const entry = this.#entries[i];
64
99
  if (entry.kind === "middleware") {
65
- stack.push(entry.fn);
100
+ const { fn } = entry;
101
+ const from = groups.length;
102
+ stack.push(sourceOf(fn) ? fn : (ctx, next) => reaches(ctx, from) ? fn(ctx, next) : next());
66
103
  i++;
67
104
  continue;
68
105
  }
@@ -74,15 +111,16 @@ class RhythmCli {
74
111
  compiled.push({ segments: command.segments, dispatch: compose(command.handlers) });
75
112
  i++;
76
113
  }
114
+ groups.push(compiled);
77
115
  stack.push(dispatchFor(compiled));
78
116
  }
79
117
  return compose(stack);
80
118
  }
81
119
  middleware() {
82
120
  const fn = this.#compile();
83
- return async (ctx, next) => {
121
+ return withSource(async (ctx, next) => {
84
122
  await fn(ctx, next);
85
- };
123
+ }, this);
86
124
  }
87
125
  }
88
126
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rhythmjs/cli",
3
- "version": "0.0.12",
3
+ "version": "0.0.14",
4
4
  "description": "Command-line argument parsing, prompts, and command routing for the Rhythm middleware kernel, running on Bun.",
5
5
  "homepage": "https://rhythm.js.org/cli",
6
6
  "license": "ISC",
@@ -49,7 +49,7 @@
49
49
  "access": "public"
50
50
  },
51
51
  "dependencies": {
52
- "@rhythmjs/rhythm": "0.0.12"
52
+ "@rhythmjs/rhythm": "0.0.14"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@types/bun": "^1.4.2",