@h3ravel/console
Version:
CLI utilities for scaffolding, running migrations, tasks and for H3ravel.
885 lines (870 loc) • 31.8 kB
JavaScript
import { TableGuesser, Utils } from "./Utils-Dn22CO9s.js";
import { FileSystem, Logger, TaskManager } from "@h3ravel/shared";
import { Application, ConsoleCommand, ConsoleKernel, ServiceProvider } from "@h3ravel/core";
import { execa } from "execa";
import preferredPM from "preferred-pm";
import { glob, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { beforeLast } from "@h3ravel/support";
import dayjs from "dayjs";
import nodepath from "node:path";
import { Option, program } from "commander";
import { existsSync } from "node:fs";
import { fork } from "child_process";
import { dirname, join, resolve } from "path";
import { build } from "tsdown";
//#region src/Commands/BuildCommand.ts
var BuildCommand = class extends ConsoleCommand {
/**
* The name and signature of the console command.
*
* @var string
*/
signature = `build:
{--m|minify=false : Minify your bundle output}
`;
/**
* The console command description.
*
* @var string
*/
description = "Build the app for production";
async handle() {
try {
await this.fire();
} catch (e) {
Logger.error(e);
}
}
async fire() {
const outDir$1 = env("DIST_DIR", "dist");
const pm = (await preferredPM(base_path()))?.name ?? "pnpm";
const minify = this.option("minify");
const ENV_VARS = {
EXTENDED_DEBUG: Number(this.option("verbose", 0)) > 0 ? "true" : "false",
CLI_BUILD: "true",
NODE_ENV: "production",
DIST_DIR: outDir$1,
DIST_MINIFY: minify,
LOG_LEVEL: [
"silent",
"info",
"warn",
"error"
][Number(this.option("verbose", 0))]
};
const silent = ENV_VARS.LOG_LEVEL === "silent" ? "--silent" : null;
Logger.log([["\n INFO ", "bgBlue"], [" Creating Production Bundle", "white"]], "");
console.log("");
await TaskManager.taskRunner(Logger.log([[" SUCCESS ", "bgGreen"], [" Production Bundle Created", "white"]], "", false), async () => {
await execa(pm, [
"tsdown",
silent,
"--config-loader",
"unconfig",
"-c",
"tsdown.default.config.ts"
].filter((e) => e !== null), {
stdout: "inherit",
stderr: "inherit",
cwd: base_path(),
env: Object.assign({}, process.env, ENV_VARS)
});
console.log("");
});
}
};
//#endregion
//#region src/Commands/Command.ts
var Command = class extends ConsoleCommand {};
//#endregion
//#region src/logo.ts
const logo = String.raw`
111
111111111
1111111111 111111
111111 111 111111
111111 111 111111
11111 111 11111
1111111 111 1111111
111 11111 111 111111 111 1111 1111 11111111 1111
111 11111 1111 111111 111 1111 1111 1111 11111 1111
111 11111 11111 111 1111 1111 111111111111 111111111111 1111 1111111 1111
111 111111 1111 111 111111111111 111111 11111 1111 111 1111 11111111 1111 1111
111 111 11111111 111 1101 1101 111111111 11111111 1111 1111111111111111101
111 1111111111111111 1111 111 1111 1111 111 11111011 1111 111 1111111 1101 1111
111 11111 1110111111111111 111 1111 1111 1111111101 1111 111111111 1111011 111111111 1111
1111111 111110111110 111 1111 1111 111111 1111 11011101 10111 11111 1111
11011 111111 11 11111
111111 11101 111111
111111 111 111111
111111 111 111111
111111111
110
`;
const altLogo = String.raw`
_ _ _____ _
| | | |___ / _ __ __ ___ _____| |
| |_| | |_ \| '__/ _ \ \ / / _ \ |
| _ |___) | | | (_| |\ V / __/ |
|_| |_|____/|_| \__,_| \_/ \___|_|
`;
//#endregion
//#region src/Commands/ListCommand.ts
var ListCommand = class extends Command {
/**
* The name and signature of the console command.
*
* @var string
*/
signature = "list";
/**
* The console command description.
*
* @var string
*/
description = "List all available commands";
async handle() {
const options = [{
short: "-h",
long: "--help",
description: "Display help for the given command. When no command is given display help for the list command"
}].concat(this.program.options).map((e) => {
return Logger.describe(Logger.log(" " + [e.short, e.long].filter((e$1) => !!e$1).join(", "), "green", false), e.description, 25, false).join("");
});
const grouped = this.program.commands.map((e) => {
return Logger.describe(Logger.log(" " + e.name(), "green", false), e.description(), 25, false).join("");
}).reduce((acc, cmd) => {
/** strip colors before checking prefix */
const clean = cmd.replace(/\x1b\[\d+m/g, "");
const prefix = clean.includes(":") ? clean.split(":")[0].trim() : "__root__";
acc[prefix] ??= [];
/** keep original with colors */
acc[prefix].push(cmd);
return acc;
}, {});
const list = Object.entries(grouped).map(([group, cmds]) => {
const label = group === "__root__" ? "" : group;
return [Logger.log(label, "yellow", false), cmds.join("\n")].join("\n");
});
/** Ootput the app version */
Logger.log([["H3ravel Framework", "white"], [this.kernel.modulePackage.version, "green"]], " ");
console.log("");
console.log(altLogo);
console.log("");
Logger.log("Usage:", "yellow");
Logger.log(" command [options] [arguments]", "white");
console.log("");
/** Ootput the options */
Logger.log("Options:", "yellow");
console.log(options.join("\n").trim());
console.log("");
/** Ootput the commands */
Logger.log("Available Commands:", "yellow");
console.log(list.join("\n\n").trim());
}
};
//#endregion
//#region src/Commands/MakeCommand.ts
var MakeCommand = class extends Command {
/**
* The name and signature of the console command.
*
* @var string
*/
signature = `#make:
{controller : Create a new controller class.
| {--a|api : Exclude the create and edit methods from the controller}
| {--m|model= : Generate a resource controller for the given model}
| {--r|resource : Generate a resource controller class}
| {--force : Create the controller even if it already exists}
}
{resource : Create a new resource.
| {--c|collection : Create a resource collection}
| {--force : Create the resource even if it already exists}
}
{migration : Generates a new database migration class.
| {--l|type=ts : The file type to generate}
| {--t|table : The table to migrate}
| {--c|create : The table to be created}
}
{command : Create a new Musket command.
| {--command : The terminal command that will be used to invoke the class}
| {--force : Create the class even if the console command already exists}
}
{factory : Create a new model factory.}
{seeder : Create a new seeder class.}
{view : Create a new view.
| {--force : Create the view even if it already exists}
}
{model : Create a new Eloquent model class.
| {--api : Indicates if the generated controller should be an API resource controller}
| {--c|controller : Create a new controller for the model}
| {--f|factory : Create a new factory for the model}
| {--m|migration : Create a new migration file for the model}
| {--r|resource : Indicates if the generated controller should be a resource controller}
| {--a|all : Generate a migration, seeder, factory, policy, resource controller, and form request classes for the model}
| {--s|seed : Create a new seeder for the model}
| {--t|type=ts : The file type to generate}
| {--force : Create the model even if it already exists}
}
{^name : The name of the [name] to generate}
`;
/**
* The console command description.
*
* @var string
*/
description = "Generate component classes";
async handle() {
const command = this.dictionary.baseCommand ?? this.dictionary.name;
if (!this.argument("name")) this.program.error("Please provide a valid name for the " + command);
await this[{
controller: "makeController",
resource: "makeResource",
migration: "makeMigration",
factory: "makeFactory",
seeder: "makeSeeder",
model: "makeModel",
view: "makeView",
command: "makeCommand"
}[command]]();
}
/**
* Create a new controller class.
*/
async makeController() {
const type = this.option("api") ? "-resource" : "";
const name = this.argument("name");
const force = this.option("force");
const crtlrPath = FileSystem.findModulePkg("@h3ravel/http", this.kernel.cwd) ?? "";
const stubPath = nodepath.join(crtlrPath, `dist/stubs/controller${type}.stub`);
const path = app_path(`Http/Controllers/${name}.ts`);
/** The Controller is scoped to a path make sure to create the associated directories */
if (name.includes("/")) await mkdir(beforeLast(path, "/"), { recursive: true });
/** Check if the controller already exists */
if (!force && await FileSystem.fileExists(path)) Logger.error(`ERORR: ${name} controller already exists`);
let stub = await readFile(stubPath, "utf-8");
stub = stub.replace(/{{ name }}/g, name);
await writeFile(path, stub);
Logger.split("INFO: Controller Created", Logger.log(nodepath.basename(path), "gray", false));
}
makeResource() {
Logger.success("Resource support is not yet available");
}
/**
* Generate a new database migration class
*/
async makeMigration() {
const name = this.argument("name");
const datePrefix = dayjs().format("YYYY_MM_DD_HHmmss");
const path = database_path(`migrations/${datePrefix}_${name}.ts`);
const crtlrPath = FileSystem.findModulePkg("@h3ravel/database", this.kernel.cwd) ?? "";
let create = this.option("create", false);
let table = this.option("table");
if (!table && typeof create === "string") {
table = create;
create = true;
}
if (!table) {
const guessed = TableGuesser.guess(name);
table = guessed[0];
create = !!guessed[1];
}
const stubPath = nodepath.join(crtlrPath, this.getMigrationStubName(table, create));
let stub = await readFile(stubPath, "utf-8");
if (table !== null) stub = stub.replace(/DummyTable|{{\s*table\s*}}/g, table);
Logger.info("INFO: Creating Migration");
await this.kernel.ensureDirectoryExists(nodepath.dirname(path));
await writeFile(path, stub);
Logger.split("INFO: Migration Created", Logger.log(nodepath.basename(path), "gray", false));
}
/**
* Create a new model factory
*/
makeFactory() {
Logger.success("Factory support is not yet available");
}
/**
* Create a new Musket command
*/
makeCommand() {
Logger.success("Musket command creation is not yet available");
}
/**
* Create a new seeder class
*/
makeSeeder() {
Logger.success("Seeder support is not yet available");
}
/**
* Generate a new Arquebus model class
*/
async makeModel() {
const type = this.option("type", "ts");
const name = this.argument("name");
const force = this.option("force");
const path = app_path(`Models/${name.toLowerCase()}.${type}`);
/** The model is scoped to a path make sure to create the associated directories */
if (name.includes("/")) await mkdir(beforeLast(path, "/"), { recursive: true });
/** Check if the model already exists */
if (!force && await FileSystem.fileExists(path)) Logger.error(`ERORR: ${name} model already exists`);
const crtlrPath = FileSystem.findModulePkg("@h3ravel/database", this.kernel.cwd) ?? "";
const stubPath = nodepath.join(crtlrPath, `dist/stubs/model-${type}.stub`);
let stub = await readFile(stubPath, "utf-8");
stub = stub.replace(/{{ name }}/g, name);
await writeFile(path, stub);
Logger.split(`INFO: ${name} Model Created`, Logger.log(nodepath.basename(path), "gray", false));
}
/**
* Create a new view.
*/
async makeView() {
const name = this.argument("name");
const force = this.option("force");
const path = base_path(`src/resources/views/${name}.edge`);
/** The view is scoped to a path make sure to create the associated directories */
if (name.includes("/")) await mkdir(beforeLast(path, "/"), { recursive: true });
/** Check if the view already exists */
if (!force && await FileSystem.fileExists(path)) Logger.error(`ERORR: ${name} view already exists`);
await writeFile(path, `{{-- src/resources/views/${name}.edge --}}`);
Logger.split("INFO: View Created", Logger.log(`src/resources/views/${name}.edge`, "gray", false));
}
/**
* Ge the database migration file name
*
* @param table
* @param create
* @param type
* @returns
*/
getMigrationStubName(table, create = false, type = "ts") {
let stub;
if (!table) stub = `migration-${type}.stub`;
else if (create) stub = `migration.create-${type}.stub`;
else stub = `migration.update-${type}.stub`;
return "dist/stubs/" + stub;
}
};
//#endregion
//#region src/Commands/PostinstallCommand.ts
var PostinstallCommand = class extends Command {
/**
* The name and signature of the console command.
*
* @var string
*/
signature = "postinstall";
/**
* The console command description.
*
* @var string
*/
description = "Default post installation command";
async handle() {
this.createSqliteDB();
}
/**
* Create sqlite database if none exist
*
* @returns
*/
async createSqliteDB() {
if (config("database.default") !== "sqlite") return;
if (!await FileSystem.fileExists(database_path())) await mkdir(database_path(), { recursive: true });
if (!await FileSystem.fileExists(database_path("db.sqlite"))) await writeFile(database_path("db.sqlite"), "");
}
};
//#endregion
//#region src/Signature.ts
var Signature = class Signature {
/**
* Helper to parse options inside a block of text
*
* @param block
* @returns
*/
static parseOptions(block) {
const options = [];
/**
* Match { ... } blocks at top level
*/
const regex = /\{([^{}]+(?:\{[^{}]*\}[^{}]*)*)\}/g;
let match;
while ((match = regex.exec(block)) !== null) {
const shared = "^" === match[1][0] || /:[#^]/.test(match[1]);
const isHidden = (["#", "^"].includes(match[1][0]) || /:[#^]/.test(match[1])) && !shared;
const content = match[1].trim().replace(/[#^]/, "");
/**
* Split by first ':' to separate name and description+nested
*/
const colonIndex = content.indexOf(":");
if (colonIndex === -1) {
/**
* No description, treat whole as name
*/
options.push({ name: content });
continue;
}
const namePart = content.substring(0, colonIndex).trim();
const rest = content.substring(colonIndex + 1).trim();
/**
* Check for nested options after '|'
*/
let description = rest;
let nestedOptions;
const pipeIndex = rest.indexOf("|");
if (pipeIndex !== -1) {
description = rest.substring(0, pipeIndex).trim();
/**
* nestedText should start with '{' and end with ')', clean it
* Also Remove trailing ')' if present
*/
const cleanedNestedText = rest.substring(pipeIndex + 1).trim().replace(/^\{/, "").trim();
/**
* Parse nested options recursively
*/
nestedOptions = Signature.parseOptions("{" + cleanedNestedText + "}");
} else
/**
* Trim the string
*/
description = description.trim();
/**
* Parse name modifiers (?, *, ?*)
*/
let name = namePart;
let required = /[^a-zA-Z0-9_|-]/.test(name);
let multiple = false;
if (name.endsWith("?*")) {
required = false;
multiple = true;
name = name.slice(0, -2);
} else if (name.endsWith("*")) {
multiple = true;
name = name.slice(0, -1);
} else if (name.endsWith("?")) {
required = false;
name = name.slice(0, -1);
}
/**
* Check if it's a flag option (starts with --)
*/
const isFlag = name.startsWith("--");
let flags;
let defaultValue;
if (isFlag) {
/**
* Parse flags and default values
*/
const flagParts = name.split("|").map((s) => s.trim());
flags = [];
for (let part of flagParts) {
if (part.startsWith("--") && part.slice(2).length === 1) part = "-" + part.slice(2);
else if (part.startsWith("-") && !part.startsWith("--") && part.slice(1).length > 1) part = "--" + part.slice(1);
else if (!part.startsWith("-") && part.slice(1).length > 1) part = "--" + part;
const eqIndex = part.indexOf("=");
if (eqIndex !== -1) {
flags.push(part.substring(0, eqIndex));
const val = part.substring(eqIndex + 1);
if (val === "*") defaultValue = [];
else if (val === "true" || val === "false" || !val && !required) defaultValue = val === "true";
else if (!isNaN(Number(val))) defaultValue = Number(val);
else defaultValue = val;
} else flags.push(part);
}
}
options.push({
name: isFlag ? flags[flags.length - 1] : name,
required,
multiple,
description,
flags,
shared,
isFlag,
isHidden,
defaultValue,
nestedOptions
});
}
return options;
}
/**
* Helper to parse a command's signature
*
* @param signature
* @param commandClass
* @returns
*/
static parseSignature(signature, commandClass) {
const lines = signature.split("\n").map((l) => l.trim()).filter((l) => l.length > 0);
const isHidden = ["#", "^"].includes(lines[0][0]) || /:[#^]/.test(lines[0]);
const baseCommand = lines[0].replace(/[^\w=:-]/g, "");
const description = commandClass.getDescription();
const isNamespaceCommand = baseCommand.endsWith(":");
/**
* Join the rest lines to a single string for parsing
*/
const rest = lines.slice(1).join(" ");
/**
* Parse all top-level options/subcommands
*/
const allOptions = Signature.parseOptions(rest);
if (isNamespaceCommand)
/**
* Separate subcommands (those without flags) and base options (flags)
* Here we assume subcommands are those without flags (isFlag false)
* and base options are flags or options after subcommands
* For simplicity, treat all top-level options as subcommands
* and assume base command options come after subcommands in signature (not shown in example)
*/
return {
baseCommand: baseCommand.slice(0, -1),
isNamespaceCommand,
subCommands: allOptions.filter((e) => !e.flags && !e.isHidden),
description,
commandClass,
options: allOptions.filter((e) => !!e.flags),
isHidden
};
else return {
baseCommand,
isNamespaceCommand,
options: allOptions,
description,
commandClass,
isHidden
};
}
};
//#endregion
//#region ../../node_modules/.pnpm/@rollup+plugin-run@3.1.0/node_modules/@rollup/plugin-run/dist/es/index.js
function run(opts = {}) {
let input;
let proc;
const args = opts.args || [];
const allowRestarts = opts.allowRestarts || false;
const overrideInput = opts.input;
const forkOptions = opts.options || opts;
delete forkOptions.args;
delete forkOptions.allowRestarts;
return {
name: "run",
buildStart(options) {
let inputs = overrideInput !== null && overrideInput !== void 0 ? overrideInput : options.input;
if (typeof inputs === "string") inputs = [inputs];
if (typeof inputs === "object") inputs = Object.values(inputs);
if (inputs.length > 1) throw new Error(`@rollup/plugin-run must have a single entry point; consider setting the \`input\` option`);
input = resolve(inputs[0]);
},
generateBundle(_outputOptions, _bundle, isWrite) {
if (!isWrite) this.error(`@rollup/plugin-run currently only works with bundles that are written to disk`);
},
writeBundle(outputOptions, bundle) {
const forkBundle = (dir$1, entryFileName$1) => {
if (proc) proc.kill();
proc = fork(join(dir$1, entryFileName$1), args, forkOptions);
};
const dir = outputOptions.dir || dirname(outputOptions.file);
const entryFileName = Object.keys(bundle).find((fileName) => {
const chunk = bundle[fileName];
return chunk.isEntry && chunk.facadeModuleId === input;
});
if (entryFileName) {
forkBundle(dir, entryFileName);
if (allowRestarts) {
process.stdin.resume();
process.stdin.setEncoding("utf8");
process.stdin.on("data", (data) => {
const line = data.toString().trim().toLowerCase();
if (line === "rs" || line === "restart" || data.toString().charCodeAt(0) === 11) forkBundle(dir, entryFileName);
else if (line === "cls" || line === "clear" || data.toString().charCodeAt(0) === 12) console.clear();
});
}
} else this.error(`@rollup/plugin-run could not find output chunk`);
}
};
}
//#endregion
//#region src/TsdownConfig.ts
const env$1 = process.env.NODE_ENV || "development";
let outDir = env$1 === "development" ? ".h3ravel/serve" : "dist";
if (process.env.DIST_DIR) outDir = process.env.DIST_DIR;
const TsDownConfig = {
outDir,
entry: ["src/**/*.ts"],
format: ["esm"],
target: "node22",
sourcemap: env$1 === "development",
minify: !!process.env.DIST_MINIFY,
external: [/^@h3ravel\/.*/gi],
clean: true,
shims: true,
copy: [
{
from: "public",
to: outDir
},
"src/resources",
"src/database"
],
env: env$1 === "development" ? {
NODE_ENV: env$1,
DIST_DIR: outDir
} : {},
watch: env$1 === "development" && process.env.CLI_BUILD !== "true" ? [
".env",
".env.*",
"src",
"../../packages"
] : false,
dts: false,
logLevel: "silent",
nodeProtocol: true,
skipNodeModulesBundle: true,
hooks(e) {
e.hook("build:done", async () => {
const paths = [
"database/migrations",
"database/factories",
"database/seeders"
];
for (let i = 0; i < paths.length; i++) {
const name = paths[i];
if (existsSync(nodepath.join(outDir, name))) await rm(nodepath.join(outDir, name), { recursive: true });
}
});
},
plugins: env$1 === "development" && process.env.CLI_BUILD !== "true" ? [run({
env: Object.assign({}, process.env, {
NODE_ENV: env$1,
DIST_DIR: outDir
}),
execArgv: ["-r", "source-map-support/register"],
allowRestarts: false,
input: process.cwd() + "/src/server.ts"
})] : []
};
var TsdownConfig_default = TsDownConfig;
//#endregion
//#region src/Musket.ts
/**
* Musket is H3ravel's CLI tool
*/
var Musket = class Musket {
commands = [];
constructor(app, kernel) {
this.app = app;
this.kernel = kernel;
}
async build() {
this.loadBaseCommands();
await this.loadDiscoveredCommands();
return this.initialize();
}
loadBaseCommands() {
[
new MakeCommand(this.app, this.kernel),
new ListCommand(this.app, this.kernel),
new PostinstallCommand(this.app, this.kernel),
new BuildCommand(this.app, this.kernel)
].forEach((e) => this.addCommand(e));
}
async loadDiscoveredCommands() {
const DIST_DIR = `/${env("DIST_DIR", ".h3ravel/serve")}/`.replaceAll("//", "");
const commands = [...this.app.registeredCommands.map((cmd) => new cmd(this.app, this.kernel))];
/**
* Musket Commands auto registration
*/
const providers_path = app_path("Console/Commands/*.js").replace("/src/", DIST_DIR);
/** Add the App Commands */
for await (const cmd of glob(providers_path)) {
const name = nodepath.basename(cmd).replace(".js", "");
try {
const cmdClass = (await import(cmd))[name];
commands.push(new cmdClass(this.app, this.kernel));
} catch {}
}
commands.forEach((e) => this.addCommand(e));
}
addCommand(command) {
this.commands.push(Signature.parseSignature(command.getSignature(), command));
}
initialize() {
/** Init the Musket Version */
const cliVersion = Logger.parse([["Musket CLI:", "white"], [this.kernel.consolePackage.version, "green"]], " ", false);
/** Init the App Version */
const localVersion = Logger.parse([["H3ravel Framework:", "white"], [this.kernel.modulePackage.version, "green"]], " ", false);
const additional = {
quiet: ["-q, --quiet", "Do not output any message"],
silent: ["--silent", "Do not output any message"],
verbose: ["-v, --verbose <number>", "Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug"],
lock: ["--lock", "Locked and loaded, do not ask any interactive question"]
};
/** Init Commander */
program.name("musket").version(`${cliVersion}\n${localVersion}`).description(altLogo).addOption(new Option(additional.quiet[0], additional.quiet[1]).implies({ silent: true })).addOption(new Option(additional.silent[0], additional.silent[1]).implies({ quiet: true })).addOption(new Option(additional.verbose[0], additional.verbose[1]).choices([
"1",
"2",
"3"
])).addOption(new Option(additional.lock[0], additional.lock[1])).action(async () => {
const instance = new ListCommand(this.app, this.kernel);
instance.setInput(program.opts(), program.args, program.registeredArguments, {}, program);
instance.handle();
});
/** Create the init Command */
program.command("init").description("Initialize H3ravel.").action(async () => {
Logger.success("Initialized: H3ravel has been initialized!");
});
/** Loop through all the available commands */
for (let i = 0; i < this.commands.length; i++) {
const command = this.commands[i];
const instance = command.commandClass;
if (command.isNamespaceCommand && command.subCommands) {
/**
* Initialize the base command
*/
const cmd = command.isHidden ? program : program.command(command.baseCommand).description(command.description ?? "").addOption(new Option(additional.quiet[0], additional.quiet[1]).implies({ silent: true })).addOption(new Option(additional.silent[0], additional.silent[1]).implies({ quiet: true })).addOption(new Option(additional.verbose[0], additional.verbose[1]).choices([
"1",
"2",
"3"
])).addOption(new Option(additional.lock[0], additional.lock[1])).action(async () => {
instance.setInput(cmd.opts(), cmd.args, cmd.registeredArguments, command, program);
await instance.handle();
});
/**
* Add options to the base command if it has any
*/
if ((command.options?.length ?? 0) > 0) command.options?.filter((v, i$1, a) => a.findIndex((t) => t.name === v.name) === i$1).forEach((opt) => {
this.makeOption(opt, cmd);
});
/**
* Initialize the sub commands
*/
command.subCommands.filter((v, i$1, a) => !v.shared && a.findIndex((t) => t.name === v.name) === i$1).forEach((sub) => {
const cmd$1 = program.command(`${command.baseCommand}:${sub.name}`).description(sub.description || "").addOption(new Option(additional.quiet[0], additional.quiet[1]).implies({ silent: true })).addOption(new Option(additional.silent[0], additional.silent[1]).implies({ quiet: true })).addOption(new Option(additional.verbose[0], additional.verbose[1]).choices([
"1",
"2",
"3"
])).addOption(new Option(additional.lock[0], additional.lock[1])).action(async () => {
instance.setInput(cmd$1.opts(), cmd$1.args, cmd$1.registeredArguments, sub, program);
await instance.handle();
});
/**
* Add the shared arguments here
*/
command.subCommands?.filter((e) => e.shared).forEach((opt) => {
this.makeOption(opt, cmd$1, false, sub);
});
/**
* Add the shared options here
*/
command.options?.filter((e) => e.shared).forEach((opt) => {
this.makeOption(opt, cmd$1, false, sub);
});
/**
* Add options to the sub command if it has any
*/
if (sub.nestedOptions) sub.nestedOptions.filter((v, i$1, a) => a.findIndex((t) => t.name === v.name) === i$1).forEach((opt) => {
this.makeOption(opt, cmd$1);
});
});
} else {
/**
* Initialize command with options
*/
const cmd = program.command(command.baseCommand).description(command.description ?? "");
command?.options?.filter((v, i$1, a) => a.findIndex((t) => t.name === v.name) === i$1).forEach((opt) => {
this.makeOption(opt, cmd, true);
});
cmd.action(async () => {
instance.setInput(cmd.opts(), cmd.args, cmd.registeredArguments, command, program);
await instance.handle();
});
}
}
/** Rebuild the app on every command except fire so we wont need TS */
program.hook("preAction", async (_, cmd) => {
if (cmd.name() !== "fire") await build({
...TsdownConfig_default,
watch: false,
plugins: []
});
});
return program;
}
makeOption(opt, cmd, parse, parent) {
const description = opt.description?.replace(/\[(\w+)\]/g, (_, k) => parent?.[k] ?? `[${k}]`) ?? "";
const type = opt.name.replaceAll("-", "");
if (opt.isFlag) if (parse) {
const flags = opt.flags?.map((f) => f.length === 1 ? `-${f}` : `--${f}`).join(", ").replaceAll("----", "--").replaceAll("---", "-");
cmd.option(flags || "", description, String(opt.defaultValue) || void 0);
} else cmd.option(opt.flags?.join(", ") + (opt.required ? ` <${type}>` : ""), description, opt.defaultValue);
else cmd.argument(opt.required ? `<${opt.name}>` : `[${opt.name}]`, description, opt.defaultValue);
}
static async parse(kernel) {
return (await new Musket(kernel.app, kernel).build()).parseAsync();
}
};
//#endregion
//#region src/Kernel.ts
var Kernel = class Kernel extends ConsoleKernel {
constructor(app) {
super(app);
this.app = app;
}
static init(app) {
const instance = new Kernel(app);
Promise.all([instance.loadRequirements()]).then(([e]) => e.run());
}
async run() {
await Musket.parse(this);
process.exit(0);
}
async loadRequirements() {
this.cwd = nodepath.join(process.cwd(), this.basePath);
this.modulePath = FileSystem.findModulePkg("@h3ravel/core", this.cwd) ?? "";
this.consolePath = FileSystem.findModulePkg("@h3ravel/console", this.cwd) ?? "";
try {
this.modulePackage = await import(nodepath.join(this.modulePath, "package.json"));
} catch {
this.modulePackage = { version: "N/A" };
}
try {
this.consolePackage = await import(nodepath.join(this.consolePath, "package.json"));
} catch {
this.consolePackage = { version: "N/A" };
}
return this;
}
};
//#endregion
//#region src/Providers/ConsoleServiceProvider.ts
/**
* Handles CLI commands and tooling.
*
* Register DatabaseManager and QueryBuilder.
* Set up ORM models and relationships.
* Register migration and seeder commands.
*
* Auto-Registered when in CLI mode
*/
var ConsoleServiceProvider = class extends ServiceProvider {
static priority = 992;
/**
* Indicate that this service provider only runs in console
*/
static console = true;
console = true;
register() {}
boot() {
Kernel.init(this.app);
process.on("SIGINT", () => {
process.exit(0);
});
process.on("SIGTERM", () => {
process.exit(0);
});
}
};
//#endregion
export { BuildCommand, Command, ConsoleServiceProvider, Kernel, ListCommand, MakeCommand, Musket, PostinstallCommand, Signature, TableGuesser, TsDownConfig, Utils, altLogo, logo };
//# sourceMappingURL=index.js.map