@serwist/routing 9.0.0-preview.16 → 9.0.0-preview.17

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,401 @@
1
+ import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/internal';
2
+
3
+ const defaultMethod = "GET";
4
+ const validMethods = [
5
+ "DELETE",
6
+ "GET",
7
+ "HEAD",
8
+ "PATCH",
9
+ "POST",
10
+ "PUT"
11
+ ];
12
+
13
+ const normalizeHandler = (handler)=>{
14
+ if (handler && typeof handler === "object") {
15
+ if (process.env.NODE_ENV !== "production") {
16
+ assert.hasMethod(handler, "handle", {
17
+ moduleName: "@serwist/routing",
18
+ className: "Route",
19
+ funcName: "constructor",
20
+ paramName: "handler"
21
+ });
22
+ }
23
+ return handler;
24
+ }
25
+ if (process.env.NODE_ENV !== "production") {
26
+ assert.isType(handler, "function", {
27
+ moduleName: "@serwist/routing",
28
+ className: "Route",
29
+ funcName: "constructor",
30
+ paramName: "handler"
31
+ });
32
+ }
33
+ return {
34
+ handle: handler
35
+ };
36
+ };
37
+
38
+ class Route {
39
+ handler;
40
+ match;
41
+ method;
42
+ catchHandler;
43
+ constructor(match, handler, method = defaultMethod){
44
+ if (process.env.NODE_ENV !== "production") {
45
+ assert.isType(match, "function", {
46
+ moduleName: "@serwist/routing",
47
+ className: "Route",
48
+ funcName: "constructor",
49
+ paramName: "match"
50
+ });
51
+ if (method) {
52
+ assert.isOneOf(method, validMethods, {
53
+ paramName: "method"
54
+ });
55
+ }
56
+ }
57
+ this.handler = normalizeHandler(handler);
58
+ this.match = match;
59
+ this.method = method;
60
+ }
61
+ setCatchHandler(handler) {
62
+ this.catchHandler = normalizeHandler(handler);
63
+ }
64
+ }
65
+
66
+ class RegExpRoute extends Route {
67
+ constructor(regExp, handler, method){
68
+ if (process.env.NODE_ENV !== "production") {
69
+ assert.isInstance(regExp, RegExp, {
70
+ moduleName: "@serwist/routing",
71
+ className: "RegExpRoute",
72
+ funcName: "constructor",
73
+ paramName: "pattern"
74
+ });
75
+ }
76
+ const match = ({ url })=>{
77
+ const result = regExp.exec(url.href);
78
+ if (!result) {
79
+ return;
80
+ }
81
+ if (url.origin !== location.origin && result.index !== 0) {
82
+ if (process.env.NODE_ENV !== "production") {
83
+ logger.debug(`The regular expression '${regExp.toString()}' only partially matched against the cross-origin URL '${url.toString()}'. RegExpRoute's will only handle cross-origin requests if they match the entire URL.`);
84
+ }
85
+ return;
86
+ }
87
+ return result.slice(1);
88
+ };
89
+ super(match, handler, method);
90
+ }
91
+ }
92
+
93
+ class Router {
94
+ _routes;
95
+ _defaultHandlerMap;
96
+ _catchHandler;
97
+ constructor(){
98
+ this._routes = new Map();
99
+ this._defaultHandlerMap = new Map();
100
+ }
101
+ get routes() {
102
+ return this._routes;
103
+ }
104
+ addFetchListener() {
105
+ self.addEventListener("fetch", (event)=>{
106
+ const { request } = event;
107
+ const responsePromise = this.handleRequest({
108
+ request,
109
+ event
110
+ });
111
+ if (responsePromise) {
112
+ event.respondWith(responsePromise);
113
+ }
114
+ });
115
+ }
116
+ addCacheListener() {
117
+ self.addEventListener("message", (event)=>{
118
+ if (event.data && event.data.type === "CACHE_URLS") {
119
+ const { payload } = event.data;
120
+ if (process.env.NODE_ENV !== "production") {
121
+ logger.debug("Caching URLs from the window", payload.urlsToCache);
122
+ }
123
+ const requestPromises = Promise.all(payload.urlsToCache.map((entry)=>{
124
+ if (typeof entry === "string") {
125
+ entry = [
126
+ entry
127
+ ];
128
+ }
129
+ const request = new Request(...entry);
130
+ return this.handleRequest({
131
+ request,
132
+ event
133
+ });
134
+ }));
135
+ event.waitUntil(requestPromises);
136
+ if (event.ports?.[0]) {
137
+ void requestPromises.then(()=>event.ports[0].postMessage(true));
138
+ }
139
+ }
140
+ });
141
+ }
142
+ handleRequest({ request, event }) {
143
+ if (process.env.NODE_ENV !== "production") {
144
+ assert.isInstance(request, Request, {
145
+ moduleName: "@serwist/routing",
146
+ className: "Router",
147
+ funcName: "handleRequest",
148
+ paramName: "options.request"
149
+ });
150
+ }
151
+ const url = new URL(request.url, location.href);
152
+ if (!url.protocol.startsWith("http")) {
153
+ if (process.env.NODE_ENV !== "production") {
154
+ logger.debug("The Serwist router only supports URLs that start with 'http'.");
155
+ }
156
+ return;
157
+ }
158
+ const sameOrigin = url.origin === location.origin;
159
+ const { params, route } = this.findMatchingRoute({
160
+ event,
161
+ request,
162
+ sameOrigin,
163
+ url
164
+ });
165
+ let handler = route?.handler;
166
+ const debugMessages = [];
167
+ if (process.env.NODE_ENV !== "production") {
168
+ if (handler) {
169
+ debugMessages.push([
170
+ "Found a route to handle this request:",
171
+ route
172
+ ]);
173
+ if (params) {
174
+ debugMessages.push([
175
+ `Passing the following params to the route's handler:`,
176
+ params
177
+ ]);
178
+ }
179
+ }
180
+ }
181
+ const method = request.method;
182
+ if (!handler && this._defaultHandlerMap.has(method)) {
183
+ if (process.env.NODE_ENV !== "production") {
184
+ debugMessages.push(`Failed to find a matching route. Falling back to the default handler for ${method}.`);
185
+ }
186
+ handler = this._defaultHandlerMap.get(method);
187
+ }
188
+ if (!handler) {
189
+ if (process.env.NODE_ENV !== "production") {
190
+ logger.debug(`No route found for: ${getFriendlyURL(url)}`);
191
+ }
192
+ return;
193
+ }
194
+ if (process.env.NODE_ENV !== "production") {
195
+ logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
196
+ for (const msg of debugMessages){
197
+ if (Array.isArray(msg)) {
198
+ logger.log(...msg);
199
+ } else {
200
+ logger.log(msg);
201
+ }
202
+ }
203
+ logger.groupEnd();
204
+ }
205
+ let responsePromise;
206
+ try {
207
+ responsePromise = handler.handle({
208
+ url,
209
+ request,
210
+ event,
211
+ params
212
+ });
213
+ } catch (err) {
214
+ responsePromise = Promise.reject(err);
215
+ }
216
+ const catchHandler = route?.catchHandler;
217
+ if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
218
+ responsePromise = responsePromise.catch(async (err)=>{
219
+ if (catchHandler) {
220
+ if (process.env.NODE_ENV !== "production") {
221
+ logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
222
+ logger.error("Error thrown by:", route);
223
+ logger.error(err);
224
+ logger.groupEnd();
225
+ }
226
+ try {
227
+ return await catchHandler.handle({
228
+ url,
229
+ request,
230
+ event,
231
+ params
232
+ });
233
+ } catch (catchErr) {
234
+ if (catchErr instanceof Error) {
235
+ err = catchErr;
236
+ }
237
+ }
238
+ }
239
+ if (this._catchHandler) {
240
+ if (process.env.NODE_ENV !== "production") {
241
+ logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
242
+ logger.error("Error thrown by:", route);
243
+ logger.error(err);
244
+ logger.groupEnd();
245
+ }
246
+ return this._catchHandler.handle({
247
+ url,
248
+ request,
249
+ event
250
+ });
251
+ }
252
+ throw err;
253
+ });
254
+ }
255
+ return responsePromise;
256
+ }
257
+ findMatchingRoute({ url, sameOrigin, request, event }) {
258
+ const routes = this._routes.get(request.method) || [];
259
+ for (const route of routes){
260
+ let params;
261
+ const matchResult = route.match({
262
+ url,
263
+ sameOrigin,
264
+ request,
265
+ event
266
+ });
267
+ if (matchResult) {
268
+ if (process.env.NODE_ENV !== "production") {
269
+ if (matchResult instanceof Promise) {
270
+ logger.warn(`While routing ${getFriendlyURL(url)}, an async matchCallback function was used. Please convert the following route to use a synchronous matchCallback function:`, route);
271
+ }
272
+ }
273
+ params = matchResult;
274
+ if (Array.isArray(params) && params.length === 0) {
275
+ params = undefined;
276
+ } else if (matchResult.constructor === Object && Object.keys(matchResult).length === 0) {
277
+ params = undefined;
278
+ } else if (typeof matchResult === "boolean") {
279
+ params = undefined;
280
+ }
281
+ return {
282
+ route,
283
+ params
284
+ };
285
+ }
286
+ }
287
+ return {};
288
+ }
289
+ setDefaultHandler(handler, method = defaultMethod) {
290
+ this._defaultHandlerMap.set(method, normalizeHandler(handler));
291
+ }
292
+ setCatchHandler(handler) {
293
+ this._catchHandler = normalizeHandler(handler);
294
+ }
295
+ registerRoute(route) {
296
+ if (process.env.NODE_ENV !== "production") {
297
+ assert.isType(route, "object", {
298
+ moduleName: "@serwist/routing",
299
+ className: "Router",
300
+ funcName: "registerRoute",
301
+ paramName: "route"
302
+ });
303
+ assert.hasMethod(route, "match", {
304
+ moduleName: "@serwist/routing",
305
+ className: "Router",
306
+ funcName: "registerRoute",
307
+ paramName: "route"
308
+ });
309
+ assert.isType(route.handler, "object", {
310
+ moduleName: "@serwist/routing",
311
+ className: "Router",
312
+ funcName: "registerRoute",
313
+ paramName: "route"
314
+ });
315
+ assert.hasMethod(route.handler, "handle", {
316
+ moduleName: "@serwist/routing",
317
+ className: "Router",
318
+ funcName: "registerRoute",
319
+ paramName: "route.handler"
320
+ });
321
+ assert.isType(route.method, "string", {
322
+ moduleName: "@serwist/routing",
323
+ className: "Router",
324
+ funcName: "registerRoute",
325
+ paramName: "route.method"
326
+ });
327
+ }
328
+ if (!this._routes.has(route.method)) {
329
+ this._routes.set(route.method, []);
330
+ }
331
+ this._routes.get(route.method).push(route);
332
+ }
333
+ unregisterRoute(route) {
334
+ if (!this._routes.has(route.method)) {
335
+ throw new SerwistError("unregister-route-but-not-found-with-method", {
336
+ method: route.method
337
+ });
338
+ }
339
+ const routeIndex = this._routes.get(route.method).indexOf(route);
340
+ if (routeIndex > -1) {
341
+ this._routes.get(route.method).splice(routeIndex, 1);
342
+ } else {
343
+ throw new SerwistError("unregister-route-route-not-registered");
344
+ }
345
+ }
346
+ }
347
+
348
+ let defaultRouter;
349
+ const getOrCreateDefaultRouter = ()=>{
350
+ if (!defaultRouter) {
351
+ defaultRouter = new Router();
352
+ defaultRouter.addFetchListener();
353
+ defaultRouter.addCacheListener();
354
+ }
355
+ return defaultRouter;
356
+ };
357
+
358
+ const parseRoute = (capture, handler, method)=>{
359
+ let route;
360
+ if (typeof capture === "string") {
361
+ const captureUrl = new URL(capture, location.href);
362
+ if (process.env.NODE_ENV !== "production") {
363
+ if (!(capture.startsWith("/") || capture.startsWith("http"))) {
364
+ throw new SerwistError("invalid-string", {
365
+ moduleName: "@serwist/routing",
366
+ funcName: "registerRoute",
367
+ paramName: "capture"
368
+ });
369
+ }
370
+ const valueToCheck = capture.startsWith("http") ? captureUrl.pathname : capture;
371
+ const wildcards = "[*:?+]";
372
+ if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
373
+ logger.debug(`The '$capture' parameter contains an Express-style wildcard character (${wildcards}). Strings are now always interpreted as exact matches; use a RegExp for partial or wildcard matches.`);
374
+ }
375
+ }
376
+ const matchCallback = ({ url })=>{
377
+ if (process.env.NODE_ENV !== "production") {
378
+ if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
379
+ logger.debug(`${capture} only partially matches the cross-origin URL ${url.toString()}. This route will only handle cross-origin requests if they match the entire URL.`);
380
+ }
381
+ }
382
+ return url.href === captureUrl.href;
383
+ };
384
+ route = new Route(matchCallback, handler, method);
385
+ } else if (capture instanceof RegExp) {
386
+ route = new RegExpRoute(capture, handler, method);
387
+ } else if (typeof capture === "function") {
388
+ route = new Route(capture, handler, method);
389
+ } else if (capture instanceof Route) {
390
+ route = capture;
391
+ } else {
392
+ throw new SerwistError("unsupported-route-type", {
393
+ moduleName: "@serwist/routing",
394
+ funcName: "registerRoute",
395
+ paramName: "capture"
396
+ });
397
+ }
398
+ return route;
399
+ };
400
+
401
+ export { Route as R, RegExpRoute as a, Router as b, getOrCreateDefaultRouter as g, parseRoute as p };
@@ -0,0 +1,4 @@
1
+ import { getOrCreateDefaultRouter } from "./utils/getOrCreateDefaultRouter.js";
2
+ import { parseRoute } from "./utils/parseRoute.js";
3
+ export { parseRoute, getOrCreateDefaultRouter };
4
+ //# sourceMappingURL=index.internal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.internal.d.ts","sourceRoot":"","sources":["../src/index.internal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAC/E,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAEnD,OAAO,EAAE,UAAU,EAAE,wBAAwB,EAAE,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { g as getOrCreateDefaultRouter, p as parseRoute } from './chunks/parseRoute.js';
2
+ import '@serwist/core/internal';
package/dist/index.js CHANGED
@@ -1,67 +1,6 @@
1
- import { assert, logger, getFriendlyURL, SerwistError } from '@serwist/core/internal';
2
-
3
- const defaultMethod = "GET";
4
- const validMethods = [
5
- "DELETE",
6
- "GET",
7
- "HEAD",
8
- "PATCH",
9
- "POST",
10
- "PUT"
11
- ];
12
-
13
- const normalizeHandler = (handler)=>{
14
- if (handler && typeof handler === "object") {
15
- if (process.env.NODE_ENV !== "production") {
16
- assert.hasMethod(handler, "handle", {
17
- moduleName: "@serwist/routing",
18
- className: "Route",
19
- funcName: "constructor",
20
- paramName: "handler"
21
- });
22
- }
23
- return handler;
24
- }
25
- if (process.env.NODE_ENV !== "production") {
26
- assert.isType(handler, "function", {
27
- moduleName: "@serwist/routing",
28
- className: "Route",
29
- funcName: "constructor",
30
- paramName: "handler"
31
- });
32
- }
33
- return {
34
- handle: handler
35
- };
36
- };
37
-
38
- class Route {
39
- handler;
40
- match;
41
- method;
42
- catchHandler;
43
- constructor(match, handler, method = defaultMethod){
44
- if (process.env.NODE_ENV !== "production") {
45
- assert.isType(match, "function", {
46
- moduleName: "@serwist/routing",
47
- className: "Route",
48
- funcName: "constructor",
49
- paramName: "match"
50
- });
51
- if (method) {
52
- assert.isOneOf(method, validMethods, {
53
- paramName: "method"
54
- });
55
- }
56
- }
57
- this.handler = normalizeHandler(handler);
58
- this.match = match;
59
- this.method = method;
60
- }
61
- setCatchHandler(handler) {
62
- this.catchHandler = normalizeHandler(handler);
63
- }
64
- }
1
+ import { assert, logger } from '@serwist/core/internal';
2
+ import { R as Route, p as parseRoute, g as getOrCreateDefaultRouter } from './chunks/parseRoute.js';
3
+ export { a as RegExpRoute, b as Router } from './chunks/parseRoute.js';
65
4
 
66
5
  class NavigationRoute extends Route {
67
6
  _allowlist;
@@ -113,338 +52,8 @@ class NavigationRoute extends Route {
113
52
  }
114
53
  }
115
54
 
116
- class RegExpRoute extends Route {
117
- constructor(regExp, handler, method){
118
- if (process.env.NODE_ENV !== "production") {
119
- assert.isInstance(regExp, RegExp, {
120
- moduleName: "@serwist/routing",
121
- className: "RegExpRoute",
122
- funcName: "constructor",
123
- paramName: "pattern"
124
- });
125
- }
126
- const match = ({ url })=>{
127
- const result = regExp.exec(url.href);
128
- if (!result) {
129
- return;
130
- }
131
- if (url.origin !== location.origin && result.index !== 0) {
132
- if (process.env.NODE_ENV !== "production") {
133
- logger.debug(`The regular expression '${regExp.toString()}' only partially matched against the cross-origin URL '${url.toString()}'. RegExpRoute's will only handle cross-origin requests if they match the entire URL.`);
134
- }
135
- return;
136
- }
137
- return result.slice(1);
138
- };
139
- super(match, handler, method);
140
- }
141
- }
142
-
143
- class Router {
144
- _routes;
145
- _defaultHandlerMap;
146
- _catchHandler;
147
- constructor(){
148
- this._routes = new Map();
149
- this._defaultHandlerMap = new Map();
150
- }
151
- get routes() {
152
- return this._routes;
153
- }
154
- addFetchListener() {
155
- self.addEventListener("fetch", (event)=>{
156
- const { request } = event;
157
- const responsePromise = this.handleRequest({
158
- request,
159
- event
160
- });
161
- if (responsePromise) {
162
- event.respondWith(responsePromise);
163
- }
164
- });
165
- }
166
- addCacheListener() {
167
- self.addEventListener("message", (event)=>{
168
- if (event.data && event.data.type === "CACHE_URLS") {
169
- const { payload } = event.data;
170
- if (process.env.NODE_ENV !== "production") {
171
- logger.debug("Caching URLs from the window", payload.urlsToCache);
172
- }
173
- const requestPromises = Promise.all(payload.urlsToCache.map((entry)=>{
174
- if (typeof entry === "string") {
175
- entry = [
176
- entry
177
- ];
178
- }
179
- const request = new Request(...entry);
180
- return this.handleRequest({
181
- request,
182
- event
183
- });
184
- }));
185
- event.waitUntil(requestPromises);
186
- if (event.ports?.[0]) {
187
- void requestPromises.then(()=>event.ports[0].postMessage(true));
188
- }
189
- }
190
- });
191
- }
192
- handleRequest({ request, event }) {
193
- if (process.env.NODE_ENV !== "production") {
194
- assert.isInstance(request, Request, {
195
- moduleName: "@serwist/routing",
196
- className: "Router",
197
- funcName: "handleRequest",
198
- paramName: "options.request"
199
- });
200
- }
201
- const url = new URL(request.url, location.href);
202
- if (!url.protocol.startsWith("http")) {
203
- if (process.env.NODE_ENV !== "production") {
204
- logger.debug("The Serwist router only supports URLs that start with 'http'.");
205
- }
206
- return;
207
- }
208
- const sameOrigin = url.origin === location.origin;
209
- const { params, route } = this.findMatchingRoute({
210
- event,
211
- request,
212
- sameOrigin,
213
- url
214
- });
215
- let handler = route?.handler;
216
- const debugMessages = [];
217
- if (process.env.NODE_ENV !== "production") {
218
- if (handler) {
219
- debugMessages.push([
220
- "Found a route to handle this request:",
221
- route
222
- ]);
223
- if (params) {
224
- debugMessages.push([
225
- `Passing the following params to the route's handler:`,
226
- params
227
- ]);
228
- }
229
- }
230
- }
231
- const method = request.method;
232
- if (!handler && this._defaultHandlerMap.has(method)) {
233
- if (process.env.NODE_ENV !== "production") {
234
- debugMessages.push(`Failed to find a matching route. Falling back to the default handler for ${method}.`);
235
- }
236
- handler = this._defaultHandlerMap.get(method);
237
- }
238
- if (!handler) {
239
- if (process.env.NODE_ENV !== "production") {
240
- logger.debug(`No route found for: ${getFriendlyURL(url)}`);
241
- }
242
- return;
243
- }
244
- if (process.env.NODE_ENV !== "production") {
245
- logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
246
- for (const msg of debugMessages){
247
- if (Array.isArray(msg)) {
248
- logger.log(...msg);
249
- } else {
250
- logger.log(msg);
251
- }
252
- }
253
- logger.groupEnd();
254
- }
255
- let responsePromise;
256
- try {
257
- responsePromise = handler.handle({
258
- url,
259
- request,
260
- event,
261
- params
262
- });
263
- } catch (err) {
264
- responsePromise = Promise.reject(err);
265
- }
266
- const catchHandler = route?.catchHandler;
267
- if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
268
- responsePromise = responsePromise.catch(async (err)=>{
269
- if (catchHandler) {
270
- if (process.env.NODE_ENV !== "production") {
271
- logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
272
- logger.error("Error thrown by:", route);
273
- logger.error(err);
274
- logger.groupEnd();
275
- }
276
- try {
277
- return await catchHandler.handle({
278
- url,
279
- request,
280
- event,
281
- params
282
- });
283
- } catch (catchErr) {
284
- if (catchErr instanceof Error) {
285
- err = catchErr;
286
- }
287
- }
288
- }
289
- if (this._catchHandler) {
290
- if (process.env.NODE_ENV !== "production") {
291
- logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
292
- logger.error("Error thrown by:", route);
293
- logger.error(err);
294
- logger.groupEnd();
295
- }
296
- return this._catchHandler.handle({
297
- url,
298
- request,
299
- event
300
- });
301
- }
302
- throw err;
303
- });
304
- }
305
- return responsePromise;
306
- }
307
- findMatchingRoute({ url, sameOrigin, request, event }) {
308
- const routes = this._routes.get(request.method) || [];
309
- for (const route of routes){
310
- let params;
311
- const matchResult = route.match({
312
- url,
313
- sameOrigin,
314
- request,
315
- event
316
- });
317
- if (matchResult) {
318
- if (process.env.NODE_ENV !== "production") {
319
- if (matchResult instanceof Promise) {
320
- logger.warn(`While routing ${getFriendlyURL(url)}, an async matchCallback function was used. Please convert the following route to use a synchronous matchCallback function:`, route);
321
- }
322
- }
323
- params = matchResult;
324
- if (Array.isArray(params) && params.length === 0) {
325
- params = undefined;
326
- } else if (matchResult.constructor === Object && Object.keys(matchResult).length === 0) {
327
- params = undefined;
328
- } else if (typeof matchResult === "boolean") {
329
- params = undefined;
330
- }
331
- return {
332
- route,
333
- params
334
- };
335
- }
336
- }
337
- return {};
338
- }
339
- setDefaultHandler(handler, method = defaultMethod) {
340
- this._defaultHandlerMap.set(method, normalizeHandler(handler));
341
- }
342
- setCatchHandler(handler) {
343
- this._catchHandler = normalizeHandler(handler);
344
- }
345
- registerRoute(route) {
346
- if (process.env.NODE_ENV !== "production") {
347
- assert.isType(route, "object", {
348
- moduleName: "@serwist/routing",
349
- className: "Router",
350
- funcName: "registerRoute",
351
- paramName: "route"
352
- });
353
- assert.hasMethod(route, "match", {
354
- moduleName: "@serwist/routing",
355
- className: "Router",
356
- funcName: "registerRoute",
357
- paramName: "route"
358
- });
359
- assert.isType(route.handler, "object", {
360
- moduleName: "@serwist/routing",
361
- className: "Router",
362
- funcName: "registerRoute",
363
- paramName: "route"
364
- });
365
- assert.hasMethod(route.handler, "handle", {
366
- moduleName: "@serwist/routing",
367
- className: "Router",
368
- funcName: "registerRoute",
369
- paramName: "route.handler"
370
- });
371
- assert.isType(route.method, "string", {
372
- moduleName: "@serwist/routing",
373
- className: "Router",
374
- funcName: "registerRoute",
375
- paramName: "route.method"
376
- });
377
- }
378
- if (!this._routes.has(route.method)) {
379
- this._routes.set(route.method, []);
380
- }
381
- this._routes.get(route.method).push(route);
382
- }
383
- unregisterRoute(route) {
384
- if (!this._routes.has(route.method)) {
385
- throw new SerwistError("unregister-route-but-not-found-with-method", {
386
- method: route.method
387
- });
388
- }
389
- const routeIndex = this._routes.get(route.method).indexOf(route);
390
- if (routeIndex > -1) {
391
- this._routes.get(route.method).splice(routeIndex, 1);
392
- } else {
393
- throw new SerwistError("unregister-route-route-not-registered");
394
- }
395
- }
396
- }
397
-
398
- let defaultRouter;
399
- const getOrCreateDefaultRouter = ()=>{
400
- if (!defaultRouter) {
401
- defaultRouter = new Router();
402
- defaultRouter.addFetchListener();
403
- defaultRouter.addCacheListener();
404
- }
405
- return defaultRouter;
406
- };
407
-
408
55
  const registerRoute = (capture, handler, method)=>{
409
- let route;
410
- if (typeof capture === "string") {
411
- const captureUrl = new URL(capture, location.href);
412
- if (process.env.NODE_ENV !== "production") {
413
- if (!(capture.startsWith("/") || capture.startsWith("http"))) {
414
- throw new SerwistError("invalid-string", {
415
- moduleName: "@serwist/routing",
416
- funcName: "registerRoute",
417
- paramName: "capture"
418
- });
419
- }
420
- const valueToCheck = capture.startsWith("http") ? captureUrl.pathname : capture;
421
- const wildcards = "[*:?+]";
422
- if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
423
- logger.debug(`The '$capture' parameter contains an Express-style wildcard character (${wildcards}). Strings are now always interpreted as exact matches; use a RegExp for partial or wildcard matches.`);
424
- }
425
- }
426
- const matchCallback = ({ url })=>{
427
- if (process.env.NODE_ENV !== "production") {
428
- if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
429
- logger.debug(`${capture} only partially matches the cross-origin URL ${url.toString()}. This route will only handle cross-origin requests if they match the entire URL.`);
430
- }
431
- }
432
- return url.href === captureUrl.href;
433
- };
434
- route = new Route(matchCallback, handler, method);
435
- } else if (capture instanceof RegExp) {
436
- route = new RegExpRoute(capture, handler, method);
437
- } else if (typeof capture === "function") {
438
- route = new Route(capture, handler, method);
439
- } else if (capture instanceof Route) {
440
- route = capture;
441
- } else {
442
- throw new SerwistError("unsupported-route-type", {
443
- moduleName: "@serwist/routing",
444
- funcName: "registerRoute",
445
- paramName: "capture"
446
- });
447
- }
56
+ const route = parseRoute(capture, handler, method);
448
57
  const defaultRouter = getOrCreateDefaultRouter();
449
58
  defaultRouter.registerRoute(route);
450
59
  return route;
@@ -465,4 +74,4 @@ const unregisterRoute = (route)=>{
465
74
  defaultRouter.unregisterRoute(route);
466
75
  };
467
76
 
468
- export { NavigationRoute, RegExpRoute, Route, Router, registerRoute, setCatchHandler, setDefaultHandler, unregisterRoute };
77
+ export { NavigationRoute, Route, registerRoute, setCatchHandler, setDefaultHandler, unregisterRoute };
@@ -1 +1 @@
1
- {"version":3,"file":"registerRoute.d.ts","sourceRoot":"","sources":["../src/registerRoute.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAItE,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAGvD;;;;;;;;;GASG;AACH,eAAO,MAAM,aAAa,YAAa,MAAM,GAAG,MAAM,GAAG,kBAAkB,GAAG,KAAK,YAAY,YAAY,WAAW,UAAU,KAAG,KA8DlI,CAAC"}
1
+ {"version":3,"file":"registerRoute.d.ts","sourceRoot":"","sources":["../src/registerRoute.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAEtE,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAIvD;;;;;;;;;GASG;AACH,eAAO,MAAM,aAAa,YAAa,MAAM,GAAG,MAAM,GAAG,kBAAkB,GAAG,KAAK,YAAY,YAAY,WAAW,UAAU,KAAG,KAOlI,CAAC"}
@@ -0,0 +1,5 @@
1
+ import type { RouteHandler, RouteMatchCallback } from "@serwist/core";
2
+ import { Route } from "../Route.js";
3
+ import type { HTTPMethod } from "./constants.js";
4
+ export declare const parseRoute: (capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod) => Route;
5
+ //# sourceMappingURL=parseRoute.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parseRoute.d.ts","sourceRoot":"","sources":["../../src/utils/parseRoute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAItE,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACpC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAEjD,eAAO,MAAM,UAAU,YAAa,MAAM,GAAG,MAAM,GAAG,kBAAkB,GAAG,KAAK,YAAY,YAAY,WAAW,UAAU,KAAG,KA2D/H,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@serwist/routing",
3
- "version": "9.0.0-preview.16",
3
+ "version": "9.0.0-preview.17",
4
4
  "type": "module",
5
5
  "description": "A service worker helper library to route request URLs to handlers.",
6
6
  "files": [
@@ -22,20 +22,31 @@
22
22
  "homepage": "https://serwist.pages.dev",
23
23
  "main": "./dist/index.js",
24
24
  "types": "./dist/index.d.ts",
25
+ "typesVersions": {
26
+ "*": {
27
+ "internal": [
28
+ "./dist/index.internal.d.ts"
29
+ ]
30
+ }
31
+ },
25
32
  "exports": {
26
33
  ".": {
27
34
  "types": "./dist/index.d.ts",
28
35
  "default": "./dist/index.js"
29
36
  },
37
+ "./internal": {
38
+ "types": "./dist/index.internal.d.ts",
39
+ "default": "./dist/index.internal.js"
40
+ },
30
41
  "./package.json": "./package.json"
31
42
  },
32
43
  "dependencies": {
33
- "@serwist/core": "9.0.0-preview.16"
44
+ "@serwist/core": "9.0.0-preview.17"
34
45
  },
35
46
  "devDependencies": {
36
47
  "rollup": "4.13.0",
37
48
  "typescript": "5.5.0-dev.20240323",
38
- "@serwist/constants": "9.0.0-preview.16"
49
+ "@serwist/constants": "9.0.0-preview.17"
39
50
  },
40
51
  "peerDependencies": {
41
52
  "typescript": ">=5.0.0"
@@ -0,0 +1,4 @@
1
+ import { getOrCreateDefaultRouter } from "./utils/getOrCreateDefaultRouter.js";
2
+ import { parseRoute } from "./utils/parseRoute.js";
3
+
4
+ export { parseRoute, getOrCreateDefaultRouter };
@@ -7,12 +7,11 @@
7
7
  */
8
8
 
9
9
  import type { RouteHandler, RouteMatchCallback } from "@serwist/core";
10
- import { SerwistError, logger } from "@serwist/core/internal";
11
10
 
12
- import { RegExpRoute } from "./RegExpRoute.js";
13
11
  import { Route } from "./Route.js";
14
12
  import type { HTTPMethod } from "./utils/constants.js";
15
13
  import { getOrCreateDefaultRouter } from "./utils/getOrCreateDefaultRouter.js";
14
+ import { parseRoute } from "./utils/parseRoute.js";
16
15
 
17
16
  /**
18
17
  * Registers a RegExp, string, or function with a caching
@@ -25,62 +24,7 @@ import { getOrCreateDefaultRouter } from "./utils/getOrCreateDefaultRouter.js";
25
24
  * @returns The generated `Route`.
26
25
  */
27
26
  export const registerRoute = (capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod): Route => {
28
- let route: Route;
29
-
30
- if (typeof capture === "string") {
31
- const captureUrl = new URL(capture, location.href);
32
-
33
- if (process.env.NODE_ENV !== "production") {
34
- if (!(capture.startsWith("/") || capture.startsWith("http"))) {
35
- throw new SerwistError("invalid-string", {
36
- moduleName: "@serwist/routing",
37
- funcName: "registerRoute",
38
- paramName: "capture",
39
- });
40
- }
41
-
42
- // We want to check if Express-style wildcards are in the pathname only.
43
- // TODO: Remove this log message in v4.
44
- const valueToCheck = capture.startsWith("http") ? captureUrl.pathname : capture;
45
-
46
- // See https://github.com/pillarjs/path-to-regexp#parameters
47
- const wildcards = "[*:?+]";
48
- if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
49
- logger.debug(
50
- `The '$capture' parameter contains an Express-style wildcard character (${wildcards}). Strings are now always interpreted as exact matches; use a RegExp for partial or wildcard matches.`,
51
- );
52
- }
53
- }
54
-
55
- const matchCallback: RouteMatchCallback = ({ url }) => {
56
- if (process.env.NODE_ENV !== "production") {
57
- if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
58
- logger.debug(
59
- `${capture} only partially matches the cross-origin URL ${url.toString()}. This route will only handle cross-origin requests if they match the entire URL.`,
60
- );
61
- }
62
- }
63
-
64
- return url.href === captureUrl.href;
65
- };
66
-
67
- // If `capture` is a string then `handler` and `method` must be present.
68
- route = new Route(matchCallback, handler!, method);
69
- } else if (capture instanceof RegExp) {
70
- // If `capture` is a `RegExp` then `handler` and `method` must be present.
71
- route = new RegExpRoute(capture, handler!, method);
72
- } else if (typeof capture === "function") {
73
- // If `capture` is a function then `handler` and `method` must be present.
74
- route = new Route(capture, handler!, method);
75
- } else if (capture instanceof Route) {
76
- route = capture;
77
- } else {
78
- throw new SerwistError("unsupported-route-type", {
79
- moduleName: "@serwist/routing",
80
- funcName: "registerRoute",
81
- paramName: "capture",
82
- });
83
- }
27
+ const route = parseRoute(capture, handler, method);
84
28
 
85
29
  const defaultRouter = getOrCreateDefaultRouter();
86
30
  defaultRouter.registerRoute(route);
@@ -0,0 +1,67 @@
1
+ import type { RouteHandler, RouteMatchCallback } from "@serwist/core";
2
+ import { SerwistError, logger } from "@serwist/core/internal";
3
+
4
+ import { RegExpRoute } from "../RegExpRoute.js";
5
+ import { Route } from "../Route.js";
6
+ import type { HTTPMethod } from "./constants.js";
7
+
8
+ export const parseRoute = (capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod): Route => {
9
+ let route: Route;
10
+
11
+ if (typeof capture === "string") {
12
+ const captureUrl = new URL(capture, location.href);
13
+
14
+ if (process.env.NODE_ENV !== "production") {
15
+ if (!(capture.startsWith("/") || capture.startsWith("http"))) {
16
+ throw new SerwistError("invalid-string", {
17
+ moduleName: "@serwist/routing",
18
+ funcName: "registerRoute",
19
+ paramName: "capture",
20
+ });
21
+ }
22
+
23
+ // We want to check if Express-style wildcards are in the pathname only.
24
+ // TODO: Remove this log message in v4.
25
+ const valueToCheck = capture.startsWith("http") ? captureUrl.pathname : capture;
26
+
27
+ // See https://github.com/pillarjs/path-to-regexp#parameters
28
+ const wildcards = "[*:?+]";
29
+ if (new RegExp(`${wildcards}`).exec(valueToCheck)) {
30
+ logger.debug(
31
+ `The '$capture' parameter contains an Express-style wildcard character (${wildcards}). Strings are now always interpreted as exact matches; use a RegExp for partial or wildcard matches.`,
32
+ );
33
+ }
34
+ }
35
+
36
+ const matchCallback: RouteMatchCallback = ({ url }) => {
37
+ if (process.env.NODE_ENV !== "production") {
38
+ if (url.pathname === captureUrl.pathname && url.origin !== captureUrl.origin) {
39
+ logger.debug(
40
+ `${capture} only partially matches the cross-origin URL ${url.toString()}. This route will only handle cross-origin requests if they match the entire URL.`,
41
+ );
42
+ }
43
+ }
44
+
45
+ return url.href === captureUrl.href;
46
+ };
47
+
48
+ // If `capture` is a string then `handler` and `method` must be present.
49
+ route = new Route(matchCallback, handler!, method);
50
+ } else if (capture instanceof RegExp) {
51
+ // If `capture` is a `RegExp` then `handler` and `method` must be present.
52
+ route = new RegExpRoute(capture, handler!, method);
53
+ } else if (typeof capture === "function") {
54
+ // If `capture` is a function then `handler` and `method` must be present.
55
+ route = new Route(capture, handler!, method);
56
+ } else if (capture instanceof Route) {
57
+ route = capture;
58
+ } else {
59
+ throw new SerwistError("unsupported-route-type", {
60
+ moduleName: "@serwist/routing",
61
+ funcName: "registerRoute",
62
+ paramName: "capture",
63
+ });
64
+ }
65
+
66
+ return route;
67
+ };