@aerogel/cli 0.0.0-next.926bde19326fe7b6b24b277666936862b64d8295 → 0.0.0-next.b85327579d32f21c6a9fa21142f0165cdd320d7e

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.
Files changed (42) hide show
  1. package/dist/aerogel-cli.cjs.js +1 -1
  2. package/dist/aerogel-cli.esm.js +1 -1
  3. package/noeldemartin.config.js +11 -1
  4. package/package.json +3 -2
  5. package/src/cli.ts +4 -0
  6. package/src/commands/create.test.ts +12 -4
  7. package/src/commands/create.ts +16 -2
  8. package/src/commands/generate-component.test.ts +12 -1
  9. package/src/commands/generate-component.ts +128 -19
  10. package/src/commands/generate-model.test.ts +7 -4
  11. package/src/commands/generate-model.ts +30 -20
  12. package/src/commands/generate-service.test.ts +21 -0
  13. package/src/commands/generate-service.ts +152 -0
  14. package/src/commands/install.test.ts +18 -0
  15. package/src/commands/install.ts +32 -0
  16. package/src/lib/App.ts +64 -2
  17. package/src/lib/Editor.ts +51 -0
  18. package/src/lib/File.ts +6 -0
  19. package/src/lib/Log.mock.ts +2 -1
  20. package/src/lib/Log.ts +6 -4
  21. package/src/lib/utils/app.ts +15 -0
  22. package/src/lib/utils/edit.ts +44 -0
  23. package/src/lib/{utils.test.ts → utils/format.test.ts} +2 -2
  24. package/src/lib/{utils.ts → utils/format.ts} +0 -6
  25. package/src/lib/utils/paths.ts +30 -0
  26. package/src/plugins/Plugin.ts +125 -0
  27. package/src/plugins/Solid.ts +65 -0
  28. package/src/plugins/Soukai.ts +19 -0
  29. package/src/testing/setup.ts +31 -6
  30. package/templates/app/.eslintrc.js +3 -0
  31. package/templates/app/.vscode/launch.json +16 -0
  32. package/templates/app/.vscode/settings.json +10 -0
  33. package/templates/app/cypress.config.ts +4 -0
  34. package/templates/app/index.html +1 -1
  35. package/templates/app/package.json +19 -7
  36. package/templates/app/prettier.config.js +5 -0
  37. package/templates/app/src/App.vue +3 -1
  38. package/templates/app/src/main.ts +5 -1
  39. package/templates/app/src/types/globals.d.ts +0 -1
  40. package/templates/app/tailwind.config.js +1 -1
  41. package/templates/app/vite.config.ts +5 -3
  42. package/templates/service/[service.name].ts +8 -0
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("commander"),t=require("@babel/runtime/helpers/defineProperty"),n=require("@noeldemartin/utils"),s=require("fs"),i=require("path");require("core-js/modules/esnext.async-iterator.for-each.js"),require("core-js/modules/esnext.iterator.constructor.js"),require("core-js/modules/esnext.iterator.for-each.js"),require("core-js/modules/esnext.async-iterator.find.js"),require("core-js/modules/esnext.iterator.find.js"),require("core-js/modules/esnext.async-iterator.map.js"),require("core-js/modules/esnext.iterator.map.js");var r=require("chalk"),o=require("readline");require("core-js/modules/esnext.async-iterator.reduce.js"),require("core-js/modules/esnext.iterator.reduce.js");var a=require("mustache"),c=require("child_process");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var d=l(t);var u=n.facade(new class{contains(e,t){return!!this.read(e)?.includes(t)}exists(e){return s.existsSync(e)}read(e){return this.isFile(e)?s.readFileSync(e).toString():null}getFiles(e){const t=s.readdirSync(e,{withFileTypes:!0}),n=[];for(const s of t){const t=i.resolve(e,s.name);s.isDirectory()?n.push(...this.getFiles(t)):n.push(t)}return n}isDirectory(e){return this.exists(e)&&s.lstatSync(e).isDirectory()}isFile(e){return this.exists(e)&&s.lstatSync(e).isFile()}isEmptyDirectory(e){return!!this.isDirectory(e)&&0===this.getFiles(e).length}makeDirectory(e){s.mkdirSync(e,{recursive:!0})}write(e,t){s.existsSync(i.dirname(e))||s.mkdirSync(i.dirname(e),{recursive:!0}),s.writeFileSync(e,t)}});var m=n.facade(new class{constructor(){d.default(this,"renderInfo",r.hex("#00ffff")),d.default(this,"renderSuccess",r.hex("#00ff00")),d.default(this,"renderError",r.hex("#ff0000"))}async animate(e,t){var n=this;const s=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";const s=n.renderInfo(n.renderMarkdown(e)+".".repeat(i%4))+t;n.stdout(s)};let i=0;s();const r=setInterval((()=>(i++,s())),1e3),o=await t();return clearInterval(r),s("\n"),o}info(e){this.log(this.renderMarkdown(e),this.renderInfo)}error(e){this.log(this.renderMarkdown(e),this.renderError)}fail(e){this.error(e),process.exit(1)}success(e){this.log(this.renderMarkdown(e),this.renderSuccess)}renderMarkdown(e){const t=n.stringMatchAll(e,/\*\*(.*)\*\*/g);for(const n of t)e=e.replace(n[0],r.bold(n[1]));return e}log(e,t){this.formatMessage(e).forEach((e=>{this.logLine(t?t(e):e)}))}formatMessage(e){if("\n"===e[0]){const t=(e=e.slice(1).trimEnd()).split("\n"),n=e.trim()[0]??"",s=t.find((e=>e.trim().length>0))?.indexOf(n)??0;return t.map((e=>e.slice(s)))}return[e]}logLine(e){console.log(e)}stdout(e){o.cursorTo(process.stdout,0),o.clearLine(process.stdout,0),process.stdout.write(e)}});class p{static instantiate(e,t,n){return new p(e).instantiate(t,n)}constructor(e){d.default(this,"path",void 0),this.path=e}instantiate(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=this.getFilenameReplacements(t),i=[];e=`${e}/`.replace(/\/\//,"/");for(const r of u.getFiles(this.path)){const o=Object.entries(n).reduce(((e,t)=>{let[n,s]=t;return e.replaceAll(n,s)}),r.substring(this.path.length+1)),c=s.readFileSync(r).toString(),l=e+(o.endsWith(".template")?o.slice(0,-9):o);u.write(l,a.render(c,t,void 0,["<%","%>"])),i.push(l)}return i}getFilenameReplacements(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return Object.entries(e).reduce(((e,s)=>{let[i,r]=s;return"object"==typeof r?Object.assign(e,this.getFilenameReplacements(r,`${i}.`)):e[`[${t}${i}]`]=n.toString(r),e}),{})}}function h(e){return i.resolve(__dirname,"../",e)}class f{constructor(e){d.default(this,"name",void 0),this.name=e}create(e){!u.exists(e)||u.isDirectory(e)&&u.isEmptyDirectory(e)||m.fail(`Folder at '${e}' already exists!`),p.instantiate(h("templates/app"),e,{app:{name:this.name,slug:n.stringToSlug(this.name)}})}}class g{static define(e){var t=this;e=e.command(this.command).description(this.description);for(const[t,n]of this.parameters)e=e.argument(`<${t}>`,n);for(const[t,n]of Object.entries(this.options)){const s="string"==typeof n?n:n.description,i="string"==typeof n?"string":n.type??"string";e=e.option("boolean"===i?`--${t}`:`--${t} <${i}>`,s)}e=e.action((function(){for(var e=arguments.length,n=new Array(e),s=0;s<e;s++)n[s]=arguments[s];return t.run.call(t,...n)}))}static async run(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const s=new this(...t);await s.run()}async run(){}assertAerogelOrDirectory(e){const t=u.read("package.json");if(t?.includes("@aerogel/core"))return;if(e&&u.isDirectory(e))return;const n=e?`${e} folder does not exist.`:"package.json does not contain @aerogel/core.";m.fail(`${n} Are you sure this is an Aerogel app?`)}}d.default(g,"command",""),d.default(g,"description",""),d.default(g,"parameters",[]),d.default(g,"options",{});var y=n.facade(new class{constructor(){d.default(this,"cwd",null)}setWorkingDirectory(e){this.cwd=e}async run(e){await new Promise(((t,n)=>{c.exec(e,{cwd:this.cwd??void 0},(e=>{e?n(e):t()}))}))}});class w extends g{constructor(e,t){super(),d.default(this,"path",void 0),d.default(this,"options",void 0),this.path=e,this.options=t}async run(){const e=this.path,t=this.options.name??"Aerogel App";y.setWorkingDirectory(e),await this.createApp(t,e),await this.installDependencies(),await this.initializeGit(),m.success(`\n\n That's it! You can start working on **${t}** doing the following:\n\n cd ${e}\n npm run dev\n\n Have fun!\n `)}async createApp(e,t){m.info(`Creating **${e}**...`),new f(e).create(t)}async installDependencies(){await m.animate("Installing dependencies",(async()=>{await y.run("npm install")}))}async initializeGit(){await m.animate("Initializing git",(async()=>{await y.run("git init"),await y.run("git add ."),await y.run('git commit -m "Start"')}))}}d.default(w,"command","create"),d.default(w,"description","Create AerogelJS app"),d.default(w,"parameters",[["path","Application path"]]),d.default(w,"options",{name:"Application name"});class v extends g{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),d.default(this,"name",void 0),d.default(this,"options",void 0),this.name=e,this.options=t}async run(){this.assertAerogelOrDirectory("src/components"),this.options.story&&this.assertHistoireInstalled(),u.exists(`src/components/${this.name}.vue`)&&m.fail(`${this.name} component already exists!`);const e=p.instantiate(h("templates/component"),"src/components",{component:{name:this.name}});if(this.options.story){const t=p.instantiate(h("templates/component-story"),"src/components",{component:{name:this.name}});e.push(...t)}const t=e.map((e=>`- ${e}`)).join("\n");m.info(`${this.name} component created successfully! The following files were created:\n\n${t}`)}assertHistoireInstalled(){u.exists("src/main.histoire.ts")||m.fail("Histoire is not installed yet!")}}d.default(v,"command","generate:component"),d.default(v,"description","Generate an AerogelJS component"),d.default(v,"parameters",[["name","Component name"]]),d.default(v,"options",{story:{description:"Create component story using Histoire",type:"boolean"}});class x extends g{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),d.default(this,"name",void 0),d.default(this,"options",void 0),this.name=e,this.options=t}async run(){this.assertAerogelOrDirectory("src/models"),u.exists(`src/models/${this.name}.ts`)&&m.fail(`${this.name} model already exists!`),this.assertSoukaiInstalled();const e=p.instantiate(h("templates/model"),"src/models",{model:{name:this.name,fieldsDefinition:this.getFieldsDefinition()},soukaiImports:this.options.fields?"FieldType, defineModelSchema":"defineModelSchema"}).map((e=>`- ${e}`)).join("\n");m.info(`${this.name} model created successfully! The following files were created:\n\n${e}`)}getFieldsDefinition(){if(!this.options.fields)return" //";return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=e.split("\n"),s=t.indent??0;let i=0,r="";for(const e of n){const t=e.trim(),n=0===t.length;if(0===r.length){if(n)continue;i=e.indexOf(t[0]??""),r+=`${" ".repeat(s)}${t}\n`;continue}if(n){r+="\n";continue}const o=e.indexOf(t[0]??"");r+=`${" ".repeat(s+o-i)}${t}\n`}return r.trimEnd()}(this.options.fields.split(",").map((e=>{const[t,s]=e.split(":");return{name:t,type:n.stringToStudlyCase(s??"string")}})).reduce(((e,t)=>e+`\n${t.name}: FieldType.${t.type},`),""),{indent:8})}assertSoukaiInstalled(){u.contains("package.json",'"soukai"')||m.fail("\n Soukai is not installed yet! You can install it doing the following:\n\n 1. Run the following command:\n npm install soukai @aerogel/plugin-soukai\"\n\n 2. Add this to your plugins array:\n soukai({ models: import.meta.glob('@/models/*', { eager: true }) })\n ")}}d.default(x,"command","generate:model"),d.default(x,"description","Generate an AerogelJS model"),d.default(x,"parameters",[["name","Model name"]]),d.default(x,"options",{fields:"Create model with the given fields"});var j=n.facade(new class{run(t){const n=new e.Command;n.name("ag").description("AerogelJS CLI").version("0.0.0"),w.define(n),v.define(n),x.define(n),n.parse(t)}});exports.CLI=j;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("commander"),t=require("@babel/runtime/helpers/defineProperty");require("core-js/modules/esnext.async-iterator.reduce.js"),require("core-js/modules/esnext.iterator.constructor.js"),require("core-js/modules/esnext.iterator.reduce.js");var i=require("@noeldemartin/utils"),s=require("fs"),n=require("path");require("core-js/modules/esnext.async-iterator.for-each.js"),require("core-js/modules/esnext.iterator.for-each.js"),require("core-js/modules/esnext.async-iterator.find.js"),require("core-js/modules/esnext.iterator.find.js"),require("core-js/modules/esnext.async-iterator.map.js"),require("core-js/modules/esnext.iterator.map.js");var r=require("chalk"),a=require("readline"),o=require("mustache");require("core-js/modules/esnext.set.add-all.js"),require("core-js/modules/esnext.set.delete-all.js"),require("core-js/modules/esnext.set.difference.js"),require("core-js/modules/esnext.set.every.js"),require("core-js/modules/esnext.set.filter.js"),require("core-js/modules/esnext.set.find.js"),require("core-js/modules/esnext.set.intersection.js"),require("core-js/modules/esnext.set.is-disjoint-from.js"),require("core-js/modules/esnext.set.is-subset-of.js"),require("core-js/modules/esnext.set.is-superset-of.js"),require("core-js/modules/esnext.set.join.js"),require("core-js/modules/esnext.set.map.js"),require("core-js/modules/esnext.set.reduce.js"),require("core-js/modules/esnext.set.some.js"),require("core-js/modules/esnext.set.symmetric-difference.js"),require("core-js/modules/esnext.set.union.js");var l=require("ts-morph"),c=require("child_process");function d(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}require("core-js/modules/esnext.async-iterator.some.js"),require("core-js/modules/esnext.iterator.some.js");var u=d(t);var p=i.facade(new class{contains(e,t){return!!this.read(e)?.includes(t)}exists(e){return s.existsSync(e)}isSymlink(e){return s.lstatSync(e).isSymbolicLink()}read(e){return this.isFile(e)?s.readFileSync(e).toString():null}getFiles(e){const t=s.readdirSync(e,{withFileTypes:!0}),i=[];for(const s of t){const t=n.resolve(e,s.name);s.isDirectory()?i.push(...this.getFiles(t)):i.push(t)}return i}isDirectory(e){return this.exists(e)&&s.lstatSync(e).isDirectory()}isFile(e){return this.exists(e)&&s.lstatSync(e).isFile()}isEmptyDirectory(e){return!!this.isDirectory(e)&&0===this.getFiles(e).length}makeDirectory(e){s.mkdirSync(e,{recursive:!0})}write(e,t){s.existsSync(n.dirname(e))||s.mkdirSync(n.dirname(e),{recursive:!0}),s.writeFileSync(e,t)}});var m=i.facade(new class{constructor(){u.default(this,"renderInfo",r.hex("#00ffff")),u.default(this,"renderSuccess",r.hex("#00ff00")),u.default(this,"renderError",r.hex("#ff0000"))}async animate(e,t){var i=this;const s=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",s=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const r=i.renderInfo(i.renderMarkdown(e)+(s?"...":".".repeat(n%4)))+t;i.stdout(r)};let n=0;s();const r=setInterval((()=>(n++,s())),1e3),a=await t();return clearInterval(r),s("\n",!0),a}info(e){this.log(this.renderMarkdown(e),this.renderInfo)}error(e){this.log(this.renderMarkdown(e),this.renderError)}fail(e){this.error(e),process.exit(1)}success(e){this.log(this.renderMarkdown(e),this.renderSuccess)}renderMarkdown(e){const t=i.stringMatchAll(e,/\*\*(.*)\*\*/g);for(const i of t)e=e.replace(i[0],r.bold(i[1]));return e}log(e,t){this.formatMessage(e).forEach((e=>{this.logLine(t?t(e):e)}))}formatMessage(e){if("\n"===e[0]){const t=(e=e.slice(1).trimEnd()).split("\n"),i=e.trim()[0]??"",s=t.find((e=>e.trim().length>0))?.indexOf(i)??0;return t.map((e=>e.slice(s)))}return[e]}logLine(e){console.log(e)}stdout(e){a.cursorTo(process.stdout,0),a.clearLine(process.stdout,0),process.stdout.write(e)}});class g{static instantiate(e,t,i){return new g(e).instantiate(t,i)}constructor(e){u.default(this,"path",void 0),this.path=e}instantiate(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=this.getFilenameReplacements(t),n=[];e=`${e}/`.replace(/\/\//,"/");for(const r of p.getFiles(this.path)){const a=Object.entries(i).reduce(((e,t)=>{let[i,s]=t;return e.replaceAll(i,s)}),r.substring(this.path.length+1)),l=s.readFileSync(r).toString(),c=e+(a.endsWith(".template")?a.slice(0,-9):a);p.write(c,o.render(l,t,void 0,["<%","%>"])),n.push(c)}return n}getFilenameReplacements(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return Object.entries(e).reduce(((e,s)=>{let[n,r]=s;return"object"==typeof r?Object.assign(e,this.getFilenameReplacements(r,`${n}.`)):e[`[${t}${n}]`]=i.toString(r),e}),{})}}function f(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";if(p.contains(n.resolve(__dirname,"../../../package.json"),'"name": "aerogel"'))return n.resolve(__dirname,"../",e);const t=p.read(n.resolve(__dirname,"../../../../package.json")),s=i.stringMatch(t??"",/"@aerogel\/cli": "file:(.*)\/aerogel-cli-[\d.]*\.tgz"/),r=s?.[1]??m.fail("Could not determine base path");return n.resolve(r,e)}function h(e){return m.fail(`Could not find ${e} pack file, did you run 'npm pack'?`)}function y(e){return p.getFiles(v(e)).find((e=>e.endsWith(".tgz")))??null}function v(e){return f(`../${e}`)}var w=i.facade(new class{constructor(){u.default(this,"cwd",null)}setWorkingDirectory(e){this.cwd=e}async run(e){await new Promise(((t,i)=>{c.exec(e,{cwd:this.cwd??void 0},(e=>{e?i(e):t()}))}))}});class x{constructor(){u.default(this,"project",void 0),u.default(this,"modifiedFiles",void 0),this.project=new l.Project({tsConfigFilePath:"tsconfig.json"}),this.modifiedFiles=new Set,this.project.addSourceFilesAtPaths("src/**/*.ts"),this.project.addSourceFilesAtPaths("tailwind.config.js"),this.project.addSourceFilesAtPaths("vite.config.ts")}addSourceFile(e){this.project.addSourceFilesAtPaths(e)}requireSourceFile(e){return this.project.getSourceFileOrThrow(e)}async format(){await m.animate("Formatting modified files",(async()=>{const e=p.exists("prettier.config.js"),t=p.exists(".eslintrc.js");await Promise.all(i.arrayFrom(this.modifiedFiles).map((async i=>{e&&await w.run(`npx prettier ${i} --write`),t&&await w.run(`npx eslint ${i} --fix`)})))}))}async save(e){await e.save(),this.modifiedFiles.add(e.getFilePath())}}class j{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};u.default(this,"name",void 0),u.default(this,"options",void 0),this.name=e,this.options=t}create(e){!p.exists(e)||p.isDirectory(e)&&p.isEmptyDirectory(e)||m.fail(`Folder at '${e}' already exists!`),g.instantiate(f("templates/app"),e,{app:{name:this.name,slug:i.stringToSlug(this.name)},dependencies:this.getDependencies(),contentPath:this.options.linkedLocal?`${v("core")}/dist/**/*.js`:"./node_modules/@aerogel/core/dist/**/*.js"})}edit(){return new x}getDependencies(){const e=e=>Object.entries(e).reduce(((e,t)=>{let[i,s]=t;return Object.assign(e,{[i]:`file:${s}`})}),{});return this.options.linkedLocal?e({aerogelCli:v("cli"),aerogelCore:v("core"),aerogelCypress:v("cypress"),aerogelPluginI18n:v("plugin-i18n"),aerogelPluginSoukai:v("plugin-soukai"),aerogelVite:v("vite")}):this.options.local?e({aerogelCli:y("cli")??h("cli"),aerogelCore:y("core")??h("core"),aerogelCypress:y("cypress")??h("cypress"),aerogelPluginI18n:y("plugin-i18n")??h("plugin-i18n"),aerogelPluginSoukai:y("plugin-soukai")??h("plugin-soukai"),aerogelVite:y("vite")??h("vite")}):{aerogelCli:"next",aerogelCore:"next",aerogelCypress:"next",aerogelPluginI18n:"next",aerogelPluginSoukai:"next",aerogelVite:"next"}}}class S{static define(e){var t=this;e=e.command(this.command).description(this.description);for(const[t,i]of this.parameters)e=e.argument(`<${t}>`,i);for(const[t,i]of Object.entries(this.options)){const s="string"==typeof i?i:i.description,n="string"==typeof i?"string":i.type??"string";e=e.option("boolean"===n?`--${t}`:`--${t} <${n}>`,s)}e=e.action((function(){for(var e=arguments.length,i=new Array(e),s=0;s<e;s++)i[s]=arguments[s];return t.run.call(t,...i)}))}static async run(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const s=new this(...t);await s.run()}async run(){}assertAerogelOrDirectory(e){const t=p.read("package.json");if(t?.includes("@aerogel/core"))return;if(e&&p.isDirectory(e))return;const i=e?`${e} folder does not exist.`:"package.json does not contain @aerogel/core.";m.fail(`${i} Are you sure this is an Aerogel app?`)}}u.default(S,"command",""),u.default(S,"description",""),u.default(S,"parameters",[]),u.default(S,"options",{});class k extends S{constructor(e,t){super(),u.default(this,"path",void 0),u.default(this,"options",void 0),this.path=e,this.options=t}async run(){const e=this.path,t=this.options.name??"Aerogel App";w.setWorkingDirectory(e),await this.createApp(t,e),await this.installDependencies(),await this.initializeGit(),m.success(`\n\n That's it! You can start working on **${t}** doing the following:\n\n cd ${e}\n npm run dev\n\n Have fun!\n `)}async createApp(e,t){m.info(`Creating **${e}**...`),new j(e,{local:this.options.local,linkedLocal:this.options.local&&!this.options.copy}).create(t)}async installDependencies(){await m.animate("Installing dependencies",(async()=>{await w.run("npm install")}))}async initializeGit(){await m.animate("Initializing git",(async()=>{await w.run("git init"),await w.run("git add ."),await w.run('git commit -m "Start"')}))}}function $(){return new j("")}function C(){return p.isSymlink("node_modules/@aerogel/core")}function A(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e)return;const s=t.guard??(()=>!0),n=t.validate??(()=>!0),r=i.arrayFrom(t.skip??[]);return e.forEachDescendant(((e,t)=>{if(s(e)&&n(e))return e;const i=e.getKind();r.includes(i)&&t.skip()}))}function F(e,t){if(e&&t(e))return e}u.default(k,"command","create"),u.default(k,"description","Create AerogelJS app"),u.default(k,"parameters",[["path","Application path"]]),u.default(k,"options",{name:"Application name",local:{type:"boolean",description:"Whether to create an app using local Aerogel packages (used for core development)"},copy:{type:"boolean",description:"Whether to create an app linked to local Aerogel packages (used in CI)"}});class q extends S{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),u.default(this,"path",void 0),u.default(this,"options",void 0),this.path=e,this.options=t}async run(){this.assertAerogelOrDirectory("src/components"),this.assertHistoireInstalled();const e=new Set,[t,s]=this.parsePathComponents();await this.createComponent(t,s,e),await this.createStory(s,e),await this.declareComponents();const n=i.arrayFrom(e).map((e=>`- ${e}`)).join("\n");m.info(`${s} component created successfully! The following files were created:\n\n${n}`)}assertHistoireInstalled(){this.options.story&&(p.exists("src/main.histoire.ts")||m.fail("Histoire is not installed yet!"))}async createComponent(e,t,i){await m.animate("Creating component",(async()=>{p.exists(`src/components/${this.path}.vue`)&&m.fail(`${this.path} component already exists!`);g.instantiate(f("templates/component"),`src/components/${e}`,{component:{name:t}}).forEach((e=>i.add(e)))}))}async createStory(e,t){this.options.story&&await m.animate("Creating story",(async()=>{g.instantiate(f("templates/component-story"),"src/components",{component:{name:e}}).forEach((e=>t.add(e)))}))}async declareComponents(){const e=$().edit(),t=e.requireSourceFile("vite.config.ts"),i=this.getComponentDirsArray(t);if(!i)return m.fail("Could not find component dirs declaration in vite config!");i.getDescendantsOfKind(l.SyntaxKind.StringLiteral).some((e=>"'src/components'"===e.getText()))||(await m.animate("Updating vite config",(async()=>{i.addElement("'src/components'"),await e.save(t)})),await e.format())}getComponentDirsArray(e){const t=A(e,{guard:l.Node.isCallExpression,validate:e=>e.getText().startsWith("Components("),skip:l.SyntaxKind.ImportDeclaration});if(!t)return null;const i=A(t,{guard:l.Node.isPropertyAssignment,validate:e=>"dirs"===e.getName()}),s=i?.getInitializer();return l.Node.isArrayLiteralExpression(s)?s:this.declareComponentDirsArray(t)}declareComponentDirsArray(e){const t=A(e,{guard:l.Node.isObjectLiteralExpression}),i=t?.addPropertyAssignment({name:"dirs",initializer:"[]"});return i?.getInitializer()??null}parsePathComponents(){const e=this.path.lastIndexOf("/");return-1===e?["",this.path]:[this.path.substring(0,e),this.path.substring(e+1)]}}function D(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=e.split("\n"),s=t.indent??0;let n=0,r="";for(const e of i){const t=e.trim(),i=0===t.length;if(0===r.length){if(i)continue;n=e.indexOf(t[0]??""),r+=`${" ".repeat(s)}${t}\n`;continue}if(i){r+="\n";continue}const a=e.indexOf(t[0]??"");r+=`${" ".repeat(s+a-n)}${t}\n`}return r.trimEnd()}u.default(q,"command","generate:component"),u.default(q,"description","Generate an AerogelJS Component"),u.default(q,"parameters",[["path","Component path (relative to components folder; extension not necessary)"]]),u.default(q,"options",{story:{description:"Create component story using Histoire",type:"boolean"}});class I extends S{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),u.default(this,"name",void 0),u.default(this,"options",void 0),this.name=e,this.options=t}async run(){this.assertAerogelOrDirectory("src/models"),p.exists(`src/models/${this.name}.ts`)&&m.fail(`${this.name} model already exists!`),this.assertSoukaiInstalled();const e=await m.animate("Creating model",(async()=>g.instantiate(f("templates/model"),"src/models",{model:{name:this.name,fieldsDefinition:this.getFieldsDefinition()},soukaiImports:this.options.fields?"FieldType, defineModelSchema":"defineModelSchema"}).map((e=>`- ${e}`)).join("\n")));m.info(`${this.name} model created successfully! The following files were created:\n\n${e}`)}getFieldsDefinition(){if(!this.options.fields)return" //";const e=this.options.fields.split(",").map((e=>{const[t,s,n]=e.split(":");return{name:t,type:i.stringToStudlyCase(s??"string"),required:"required"===n}})).reduce(((e,t)=>e+`\n${t.required?D(`\n ${t.name}: {\n type: FieldType.${t.type},\n required: true,\n }\n `):`${t.name}: FieldType.${t.type}`},`),"");return D(e,{indent:8})}assertSoukaiInstalled(){p.contains("package.json",'"soukai"')||p.contains("package.json",'"@aerogel/plugin-soukai"')||m.fail("\n Soukai is not installed yet! You can install it running:\n npx ag install soukai\n ")}}u.default(I,"command","generate:model"),u.default(I,"description","Generate an AerogelJS Model"),u.default(I,"parameters",[["name","Model name"]]),u.default(I,"options",{fields:"Create model with the given fields"});class P extends S{constructor(e){super(),u.default(this,"name",void 0),this.name=e}async run(){this.assertAerogelOrDirectory("src/services");const e=new Set,t=$().edit();await this.createService(e),await this.registerService(t),await t.format();const s=i.arrayFrom(e).map((e=>`- ${e}`)).join("\n");m.info(`${this.name} service created successfully! The following files were created:\n\n${s}`)}async createService(e){await m.animate("Creating service",(async()=>{p.exists(`src/services/${this.name}.ts`)&&m.fail(`${this.name} service already exists!`);g.instantiate(f("templates/service"),"src/services",{service:{name:this.name}}).forEach((t=>e.add(t)))}))}async registerService(e){await m.animate("Registering service",(async()=>{p.exists("src/services/index.ts")||await this.createServicesIndex(e);const t=e.requireSourceFile("src/services/index.ts"),s=this.getServicesObject(t);if(!s)return m.fail("Could not find services object in services config, please add it manually.");t.addImportDeclaration({defaultImport:this.name,moduleSpecifier:`./${this.name}`}),s.addPropertyAssignment({name:`$${i.stringToCamelCase(this.name)}`,initializer:this.name}),await e.save(t)}))}async createServicesIndex(e){p.write("src/services/index.ts",D("\n export const services = {};\n\n export type AppServices = typeof services;\n\n declare module '@vue/runtime-core' {\n interface ComponentCustomProperties extends AppServices {}\n }\n ")),e.addSourceFile("src/services/index.ts");const t=e.requireSourceFile("src/main.ts"),i=this.getBootstrapOptions(t);if(!i)return m.fail("Could not find options object in bootstrap config, please add the services manually.");i.insertShorthandPropertyAssignment(0,{name:"services"}),t.addImportDeclaration({namedImports:["services"],moduleSpecifier:"./services"}),await e.save(t)}getBootstrapOptions(e){const t=A(e,{guard:l.Node.isCallExpression,validate:e=>"bootstrapApplication"===e.getExpression().getText(),skip:l.SyntaxKind.ImportDeclaration}),i=t?.getArguments()[1];return l.Node.isObjectLiteralExpression(i)?i:null}getServicesObject(e){const t=A(e,{guard:l.Node.isVariableDeclaration,validate:e=>"services"===e.getName()}),i=t?.getInitializer();return l.Node.isObjectLiteralExpression(i)?i:null}}u.default(P,"command","generate:service"),u.default(P,"description","Generate an AerogelJS Service"),u.default(P,"parameters",[["name","Service name"]]);class b{constructor(e){u.default(this,"name",void 0),this.name=e}async install(){this.assertNotInstalled(),await this.installDependencies();{const e=$().edit();await this.updateFiles(e),await e.format()}m.info(`Plugin ${this.name} installed!`)}assertNotInstalled(){p.contains("package.json",`"${this.getNpmPackageName()}"`)&&m.fail(`${this.name} is already installed!`)}async installDependencies(){await m.animate("Installing plugin dependencies",(async()=>{await this.installNpmDependencies()}))}async updateFiles(e){await this.updateBootstrapConfig(e)}async installNpmDependencies(){if(C())await w.run(`npm install file:${v(this.getLocalPackageName())}`);else if(p.contains("package.json","file")){const e=y(this.getLocalPackageName())??h(this.getLocalPackageName());await w.run(`npm install file:${e}`)}else await w.run(`npm install ${this.getNpmPackageName()}@next`)}async updateBootstrapConfig(e){await m.animate("Injecting plugin in bootstrap configuration",(async()=>{const t=e.requireSourceFile("src/main.ts"),i=this.getBootstrapPluginsDeclaration(t);if(!i)return m.fail(`\n Could not find plugins array in bootstrap config, please add the following manually:\n\n ${this.getBootstrapConfig()}\n `);t.addImportDeclaration(this.getBootstrapImport()),i.addElement(this.getBootstrapConfig()),await e.save(t)}))}getBootstrapPluginsDeclaration(e){const t=A(e,{guard:l.Node.isCallExpression,validate:e=>"bootstrapApplication"===e.getExpression().getText(),skip:l.SyntaxKind.ImportDeclaration}),i=t?.getArguments()[1],s=F(i,l.Node.isObjectLiteralExpression)?.getProperty("plugins"),n=F(s,l.Node.isPropertyAssignment)?.getInitializer();return l.Node.isArrayLiteralExpression(n)?n:null}getBootstrapImport(){return{defaultImport:this.name,moduleSpecifier:`@aerogel/plugin-${this.name}`}}getNpmPackageName(){return`@aerogel/${this.getLocalPackageName()}`}getLocalPackageName(){return`plugin-${this.name}`}getBootstrapConfig(){return`${this.name}()`}}const N=[new class extends b{constructor(){super("soukai")}async installNpmDependencies(){await w.run("npm install soukai@next"),await super.installNpmDependencies()}getBootstrapConfig(){return"soukai({ models: import.meta.glob('@/models/*', { eager: true }) })"}},new class extends b{constructor(){super("solid")}async updateFiles(e){await this.updateTailwindConfig(e),await super.updateFiles(e)}async installNpmDependencies(){await w.run("npm install soukai-solid@next"),await super.installNpmDependencies()}async updateTailwindConfig(e){await m.animate("Updating tailwind configuration",(async()=>{const t=e.requireSourceFile("tailwind.config.js"),i=this.getTailwindContentArray(t),s=C()?`'${v("plugin-solid")}/dist/**/*.js'`:"'./node_modules/@aerogel/plugin-solid/dist/**/*.js'";if(!i)return m.fail(`\n Could not find content array in tailwind config, please add the following manually:\n\n ${s}\n `);i.addElement(s),await e.save(t)}))}getTailwindContentArray(e){const t=A(e,{guard:l.Node.isPropertyAssignment,validate:e=>"content"===e.getName(),skip:l.SyntaxKind.JSDoc}),i=t?.getInitializer();return l.Node.isArrayLiteralExpression(i)?i:null}}].reduce(((e,t)=>Object.assign(e,{[t.name]:t})),{});class O extends S{constructor(e){super(),u.default(this,"plugin",void 0),this.plugin=N[e]??m.fail(`Plugin '${e}' doesn't exist. Available plugins: ${Object.keys(N).join(", ")}`)}async run(){await this.plugin.install()}}u.default(O,"command","install"),u.default(O,"description","Install an AerogelJS plugin"),u.default(O,"parameters",[["plugin","Plugin to install"]]);var E=i.facade(new class{run(t){const i=new e.Command;i.name("ag").description("AerogelJS CLI").version("0.0.0"),k.define(i),q.define(i),I.define(i),P.define(i),O.define(i),i.parse(t)}});exports.CLI=E;
2
2
  //# sourceMappingURL=aerogel-cli.cjs.js.map
@@ -1,2 +1,2 @@
1
- import{Command as e}from"commander";import t from"@babel/runtime/helpers/esm/defineProperty";import{facade as s,stringMatchAll as n,toString as i,stringToSlug as r,stringToStudlyCase as o}from"@noeldemartin/utils";import{existsSync as a,readFileSync as c,readdirSync as l,lstatSync as m,mkdirSync as d,writeFileSync as p}from"fs";import{resolve as h,dirname as u}from"path";import"core-js/modules/esnext.async-iterator.for-each.js";import"core-js/modules/esnext.iterator.constructor.js";import"core-js/modules/esnext.iterator.for-each.js";import"core-js/modules/esnext.async-iterator.find.js";import"core-js/modules/esnext.iterator.find.js";import"core-js/modules/esnext.async-iterator.map.js";import"core-js/modules/esnext.iterator.map.js";import{hex as f,bold as g}from"chalk";import{cursorTo as y,clearLine as w}from"readline";import"core-js/modules/esnext.async-iterator.reduce.js";import"core-js/modules/esnext.iterator.reduce.js";import{render as v}from"mustache";import{exec as $}from"child_process";var j=s(new class{contains(e,t){return!!this.read(e)?.includes(t)}exists(e){return a(e)}read(e){return this.isFile(e)?c(e).toString():null}getFiles(e){const t=l(e,{withFileTypes:!0}),s=[];for(const n of t){const t=h(e,n.name);n.isDirectory()?s.push(...this.getFiles(t)):s.push(t)}return s}isDirectory(e){return this.exists(e)&&m(e).isDirectory()}isFile(e){return this.exists(e)&&m(e).isFile()}isEmptyDirectory(e){return!!this.isDirectory(e)&&0===this.getFiles(e).length}makeDirectory(e){d(e,{recursive:!0})}write(e,t){a(u(e))||d(u(e),{recursive:!0}),p(e,t)}});var x=s(new class{constructor(){t(this,"renderInfo",f("#00ffff")),t(this,"renderSuccess",f("#00ff00")),t(this,"renderError",f("#ff0000"))}async animate(e,t){var s=this;const n=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";const n=s.renderInfo(s.renderMarkdown(e)+".".repeat(i%4))+t;s.stdout(n)};let i=0;n();const r=setInterval((()=>(i++,n())),1e3),o=await t();return clearInterval(r),n("\n"),o}info(e){this.log(this.renderMarkdown(e),this.renderInfo)}error(e){this.log(this.renderMarkdown(e),this.renderError)}fail(e){this.error(e),process.exit(1)}success(e){this.log(this.renderMarkdown(e),this.renderSuccess)}renderMarkdown(e){const t=n(e,/\*\*(.*)\*\*/g);for(const s of t)e=e.replace(s[0],g(s[1]));return e}log(e,t){this.formatMessage(e).forEach((e=>{this.logLine(t?t(e):e)}))}formatMessage(e){if("\n"===e[0]){const t=(e=e.slice(1).trimEnd()).split("\n"),s=e.trim()[0]??"",n=t.find((e=>e.trim().length>0))?.indexOf(s)??0;return t.map((e=>e.slice(n)))}return[e]}logLine(e){console.log(e)}stdout(e){y(process.stdout,0),w(process.stdout,0),process.stdout.write(e)}});class k{static instantiate(e,t,s){return new k(e).instantiate(t,s)}constructor(e){t(this,"path",void 0),this.path=e}instantiate(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=this.getFilenameReplacements(t),n=[];e=`${e}/`.replace(/\/\//,"/");for(const i of j.getFiles(this.path)){const r=Object.entries(s).reduce(((e,t)=>{let[s,n]=t;return e.replaceAll(s,n)}),i.substring(this.path.length+1)),o=c(i).toString(),a=e+(r.endsWith(".template")?r.slice(0,-9):r);j.write(a,v(o,t,void 0,["<%","%>"])),n.push(a)}return n}getFilenameReplacements(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return Object.entries(e).reduce(((e,s)=>{let[n,r]=s;return"object"==typeof r?Object.assign(e,this.getFilenameReplacements(r,`${n}.`)):e[`[${t}${n}]`]=i(r),e}),{})}}function A(e){return h(__dirname,"../",e)}class D{constructor(e){t(this,"name",void 0),this.name=e}create(e){!j.exists(e)||j.isDirectory(e)&&j.isEmptyDirectory(e)||x.fail(`Folder at '${e}' already exists!`),k.instantiate(A("templates/app"),e,{app:{name:this.name,slug:r(this.name)}})}}class F{static define(e){var t=this;e=e.command(this.command).description(this.description);for(const[t,s]of this.parameters)e=e.argument(`<${t}>`,s);for(const[t,s]of Object.entries(this.options)){const n="string"==typeof s?s:s.description,i="string"==typeof s?"string":s.type??"string";e=e.option("boolean"===i?`--${t}`:`--${t} <${i}>`,n)}e=e.action((function(){for(var e=arguments.length,s=new Array(e),n=0;n<e;n++)s[n]=arguments[n];return t.run.call(t,...s)}))}static async run(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];const n=new this(...t);await n.run()}async run(){}assertAerogelOrDirectory(e){const t=j.read("package.json");if(t?.includes("@aerogel/core"))return;if(e&&j.isDirectory(e))return;const s=e?`${e} folder does not exist.`:"package.json does not contain @aerogel/core.";x.fail(`${s} Are you sure this is an Aerogel app?`)}}t(F,"command",""),t(F,"description",""),t(F,"parameters",[]),t(F,"options",{});var I=s(new class{constructor(){t(this,"cwd",null)}setWorkingDirectory(e){this.cwd=e}async run(e){await new Promise(((t,s)=>{$(e,{cwd:this.cwd??void 0},(e=>{e?s(e):t()}))}))}});class S extends F{constructor(e,s){super(),t(this,"path",void 0),t(this,"options",void 0),this.path=e,this.options=s}async run(){const e=this.path,t=this.options.name??"Aerogel App";I.setWorkingDirectory(e),await this.createApp(t,e),await this.installDependencies(),await this.initializeGit(),x.success(`\n\n That's it! You can start working on **${t}** doing the following:\n\n cd ${e}\n npm run dev\n\n Have fun!\n `)}async createApp(e,t){x.info(`Creating **${e}**...`),new D(e).create(t)}async installDependencies(){await x.animate("Installing dependencies",(async()=>{await I.run("npm install")}))}async initializeGit(){await x.animate("Initializing git",(async()=>{await I.run("git init"),await I.run("git add ."),await I.run('git commit -m "Start"')}))}}t(S,"command","create"),t(S,"description","Create AerogelJS app"),t(S,"parameters",[["path","Application path"]]),t(S,"options",{name:"Application name"});class b extends F{constructor(e){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),t(this,"name",void 0),t(this,"options",void 0),this.name=e,this.options=s}async run(){this.assertAerogelOrDirectory("src/components"),this.options.story&&this.assertHistoireInstalled(),j.exists(`src/components/${this.name}.vue`)&&x.fail(`${this.name} component already exists!`);const e=k.instantiate(A("templates/component"),"src/components",{component:{name:this.name}});if(this.options.story){const t=k.instantiate(A("templates/component-story"),"src/components",{component:{name:this.name}});e.push(...t)}const t=e.map((e=>`- ${e}`)).join("\n");x.info(`${this.name} component created successfully! The following files were created:\n\n${t}`)}assertHistoireInstalled(){j.exists("src/main.histoire.ts")||x.fail("Histoire is not installed yet!")}}t(b,"command","generate:component"),t(b,"description","Generate an AerogelJS component"),t(b,"parameters",[["name","Component name"]]),t(b,"options",{story:{description:"Create component story using Histoire",type:"boolean"}});class M extends F{constructor(e){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),t(this,"name",void 0),t(this,"options",void 0),this.name=e,this.options=s}async run(){this.assertAerogelOrDirectory("src/models"),j.exists(`src/models/${this.name}.ts`)&&x.fail(`${this.name} model already exists!`),this.assertSoukaiInstalled();const e=k.instantiate(A("templates/model"),"src/models",{model:{name:this.name,fieldsDefinition:this.getFieldsDefinition()},soukaiImports:this.options.fields?"FieldType, defineModelSchema":"defineModelSchema"}).map((e=>`- ${e}`)).join("\n");x.info(`${this.name} model created successfully! The following files were created:\n\n${e}`)}getFieldsDefinition(){if(!this.options.fields)return" //";return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=e.split("\n"),n=t.indent??0;let i=0,r="";for(const e of s){const t=e.trim(),s=0===t.length;if(0===r.length){if(s)continue;i=e.indexOf(t[0]??""),r+=`${" ".repeat(n)}${t}\n`;continue}if(s){r+="\n";continue}const o=e.indexOf(t[0]??"");r+=`${" ".repeat(n+o-i)}${t}\n`}return r.trimEnd()}(this.options.fields.split(",").map((e=>{const[t,s]=e.split(":");return{name:t,type:o(s??"string")}})).reduce(((e,t)=>e+`\n${t.name}: FieldType.${t.type},`),""),{indent:8})}assertSoukaiInstalled(){j.contains("package.json",'"soukai"')||x.fail("\n Soukai is not installed yet! You can install it doing the following:\n\n 1. Run the following command:\n npm install soukai @aerogel/plugin-soukai\"\n\n 2. Add this to your plugins array:\n soukai({ models: import.meta.glob('@/models/*', { eager: true }) })\n ")}}t(M,"command","generate:model"),t(M,"description","Generate an AerogelJS model"),t(M,"parameters",[["name","Model name"]]),t(M,"options",{fields:"Create model with the given fields"});var O=s(new class{run(t){const s=new e;s.name("ag").description("AerogelJS CLI").version("0.0.0"),S.define(s),b.define(s),M.define(s),s.parse(t)}});export{O as CLI};
1
+ import{Command as e}from"commander";import t from"@babel/runtime/helpers/esm/defineProperty";import"core-js/modules/esnext.async-iterator.reduce.js";import"core-js/modules/esnext.iterator.constructor.js";import"core-js/modules/esnext.iterator.reduce.js";import{facade as i,stringMatchAll as s,toString as n,stringMatch as r,arrayFrom as a,stringToSlug as o,stringToStudlyCase as l,stringToCamelCase as c}from"@noeldemartin/utils";import{existsSync as p,lstatSync as d,readFileSync as m,readdirSync as u,mkdirSync as g,writeFileSync as h}from"fs";import{resolve as f,dirname as y}from"path";import"core-js/modules/esnext.async-iterator.for-each.js";import"core-js/modules/esnext.iterator.for-each.js";import"core-js/modules/esnext.async-iterator.find.js";import"core-js/modules/esnext.iterator.find.js";import"core-js/modules/esnext.async-iterator.map.js";import"core-js/modules/esnext.iterator.map.js";import{hex as w,bold as v}from"chalk";import{cursorTo as j,clearLine as x}from"readline";import{render as $}from"mustache";import"core-js/modules/esnext.set.add-all.js";import"core-js/modules/esnext.set.delete-all.js";import"core-js/modules/esnext.set.difference.js";import"core-js/modules/esnext.set.every.js";import"core-js/modules/esnext.set.filter.js";import"core-js/modules/esnext.set.find.js";import"core-js/modules/esnext.set.intersection.js";import"core-js/modules/esnext.set.is-disjoint-from.js";import"core-js/modules/esnext.set.is-subset-of.js";import"core-js/modules/esnext.set.is-superset-of.js";import"core-js/modules/esnext.set.join.js";import"core-js/modules/esnext.set.map.js";import"core-js/modules/esnext.set.reduce.js";import"core-js/modules/esnext.set.some.js";import"core-js/modules/esnext.set.symmetric-difference.js";import"core-js/modules/esnext.set.union.js";import{Project as k,SyntaxKind as S,Node as C}from"ts-morph";import{exec as A}from"child_process";import"core-js/modules/esnext.async-iterator.some.js";import"core-js/modules/esnext.iterator.some.js";var D=i(new class{contains(e,t){return!!this.read(e)?.includes(t)}exists(e){return p(e)}isSymlink(e){return d(e).isSymbolicLink()}read(e){return this.isFile(e)?m(e).toString():null}getFiles(e){const t=u(e,{withFileTypes:!0}),i=[];for(const s of t){const t=f(e,s.name);s.isDirectory()?i.push(...this.getFiles(t)):i.push(t)}return i}isDirectory(e){return this.exists(e)&&d(e).isDirectory()}isFile(e){return this.exists(e)&&d(e).isFile()}isEmptyDirectory(e){return!!this.isDirectory(e)&&0===this.getFiles(e).length}makeDirectory(e){g(e,{recursive:!0})}write(e,t){p(y(e))||g(y(e),{recursive:!0}),h(e,t)}});var F=i(new class{constructor(){t(this,"renderInfo",w("#00ffff")),t(this,"renderSuccess",w("#00ff00")),t(this,"renderError",w("#ff0000"))}async animate(e,t){var i=this;const s=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",s=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const r=i.renderInfo(i.renderMarkdown(e)+(s?"...":".".repeat(n%4)))+t;i.stdout(r)};let n=0;s();const r=setInterval((()=>(n++,s())),1e3),a=await t();return clearInterval(r),s("\n",!0),a}info(e){this.log(this.renderMarkdown(e),this.renderInfo)}error(e){this.log(this.renderMarkdown(e),this.renderError)}fail(e){this.error(e),process.exit(1)}success(e){this.log(this.renderMarkdown(e),this.renderSuccess)}renderMarkdown(e){const t=s(e,/\*\*(.*)\*\*/g);for(const i of t)e=e.replace(i[0],v(i[1]));return e}log(e,t){this.formatMessage(e).forEach((e=>{this.logLine(t?t(e):e)}))}formatMessage(e){if("\n"===e[0]){const t=(e=e.slice(1).trimEnd()).split("\n"),i=e.trim()[0]??"",s=t.find((e=>e.trim().length>0))?.indexOf(i)??0;return t.map((e=>e.slice(s)))}return[e]}logLine(e){console.log(e)}stdout(e){j(process.stdout,0),x(process.stdout,0),process.stdout.write(e)}});class I{static instantiate(e,t,i){return new I(e).instantiate(t,i)}constructor(e){t(this,"path",void 0),this.path=e}instantiate(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=this.getFilenameReplacements(t),s=[];e=`${e}/`.replace(/\/\//,"/");for(const n of D.getFiles(this.path)){const r=Object.entries(i).reduce(((e,t)=>{let[i,s]=t;return e.replaceAll(i,s)}),n.substring(this.path.length+1)),a=m(n).toString(),o=e+(r.endsWith(".template")?r.slice(0,-9):r);D.write(o,$(a,t,void 0,["<%","%>"])),s.push(o)}return s}getFilenameReplacements(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return Object.entries(e).reduce(((e,i)=>{let[s,r]=i;return"object"==typeof r?Object.assign(e,this.getFilenameReplacements(r,`${s}.`)):e[`[${t}${s}]`]=n(r),e}),{})}}function P(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";if(D.contains(f(__dirname,"../../../package.json"),'"name": "aerogel"'))return f(__dirname,"../",e);const t=D.read(f(__dirname,"../../../../package.json")),i=r(t??"",/"@aerogel\/cli": "file:(.*)\/aerogel-cli-[\d.]*\.tgz"/),s=i?.[1]??F.fail("Could not determine base path");return f(s,e)}function b(e){return F.fail(`Could not find ${e} pack file, did you run 'npm pack'?`)}function E(e){return D.getFiles(O(e)).find((e=>e.endsWith(".tgz")))??null}function O(e){return P(`../${e}`)}var N=i(new class{constructor(){t(this,"cwd",null)}setWorkingDirectory(e){this.cwd=e}async run(e){await new Promise(((t,i)=>{A(e,{cwd:this.cwd??void 0},(e=>{e?i(e):t()}))}))}});class L{constructor(){t(this,"project",void 0),t(this,"modifiedFiles",void 0),this.project=new k({tsConfigFilePath:"tsconfig.json"}),this.modifiedFiles=new Set,this.project.addSourceFilesAtPaths("src/**/*.ts"),this.project.addSourceFilesAtPaths("tailwind.config.js"),this.project.addSourceFilesAtPaths("vite.config.ts")}addSourceFile(e){this.project.addSourceFilesAtPaths(e)}requireSourceFile(e){return this.project.getSourceFileOrThrow(e)}async format(){await F.animate("Formatting modified files",(async()=>{const e=D.exists("prettier.config.js"),t=D.exists(".eslintrc.js");await Promise.all(a(this.modifiedFiles).map((async i=>{e&&await N.run(`npx prettier ${i} --write`),t&&await N.run(`npx eslint ${i} --fix`)})))}))}async save(e){await e.save(),this.modifiedFiles.add(e.getFilePath())}}class T{constructor(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t(this,"name",void 0),t(this,"options",void 0),this.name=e,this.options=i}create(e){!D.exists(e)||D.isDirectory(e)&&D.isEmptyDirectory(e)||F.fail(`Folder at '${e}' already exists!`),I.instantiate(P("templates/app"),e,{app:{name:this.name,slug:o(this.name)},dependencies:this.getDependencies(),contentPath:this.options.linkedLocal?`${O("core")}/dist/**/*.js`:"./node_modules/@aerogel/core/dist/**/*.js"})}edit(){return new L}getDependencies(){const e=e=>Object.entries(e).reduce(((e,t)=>{let[i,s]=t;return Object.assign(e,{[i]:`file:${s}`})}),{});return this.options.linkedLocal?e({aerogelCli:O("cli"),aerogelCore:O("core"),aerogelCypress:O("cypress"),aerogelPluginI18n:O("plugin-i18n"),aerogelPluginSoukai:O("plugin-soukai"),aerogelVite:O("vite")}):this.options.local?e({aerogelCli:E("cli")??b("cli"),aerogelCore:E("core")??b("core"),aerogelCypress:E("cypress")??b("cypress"),aerogelPluginI18n:E("plugin-i18n")??b("plugin-i18n"),aerogelPluginSoukai:E("plugin-soukai")??b("plugin-soukai"),aerogelVite:E("vite")??b("vite")}):{aerogelCli:"next",aerogelCore:"next",aerogelCypress:"next",aerogelPluginI18n:"next",aerogelPluginSoukai:"next",aerogelVite:"next"}}}class z{static define(e){var t=this;e=e.command(this.command).description(this.description);for(const[t,i]of this.parameters)e=e.argument(`<${t}>`,i);for(const[t,i]of Object.entries(this.options)){const s="string"==typeof i?i:i.description,n="string"==typeof i?"string":i.type??"string";e=e.option("boolean"===n?`--${t}`:`--${t} <${n}>`,s)}e=e.action((function(){for(var e=arguments.length,i=new Array(e),s=0;s<e;s++)i[s]=arguments[s];return t.run.call(t,...i)}))}static async run(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];const s=new this(...t);await s.run()}async run(){}assertAerogelOrDirectory(e){const t=D.read("package.json");if(t?.includes("@aerogel/core"))return;if(e&&D.isDirectory(e))return;const i=e?`${e} folder does not exist.`:"package.json does not contain @aerogel/core.";F.fail(`${i} Are you sure this is an Aerogel app?`)}}t(z,"command",""),t(z,"description",""),t(z,"parameters",[]),t(z,"options",{});class B extends z{constructor(e,i){super(),t(this,"path",void 0),t(this,"options",void 0),this.path=e,this.options=i}async run(){const e=this.path,t=this.options.name??"Aerogel App";N.setWorkingDirectory(e),await this.createApp(t,e),await this.installDependencies(),await this.initializeGit(),F.success(`\n\n That's it! You can start working on **${t}** doing the following:\n\n cd ${e}\n npm run dev\n\n Have fun!\n `)}async createApp(e,t){F.info(`Creating **${e}**...`),new T(e,{local:this.options.local,linkedLocal:this.options.local&&!this.options.copy}).create(t)}async installDependencies(){await F.animate("Installing dependencies",(async()=>{await N.run("npm install")}))}async initializeGit(){await F.animate("Initializing git",(async()=>{await N.run("git init"),await N.run("git add ."),await N.run('git commit -m "Start"')}))}}function M(){return new T("")}function q(){return D.isSymlink("node_modules/@aerogel/core")}function _(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e)return;const i=t.guard??(()=>!0),s=t.validate??(()=>!0),n=a(t.skip??[]);return e.forEachDescendant(((e,t)=>{if(i(e)&&s(e))return e;const r=e.getKind();n.includes(r)&&t.skip()}))}function J(e,t){if(e&&t(e))return e}t(B,"command","create"),t(B,"description","Create AerogelJS app"),t(B,"parameters",[["path","Application path"]]),t(B,"options",{name:"Application name",local:{type:"boolean",description:"Whether to create an app using local Aerogel packages (used for core development)"},copy:{type:"boolean",description:"Whether to create an app linked to local Aerogel packages (used in CI)"}});class W extends z{constructor(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),t(this,"path",void 0),t(this,"options",void 0),this.path=e,this.options=i}async run(){this.assertAerogelOrDirectory("src/components"),this.assertHistoireInstalled();const e=new Set,[t,i]=this.parsePathComponents();await this.createComponent(t,i,e),await this.createStory(i,e),await this.declareComponents();const s=a(e).map((e=>`- ${e}`)).join("\n");F.info(`${i} component created successfully! The following files were created:\n\n${s}`)}assertHistoireInstalled(){this.options.story&&(D.exists("src/main.histoire.ts")||F.fail("Histoire is not installed yet!"))}async createComponent(e,t,i){await F.animate("Creating component",(async()=>{D.exists(`src/components/${this.path}.vue`)&&F.fail(`${this.path} component already exists!`);I.instantiate(P("templates/component"),`src/components/${e}`,{component:{name:t}}).forEach((e=>i.add(e)))}))}async createStory(e,t){this.options.story&&await F.animate("Creating story",(async()=>{I.instantiate(P("templates/component-story"),"src/components",{component:{name:e}}).forEach((e=>t.add(e)))}))}async declareComponents(){const e=M().edit(),t=e.requireSourceFile("vite.config.ts"),i=this.getComponentDirsArray(t);if(!i)return F.fail("Could not find component dirs declaration in vite config!");i.getDescendantsOfKind(S.StringLiteral).some((e=>"'src/components'"===e.getText()))||(await F.animate("Updating vite config",(async()=>{i.addElement("'src/components'"),await e.save(t)})),await e.format())}getComponentDirsArray(e){const t=_(e,{guard:C.isCallExpression,validate:e=>e.getText().startsWith("Components("),skip:S.ImportDeclaration});if(!t)return null;const i=_(t,{guard:C.isPropertyAssignment,validate:e=>"dirs"===e.getName()}),s=i?.getInitializer();return C.isArrayLiteralExpression(s)?s:this.declareComponentDirsArray(t)}declareComponentDirsArray(e){const t=_(e,{guard:C.isObjectLiteralExpression}),i=t?.addPropertyAssignment({name:"dirs",initializer:"[]"});return i?.getInitializer()??null}parsePathComponents(){const e=this.path.lastIndexOf("/");return-1===e?["",this.path]:[this.path.substring(0,e),this.path.substring(e+1)]}}function G(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=e.split("\n"),s=t.indent??0;let n=0,r="";for(const e of i){const t=e.trim(),i=0===t.length;if(0===r.length){if(i)continue;n=e.indexOf(t[0]??""),r+=`${" ".repeat(s)}${t}\n`;continue}if(i){r+="\n";continue}const a=e.indexOf(t[0]??"");r+=`${" ".repeat(s+a-n)}${t}\n`}return r.trimEnd()}t(W,"command","generate:component"),t(W,"description","Generate an AerogelJS Component"),t(W,"parameters",[["path","Component path (relative to components folder; extension not necessary)"]]),t(W,"options",{story:{description:"Create component story using Histoire",type:"boolean"}});class H extends z{constructor(e){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),t(this,"name",void 0),t(this,"options",void 0),this.name=e,this.options=i}async run(){this.assertAerogelOrDirectory("src/models"),D.exists(`src/models/${this.name}.ts`)&&F.fail(`${this.name} model already exists!`),this.assertSoukaiInstalled();const e=await F.animate("Creating model",(async()=>I.instantiate(P("templates/model"),"src/models",{model:{name:this.name,fieldsDefinition:this.getFieldsDefinition()},soukaiImports:this.options.fields?"FieldType, defineModelSchema":"defineModelSchema"}).map((e=>`- ${e}`)).join("\n")));F.info(`${this.name} model created successfully! The following files were created:\n\n${e}`)}getFieldsDefinition(){if(!this.options.fields)return" //";const e=this.options.fields.split(",").map((e=>{const[t,i,s]=e.split(":");return{name:t,type:l(i??"string"),required:"required"===s}})).reduce(((e,t)=>e+`\n${t.required?G(`\n ${t.name}: {\n type: FieldType.${t.type},\n required: true,\n }\n `):`${t.name}: FieldType.${t.type}`},`),"");return G(e,{indent:8})}assertSoukaiInstalled(){D.contains("package.json",'"soukai"')||D.contains("package.json",'"@aerogel/plugin-soukai"')||F.fail("\n Soukai is not installed yet! You can install it running:\n npx ag install soukai\n ")}}t(H,"command","generate:model"),t(H,"description","Generate an AerogelJS Model"),t(H,"parameters",[["name","Model name"]]),t(H,"options",{fields:"Create model with the given fields"});class R extends z{constructor(e){super(),t(this,"name",void 0),this.name=e}async run(){this.assertAerogelOrDirectory("src/services");const e=new Set,t=M().edit();await this.createService(e),await this.registerService(t),await t.format();const i=a(e).map((e=>`- ${e}`)).join("\n");F.info(`${this.name} service created successfully! The following files were created:\n\n${i}`)}async createService(e){await F.animate("Creating service",(async()=>{D.exists(`src/services/${this.name}.ts`)&&F.fail(`${this.name} service already exists!`);I.instantiate(P("templates/service"),"src/services",{service:{name:this.name}}).forEach((t=>e.add(t)))}))}async registerService(e){await F.animate("Registering service",(async()=>{D.exists("src/services/index.ts")||await this.createServicesIndex(e);const t=e.requireSourceFile("src/services/index.ts"),i=this.getServicesObject(t);if(!i)return F.fail("Could not find services object in services config, please add it manually.");t.addImportDeclaration({defaultImport:this.name,moduleSpecifier:`./${this.name}`}),i.addPropertyAssignment({name:`$${c(this.name)}`,initializer:this.name}),await e.save(t)}))}async createServicesIndex(e){D.write("src/services/index.ts",G("\n export const services = {};\n\n export type AppServices = typeof services;\n\n declare module '@vue/runtime-core' {\n interface ComponentCustomProperties extends AppServices {}\n }\n ")),e.addSourceFile("src/services/index.ts");const t=e.requireSourceFile("src/main.ts"),i=this.getBootstrapOptions(t);if(!i)return F.fail("Could not find options object in bootstrap config, please add the services manually.");i.insertShorthandPropertyAssignment(0,{name:"services"}),t.addImportDeclaration({namedImports:["services"],moduleSpecifier:"./services"}),await e.save(t)}getBootstrapOptions(e){const t=_(e,{guard:C.isCallExpression,validate:e=>"bootstrapApplication"===e.getExpression().getText(),skip:S.ImportDeclaration}),i=t?.getArguments()[1];return C.isObjectLiteralExpression(i)?i:null}getServicesObject(e){const t=_(e,{guard:C.isVariableDeclaration,validate:e=>"services"===e.getName()}),i=t?.getInitializer();return C.isObjectLiteralExpression(i)?i:null}}t(R,"command","generate:service"),t(R,"description","Generate an AerogelJS Service"),t(R,"parameters",[["name","Service name"]]);class V{constructor(e){t(this,"name",void 0),this.name=e}async install(){this.assertNotInstalled(),await this.installDependencies();{const e=M().edit();await this.updateFiles(e),await e.format()}F.info(`Plugin ${this.name} installed!`)}assertNotInstalled(){D.contains("package.json",`"${this.getNpmPackageName()}"`)&&F.fail(`${this.name} is already installed!`)}async installDependencies(){await F.animate("Installing plugin dependencies",(async()=>{await this.installNpmDependencies()}))}async updateFiles(e){await this.updateBootstrapConfig(e)}async installNpmDependencies(){if(q())await N.run(`npm install file:${O(this.getLocalPackageName())}`);else if(D.contains("package.json","file")){const e=E(this.getLocalPackageName())??b(this.getLocalPackageName());await N.run(`npm install file:${e}`)}else await N.run(`npm install ${this.getNpmPackageName()}@next`)}async updateBootstrapConfig(e){await F.animate("Injecting plugin in bootstrap configuration",(async()=>{const t=e.requireSourceFile("src/main.ts"),i=this.getBootstrapPluginsDeclaration(t);if(!i)return F.fail(`\n Could not find plugins array in bootstrap config, please add the following manually:\n\n ${this.getBootstrapConfig()}\n `);t.addImportDeclaration(this.getBootstrapImport()),i.addElement(this.getBootstrapConfig()),await e.save(t)}))}getBootstrapPluginsDeclaration(e){const t=_(e,{guard:C.isCallExpression,validate:e=>"bootstrapApplication"===e.getExpression().getText(),skip:S.ImportDeclaration}),i=t?.getArguments()[1],s=J(i,C.isObjectLiteralExpression)?.getProperty("plugins"),n=J(s,C.isPropertyAssignment)?.getInitializer();return C.isArrayLiteralExpression(n)?n:null}getBootstrapImport(){return{defaultImport:this.name,moduleSpecifier:`@aerogel/plugin-${this.name}`}}getNpmPackageName(){return`@aerogel/${this.getLocalPackageName()}`}getLocalPackageName(){return`plugin-${this.name}`}getBootstrapConfig(){return`${this.name}()`}}const K=[new class extends V{constructor(){super("soukai")}async installNpmDependencies(){await N.run("npm install soukai@next"),await super.installNpmDependencies()}getBootstrapConfig(){return"soukai({ models: import.meta.glob('@/models/*', { eager: true }) })"}},new class extends V{constructor(){super("solid")}async updateFiles(e){await this.updateTailwindConfig(e),await super.updateFiles(e)}async installNpmDependencies(){await N.run("npm install soukai-solid@next"),await super.installNpmDependencies()}async updateTailwindConfig(e){await F.animate("Updating tailwind configuration",(async()=>{const t=e.requireSourceFile("tailwind.config.js"),i=this.getTailwindContentArray(t),s=q()?`'${O("plugin-solid")}/dist/**/*.js'`:"'./node_modules/@aerogel/plugin-solid/dist/**/*.js'";if(!i)return F.fail(`\n Could not find content array in tailwind config, please add the following manually:\n\n ${s}\n `);i.addElement(s),await e.save(t)}))}getTailwindContentArray(e){const t=_(e,{guard:C.isPropertyAssignment,validate:e=>"content"===e.getName(),skip:S.JSDoc}),i=t?.getInitializer();return C.isArrayLiteralExpression(i)?i:null}}].reduce(((e,t)=>Object.assign(e,{[t.name]:t})),{});class U extends z{constructor(e){super(),t(this,"plugin",void 0),this.plugin=K[e]??F.fail(`Plugin '${e}' doesn't exist. Available plugins: ${Object.keys(K).join(", ")}`)}async run(){await this.plugin.install()}}t(U,"command","install"),t(U,"description","Install an AerogelJS plugin"),t(U,"parameters",[["plugin","Plugin to install"]]);var Y=i(new class{run(t){const i=new e;i.name("ag").description("AerogelJS CLI").version("0.0.0"),B.define(i),W.define(i),H.define(i),R.define(i),U.define(i),i.parse(t)}});export{Y as CLI};
2
2
  //# sourceMappingURL=aerogel-cli.esm.js.map
@@ -1,4 +1,14 @@
1
1
  /** @type {import('@noeldemartin/scripts').Config} */
2
2
  module.exports = {
3
- external: ['fs', '@noeldemartin/utils', 'chalk', 'child_process', 'commander', 'mustache', 'path', 'readline'],
3
+ external: [
4
+ '@noeldemartin/utils',
5
+ 'chalk',
6
+ 'child_process',
7
+ 'commander',
8
+ 'fs',
9
+ 'mustache',
10
+ 'path',
11
+ 'readline',
12
+ 'ts-morph',
13
+ ],
4
14
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@aerogel/cli",
3
3
  "description": "Aerogel CLI",
4
- "version": "0.0.0-next.926bde19326fe7b6b24b277666936862b64d8295",
4
+ "version": "0.0.0-next.b85327579d32f21c6a9fa21142f0165cdd320d7e",
5
5
  "main": "dist/aerogel-cli.cjs.js",
6
6
  "module": "dist/aerogel-cli.esm.js",
7
7
  "types": "dist/aerogel-cli.d.ts",
@@ -38,7 +38,8 @@
38
38
  "@noeldemartin/utils": "0.4.0-next.ac00beaecf32bb02ed8e335225d7948d946d73bd",
39
39
  "chalk": "^4.1.2",
40
40
  "commander": "^11.0.0",
41
- "mustache": "^4.2.0"
41
+ "mustache": "^4.2.0",
42
+ "ts-morph": "^20.0.0"
42
43
  },
43
44
  "devDependencies": {
44
45
  "@types/node": "^20.4.0"
package/src/cli.ts CHANGED
@@ -3,6 +3,8 @@ import { CreateCommand } from '@/commands/create';
3
3
  import { facade } from '@noeldemartin/utils';
4
4
  import { GenerateComponentCommand } from '@/commands/generate-component';
5
5
  import { GenerateModelCommand } from '@/commands/generate-model';
6
+ import { GenerateServiceCommand } from '@/commands/generate-service';
7
+ import { InstallCommand } from '@/commands/install';
6
8
 
7
9
  export class CLIService {
8
10
 
@@ -14,6 +16,8 @@ export class CLIService {
14
16
  CreateCommand.define(program);
15
17
  GenerateComponentCommand.define(program);
16
18
  GenerateModelCommand.define(program);
19
+ GenerateServiceCommand.define(program);
20
+ InstallCommand.define(program);
17
21
 
18
22
  program.parse(argv);
19
23
  }
@@ -7,20 +7,28 @@ import { CreateCommand } from './create';
7
7
 
8
8
  describe('Create command', () => {
9
9
 
10
- it('works', async () => {
10
+ it('creates apps', async () => {
11
11
  // Act
12
12
  await CreateCommand.run('./app', { name: 'My App' });
13
13
 
14
14
  // Assert
15
15
  FileMock.expectCreated('./app/.gitignore').toContain('node_modules');
16
16
  FileMock.expectCreated('./app/package.json').toContain('"name": "my-app"');
17
+ FileMock.expectCreated('./app/package.json').toContain('"@aerogel/core": "next"');
17
18
  FileMock.expectCreated('./app/index.html').toContain('My App');
18
- FileMock.expectCreated('./app/src/App.vue').toContain(
19
- '<h1 class="text-4xl font-semibold">{{ $t(\'home.title\') }}</h1>',
20
- );
19
+ FileMock.expectCreated('./app/src/App.vue').toContain('<h1 class="text-4xl font-semibold">');
20
+ FileMock.expectCreated('./app/src/App.vue').toContain('{{ $t(\'home.title\') }}');
21
21
 
22
22
  ShellMock.expectRan('npm install');
23
23
  ShellMock.expectRan('git init');
24
24
  });
25
25
 
26
+ it('creates apps for local core development', async () => {
27
+ // Act
28
+ await CreateCommand.run('./app', { name: 'My App', local: true });
29
+
30
+ // Assert
31
+ FileMock.expectCreated('./app/package.json').toMatch(/"@aerogel\/core": "file:[^"]+\/packages\/core"/);
32
+ });
33
+
26
34
  });
@@ -2,9 +2,12 @@ import App from '@/lib/App';
2
2
  import Command from '@/commands/Command';
3
3
  import Log from '@/lib/Log';
4
4
  import Shell from '@/lib/Shell';
5
+ import type { CommandOptions } from '@/commands/Command';
5
6
 
6
7
  export interface Options {
7
8
  name?: string;
9
+ local?: boolean;
10
+ copy?: boolean;
8
11
  }
9
12
 
10
13
  export class CreateCommand extends Command {
@@ -12,8 +15,16 @@ export class CreateCommand extends Command {
12
15
  public static command: string = 'create';
13
16
  public static description: string = 'Create AerogelJS app';
14
17
  public static parameters: [string, string][] = [['path', 'Application path']];
15
- public static options: Record<string, string> = {
18
+ public static options: CommandOptions = {
16
19
  name: 'Application name',
20
+ local: {
21
+ type: 'boolean',
22
+ description: 'Whether to create an app using local Aerogel packages (used for core development)',
23
+ },
24
+ copy: {
25
+ type: 'boolean',
26
+ description: 'Whether to create an app linked to local Aerogel packages (used in CI)',
27
+ },
17
28
  };
18
29
 
19
30
  private path: string;
@@ -50,7 +61,10 @@ export class CreateCommand extends Command {
50
61
  protected async createApp(name: string, path: string): Promise<void> {
51
62
  Log.info(`Creating **${name}**...`);
52
63
 
53
- new App(name).create(path);
64
+ new App(name, {
65
+ local: this.options.local,
66
+ linkedLocal: this.options.local && !this.options.copy,
67
+ }).create(path);
54
68
  }
55
69
 
56
70
  protected async installDependencies(): Promise<void> {
@@ -4,7 +4,7 @@ import FileMock from '@/lib/File.mock';
4
4
 
5
5
  import { GenerateComponentCommand } from './generate-component';
6
6
 
7
- describe('Generate component command', () => {
7
+ describe('Generate Component command', () => {
8
8
 
9
9
  it('generates components', async () => {
10
10
  // Arrange
@@ -17,6 +17,17 @@ describe('Generate component command', () => {
17
17
  FileMock.expectCreated('src/components/FooBar.vue').toContain('<div>FooBar</div>');
18
18
  });
19
19
 
20
+ it('generates components in subfolders', async () => {
21
+ // Arrange
22
+ FileMock.stub('package.json', '@aerogel/core');
23
+
24
+ // Act
25
+ await GenerateComponentCommand.run('module/FooBar');
26
+
27
+ // Assert
28
+ FileMock.expectCreated('src/components/module/FooBar.vue').toContain('<div>FooBar</div>');
29
+ });
30
+
20
31
  it('generates components with stories', async () => {
21
32
  // Arrange
22
33
  FileMock.stub('package.json', '@aerogel/core');
@@ -1,8 +1,14 @@
1
+ import { arrayFrom } from '@noeldemartin/utils';
2
+ import { Node, SyntaxKind } from 'ts-morph';
3
+ import type { ArrayLiteralExpression, CallExpression, SourceFile } from 'ts-morph';
4
+
1
5
  import Command from '@/commands/Command';
2
6
  import File from '@/lib/File';
3
7
  import Log from '@/lib/Log';
4
8
  import Template from '@/lib/Template';
5
- import { basePath } from '@/lib/utils';
9
+ import { app } from '@/lib/utils/app';
10
+ import { editFiles, findDescendant } from '@/lib/utils/edit';
11
+ import { basePath } from '@/lib/utils/paths';
6
12
  import type { CommandOptions } from '@/commands/Command';
7
13
 
8
14
  export interface Options {
@@ -12,8 +18,11 @@ export interface Options {
12
18
  export class GenerateComponentCommand extends Command {
13
19
 
14
20
  public static command: string = 'generate:component';
15
- public static description: string = 'Generate an AerogelJS component';
16
- public static parameters: [string, string][] = [['name', 'Component name']];
21
+ public static description: string = 'Generate an AerogelJS Component';
22
+ public static parameters: [string, string][] = [
23
+ ['path', 'Component path (relative to components folder; extension not necessary)'],
24
+ ];
25
+
17
26
  public static options: CommandOptions = {
18
27
  story: {
19
28
  description: 'Create component story using Histoire',
@@ -21,45 +30,145 @@ export class GenerateComponentCommand extends Command {
21
30
  },
22
31
  };
23
32
 
24
- private name: string;
33
+ private path: string;
25
34
  private options: Options;
26
35
 
27
- constructor(name: string, options: Options = {}) {
36
+ constructor(path: string, options: Options = {}) {
28
37
  super();
29
38
 
30
- this.name = name;
39
+ this.path = path;
31
40
  this.options = options;
32
41
  }
33
42
 
34
43
  public async run(): Promise<void> {
35
44
  this.assertAerogelOrDirectory('src/components');
36
- this.options.story && this.assertHistoireInstalled();
45
+ this.assertHistoireInstalled();
46
+
47
+ const files = new Set<string>();
48
+ const [directoryName, componentName] = this.parsePathComponents();
49
+
50
+ await this.createComponent(directoryName, componentName, files);
51
+ await this.createStory(componentName, files);
52
+ await this.declareComponents();
53
+
54
+ const filesList = arrayFrom(files)
55
+ .map((file) => `- ${file}`)
56
+ .join('\n');
57
+
58
+ Log.info(`${componentName} component created successfully! The following files were created:\n\n${filesList}`);
59
+ }
37
60
 
38
- if (File.exists(`src/components/${this.name}.vue`)) {
39
- Log.fail(`${this.name} component already exists!`);
61
+ protected assertHistoireInstalled(): void {
62
+ if (!this.options.story) {
63
+ return;
40
64
  }
41
65
 
42
- const files = Template.instantiate(basePath('templates/component'), 'src/components', {
43
- component: { name: this.name },
66
+ if (!File.exists('src/main.histoire.ts')) {
67
+ Log.fail('Histoire is not installed yet!');
68
+ }
69
+ }
70
+
71
+ protected async createComponent(directoryName: string, componentName: string, files: Set<string>): Promise<void> {
72
+ await Log.animate('Creating component', async () => {
73
+ if (File.exists(`src/components/${this.path}.vue`)) {
74
+ Log.fail(`${this.path} component already exists!`);
75
+ }
76
+
77
+ const componentFiles = Template.instantiate(
78
+ basePath('templates/component'),
79
+ `src/components/${directoryName}`,
80
+ { component: { name: componentName } },
81
+ );
82
+
83
+ componentFiles.forEach((file) => files.add(file));
44
84
  });
85
+ }
86
+
87
+ protected async createStory(componentName: string, files: Set<string>): Promise<void> {
88
+ if (!this.options.story) {
89
+ return;
90
+ }
45
91
 
46
- if (this.options.story) {
92
+ await Log.animate('Creating story', async () => {
47
93
  const storyFiles = Template.instantiate(basePath('templates/component-story'), 'src/components', {
48
- component: { name: this.name },
94
+ component: { name: componentName },
49
95
  });
50
96
 
51
- files.push(...storyFiles);
97
+ storyFiles.forEach((file) => files.add(file));
98
+ });
99
+ }
100
+
101
+ protected async declareComponents(): Promise<void> {
102
+ if (!editFiles()) {
103
+ return;
104
+ }
105
+
106
+ const editor = app().edit();
107
+ const viteConfig = editor.requireSourceFile('vite.config.ts');
108
+ const componentDirsArray = this.getComponentDirsArray(viteConfig);
109
+
110
+ if (!componentDirsArray) {
111
+ return Log.fail('Could not find component dirs declaration in vite config!');
112
+ }
113
+
114
+ if (
115
+ componentDirsArray
116
+ .getDescendantsOfKind(SyntaxKind.StringLiteral)
117
+ .some((literal) => literal.getText() === '\'src/components\'')
118
+ ) {
119
+ return;
52
120
  }
53
121
 
54
- const filesList = files.map((file) => `- ${file}`).join('\n');
122
+ await Log.animate('Updating vite config', async () => {
123
+ componentDirsArray.addElement('\'src/components\'');
55
124
 
56
- Log.info(`${this.name} component created successfully! The following files were created:\n\n${filesList}`);
125
+ await editor.save(viteConfig);
126
+ });
127
+
128
+ await editor.format();
57
129
  }
58
130
 
59
- protected assertHistoireInstalled(): void {
60
- if (!File.exists('src/main.histoire.ts')) {
61
- Log.fail('Histoire is not installed yet!');
131
+ protected getComponentDirsArray(viteConfig: SourceFile): ArrayLiteralExpression | null {
132
+ const pluginCall = findDescendant(viteConfig, {
133
+ guard: Node.isCallExpression,
134
+ validate: (callExpression) => callExpression.getText().startsWith('Components('),
135
+ skip: SyntaxKind.ImportDeclaration,
136
+ });
137
+
138
+ if (!pluginCall) {
139
+ return null;
62
140
  }
141
+
142
+ const dirsAssignment = findDescendant(pluginCall, {
143
+ guard: Node.isPropertyAssignment,
144
+ validate: (propertyAssignment) => propertyAssignment.getName() === 'dirs',
145
+ });
146
+
147
+ const dirsArray = dirsAssignment?.getInitializer();
148
+
149
+ if (!Node.isArrayLiteralExpression(dirsArray)) {
150
+ return this.declareComponentDirsArray(pluginCall);
151
+ }
152
+
153
+ return dirsArray;
154
+ }
155
+
156
+ protected declareComponentDirsArray(pluginCall: CallExpression): ArrayLiteralExpression | null {
157
+ const pluginOptions = findDescendant(pluginCall, { guard: Node.isObjectLiteralExpression });
158
+ const dirsAssignment = pluginOptions?.addPropertyAssignment({
159
+ name: 'dirs',
160
+ initializer: '[]',
161
+ });
162
+
163
+ return (dirsAssignment?.getInitializer() as ArrayLiteralExpression) ?? null;
164
+ }
165
+
166
+ protected parsePathComponents(): [string, string] {
167
+ const lastSlashIndex = this.path.lastIndexOf('/');
168
+
169
+ return lastSlashIndex === -1
170
+ ? ['', this.path]
171
+ : [this.path.substring(0, lastSlashIndex), this.path.substring(lastSlashIndex + 1)];
63
172
  }
64
173
 
65
174
  }
@@ -1,11 +1,11 @@
1
1
  import { describe, it } from 'vitest';
2
2
 
3
3
  import FileMock from '@/lib/File.mock';
4
- import { formatCodeBlock } from '@/lib/utils';
4
+ import { formatCodeBlock } from '@/lib/utils/format';
5
5
 
6
6
  import { GenerateModelCommand } from './generate-model';
7
7
 
8
- describe('Generate model command', () => {
8
+ describe('Generate Model command', () => {
9
9
 
10
10
  it('generates models', async () => {
11
11
  // Arrange
@@ -21,7 +21,7 @@ describe('Generate model command', () => {
21
21
 
22
22
  // Act
23
23
  await GenerateModelCommand.run('FooBar', {
24
- fields: 'name:string,age:number,birth:Date',
24
+ fields: 'name:string:required,age:number,birth:Date',
25
25
  });
26
26
 
27
27
  // Assert
@@ -30,7 +30,10 @@ describe('Generate model command', () => {
30
30
  formatCodeBlock(`
31
31
  defineModelSchema({
32
32
  fields: {
33
- name: FieldType.String,
33
+ name: {
34
+ type: FieldType.String,
35
+ required: true,
36
+ },
34
37
  age: FieldType.Number,
35
38
  birth: FieldType.Date,
36
39
  },