@adonisjs/http-server 7.0.0-0 → 7.0.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.
Files changed (107) hide show
  1. package/build/factories/http_context.d.ts +25 -0
  2. package/build/factories/http_context.js +51 -0
  3. package/build/factories/http_server.d.ts +8 -0
  4. package/build/factories/http_server.js +26 -0
  5. package/build/factories/main.d.ts +6 -149
  6. package/build/factories/main.js +14 -331
  7. package/build/factories/qs_parser_factory.d.ts +20 -0
  8. package/build/factories/qs_parser_factory.js +44 -0
  9. package/build/factories/request.d.ts +29 -0
  10. package/build/factories/request.js +73 -0
  11. package/build/factories/response.d.ts +29 -0
  12. package/build/factories/response.js +77 -0
  13. package/build/factories/router.d.ts +23 -0
  14. package/build/factories/router.js +45 -0
  15. package/build/factories/server_factory.d.ts +29 -0
  16. package/build/factories/server_factory.js +65 -0
  17. package/build/index.d.ts +14 -272
  18. package/build/index.js +22 -308
  19. package/build/src/cookies/client.d.ts +37 -0
  20. package/build/src/cookies/client.js +84 -0
  21. package/build/src/cookies/drivers/encrypted.d.ts +16 -0
  22. package/build/src/cookies/drivers/encrypted.js +36 -0
  23. package/build/src/cookies/drivers/plain.d.ts +15 -0
  24. package/build/src/cookies/drivers/plain.js +33 -0
  25. package/build/src/cookies/drivers/signed.d.ts +16 -0
  26. package/build/src/cookies/drivers/signed.js +36 -0
  27. package/build/src/cookies/parser.d.ts +37 -0
  28. package/build/src/cookies/parser.js +167 -0
  29. package/build/src/cookies/serializer.d.ts +33 -0
  30. package/build/src/cookies/serializer.js +79 -0
  31. package/build/src/debug.d.ts +3 -0
  32. package/build/src/debug.js +10 -0
  33. package/build/src/define_config.d.ts +9 -0
  34. package/build/src/define_config.js +68 -0
  35. package/build/src/define_middleware.d.ts +11 -0
  36. package/build/src/define_middleware.js +35 -0
  37. package/build/src/exception_handler.d.ts +113 -0
  38. package/build/src/exception_handler.js +306 -0
  39. package/build/src/exceptions.d.ts +84 -0
  40. package/build/src/exceptions.js +38 -0
  41. package/build/src/helpers.d.ts +23 -0
  42. package/build/src/helpers.js +105 -0
  43. package/build/src/http_context/local_storage.d.ts +12 -0
  44. package/build/src/http_context/local_storage.js +39 -0
  45. package/build/src/http_context/main.d.ts +58 -0
  46. package/build/src/http_context/main.js +105 -0
  47. package/build/src/qs.d.ts +11 -0
  48. package/build/src/qs.js +25 -0
  49. package/build/src/redirect.d.ts +42 -0
  50. package/build/src/redirect.js +140 -0
  51. package/build/src/request.d.ts +565 -0
  52. package/build/src/request.js +865 -0
  53. package/build/src/response.d.ts +620 -0
  54. package/build/src/response.js +1208 -0
  55. package/build/src/router/brisk.d.ts +42 -0
  56. package/build/src/router/brisk.js +85 -0
  57. package/build/src/router/executor.d.ts +9 -0
  58. package/build/src/router/executor.js +30 -0
  59. package/build/src/router/factories/use_return_value.d.ts +6 -0
  60. package/build/src/router/factories/use_return_value.js +22 -0
  61. package/build/src/router/group.d.ts +65 -0
  62. package/build/src/router/group.js +207 -0
  63. package/build/src/router/lookup_store/main.d.ts +49 -0
  64. package/build/src/router/lookup_store/main.js +86 -0
  65. package/build/src/router/lookup_store/route_finder.d.ts +21 -0
  66. package/build/src/router/lookup_store/route_finder.js +49 -0
  67. package/build/src/router/lookup_store/url_builder.d.ts +52 -0
  68. package/build/src/router/lookup_store/url_builder.js +209 -0
  69. package/build/src/router/main.d.ts +128 -0
  70. package/build/src/router/main.js +316 -0
  71. package/build/src/router/matchers.d.ts +27 -0
  72. package/build/src/router/matchers.js +36 -0
  73. package/build/src/router/parser.d.ts +5 -0
  74. package/build/src/router/parser.js +17 -0
  75. package/build/src/router/resource.d.ts +54 -0
  76. package/build/src/router/resource.js +216 -0
  77. package/build/src/router/route.d.ts +92 -0
  78. package/build/src/router/route.js +293 -0
  79. package/build/src/router/store.d.ts +66 -0
  80. package/build/src/router/store.js +195 -0
  81. package/build/src/server/factories/final_handler.d.ts +10 -0
  82. package/build/src/server/factories/final_handler.js +30 -0
  83. package/build/src/server/factories/middleware_handler.d.ts +8 -0
  84. package/build/src/server/factories/middleware_handler.js +16 -0
  85. package/build/src/server/factories/write_response.d.ts +6 -0
  86. package/build/src/server/factories/write_response.js +24 -0
  87. package/build/{main-29eaaee4.d.ts → src/server/main.d.ts} +18 -13
  88. package/build/src/server/main.js +292 -0
  89. package/build/src/types/base.d.ts +19 -0
  90. package/build/src/types/base.js +9 -0
  91. package/build/src/types/main.d.ts +7 -14
  92. package/build/src/types/main.js +15 -0
  93. package/build/src/types/middleware.d.ts +35 -0
  94. package/build/src/types/middleware.js +9 -0
  95. package/build/src/types/qs.d.ts +68 -0
  96. package/build/src/types/qs.js +9 -0
  97. package/build/src/types/request.d.ts +39 -0
  98. package/build/src/types/request.js +9 -0
  99. package/build/src/types/response.d.ts +45 -0
  100. package/build/src/types/response.js +9 -0
  101. package/build/src/types/route.d.ts +166 -0
  102. package/build/src/types/route.js +9 -0
  103. package/build/src/types/server.d.ts +72 -0
  104. package/build/src/types/server.js +9 -0
  105. package/package.json +6 -3
  106. package/build/chunk-XX72ATFY.js +0 -4388
  107. package/build/main-e5b46c83.d.ts +0 -2210
@@ -0,0 +1,52 @@
1
+ import type { Encryption } from '@adonisjs/encryption';
2
+ import type { Qs } from '../../qs.js';
3
+ import type { RouteFinder } from './route_finder.js';
4
+ /**
5
+ * URL builder class is used to create URIs for pre-registered
6
+ * routes.
7
+ *
8
+ * ```ts
9
+ * const builder = new UrlBuilder(encryption, routeFinder)
10
+ *
11
+ * builder
12
+ * .qs({ sort: 'id' })
13
+ * .params([category.id])
14
+ * .make('categories.posts.index')
15
+ * ```
16
+ */
17
+ export declare class UrlBuilder {
18
+ #private;
19
+ constructor(encryption: Encryption, routeFinder: RouteFinder, qsParser: Qs);
20
+ /**
21
+ * Prefix a custom base URL to the final URI
22
+ */
23
+ prefixUrl(url: string): this;
24
+ /**
25
+ * Disable route lookup. Calling this method considers
26
+ * the "identifier" as the route pattern
27
+ */
28
+ disableRouteLookup(): this;
29
+ /**
30
+ * Append query string to the final URI
31
+ */
32
+ qs(queryString?: Record<string, any>): this;
33
+ /**
34
+ * Specify params to apply to the route pattern
35
+ */
36
+ params(params?: any[] | Record<string, any>): this;
37
+ /**
38
+ * Generate URL for the given route identifier. The identifier can be the
39
+ * route name, controller.method name or the route pattern
40
+ * itself.
41
+ */
42
+ make(identifier: string): string;
43
+ /**
44
+ * Generate a signed URL for the given route identifier. The identifier can be the
45
+ * route name, controller.method name or the route pattern
46
+ * itself.
47
+ */
48
+ makeSigned(identifier: string, options?: {
49
+ expiresIn?: string | number;
50
+ purpose?: string;
51
+ }): string;
52
+ }
@@ -0,0 +1,209 @@
1
+ /*
2
+ * @adonisjs/http-server
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+ import { RuntimeException } from '@poppinss/utils';
10
+ import { parseRoutePattern } from '../parser.js';
11
+ /**
12
+ * URL builder class is used to create URIs for pre-registered
13
+ * routes.
14
+ *
15
+ * ```ts
16
+ * const builder = new UrlBuilder(encryption, routeFinder)
17
+ *
18
+ * builder
19
+ * .qs({ sort: 'id' })
20
+ * .params([category.id])
21
+ * .make('categories.posts.index')
22
+ * ```
23
+ */
24
+ export class UrlBuilder {
25
+ /**
26
+ * Query string parser
27
+ */
28
+ #qsParser;
29
+ /**
30
+ * The parameters to apply on the route
31
+ */
32
+ #params = {};
33
+ /**
34
+ * Query string to append to the route
35
+ */
36
+ #qs = {};
37
+ /**
38
+ * Should we perform the route lookup or just build the
39
+ * given pattern as it is.
40
+ */
41
+ #shouldPerformLookup = true;
42
+ /**
43
+ * BaseURL to append to the constructored URL
44
+ */
45
+ #baseUrl;
46
+ /**
47
+ * Encryption class for making signed URLs
48
+ */
49
+ #encryption;
50
+ /**
51
+ * Route finder for finding route pattern
52
+ */
53
+ #routeFinder;
54
+ constructor(encryption, routeFinder, qsParser) {
55
+ this.#qsParser = qsParser;
56
+ this.#encryption = encryption;
57
+ this.#routeFinder = routeFinder;
58
+ }
59
+ /**
60
+ * Raises exception when wildcard values array is missing or
61
+ * has length of zero.
62
+ */
63
+ #ensureHasWildCardValues(pattern, values) {
64
+ if (!values || !Array.isArray(values) || !values.length) {
65
+ throw new RuntimeException(`Cannot make URL for "${pattern}" route. Invalid value provided for wildcard param`);
66
+ }
67
+ }
68
+ /*
69
+ * Raises exception when value is not defined
70
+ */
71
+ #ensureHasParamValue(pattern, param, value) {
72
+ if (value === undefined || value === null) {
73
+ throw new RuntimeException(`Cannot make URL for "${pattern}" route. Missing value for "${param}" param`);
74
+ }
75
+ }
76
+ /**
77
+ * Processes the pattern against the params
78
+ */
79
+ #processPattern(pattern) {
80
+ const uriSegments = [];
81
+ const paramsArray = Array.isArray(this.#params) ? this.#params : null;
82
+ const paramsObject = !Array.isArray(this.#params) ? this.#params : {};
83
+ let paramsIndex = 0;
84
+ const tokens = parseRoutePattern(pattern);
85
+ for (const token of tokens) {
86
+ /**
87
+ * Expected wildcard param to be at the end always and hence
88
+ * we must break out from the loop
89
+ */
90
+ if (token.type === 0) {
91
+ uriSegments.push(`${token.val}${token.end}`);
92
+ }
93
+ else if (token.type === 2) {
94
+ const values = paramsArray ? paramsArray.slice(paramsIndex) : paramsObject['*'];
95
+ this.#ensureHasWildCardValues(pattern, values);
96
+ uriSegments.push(`${values.join('/')}${token.end}`);
97
+ break;
98
+ }
99
+ else {
100
+ const paramName = token.val;
101
+ const value = paramsArray ? paramsArray[paramsIndex] : paramsObject[paramName];
102
+ /**
103
+ * Type = 1 means param is required
104
+ */
105
+ if (token.type === 1) {
106
+ this.#ensureHasParamValue(pattern, paramName, value);
107
+ }
108
+ paramsIndex++;
109
+ if (value !== undefined && value !== null) {
110
+ uriSegments.push(`${value}${token.end}`);
111
+ }
112
+ }
113
+ }
114
+ return `/${uriSegments.join('/')}`;
115
+ }
116
+ /**
117
+ * Suffix the query string to the URL
118
+ */
119
+ #suffixQueryString(url, qs) {
120
+ if (qs) {
121
+ const queryString = this.#qsParser.stringify(qs);
122
+ url = queryString ? `${url}?${queryString}` : url;
123
+ }
124
+ return url;
125
+ }
126
+ /**
127
+ * Prefixes base URL to the uri string
128
+ */
129
+ #prefixBaseUrl(uri) {
130
+ return this.#baseUrl ? `${this.#baseUrl}${uri}` : uri;
131
+ }
132
+ /**
133
+ * Prefix a custom base URL to the final URI
134
+ */
135
+ prefixUrl(url) {
136
+ this.#baseUrl = url;
137
+ return this;
138
+ }
139
+ /**
140
+ * Disable route lookup. Calling this method considers
141
+ * the "identifier" as the route pattern
142
+ */
143
+ disableRouteLookup() {
144
+ this.#shouldPerformLookup = false;
145
+ return this;
146
+ }
147
+ /**
148
+ * Append query string to the final URI
149
+ */
150
+ qs(queryString) {
151
+ if (!queryString) {
152
+ return this;
153
+ }
154
+ this.#qs = queryString;
155
+ return this;
156
+ }
157
+ /**
158
+ * Specify params to apply to the route pattern
159
+ */
160
+ params(params) {
161
+ if (!params) {
162
+ return this;
163
+ }
164
+ this.#params = params;
165
+ return this;
166
+ }
167
+ /**
168
+ * Generate URL for the given route identifier. The identifier can be the
169
+ * route name, controller.method name or the route pattern
170
+ * itself.
171
+ */
172
+ make(identifier) {
173
+ let url;
174
+ if (this.#shouldPerformLookup) {
175
+ const route = this.#routeFinder.findOrFail(identifier);
176
+ url = this.#processPattern(route.pattern);
177
+ }
178
+ else {
179
+ url = this.#processPattern(identifier);
180
+ }
181
+ return this.#suffixQueryString(this.#prefixBaseUrl(url), this.#qs);
182
+ }
183
+ /**
184
+ * Generate a signed URL for the given route identifier. The identifier can be the
185
+ * route name, controller.method name or the route pattern
186
+ * itself.
187
+ */
188
+ makeSigned(identifier, options) {
189
+ let url;
190
+ if (this.#shouldPerformLookup) {
191
+ const route = this.#routeFinder.findOrFail(identifier);
192
+ url = this.#processPattern(route.pattern);
193
+ }
194
+ else {
195
+ url = this.#processPattern(identifier);
196
+ }
197
+ /*
198
+ * Making the signature from the qualified url. We do not prefix the domain when
199
+ * making signature, since it just makes the signature big.
200
+ *
201
+ * There might be a case, when someone wants to generate signature for the same route
202
+ * on their 2 different domains, but we ignore that case for now and can consider
203
+ * it later (when someone asks for it)
204
+ */
205
+ const signature = this.#encryption.verifier.sign(this.#suffixQueryString(url, this.#qs), options?.expiresIn, options?.purpose);
206
+ const qs = Object.assign({}, this.#qs, { signature });
207
+ return this.#suffixQueryString(this.#prefixBaseUrl(url), qs);
208
+ }
209
+ }
@@ -0,0 +1,128 @@
1
+ import type { Encryption } from '@adonisjs/encryption';
2
+ import type { Application } from '@adonisjs/application';
3
+ import type { Qs } from '../qs.js';
4
+ import { Route } from './route.js';
5
+ import { RouteGroup } from './group.js';
6
+ import { BriskRoute } from './brisk.js';
7
+ import { RouteResource } from './resource.js';
8
+ import { LookupStore } from './lookup_store/main.js';
9
+ import { RouteMatchers as Matchers } from './matchers.js';
10
+ import type { Constructor, LazyImport } from '../types/base.js';
11
+ import type { MiddlewareAsClass, ParsedGlobalMiddleware } from '../types/middleware.js';
12
+ import type { RouteFn, MatchedRoute, RouteMatcher, RouteMatchers, MakeUrlOptions, MakeSignedUrlOptions, GetControllerHandlers } from '../types/route.js';
13
+ /**
14
+ * Router class exposes a unified API to register new routes, group them or
15
+ * create route resources.
16
+ *
17
+ * ```ts
18
+ * const router = new Router()
19
+ *
20
+ * router.get('/', async function () {
21
+ * // handle request
22
+ * })
23
+ * ```
24
+ */
25
+ export declare class Router extends LookupStore {
26
+ #private;
27
+ /**
28
+ * Collection of routes, including route resource and route
29
+ * group. To get a flat list of routes, call `router.toJSON()`
30
+ */
31
+ routes: (Route | RouteResource | RouteGroup | BriskRoute)[];
32
+ /**
33
+ * A flag to know if routes for explicit domains have been registered.
34
+ * The boolean is computed after calling the "commit" method.
35
+ */
36
+ usingDomains: boolean;
37
+ /**
38
+ * Shortcut methods for commonly used route matchers
39
+ */
40
+ matchers: Matchers;
41
+ constructor(app: Application<any>, encryption: Encryption, qsParser: Qs);
42
+ /**
43
+ * Parses the route pattern
44
+ */
45
+ parsePattern(pattern: string, matchers?: RouteMatchers): import("../types/route.js").MatchItRouteToken[];
46
+ /**
47
+ * Define an array of middleware to use on all the routes.
48
+ * Calling this method multiple times pushes to the
49
+ * existing list of middleware
50
+ */
51
+ use(middleware: LazyImport<MiddlewareAsClass>[]): this;
52
+ /**
53
+ * Define a collection of named middleware. The defined collection is
54
+ * not registered anywhere, but instead converted in a new collection
55
+ * of functions you can apply on the routes, or router groups.
56
+ */
57
+ named<NamedMiddleware extends Record<string, LazyImport<MiddlewareAsClass>>>(collection: NamedMiddleware): { [K in keyof NamedMiddleware]: <Args extends import("../types/middleware.js").GetMiddlewareArgs<import("../types/base.js").UnWrapLazyImport<NamedMiddleware[K]>>>(...args: Args) => {
58
+ name: K;
59
+ args: Args[0];
60
+ } & ParsedGlobalMiddleware; };
61
+ /**
62
+ * Add route for a given pattern and methods
63
+ */
64
+ route<T extends Constructor<any>>(pattern: string, methods: string[], handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>;
65
+ /**
66
+ * Define a route that handles all common HTTP methods
67
+ */
68
+ any<T extends Constructor<any>>(pattern: string, handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>;
69
+ /**
70
+ * Define `GET` route
71
+ */
72
+ get<T extends Constructor<any>>(pattern: string, handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>;
73
+ /**
74
+ * Define `POST` route
75
+ */
76
+ post<T extends Constructor<any>>(pattern: string, handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>;
77
+ /**
78
+ * Define `PUT` route
79
+ */
80
+ put<T extends Constructor<any>>(pattern: string, handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>;
81
+ /**
82
+ * Define `PATCH` route
83
+ */
84
+ patch<T extends Constructor<any>>(pattern: string, handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>;
85
+ /**
86
+ * Define `DELETE` route
87
+ */
88
+ delete<T extends Constructor<any>>(pattern: string, handler: string | RouteFn | [LazyImport<T> | T, GetControllerHandlers<T>?]): Route<T>;
89
+ /**
90
+ * Creates a group of routes. A route group can apply transforms
91
+ * to routes in bulk
92
+ */
93
+ group(callback: () => void): RouteGroup;
94
+ /**
95
+ * Registers a route resource with conventional set of routes
96
+ */
97
+ resource(resource: string, controller: string | LazyImport<Constructor<any>> | Constructor<any>): RouteResource;
98
+ /**
99
+ * Register a route resource with shallow nested routes.
100
+ */
101
+ shallowResource(resource: string, controller: string | LazyImport<Constructor<any>> | Constructor<any>): RouteResource;
102
+ /**
103
+ * Returns a brisk route instance for a given URL pattern
104
+ */
105
+ on(pattern: string): BriskRoute;
106
+ /**
107
+ * Define matcher for a given param. The global params are applied
108
+ * on all the routes (unless overridden at the route level).
109
+ */
110
+ where(param: string, matcher: RouteMatcher | string | RegExp): this;
111
+ /**
112
+ * Commit routes to the store. The router is freezed after the
113
+ * commit method is called.
114
+ */
115
+ commit(): void;
116
+ /**
117
+ * Find route for a given URL, method and optionally domain
118
+ */
119
+ match(url: string, method: string, hostname?: string | null): null | MatchedRoute;
120
+ /**
121
+ * Make URL to a pre-registered route
122
+ */
123
+ makeUrl(routeIdentifier: string, params?: any[] | Record<string, any>, options?: MakeUrlOptions): string;
124
+ /**
125
+ * Makes a signed URL to a pre-registered route.
126
+ */
127
+ makeSignedUrl(routeIdentifier: string, params?: any[] | Record<string, any>, options?: MakeSignedUrlOptions): string;
128
+ }
@@ -0,0 +1,316 @@
1
+ /*
2
+ * @adonisjs/http-server
3
+ *
4
+ * (c) AdonisJS
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+ import is from '@sindresorhus/is';
10
+ import { moduleImporter } from '@adonisjs/fold';
11
+ import { RuntimeException } from '@poppinss/utils';
12
+ import { Route } from './route.js';
13
+ import { RouteGroup } from './group.js';
14
+ import { BriskRoute } from './brisk.js';
15
+ import { RoutesStore } from './store.js';
16
+ import { toRoutesJSON } from '../helpers.js';
17
+ import { RouteResource } from './resource.js';
18
+ import { LookupStore } from './lookup_store/main.js';
19
+ import { RouteMatchers as Matchers } from './matchers.js';
20
+ import { defineNamedMiddleware } from '../define_middleware.js';
21
+ import { parseRoutePattern } from './parser.js';
22
+ /**
23
+ * Router class exposes a unified API to register new routes, group them or
24
+ * create route resources.
25
+ *
26
+ * ```ts
27
+ * const router = new Router()
28
+ *
29
+ * router.get('/', async function () {
30
+ * // handle request
31
+ * })
32
+ * ```
33
+ */
34
+ export class Router extends LookupStore {
35
+ /**
36
+ * Application is needed to resolve string based controller expressions
37
+ */
38
+ #app;
39
+ /**
40
+ * Store with tokenized routes
41
+ */
42
+ #store = new RoutesStore();
43
+ /**
44
+ * Global matchers to test route params against regular expressions.
45
+ */
46
+ #globalMatchers = {};
47
+ /**
48
+ * Middleware store to be shared with the routes
49
+ */
50
+ #middleware = [];
51
+ /**
52
+ * A boolean to tell the router that a group is in
53
+ * open state right now
54
+ */
55
+ #openedGroups = [];
56
+ /**
57
+ * Collection of routes, including route resource and route
58
+ * group. To get a flat list of routes, call `router.toJSON()`
59
+ */
60
+ routes = [];
61
+ /**
62
+ * A flag to know if routes for explicit domains have been registered.
63
+ * The boolean is computed after calling the "commit" method.
64
+ */
65
+ usingDomains = false;
66
+ /**
67
+ * Shortcut methods for commonly used route matchers
68
+ */
69
+ matchers = new Matchers();
70
+ constructor(app, encryption, qsParser) {
71
+ super(encryption, qsParser);
72
+ this.#app = app;
73
+ }
74
+ /**
75
+ * Push a give router entity to the list of routes or the
76
+ * recently opened group.
77
+ */
78
+ #pushToRoutes(entity) {
79
+ const openedGroup = this.#openedGroups[this.#openedGroups.length - 1];
80
+ if (openedGroup) {
81
+ openedGroup.routes.push(entity);
82
+ return;
83
+ }
84
+ this.routes.push(entity);
85
+ }
86
+ /**
87
+ * Parses the route pattern
88
+ */
89
+ parsePattern(pattern, matchers) {
90
+ return parseRoutePattern(pattern, matchers);
91
+ }
92
+ /**
93
+ * Define an array of middleware to use on all the routes.
94
+ * Calling this method multiple times pushes to the
95
+ * existing list of middleware
96
+ */
97
+ use(middleware) {
98
+ middleware.forEach((one) => this.#middleware.push(moduleImporter(one, 'handle').toHandleMethod()));
99
+ return this;
100
+ }
101
+ /**
102
+ * Define a collection of named middleware. The defined collection is
103
+ * not registered anywhere, but instead converted in a new collection
104
+ * of functions you can apply on the routes, or router groups.
105
+ */
106
+ named(collection) {
107
+ return defineNamedMiddleware(collection);
108
+ }
109
+ /**
110
+ * Add route for a given pattern and methods
111
+ */
112
+ route(pattern, methods, handler) {
113
+ const route = new Route(this.#app, this.#middleware, {
114
+ pattern,
115
+ methods,
116
+ handler,
117
+ globalMatchers: this.#globalMatchers,
118
+ });
119
+ this.#pushToRoutes(route);
120
+ return route;
121
+ }
122
+ /**
123
+ * Define a route that handles all common HTTP methods
124
+ */
125
+ any(pattern, handler) {
126
+ return this.route(pattern, ['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'], handler);
127
+ }
128
+ /**
129
+ * Define `GET` route
130
+ */
131
+ get(pattern, handler) {
132
+ return this.route(pattern, ['GET', 'HEAD'], handler);
133
+ }
134
+ /**
135
+ * Define `POST` route
136
+ */
137
+ post(pattern, handler) {
138
+ return this.route(pattern, ['POST'], handler);
139
+ }
140
+ /**
141
+ * Define `PUT` route
142
+ */
143
+ put(pattern, handler) {
144
+ return this.route(pattern, ['PUT'], handler);
145
+ }
146
+ /**
147
+ * Define `PATCH` route
148
+ */
149
+ patch(pattern, handler) {
150
+ return this.route(pattern, ['PATCH'], handler);
151
+ }
152
+ /**
153
+ * Define `DELETE` route
154
+ */
155
+ delete(pattern, handler) {
156
+ return this.route(pattern, ['DELETE'], handler);
157
+ }
158
+ /**
159
+ * Creates a group of routes. A route group can apply transforms
160
+ * to routes in bulk
161
+ */
162
+ group(callback) {
163
+ /*
164
+ * Create a new group with empty set of routes
165
+ */
166
+ const group = new RouteGroup([]);
167
+ /**
168
+ * Track group
169
+ */
170
+ this.#pushToRoutes(group);
171
+ /*
172
+ * Track the group, so that the upcoming calls inside the callback
173
+ * can use this group
174
+ */
175
+ this.#openedGroups.push(group);
176
+ /*
177
+ * Execute the callback. Now all registered routes will be
178
+ * collected seperately from the `routes` array
179
+ */
180
+ callback();
181
+ /*
182
+ * Now the callback is over, get rid of the opened group
183
+ */
184
+ this.#openedGroups.pop();
185
+ return group;
186
+ }
187
+ /**
188
+ * Registers a route resource with conventional set of routes
189
+ */
190
+ resource(resource, controller) {
191
+ const resourceInstance = new RouteResource(this.#app, this.#middleware, {
192
+ resource,
193
+ controller,
194
+ shallow: false,
195
+ globalMatchers: this.#globalMatchers,
196
+ });
197
+ this.#pushToRoutes(resourceInstance);
198
+ return resourceInstance;
199
+ }
200
+ /**
201
+ * Register a route resource with shallow nested routes.
202
+ */
203
+ shallowResource(resource, controller) {
204
+ const resourceInstance = new RouteResource(this.#app, this.#middleware, {
205
+ resource,
206
+ controller,
207
+ shallow: true,
208
+ globalMatchers: this.#globalMatchers,
209
+ });
210
+ this.#pushToRoutes(resourceInstance);
211
+ return resourceInstance;
212
+ }
213
+ /**
214
+ * Returns a brisk route instance for a given URL pattern
215
+ */
216
+ on(pattern) {
217
+ const briskRoute = new BriskRoute(this.#app, this.#middleware, {
218
+ pattern,
219
+ globalMatchers: this.#globalMatchers,
220
+ });
221
+ this.#pushToRoutes(briskRoute);
222
+ return briskRoute;
223
+ }
224
+ /**
225
+ * Define matcher for a given param. The global params are applied
226
+ * on all the routes (unless overridden at the route level).
227
+ */
228
+ where(param, matcher) {
229
+ if (typeof matcher === 'string') {
230
+ this.#globalMatchers[param] = { match: new RegExp(matcher) };
231
+ }
232
+ else if (is.regExp(matcher)) {
233
+ this.#globalMatchers[param] = { match: matcher };
234
+ }
235
+ else {
236
+ this.#globalMatchers[param] = matcher;
237
+ }
238
+ return this;
239
+ }
240
+ /**
241
+ * Commit routes to the store. The router is freezed after the
242
+ * commit method is called.
243
+ */
244
+ commit() {
245
+ const routeNamesByDomain = new Map();
246
+ toRoutesJSON(this.routes).forEach((route) => {
247
+ if (!routeNamesByDomain.has(route.domain)) {
248
+ routeNamesByDomain.set(route.domain, new Set());
249
+ }
250
+ const routeNames = routeNamesByDomain.get(route.domain);
251
+ /*
252
+ * Raise error when route name is already in use. Route names have to be unique
253
+ * to ensure that only one route is returned during lookup.
254
+ */
255
+ if (route.name && routeNames.has(route.name)) {
256
+ throw new RuntimeException(`Route with duplicate name found. A route with name "${route.name}" already exists`);
257
+ }
258
+ /*
259
+ * If route has a unique, then track the name for checking duplicates
260
+ */
261
+ if (route.name) {
262
+ routeNames.add(route.name);
263
+ }
264
+ /**
265
+ * Register the route with the lookup store
266
+ */
267
+ this.register(route);
268
+ this.#store.add(route);
269
+ });
270
+ routeNamesByDomain.clear();
271
+ this.usingDomains = this.#store.usingDomains;
272
+ this.routes = [];
273
+ this.#globalMatchers = {};
274
+ this.#middleware = [];
275
+ }
276
+ /**
277
+ * Find route for a given URL, method and optionally domain
278
+ */
279
+ match(url, method, hostname) {
280
+ const matchingDomain = this.#store.matchDomain(hostname);
281
+ return matchingDomain.length
282
+ ? this.#store.match(url, method, {
283
+ tokens: matchingDomain,
284
+ hostname: hostname,
285
+ })
286
+ : this.#store.match(url, method);
287
+ }
288
+ /**
289
+ * Make URL to a pre-registered route
290
+ */
291
+ makeUrl(routeIdentifier, params, options) {
292
+ const normalizedOptions = Object.assign({}, options);
293
+ const builder = normalizedOptions.domain
294
+ ? this.builderForDomain(normalizedOptions.domain)
295
+ : this.builder();
296
+ builder.params(params);
297
+ builder.qs(normalizedOptions.qs);
298
+ normalizedOptions.prefixUrl && builder.prefixUrl(normalizedOptions.prefixUrl);
299
+ normalizedOptions.disableRouteLookup && builder.disableRouteLookup();
300
+ return builder.make(routeIdentifier);
301
+ }
302
+ /**
303
+ * Makes a signed URL to a pre-registered route.
304
+ */
305
+ makeSignedUrl(routeIdentifier, params, options) {
306
+ const normalizedOptions = Object.assign({}, options);
307
+ const builder = normalizedOptions.domain
308
+ ? this.builderForDomain(normalizedOptions.domain)
309
+ : this.builder();
310
+ builder.params(params);
311
+ builder.qs(normalizedOptions.qs);
312
+ normalizedOptions.prefixUrl && builder.prefixUrl(normalizedOptions.prefixUrl);
313
+ normalizedOptions.disableRouteLookup && builder.disableRouteLookup();
314
+ return builder.makeSigned(routeIdentifier, normalizedOptions);
315
+ }
316
+ }