@h3ravel/console
Version:
CLI utilities for scaffolding, running migrations, tasks and for H3ravel.
56 lines (55 loc) • 11.6 kB
JavaScript
import"./zero-Dv_r7pNi.js";import"tsx/esm";import{Application as e,ContainerResolver as t,ServiceProvider as n}from"@h3ravel/core";import{FileSystem as r,Logger as i,TaskManager as a}from"@h3ravel/shared";import{Command as o,Kernel as s}from"@h3ravel/musket";import{execa as c}from"execa";import l from"preferred-pm";import{copyFile as u,readFile as d,writeFile as f}from"fs/promises";import p from"crypto";import m from"dotenv";import{mkdir as h,readFile as g,rm as _,writeFile as v}from"node:fs/promises";import{Str as y}from"@h3ravel/support";import b from"node:path";import{existsSync as x}from"node:fs";import{fork as S}from"child_process";import{dirname as C,join as w,resolve as T}from"path";var E=class e extends o{signature=`build
{--m|minify : Minify your bundle output}
{--d|dev : Build for dev but don't watch for changes}
`;description=`Build the app for production`;async handle(){try{await this.fire()}catch(e){i.error(e)}}async fire(){let t=this.option(`dev`)?`.h3ravel/serve`:env(`DIST_DIR`,`dist`),n=this.option(`minify`),r=this.getVerbosity(),i=r>0;this.newLine(),await e.build({outDir:t,minify:n,verbosity:r,debug:i,mute:!1}),this.newLine()}static async build({debug:e,minify:t,mute:n,verbosity:r,outDir:i}={mute:!1,debug:!1,minify:!1,verbosity:0,outDir:`dist`}){let o=(await l(base_path()))?.name??`pnpm`,s={EXTENDED_DEBUG:e?`true`:`false`,CLI_BUILD:`true`,NODE_ENV:`production`,DIST_DIR:i,DIST_MINIFY:t,LOG_LEVEL:[`silent`,`info`,`warn`,`error`][r]},u=s.LOG_LEVEL===`silent`?`--silent`:null;if(n)return await c(o,[`tsdown`,u,`--config-loader`,`unconfig`,`-c`,`tsdown.default.config.ts`].filter(e=>e!==null),{stdout:`inherit`,stderr:`inherit`,cwd:base_path(),env:Object.assign({},process.env,s)});let d=i===`dist`?`Production`:`Development`;return await a.advancedTaskRunner([[`Creating ${d} Bundle`,`STARTED`],[`${d} Bundle Created`,`COMPLETED`]],async()=>{await c(o,[`tsdown`,u,`--config-loader`,`unconfig`,`-c`,`tsdown.default.config.ts`].filter(e=>e!==null),{stdout:`inherit`,stderr:`inherit`,cwd:base_path(),env:Object.assign({},process.env,s)})})}},D=class extends o{signature=`key:generate
{--force: Force the operation to run when in production}
{--show: Display the key instead of modifying files}
`;description=`Set the application key`;async handle(){let e={key:p.randomBytes(32).toString(`base64`),envPath:base_path(`.env`),egEnvPath:base_path(`.env.example`),updated:!1,show:this.option(`show`)};this.newLine(),await r.fileExists(e.envPath)||(await r.fileExists(e.egEnvPath)?await u(e.egEnvPath,e.envPath):(this.error(`.env file not found.`),this.newLine(),process.exit(0)));let t=await d(e.envPath,`utf8`),n=Buffer.from(t),a=m.parse(n);if(e.show){(!a.APP_KEY||a.APP_KEY===``)&&(this.error(`Application key not set.`),this.newLine(),process.exit(0));let[e,t]=a.APP_KEY.split(`:`);i.log([[e,`yellow`],[t,`white`]],`:`),this.newLine(),process.exit(0)}else a.APP_ENV===`production`&&!this.option(`force`)&&(this.error(`Application is currently in production, failed to set key.`),this.newLine(),process.exit(1));/^APP_KEY=.*$/m.test(t)?(e.updated=!0,t=t.replace(/^APP_KEY=.*$/m,`APP_KEY=base64:${e.key}`)):(e.updated=!1,t=`APP_KEY=base64:${e.key}\n\n${t}`),await f(e.envPath,t,`utf8`),this.success(`Application key set successfully.`),this.newLine()}},O=class extends o{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}
}
{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}
}
{view : Create a new view.
| {--force : Create the view even if it already exists}
}
{^name : The name of the [name] to generate}
`;description=`Generate component classes`;async handle(){let e=this.dictionary.baseCommand??this.dictionary.name;this.argument(`name`)||this.program.error(`Please provide a valid name for the `+e),await this[{controller:`makeController`,resource:`makeResource`,view:`makeView`,command:`makeCommand`}[e]]()}async makeController(){let e=this.option(`api`)?`-resource`:``,t=this.argument(`name`),n=this.option(`force`),a=r.findModulePkg(`@h3ravel/http`,this.kernel.cwd)??``,o=b.join(a,`dist/stubs/controller${e}.stub`),s=app_path(`Http/Controllers/${t}.ts`);t.includes(`/`)&&await h(y.beforeLast(s,`/`),{recursive:!0}),!n&&await r.fileExists(s)&&i.error(`ERORR: ${t} controller already exists`);let c=await g(o,`utf-8`);c=c.replace(/{{ name }}/g,t),await v(s,c),i.split(`INFO: Controller Created`,i.log(b.basename(s),`gray`,!1))}makeResource(){i.success(`Resource support is not yet available`)}makeCommand(){i.success(`Musket command creation is not yet available`)}async makeView(){let e=this.argument(`name`),t=this.option(`force`),n=base_path(`src/resources/views/${e}.edge`);e.includes(`/`)&&await h(y.beforeLast(n,`/`),{recursive:!0}),!t&&await r.fileExists(n)&&i.error(`ERORR: ${e} view already exists`),await v(n,`{{-- src/resources/views/${e}.edge --}}`),i.split(`INFO: View Created`,i.log(`src/resources/views/${e}.edge`,`gray`,!1))}},k=class extends o{signature=`postinstall`;description=`Default post installation command`;async handle(){this.genEncryptionKey(),this.createSqliteDB()}async genEncryptionKey(){new D(this.app,this.kernel).setProgram(this.program).setOption(`force`,!0).setOption(`silent`,!0).setOption(`quiet`,!0).setInput({force:!0,silent:!0,quiet:!0},[],[],{},this.program).handle()}async createSqliteDB(){config(`database.default`)===`sqlite`&&(await r.fileExists(database_path())||await h(database_path(),{recursive:!0}),await r.fileExists(database_path(`db.sqlite`))||await v(database_path(`db.sqlite`),``))}};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 A=String.raw`
_ _ _____ _
| | | |___ / _ __ __ ___ _____| |
| |_| | |_ \| '__/ _ \ \ / / _ \ |
| _ |___) | | | (_| |\ V / __/ |
|_| |_|____/|_| \__,_| \_/ \___|_|
`;function j(e={}){let t,n,r=e.args||[],i=e.allowRestarts||!1,a=e.input,o=e.options||e;return delete o.args,delete o.allowRestarts,{name:`run`,buildStart(e){let n=a??e.input;if(typeof n==`string`&&(n=[n]),typeof n==`object`&&(n=Object.values(n)),n.length>1)throw Error("@rollup/plugin-run must have a single entry point; consider setting the `input` option");t=T(n[0])},generateBundle(e,t,n){n||this.error(`@rollup/plugin-run currently only works with bundles that are written to disk`)},writeBundle(e,a){let s=(e,t)=>{n&&n.kill(),n=S(w(e,t),r,o)},c=e.dir||C(e.file),l=Object.keys(a).find(e=>{let n=a[e];return n.isEntry&&n.facadeModuleId===t});l?(s(c,l),i&&(process.stdin.resume(),process.stdin.setEncoding(`utf8`),process.stdin.on(`data`,e=>{let t=e.toString().trim().toLowerCase();t===`rs`||t===`restart`||e.toString().charCodeAt(0)===11?s(c,l):(t===`cls`||t===`clear`||e.toString().charCodeAt(0)===12)&&console.clear()}))):this.error(`@rollup/plugin-run could not find output chunk`)}}}const M=process.env.NODE_ENV||`development`;let N=M===`development`?`.h3ravel/serve`:`dist`;process.env.DIST_DIR&&(N=process.env.DIST_DIR);var P={outDir:N,outExtensions:e=>({js:e.format===`es`?`.js`:`.cjs`,dts:`.d.ts`}),entry:[`src/**/*.ts`],format:[`esm`],target:`node22`,sourcemap:M===`development`,minify:!!process.env.DIST_MINIFY,external:[/^@h3ravel\/.*/gi],clean:!0,shims:!0,copy:[{from:`public`,to:N},`src/resources`,`src/database`],env:M===`development`?{NODE_ENV:M,DIST_DIR:N}:{},watch:M===`development`&&process.env.CLI_BUILD!==`true`?[`.env`,`.env.*`,`src`,`../../packages`]:!1,dts:!1,logLevel:`silent`,nodeProtocol:!0,skipNodeModulesBundle:!0,hooks(e){e.hook(`build:done`,async()=>{let e=[`database/migrations`,`database/factories`,`database/seeders`];for(let t=0;t<e.length;t++){let n=e[t];x(b.join(N,n))&&await _(b.join(N,n),{recursive:!0})}})},plugins:M===`development`&&process.env.CLI_BUILD!==`true`?[j({env:Object.assign({},process.env,{NODE_ENV:M,DIST_DIR:N}),execArgv:[`-r`,`source-map-support/register`],allowRestarts:!1,input:process.cwd()+`/src/server.ts`})]:[]},F=class extends n{static priority=992;static runsInConsole=!0;runsInConsole=!0;register(){let e=`/${env(`DIST_DIR`,`.h3ravel/serve`)}/`.replaceAll(`//`,``),n=[E,O,k,D];s.init(this.app,{logo:A,resolver:new t(this.app).resolveMethodParams,tsDownConfig:P,baseCommands:n,packages:[{name:`@h3ravel/core`,alias:`H3ravel Framework`},{name:`@h3ravel/musket`,alias:`Musket CLI`}],cliName:`musket`,hideMusketInfo:!0,discoveryPaths:[app_path(`Console/Commands/*.js`).replace(`/src/`,e)]}),[`SIGINT`,`SIGTERM`,`SIGTSTP`].forEach(e=>process.on(e,()=>{process.exit(0)}))}};new class{async fire(){let t=process.env.DIST_DIR??`/.h3ravel/serve/`,n=[],r=new e(process.cwd()),i=base_path(b.join(t,`bootstrap/providers.js`));try{n.push(...(await import(i)).default)}catch{}n.push(F),await r.quickStartup(n,[`CoreServiceProvider`])}}().fire();export{};