@adonisjs/assembler 8.0.0 → 8.0.1

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.
@@ -0,0 +1,562 @@
1
+ import { i as isRelative, m as debug_default, t as VirtualFileSystem } from "./virtual_file_system-dzfXNwEp.js";
2
+ import { findImport, inspectClass, inspectClassMethods, inspectMethodArguments, nodeToPlainText, searchValidatorDirectUsage } from "./src/helpers.js";
3
+ import { cliui } from "@poppinss/cliui";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import string from "@poppinss/utils/string";
6
+ import { join, relative } from "node:path";
7
+ import StringBuilder from "@poppinss/utils/string_builder";
8
+ import { parseImports } from "parse-imports";
9
+ import { resolve } from "import-meta-resolve";
10
+ //#region src/paths_resolver.ts
11
+ /**
12
+ * Encapsulates the API to resolve import specifiers with the ability
13
+ * to define custom resolver functions.
14
+ *
15
+ * The PathsResolver provides a caching mechanism to avoid resolving the same
16
+ * specifier multiple times and supports custom resolvers for handling
17
+ * special import patterns like path aliases.
18
+ *
19
+ * @example
20
+ * const resolver = new PathsResolver()
21
+ * resolver.use((specifier) => '/custom/path/' + specifier)
22
+ * const resolved = resolver.resolve('#app/models/user')
23
+ */
24
+ var PathsResolver = class {
25
+ /**
26
+ * The root of the application from where we will resolve
27
+ * paths.
28
+ */
29
+ #appRoot;
30
+ /**
31
+ * Cache of resolved paths to avoid resolving the same specifier multiple times
32
+ */
33
+ #resolvedPaths = {};
34
+ /**
35
+ * The resolver function used to resolve import specifiers
36
+ */
37
+ #resolver = (specifier, parentPath) => resolve(specifier, parentPath);
38
+ constructor(appRoot) {
39
+ this.#appRoot = pathToFileURL(join(appRoot, "index.js")).href;
40
+ }
41
+ /**
42
+ * Define a custom resolver that resolves a path
43
+ *
44
+ * The custom resolver function will be used instead of the default
45
+ * import.meta.resolve() for resolving import specifiers.
46
+ *
47
+ * @param resolver - Function that takes a specifier and returns resolved path
48
+ */
49
+ use(resolver) {
50
+ this.#resolver = resolver;
51
+ }
52
+ /**
53
+ * Resolve import specifier to an absolute file path
54
+ *
55
+ * This method caches resolved paths to improve performance on repeated
56
+ * resolutions. Relative paths are not supported and will throw an error.
57
+ *
58
+ * @param specifier - The import specifier to resolve (must not be relative)
59
+ * @returns The resolved absolute file path
60
+ * @throws Error when attempting to resolve relative paths
61
+ *
62
+ * @example
63
+ * const path = resolver.resolve('#app/models/user')
64
+ * const path2 = resolver.resolve('@/utils/helper')
65
+ */
66
+ resolve(specifier, rewriteAliasImportExtension = false) {
67
+ if (isRelative(specifier)) throw new Error("Cannot resolve relative paths using PathsResolver");
68
+ const cacheKey = specifier;
69
+ const cached = this.#resolvedPaths[cacheKey];
70
+ if (cached) return cached;
71
+ /**
72
+ * Currently the PathsResolver relies on a non-standard way of resolving
73
+ * absolute paths or paths with subpath imports. Because of which, the
74
+ * on-disk file could be TypeScript, while the resolved filepath is
75
+ * JavaScript.
76
+ *
77
+ * To overcome this limitation, we rewrite the file extension to ".ts" when
78
+ * the import specifier starts with a "#".
79
+ */
80
+ let resolvedPath = fileURLToPath(this.#resolver(specifier, this.#appRoot));
81
+ if (rewriteAliasImportExtension && specifier.startsWith("#") && resolvedPath.endsWith(".js")) resolvedPath = resolvedPath.replace(/\.js$/, ".ts");
82
+ this.#resolvedPaths[cacheKey] = resolvedPath;
83
+ return this.#resolvedPaths[cacheKey];
84
+ }
85
+ };
86
+ //#endregion
87
+ //#region src/code_scanners/routes_scanner/validator_extractor.ts
88
+ /**
89
+ * Extracts the VineJS validator usage from within a controller method.
90
+ *
91
+ * This function analyzes controller method code to detect validator usage patterns
92
+ * and extracts the validator references along with their import information.
93
+ * The following syntaxes are supported:
94
+ *
95
+ * - `request.validateUsing(validatorReference)`
96
+ * - `vine.validate(validatorReference)`
97
+ * - `validatorReference.validate(request.all())`
98
+ *
99
+ * - `request.validateUsing(ControllerReference.validator)`
100
+ * - `vine.validate(ControllerReference.validator)`
101
+ * - `ControllerReference.validator.validate(request.all())`
102
+ *
103
+ * The app root is needed to create relative validator imports in case
104
+ * a relative import was used within the controller file.
105
+ *
106
+ * @param appRoot - The root directory of the application
107
+ * @param vfs - Virtual file system instance for code analysis
108
+ * @param controller - The controller to analyze for validator usage
109
+ * @returns Promise resolving to array of validator information or undefined
110
+ */
111
+ async function extractValidators(appRoot, vfs, controller) {
112
+ const root = await vfs.get(controller.path);
113
+ const fileContents = root.text();
114
+ const controllerClass = inspectClass(root);
115
+ if (!controllerClass) {
116
+ debug_default(`No class defined within the "%s"`, controller.import.specifier);
117
+ return;
118
+ }
119
+ /**
120
+ * Inspect class methods and find the scope down to the method
121
+ * we are currently inspecting
122
+ */
123
+ const method = inspectClassMethods(controllerClass).find((methodNode) => {
124
+ return methodNode.find({ rule: { kind: "property_identifier" } })?.text() === controller.method;
125
+ });
126
+ if (!method) {
127
+ debug_default(`Unable to find "%s" method in "%s"`, controller.method, controller.import.specifier);
128
+ return;
129
+ }
130
+ /**
131
+ * Inspect validators via "request.validateUsing" and "vine.validate"
132
+ * method calls.
133
+ */
134
+ const validationCalls = inspectMethodArguments(method, [
135
+ "request.validateUsing",
136
+ "$CTX.request.validateUsing",
137
+ "vine.validate"
138
+ ]).map((node) => {
139
+ const firstArg = node.find({ rule: { any: [{ kind: "identifier" }, { kind: "member_expression" }] } });
140
+ if (!firstArg) return;
141
+ return nodeToPlainText(firstArg);
142
+ }).filter((node) => node !== void 0).concat(searchValidatorDirectUsage(method).map((node) => nodeToPlainText(node)));
143
+ /**
144
+ * Unable to find any validation calls, or the first argument of the
145
+ * validation call was not a member_expression or an identifier.
146
+ */
147
+ if (!validationCalls.length) {
148
+ debug_default(`Unable to detect any validation calls in "%s.%s" method`, controller.import.specifier, controller.method);
149
+ return;
150
+ }
151
+ const controllerName = controllerClass.find({ rule: { kind: "type_identifier" } }).text();
152
+ const controllerURL = pathToFileURL(controller.path);
153
+ return (await Promise.all(validationCalls.map(async (validationCall) => {
154
+ if (validationCall.split(".")[0] === controllerName) return {
155
+ name: validationCall,
156
+ import: {
157
+ specifier: controller.import.specifier,
158
+ type: "default",
159
+ value: controllerName
160
+ }
161
+ };
162
+ const importCall = await findImport(fileContents, validationCall);
163
+ if (!importCall) {
164
+ debug_default("Unable to find import for \"%s\" used by \"%s.%s\" method", validationCall, controller.import.specifier, controller.method);
165
+ return null;
166
+ }
167
+ return {
168
+ name: validationCall,
169
+ import: {
170
+ specifier: isRelative(importCall.specifier) ? string.toUnixSlash(relative(appRoot, fileURLToPath(new URL(importCall.specifier, controllerURL)))) : importCall.specifier,
171
+ type: importCall.clause.type,
172
+ value: importCall.clause.value
173
+ }
174
+ };
175
+ }))).filter((value) => !!value);
176
+ }
177
+ //#endregion
178
+ //#region src/code_scanners/routes_scanner/main.ts
179
+ /**
180
+ * RoutesScanner is responsible for scanning application routes,
181
+ * extracting their controllers, validators, request and response types.
182
+ *
183
+ * The RoutesScanner analyzes route definitions to extract TypeScript type information
184
+ * for request validation, response types, and controller methods. It supports custom
185
+ * rules for overriding default behavior and provides hooks for extending functionality.
186
+ *
187
+ * @example
188
+ * const scanner = new RoutesScanner(appRoot, [rules])
189
+ * scanner.defineResponse((route, controller) => {
190
+ * return { type: 'CustomResponseType', imports: [] }
191
+ * })
192
+ * await scanner.scan(routes)
193
+ * const scannedRoutes = scanner.getScannedRoutes()
194
+ */
195
+ var RoutesScanner = class {
196
+ /**
197
+ * Optional filter function to selectively include routes during scanning.
198
+ * When defined, only routes for which this function returns true will be processed.
199
+ */
200
+ #filter;
201
+ /**
202
+ * The root of the application from where we will resolve
203
+ * paths.
204
+ */
205
+ #appRoot;
206
+ /**
207
+ * Collection of routes by their controller file path. This helps
208
+ * us re-compute request types when the controller is changed.
209
+ */
210
+ #controllerRoutes = {};
211
+ /**
212
+ * Collection of scanned routes
213
+ */
214
+ #scannedRoutes = [];
215
+ /**
216
+ * A custom method to self compute the response type for a route. Return
217
+ * undefined to fallback to the default behavior
218
+ */
219
+ #computeResponseTypes;
220
+ /**
221
+ * A custom method to self compute the request type for a route. Return
222
+ * undefined to fallback to the default behavior
223
+ */
224
+ #computeRequestTypes;
225
+ /**
226
+ * A custom method to self extract the validators from the route controller.
227
+ * Return undefined to fallback to the default behavior.
228
+ */
229
+ #extractValidators;
230
+ /**
231
+ * CLI UI instance to log colorful messages and progress information
232
+ */
233
+ ui = cliui();
234
+ /**
235
+ * The paths resolver is used to convert subpath and package
236
+ * imports to absolute paths
237
+ */
238
+ pathsResolver;
239
+ /**
240
+ * The rules to apply when scanning routes
241
+ */
242
+ rules = {
243
+ request: {},
244
+ response: {}
245
+ };
246
+ /**
247
+ * Create a new RoutesScanner instance
248
+ *
249
+ * @param appRoot - The root directory of the application
250
+ * @param rulesCollection - Collection of rules to apply during scanning
251
+ */
252
+ constructor(appRoot, rulesCollection) {
253
+ this.#appRoot = appRoot;
254
+ this.pathsResolver = new PathsResolver(appRoot);
255
+ rulesCollection.forEach((rules) => {
256
+ Object.assign(this.rules.request, rules.request);
257
+ Object.assign(this.rules.response, rules.response);
258
+ });
259
+ }
260
+ /**
261
+ * Determines if a route should be skipped based on the filter function.
262
+ *
263
+ * @param route - The route to check
264
+ */
265
+ #shouldSkipRoute(route) {
266
+ if (this.#filter) return !this.#filter(route);
267
+ return false;
268
+ }
269
+ /**
270
+ * Assumes the validators are from VineJS and computes the request types from them
271
+ *
272
+ * This method generates TypeScript type definitions for request validation
273
+ * by analyzing VineJS validators and creating Infer types.
274
+ *
275
+ * @param route - The scanned route with validators
276
+ * @returns Request type definition or undefined
277
+ */
278
+ #prepareRequestTypes(route) {
279
+ if (!route.validators) return;
280
+ return {
281
+ type: route.validators.reduce((result, validator) => {
282
+ const validatorExport = validator.import.type === "default" ? ".default" : validator.import.type === "named" ? `.${validator.import.value}` : "";
283
+ const [, ...segments] = validator.name.split(".");
284
+ const namespace = segments.map((segment) => `['${segment}']`).join("");
285
+ result.push(`InferInput<(typeof import('${validator.import.specifier}')${validatorExport})${namespace}>`);
286
+ return result;
287
+ }, []).join("|"),
288
+ imports: [`import { InferInput } from '@vinejs/vine/types'`]
289
+ };
290
+ }
291
+ /**
292
+ * Inspects the controller reference and fetches its import specifier
293
+ * and the controller name from it.
294
+ *
295
+ * @param importExpression - The import expression to parse (e.g., "import('#controllers/users_controller')")
296
+ * @param method - The controller method name (defaults to 'handle' if not provided)
297
+ */
298
+ async #inspectControllerSpecifier(importExpression, method) {
299
+ const importedModule = [...await parseImports(importExpression)].find(($import) => $import.isDynamicImport && $import.moduleSpecifier.value);
300
+ /**
301
+ * The provided expression was not a lazy load import.
302
+ */
303
+ if (!importedModule || importedModule.moduleSpecifier.type !== "package" || !importedModule.moduleSpecifier.value) return null;
304
+ const specifier = importedModule.moduleSpecifier.value;
305
+ const name = new StringBuilder(specifier.split("/").pop()).removeSuffix("Controller").pascalCase().suffix("Controller").toString();
306
+ return {
307
+ name,
308
+ method: method ?? "handle",
309
+ path: string.toUnixSlash(this.pathsResolver.resolve(specifier, true)),
310
+ import: {
311
+ specifier,
312
+ type: "default",
313
+ value: name
314
+ }
315
+ };
316
+ }
317
+ /**
318
+ * Defines the response type for the route by calling the custom compute function
319
+ * or falling back to inferring the return type from the controller method.
320
+ *
321
+ * @param route - The scanned route to set response type for
322
+ * @param controller - The controller containing the route handler
323
+ */
324
+ async #setResponse(route, controller) {
325
+ route.response = await this.#computeResponseTypes?.(route, controller, this) ?? {
326
+ type: `ReturnType<import('${controller.import.specifier}').default['${controller.method}']>`,
327
+ imports: []
328
+ };
329
+ debug_default("computed route \"%s\" response %O", route.name, route.response);
330
+ }
331
+ /**
332
+ * Defines the request type for the route by extracting validators and computing
333
+ * the request type from them or using a custom compute function.
334
+ *
335
+ * @param route - The scanned route to set request type for
336
+ * @param controller - The controller containing the route handler
337
+ * @param vfs - Virtual file system for analyzing controller code
338
+ */
339
+ async #setRequest(route, controller, vfs) {
340
+ route.validators = await this.#extractValidators?.(route, controller, this) ?? await extractValidators(this.#appRoot, vfs, controller);
341
+ debug_default("computed route \"%s\" validators %O", route.name, route.validators);
342
+ route.request = await this.#computeRequestTypes?.(route, controller, this) ?? this.#prepareRequestTypes(route);
343
+ debug_default("computed route \"%s\" request input %O", route.name, route.request);
344
+ }
345
+ /**
346
+ * Scans a route that is not using a controller (inline route handler).
347
+ * For routes without controllers, only rules-based request/response types are available.
348
+ *
349
+ * @param route - The route to process
350
+ */
351
+ #processRouteWithoutController(route) {
352
+ if (!route.name) {
353
+ debug_default(`skipping route "%s" as it does not have a name`, route.pattern);
354
+ return;
355
+ }
356
+ const scannedRoute = {
357
+ name: route.name,
358
+ domain: route.domain,
359
+ methods: route.methods,
360
+ pattern: route.pattern,
361
+ tokens: route.tokens,
362
+ request: this.rules.request[route.name],
363
+ response: this.rules.response[route.name]
364
+ };
365
+ debug_default("scanned route without controller %O", scannedRoute);
366
+ this.#scannedRoutes.push(scannedRoute);
367
+ }
368
+ /**
369
+ * Scans a route that is using a controller reference.
370
+ * Extracts controller information, validators, and type information.
371
+ *
372
+ * @param route - The route with a controller handler
373
+ * @param vfs - Virtual file system for analyzing controller code
374
+ */
375
+ async #processRouteWithController(route, vfs) {
376
+ /**
377
+ * Process without controller, when importExpression is missing. This is
378
+ * the case where someone imports the controllers and uses it by
379
+ * reference
380
+ */
381
+ if (!route.handler || !route.handler.importExpression) return this.#processRouteWithoutController(route);
382
+ /**
383
+ * Inspect controller by parsing its import expression
384
+ */
385
+ const controller = await this.#inspectControllerSpecifier(route.handler.importExpression, route.handler.method);
386
+ /**
387
+ * Process route without a controller when we are not able to extract the import
388
+ * path of the controller, because the import path is needed to further extract
389
+ * request and response types.
390
+ */
391
+ if (!controller) return this.#processRouteWithoutController(route);
392
+ debug_default("processing route \"%s\" with inspected controller %O", route.name, controller);
393
+ /**
394
+ * Converting controller name and its method to snake_case to create a unique
395
+ * name for the route. There could be chances where one controller+method
396
+ * combination is bound to multiple routes.
397
+ */
398
+ route.name = route.name ?? new StringBuilder(controller.name).removeSuffix("Controller").snakeCase().suffix(`.${string.snakeCase(controller.method)}`).toString();
399
+ /**
400
+ * Skip route when its name is within the array of
401
+ * skip routes
402
+ */
403
+ if (this.#shouldSkipRoute(route)) return;
404
+ /**
405
+ * Creating a scanned route and tracking it. We will inspect the response
406
+ * and request if these values are not provided via rules.
407
+ */
408
+ const scannedRoute = {
409
+ name: route.name,
410
+ domain: route.domain,
411
+ methods: route.methods,
412
+ pattern: route.pattern,
413
+ tokens: route.tokens,
414
+ request: this.rules.request[route.name],
415
+ response: this.rules.response[route.name],
416
+ controller
417
+ };
418
+ debug_default("scanned route %O", scannedRoute);
419
+ this.#scannedRoutes.push(scannedRoute);
420
+ /**
421
+ * Track route next to the controller absolute path. This way we will be
422
+ * able to invalidate request types everytime the controller is modified.
423
+ */
424
+ if (!scannedRoute.request || !scannedRoute.response) {
425
+ debug_default("tracking controller for rescanning %O", scannedRoute);
426
+ this.#controllerRoutes[controller.path] ??= [];
427
+ this.#controllerRoutes[controller.path].push(scannedRoute);
428
+ if (!scannedRoute.response) await this.#setResponse(scannedRoute, controller);
429
+ if (!scannedRoute.request) await this.#setRequest(scannedRoute, controller, vfs);
430
+ }
431
+ }
432
+ /**
433
+ * Processes a given route list item and scans it to extract
434
+ * the controller, request and response types.
435
+ *
436
+ * @param route - The route to process
437
+ * @param vfs - Virtual file system for analyzing controller code
438
+ */
439
+ async #processRoute(route, vfs) {
440
+ /**
441
+ * Skip route when it has a name and also part of
442
+ * skip array
443
+ */
444
+ if (route.name && this.#shouldSkipRoute(route)) {
445
+ debug_default("route skipped route: %O, rules: %O", route, this.rules);
446
+ return;
447
+ }
448
+ /**
449
+ * Routes without a controller reference cannot have types for the request
450
+ * and response (unless provided via rules)
451
+ */
452
+ if (typeof route.handler === "function") {
453
+ this.#processRouteWithoutController(route);
454
+ return;
455
+ }
456
+ await this.#processRouteWithController(route, vfs);
457
+ }
458
+ /**
459
+ * Register a callback to self compute the response types for
460
+ * a given route. The callback will be executed for all
461
+ * the routes and you must return undefined to fallback
462
+ * to the default behavior of detecting types
463
+ *
464
+ * @param callback - Function to compute response types for routes
465
+ * @returns This RoutesScanner instance for method chaining
466
+ */
467
+ defineResponse(callback) {
468
+ this.#computeResponseTypes = callback;
469
+ return this;
470
+ }
471
+ /**
472
+ * Register a callback to self compute the request types for
473
+ * a given route. The callback will be executed for all
474
+ * the routes and you must return undefined to fallback
475
+ * to the default behavior of detecting types
476
+ *
477
+ * @param callback - Function to compute request types for routes
478
+ * @returns This RoutesScanner instance for method chaining
479
+ */
480
+ defineRequest(callback) {
481
+ this.#computeRequestTypes = callback;
482
+ return this;
483
+ }
484
+ /**
485
+ * Register a callback to extract validators from the route controller
486
+ *
487
+ * @param callback - Function to extract validators from controllers
488
+ * @returns This RoutesScanner instance for method chaining
489
+ */
490
+ extractValidators(callback) {
491
+ this.#extractValidators = callback;
492
+ return this;
493
+ }
494
+ /**
495
+ * Returns the scanned routes
496
+ *
497
+ * @returns Array of scanned routes with their metadata
498
+ */
499
+ getScannedRoutes() {
500
+ return this.#scannedRoutes;
501
+ }
502
+ /**
503
+ * Returns an array of controllers bound to the provided
504
+ * routes
505
+ *
506
+ * @returns Array of controller's absolute paths
507
+ */
508
+ getControllers() {
509
+ return Object.keys(this.#controllerRoutes);
510
+ }
511
+ /**
512
+ * Invalidating a controller will trigger computing the validators,
513
+ * request types and the response types.
514
+ *
515
+ * @param controllerPath - Path to the controller file to invalidate
516
+ */
517
+ async invalidate(controllerPath) {
518
+ const controllerRoutes = this.#controllerRoutes[controllerPath];
519
+ if (!controllerRoutes || !controllerRoutes.length) {
520
+ debug_default("\"%s\" controllers is not part of scanned controllers %O", controllerPath, this.#controllerRoutes);
521
+ return false;
522
+ }
523
+ for (let scannedRoute of controllerRoutes) if (scannedRoute.controller) {
524
+ debug_default("invalidating route %O", scannedRoute);
525
+ const vfs = new VirtualFileSystem(this.#appRoot);
526
+ await this.#setResponse(scannedRoute, scannedRoute.controller);
527
+ await this.#setRequest(scannedRoute, scannedRoute.controller, vfs);
528
+ }
529
+ return true;
530
+ }
531
+ /**
532
+ * Sets a filter function to selectively include routes during scanning.
533
+ *
534
+ * @param filterFn - Function that returns true for routes to include
535
+ * @returns This RoutesScanner instance for method chaining
536
+ *
537
+ * @example
538
+ * scanner.filter((route) => {
539
+ * return route.pattern.startsWith('/api')
540
+ * })
541
+ */
542
+ filter(filterFn) {
543
+ this.#filter = filterFn;
544
+ return this;
545
+ }
546
+ /**
547
+ * Scans an array of Route list items and fetches their validators,
548
+ * controllers, and request/response types.
549
+ *
550
+ * This is the main method that processes all routes and extracts
551
+ * their type information for code generation purposes.
552
+ *
553
+ * @param routes - Array of route list items to scan
554
+ */
555
+ async scan(routes) {
556
+ const vfs = new VirtualFileSystem(this.#appRoot);
557
+ for (const route of routes) await this.#processRoute(route, vfs);
558
+ vfs.invalidate();
559
+ }
560
+ };
561
+ //#endregion
562
+ export { RoutesScanner as t };