@wooksjs/event-cli 0.5.20 → 0.5.25

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/dist/index.mjs CHANGED
@@ -1,268 +1,257 @@
1
- import { CliHelpRenderer } from '@prostojs/cli-help';
2
- import minimist from 'minimist';
3
- import { WooksAdapterBase } from 'wooks';
4
- import { createAsyncEventContext, useAsyncEventContext } from '@wooksjs/event-core';
1
+ import { CliHelpRenderer } from "@prostojs/cli-help";
2
+ import minimist from "minimist";
3
+ import { WooksAdapterBase } from "wooks";
4
+ import { createAsyncEventContext, useAsyncEventContext } from "@wooksjs/event-core";
5
5
 
6
+ //#region packages/event-cli/src/event-cli.ts
6
7
  function createCliContext(data, options) {
7
- return createAsyncEventContext({
8
- event: {
9
- ...data,
10
- type: 'CLI',
11
- },
12
- options,
13
- });
8
+ return createAsyncEventContext({
9
+ event: {
10
+ ...data,
11
+ type: "CLI"
12
+ },
13
+ options
14
+ });
14
15
  }
15
16
  function useCliContext() {
16
- return useAsyncEventContext('CLI');
17
+ return useAsyncEventContext("CLI");
17
18
  }
18
19
 
19
- const cliShortcuts = {
20
- cli: 'CLI',
20
+ //#endregion
21
+ //#region packages/event-cli/src/cli-adapter.ts
22
+ const cliShortcuts = { cli: "CLI" };
23
+ var WooksCli = class extends WooksAdapterBase {
24
+ logger;
25
+ cliHelp;
26
+ constructor(opts, wooks) {
27
+ super(wooks, opts?.logger, opts?.router);
28
+ this.opts = opts;
29
+ this.logger = opts?.logger || this.getLogger(`${"\x1B[96m"}[wooks-cli]`);
30
+ this.cliHelp = opts?.cliHelp instanceof CliHelpRenderer ? opts.cliHelp : new CliHelpRenderer(opts?.cliHelp);
31
+ }
32
+ /**
33
+ * ### Register CLI Command
34
+ * Command path segments may be separated by / or space.
35
+ *
36
+ * For example the folowing path are interpreted the same:
37
+ * - "command test use:dev :name"
38
+ * - "command/test/use:dev/:name"
39
+ *
40
+ * Where name will become an argument
41
+ *
42
+ * ```js
43
+ * // example without options
44
+ * app.cli('command/:arg', () => 'arg = ' + useRouteParams().params.arg )
45
+ *
46
+ * // example with options
47
+ * app.cli('command/:arg', {
48
+ * description: 'Description of the command',
49
+ * options: [{ keys: ['project', 'p'], description: 'Description of the option', value: 'myProject' }],
50
+ * args: { arg: 'Description of the arg' },
51
+ * aliases: ['cmd'], // alias "cmd/:arg" will be registered
52
+ * examples: [{
53
+ * description: 'Example of usage with someProject',
54
+ * cmd: 'argValue -p=someProject',
55
+ * // will result in help display:
56
+ * // "# Example of usage with someProject\n" +
57
+ * // "$ myCli command argValue -p=someProject\n"
58
+ * }],
59
+ * handler: () => 'arg = ' + useRouteParams().params.arg
60
+ * })
61
+ * ```
62
+ *
63
+ * @param path command path
64
+ * @param _options handler or options
65
+ *
66
+ * @returns
67
+ */
68
+ cli(path, _options) {
69
+ const options = typeof _options === "function" ? { handler: _options } : _options;
70
+ const handler = typeof _options === "function" ? _options : _options.handler;
71
+ const makePath = (s) => `/${s.replace(/\s+/gu, "/")}`;
72
+ const targetPath = makePath(path);
73
+ const routed = this.on("CLI", targetPath, handler);
74
+ if (options.onRegister) options.onRegister(targetPath, 0, routed);
75
+ for (const alias of options.aliases || []) {
76
+ const vars = routed.getArgs().map((k) => `:${k}`).join("/");
77
+ const targetPath$1 = makePath(alias) + (vars ? `/${vars}` : "");
78
+ this.on("CLI", targetPath$1, handler);
79
+ if (options.onRegister) options.onRegister(targetPath$1, 1, routed);
80
+ }
81
+ const command = routed.getStaticPart().replace(/\//gu, " ").trim();
82
+ const args = { ...options.args };
83
+ for (const arg of routed.getArgs()) if (!args[arg]) args[arg] = "";
84
+ this.cliHelp.addEntry({
85
+ command,
86
+ aliases: options.aliases?.map((alias) => alias.replace(/\\:/gu, ":")),
87
+ args,
88
+ description: options.description,
89
+ examples: options.examples,
90
+ options: options.options,
91
+ custom: {
92
+ handler: options.handler,
93
+ cb: options.onRegister
94
+ }
95
+ });
96
+ return routed;
97
+ }
98
+ alreadyComputedAliases = false;
99
+ computeAliases() {
100
+ if (!this.alreadyComputedAliases) {
101
+ this.alreadyComputedAliases = true;
102
+ const aliases = this.cliHelp.getComputedAliases();
103
+ for (const [alias, entry] of Object.entries(aliases)) if (entry.custom) {
104
+ const vars = Object.keys(entry.args || {}).map((k) => `:${k}`).join("/");
105
+ const path = `/${alias.replace(/\s+/gu, "/").replace(/:/gu, "\\:")}${vars ? `/${vars}` : ""}`;
106
+ this.on("CLI", path, entry.custom.handler);
107
+ if (entry.custom.cb) entry.custom.cb(path, 3);
108
+ }
109
+ }
110
+ }
111
+ /**
112
+ * ## run
113
+ * ### Start command processing
114
+ * Triggers command processing
115
+ *
116
+ * By default takes `process.argv.slice(2)` as a command
117
+ *
118
+ * It's possible to replace the command by passing an argument
119
+ *
120
+ * @param _argv optionally overwrite `process.argv.slice(2)` with your `argv` array
121
+ */
122
+ async run(_argv, _opts) {
123
+ const argv = _argv || process.argv.slice(2);
124
+ const parsedFlags = minimist(argv, _opts);
125
+ const pathParams = parsedFlags._;
126
+ const path = `/${pathParams.map((v) => encodeURI(v).replace(/\//gu, "%2F")).join("/")}`;
127
+ const runInContext = createCliContext({
128
+ opts: _opts,
129
+ argv,
130
+ pathParams,
131
+ cliHelp: this.cliHelp,
132
+ command: path.replace(/\//gu, " ").trim()
133
+ }, this.mergeEventOptions(this.opts?.eventOptions));
134
+ return runInContext(async () => {
135
+ const { store } = useCliContext();
136
+ store("flags").value = parsedFlags;
137
+ this.computeAliases();
138
+ const { handlers: foundHandlers, firstStatic } = this.wooks.lookup("CLI", path);
139
+ if (typeof firstStatic === "string") store("event").set("command", firstStatic.replace(/\//gu, " ").trim());
140
+ const handlers = foundHandlers || this.opts?.onNotFound && [this.opts.onNotFound] || null;
141
+ if (handlers) try {
142
+ for (const handler of handlers) {
143
+ const response = await handler();
144
+ if (typeof response === "string") console.log(response);
145
+ else if (Array.isArray(response)) response.forEach((r) => {
146
+ console.log(typeof r === "string" ? r : JSON.stringify(r, null, " "));
147
+ });
148
+ else if (response instanceof Error) {
149
+ this.onError(response);
150
+ return response;
151
+ } else if (response) console.log(JSON.stringify(response, null, " "));
152
+ }
153
+ } catch (error) {
154
+ this.onError(error);
155
+ return error;
156
+ }
157
+ else {
158
+ this.onUnknownCommand(pathParams);
159
+ return new Error("Unknown command");
160
+ }
161
+ });
162
+ }
163
+ onError(e) {
164
+ if (this.opts?.onError) this.opts.onError(e);
165
+ else {
166
+ this.error(e.message);
167
+ process.exit(1);
168
+ }
169
+ }
170
+ /**
171
+ * Triggers `unknown command` processing and callbacks
172
+ * @param pathParams `string[]` containing command
173
+ */
174
+ onUnknownCommand(pathParams) {
175
+ const raiseError = () => {
176
+ this.error(`${"\x1B[0m"}Unknown command: ${pathParams.join(" ")}`);
177
+ process.exit(1);
178
+ };
179
+ if (this.opts?.onUnknownCommand) this.opts.onUnknownCommand(pathParams, raiseError);
180
+ else raiseError();
181
+ }
182
+ error(e) {
183
+ if (typeof e === "string") console.error(`${"\x1B[31m"}ERROR: ${"\x1B[0m"}${e}`);
184
+ else console.error(`${"\x1B[31m"}ERROR: ${"\x1B[0m"}${e.message}`);
185
+ }
21
186
  };
22
- class WooksCli extends WooksAdapterBase {
23
- constructor(opts, wooks) {
24
- super(wooks, opts?.logger, opts?.router);
25
- this.opts = opts;
26
- this.alreadyComputedAliases = false;
27
- this.logger = opts?.logger || this.getLogger(`${''}[wooks-cli]`);
28
- this.cliHelp =
29
- opts?.cliHelp instanceof CliHelpRenderer
30
- ? opts.cliHelp
31
- : new CliHelpRenderer(opts?.cliHelp);
32
- }
33
- cli(path, _options) {
34
- const options = typeof _options === 'function' ? { handler: _options } : _options;
35
- const handler = typeof _options === 'function' ? _options : _options.handler;
36
- const makePath = (s) => `/${s.replace(/\s+/g, '/')}`;
37
- const targetPath = makePath(path);
38
- const routed = this.on('CLI', targetPath, handler);
39
- if (options.onRegister) {
40
- options.onRegister(targetPath, 0, routed);
41
- }
42
- for (const alias of options.aliases || []) {
43
- const vars = routed
44
- .getArgs()
45
- .map(k => `:${k}`)
46
- .join('/');
47
- const targetPath = makePath(alias) + (vars ? `/${vars}` : '');
48
- this.on('CLI', targetPath, handler);
49
- if (options.onRegister) {
50
- options.onRegister(targetPath, 1, routed);
51
- }
52
- }
53
- const command = routed.getStaticPart().replace(/\//g, ' ').trim();
54
- const args = {
55
- ...options.args,
56
- };
57
- for (const arg of routed.getArgs()) {
58
- if (!args[arg]) {
59
- args[arg] = '';
60
- }
61
- }
62
- this.cliHelp.addEntry({
63
- command,
64
- aliases: options.aliases?.map(alias => alias.replace(/\\:/g, ':')),
65
- args,
66
- description: options.description,
67
- examples: options.examples,
68
- options: options.options,
69
- custom: { handler: options.handler, cb: options.onRegister },
70
- });
71
- return routed;
72
- }
73
- computeAliases() {
74
- if (!this.alreadyComputedAliases) {
75
- this.alreadyComputedAliases = true;
76
- const aliases = this.cliHelp.getComputedAliases();
77
- for (const [alias, entry] of Object.entries(aliases)) {
78
- if (entry.custom) {
79
- const vars = Object.keys(entry.args || {})
80
- .map(k => `:${k}`)
81
- .join('/');
82
- const path = `/${alias.replace(/\s+/g, '/').replace(/:/g, '\\:')}${vars ? `/${vars}` : ''}`;
83
- this.on('CLI', path, entry.custom.handler);
84
- if (entry.custom.cb) {
85
- entry.custom.cb(path, 3);
86
- }
87
- }
88
- }
89
- }
90
- }
91
- async run(_argv, _opts) {
92
- const argv = _argv || process.argv.slice(2);
93
- const parsedFlags = minimist(argv, _opts);
94
- const pathParams = parsedFlags._;
95
- const path = `/${pathParams.map(v => encodeURI(v).replace(/\//g, '%2F')).join('/')}`;
96
- const runInContext = createCliContext({
97
- opts: _opts,
98
- argv,
99
- pathParams,
100
- cliHelp: this.cliHelp,
101
- command: path.replace(/\//g, ' ').trim(),
102
- }, this.mergeEventOptions(this.opts?.eventOptions));
103
- return runInContext(async () => {
104
- const { store } = useCliContext();
105
- store('flags').value = parsedFlags;
106
- this.computeAliases();
107
- const { handlers: foundHandlers, firstStatic } = this.wooks.lookup('CLI', path);
108
- if (typeof firstStatic === 'string') {
109
- store('event').set('command', firstStatic.replace(/\//g, ' ').trim());
110
- }
111
- const handlers = foundHandlers || (this.opts?.onNotFound && [this.opts.onNotFound]) || null;
112
- if (handlers) {
113
- try {
114
- for (const handler of handlers) {
115
- const response = await handler();
116
- if (typeof response === 'string') {
117
- console.log(response);
118
- }
119
- else if (Array.isArray(response)) {
120
- response.forEach(r => {
121
- console.log(typeof r === 'string' ? r : JSON.stringify(r, null, ' '));
122
- });
123
- }
124
- else if (response instanceof Error) {
125
- this.onError(response);
126
- return response;
127
- }
128
- else if (response) {
129
- console.log(JSON.stringify(response, null, ' '));
130
- }
131
- }
132
- }
133
- catch (error) {
134
- this.onError(error);
135
- return error;
136
- }
137
- }
138
- else {
139
- this.onUnknownCommand(pathParams);
140
- return new Error('Unknown command');
141
- }
142
- });
143
- }
144
- onError(e) {
145
- if (this.opts?.onError) {
146
- this.opts.onError(e);
147
- }
148
- else {
149
- this.error(e.message);
150
- process.exit(1);
151
- }
152
- }
153
- onUnknownCommand(pathParams) {
154
- const raiseError = () => {
155
- this.error(`${''}Unknown command: ${pathParams.join(' ')}`);
156
- process.exit(1);
157
- };
158
- if (this.opts?.onUnknownCommand) {
159
- this.opts.onUnknownCommand(pathParams, raiseError);
160
- }
161
- else {
162
- raiseError();
163
- }
164
- }
165
- error(e) {
166
- if (typeof e === 'string') {
167
- console.error(`${''}ERROR: ${''}${e}`);
168
- }
169
- else {
170
- console.error(`${''}ERROR: ${''}${e.message}`);
171
- }
172
- }
173
- }
174
187
  function createCliApp(opts, wooks) {
175
- return new WooksCli(opts, wooks);
188
+ return new WooksCli(opts, wooks);
176
189
  }
177
190
 
191
+ //#endregion
192
+ //#region packages/event-cli/src/composables/options.ts
178
193
  function useCliOptions() {
179
- const { store } = useCliContext();
180
- const flags = store('flags');
181
- if (!flags.value) {
182
- const event = store('event');
183
- flags.value = minimist(event.get('argv'), event.get('opts'));
184
- }
185
- return flags.value;
194
+ const { store } = useCliContext();
195
+ const flags = store("flags");
196
+ if (!flags.value) {
197
+ const event = store("event");
198
+ flags.value = minimist(event.get("argv"), event.get("opts"));
199
+ }
200
+ return flags.value;
186
201
  }
187
202
  function useCliOption(name) {
188
- try {
189
- const options = useCliHelp().getEntry().options || [];
190
- const opt = options.find(o => o.keys.includes(name));
191
- if (opt) {
192
- for (const key of opt.keys) {
193
- if (useCliOptions()[key]) {
194
- return useCliOptions()[key];
195
- }
196
- }
197
- }
198
- }
199
- catch (error) {
200
- }
201
- return useCliOptions()[name];
203
+ try {
204
+ const options = useCliHelp().getEntry().options || [];
205
+ const opt = options.find((o) => o.keys.includes(name));
206
+ if (opt) {
207
+ for (const key of opt.keys) if (useCliOptions()[key]) return useCliOptions()[key];
208
+ }
209
+ } catch (error) {}
210
+ return useCliOptions()[name];
202
211
  }
203
212
 
213
+ //#endregion
214
+ //#region packages/event-cli/src/composables/cli-help.ts
204
215
  function useCliHelp() {
205
- const event = useCliContext().store('event');
206
- const getCliHelp = () => event.get('cliHelp');
207
- const getEntry = () => getCliHelp().match(event.get('command')).main;
208
- return {
209
- getCliHelp,
210
- getEntry,
211
- render: (width, withColors) => getCliHelp().render(event.get('command'), width, withColors),
212
- print: (withColors) => {
213
- getCliHelp().print(event.get('command'), withColors);
214
- },
215
- };
216
+ const event = useCliContext().store("event");
217
+ const getCliHelp = () => event.get("cliHelp");
218
+ const getEntry = () => getCliHelp().match(event.get("command")).main;
219
+ return {
220
+ getCliHelp,
221
+ getEntry,
222
+ render: (width, withColors) => getCliHelp().render(event.get("command"), width, withColors),
223
+ print: (withColors) => {
224
+ getCliHelp().print(event.get("command"), withColors);
225
+ }
226
+ };
216
227
  }
217
- function useAutoHelp(keys = ['help'], colors = true) {
218
- for (const option of keys) {
219
- if (useCliOption(option) === true) {
220
- useCliHelp().print(colors);
221
- return true;
222
- }
223
- }
228
+ function useAutoHelp(keys = ["help"], colors = true) {
229
+ for (const option of keys) if (useCliOption(option) === true) {
230
+ useCliHelp().print(colors);
231
+ return true;
232
+ }
224
233
  }
225
234
  function useCommandLookupHelp(lookupDepth = 3) {
226
- const parts = useCliContext()
227
- .store('event')
228
- .get('pathParams')
229
- ?.flatMap(p => `${p} `.split(':').map((s, i) => (i ? `:${s}` : s))) || [];
230
- const cliHelp = useCliHelp().getCliHelp();
231
- const cmd = cliHelp.getCliName();
232
- let data;
233
- for (let i = 0; i < Math.min(parts.length, lookupDepth + 1); i++) {
234
- const pathParams = parts
235
- .slice(0, i ? -i : parts.length)
236
- .join('')
237
- .trim();
238
- try {
239
- data = cliHelp.match(pathParams);
240
- break;
241
- }
242
- catch (error) {
243
- const variants = cliHelp.lookup(pathParams);
244
- if (variants.length > 0) {
245
- throw new Error(`Wrong command, did you mean:\n${variants
246
- .slice(0, 7)
247
- .map(c => ` $ ${cmd} ${c.main.command}`)
248
- .join('\n')}`);
249
- }
250
- }
251
- }
252
- if (data) {
253
- const { main, children } = data;
254
- if (main.args && Object.keys(main.args).length > 0) {
255
- throw new Error(`Arguments expected: ${Object.keys(main.args)
256
- .map(l => `<${l}>`)
257
- .join(', ')}`);
258
- }
259
- else if (children?.length > 0) {
260
- throw new Error(`Wrong command, did you mean:\n${children
261
- .slice(0, 7)
262
- .map(c => ` $ ${cmd} ${c.command}`)
263
- .join('\n')}`);
264
- }
265
- }
235
+ const parts = useCliContext().store("event").get("pathParams")?.flatMap((p) => `${p} `.split(":").map((s, i) => i ? `:${s}` : s)) || [];
236
+ const cliHelp = useCliHelp().getCliHelp();
237
+ const cmd = cliHelp.getCliName();
238
+ let data;
239
+ for (let i = 0; i < Math.min(parts.length, lookupDepth + 1); i++) {
240
+ const pathParams = parts.slice(0, i ? -i : parts.length).join("").trim();
241
+ try {
242
+ data = cliHelp.match(pathParams);
243
+ break;
244
+ } catch (error) {
245
+ const variants = cliHelp.lookup(pathParams);
246
+ if (variants.length > 0) throw new Error(`Wrong command, did you mean:\n${variants.slice(0, 7).map((c) => ` $ ${cmd} ${c.main.command}`).join("\n")}`);
247
+ }
248
+ }
249
+ if (data) {
250
+ const { main, children } = data;
251
+ if (main.args && Object.keys(main.args).length > 0) throw new Error(`Arguments expected: ${Object.keys(main.args).map((l) => `<${l}>`).join(", ")}`);
252
+ else if (children?.length > 0) throw new Error(`Wrong command, did you mean:\n${children.slice(0, 7).map((c) => ` $ ${cmd} ${c.command}`).join("\n")}`);
253
+ }
266
254
  }
267
255
 
268
- export { WooksCli, cliShortcuts, createCliApp, createCliContext, useAutoHelp, useCliContext, useCliHelp, useCliOption, useCliOptions, useCommandLookupHelp };
256
+ //#endregion
257
+ export { WooksCli, cliShortcuts, createCliApp, createCliContext, useAutoHelp, useCliContext, useCliHelp, useCliOption, useCliOptions, useCommandLookupHelp };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wooksjs/event-cli",
3
- "version": "0.5.20",
3
+ "version": "0.5.25",
4
4
  "description": "@wooksjs/event-cli",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",
@@ -39,17 +39,22 @@
39
39
  "url": "https://github.com/wooksjs/wooksjs/issues"
40
40
  },
41
41
  "peerDependencies": {
42
- "wooks": "0.5.20",
43
- "@wooksjs/event-core": "0.5.20"
42
+ "@wooksjs/event-core": "^0.5.25",
43
+ "wooks": "^0.5.25"
44
44
  },
45
45
  "dependencies": {
46
- "minimist": "^1.2.6",
47
46
  "@prostojs/cli-help": "^0.0.11",
47
+ "@prostojs/logger": "^0.4.3",
48
48
  "@prostojs/router": "^0.2.1",
49
- "@prostojs/logger": "^0.4.3"
49
+ "minimist": "^1.2.6"
50
50
  },
51
51
  "devDependencies": {
52
- "@types/minimist": "^1.2.5"
52
+ "@types/minimist": "^1.2.5",
53
+ "typescript": "^5.7.3",
54
+ "vitest": "^2.1.8"
53
55
  },
54
- "homepage": "https://github.com/wooksjs/wooksjs/tree/main/packages/event-cli#readme"
55
- }
56
+ "homepage": "https://github.com/wooksjs/wooksjs/tree/main/packages/event-cli#readme",
57
+ "scripts": {
58
+ "build": "rolldown -c ../../rolldown.config.mjs"
59
+ }
60
+ }