@adonisjs/assembler 8.0.0-next.21 → 8.0.0-next.23

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.
@@ -1,634 +1,288 @@
1
- // src/code_transformer/main.ts
2
- import { join } from "path";
3
- import { fileURLToPath as fileURLToPath2 } from "url";
4
- import { installPackage, detectPackageManager } from "@antfu/install-pkg";
5
- import {
6
- Node as Node2,
7
- Project,
8
- QuoteKind,
9
- SyntaxKind as SyntaxKind2
10
- } from "ts-morph";
11
-
12
- // src/code_transformer/rc_file_transformer.ts
13
- import { fileURLToPath } from "url";
14
- import {
15
- Node,
16
- SyntaxKind
17
- } from "ts-morph";
18
- var ALLOWED_ENVIRONMENTS = ["web", "console", "test", "repl"];
1
+ import { fileURLToPath } from "node:url";
2
+ import { detectPackageManager, installPackage } from "@antfu/install-pkg";
3
+ import { join } from "node:path";
4
+ import { Node, Project, QuoteKind, SyntaxKind } from "ts-morph";
5
+ const ALLOWED_ENVIRONMENTS = [
6
+ "web",
7
+ "console",
8
+ "test",
9
+ "repl"
10
+ ];
19
11
  var RcFileTransformer = class {
20
- /**
21
- * The current working directory URL
22
- */
23
- #cwd;
24
- /**
25
- * The TsMorph project instance
26
- */
27
- #project;
28
- /**
29
- * Settings to use when persisting files
30
- */
31
- #editorSettings = {
32
- indentSize: 2,
33
- convertTabsToSpaces: true,
34
- trimTrailingWhitespace: true,
35
- ensureNewLineAtEndOfFile: true,
36
- indentStyle: 2,
37
- // @ts-expect-error SemicolonPreference doesn't seem to be re-exported from ts-morph
38
- semicolons: "remove"
39
- };
40
- /**
41
- * Create a new RcFileTransformer instance
42
- *
43
- * @param cwd - The current working directory URL
44
- * @param project - The TsMorph project instance
45
- */
46
- constructor(cwd, project) {
47
- this.#cwd = cwd;
48
- this.#project = project;
49
- }
50
- /**
51
- * Get the `adonisrc.ts` source file
52
- *
53
- * @returns The adonisrc.ts source file
54
- * @throws Error if the file cannot be found
55
- */
56
- #getRcFileOrThrow() {
57
- const kernelUrl = fileURLToPath(new URL("./adonisrc.ts", this.#cwd));
58
- return this.#project.getSourceFileOrThrow(kernelUrl);
59
- }
60
- /**
61
- * Check if environments array has a subset of available environments
62
- *
63
- * @param environments - Optional array of environment names
64
- * @returns True if the provided environments are a subset of available ones
65
- */
66
- #isInSpecificEnvironment(environments) {
67
- if (!environments) {
68
- return false;
69
- }
70
- return !!ALLOWED_ENVIRONMENTS.find((env) => !environments.includes(env));
71
- }
72
- /**
73
- * Locate the `defineConfig` call inside the `adonisrc.ts` file
74
- *
75
- * @param file - The source file to search in
76
- * @returns The defineConfig call expression
77
- * @throws Error if defineConfig call cannot be found
78
- */
79
- #locateDefineConfigCallOrThrow(file) {
80
- const call = file.getDescendantsOfKind(SyntaxKind.CallExpression).find((statement) => statement.getExpression().getText() === "defineConfig");
81
- if (!call) {
82
- throw new Error("Could not locate the defineConfig call.");
83
- }
84
- return call;
85
- }
86
- /**
87
- * Return the ObjectLiteralExpression of the defineConfig call
88
- *
89
- * @param defineConfigCall - The defineConfig call expression
90
- * @returns The configuration object literal expression
91
- * @throws Error if the object literal cannot be found
92
- */
93
- #getDefineConfigObjectOrThrow(defineConfigCall) {
94
- const configObject = defineConfigCall.getArguments()[0].asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
95
- return configObject;
96
- }
97
- /**
98
- * Check if the defineConfig() call has the property assignment
99
- * inside it or not. If not, it will create one and return it.
100
- *
101
- * @param propertyName - The name of the property to find or create
102
- * @param initializer - The initial value if the property needs to be created
103
- * @returns The property assignment node
104
- */
105
- #getPropertyAssignmentInDefineConfigCall(propertyName, initializer) {
106
- const file = this.#getRcFileOrThrow();
107
- const defineConfigCall = this.#locateDefineConfigCallOrThrow(file);
108
- const configObject = this.#getDefineConfigObjectOrThrow(defineConfigCall);
109
- let property = configObject.getProperty(propertyName);
110
- if (!property) {
111
- configObject.addPropertyAssignment({ name: propertyName, initializer });
112
- property = configObject.getProperty(propertyName);
113
- }
114
- return property;
115
- }
116
- /**
117
- * Extract list of imported modules from an ArrayLiteralExpression
118
- *
119
- * It assumes that the array can have two types of elements:
120
- *
121
- * - Simple lazy imported modules: [() => import('path/to/file')]
122
- * - Or an object entry: [{ file: () => import('path/to/file'), environment: ['web', 'console'] }]
123
- * where the `file` property is a lazy imported module.
124
- */
125
- #extractModulesFromArray(array) {
126
- const modules = array.getElements().map((element) => {
127
- if (Node.isArrowFunction(element)) {
128
- const importExp = element.getFirstDescendantByKindOrThrow(SyntaxKind.CallExpression);
129
- const literal = importExp.getFirstDescendantByKindOrThrow(SyntaxKind.StringLiteral);
130
- return literal.getLiteralValue();
131
- }
132
- if (Node.isObjectLiteralExpression(element)) {
133
- const fileProp = element.getPropertyOrThrow("file");
134
- const arrowFn = fileProp.getFirstDescendantByKindOrThrow(SyntaxKind.ArrowFunction);
135
- const importExp = arrowFn.getFirstDescendantByKindOrThrow(SyntaxKind.CallExpression);
136
- const literal = importExp.getFirstDescendantByKindOrThrow(SyntaxKind.StringLiteral);
137
- return literal.getLiteralValue();
138
- }
139
- });
140
- return modules.filter(Boolean);
141
- }
142
- /**
143
- * Extract a specific property from an ArrayLiteralExpression
144
- * that contains object entries.
145
- *
146
- * This function is mainly used for extractring the `pattern` property
147
- * when adding a new meta files entry, or the `name` property when
148
- * adding a new test suite.
149
- */
150
- #extractPropertyFromArray(array, propertyName) {
151
- const property = array.getElements().map((el) => {
152
- if (!Node.isObjectLiteralExpression(el)) return;
153
- const nameProp = el.getPropertyOrThrow(propertyName);
154
- if (!Node.isPropertyAssignment(nameProp)) return;
155
- const name = nameProp.getInitializerIfKindOrThrow(SyntaxKind.StringLiteral);
156
- return name.getLiteralValue();
157
- });
158
- return property.filter(Boolean);
159
- }
160
- /**
161
- * Build a new module entry for the preloads and providers array
162
- * based upon the environments specified
163
- */
164
- #buildNewModuleEntry(modulePath, environments) {
165
- if (!this.#isInSpecificEnvironment(environments)) {
166
- return `() => import('${modulePath}')`;
167
- }
168
- return `{
12
+ #cwd;
13
+ #project;
14
+ #editorSettings = {
15
+ indentSize: 2,
16
+ convertTabsToSpaces: true,
17
+ trimTrailingWhitespace: true,
18
+ ensureNewLineAtEndOfFile: true,
19
+ indentStyle: 2,
20
+ semicolons: "remove"
21
+ };
22
+ constructor(cwd, project) {
23
+ this.#cwd = cwd;
24
+ this.#project = project;
25
+ }
26
+ #getRcFileOrThrow() {
27
+ const kernelUrl = fileURLToPath(new URL("./adonisrc.ts", this.#cwd));
28
+ return this.#project.getSourceFileOrThrow(kernelUrl);
29
+ }
30
+ #isInSpecificEnvironment(environments) {
31
+ if (!environments) return false;
32
+ return !!ALLOWED_ENVIRONMENTS.find((env) => !environments.includes(env));
33
+ }
34
+ #locateDefineConfigCallOrThrow(file) {
35
+ const call = file.getDescendantsOfKind(SyntaxKind.CallExpression).find((statement) => statement.getExpression().getText() === "defineConfig");
36
+ if (!call) throw new Error("Could not locate the defineConfig call.");
37
+ return call;
38
+ }
39
+ #getDefineConfigObjectOrThrow(defineConfigCall) {
40
+ return defineConfigCall.getArguments()[0].asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
41
+ }
42
+ #getPropertyAssignmentInDefineConfigCall(propertyName, initializer) {
43
+ const file = this.#getRcFileOrThrow();
44
+ const defineConfigCall = this.#locateDefineConfigCallOrThrow(file);
45
+ const configObject = this.#getDefineConfigObjectOrThrow(defineConfigCall);
46
+ let property = configObject.getProperty(propertyName);
47
+ if (!property) {
48
+ configObject.addPropertyAssignment({
49
+ name: propertyName,
50
+ initializer
51
+ });
52
+ property = configObject.getProperty(propertyName);
53
+ }
54
+ return property;
55
+ }
56
+ #extractModulesFromArray(array) {
57
+ return array.getElements().map((element) => {
58
+ if (Node.isArrowFunction(element)) return element.getFirstDescendantByKindOrThrow(SyntaxKind.CallExpression).getFirstDescendantByKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();
59
+ if (Node.isObjectLiteralExpression(element)) return element.getPropertyOrThrow("file").getFirstDescendantByKindOrThrow(SyntaxKind.ArrowFunction).getFirstDescendantByKindOrThrow(SyntaxKind.CallExpression).getFirstDescendantByKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();
60
+ }).filter(Boolean);
61
+ }
62
+ #extractPropertyFromArray(array, propertyName) {
63
+ return array.getElements().map((el) => {
64
+ if (!Node.isObjectLiteralExpression(el)) return;
65
+ const nameProp = el.getPropertyOrThrow(propertyName);
66
+ if (!Node.isPropertyAssignment(nameProp)) return;
67
+ return nameProp.getInitializerIfKindOrThrow(SyntaxKind.StringLiteral).getLiteralValue();
68
+ }).filter(Boolean);
69
+ }
70
+ #buildNewModuleEntry(modulePath, environments) {
71
+ if (!this.#isInSpecificEnvironment(environments)) return `() => import('${modulePath}')`;
72
+ return `{
169
73
  file: () => import('${modulePath}'),
170
74
  environment: [${environments?.map((env) => `'${env}'`).join(", ")}],
171
75
  }`;
172
- }
173
- /**
174
- * Add a new command to the rcFile
175
- *
176
- * @param commandPath - The path to the command file
177
- * @returns This RcFileTransformer instance for method chaining
178
- */
179
- addCommand(commandPath) {
180
- const commandsProperty = this.#getPropertyAssignmentInDefineConfigCall("commands", "[]");
181
- const commandsArray = commandsProperty.getInitializerIfKindOrThrow(
182
- SyntaxKind.ArrayLiteralExpression
183
- );
184
- const commandString = `() => import('${commandPath}')`;
185
- if (commandsArray.getElements().some((el) => el.getText() === commandString)) {
186
- return this;
187
- }
188
- commandsArray.addElement(commandString);
189
- return this;
190
- }
191
- /**
192
- * Add a new preloaded file to the rcFile
193
- *
194
- * @param modulePath - The path to the preload file
195
- * @param environments - Optional array of environments where this preload should run
196
- * @returns This RcFileTransformer instance for method chaining
197
- */
198
- addPreloadFile(modulePath, environments) {
199
- const preloadsProperty = this.#getPropertyAssignmentInDefineConfigCall("preloads", "[]");
200
- const preloadsArray = preloadsProperty.getInitializerIfKindOrThrow(
201
- SyntaxKind.ArrayLiteralExpression
202
- );
203
- const existingPreloadedFiles = this.#extractModulesFromArray(preloadsArray);
204
- const isDuplicate = existingPreloadedFiles.includes(modulePath);
205
- if (isDuplicate) {
206
- return this;
207
- }
208
- preloadsArray.addElement(this.#buildNewModuleEntry(modulePath, environments));
209
- return this;
210
- }
211
- /**
212
- * Add a new provider to the rcFile
213
- *
214
- * @param providerPath - The path to the provider file
215
- * @param environments - Optional array of environments where this provider should run
216
- * @returns This RcFileTransformer instance for method chaining
217
- */
218
- addProvider(providerPath, environments) {
219
- const property = this.#getPropertyAssignmentInDefineConfigCall("providers", "[]");
220
- const providersArray = property.getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
221
- const existingProviderPaths = this.#extractModulesFromArray(providersArray);
222
- const isDuplicate = existingProviderPaths.includes(providerPath);
223
- if (isDuplicate) {
224
- return this;
225
- }
226
- providersArray.addElement(this.#buildNewModuleEntry(providerPath, environments));
227
- return this;
228
- }
229
- /**
230
- * Add a new meta file to the rcFile
231
- *
232
- * @param globPattern - The glob pattern for the meta file
233
- * @param reloadServer - Whether the server should reload when this file changes
234
- * @returns This RcFileTransformer instance for method chaining
235
- */
236
- addMetaFile(globPattern, reloadServer = false) {
237
- const property = this.#getPropertyAssignmentInDefineConfigCall("metaFiles", "[]");
238
- const metaFilesArray = property.getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
239
- const alreadyDefinedPatterns = this.#extractPropertyFromArray(metaFilesArray, "pattern");
240
- if (alreadyDefinedPatterns.includes(globPattern)) {
241
- return this;
242
- }
243
- metaFilesArray.addElement(
244
- `{
76
+ }
77
+ addCommand(commandPath) {
78
+ const commandsArray = this.#getPropertyAssignmentInDefineConfigCall("commands", "[]").getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
79
+ const commandString = `() => import('${commandPath}')`;
80
+ if (commandsArray.getElements().some((el) => el.getText() === commandString)) return this;
81
+ commandsArray.addElement(commandString);
82
+ return this;
83
+ }
84
+ addPreloadFile(modulePath, environments) {
85
+ const preloadsArray = this.#getPropertyAssignmentInDefineConfigCall("preloads", "[]").getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
86
+ if (this.#extractModulesFromArray(preloadsArray).includes(modulePath)) return this;
87
+ preloadsArray.addElement(this.#buildNewModuleEntry(modulePath, environments));
88
+ return this;
89
+ }
90
+ addProvider(providerPath, environments) {
91
+ const providersArray = this.#getPropertyAssignmentInDefineConfigCall("providers", "[]").getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
92
+ if (this.#extractModulesFromArray(providersArray).includes(providerPath)) return this;
93
+ providersArray.addElement(this.#buildNewModuleEntry(providerPath, environments));
94
+ return this;
95
+ }
96
+ addMetaFile(globPattern, reloadServer = false) {
97
+ const metaFilesArray = this.#getPropertyAssignmentInDefineConfigCall("metaFiles", "[]").getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
98
+ if (this.#extractPropertyFromArray(metaFilesArray, "pattern").includes(globPattern)) return this;
99
+ metaFilesArray.addElement(`{
245
100
  pattern: '${globPattern}',
246
101
  reloadServer: ${reloadServer},
247
- }`
248
- );
249
- return this;
250
- }
251
- /**
252
- * Set directory name and path in the directories configuration
253
- *
254
- * @param key - The directory key (e.g., 'controllers', 'models')
255
- * @param value - The directory path
256
- * @returns This RcFileTransformer instance for method chaining
257
- */
258
- setDirectory(key, value) {
259
- const property = this.#getPropertyAssignmentInDefineConfigCall("directories", "{}");
260
- const directories = property.getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);
261
- directories.addPropertyAssignment({ name: key, initializer: `'${value}'` });
262
- return this;
263
- }
264
- /**
265
- * Set command alias in the command aliases configuration
266
- *
267
- * @param alias - The alias name
268
- * @param command - The full command name
269
- * @returns This RcFileTransformer instance for method chaining
270
- */
271
- setCommandAlias(alias, command) {
272
- const aliasProperty = this.#getPropertyAssignmentInDefineConfigCall("commandsAliases", "{}");
273
- const aliases = aliasProperty.getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);
274
- aliases.addPropertyAssignment({ name: alias, initializer: `'${command}'` });
275
- return this;
276
- }
277
- /**
278
- * Add a new test suite to the rcFile
279
- *
280
- * @param suiteName - The name of the test suite
281
- * @param files - File patterns for the test suite (string or array)
282
- * @param timeout - Optional timeout in milliseconds (defaults to 2000)
283
- * @returns This RcFileTransformer instance for method chaining
284
- */
285
- addSuite(suiteName, files, timeout) {
286
- const testProperty = this.#getPropertyAssignmentInDefineConfigCall(
287
- "tests",
288
- `{ suites: [], forceExit: true, timeout: 2000 }`
289
- );
290
- const property = testProperty.getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression).getPropertyOrThrow("suites");
291
- const suitesArray = property.getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
292
- const existingSuitesNames = this.#extractPropertyFromArray(suitesArray, "name");
293
- if (existingSuitesNames.includes(suiteName)) {
294
- return this;
295
- }
296
- const filesArray = Array.isArray(files) ? files : [files];
297
- suitesArray.addElement(
298
- `{
102
+ }`);
103
+ return this;
104
+ }
105
+ setDirectory(key, value) {
106
+ this.#getPropertyAssignmentInDefineConfigCall("directories", "{}").getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression).addPropertyAssignment({
107
+ name: key,
108
+ initializer: `'${value}'`
109
+ });
110
+ return this;
111
+ }
112
+ setCommandAlias(alias, command) {
113
+ this.#getPropertyAssignmentInDefineConfigCall("commandsAliases", "{}").getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression).addPropertyAssignment({
114
+ name: alias,
115
+ initializer: `'${command}'`
116
+ });
117
+ return this;
118
+ }
119
+ addSuite(suiteName, files, timeout) {
120
+ const suitesArray = this.#getPropertyAssignmentInDefineConfigCall("tests", `{ suites: [], forceExit: true, timeout: 2000 }`).getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression).getPropertyOrThrow("suites").getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
121
+ if (this.#extractPropertyFromArray(suitesArray, "name").includes(suiteName)) return this;
122
+ const filesArray = Array.isArray(files) ? files : [files];
123
+ suitesArray.addElement(`{
299
124
  name: '${suiteName}',
300
125
  files: [${filesArray.map((file) => `'${file}'`).join(", ")}],
301
126
  timeout: ${timeout ?? 2e3},
302
- }`
303
- );
304
- return this;
305
- }
306
- /**
307
- * Add a new assembler hook
308
- *
309
- * @param type - The type of hook to add
310
- * @param path - The path to the hook file
311
- * @returns This RcFileTransformer instance for method chaining
312
- */
313
- addAssemblerHook(type, path) {
314
- const hooksProperty = this.#getPropertyAssignmentInDefineConfigCall("hooks", "{}");
315
- const hooks = hooksProperty.getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);
316
- let hookArray = hooks.getProperty(type);
317
- if (!hookArray) {
318
- hooks.addPropertyAssignment({ name: type, initializer: "[]" });
319
- hookArray = hooks.getProperty(type);
320
- }
321
- const hooksArray = hookArray.getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
322
- const existingHooks = this.#extractModulesFromArray(hooksArray);
323
- if (existingHooks.includes(path)) {
324
- return this;
325
- }
326
- hooksArray.addElement(`() => import('${path}')`);
327
- return this;
328
- }
329
- /**
330
- * Save the adonisrc.ts file with all applied transformations
331
- *
332
- * Formats the file according to editor settings and saves it to disk.
333
- *
334
- * @returns Promise that resolves when the file is saved
335
- */
336
- save() {
337
- const file = this.#getRcFileOrThrow();
338
- file.formatText(this.#editorSettings);
339
- return file.save();
340
- }
127
+ }`);
128
+ return this;
129
+ }
130
+ addAssemblerHook(type, path) {
131
+ const hooks = this.#getPropertyAssignmentInDefineConfigCall("hooks", "{}").getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);
132
+ let hookArray = hooks.getProperty(type);
133
+ if (!hookArray) {
134
+ hooks.addPropertyAssignment({
135
+ name: type,
136
+ initializer: "[]"
137
+ });
138
+ hookArray = hooks.getProperty(type);
139
+ }
140
+ const hooksArray = hookArray.getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
141
+ if (this.#extractModulesFromArray(hooksArray).includes(path)) return this;
142
+ hooksArray.addElement(`() => import('${path}')`);
143
+ return this;
144
+ }
145
+ save() {
146
+ const file = this.#getRcFileOrThrow();
147
+ file.formatText(this.#editorSettings);
148
+ return file.save();
149
+ }
341
150
  };
342
-
343
- // src/code_transformer/main.ts
344
151
  var CodeTransformer = class {
345
- /**
346
- * Utility function for installing packages
347
- */
348
- installPackage = installPackage;
349
- /**
350
- * Utility function for detecting the package manager
351
- */
352
- detectPackageManager = detectPackageManager;
353
- /**
354
- * Directory of the adonisjs project
355
- */
356
- #cwd;
357
- /**
358
- * String path version of the current working directory
359
- */
360
- #cwdPath;
361
- /**
362
- * The TsMorph project instance for AST manipulation
363
- */
364
- project;
365
- /**
366
- * Settings to use when persisting files
367
- */
368
- #editorSettings = {
369
- indentSize: 2,
370
- convertTabsToSpaces: true,
371
- trimTrailingWhitespace: true,
372
- ensureNewLineAtEndOfFile: true,
373
- indentStyle: 2,
374
- // @ts-expect-error SemicolonPreference doesn't seem to be re-exported from ts-morph
375
- semicolons: "remove"
376
- };
377
- /**
378
- * Create a new CodeTransformer instance
379
- *
380
- * @param cwd - The current working directory URL
381
- */
382
- constructor(cwd) {
383
- this.#cwd = cwd;
384
- this.#cwdPath = fileURLToPath2(this.#cwd);
385
- this.project = new Project({
386
- tsConfigFilePath: join(fileURLToPath2(this.#cwd), "tsconfig.json"),
387
- manipulationSettings: { quoteKind: QuoteKind.Single }
388
- });
389
- }
390
- /**
391
- * Add a new middleware to the middleware array of the given file
392
- *
393
- * This method locates middleware stack calls (like server.use or router.use)
394
- * and adds the middleware entry to the appropriate position in the array.
395
- *
396
- * @param file - The source file to modify
397
- * @param target - The target method call (e.g., 'server.use', 'router.use')
398
- * @param middlewareEntry - The middleware entry to add
399
- */
400
- #addToMiddlewareArray(file, target, middlewareEntry) {
401
- const callExpressions = file.getDescendantsOfKind(SyntaxKind2.CallExpression).filter((statement) => statement.getExpression().getText() === target);
402
- if (!callExpressions.length) {
403
- throw new Error(`Cannot find ${target} statement in the file.`);
404
- }
405
- const arrayLiteralExpression = callExpressions[0].getArguments()[0];
406
- if (!arrayLiteralExpression || !Node2.isArrayLiteralExpression(arrayLiteralExpression)) {
407
- throw new Error(`Cannot find middleware array in ${target} statement.`);
408
- }
409
- const middleware = `() => import('${middlewareEntry.path}')`;
410
- const existingMiddlewareIndex = arrayLiteralExpression.getElements().findIndex((element) => element.getText() === middleware);
411
- if (existingMiddlewareIndex === -1) {
412
- if (middlewareEntry.position === "before") {
413
- arrayLiteralExpression.insertElement(0, middleware);
414
- } else {
415
- arrayLiteralExpression.addElement(middleware);
416
- }
417
- }
418
- }
419
- /**
420
- * Add a new middleware to the named middleware of the given file
421
- *
422
- * This method adds middleware entries to the named middleware object,
423
- * typically used for route-specific middleware registration.
424
- *
425
- * @param file - The source file to modify
426
- * @param middlewareEntry - The middleware entry to add (must have a name)
427
- */
428
- #addToNamedMiddleware(file, middlewareEntry) {
429
- if (!middlewareEntry.name) {
430
- throw new Error("Named middleware requires a name.");
431
- }
432
- const callArguments = file.getVariableDeclarationOrThrow("middleware").getInitializerIfKindOrThrow(SyntaxKind2.CallExpression).getArguments();
433
- if (callArguments.length === 0) {
434
- throw new Error("Named middleware call has no arguments.");
435
- }
436
- const namedMiddlewareObject = callArguments[0];
437
- if (!Node2.isObjectLiteralExpression(namedMiddlewareObject)) {
438
- throw new Error("The argument of the named middleware call is not an object literal.");
439
- }
440
- const existingProperty = namedMiddlewareObject.getProperty(middlewareEntry.name);
441
- if (!existingProperty) {
442
- const middleware = `${middlewareEntry.name}: () => import('${middlewareEntry.path}')`;
443
- namedMiddlewareObject.insertProperty(0, middleware);
444
- }
445
- }
446
- /**
447
- * Add a policy to the list of pre-registered policies
448
- *
449
- * This method adds bouncer policy entries to the policies object,
450
- * allowing them to be used in route authorization.
451
- *
452
- * @param file - The source file to modify
453
- * @param policyEntry - The policy entry to add
454
- */
455
- #addToPoliciesList(file, policyEntry) {
456
- const policiesObject = file.getVariableDeclarationOrThrow("policies").getInitializerIfKindOrThrow(SyntaxKind2.ObjectLiteralExpression);
457
- const existingProperty = policiesObject.getProperty(policyEntry.name);
458
- if (!existingProperty) {
459
- const policy = `${policyEntry.name}: () => import('${policyEntry.path}')`;
460
- policiesObject.insertProperty(0, policy);
461
- }
462
- }
463
- /**
464
- * Add the given import declarations to the source file
465
- * and merge named imports with the existing import
466
- */
467
- #addImportDeclarations(file, importDeclarations) {
468
- const existingImports = file.getImportDeclarations();
469
- importDeclarations.forEach((importDeclaration) => {
470
- const existingImport = existingImports.find(
471
- (mod) => mod.getModuleSpecifierValue() === importDeclaration.module
472
- );
473
- if (existingImport && importDeclaration.isNamed) {
474
- if (!existingImport.getNamedImports().find((namedImport) => namedImport.getName() === importDeclaration.identifier)) {
475
- existingImport.addNamedImport(importDeclaration.identifier);
476
- }
477
- return;
478
- }
479
- if (existingImport) {
480
- return;
481
- }
482
- file.addImportDeclaration({
483
- ...importDeclaration.isNamed ? { namedImports: [importDeclaration.identifier] } : { defaultImport: importDeclaration.identifier },
484
- moduleSpecifier: importDeclaration.module
485
- });
486
- });
487
- }
488
- /**
489
- * Write a leading comment
490
- */
491
- #addLeadingComment(writer, comment) {
492
- if (!comment) {
493
- return writer.blankLine();
494
- }
495
- return writer.blankLine().writeLine("/*").writeLine(`|----------------------------------------------------------`).writeLine(`| ${comment}`).writeLine(`|----------------------------------------------------------`).writeLine(`*/`);
496
- }
497
- /**
498
- * Add new env variable validation in the `env.ts` file
499
- *
500
- * @param definition - Environment validation definition containing variables and comment
501
- */
502
- async defineEnvValidations(definition) {
503
- const kernelUrl = join(this.#cwdPath, "./start/env.ts");
504
- const file = this.project.getSourceFileOrThrow(kernelUrl);
505
- const callExpressions = file.getDescendantsOfKind(SyntaxKind2.CallExpression).filter((statement) => statement.getExpression().getText() === "Env.create");
506
- if (!callExpressions.length) {
507
- throw new Error(`Cannot find Env.create statement in the file.`);
508
- }
509
- const objectLiteralExpression = callExpressions[0].getArguments()[1];
510
- if (!Node2.isObjectLiteralExpression(objectLiteralExpression)) {
511
- throw new Error(`The second argument of Env.create is not an object literal.`);
512
- }
513
- let shouldAddComment = true;
514
- for (const [variable, validation] of Object.entries(definition.variables)) {
515
- const existingProperty = objectLiteralExpression.getProperty(variable);
516
- if (existingProperty) {
517
- shouldAddComment = false;
518
- }
519
- if (!existingProperty) {
520
- objectLiteralExpression.addPropertyAssignment({
521
- name: variable,
522
- initializer: validation,
523
- leadingTrivia: (writer) => {
524
- if (!shouldAddComment) {
525
- return;
526
- }
527
- shouldAddComment = false;
528
- return this.#addLeadingComment(writer, definition.leadingComment);
529
- }
530
- });
531
- }
532
- }
533
- file.formatText(this.#editorSettings);
534
- await file.save();
535
- }
536
- /**
537
- * Define new middlewares inside the `start/kernel.ts` file
538
- *
539
- * This function is highly based on some assumptions
540
- * and will not work if you significantly tweaked
541
- * your `start/kernel.ts` file.
542
- *
543
- * @param stack - The middleware stack to add to ('server', 'router', or 'named')
544
- * @param middleware - Array of middleware entries to add
545
- */
546
- async addMiddlewareToStack(stack, middleware) {
547
- const kernelUrl = join(this.#cwdPath, "./start/kernel.ts");
548
- const file = this.project.getSourceFileOrThrow(kernelUrl);
549
- for (const middlewareEntry of middleware) {
550
- if (stack === "named") {
551
- this.#addToNamedMiddleware(file, middlewareEntry);
552
- } else {
553
- this.#addToMiddlewareArray(file, `${stack}.use`, middlewareEntry);
554
- }
555
- }
556
- file.formatText(this.#editorSettings);
557
- await file.save();
558
- }
559
- /**
560
- * Update the `adonisrc.ts` file using the provided callback
561
- *
562
- * @param callback - Function that receives the RcFileTransformer for modifications
563
- */
564
- async updateRcFile(callback) {
565
- const rcFileTransformer = new RcFileTransformer(this.#cwd, this.project);
566
- callback(rcFileTransformer);
567
- await rcFileTransformer.save();
568
- }
569
- /**
570
- * Add a new Japa plugin in the `tests/bootstrap.ts` file
571
- *
572
- * @param pluginCall - The plugin function call to add
573
- * @param importDeclarations - Import declarations needed for the plugin
574
- */
575
- async addJapaPlugin(pluginCall, importDeclarations) {
576
- const testBootstrapUrl = join(this.#cwdPath, "./tests/bootstrap.ts");
577
- const file = this.project.getSourceFileOrThrow(testBootstrapUrl);
578
- this.#addImportDeclarations(file, importDeclarations);
579
- const pluginsArray = file.getVariableDeclaration("plugins")?.getInitializerIfKind(SyntaxKind2.ArrayLiteralExpression);
580
- if (pluginsArray) {
581
- if (!pluginsArray.getElements().find((element) => element.getText() === pluginCall)) {
582
- pluginsArray.addElement(pluginCall);
583
- }
584
- }
585
- file.formatText(this.#editorSettings);
586
- await file.save();
587
- }
588
- /**
589
- * Add a new Vite plugin to the `vite.config.ts` file
590
- *
591
- * @param pluginCall - The plugin function call to add
592
- * @param importDeclarations - Import declarations needed for the plugin
593
- */
594
- async addVitePlugin(pluginCall, importDeclarations) {
595
- const viteConfigTsUrl = join(this.#cwdPath, "./vite.config.ts");
596
- const file = this.project.getSourceFile(viteConfigTsUrl);
597
- if (!file) {
598
- throw new Error(
599
- "Cannot find vite.config.ts file. Make sure to rename vite.config.js to vite.config.ts"
600
- );
601
- }
602
- this.#addImportDeclarations(file, importDeclarations);
603
- const defaultExport = file.getDefaultExportSymbol();
604
- if (!defaultExport) {
605
- throw new Error("Cannot find the default export in vite.config.ts");
606
- }
607
- const declaration = defaultExport.getDeclarations()[0];
608
- const options = declaration.getChildrenOfKind(SyntaxKind2.ObjectLiteralExpression)[0] || declaration.getChildrenOfKind(SyntaxKind2.CallExpression)[0].getArguments()[0];
609
- const pluginsArray = options.getPropertyOrThrow("plugins").getFirstChildByKindOrThrow(SyntaxKind2.ArrayLiteralExpression);
610
- if (!pluginsArray.getElements().find((element) => element.getText() === pluginCall)) {
611
- pluginsArray.addElement(pluginCall);
612
- }
613
- file.formatText(this.#editorSettings);
614
- await file.save();
615
- }
616
- /**
617
- * Adds a policy to the list of `policies` object configured
618
- * inside the `app/policies/main.ts` file.
619
- *
620
- * @param policies - Array of bouncer policy entries to add
621
- */
622
- async addPolicies(policies) {
623
- const kernelUrl = join(this.#cwdPath, "./app/policies/main.ts");
624
- const file = this.project.getSourceFileOrThrow(kernelUrl);
625
- for (const policy of policies) {
626
- this.#addToPoliciesList(file, policy);
627
- }
628
- file.formatText(this.#editorSettings);
629
- await file.save();
630
- }
631
- };
632
- export {
633
- CodeTransformer
152
+ installPackage = installPackage;
153
+ detectPackageManager = detectPackageManager;
154
+ #cwd;
155
+ #cwdPath;
156
+ project;
157
+ #editorSettings = {
158
+ indentSize: 2,
159
+ convertTabsToSpaces: true,
160
+ trimTrailingWhitespace: true,
161
+ ensureNewLineAtEndOfFile: true,
162
+ indentStyle: 2,
163
+ semicolons: "remove"
164
+ };
165
+ constructor(cwd) {
166
+ this.#cwd = cwd;
167
+ this.#cwdPath = fileURLToPath(this.#cwd);
168
+ this.project = new Project({
169
+ tsConfigFilePath: join(fileURLToPath(this.#cwd), "tsconfig.json"),
170
+ manipulationSettings: { quoteKind: QuoteKind.Single }
171
+ });
172
+ }
173
+ #addToMiddlewareArray(file, target, middlewareEntry) {
174
+ const callExpressions = file.getDescendantsOfKind(SyntaxKind.CallExpression).filter((statement) => statement.getExpression().getText() === target);
175
+ if (!callExpressions.length) throw new Error(`Cannot find ${target} statement in the file.`);
176
+ const arrayLiteralExpression = callExpressions[0].getArguments()[0];
177
+ if (!arrayLiteralExpression || !Node.isArrayLiteralExpression(arrayLiteralExpression)) throw new Error(`Cannot find middleware array in ${target} statement.`);
178
+ const middleware = `() => import('${middlewareEntry.path}')`;
179
+ if (arrayLiteralExpression.getElements().findIndex((element) => element.getText() === middleware) === -1) if (middlewareEntry.position === "before") arrayLiteralExpression.insertElement(0, middleware);
180
+ else arrayLiteralExpression.addElement(middleware);
181
+ }
182
+ #addToNamedMiddleware(file, middlewareEntry) {
183
+ if (!middlewareEntry.name) throw new Error("Named middleware requires a name.");
184
+ const callArguments = file.getVariableDeclarationOrThrow("middleware").getInitializerIfKindOrThrow(SyntaxKind.CallExpression).getArguments();
185
+ if (callArguments.length === 0) throw new Error("Named middleware call has no arguments.");
186
+ const namedMiddlewareObject = callArguments[0];
187
+ if (!Node.isObjectLiteralExpression(namedMiddlewareObject)) throw new Error("The argument of the named middleware call is not an object literal.");
188
+ if (!namedMiddlewareObject.getProperty(middlewareEntry.name)) {
189
+ const middleware = `${middlewareEntry.name}: () => import('${middlewareEntry.path}')`;
190
+ namedMiddlewareObject.insertProperty(0, middleware);
191
+ }
192
+ }
193
+ #addToPoliciesList(file, policyEntry) {
194
+ const policiesObject = file.getVariableDeclarationOrThrow("policies").getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);
195
+ if (!policiesObject.getProperty(policyEntry.name)) {
196
+ const policy = `${policyEntry.name}: () => import('${policyEntry.path}')`;
197
+ policiesObject.insertProperty(0, policy);
198
+ }
199
+ }
200
+ #addImportDeclarations(file, importDeclarations) {
201
+ const existingImports = file.getImportDeclarations();
202
+ importDeclarations.forEach((importDeclaration) => {
203
+ const existingImport = existingImports.find((mod) => mod.getModuleSpecifierValue() === importDeclaration.module);
204
+ if (existingImport && importDeclaration.isNamed) {
205
+ if (!existingImport.getNamedImports().find((namedImport) => namedImport.getName() === importDeclaration.identifier)) existingImport.addNamedImport(importDeclaration.identifier);
206
+ return;
207
+ }
208
+ if (existingImport) return;
209
+ file.addImportDeclaration({
210
+ ...importDeclaration.isNamed ? { namedImports: [importDeclaration.identifier] } : { defaultImport: importDeclaration.identifier },
211
+ moduleSpecifier: importDeclaration.module
212
+ });
213
+ });
214
+ }
215
+ #addLeadingComment(writer, comment) {
216
+ if (!comment) return writer.blankLine();
217
+ return writer.blankLine().writeLine("/*").writeLine(`|----------------------------------------------------------`).writeLine(`| ${comment}`).writeLine(`|----------------------------------------------------------`).writeLine(`*/`);
218
+ }
219
+ async defineEnvValidations(definition) {
220
+ const kernelUrl = join(this.#cwdPath, "./start/env.ts");
221
+ const file = this.project.getSourceFileOrThrow(kernelUrl);
222
+ const callExpressions = file.getDescendantsOfKind(SyntaxKind.CallExpression).filter((statement) => statement.getExpression().getText() === "Env.create");
223
+ if (!callExpressions.length) throw new Error(`Cannot find Env.create statement in the file.`);
224
+ const objectLiteralExpression = callExpressions[0].getArguments()[1];
225
+ if (!Node.isObjectLiteralExpression(objectLiteralExpression)) throw new Error(`The second argument of Env.create is not an object literal.`);
226
+ let shouldAddComment = true;
227
+ for (const [variable, validation] of Object.entries(definition.variables)) {
228
+ const existingProperty = objectLiteralExpression.getProperty(variable);
229
+ if (existingProperty) shouldAddComment = false;
230
+ if (!existingProperty) objectLiteralExpression.addPropertyAssignment({
231
+ name: variable,
232
+ initializer: validation,
233
+ leadingTrivia: (writer) => {
234
+ if (!shouldAddComment) return;
235
+ shouldAddComment = false;
236
+ return this.#addLeadingComment(writer, definition.leadingComment);
237
+ }
238
+ });
239
+ }
240
+ file.formatText(this.#editorSettings);
241
+ await file.save();
242
+ }
243
+ async addMiddlewareToStack(stack, middleware) {
244
+ const kernelUrl = join(this.#cwdPath, "./start/kernel.ts");
245
+ const file = this.project.getSourceFileOrThrow(kernelUrl);
246
+ for (const middlewareEntry of middleware) if (stack === "named") this.#addToNamedMiddleware(file, middlewareEntry);
247
+ else this.#addToMiddlewareArray(file, `${stack}.use`, middlewareEntry);
248
+ file.formatText(this.#editorSettings);
249
+ await file.save();
250
+ }
251
+ async updateRcFile(callback) {
252
+ const rcFileTransformer = new RcFileTransformer(this.#cwd, this.project);
253
+ callback(rcFileTransformer);
254
+ await rcFileTransformer.save();
255
+ }
256
+ async addJapaPlugin(pluginCall, importDeclarations) {
257
+ const testBootstrapUrl = join(this.#cwdPath, "./tests/bootstrap.ts");
258
+ const file = this.project.getSourceFileOrThrow(testBootstrapUrl);
259
+ this.#addImportDeclarations(file, importDeclarations);
260
+ const pluginsArray = file.getVariableDeclaration("plugins")?.getInitializerIfKind(SyntaxKind.ArrayLiteralExpression);
261
+ if (pluginsArray) {
262
+ if (!pluginsArray.getElements().find((element) => element.getText() === pluginCall)) pluginsArray.addElement(pluginCall);
263
+ }
264
+ file.formatText(this.#editorSettings);
265
+ await file.save();
266
+ }
267
+ async addVitePlugin(pluginCall, importDeclarations) {
268
+ const viteConfigTsUrl = join(this.#cwdPath, "./vite.config.ts");
269
+ const file = this.project.getSourceFile(viteConfigTsUrl);
270
+ if (!file) throw new Error("Cannot find vite.config.ts file. Make sure to rename vite.config.js to vite.config.ts");
271
+ this.#addImportDeclarations(file, importDeclarations);
272
+ const defaultExport = file.getDefaultExportSymbol();
273
+ if (!defaultExport) throw new Error("Cannot find the default export in vite.config.ts");
274
+ const declaration = defaultExport.getDeclarations()[0];
275
+ const pluginsArray = (declaration.getChildrenOfKind(SyntaxKind.ObjectLiteralExpression)[0] || declaration.getChildrenOfKind(SyntaxKind.CallExpression)[0].getArguments()[0]).getPropertyOrThrow("plugins").getFirstChildByKindOrThrow(SyntaxKind.ArrayLiteralExpression);
276
+ if (!pluginsArray.getElements().find((element) => element.getText() === pluginCall)) pluginsArray.addElement(pluginCall);
277
+ file.formatText(this.#editorSettings);
278
+ await file.save();
279
+ }
280
+ async addPolicies(policies) {
281
+ const kernelUrl = join(this.#cwdPath, "./app/policies/main.ts");
282
+ const file = this.project.getSourceFileOrThrow(kernelUrl);
283
+ for (const policy of policies) this.#addToPoliciesList(file, policy);
284
+ file.formatText(this.#editorSettings);
285
+ await file.save();
286
+ }
634
287
  };
288
+ export { CodeTransformer };