@adonisjs/assembler 8.0.0-next.2 → 8.0.0-next.20

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 (35) hide show
  1. package/README.md +88 -84
  2. package/build/chunk-4452KFDQ.js +465 -0
  3. package/build/chunk-JFBQ4OEM.js +434 -0
  4. package/build/chunk-NAASGAFO.js +478 -0
  5. package/build/chunk-TIKQQRMX.js +116 -0
  6. package/build/index.d.ts +3 -0
  7. package/build/index.js +800 -447
  8. package/build/src/bundler.d.ts +44 -3
  9. package/build/src/code_scanners/routes_scanner/main.d.ts +119 -0
  10. package/build/src/code_scanners/routes_scanner/main.js +8 -0
  11. package/build/src/code_scanners/routes_scanner/validator_extractor.d.ts +26 -0
  12. package/build/src/code_transformer/main.d.ts +44 -43
  13. package/build/src/code_transformer/main.js +123 -101
  14. package/build/src/code_transformer/rc_file_transformer.d.ts +56 -4
  15. package/build/src/debug.d.ts +12 -0
  16. package/build/src/dev_server.d.ts +92 -17
  17. package/build/src/file_buffer.d.ts +87 -0
  18. package/build/src/file_system.d.ts +46 -8
  19. package/build/src/helpers.d.ts +115 -0
  20. package/build/src/helpers.js +16 -0
  21. package/build/src/index_generator/main.d.ts +68 -0
  22. package/build/src/index_generator/main.js +7 -0
  23. package/build/src/index_generator/source.d.ts +60 -0
  24. package/build/src/paths_resolver.d.ts +41 -0
  25. package/build/src/shortcuts_manager.d.ts +43 -28
  26. package/build/src/test_runner.d.ts +57 -12
  27. package/build/src/types/code_scanners.d.ts +226 -0
  28. package/build/src/types/code_transformer.d.ts +61 -19
  29. package/build/src/types/common.d.ts +270 -51
  30. package/build/src/types/hooks.d.ts +235 -22
  31. package/build/src/types/main.d.ts +15 -1
  32. package/build/src/utils.d.ts +99 -15
  33. package/build/src/virtual_file_system.d.ts +112 -0
  34. package/package.json +33 -20
  35. package/build/chunk-RR4HCA4M.js +0 -7
@@ -0,0 +1,478 @@
1
+ import {
2
+ findImport,
3
+ inspectClass,
4
+ inspectClassMethods,
5
+ inspectMethodArguments,
6
+ nodeToPlainText,
7
+ searchValidatorDirectUsage
8
+ } from "./chunk-TIKQQRMX.js";
9
+ import {
10
+ VirtualFileSystem,
11
+ debug_default,
12
+ isRelative
13
+ } from "./chunk-JFBQ4OEM.js";
14
+
15
+ // src/code_scanners/routes_scanner/main.ts
16
+ import { cliui } from "@poppinss/cliui";
17
+ import string2 from "@poppinss/utils/string";
18
+ import { parseImports } from "parse-imports";
19
+ import StringBuilder from "@poppinss/utils/string_builder";
20
+
21
+ // src/paths_resolver.ts
22
+ import { join } from "path";
23
+ import { resolve } from "import-meta-resolve";
24
+ import { fileURLToPath, pathToFileURL } from "url";
25
+ var PathsResolver = class {
26
+ /**
27
+ * The root of the application from where we will resolve
28
+ * paths.
29
+ */
30
+ #appRoot;
31
+ /**
32
+ * Cache of resolved paths to avoid resolving the same specifier multiple times
33
+ */
34
+ #resolvedPaths = {};
35
+ /**
36
+ * The resolver function used to resolve import specifiers
37
+ */
38
+ #resolver = (specifier, parentPath) => resolve(specifier, parentPath);
39
+ constructor(appRoot) {
40
+ this.#appRoot = pathToFileURL(join(appRoot, "index.js")).href;
41
+ }
42
+ /**
43
+ * Define a custom resolver that resolves a path
44
+ *
45
+ * The custom resolver function will be used instead of the default
46
+ * import.meta.resolve() for resolving import specifiers.
47
+ *
48
+ * @param resolver - Function that takes a specifier and returns resolved path
49
+ */
50
+ use(resolver) {
51
+ this.#resolver = resolver;
52
+ }
53
+ /**
54
+ * Resolve import specifier to an absolute file path
55
+ *
56
+ * This method caches resolved paths to improve performance on repeated
57
+ * resolutions. Relative paths are not supported and will throw an error.
58
+ *
59
+ * @param specifier - The import specifier to resolve (must not be relative)
60
+ * @returns The resolved absolute file path
61
+ * @throws Error when attempting to resolve relative paths
62
+ *
63
+ * @example
64
+ * const path = resolver.resolve('#app/models/user')
65
+ * const path2 = resolver.resolve('@/utils/helper')
66
+ */
67
+ resolve(specifier, rewriteAliasImportExtension = false) {
68
+ if (isRelative(specifier)) {
69
+ throw new Error("Cannot resolve relative paths using PathsResolver");
70
+ }
71
+ const cacheKey = specifier;
72
+ const cached = this.#resolvedPaths[cacheKey];
73
+ if (cached) {
74
+ return cached;
75
+ }
76
+ let resolvedPath = fileURLToPath(this.#resolver(specifier, this.#appRoot));
77
+ if (rewriteAliasImportExtension && specifier.startsWith("#") && resolvedPath.endsWith(".js")) {
78
+ resolvedPath = resolvedPath.replace(/\.js$/, ".ts");
79
+ }
80
+ this.#resolvedPaths[cacheKey] = resolvedPath;
81
+ return this.#resolvedPaths[cacheKey];
82
+ }
83
+ };
84
+
85
+ // src/code_scanners/routes_scanner/validator_extractor.ts
86
+ import { relative } from "path";
87
+ import string from "@poppinss/utils/string";
88
+ import { fileURLToPath as fileURLToPath2, pathToFileURL as pathToFileURL2 } from "url";
89
+ async function extractValidators(appRoot, vfs, controller) {
90
+ const root = await vfs.get(controller.path);
91
+ const fileContents = root.text();
92
+ const controllerClass = inspectClass(root);
93
+ if (!controllerClass) {
94
+ debug_default(`No class defined within the "%s"`, controller.import.specifier);
95
+ return;
96
+ }
97
+ const method = inspectClassMethods(controllerClass).find((methodNode) => {
98
+ const methodName = methodNode.find({ rule: { kind: "property_identifier" } });
99
+ return methodName?.text() === controller.method;
100
+ });
101
+ if (!method) {
102
+ debug_default(`Unable to find "%s" method in "%s"`, controller.method, controller.import.specifier);
103
+ return;
104
+ }
105
+ const validationCalls = inspectMethodArguments(method, ["request.validateUsing", "vine.validate"]).map((node) => {
106
+ const firstArg = node.find({
107
+ rule: { any: [{ kind: "identifier" }, { kind: "member_expression" }] }
108
+ });
109
+ if (!firstArg) {
110
+ return;
111
+ }
112
+ return nodeToPlainText(firstArg);
113
+ }).filter((node) => node !== void 0).concat(searchValidatorDirectUsage(method).map((node) => nodeToPlainText(node)));
114
+ if (!validationCalls.length) {
115
+ debug_default(
116
+ `Unable to detect any validation calls in "%s.%s" method`,
117
+ controller.import.specifier,
118
+ controller.method
119
+ );
120
+ return;
121
+ }
122
+ const controllerName = controllerClass.find({ rule: { kind: "type_identifier" } }).text();
123
+ const controllerURL = pathToFileURL2(controller.path);
124
+ const imports = await Promise.all(
125
+ validationCalls.map(async (validationCall) => {
126
+ const validatorNamespace = validationCall.split(".")[0];
127
+ if (validatorNamespace === controllerName) {
128
+ return {
129
+ name: validationCall,
130
+ import: {
131
+ specifier: controller.import.specifier,
132
+ type: "default",
133
+ value: controllerName
134
+ }
135
+ };
136
+ }
137
+ const importCall = await findImport(fileContents, validationCall);
138
+ if (!importCall) {
139
+ debug_default(
140
+ 'Unable to find import for "%s" used by "%s.%s" method',
141
+ validationCall,
142
+ controller.import.specifier,
143
+ controller.method
144
+ );
145
+ return null;
146
+ }
147
+ return {
148
+ name: validationCall,
149
+ import: {
150
+ specifier: isRelative(importCall.specifier) ? string.toUnixSlash(
151
+ relative(appRoot, fileURLToPath2(new URL(importCall.specifier, controllerURL)))
152
+ ) : importCall.specifier,
153
+ type: importCall.clause.type,
154
+ value: importCall.clause.value
155
+ }
156
+ };
157
+ })
158
+ );
159
+ return imports.filter((value) => !!value);
160
+ }
161
+
162
+ // src/code_scanners/routes_scanner/main.ts
163
+ var RoutesScanner = class {
164
+ /**
165
+ * The root of the application from where we will resolve
166
+ * paths.
167
+ */
168
+ #appRoot;
169
+ /**
170
+ * Collection of routes by their controller file path. This helps
171
+ * us re-compute request types when the controller is changed.
172
+ */
173
+ #controllerRoutes = {};
174
+ /**
175
+ * Collection of scanned routes
176
+ */
177
+ #scannedRoutes = [];
178
+ /**
179
+ * A custom method to self compute the response type for a route. Return
180
+ * undefined to fallback to the default behavior
181
+ */
182
+ #computeResponseTypes;
183
+ /**
184
+ * A custom method to self compute the request type for a route. Return
185
+ * undefined to fallback to the default behavior
186
+ */
187
+ #computeRequestTypes;
188
+ /**
189
+ * A custom method to self extract the validators from the route controller.
190
+ * Return undefined to fallback to the default behavior.
191
+ */
192
+ #extractValidators;
193
+ /**
194
+ * CLI UI instance to log colorful messages and progress information
195
+ */
196
+ ui = cliui();
197
+ /**
198
+ * The paths resolver is used to convert subpath and package
199
+ * imports to absolute paths
200
+ */
201
+ pathsResolver;
202
+ /**
203
+ * The rules to apply when scanning routes
204
+ */
205
+ rules = {
206
+ skip: [],
207
+ request: {},
208
+ response: {}
209
+ };
210
+ /**
211
+ * Create a new RoutesScanner instance
212
+ *
213
+ * @param appRoot - The root directory of the application
214
+ * @param rulesCollection - Collection of rules to apply during scanning
215
+ */
216
+ constructor(appRoot, rulesCollection) {
217
+ this.#appRoot = appRoot;
218
+ this.pathsResolver = new PathsResolver(appRoot);
219
+ rulesCollection.forEach((rules) => {
220
+ this.rules.skip = this.rules.skip.concat(rules.skip);
221
+ Object.assign(this.rules.request, rules.request);
222
+ Object.assign(this.rules.response, rules.response);
223
+ });
224
+ this.rules.skip = Array.from(/* @__PURE__ */ new Set([...this.rules.skip]));
225
+ }
226
+ /**
227
+ * Assumes the validators are from VineJS and computes the request types from them
228
+ *
229
+ * This method generates TypeScript type definitions for request validation
230
+ * by analyzing VineJS validators and creating Infer types.
231
+ *
232
+ * @param route - The scanned route with validators
233
+ * @returns Request type definition or undefined
234
+ */
235
+ #prepareRequestTypes(route) {
236
+ if (!route.validators) {
237
+ return;
238
+ }
239
+ const schemas = route.validators.reduce((result, validator) => {
240
+ const validatorExport = validator.import.type === "default" ? ".default" : validator.import.type === "named" ? `.${validator.import.value}` : "";
241
+ const [, ...segments] = validator.name.split(".");
242
+ const namespace = segments.map((segment) => `['${segment}']`).join("");
243
+ result.push(
244
+ `Infer<(typeof import('${validator.import.specifier}')${validatorExport})${namespace}>`
245
+ );
246
+ return result;
247
+ }, []);
248
+ return {
249
+ type: schemas.join("|"),
250
+ imports: [`import { Infer } from '@vinejs/vine/types'`]
251
+ };
252
+ }
253
+ /**
254
+ * Inspects the controller reference and fetches its import specifier
255
+ * and the controller name from it.
256
+ */
257
+ async #inspectControllerSpecifier(importExpression, method) {
258
+ const imports = [...await parseImports(importExpression)];
259
+ const importedModule = imports.find(
260
+ ($import) => $import.isDynamicImport && $import.moduleSpecifier.value
261
+ );
262
+ if (!importedModule || importedModule.moduleSpecifier.type !== "package" || !importedModule.moduleSpecifier.value) {
263
+ return null;
264
+ }
265
+ const specifier = importedModule.moduleSpecifier.value;
266
+ const name = new StringBuilder(specifier.split("/").pop()).removeSuffix("Controller").pascalCase().suffix("Controller").toString();
267
+ return {
268
+ name,
269
+ method: method ?? "handle",
270
+ path: string2.toUnixSlash(this.pathsResolver.resolve(specifier, true)),
271
+ import: {
272
+ specifier,
273
+ type: "default",
274
+ value: name
275
+ }
276
+ };
277
+ }
278
+ /**
279
+ * Defines the response type for the route
280
+ */
281
+ async #setResponse(route, controller) {
282
+ const responseType = await this.#computeResponseTypes?.(route, controller, this);
283
+ route.response = responseType ?? {
284
+ type: `ReturnType<import('${controller.import.specifier}').default['${controller.method}']>`,
285
+ imports: []
286
+ };
287
+ debug_default('computed route "%s" response %O', route.name, route.response);
288
+ }
289
+ /**
290
+ * Defines the request type for the route
291
+ */
292
+ async #setRequest(route, controller, vfs) {
293
+ route.validators = await this.#extractValidators?.(route, controller, this) ?? await extractValidators(this.#appRoot, vfs, controller);
294
+ debug_default('computed route "%s" validators %O', route.name, route.validators);
295
+ route.request = await this.#computeRequestTypes?.(route, controller, this) ?? this.#prepareRequestTypes(route);
296
+ debug_default('computed route "%s" request input %O', route.name, route.request);
297
+ }
298
+ /**
299
+ * Scans a route that is not using a controller
300
+ */
301
+ #processRouteWithoutController(route) {
302
+ if (!route.name) {
303
+ debug_default(`skipping route "%s" as it does not have a name`, route.pattern);
304
+ return;
305
+ }
306
+ const scannedRoute = {
307
+ name: route.name,
308
+ domain: route.domain,
309
+ methods: route.methods,
310
+ pattern: route.pattern,
311
+ tokens: route.tokens,
312
+ request: this.rules.request[route.name],
313
+ response: this.rules.response[route.name]
314
+ };
315
+ debug_default("scanned route without controller %O", scannedRoute);
316
+ this.#scannedRoutes.push(scannedRoute);
317
+ }
318
+ /**
319
+ * Scans a route that is using a controller reference
320
+ */
321
+ async #processRouteWithController(route, vfs) {
322
+ if (!route.handler || !route.handler.importExpression) {
323
+ return this.#processRouteWithoutController(route);
324
+ }
325
+ const controller = await this.#inspectControllerSpecifier(
326
+ route.handler.importExpression,
327
+ route.handler.method
328
+ );
329
+ if (!controller) {
330
+ return this.#processRouteWithoutController(route);
331
+ }
332
+ debug_default('processing route "%s" with inspected controller %O', route.name, controller);
333
+ const routeName = route.name ?? new StringBuilder(controller.name).removeSuffix("Controller").snakeCase().suffix(`.${string2.snakeCase(controller.method)}`).toString();
334
+ if (this.rules.skip.includes(routeName)) {
335
+ return;
336
+ }
337
+ const scannedRoute = {
338
+ name: routeName,
339
+ domain: route.domain,
340
+ methods: route.methods,
341
+ pattern: route.pattern,
342
+ tokens: route.tokens,
343
+ request: this.rules.request[routeName],
344
+ response: this.rules.response[routeName],
345
+ controller
346
+ };
347
+ debug_default("scanned route %O", scannedRoute);
348
+ this.#scannedRoutes.push(scannedRoute);
349
+ if (!scannedRoute.request || !scannedRoute.response) {
350
+ debug_default("tracking controller for rescanning %O", scannedRoute);
351
+ this.#controllerRoutes[controller.path] ??= [];
352
+ this.#controllerRoutes[controller.path].push(scannedRoute);
353
+ if (!scannedRoute.response) {
354
+ await this.#setResponse(scannedRoute, controller);
355
+ }
356
+ if (!scannedRoute.request) {
357
+ await this.#setRequest(scannedRoute, controller, vfs);
358
+ }
359
+ }
360
+ }
361
+ /**
362
+ * Processing a given route list item and further scan it to
363
+ * fetch the controller, request and response types.
364
+ */
365
+ async #processRoute(route, vfs) {
366
+ if (route.name && this.rules.skip.includes(route.name)) {
367
+ debug_default("route skipped route: %O, rules: %O", route, this.rules);
368
+ return;
369
+ }
370
+ if (typeof route.handler === "function") {
371
+ this.#processRouteWithoutController(route);
372
+ return;
373
+ }
374
+ await this.#processRouteWithController(
375
+ route,
376
+ vfs
377
+ );
378
+ }
379
+ /**
380
+ * Register a callback to self compute the response types for
381
+ * a given route. The callback will be executed for all
382
+ * the routes and you must return undefined to fallback
383
+ * to the default behavior of detecting types
384
+ *
385
+ * @param callback - Function to compute response types for routes
386
+ * @returns This RoutesScanner instance for method chaining
387
+ */
388
+ defineResponse(callback) {
389
+ this.#computeResponseTypes = callback;
390
+ return this;
391
+ }
392
+ /**
393
+ * Register a callback to self compute the request types for
394
+ * a given route. The callback will be executed for all
395
+ * the routes and you must return undefined to fallback
396
+ * to the default behavior of detecting types
397
+ *
398
+ * @param callback - Function to compute request types for routes
399
+ * @returns This RoutesScanner instance for method chaining
400
+ */
401
+ defineRequest(callback) {
402
+ this.#computeRequestTypes = callback;
403
+ return this;
404
+ }
405
+ /**
406
+ * Register a callback to extract validators from the route controller
407
+ *
408
+ * @param callback - Function to extract validators from controllers
409
+ * @returns This RoutesScanner instance for method chaining
410
+ */
411
+ extractValidators(callback) {
412
+ this.#extractValidators = callback;
413
+ return this;
414
+ }
415
+ /**
416
+ * Returns the scanned routes
417
+ *
418
+ * @returns Array of scanned routes with their metadata
419
+ */
420
+ getScannedRoutes() {
421
+ return this.#scannedRoutes;
422
+ }
423
+ /**
424
+ * Returns an array of controllers bound to the provided
425
+ * routes
426
+ *
427
+ * @returns Array of controller's absolute paths
428
+ */
429
+ getControllers() {
430
+ return Object.keys(this.#controllerRoutes);
431
+ }
432
+ /**
433
+ * Invalidating a controller will trigger computing the validators,
434
+ * request types and the response types.
435
+ *
436
+ * @param controllerPath - Path to the controller file to invalidate
437
+ */
438
+ async invalidate(controllerPath) {
439
+ const controllerRoutes = this.#controllerRoutes[controllerPath];
440
+ if (!controllerRoutes || !controllerRoutes.length) {
441
+ debug_default(
442
+ '"%s" controllers is not part of scanned controllers %O',
443
+ controllerPath,
444
+ this.#controllerRoutes
445
+ );
446
+ return false;
447
+ }
448
+ for (let scannedRoute of controllerRoutes) {
449
+ if (scannedRoute.controller) {
450
+ debug_default("invalidating route %O", scannedRoute);
451
+ const vfs = new VirtualFileSystem(this.#appRoot);
452
+ await this.#setResponse(scannedRoute, scannedRoute.controller);
453
+ await this.#setRequest(scannedRoute, scannedRoute.controller, vfs);
454
+ }
455
+ }
456
+ return true;
457
+ }
458
+ /**
459
+ * Scans an array of Route list items and fetches their validators,
460
+ * controllers, and request/response types.
461
+ *
462
+ * This is the main method that processes all routes and extracts
463
+ * their type information for code generation purposes.
464
+ *
465
+ * @param routes - Array of route list items to scan
466
+ */
467
+ async scan(routes) {
468
+ const vfs = new VirtualFileSystem(this.#appRoot);
469
+ for (const route of routes) {
470
+ await this.#processRoute(route, vfs);
471
+ }
472
+ vfs.invalidate();
473
+ }
474
+ };
475
+
476
+ export {
477
+ RoutesScanner
478
+ };
@@ -0,0 +1,116 @@
1
+ // src/helpers.ts
2
+ import { parseImports } from "parse-imports";
3
+ async function findImport(code, importReference) {
4
+ const importIdentifier = importReference.split(".")[0];
5
+ for (const $import of await parseImports(code, {})) {
6
+ if (!$import.importClause) {
7
+ continue;
8
+ }
9
+ if (!$import.moduleSpecifier.value) {
10
+ continue;
11
+ }
12
+ if ($import.importClause.default === importIdentifier) {
13
+ return {
14
+ specifier: $import.moduleSpecifier.value,
15
+ isConstant: $import.moduleSpecifier.isConstant,
16
+ clause: {
17
+ type: "default",
18
+ value: importIdentifier
19
+ }
20
+ };
21
+ }
22
+ if ($import.importClause.namespace === importIdentifier) {
23
+ return {
24
+ specifier: $import.moduleSpecifier.value,
25
+ isConstant: $import.moduleSpecifier.isConstant,
26
+ clause: {
27
+ type: "namespace",
28
+ value: importIdentifier
29
+ }
30
+ };
31
+ }
32
+ const namedImport = $import.importClause.named.find(({ binding }) => {
33
+ return binding === importIdentifier;
34
+ });
35
+ if (namedImport) {
36
+ return {
37
+ specifier: $import.moduleSpecifier.value,
38
+ isConstant: $import.moduleSpecifier.isConstant,
39
+ clause: {
40
+ type: "named",
41
+ value: namedImport.specifier,
42
+ ...namedImport.binding !== namedImport.specifier ? {
43
+ alias: namedImport.binding
44
+ } : {}
45
+ }
46
+ };
47
+ }
48
+ }
49
+ return null;
50
+ }
51
+ function inspectClass(node) {
52
+ return node.find({
53
+ rule: {
54
+ kind: "class_declaration"
55
+ }
56
+ });
57
+ }
58
+ function inspectClassMethods(node) {
59
+ return node.findAll({
60
+ rule: {
61
+ kind: "method_definition"
62
+ }
63
+ });
64
+ }
65
+ function nodeToPlainText(node) {
66
+ let out = [];
67
+ function toText(one) {
68
+ const children = one.children();
69
+ if (!children.length) {
70
+ out.push(one.text());
71
+ } else {
72
+ children.forEach((child) => toText(child));
73
+ }
74
+ }
75
+ toText(node);
76
+ return out.join("");
77
+ }
78
+ function inspectMethodArguments(node, methodCalls) {
79
+ const matchingExpressions = node.findAll({
80
+ rule: {
81
+ any: methodCalls.map((methodCall) => {
82
+ return {
83
+ pattern: {
84
+ context: `${methodCall}($$$ARGUMENTS)`,
85
+ selector: "call_expression"
86
+ }
87
+ };
88
+ })
89
+ }
90
+ });
91
+ return matchingExpressions.flatMap((matchingExpression) => {
92
+ return matchingExpression.findAll({ rule: { kind: "arguments" } });
93
+ });
94
+ }
95
+ function searchValidatorDirectUsage(node) {
96
+ const matchingExpressions = node.findAll({
97
+ rule: {
98
+ pattern: {
99
+ context: "$$$VALIDATOR.validate($$$)",
100
+ selector: "call_expression"
101
+ }
102
+ }
103
+ });
104
+ return matchingExpressions.flatMap((expression) => {
105
+ return expression.getMultipleMatches("VALIDATOR");
106
+ });
107
+ }
108
+
109
+ export {
110
+ findImport,
111
+ inspectClass,
112
+ inspectClassMethods,
113
+ nodeToPlainText,
114
+ inspectMethodArguments,
115
+ searchValidatorDirectUsage
116
+ };
package/build/index.d.ts CHANGED
@@ -1,3 +1,6 @@
1
1
  export { Bundler } from './src/bundler.ts';
2
2
  export { DevServer } from './src/dev_server.ts';
3
3
  export { TestRunner } from './src/test_runner.ts';
4
+ export { FileBuffer } from './src/file_buffer.ts';
5
+ export { VirtualFileSystem } from './src/virtual_file_system.ts';
6
+ export { SUPPORTED_PACKAGE_MANAGERS } from './src/bundler.ts';