@optique/discover 1.2.0-dev.2254 → 1.2.0-dev.2259

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.
@@ -1,4 +1,4 @@
1
- import { isCommand } from "./command-DO5zgkvS.js";
1
+ import { isCommand, validateHooks } from "./command-9sgrJtwh.js";
2
2
  import { longestMatch, or } from "@optique/core/constructs";
3
3
  import { map } from "@optique/core/modifiers";
4
4
  import { command } from "@optique/core/primitives";
@@ -145,10 +145,12 @@ function createProgramParser(commands, metadata = {}) {
145
145
  * @param options Program options.
146
146
  * @returns A promise that resolves after the selected command handler
147
147
  * completes.
148
- * @throws {TypeError} If discovery or command loading fails.
148
+ * @throws {TypeError} If discovery or command loading fails, or `hooks` is
149
+ * malformed.
149
150
  * @since 1.1.0
150
151
  */
151
152
  async function runProgram(options) {
153
+ if (options.hooks != null) validateHooks(options.hooks, "Program");
152
154
  let commands;
153
155
  if (isStaticRunProgramOptions(options)) commands = staticCommandsToEntries(options.commands);
154
156
  else commands = await discoverCommands({
@@ -158,7 +160,55 @@ async function runProgram(options) {
158
160
  });
159
161
  const parser = createProgramParser(commands, options.metadata);
160
162
  const invocation = await runAsync(parser, buildRunOptions(options));
161
- await invocation.handler(invocation.value);
163
+ await dispatchInvocation(invocation, options.hooks);
164
+ }
165
+ /**
166
+ * Runs a command handler wrapped in the program-level and command-level
167
+ * lifecycle hooks.
168
+ *
169
+ * The hooks nest: the program-level `beforeEach` runs first, then the command's
170
+ * `beforeEach`, then the handler; `afterEach` and `onError` unwind in reverse,
171
+ * with the command-level hook running before the program-level one.
172
+ *
173
+ * @param invocation The selected command invocation.
174
+ * @param programHooks Program-level hooks, if any.
175
+ * @returns A promise that resolves after the handler and matching hooks
176
+ * complete.
177
+ * @throws The original error thrown by `beforeEach`, the handler, or
178
+ * `afterEach`, re-thrown after the `onError` hooks run.
179
+ */
180
+ async function dispatchInvocation(invocation, programHooks) {
181
+ const commandHooks = invocation.command.hooks;
182
+ await runHookScope(programHooks, invocation, (programContext) => runHookScope(commandHooks, invocation, (commandContext) => {
183
+ if (commandHooks?.beforeEach != null) return invocation.handler(invocation.value, commandContext);
184
+ if (programHooks?.beforeEach != null) return invocation.handler(invocation.value, programContext);
185
+ return invocation.handler(invocation.value);
186
+ }));
187
+ }
188
+ /**
189
+ * Runs an inner step wrapped in a single set of lifecycle hooks.
190
+ *
191
+ * @param hooks The hooks for this scope, if any.
192
+ * @param invocation The selected command invocation passed to `beforeEach`.
193
+ * @param inner The step to wrap; receives the context from `beforeEach`.
194
+ * @returns The value returned by `inner`.
195
+ * @throws The original error thrown by `beforeEach`, `inner`, or `afterEach`,
196
+ * re-thrown after `onError` runs. An error thrown by `onError` itself
197
+ * is suppressed so it cannot mask the original failure.
198
+ */
199
+ async function runHookScope(hooks, invocation, inner) {
200
+ let context = {};
201
+ try {
202
+ if (hooks?.beforeEach != null) context = await hooks.beforeEach(invocation) ?? {};
203
+ const result = await inner(context);
204
+ if (hooks?.afterEach != null) await hooks.afterEach(context, result);
205
+ return result;
206
+ } catch (error) {
207
+ if (hooks?.onError != null) try {
208
+ await hooks.onError(context, error);
209
+ } catch {}
210
+ throw error;
211
+ }
162
212
  }
163
213
  function getRuntime() {
164
214
  if ("Deno" in globalThis) return "deno";
@@ -336,18 +386,19 @@ function buildCommandTree(commands) {
336
386
  current = child;
337
387
  }
338
388
  current.command = entry.command;
389
+ current.path = entry.path;
339
390
  }
340
391
  return root;
341
392
  }
342
393
  function buildNodeParser(node, inheritedHidden) {
343
394
  const childParser = buildChildrenParser(node, inheritedHidden);
344
- if (childParser != null && node.command != null) return createExecutableNodeParser(childParser, node.command);
395
+ if (childParser != null && node.command != null) return createExecutableNodeParser(childParser, node.command, node.path ?? []);
345
396
  if (childParser != null) return childParser;
346
- if (node.command != null) return createLeafParser(node.command);
397
+ if (node.command != null) return createLeafParser(node.command, node.path ?? []);
347
398
  throw new TypeError("Command tree node must contain a command.");
348
399
  }
349
- function createExecutableNodeParser(childParser, commandDefinition) {
350
- const leafParser = createLeafParser(commandDefinition, true);
400
+ function createExecutableNodeParser(childParser, commandDefinition, path) {
401
+ const leafParser = createLeafParser(commandDefinition, path, true);
351
402
  const branchParsers = [childParser, leafParser];
352
403
  const parser = longestMatch(childParser, leafParser);
353
404
  const phase2SeedHook = findPhase2SeedHook(parser);
@@ -386,16 +437,16 @@ function createExecutableNodeParser(childParser, commandDefinition) {
386
437
  state: toExclusiveState(activeState, context.state)
387
438
  }, prefix);
388
439
  },
389
- getSuggestRuntimeNodes(state, path) {
440
+ getSuggestRuntimeNodes(state, path$1) {
390
441
  const activeState = normalizeExecutableNodeState(state);
391
442
  if (activeState == null) {
392
- const branchPath$1 = [...path, 1];
443
+ const branchPath$1 = [...path$1, 1];
393
444
  const branchState$1 = inheritAnnotations(state, leafParser.initialState);
394
445
  return getExecutableNodeBranchSuggestRuntimeNodes(leafParser, branchState$1, branchPath$1);
395
446
  }
396
- if (activeState?.result.success !== true) return parser.getSuggestRuntimeNodes?.(toExclusiveState(activeState, state), path) ?? [];
447
+ if (activeState?.result.success !== true) return parser.getSuggestRuntimeNodes?.(toExclusiveState(activeState, state), path$1) ?? [];
397
448
  const branchParser = branchParsers[activeState.branch];
398
- const branchPath = [...path, activeState.branch];
449
+ const branchPath = [...path$1, activeState.branch];
399
450
  const branchState = inheritAnnotations(state, activeState.result.next.state);
400
451
  return getExecutableNodeBranchSuggestRuntimeNodes(branchParser, branchState, branchPath);
401
452
  },
@@ -647,9 +698,10 @@ function commandMetadataWithInheritedHidden(metadata, inheritedHidden) {
647
698
  ...hidden != null && { hidden }
648
699
  };
649
700
  }
650
- function createLeafParser(commandDefinition, includeMetadata = false) {
701
+ function createLeafParser(commandDefinition, path, includeMetadata = false) {
651
702
  const parser = map(commandDefinition.parser, (value) => ({
652
703
  command: commandDefinition,
704
+ path,
653
705
  value,
654
706
  handler: commandDefinition.handler
655
707
  }));
@@ -702,7 +754,7 @@ function commandPathHidden(path, commandsByPath) {
702
754
  }
703
755
  function buildRunOptions(options) {
704
756
  const metadata = options.metadata;
705
- const { dir: _dir, commands: _commands, extensions: _extensions, entryFileName: _entryFileName, metadata: _metadata, help, version, completion,...rest } = options;
757
+ const { dir: _dir, commands: _commands, extensions: _extensions, entryFileName: _entryFileName, metadata: _metadata, hooks: _hooks, help, version, completion,...rest } = options;
706
758
  const runOptions = {
707
759
  ...rest,
708
760
  contexts: unwrapProgramContexts(rest.contexts),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@optique/discover",
3
- "version": "1.2.0-dev.2254",
3
+ "version": "1.2.0-dev.2259",
4
4
  "description": "Runtime-aware command discovery for Optique CLI programs",
5
5
  "keywords": [
6
6
  "CLI",
@@ -83,8 +83,8 @@
83
83
  "optique-discover": "./dist/cli.js"
84
84
  },
85
85
  "dependencies": {
86
- "@optique/core": "1.2.0-dev.2254+22b59099",
87
- "@optique/run": "1.2.0-dev.2254+22b59099"
86
+ "@optique/core": "1.2.0-dev.2259+0b30260e",
87
+ "@optique/run": "1.2.0-dev.2259+0b30260e"
88
88
  },
89
89
  "devDependencies": {
90
90
  "@types/node": "^24.0.0",
@@ -1,139 +0,0 @@
1
- import { CommandOptions } from "@optique/core/primitives";
2
- import { Mode, Parser } from "@optique/core/parser";
3
-
4
- //#region src/command.d.ts
5
- declare const commandBrand: unique symbol;
6
- /**
7
- * Metadata shown for a discovered command.
8
- *
9
- * This uses the same shape as Optique's `command()` options so discovered
10
- * commands can provide descriptions, usage overrides, visibility, and custom
11
- * command-level errors.
12
- *
13
- * @since 1.1.0
14
- */
15
- type CommandMetadata = CommandOptions;
16
- /**
17
- * Command path used by static command registration.
18
- *
19
- * An empty path represents the root command.
20
- *
21
- * @since 1.1.0
22
- */
23
- type CommandPath = readonly string[];
24
- /**
25
- * Input accepted by {@link defineCommand}.
26
- *
27
- * @template M The mode of the command parser.
28
- * @template T The parsed value passed to the command handler.
29
- * @since 1.1.0
30
- */
31
- interface CommandDefinition<M extends Mode, T> {
32
- /**
33
- * Command path used when commands are passed directly to `runProgram()`.
34
- * Use an empty path (`[]`) to register the root command.
35
- *
36
- * File-based discovery derives the command path from the file name and uses
37
- * this field only to validate that the declared path matches.
38
- */
39
- readonly path?: CommandPath;
40
- /**
41
- * Parser for this command's command-specific arguments and options.
42
- */
43
- readonly parser: Parser<M, T, unknown>;
44
- /**
45
- * Metadata used in help output and shell completion.
46
- */
47
- readonly metadata?: CommandMetadata;
48
- /**
49
- * Handles the parsed command value.
50
- *
51
- * @param value Parsed command value.
52
- * @returns Nothing, or a promise that resolves when command handling
53
- * completes.
54
- */
55
- readonly handler: (value: T) => void | Promise<void>;
56
- }
57
- /**
58
- * A discovered command module definition.
59
- *
60
- * @template M The mode of the command parser.
61
- * @template T The parsed value passed to the command handler.
62
- * @since 1.1.0
63
- */
64
- interface Command<M extends Mode, T> extends CommandDefinition<M, T> {
65
- /**
66
- * Internal marker used to validate discovered modules.
67
- *
68
- * @internal
69
- */
70
- readonly [commandBrand]: true;
71
- }
72
- /**
73
- * A command that declares its own command path.
74
- *
75
- * Static `runProgram({ commands })` registration accepts this shape.
76
- *
77
- * @template M The mode of the command parser.
78
- * @template T The parsed value passed to the command handler.
79
- * @since 1.1.0
80
- */
81
- interface StaticCommand<M extends Mode, T> extends Command<M, T> {
82
- /**
83
- * Command path used by static command registration.
84
- */
85
- readonly path: CommandPath;
86
- }
87
- /**
88
- * A command with its handler value type erased.
89
- *
90
- * This type is used by discovery APIs that collect commands with different
91
- * parsed value types. The handler cannot be called directly without first
92
- * recovering the parser's value type.
93
- *
94
- * @since 1.1.0
95
- */
96
- type AnyCommand = Omit<Command<Mode, unknown>, "handler"> & {
97
- /**
98
- * Erased command handler.
99
- */
100
- readonly handler: (value: never) => void | Promise<void>;
101
- };
102
- /**
103
- * A statically registered command with its handler value type erased.
104
- *
105
- * @since 1.1.0
106
- */
107
- type AnyStaticCommand = Omit<StaticCommand<Mode, unknown>, "handler"> & {
108
- /**
109
- * Erased command handler.
110
- */
111
- readonly handler: (value: never) => void | Promise<void>;
112
- };
113
- /**
114
- * Defines a command module for `@optique/discover`.
115
- *
116
- * This helper returns its argument unchanged while preserving parser value
117
- * inference for the handler callback.
118
- *
119
- * @template M The mode of the command parser.
120
- * @template T The parsed value passed to the command handler.
121
- * @param command The command definition.
122
- * @returns The same command definition with inferred types.
123
- * @throws {TypeError} If the parser, path, or handler is missing or malformed.
124
- * @since 1.1.0
125
- */
126
- declare function defineCommand<M extends Mode, T>(command: CommandDefinition<M, T> & {
127
- readonly path: CommandPath;
128
- }): StaticCommand<M, T>;
129
- declare function defineCommand<M extends Mode, T>(command: CommandDefinition<M, T>): Command<M, T>;
130
- /**
131
- * Returns whether a value is a command created by {@link defineCommand}.
132
- *
133
- * @param value The value to inspect.
134
- * @returns `true` when the value is a discovered command definition.
135
- * @since 1.1.0
136
- */
137
- declare function isCommand(value: unknown): value is AnyCommand;
138
- //#endregion
139
- export { AnyCommand, AnyStaticCommand, Command, CommandDefinition, CommandMetadata, CommandPath, StaticCommand, defineCommand, isCommand };
@@ -1,139 +0,0 @@
1
- import { CommandOptions } from "@optique/core/primitives";
2
- import { Mode, Parser } from "@optique/core/parser";
3
-
4
- //#region src/command.d.ts
5
- declare const commandBrand: unique symbol;
6
- /**
7
- * Metadata shown for a discovered command.
8
- *
9
- * This uses the same shape as Optique's `command()` options so discovered
10
- * commands can provide descriptions, usage overrides, visibility, and custom
11
- * command-level errors.
12
- *
13
- * @since 1.1.0
14
- */
15
- type CommandMetadata = CommandOptions;
16
- /**
17
- * Command path used by static command registration.
18
- *
19
- * An empty path represents the root command.
20
- *
21
- * @since 1.1.0
22
- */
23
- type CommandPath = readonly string[];
24
- /**
25
- * Input accepted by {@link defineCommand}.
26
- *
27
- * @template M The mode of the command parser.
28
- * @template T The parsed value passed to the command handler.
29
- * @since 1.1.0
30
- */
31
- interface CommandDefinition<M extends Mode, T> {
32
- /**
33
- * Command path used when commands are passed directly to `runProgram()`.
34
- * Use an empty path (`[]`) to register the root command.
35
- *
36
- * File-based discovery derives the command path from the file name and uses
37
- * this field only to validate that the declared path matches.
38
- */
39
- readonly path?: CommandPath;
40
- /**
41
- * Parser for this command's command-specific arguments and options.
42
- */
43
- readonly parser: Parser<M, T, unknown>;
44
- /**
45
- * Metadata used in help output and shell completion.
46
- */
47
- readonly metadata?: CommandMetadata;
48
- /**
49
- * Handles the parsed command value.
50
- *
51
- * @param value Parsed command value.
52
- * @returns Nothing, or a promise that resolves when command handling
53
- * completes.
54
- */
55
- readonly handler: (value: T) => void | Promise<void>;
56
- }
57
- /**
58
- * A discovered command module definition.
59
- *
60
- * @template M The mode of the command parser.
61
- * @template T The parsed value passed to the command handler.
62
- * @since 1.1.0
63
- */
64
- interface Command<M extends Mode, T> extends CommandDefinition<M, T> {
65
- /**
66
- * Internal marker used to validate discovered modules.
67
- *
68
- * @internal
69
- */
70
- readonly [commandBrand]: true;
71
- }
72
- /**
73
- * A command that declares its own command path.
74
- *
75
- * Static `runProgram({ commands })` registration accepts this shape.
76
- *
77
- * @template M The mode of the command parser.
78
- * @template T The parsed value passed to the command handler.
79
- * @since 1.1.0
80
- */
81
- interface StaticCommand<M extends Mode, T> extends Command<M, T> {
82
- /**
83
- * Command path used by static command registration.
84
- */
85
- readonly path: CommandPath;
86
- }
87
- /**
88
- * A command with its handler value type erased.
89
- *
90
- * This type is used by discovery APIs that collect commands with different
91
- * parsed value types. The handler cannot be called directly without first
92
- * recovering the parser's value type.
93
- *
94
- * @since 1.1.0
95
- */
96
- type AnyCommand = Omit<Command<Mode, unknown>, "handler"> & {
97
- /**
98
- * Erased command handler.
99
- */
100
- readonly handler: (value: never) => void | Promise<void>;
101
- };
102
- /**
103
- * A statically registered command with its handler value type erased.
104
- *
105
- * @since 1.1.0
106
- */
107
- type AnyStaticCommand = Omit<StaticCommand<Mode, unknown>, "handler"> & {
108
- /**
109
- * Erased command handler.
110
- */
111
- readonly handler: (value: never) => void | Promise<void>;
112
- };
113
- /**
114
- * Defines a command module for `@optique/discover`.
115
- *
116
- * This helper returns its argument unchanged while preserving parser value
117
- * inference for the handler callback.
118
- *
119
- * @template M The mode of the command parser.
120
- * @template T The parsed value passed to the command handler.
121
- * @param command The command definition.
122
- * @returns The same command definition with inferred types.
123
- * @throws {TypeError} If the parser, path, or handler is missing or malformed.
124
- * @since 1.1.0
125
- */
126
- declare function defineCommand<M extends Mode, T>(command: CommandDefinition<M, T> & {
127
- readonly path: CommandPath;
128
- }): StaticCommand<M, T>;
129
- declare function defineCommand<M extends Mode, T>(command: CommandDefinition<M, T>): Command<M, T>;
130
- /**
131
- * Returns whether a value is a command created by {@link defineCommand}.
132
- *
133
- * @param value The value to inspect.
134
- * @returns `true` when the value is a discovered command definition.
135
- * @since 1.1.0
136
- */
137
- declare function isCommand(value: unknown): value is AnyCommand;
138
- //#endregion
139
- export { AnyCommand, AnyStaticCommand, Command, CommandDefinition, CommandMetadata, CommandPath, StaticCommand, defineCommand, isCommand };