@moostjs/event-cli
Version:
@moostjs/event-cli
332 lines (323 loc) • 11.1 kB
JavaScript
;
//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
const moost = __toESM(require("moost"));
const __wooksjs_event_cli = __toESM(require("@wooksjs/event-cli"));
//#region packages/event-cli/src/meta-types.ts
function getCliMate() {
return (0, moost.getMoostMate)();
}
//#endregion
//#region packages/event-cli/src/decorators/cli.decorator.ts
function Cli(path) {
return getCliMate().decorate("handlers", {
path: path?.replace(/\s+/g, "/"),
type: "CLI"
}, true);
}
function CliAlias(alias) {
return getCliMate().decorate("cliAliases", alias, true);
}
function CliExample(cmd, description) {
return getCliMate().decorate("cliExamples", {
cmd,
description
}, true);
}
//#endregion
//#region packages/event-cli/src/utils.ts
function formatParams(keys) {
const names = [keys].flat();
return names.map((n) => n.length === 1 ? `-${n}` : `--${n}`);
}
//#endregion
//#region packages/event-cli/src/decorators/option.decorator.ts
function CliOption(...keys) {
const mate = getCliMate();
return mate.apply(mate.decorate("cliOptionsKeys", keys, false), (0, moost.Resolve)(() => (0, __wooksjs_event_cli.useCliOption)(keys[0]), formatParams(keys).join(", ")));
}
function CliGlobalOption(option) {
const mate = getCliMate();
return mate.decorate("cliOptions", option, true);
}
//#endregion
//#region packages/event-cli/src/event-cli.ts
function _define_property$1(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
const LOGGER_TITLE = "moost-cli";
const CONTEXT_TYPE = "CLI";
var MoostCli = class {
async onNotFound() {
const pathParams = (0, __wooksjs_event_cli.useCliContext)().store("event").get("pathParams") || [];
const response = await (0, moost.defineMoostEventHandler)({
loggerTitle: LOGGER_TITLE,
getIterceptorHandler: () => this.moost?.getGlobalInterceptorHandler(),
getControllerInstance: () => this.moost,
callControllerMethod: () => undefined,
logErrors: this.opts?.debug,
targetPath: "",
handlerType: "__SYSTEM__"
})();
if (response === undefined) this.cliApp.onUnknownCommand(pathParams);
return response;
}
onInit(moost$1) {
this.moost = moost$1;
const boolean = Object.entries(this.optionTypes).filter(([_key, val]) => val.length === 1 && val[0] === Boolean).map(([key, _val]) => key);
this.cliApp.run(undefined, { boolean });
}
bindHandler(opts) {
let fn;
for (const handler of opts.handlers) {
if (handler.type !== "CLI") continue;
const path = typeof handler.path === "string" ? handler.path : typeof opts.method === "string" ? opts.method : "";
const prefix = opts.prefix.replace(/\s+/g, "/") || "";
const makePath = (p) => `${prefix}/${p}`.replace(/\/\/+/g, "/").replace(/\/\\:/g, "\\:").replace(/^\/+/g, "");
const targetPath = makePath(path);
fn = (0, moost.defineMoostEventHandler)({
contextType: CONTEXT_TYPE,
loggerTitle: LOGGER_TITLE,
getIterceptorHandler: opts.getIterceptorHandler,
getControllerInstance: opts.getInstance,
controllerMethod: opts.method,
resolveArgs: opts.resolveArgs,
logErrors: this.opts?.debug,
targetPath,
handlerType: handler.type
});
const meta = getCliMate().read(opts.fakeInstance, opts.method);
const classMeta = getCliMate().read(opts.fakeInstance);
const cliOptions = new Map();
[
...this.opts?.globalCliOptions?.length ? this.opts.globalCliOptions : [],
...classMeta?.cliOptions || [],
...meta?.params ? meta.params.filter((param) => param.cliOptionsKeys?.length).map((param) => ({
keys: param.cliOptionsKeys,
value: typeof param.value === "string" ? param.value : "",
description: param.description || "",
type: param.type
})) : []
].forEach((o) => cliOptions.set(o.keys[0], o));
const aliases = [];
if (meta?.cliAliases) for (const alias of meta.cliAliases) {
const targetPath$1 = makePath(alias);
aliases.push(targetPath$1);
}
const cliOptionsArray = Array.from(cliOptions.values());
cliOptionsArray.forEach((o) => {
for (const key of o.keys) {
if (!this.optionTypes[key]) this.optionTypes[key] = [];
if (!this.optionTypes[key].includes(o.type)) this.optionTypes[key].push(o.type);
}
});
const args = {};
meta?.params.filter((p) => p.paramSource === "ROUTE" && p.description).forEach((p) => args[p.paramName] = p.description);
const routerBinding = this.cliApp.cli(targetPath, {
description: meta?.description || "",
options: cliOptionsArray,
args,
aliases,
examples: meta?.cliExamples || [],
handler: fn,
onRegister: (path$1, aliasType, route) => {
opts.register(handler, path$1, route?.getArgs() || routerBinding.getArgs());
if (this.opts?.debug) opts.logHandler(`${"\x1B[36m"}(${aliasTypes[aliasType]})${"\x1B[32m"}${path$1}`);
}
});
opts.register(handler, targetPath, routerBinding.getArgs());
}
}
constructor(opts) {
_define_property$1(this, "opts", void 0);
_define_property$1(this, "name", void 0);
_define_property$1(this, "cliApp", void 0);
_define_property$1(this, "optionTypes", void 0);
_define_property$1(this, "moost", void 0);
this.opts = opts;
this.name = "cli";
this.optionTypes = {};
const cliAppOpts = opts?.wooksCli;
if (cliAppOpts && cliAppOpts instanceof __wooksjs_event_cli.WooksCli) this.cliApp = cliAppOpts;
else if (cliAppOpts) this.cliApp = (0, __wooksjs_event_cli.createCliApp)({
...cliAppOpts,
onNotFound: this.onNotFound.bind(this)
});
else this.cliApp = (0, __wooksjs_event_cli.createCliApp)({ onNotFound: this.onNotFound.bind(this) });
if (!opts?.debug) (0, moost.setInfactLoggingOptions)({
newInstance: false,
error: false,
warn: false
});
}
};
const aliasTypes = [
"CLI",
"CLI-alias",
"CLI-alias*",
"CLI-alias*"
];
//#endregion
//#region packages/event-cli/src/interceptors/help.interceptor.ts
const cliHelpInterceptor = (opts) => (0, moost.defineInterceptorFn)(() => {
try {
if ((0, __wooksjs_event_cli.useAutoHelp)(opts?.helpOptions, opts?.colors)) return "";
} catch (error) {}
if (opts?.lookupLevel) {
const { getMethod } = (0, moost.useControllerContext)();
if (!getMethod()) (0, __wooksjs_event_cli.useCommandLookupHelp)(opts.lookupLevel);
}
}, moost.TInterceptorPriority.BEFORE_ALL);
const CliHelpInterceptor = (...opts) => (0, moost.Intercept)(cliHelpInterceptor(...opts));
//#endregion
//#region packages/event-cli/src/quick-cli.ts
function _define_property(obj, key, value) {
if (key in obj) Object.defineProperty(obj, key, {
value,
enumerable: true,
configurable: true,
writable: true
});
else obj[key] = value;
return obj;
}
var CliApp = class extends moost.Moost {
/**
* Registers one or more CLI controllers.
*
* (Shortcut for `registerControllers` method.)
*
* @param {...(object|Function|[string, object|Function])} controllers - List of controllers.
* Each controller can be an object, a class, or a tuple with a name and the controller.
* @returns {this} The CliApp instance for method chaining.
*/ controllers(...controllers) {
return this.registerControllers(...controllers);
}
/**
* Configures the CLI help options.
*
* This method sets the help options for the CLI. It ensures that colored output is enabled
* (unless explicitly disabled) and that the lookup level defaults to 3 if not provided.
*
* @param {THelpOptions} helpOpts - Help options configuration.
* @param {boolean} helpOpts.colors - Enable colored output.
* @param {number} helpOpts.lookupLevel - Level for help lookup.
* @returns {this} The CliApp instance for method chaining.
*/ useHelp(helpOpts) {
this._helpOpts = helpOpts;
if (this._helpOpts.colors !== false) this._helpOpts.colors = true;
if (typeof this._helpOpts.lookupLevel !== "number") this._helpOpts.lookupLevel = 3;
return this;
}
/**
* Sets the global CLI options.
*
* @param {TMoostCliOpts['globalCliOptions']} globalOpts - Global options for the CLI.
* @returns {this} The CliApp instance for method chaining.
*/ useOptions(globalOpts) {
this._globalOpts = globalOpts;
return this;
}
/**
* Starts the CLI application.
*
* This method creates a MoostCli instance using the configured help and global options,
* attaches it via the adapter, applies the CLI help interceptor (if help options are set),
* and then initializes the application.
*
* @returns {any} The result of the initialization process.
*/ start() {
const cli = new MoostCli({
wooksCli: { cliHelp: this._helpOpts ? {
name: this._helpOpts.name,
title: this._helpOpts.title,
maxWidth: this._helpOpts.maxWidth,
maxLeft: this._helpOpts.maxLeft,
mark: this._helpOpts.mark
} : undefined },
globalCliOptions: this._globalOpts
});
this.adapter(cli);
if (this._helpOpts) this.applyGlobalInterceptors(cliHelpInterceptor({
colors: this._helpOpts.colors,
lookupLevel: this._helpOpts.lookupLevel
}));
return this.init();
}
constructor(...args) {
super(...args), _define_property(this, "_helpOpts", void 0), _define_property(this, "_globalOpts", void 0);
}
};
//#endregion
exports.Cli = Cli
exports.CliAlias = CliAlias
exports.CliApp = CliApp
exports.CliExample = CliExample
exports.CliGlobalOption = CliGlobalOption
exports.CliHelpInterceptor = CliHelpInterceptor
exports.CliOption = CliOption
Object.defineProperty(exports, 'Controller', {
enumerable: true,
get: function () {
return moost.Controller;
}
});
Object.defineProperty(exports, 'Description', {
enumerable: true,
get: function () {
return moost.Description;
}
});
Object.defineProperty(exports, 'Intercept', {
enumerable: true,
get: function () {
return moost.Intercept;
}
});
exports.MoostCli = MoostCli
Object.defineProperty(exports, 'Optional', {
enumerable: true,
get: function () {
return moost.Optional;
}
});
Object.defineProperty(exports, 'Param', {
enumerable: true,
get: function () {
return moost.Param;
}
});
exports.cliHelpInterceptor = cliHelpInterceptor
Object.defineProperty(exports, 'useCliContext', {
enumerable: true,
get: function () {
return __wooksjs_event_cli.useCliContext;
}
});