@optique/discover 1.2.0-dev.2167 → 1.2.0-dev.2179

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
@@ -14,7 +14,8 @@ handler.
14
14
  > *@optique/discover* reads command files and imports them dynamically at
15
15
  > runtime. It is a poor fit for CLIs that rely on aggressive tree shaking,
16
16
  > static bundling, or single-file executable packaging. In those cases, use
17
- > manually imported commands with `runProgram({ commands })`.
17
+ > `commandsFromModules()` with a static module map, or manually imported
18
+ > commands with `runProgram({ commands })`.
18
19
 
19
20
 
20
21
  Installation
@@ -79,32 +80,52 @@ admin --help
79
80
  admin completion bash
80
81
  ~~~~
81
82
 
82
- For bundlers and single-file packagers, import commands manually and declare
83
- their paths in the command definitions:
83
+ For bundlers and single-file packagers, turn a static module map into command
84
+ entries:
84
85
 
85
86
  ~~~~ typescript
86
87
  // cli.ts
87
- import { defineCommand, runProgram } from "@optique/discover";
88
- import { object } from "@optique/core/constructs";
88
+ import { commandsFromModules, runProgram } from "@optique/discover";
89
89
  import { message } from "@optique/core/message";
90
- import { option } from "@optique/core/primitives";
91
- import { string } from "@optique/core/valueparser";
92
90
 
93
- const addUser = defineCommand({
94
- path: ["user", "add"],
95
- parser: object({
96
- name: option("--name", string()),
91
+ const modules = import.meta.glob("./commands/**/*.ts", {
92
+ eager: true,
93
+ });
94
+
95
+ await runProgram({
96
+ commands: commandsFromModules(modules, {
97
+ base: "./commands",
98
+ extensions: [".ts"],
97
99
  }),
98
100
  metadata: {
99
- brief: message`Add a user.`,
100
- },
101
- handler(value) {
102
- console.log(`Adding ${value.name}.`);
101
+ name: "admin",
102
+ version: "1.0.0",
103
+ brief: message`Administrative command-line tools.`,
103
104
  },
104
105
  });
106
+ ~~~~
107
+
108
+ `commandsFromModules()` preserves the file-based command layout while making
109
+ the module list visible to bundlers. For smaller registries, you can also
110
+ import commands manually, declare `path` in each `defineCommand()` call, and
111
+ pass those commands to `runProgram({ commands })`.
112
+
113
+ If you do not want to maintain the static module map by hand, generate one:
114
+
115
+ ~~~~ bash
116
+ optique-discover ./commands --output ./commands.generated.ts --extension .ts
117
+ ~~~~
118
+
119
+ Then import the generated module from your CLI entry point:
120
+
121
+ ~~~~ typescript
122
+ // cli.ts
123
+ import { runProgram } from "@optique/discover";
124
+ import { message } from "@optique/core/message";
125
+ import commands from "./commands.generated.ts";
105
126
 
106
127
  await runProgram({
107
- commands: [addUser],
128
+ commands,
108
129
  metadata: {
109
130
  name: "admin",
110
131
  version: "1.0.0",
@@ -113,6 +134,9 @@ await runProgram({
113
134
  });
114
135
  ~~~~
115
136
 
137
+ Use `--watch` during development to regenerate only when command files are
138
+ added, removed, or renamed.
139
+
116
140
  By default, Deno and Bun discover `.ts`, `.mts`, `.js`, and `.mjs` files.
117
141
  Node.js discovers `.js`, `.mjs`, and `.cjs` files, plus `.ts`, `.mts`, and
118
142
  `.cts` when it reports native TypeScript support or runs with a recognized
@@ -120,7 +144,8 @@ TypeScript loader. TypeScript declaration files such as `.d.ts` are ignored.
120
144
  Entry files named `index` map to their containing command path, so
121
145
  `commands/index.ts` defines the root command and `commands/user/index.ts`
122
146
  defines `user`. Use `entryFileName` to choose another entry name or disable
123
- this rule.
147
+ this rule. `commandsFromModules()` applies the same path rules to module map
148
+ keys after stripping its `base` option.
124
149
 
125
150
  For more resources, see the [docs] and the [*examples/*](/examples/)
126
151
  directory.
@@ -0,0 +1,30 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+
25
+ Object.defineProperty(exports, '__toESM', {
26
+ enumerable: true,
27
+ get: function () {
28
+ return __toESM;
29
+ }
30
+ });
package/dist/cli.cjs ADDED
@@ -0,0 +1,144 @@
1
+ #!/usr/bin/env node
2
+ const require_chunk = require('./chunk-CUT6urMc.cjs');
3
+ require('./command-CUn2_NIA.cjs');
4
+ require('./src-BYGxdHGJ.cjs');
5
+ const require_generator = require('./generator-e4RwnDKG.cjs');
6
+ const require_main_check = require('./main-check-CwunSNpK.cjs');
7
+ const __optique_core_constructs = require_chunk.__toESM(require("@optique/core/constructs"));
8
+ const __optique_core_message = require_chunk.__toESM(require("@optique/core/message"));
9
+ const __optique_core_modifiers = require_chunk.__toESM(require("@optique/core/modifiers"));
10
+ const __optique_core_primitives = require_chunk.__toESM(require("@optique/core/primitives"));
11
+ const __optique_core_program = require_chunk.__toESM(require("@optique/core/program"));
12
+ const __optique_core_valueparser = require_chunk.__toESM(require("@optique/core/valueparser"));
13
+ const __optique_run = require_chunk.__toESM(require("@optique/run"));
14
+ const node_process = require_chunk.__toESM(require("node:process"));
15
+
16
+ //#region deno.json
17
+ var name = "@optique/discover";
18
+ var version = "1.2.0-dev.2179+919d5ae8";
19
+ var license = "MIT";
20
+ var exports$1 = {
21
+ ".": "./src/index.ts",
22
+ "./command": "./src/command.ts",
23
+ "./generator": "./src/generator.ts",
24
+ "./cli": "./src/cli.ts"
25
+ };
26
+ var imports = { "#src/": "./src/" };
27
+ var exclude = [
28
+ "dist/",
29
+ "node_modules",
30
+ "tsdown.config.ts"
31
+ ];
32
+ var tasks = {
33
+ "build": "pnpm build",
34
+ "test": "deno test --allow-read --allow-write --allow-env",
35
+ "test:node": {
36
+ "dependencies": ["build"],
37
+ "command": "node --test"
38
+ },
39
+ "test:bun": {
40
+ "dependencies": ["build"],
41
+ "command": "bun test"
42
+ },
43
+ "test-all": { "dependencies": [
44
+ "test",
45
+ "test:node",
46
+ "test:bun"
47
+ ] }
48
+ };
49
+ var deno_default = {
50
+ name,
51
+ version,
52
+ license,
53
+ exports: exports$1,
54
+ imports,
55
+ exclude,
56
+ tasks
57
+ };
58
+
59
+ //#endregion
60
+ //#region src/cli.ts
61
+ const EXIT_GENERATION_FAILED = 1;
62
+ const EXIT_INVALID_OPTIONS = 2;
63
+ const cliProgram = (0, __optique_core_program.defineProgram)({
64
+ parser: (0, __optique_core_constructs.object)({
65
+ dir: (0, __optique_core_primitives.argument)((0, __optique_core_valueparser.string)({ metavar: "DIR" }), { description: __optique_core_message.message`Directory containing command modules.` }),
66
+ outputFile: (0, __optique_core_primitives.option)("-o", "--output", (0, __optique_core_valueparser.string)({ metavar: "FILE" }), { description: __optique_core_message.message`Generated TypeScript module path.` }),
67
+ base: (0, __optique_core_modifiers.optional)((0, __optique_core_primitives.option)("--base", (0, __optique_core_valueparser.string)({ metavar: "PATH" }), { description: __optique_core_message.message`Module map base path passed to commandsFromModules().
68
+ Defaults to the command directory relative to the generated module.` })),
69
+ extensions: (0, __optique_core_modifiers.withDefault)((0, __optique_core_modifiers.multiple)((0, __optique_core_primitives.option)("--extension", (0, __optique_core_valueparser.string)({ metavar: "EXT" }))), []),
70
+ entryFileName: (0, __optique_core_modifiers.optional)((0, __optique_core_primitives.option)("--entry-file-name", (0, __optique_core_valueparser.string)({ metavar: "NAME" }), { description: __optique_core_message.message`File name that maps to the containing command path.
71
+ Defaults to commandsFromModules() behavior.` })),
72
+ noEntryFileName: (0, __optique_core_primitives.option)("--no-entry-file-name", { description: __optique_core_message.message`Treat entry files as ordinary command names.` }),
73
+ watch: (0, __optique_core_primitives.option)("--watch", { description: __optique_core_message.message`Regenerate when command files are added, removed,
74
+ or renamed.` })
75
+ }),
76
+ metadata: {
77
+ name: "optique-discover",
78
+ version: deno_default.version,
79
+ brief: __optique_core_message.message`Generate static command modules for @optique/discover`
80
+ }
81
+ });
82
+ /**
83
+ * Runs the optique-discover command-line interface.
84
+ *
85
+ * @returns A promise that resolves after generation or watch mode finishes.
86
+ * @since 1.2.0
87
+ */
88
+ async function main() {
89
+ const args = (0, __optique_run.runSync)(cliProgram, {
90
+ help: "option",
91
+ version: {
92
+ value: deno_default.version,
93
+ option: true
94
+ }
95
+ });
96
+ if (args.noEntryFileName && args.entryFileName != null) {
97
+ (0, __optique_run.printError)(__optique_core_message.message`Use either --entry-file-name or --no-entry-file-name, not both.`, { exitCode: EXIT_INVALID_OPTIONS });
98
+ return;
99
+ }
100
+ const options = {
101
+ dir: args.dir,
102
+ outputFile: args.outputFile,
103
+ ...args.base != null ? { base: args.base } : {},
104
+ ...args.extensions.length > 0 ? { extensions: args.extensions } : {},
105
+ ...args.noEntryFileName ? { entryFileName: false } : args.entryFileName != null ? { entryFileName: args.entryFileName } : {}
106
+ };
107
+ try {
108
+ if (args.watch) await require_generator.watchCommandsModule({
109
+ ...options,
110
+ onGenerate(result) {
111
+ writeGeneratedMessage(result.files.length);
112
+ },
113
+ onError(error) {
114
+ printGenerationError(error);
115
+ }
116
+ });
117
+ else {
118
+ const result = await require_generator.writeCommandsModule(options);
119
+ writeGeneratedMessage(result.files.length);
120
+ }
121
+ } catch (error) {
122
+ printGenerationError(error, EXIT_GENERATION_FAILED);
123
+ }
124
+ }
125
+ function printGenerationError(error, exitCode) {
126
+ const messageText = error instanceof Error ? error.message : String(error);
127
+ if (exitCode == null) (0, __optique_run.printError)(__optique_core_message.message`Failed to generate command module: ${messageText}`);
128
+ else (0, __optique_run.printError)(__optique_core_message.message`Failed to generate command module: ${messageText}`, { exitCode });
129
+ }
130
+ function writeGeneratedMessage(count) {
131
+ const noun = count === 1 ? "command module" : "command modules";
132
+ console.log(`Generated ${count} ${noun}.`);
133
+ }
134
+ const isMain = require_main_check.isMainModuleUrl({
135
+ importMetaMain: "main" in import.meta ? void 0 : void 0,
136
+ moduleUrl: require("url").pathToFileURL(__filename).href,
137
+ argvEntry: node_process.default.argv[1]
138
+ });
139
+ if (isMain) main().catch((error) => {
140
+ printGenerationError(error, EXIT_GENERATION_FAILED);
141
+ });
142
+
143
+ //#endregion
144
+ exports.main = main;
package/dist/cli.d.cts ADDED
@@ -0,0 +1,10 @@
1
+ //#region src/cli.d.ts
2
+ /**
3
+ * Runs the optique-discover command-line interface.
4
+ *
5
+ * @returns A promise that resolves after generation or watch mode finishes.
6
+ * @since 1.2.0
7
+ */
8
+ declare function main(): Promise<void>;
9
+ //#endregion
10
+ export { main };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ //#region src/cli.d.ts
2
+ /**
3
+ * Runs the optique-discover command-line interface.
4
+ *
5
+ * @returns A promise that resolves after generation or watch mode finishes.
6
+ * @since 1.2.0
7
+ */
8
+ declare function main(): Promise<void>;
9
+ //#endregion
10
+ export { main };
package/dist/cli.js ADDED
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env node
2
+ import "./command-DO5zgkvS.js";
3
+ import "./src-Ci75oZo-.js";
4
+ import { watchCommandsModule, writeCommandsModule } from "./generator-C12pIuFe.js";
5
+ import { isMainModuleUrl } from "./main-check-mMnKfUZs.js";
6
+ import { object } from "@optique/core/constructs";
7
+ import { message } from "@optique/core/message";
8
+ import { multiple, optional, withDefault } from "@optique/core/modifiers";
9
+ import { argument, option } from "@optique/core/primitives";
10
+ import { defineProgram } from "@optique/core/program";
11
+ import { string } from "@optique/core/valueparser";
12
+ import { printError, runSync } from "@optique/run";
13
+ import process from "node:process";
14
+
15
+ //#region deno.json
16
+ var name = "@optique/discover";
17
+ var version = "1.2.0-dev.2179+919d5ae8";
18
+ var license = "MIT";
19
+ var exports = {
20
+ ".": "./src/index.ts",
21
+ "./command": "./src/command.ts",
22
+ "./generator": "./src/generator.ts",
23
+ "./cli": "./src/cli.ts"
24
+ };
25
+ var imports = { "#src/": "./src/" };
26
+ var exclude = [
27
+ "dist/",
28
+ "node_modules",
29
+ "tsdown.config.ts"
30
+ ];
31
+ var tasks = {
32
+ "build": "pnpm build",
33
+ "test": "deno test --allow-read --allow-write --allow-env",
34
+ "test:node": {
35
+ "dependencies": ["build"],
36
+ "command": "node --test"
37
+ },
38
+ "test:bun": {
39
+ "dependencies": ["build"],
40
+ "command": "bun test"
41
+ },
42
+ "test-all": { "dependencies": [
43
+ "test",
44
+ "test:node",
45
+ "test:bun"
46
+ ] }
47
+ };
48
+ var deno_default = {
49
+ name,
50
+ version,
51
+ license,
52
+ exports,
53
+ imports,
54
+ exclude,
55
+ tasks
56
+ };
57
+
58
+ //#endregion
59
+ //#region src/cli.ts
60
+ const EXIT_GENERATION_FAILED = 1;
61
+ const EXIT_INVALID_OPTIONS = 2;
62
+ const cliProgram = defineProgram({
63
+ parser: object({
64
+ dir: argument(string({ metavar: "DIR" }), { description: message`Directory containing command modules.` }),
65
+ outputFile: option("-o", "--output", string({ metavar: "FILE" }), { description: message`Generated TypeScript module path.` }),
66
+ base: optional(option("--base", string({ metavar: "PATH" }), { description: message`Module map base path passed to commandsFromModules().
67
+ Defaults to the command directory relative to the generated module.` })),
68
+ extensions: withDefault(multiple(option("--extension", string({ metavar: "EXT" }))), []),
69
+ entryFileName: optional(option("--entry-file-name", string({ metavar: "NAME" }), { description: message`File name that maps to the containing command path.
70
+ Defaults to commandsFromModules() behavior.` })),
71
+ noEntryFileName: option("--no-entry-file-name", { description: message`Treat entry files as ordinary command names.` }),
72
+ watch: option("--watch", { description: message`Regenerate when command files are added, removed,
73
+ or renamed.` })
74
+ }),
75
+ metadata: {
76
+ name: "optique-discover",
77
+ version: deno_default.version,
78
+ brief: message`Generate static command modules for @optique/discover`
79
+ }
80
+ });
81
+ /**
82
+ * Runs the optique-discover command-line interface.
83
+ *
84
+ * @returns A promise that resolves after generation or watch mode finishes.
85
+ * @since 1.2.0
86
+ */
87
+ async function main() {
88
+ const args = runSync(cliProgram, {
89
+ help: "option",
90
+ version: {
91
+ value: deno_default.version,
92
+ option: true
93
+ }
94
+ });
95
+ if (args.noEntryFileName && args.entryFileName != null) {
96
+ printError(message`Use either --entry-file-name or --no-entry-file-name, not both.`, { exitCode: EXIT_INVALID_OPTIONS });
97
+ return;
98
+ }
99
+ const options = {
100
+ dir: args.dir,
101
+ outputFile: args.outputFile,
102
+ ...args.base != null ? { base: args.base } : {},
103
+ ...args.extensions.length > 0 ? { extensions: args.extensions } : {},
104
+ ...args.noEntryFileName ? { entryFileName: false } : args.entryFileName != null ? { entryFileName: args.entryFileName } : {}
105
+ };
106
+ try {
107
+ if (args.watch) await watchCommandsModule({
108
+ ...options,
109
+ onGenerate(result) {
110
+ writeGeneratedMessage(result.files.length);
111
+ },
112
+ onError(error) {
113
+ printGenerationError(error);
114
+ }
115
+ });
116
+ else {
117
+ const result = await writeCommandsModule(options);
118
+ writeGeneratedMessage(result.files.length);
119
+ }
120
+ } catch (error) {
121
+ printGenerationError(error, EXIT_GENERATION_FAILED);
122
+ }
123
+ }
124
+ function printGenerationError(error, exitCode) {
125
+ const messageText = error instanceof Error ? error.message : String(error);
126
+ if (exitCode == null) printError(message`Failed to generate command module: ${messageText}`);
127
+ else printError(message`Failed to generate command module: ${messageText}`, { exitCode });
128
+ }
129
+ function writeGeneratedMessage(count) {
130
+ const noun = count === 1 ? "command module" : "command modules";
131
+ console.log(`Generated ${count} ${noun}.`);
132
+ }
133
+ const isMain = isMainModuleUrl({
134
+ importMetaMain: "main" in import.meta ? import.meta.main : void 0,
135
+ moduleUrl: import.meta.url,
136
+ argvEntry: process.argv[1]
137
+ });
138
+ if (isMain) main().catch((error) => {
139
+ printGenerationError(error, EXIT_GENERATION_FAILED);
140
+ });
141
+
142
+ //#endregion
143
+ export { main };
package/dist/command.cjs CHANGED
@@ -1,4 +1,4 @@
1
- const require_command = require('./command-B0lV6NBO.cjs');
1
+ const require_command = require('./command-CUn2_NIA.cjs');
2
2
 
3
3
  exports.defineCommand = require_command.defineCommand;
4
4
  exports.isCommand = require_command.isCommand;
package/dist/command.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { AnyCommand, AnyStaticCommand, Command, CommandDefinition, CommandMetadata, CommandPath, StaticCommand, defineCommand, isCommand } from "./command-DyiVIMUh.js";
1
+ import { AnyCommand, AnyStaticCommand, Command, CommandDefinition, CommandMetadata, CommandPath, StaticCommand, defineCommand, isCommand } from "./command-DrmNW0HO.js";
2
2
  export { AnyCommand, AnyStaticCommand, Command, CommandDefinition, CommandMetadata, CommandPath, StaticCommand, defineCommand, isCommand };