@serwist/routing 9.0.0-preview.9 → 9.0.0

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 (41) hide show
  1. package/dist/index.d.ts +3 -12
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +2 -468
  4. package/package.json +6 -7
  5. package/src/index.ts +3 -22
  6. package/dist/NavigationRoute.d.ts +0 -57
  7. package/dist/NavigationRoute.d.ts.map +0 -1
  8. package/dist/RegExpRoute.d.ts +0 -24
  9. package/dist/RegExpRoute.d.ts.map +0 -1
  10. package/dist/Route.d.ts +0 -33
  11. package/dist/Route.d.ts.map +0 -1
  12. package/dist/Router.d.ts +0 -124
  13. package/dist/Router.d.ts.map +0 -1
  14. package/dist/_types.d.ts +0 -48
  15. package/dist/_types.d.ts.map +0 -1
  16. package/dist/registerRoute.d.ts +0 -15
  17. package/dist/registerRoute.d.ts.map +0 -1
  18. package/dist/setCatchHandler.d.ts +0 -9
  19. package/dist/setCatchHandler.d.ts.map +0 -1
  20. package/dist/setDefaultHandler.d.ts +0 -12
  21. package/dist/setDefaultHandler.d.ts.map +0 -1
  22. package/dist/unregisterRoute.d.ts +0 -8
  23. package/dist/unregisterRoute.d.ts.map +0 -1
  24. package/dist/utils/constants.d.ts +0 -15
  25. package/dist/utils/constants.d.ts.map +0 -1
  26. package/dist/utils/getOrCreateDefaultRouter.d.ts +0 -10
  27. package/dist/utils/getOrCreateDefaultRouter.d.ts.map +0 -1
  28. package/dist/utils/normalizeHandler.d.ts +0 -10
  29. package/dist/utils/normalizeHandler.d.ts.map +0 -1
  30. package/src/NavigationRoute.ts +0 -119
  31. package/src/RegExpRoute.ts +0 -74
  32. package/src/Route.ts +0 -68
  33. package/src/Router.ts +0 -432
  34. package/src/_types.ts +0 -62
  35. package/src/registerRoute.ts +0 -89
  36. package/src/setCatchHandler.ts +0 -22
  37. package/src/setDefaultHandler.ts +0 -25
  38. package/src/unregisterRoute.ts +0 -12
  39. package/src/utils/constants.ts +0 -24
  40. package/src/utils/getOrCreateDefaultRouter.ts +0 -29
  41. package/src/utils/normalizeHandler.ts +0 -40
package/src/Router.ts DELETED
@@ -1,432 +0,0 @@
1
- /*
2
- Copyright 2018 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- import type { RouteHandler, RouteHandlerCallbackOptions, RouteHandlerObject, RouteMatchCallbackOptions } from "@serwist/core";
10
- import { assert, SerwistError, getFriendlyURL, logger } from "@serwist/core/internal";
11
-
12
- import type { Route } from "./Route.js";
13
- import type { HTTPMethod } from "./utils/constants.js";
14
- import { defaultMethod } from "./utils/constants.js";
15
- import { normalizeHandler } from "./utils/normalizeHandler.js";
16
-
17
- declare const self: ServiceWorkerGlobalScope;
18
-
19
- type RequestArgs = string | [string, RequestInit?];
20
-
21
- interface CacheURLsMessageData {
22
- type: string;
23
- payload: {
24
- urlsToCache: RequestArgs[];
25
- };
26
- }
27
-
28
- /**
29
- * The Router can be used to process a `FetchEvent` using one or more `@serwist/routing` Route(s),
30
- * responding with a `Response` if a matching route exists.
31
- *
32
- * If no route matches a given a request, the Router will use a "default" handler if one is defined.
33
- *
34
- * Should the matching Route throw an error, the Router will use a "catch" handler if one is defined to
35
- * gracefully deal with issues and respond with a Request.
36
- *
37
- * If a request matches multiple routes, the **earliest** registered route will
38
- * be used to respond to the request.
39
- */
40
- export class Router {
41
- private readonly _routes: Map<HTTPMethod, Route[]>;
42
- private readonly _defaultHandlerMap: Map<HTTPMethod, RouteHandlerObject>;
43
- private _catchHandler?: RouteHandlerObject;
44
-
45
- /**
46
- * Initializes a new Router.
47
- */
48
- constructor() {
49
- this._routes = new Map();
50
- this._defaultHandlerMap = new Map();
51
- }
52
-
53
- /**
54
- * @returns routes A `Map` of HTTP method name ('GET', etc.) to an array of all the corresponding `Route`
55
- * instances that are registered.
56
- */
57
- get routes(): Map<HTTPMethod, Route[]> {
58
- return this._routes;
59
- }
60
-
61
- /**
62
- * Adds a fetch event listener to respond to events when a route matches
63
- * the event's request.
64
- */
65
- addFetchListener(): void {
66
- self.addEventListener("fetch", (event) => {
67
- const { request } = event;
68
- const responsePromise = this.handleRequest({ request, event });
69
- if (responsePromise) {
70
- event.respondWith(responsePromise);
71
- }
72
- });
73
- }
74
-
75
- /**
76
- * Adds a message event listener for URLs to cache from the window.
77
- * This is useful to cache resources loaded on the page prior to when the
78
- * service worker started controlling it.
79
- *
80
- * The format of the message data sent from the window should be as follows.
81
- * Where the `urlsToCache` array may consist of URL strings or an array of
82
- * URL string + `requestInit` object (the same as you'd pass to `fetch()`).
83
- *
84
- * ```
85
- * {
86
- * type: 'CACHE_URLS',
87
- * payload: {
88
- * urlsToCache: [
89
- * './script1.js',
90
- * './script2.js',
91
- * ['./script3.js', {mode: 'no-cors'}],
92
- * ],
93
- * },
94
- * }
95
- * ```
96
- */
97
- addCacheListener(): void {
98
- self.addEventListener("message", (event) => {
99
- if (event.data && event.data.type === "CACHE_URLS") {
100
- const { payload }: CacheURLsMessageData = event.data;
101
-
102
- if (process.env.NODE_ENV !== "production") {
103
- logger.debug("Caching URLs from the window", payload.urlsToCache);
104
- }
105
-
106
- const requestPromises = Promise.all(
107
- payload.urlsToCache.map((entry: string | [string, RequestInit?]) => {
108
- if (typeof entry === "string") {
109
- entry = [entry];
110
- }
111
-
112
- const request = new Request(...entry);
113
- return this.handleRequest({ request, event });
114
- }),
115
- );
116
-
117
- event.waitUntil(requestPromises);
118
-
119
- // If a MessageChannel was used, reply to the message on success.
120
- if (event.ports?.[0]) {
121
- void requestPromises.then(() => event.ports[0].postMessage(true));
122
- }
123
- }
124
- });
125
- }
126
-
127
- /**
128
- * Apply the routing rules to a FetchEvent object to get a Response from an
129
- * appropriate Route's handler.
130
- *
131
- * @param options
132
- * @returns A promise is returned if a registered route can handle the request.
133
- * If there is no matching route and there's no `defaultHandler`, `undefined`
134
- * is returned.
135
- */
136
- handleRequest({
137
- request,
138
- event,
139
- }: {
140
- /**
141
- * The request to handle.
142
- */
143
- request: Request;
144
- /**
145
- * The event that triggered the request.
146
- */
147
- event: ExtendableEvent;
148
- }): Promise<Response> | undefined {
149
- if (process.env.NODE_ENV !== "production") {
150
- assert!.isInstance(request, Request, {
151
- moduleName: "@serwist/routing",
152
- className: "Router",
153
- funcName: "handleRequest",
154
- paramName: "options.request",
155
- });
156
- }
157
-
158
- const url = new URL(request.url, location.href);
159
- if (!url.protocol.startsWith("http")) {
160
- if (process.env.NODE_ENV !== "production") {
161
- logger.debug(`Serwist Router only supports URLs that start with 'http'.`);
162
- }
163
- return;
164
- }
165
-
166
- const sameOrigin = url.origin === location.origin;
167
- const { params, route } = this.findMatchingRoute({
168
- event,
169
- request,
170
- sameOrigin,
171
- url,
172
- });
173
- let handler = route?.handler;
174
-
175
- const debugMessages = [];
176
- if (process.env.NODE_ENV !== "production") {
177
- if (handler) {
178
- debugMessages.push(["Found a route to handle this request:", route]);
179
-
180
- if (params) {
181
- debugMessages.push([`Passing the following params to the route's handler:`, params]);
182
- }
183
- }
184
- }
185
-
186
- // If we don't have a handler because there was no matching route, then
187
- // fall back to defaultHandler if that's defined.
188
- const method = request.method as HTTPMethod;
189
- if (!handler && this._defaultHandlerMap.has(method)) {
190
- if (process.env.NODE_ENV !== "production") {
191
- debugMessages.push(`Failed to find a matching route. Falling back to the default handler for ${method}.`);
192
- }
193
- handler = this._defaultHandlerMap.get(method);
194
- }
195
-
196
- if (!handler) {
197
- if (process.env.NODE_ENV !== "production") {
198
- // No handler so Serwist will do nothing. If logs is set of debug
199
- // i.e. verbose, we should print out this information.
200
- logger.debug(`No route found for: ${getFriendlyURL(url)}`);
201
- }
202
- return;
203
- }
204
-
205
- if (process.env.NODE_ENV !== "production") {
206
- // We have a handler, meaning Serwist is going to handle the route.
207
- // print the routing details to the console.
208
- logger.groupCollapsed(`Router is responding to: ${getFriendlyURL(url)}`);
209
-
210
- for (const msg of debugMessages) {
211
- if (Array.isArray(msg)) {
212
- logger.log(...msg);
213
- } else {
214
- logger.log(msg);
215
- }
216
- }
217
-
218
- logger.groupEnd();
219
- }
220
-
221
- // Wrap in try and catch in case the handle method throws a synchronous
222
- // error. It should still callback to the catch handler.
223
- let responsePromise: Promise<Response>;
224
- try {
225
- responsePromise = handler.handle({ url, request, event, params });
226
- } catch (err) {
227
- responsePromise = Promise.reject(err);
228
- }
229
-
230
- // Get route's catch handler, if it exists
231
- const catchHandler = route?.catchHandler;
232
-
233
- if (responsePromise instanceof Promise && (this._catchHandler || catchHandler)) {
234
- responsePromise = responsePromise.catch(async (err) => {
235
- // If there's a route catch handler, process that first
236
- if (catchHandler) {
237
- if (process.env.NODE_ENV !== "production") {
238
- // Still include URL here as it will be async from the console group
239
- // and may not make sense without the URL
240
- logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to route's Catch Handler.`);
241
- logger.error("Error thrown by:", route);
242
- logger.error(err);
243
- logger.groupEnd();
244
- }
245
-
246
- try {
247
- return await catchHandler.handle({ url, request, event, params });
248
- } catch (catchErr) {
249
- if (catchErr instanceof Error) {
250
- err = catchErr;
251
- }
252
- }
253
- }
254
-
255
- if (this._catchHandler) {
256
- if (process.env.NODE_ENV !== "production") {
257
- // Still include URL here as it will be async from the console group
258
- // and may not make sense without the URL
259
- logger.groupCollapsed(`Error thrown when responding to: ${getFriendlyURL(url)}. Falling back to global Catch Handler.`);
260
- logger.error("Error thrown by:", route);
261
- logger.error(err);
262
- logger.groupEnd();
263
- }
264
- return this._catchHandler.handle({ url, request, event });
265
- }
266
-
267
- throw err;
268
- });
269
- }
270
-
271
- return responsePromise;
272
- }
273
-
274
- /**
275
- * Checks a request and URL (and optionally an event) against the list of
276
- * registered routes, and if there's a match, returns the corresponding
277
- * route along with any params generated by the match.
278
- *
279
- * @param options
280
- * @returns An object with `route` and `params` properties. They are populated
281
- * if a matching route was found or `undefined` otherwise.
282
- */
283
- findMatchingRoute({ url, sameOrigin, request, event }: RouteMatchCallbackOptions): {
284
- route?: Route;
285
- params?: RouteHandlerCallbackOptions["params"];
286
- } {
287
- const routes = this._routes.get(request.method as HTTPMethod) || [];
288
- for (const route of routes) {
289
- let params: Promise<any> | undefined;
290
- // route.match returns type any, not possible to change right now.
291
- const matchResult = route.match({ url, sameOrigin, request, event });
292
- if (matchResult) {
293
- if (process.env.NODE_ENV !== "production") {
294
- // Warn developers that using an async matchCallback is almost always
295
- // not the right thing to do.
296
- if (matchResult instanceof Promise) {
297
- logger.warn(
298
- `While routing ${getFriendlyURL(
299
- url,
300
- )}, an async matchCallback function was used. Please convert the following route to use a synchronous matchCallback function:`,
301
- route,
302
- );
303
- }
304
- }
305
-
306
- // See https://github.com/GoogleChrome/workbox/issues/2079
307
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
308
- params = matchResult;
309
- if (Array.isArray(params) && params.length === 0) {
310
- // Instead of passing an empty array in as params, use undefined.
311
- params = undefined;
312
- } else if (
313
- matchResult.constructor === Object && // eslint-disable-line
314
- Object.keys(matchResult).length === 0
315
- ) {
316
- // Instead of passing an empty object in as params, use undefined.
317
- params = undefined;
318
- } else if (typeof matchResult === "boolean") {
319
- // For the boolean value true (rather than just something truth-y),
320
- // don't set params.
321
- // See https://github.com/GoogleChrome/workbox/pull/2134#issuecomment-513924353
322
- params = undefined;
323
- }
324
-
325
- // Return early if have a match.
326
- return { route, params };
327
- }
328
- }
329
- // If no match was found above, return and empty object.
330
- return {};
331
- }
332
-
333
- /**
334
- * Define a default `handler` that's called when no routes explicitly
335
- * match the incoming request.
336
- *
337
- * Each HTTP method ('GET', 'POST', etc.) gets its own default handler.
338
- *
339
- * Without a default handler, unmatched requests will go against the
340
- * network as if there were no service worker present.
341
- *
342
- * @param handler A callback function that returns a Promise resulting in a Response.
343
- * @param method The HTTP method to associate with this default handler. Each method
344
- * has its own default. Defaults to GET.
345
- */
346
- setDefaultHandler(handler: RouteHandler, method: HTTPMethod = defaultMethod): void {
347
- this._defaultHandlerMap.set(method, normalizeHandler(handler));
348
- }
349
-
350
- /**
351
- * If a Route throws an error while handling a request, this `handler`
352
- * will be called and given a chance to provide a response.
353
- *
354
- * @param handler A callback function that returns a Promise resulting
355
- * in a Response.
356
- */
357
- setCatchHandler(handler: RouteHandler): void {
358
- this._catchHandler = normalizeHandler(handler);
359
- }
360
-
361
- /**
362
- * Registers a route with the router.
363
- *
364
- * @param route The route to register.
365
- */
366
- registerRoute(route: Route): void {
367
- if (process.env.NODE_ENV !== "production") {
368
- assert!.isType(route, "object", {
369
- moduleName: "@serwist/routing",
370
- className: "Router",
371
- funcName: "registerRoute",
372
- paramName: "route",
373
- });
374
-
375
- assert!.hasMethod(route, "match", {
376
- moduleName: "@serwist/routing",
377
- className: "Router",
378
- funcName: "registerRoute",
379
- paramName: "route",
380
- });
381
-
382
- assert!.isType(route.handler, "object", {
383
- moduleName: "@serwist/routing",
384
- className: "Router",
385
- funcName: "registerRoute",
386
- paramName: "route",
387
- });
388
-
389
- assert!.hasMethod(route.handler, "handle", {
390
- moduleName: "@serwist/routing",
391
- className: "Router",
392
- funcName: "registerRoute",
393
- paramName: "route.handler",
394
- });
395
-
396
- assert!.isType(route.method, "string", {
397
- moduleName: "@serwist/routing",
398
- className: "Router",
399
- funcName: "registerRoute",
400
- paramName: "route.method",
401
- });
402
- }
403
-
404
- if (!this._routes.has(route.method)) {
405
- this._routes.set(route.method, []);
406
- }
407
-
408
- // Give precedence to all of the earlier routes by adding this additional
409
- // route to the end of the array.
410
- this._routes.get(route.method)!.push(route);
411
- }
412
-
413
- /**
414
- * Unregisters a route with the router.
415
- *
416
- * @param route The route to unregister.
417
- */
418
- unregisterRoute(route: Route): void {
419
- if (!this._routes.has(route.method)) {
420
- throw new SerwistError("unregister-route-but-not-found-with-method", {
421
- method: route.method,
422
- });
423
- }
424
-
425
- const routeIndex = this._routes.get(route.method)!.indexOf(route);
426
- if (routeIndex > -1) {
427
- this._routes.get(route.method)!.splice(routeIndex, 1);
428
- } else {
429
- throw new SerwistError("unregister-route-route-not-registered");
430
- }
431
- }
432
- }
package/src/_types.ts DELETED
@@ -1,62 +0,0 @@
1
- /*
2
- Copyright 2018 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- // * * * IMPORTANT! * * *
10
- // ------------------------------------------------------------------------- //
11
- // jdsoc type definitions cannot be declared above TypeScript definitions or
12
- // they'll be stripped from the built `.js` files, and they'll only be in the
13
- // `d.ts` files, which aren't read by the jsdoc generator. As a result we
14
- // have to put declare them below.
15
-
16
- /**
17
- * The "match" callback is used to determine if a `Route` should apply for a
18
- * particular URL. When matching occurs in response to a fetch event from the
19
- * client, the `event` object is supplied in addition to the `url`, `request`,
20
- * and `sameOrigin` value. However, since the match callback can be invoked
21
- * outside of a fetch event, matching logic should not assume the `event`
22
- * object will always be available.
23
- *
24
- * If the match callback returns a truthy value, the matching route's
25
- * {@link workbox-routing~handlerCallback} will be
26
- * invoked immediately. If the value returned is a non-empty array or object,
27
- * that value will be set on the handler's `context.params` argument.
28
- *
29
- * @callback ~matchCallback
30
- * @param context
31
- * @param context.request The corresponding request.
32
- * @param context.url The request's URL.
33
- * @param context.event The corresponding event that triggered
34
- * the request.
35
- * @param context.sameOrigin The result of comparing `url.origin`
36
- * against the current origin.
37
- * @returns To signify a match, return a truthy value.
38
- */
39
-
40
- /**
41
- * The "handler" callback is invoked whenever a `Router` matches a URL to a
42
- * `Route` via its {@link workbox-routing~matchCallback}
43
- * callback. This callback should return a Promise that resolves with a
44
- * `Response`.
45
- *
46
- * If a non-empty array or object is returned by the
47
- * {@link workbox-routing~matchCallback} it
48
- * will be passed in as the handler's `context.params` argument.
49
- *
50
- * @callback ~handlerCallback
51
- * @param context
52
- * @param context.request The corresponding request.
53
- * @param context.url The URL that matched, if available.
54
- * @param context.event The corresponding event that triggered
55
- * the request.
56
- * @param context.params Array or Object parameters returned by the
57
- * Route's {@link workbox-routing~matchCallback}.
58
- * This will be undefined if an empty array or object were returned.
59
- * @returns The response that will fulfill the request.
60
- *
61
- * @memberof workbox-routing
62
- */
@@ -1,89 +0,0 @@
1
- /*
2
- Copyright 2019 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- import type { RouteHandler, RouteMatchCallback } from "@serwist/core";
10
- import { SerwistError, logger } from "@serwist/core/internal";
11
-
12
- import { RegExpRoute } from "./RegExpRoute.js";
13
- import { Route } from "./Route.js";
14
- import type { HTTPMethod } from "./utils/constants.js";
15
- import { getOrCreateDefaultRouter } from "./utils/getOrCreateDefaultRouter.js";
16
-
17
- /**
18
- * Registers a RegExp, string, or function with a caching
19
- * strategy to a singleton Router instance.
20
- *
21
- * @param capture If the capture param is a `Route`, all other arguments will be ignored.
22
- * @param handler A callback function that returns a Promise resulting in a Response.
23
- * This parameter is required if `capture` is not a `Route` object.
24
- * @param method The HTTP method to match the Route against. Defaults to GET.
25
- * @returns The generated `Route`.
26
- */
27
- 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
- }
84
-
85
- const defaultRouter = getOrCreateDefaultRouter();
86
- defaultRouter.registerRoute(route);
87
-
88
- return route;
89
- };
@@ -1,22 +0,0 @@
1
- /*
2
- Copyright 2019 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- import type { RouteHandler } from "@serwist/core";
10
-
11
- import { getOrCreateDefaultRouter } from "./utils/getOrCreateDefaultRouter.js";
12
-
13
- /**
14
- * If a Route throws an error while handling a request, this `handler`
15
- * will be called and given a chance to provide a response.
16
- *
17
- * @param handler A callback function that returns a Promise resulting in a Response.
18
- */
19
- export const setCatchHandler = (handler: RouteHandler): void => {
20
- const defaultRouter = getOrCreateDefaultRouter();
21
- defaultRouter.setCatchHandler(handler);
22
- };
@@ -1,25 +0,0 @@
1
- /*
2
- Copyright 2019 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- import type { RouteHandler } from "@serwist/core";
10
-
11
- import { getOrCreateDefaultRouter } from "./utils/getOrCreateDefaultRouter.js";
12
-
13
- /**
14
- * Defines a default `handler` that's called when no routes explicitly
15
- * match the incoming request.
16
- *
17
- * Without a default handler, unmatched requests will go against the
18
- * network as if there were no service worker present.
19
- *
20
- * @param handler A callback function that returns a Promise resulting in a Response.
21
- */
22
- export const setDefaultHandler = (handler: RouteHandler): void => {
23
- const defaultRouter = getOrCreateDefaultRouter();
24
- defaultRouter.setDefaultHandler(handler);
25
- };
@@ -1,12 +0,0 @@
1
- import type { Route } from "./Route.js";
2
- import { getOrCreateDefaultRouter } from "./utils/getOrCreateDefaultRouter.js";
3
-
4
- /**
5
- * Unregisters a route from the singleton Router instance.
6
- *
7
- * @param route The route to unregister.
8
- */
9
- export const unregisterRoute = (route: Route): void => {
10
- const defaultRouter = getOrCreateDefaultRouter();
11
- defaultRouter.unregisterRoute(route);
12
- };
@@ -1,24 +0,0 @@
1
- /*
2
- Copyright 2018 Google LLC
3
-
4
- Use of this source code is governed by an MIT-style
5
- license that can be found in the LICENSE file or at
6
- https://opensource.org/licenses/MIT.
7
- */
8
-
9
- export type HTTPMethod = "DELETE" | "GET" | "HEAD" | "PATCH" | "POST" | "PUT";
10
-
11
- /**
12
- * The default HTTP method, 'GET', used when there's no specific method
13
- * configured for a route.
14
- *
15
- * @private
16
- */
17
- export const defaultMethod = "GET" satisfies HTTPMethod;
18
-
19
- /**
20
- * The list of valid HTTP methods associated with requests that could be routed.
21
- *
22
- * @private
23
- */
24
- export const validMethods = ["DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"] satisfies HTTPMethod[];