@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
@@ -4,7 +4,8 @@ import Command from '@/commands/Command';
4
4
  import File from '@/lib/File';
5
5
  import Log from '@/lib/Log';
6
6
  import Template from '@/lib/Template';
7
- import { basePath, formatCodeBlock } from '@/lib/utils';
7
+ import { basePath } from '@/lib/utils/paths';
8
+ import { formatCodeBlock } from '@/lib/utils/format';
8
9
  import type { CommandOptions } from '@/commands/Command';
9
10
 
10
11
  interface Options {
@@ -14,7 +15,7 @@ interface Options {
14
15
  export class GenerateModelCommand extends Command {
15
16
 
16
17
  public static command: string = 'generate:model';
17
- public static description: string = 'Generate an AerogelJS model';
18
+ public static description: string = 'Generate an AerogelJS Model';
18
19
  public static parameters: [string, string][] = [['name', 'Model name']];
19
20
  public static options: CommandOptions = {
20
21
  fields: 'Create model with the given fields',
@@ -39,15 +40,17 @@ export class GenerateModelCommand extends Command {
39
40
 
40
41
  this.assertSoukaiInstalled();
41
42
 
42
- const files = Template.instantiate(basePath('templates/model'), 'src/models', {
43
- model: {
44
- name: this.name,
45
- fieldsDefinition: this.getFieldsDefinition(),
46
- },
47
- soukaiImports: this.options.fields ? 'FieldType, defineModelSchema' : 'defineModelSchema',
48
- });
43
+ const filesList = await Log.animate('Creating model', async () => {
44
+ const files = Template.instantiate(basePath('templates/model'), 'src/models', {
45
+ model: {
46
+ name: this.name,
47
+ fieldsDefinition: this.getFieldsDefinition(),
48
+ },
49
+ soukaiImports: this.options.fields ? 'FieldType, defineModelSchema' : 'defineModelSchema',
50
+ });
49
51
 
50
- const filesList = files.map((file) => `- ${file}`).join('\n');
52
+ return files.map((file) => `- ${file}`).join('\n');
53
+ });
51
54
 
52
55
  Log.info(`${this.name} model created successfully! The following files were created:\n\n${filesList}`);
53
56
  }
@@ -60,28 +63,35 @@ export class GenerateModelCommand extends Command {
60
63
  const code = this.options.fields
61
64
  .split(',')
62
65
  .map((field) => {
63
- const [name, type] = field.split(':');
66
+ const [name, type, rules] = field.split(':');
64
67
 
65
68
  return {
66
69
  name,
67
70
  type: stringToStudlyCase(type ?? 'string'),
71
+ required: rules === 'required',
68
72
  };
69
73
  })
70
- .reduce((definition, field) => definition + `\n${field.name}: FieldType.${field.type},`, '');
74
+ .reduce((definition, field) => {
75
+ const fieldDefinition = field.required
76
+ ? formatCodeBlock(`
77
+ ${field.name}: {
78
+ type: FieldType.${field.type},
79
+ required: true,
80
+ }
81
+ `)
82
+ : `${field.name}: FieldType.${field.type}`;
83
+
84
+ return definition + `\n${fieldDefinition},`;
85
+ }, '');
71
86
 
72
87
  return formatCodeBlock(code, { indent: 8 });
73
88
  }
74
89
 
75
90
  protected assertSoukaiInstalled(): void {
76
- if (!File.contains('package.json', '"soukai"')) {
91
+ if (!File.contains('package.json', '"soukai"') && !File.contains('package.json', '"@aerogel/plugin-soukai"')) {
77
92
  Log.fail(`
78
- Soukai is not installed yet! You can install it doing the following:
79
-
80
- 1. Run the following command:
81
- npm install soukai @aerogel/plugin-soukai"
82
-
83
- 2. Add this to your plugins array:
84
- soukai({ models: import.meta.glob('@/models/*', { eager: true }) })
93
+ Soukai is not installed yet! You can install it running:
94
+ npx ag install soukai
85
95
  `);
86
96
  }
87
97
  }
@@ -0,0 +1,21 @@
1
+ import { describe, it } from 'vitest';
2
+
3
+ import FileMock from '@/lib/File.mock';
4
+
5
+ import { GenerateServiceCommand } from './generate-service';
6
+
7
+ describe('Generate Service command', () => {
8
+
9
+ it('generates services', async () => {
10
+ // Arrange
11
+ FileMock.stub('package.json', '@aerogel/core');
12
+
13
+ // Act
14
+ await GenerateServiceCommand.run('FooBar');
15
+
16
+ // Assert
17
+ FileMock.expectCreated('src/services/FooBar.ts').toContain('class FooBarService extends Service');
18
+ FileMock.expectCreated('src/services/FooBar.ts').toContain('export default facade(new FooBarService());');
19
+ });
20
+
21
+ });
@@ -0,0 +1,152 @@
1
+ import { arrayFrom, stringToCamelCase } from '@noeldemartin/utils';
2
+ import { Node, SyntaxKind } from 'ts-morph';
3
+ import type { ObjectLiteralExpression, SourceFile } from 'ts-morph';
4
+
5
+ import Command from '@/commands/Command';
6
+ import File from '@/lib/File';
7
+ import Log from '@/lib/Log';
8
+ import Template from '@/lib/Template';
9
+ import { app } from '@/lib/utils/app';
10
+ import { basePath } from '@/lib/utils/paths';
11
+ import { editFiles, findDescendant } from '@/lib/utils/edit';
12
+ import { formatCodeBlock } from '@/lib/utils/format';
13
+ import type { Editor } from '@/lib/Editor';
14
+
15
+ export class GenerateServiceCommand extends Command {
16
+
17
+ public static command: string = 'generate:service';
18
+ public static description: string = 'Generate an AerogelJS Service';
19
+ public static parameters: [string, string][] = [['name', 'Service name']];
20
+
21
+ private name: string;
22
+
23
+ constructor(name: string) {
24
+ super();
25
+
26
+ this.name = name;
27
+ }
28
+
29
+ public async run(): Promise<void> {
30
+ this.assertAerogelOrDirectory('src/services');
31
+
32
+ const files = new Set<string>();
33
+ const editor = app().edit();
34
+
35
+ await this.createService(files);
36
+
37
+ if (editFiles()) {
38
+ await this.registerService(editor);
39
+ await editor.format();
40
+ }
41
+
42
+ const filesList = arrayFrom(files)
43
+ .map((file) => `- ${file}`)
44
+ .join('\n');
45
+
46
+ Log.info(`${this.name} service created successfully! The following files were created:\n\n${filesList}`);
47
+ }
48
+
49
+ protected async createService(files: Set<string>): Promise<void> {
50
+ await Log.animate('Creating service', async () => {
51
+ if (File.exists(`src/services/${this.name}.ts`)) {
52
+ Log.fail(`${this.name} service already exists!`);
53
+ }
54
+
55
+ const serviceFiles = Template.instantiate(basePath('templates/service'), 'src/services', {
56
+ service: {
57
+ name: this.name,
58
+ },
59
+ });
60
+
61
+ serviceFiles.forEach((file) => files.add(file));
62
+ });
63
+ }
64
+
65
+ protected async registerService(editor: Editor): Promise<void> {
66
+ await Log.animate('Registering service', async () => {
67
+ if (!File.exists('src/services/index.ts')) {
68
+ await this.createServicesIndex(editor);
69
+ }
70
+
71
+ const servicesIndex = editor.requireSourceFile('src/services/index.ts');
72
+ const servicesObject = this.getServicesObject(servicesIndex);
73
+
74
+ if (!servicesObject) {
75
+ return Log.fail('Could not find services object in services config, please add it manually.');
76
+ }
77
+
78
+ servicesIndex.addImportDeclaration({
79
+ defaultImport: this.name,
80
+ moduleSpecifier: `./${this.name}`,
81
+ });
82
+ servicesObject.addPropertyAssignment({
83
+ name: `$${stringToCamelCase(this.name)}`,
84
+ initializer: this.name,
85
+ });
86
+
87
+ await editor.save(servicesIndex);
88
+ });
89
+ }
90
+
91
+ protected async createServicesIndex(editor: Editor): Promise<void> {
92
+ File.write(
93
+ 'src/services/index.ts',
94
+ formatCodeBlock(`
95
+ export const services = {};
96
+
97
+ export type AppServices = typeof services;
98
+
99
+ declare module '@vue/runtime-core' {
100
+ interface ComponentCustomProperties extends AppServices {}
101
+ }
102
+ `),
103
+ );
104
+
105
+ editor.addSourceFile('src/services/index.ts');
106
+
107
+ const mainConfig = editor.requireSourceFile('src/main.ts');
108
+ const bootstrapOptions = this.getBootstrapOptions(mainConfig);
109
+
110
+ if (!bootstrapOptions) {
111
+ return Log.fail('Could not find options object in bootstrap config, please add the services manually.');
112
+ }
113
+
114
+ bootstrapOptions.insertShorthandPropertyAssignment(0, { name: 'services' });
115
+ mainConfig.addImportDeclaration({
116
+ namedImports: ['services'],
117
+ moduleSpecifier: './services',
118
+ });
119
+
120
+ await editor.save(mainConfig);
121
+ }
122
+
123
+ protected getBootstrapOptions(mainConfig: SourceFile): ObjectLiteralExpression | null {
124
+ const bootstrapAppCall = findDescendant(mainConfig, {
125
+ guard: Node.isCallExpression,
126
+ validate: (callExpression) => callExpression.getExpression().getText() === 'bootstrapApplication',
127
+ skip: SyntaxKind.ImportDeclaration,
128
+ });
129
+ const bootstrapOptions = bootstrapAppCall?.getArguments()[1];
130
+
131
+ if (!Node.isObjectLiteralExpression(bootstrapOptions)) {
132
+ return null;
133
+ }
134
+
135
+ return bootstrapOptions;
136
+ }
137
+
138
+ protected getServicesObject(servicesIndex: SourceFile): ObjectLiteralExpression | null {
139
+ const servicesDeclaration = findDescendant(servicesIndex, {
140
+ guard: Node.isVariableDeclaration,
141
+ validate: (variableDeclaration) => variableDeclaration.getName() === 'services',
142
+ });
143
+ const servicesObject = servicesDeclaration?.getInitializer();
144
+
145
+ if (!Node.isObjectLiteralExpression(servicesObject)) {
146
+ return null;
147
+ }
148
+
149
+ return servicesObject;
150
+ }
151
+
152
+ }
@@ -0,0 +1,18 @@
1
+ import { describe, it } from 'vitest';
2
+
3
+ import ShellMock from '@/lib/Shell.mock';
4
+
5
+ import { InstallCommand } from './install';
6
+
7
+ describe('Install plugin command', () => {
8
+
9
+ it('installs plugins', async () => {
10
+ // Act
11
+ await InstallCommand.run('solid');
12
+
13
+ // Assert
14
+ ShellMock.expectRan('npm install soukai-solid@next');
15
+ ShellMock.expectRan('npm install @aerogel/plugin-solid@next');
16
+ });
17
+
18
+ });
@@ -0,0 +1,32 @@
1
+ import Command from '@/commands/Command';
2
+ import Log from '@/lib/Log';
3
+ import { Solid } from '@/plugins/Solid';
4
+ import { Soukai } from '@/plugins/Soukai';
5
+ import type Plugin from '@/plugins/Plugin';
6
+
7
+ const plugins = [new Soukai(), new Solid()].reduce(
8
+ (pluginsObject, plugin) => Object.assign(pluginsObject, { [plugin.name]: plugin }),
9
+ {} as Record<string, Plugin>,
10
+ );
11
+
12
+ export class InstallCommand extends Command {
13
+
14
+ public static command: string = 'install';
15
+ public static description: string = 'Install an AerogelJS plugin';
16
+ public static parameters: [string, string][] = [['plugin', 'Plugin to install']];
17
+
18
+ private plugin: Plugin;
19
+
20
+ constructor(plugin: string) {
21
+ super();
22
+
23
+ this.plugin =
24
+ plugins[plugin] ??
25
+ Log.fail(`Plugin '${plugin}' doesn't exist. Available plugins: ${Object.keys(plugins).join(', ')}`);
26
+ }
27
+
28
+ public async run(): Promise<void> {
29
+ await this.plugin.install();
30
+ }
31
+
32
+ }
package/src/lib/App.ts CHANGED
@@ -3,11 +3,26 @@ import { stringToSlug } from '@noeldemartin/utils';
3
3
  import File from '@/lib/File';
4
4
  import Log from '@/lib/Log';
5
5
  import Template from '@/lib/Template';
6
- import { basePath } from '@/lib/utils';
6
+ import { basePath, packNotFound, packagePackPath, packagePath } from '@/lib/utils/paths';
7
+ import { Editor } from '@/lib/Editor';
8
+
9
+ interface Dependencies {
10
+ aerogelCli: string;
11
+ aerogelCore: string;
12
+ aerogelCypress: string;
13
+ aerogelPluginI18n: string;
14
+ aerogelPluginSoukai: string;
15
+ aerogelVite: string;
16
+ }
17
+
18
+ export interface Options {
19
+ local?: boolean;
20
+ linkedLocal?: boolean;
21
+ }
7
22
 
8
23
  export default class App {
9
24
 
10
- constructor(public name: string) {}
25
+ constructor(protected name: string, protected options: Options = {}) {}
11
26
 
12
27
  public create(path: string): void {
13
28
  if (File.exists(path) && (!File.isDirectory(path) || !File.isEmptyDirectory(path))) {
@@ -19,7 +34,54 @@ export default class App {
19
34
  name: this.name,
20
35
  slug: stringToSlug(this.name),
21
36
  },
37
+ dependencies: this.getDependencies(),
38
+ contentPath: this.options.linkedLocal
39
+ ? `${packagePath('core')}/dist/**/*.js`
40
+ : './node_modules/@aerogel/core/dist/**/*.js',
22
41
  });
23
42
  }
24
43
 
44
+ public edit(): Editor {
45
+ return new Editor();
46
+ }
47
+
48
+ protected getDependencies(): Dependencies {
49
+ const withFilePrefix = <T extends Record<string, string>>(paths: T) =>
50
+ Object.entries(paths).reduce(
51
+ (pathsWithFile, [name, path]) => Object.assign(pathsWithFile, { [name]: `file:${path}` }) as T,
52
+ {} as T,
53
+ );
54
+
55
+ if (this.options.linkedLocal) {
56
+ return withFilePrefix({
57
+ aerogelCli: packagePath('cli'),
58
+ aerogelCore: packagePath('core'),
59
+ aerogelCypress: packagePath('cypress'),
60
+ aerogelPluginI18n: packagePath('plugin-i18n'),
61
+ aerogelPluginSoukai: packagePath('plugin-soukai'),
62
+ aerogelVite: packagePath('vite'),
63
+ });
64
+ }
65
+
66
+ if (this.options.local) {
67
+ return withFilePrefix({
68
+ aerogelCli: packagePackPath('cli') ?? packNotFound('cli'),
69
+ aerogelCore: packagePackPath('core') ?? packNotFound('core'),
70
+ aerogelCypress: packagePackPath('cypress') ?? packNotFound('cypress'),
71
+ aerogelPluginI18n: packagePackPath('plugin-i18n') ?? packNotFound('plugin-i18n'),
72
+ aerogelPluginSoukai: packagePackPath('plugin-soukai') ?? packNotFound('plugin-soukai'),
73
+ aerogelVite: packagePackPath('vite') ?? packNotFound('vite'),
74
+ });
75
+ }
76
+
77
+ return {
78
+ aerogelCli: 'next',
79
+ aerogelCore: 'next',
80
+ aerogelCypress: 'next',
81
+ aerogelPluginI18n: 'next',
82
+ aerogelPluginSoukai: 'next',
83
+ aerogelVite: 'next',
84
+ };
85
+ }
86
+
25
87
  }
@@ -0,0 +1,51 @@
1
+ import { arrayFrom } from '@noeldemartin/utils';
2
+ import { Project } from 'ts-morph';
3
+ import type { SourceFile } from 'ts-morph';
4
+
5
+ import File from '@/lib/File';
6
+ import Log from '@/lib/Log';
7
+ import Shell from '@/lib/Shell';
8
+
9
+ export class Editor {
10
+
11
+ private project: Project;
12
+ private modifiedFiles: Set<string>;
13
+
14
+ constructor() {
15
+ this.project = new Project({ tsConfigFilePath: 'tsconfig.json' });
16
+ this.modifiedFiles = new Set();
17
+
18
+ this.project.addSourceFilesAtPaths('src/**/*.ts');
19
+ this.project.addSourceFilesAtPaths('tailwind.config.js');
20
+ this.project.addSourceFilesAtPaths('vite.config.ts');
21
+ }
22
+
23
+ public addSourceFile(path: string): void {
24
+ this.project.addSourceFilesAtPaths(path);
25
+ }
26
+
27
+ public requireSourceFile(path: string): SourceFile {
28
+ return this.project.getSourceFileOrThrow(path);
29
+ }
30
+
31
+ public async format(): Promise<void> {
32
+ await Log.animate('Formatting modified files', async () => {
33
+ const usingPrettier = File.exists('prettier.config.js');
34
+ const usingESLint = File.exists('.eslintrc.js');
35
+
36
+ await Promise.all(
37
+ arrayFrom(this.modifiedFiles).map(async (file) => {
38
+ usingPrettier && (await Shell.run(`npx prettier ${file} --write`));
39
+ usingESLint && (await Shell.run(`npx eslint ${file} --fix`));
40
+ }),
41
+ );
42
+ });
43
+ }
44
+
45
+ public async save(file: SourceFile): Promise<void> {
46
+ await file.save();
47
+
48
+ this.modifiedFiles.add(file.getFilePath());
49
+ }
50
+
51
+ }
package/src/lib/File.ts CHANGED
@@ -12,6 +12,12 @@ export class FileService {
12
12
  return existsSync(path);
13
13
  }
14
14
 
15
+ public isSymlink(path: string): boolean {
16
+ const stats = lstatSync(path);
17
+
18
+ return stats.isSymbolicLink();
19
+ }
20
+
15
21
  public read(path: string): string | null {
16
22
  if (!this.isFile(path)) {
17
23
  return null;
@@ -19,7 +19,8 @@ export class LogServiceMock extends LogService {
19
19
  this.logs.push(message);
20
20
  }
21
21
 
22
- public fail(message: string): void {
22
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
23
+ public fail<T = any>(message: string): T {
23
24
  throw new Error(`Fail: ${message}`);
24
25
  }
25
26
 
package/src/lib/Log.ts CHANGED
@@ -9,8 +9,9 @@ export class LogService {
9
9
  protected renderError = hex('#ff0000');
10
10
 
11
11
  public async animate<T>(message: string, operation: () => Promise<T>): Promise<T> {
12
- const updateStdout = (end: string = '') => {
13
- const progress = this.renderInfo(this.renderMarkdown(message) + '.'.repeat(frame % 4)) + end;
12
+ const updateStdout = (end: string = '', done: boolean = false) => {
13
+ const progress =
14
+ this.renderInfo(this.renderMarkdown(message) + (done ? '...' : '.'.repeat(frame % 4))) + end;
14
15
 
15
16
  this.stdout(progress);
16
17
  };
@@ -23,7 +24,7 @@ export class LogService {
23
24
  const result = await operation();
24
25
 
25
26
  clearInterval(interval);
26
- updateStdout('\n');
27
+ updateStdout('\n', true);
27
28
 
28
29
  return result;
29
30
  }
@@ -36,7 +37,8 @@ export class LogService {
36
37
  this.log(this.renderMarkdown(message), this.renderError);
37
38
  }
38
39
 
39
- public fail(message: string): void {
40
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
+ public fail<T = any>(message: string): T {
40
42
  this.error(message);
41
43
 
42
44
  process.exit(1);
@@ -0,0 +1,15 @@
1
+ import App from '@/lib/App';
2
+ import File from '@/lib/File';
3
+
4
+ export function app(): App {
5
+ // TODO parse app name
6
+ return new App('');
7
+ }
8
+
9
+ export function isLocalApp(): boolean {
10
+ return File.contains('package.json', 'file');
11
+ }
12
+
13
+ export function isLinkedLocalApp(): boolean {
14
+ return File.isSymlink('node_modules/@aerogel/core');
15
+ }
@@ -0,0 +1,44 @@
1
+ import { arrayFrom } from '@noeldemartin/utils';
2
+ import type { Node, SyntaxKind } from 'ts-morph';
3
+
4
+ export function editFiles(): boolean {
5
+ // TODO mock editor instead of relying on this for unit tests
6
+ return true;
7
+ }
8
+
9
+ export function findDescendant<T extends Node>(
10
+ node: Node | undefined,
11
+ options: {
12
+ guard?: (node: Node | undefined) => node is T;
13
+ validate?: (node: T) => boolean;
14
+ skip?: SyntaxKind | SyntaxKind[];
15
+ } = {},
16
+ ): T | undefined {
17
+ if (!node) {
18
+ return;
19
+ }
20
+
21
+ const guard = options.guard ?? (() => true);
22
+ const validate = options.validate ?? (() => true);
23
+ const skipKinds = arrayFrom(options.skip ?? []);
24
+
25
+ return node.forEachDescendant((descendant, traversal) => {
26
+ if (guard(descendant) && validate(descendant)) {
27
+ return descendant;
28
+ }
29
+
30
+ const descendantKind = descendant.getKind();
31
+
32
+ if (skipKinds.includes(descendantKind)) {
33
+ traversal.skip();
34
+ }
35
+ });
36
+ }
37
+
38
+ export function when<T extends Node>(node: Node | undefined, assertion: (node: Node) => node is T): T | undefined {
39
+ if (!node || !assertion(node)) {
40
+ return;
41
+ }
42
+
43
+ return node as T;
44
+ }
@@ -1,8 +1,8 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
 
3
- import { formatCodeBlock } from './utils';
3
+ import { formatCodeBlock } from './format';
4
4
 
5
- describe('Utils', () => {
5
+ describe('Format utils', () => {
6
6
 
7
7
  it('Formats code blocks', () => {
8
8
  // Arrange
@@ -1,13 +1,7 @@
1
- import { resolve } from 'path';
2
-
3
1
  export interface FormatCodeBlockOptions {
4
2
  indent?: number;
5
3
  }
6
4
 
7
- export function basePath(path: string): string {
8
- return resolve(__dirname, '../', path);
9
- }
10
-
11
5
  export function formatCodeBlock(code: string, options: FormatCodeBlockOptions = {}): string {
12
6
  const lines = code.split('\n');
13
7
  const indent = options.indent ?? 0;
@@ -0,0 +1,30 @@
1
+ import { resolve } from 'path';
2
+ import { stringMatch } from '@noeldemartin/utils';
3
+
4
+ import File from '@/lib/File';
5
+ import Log from '@/lib/Log';
6
+
7
+ export function basePath(path: string = ''): string {
8
+ if (File.contains(resolve(__dirname, '../../../package.json'), '"name": "aerogel"')) {
9
+ return resolve(__dirname, '../', path);
10
+ }
11
+
12
+ const packageJson = File.read(resolve(__dirname, '../../../../package.json'));
13
+ const matches = stringMatch<2>(packageJson ?? '', /"@aerogel\/cli": "file:(.*)\/aerogel-cli-[\d.]*\.tgz"/);
14
+ const cliPath = matches?.[1] ?? Log.fail<string>('Could not determine base path');
15
+
16
+ return resolve(cliPath, path);
17
+ }
18
+
19
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
20
+ export function packNotFound(packageName: string): any {
21
+ return Log.fail(`Could not find ${packageName} pack file, did you run 'npm pack'?`);
22
+ }
23
+
24
+ export function packagePackPath(packageName: string): string | null {
25
+ return File.getFiles(packagePath(packageName)).find((file) => file.endsWith('.tgz')) ?? null;
26
+ }
27
+
28
+ export function packagePath(packageName: string): string {
29
+ return basePath(`../${packageName}`);
30
+ }