@serwist/routing 8.4.4 → 9.0.0-preview.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 (43) hide show
  1. package/dist/NavigationRoute.d.ts +2 -2
  2. package/dist/NavigationRoute.d.ts.map +1 -0
  3. package/dist/RegExpRoute.d.ts +2 -2
  4. package/dist/RegExpRoute.d.ts.map +1 -0
  5. package/dist/Route.d.ts +2 -2
  6. package/dist/Route.d.ts.map +1 -0
  7. package/dist/Router.d.ts +2 -2
  8. package/dist/Router.d.ts.map +1 -0
  9. package/dist/_types.d.ts +1 -0
  10. package/dist/_types.d.ts.map +1 -0
  11. package/dist/index.d.ts +3 -1
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +37 -289
  14. package/dist/registerRoute.d.ts +3 -3
  15. package/dist/registerRoute.d.ts.map +1 -0
  16. package/dist/setCatchHandler.d.ts +2 -2
  17. package/dist/setCatchHandler.d.ts.map +1 -0
  18. package/dist/setDefaultHandler.d.ts +3 -3
  19. package/dist/setDefaultHandler.d.ts.map +1 -0
  20. package/dist/unregisterRoute.d.ts +8 -0
  21. package/dist/unregisterRoute.d.ts.map +1 -0
  22. package/dist/utils/constants.d.ts +3 -6
  23. package/dist/utils/constants.d.ts.map +1 -0
  24. package/dist/utils/getOrCreateDefaultRouter.d.ts +1 -0
  25. package/dist/utils/getOrCreateDefaultRouter.d.ts.map +1 -0
  26. package/dist/utils/normalizeHandler.d.ts +1 -0
  27. package/dist/utils/normalizeHandler.d.ts.map +1 -0
  28. package/package.json +18 -16
  29. package/src/NavigationRoute.ts +119 -0
  30. package/src/RegExpRoute.ts +74 -0
  31. package/src/Route.ts +68 -0
  32. package/src/Router.ts +436 -0
  33. package/src/_types.ts +62 -0
  34. package/src/index.ts +22 -0
  35. package/src/registerRoute.ts +89 -0
  36. package/src/setCatchHandler.ts +22 -0
  37. package/src/setDefaultHandler.ts +25 -0
  38. package/src/unregisterRoute.ts +12 -0
  39. package/src/utils/constants.ts +24 -0
  40. package/src/utils/getOrCreateDefaultRouter.ts +29 -0
  41. package/src/utils/normalizeHandler.ts +40 -0
  42. package/dist/index.cjs +0 -728
  43. package/dist/index.d.cts +0 -0
@@ -2,7 +2,7 @@ import type { RouteHandler, RouteMatchCallback } from "@serwist/core";
2
2
  import { Route } from "./Route.js";
3
3
  import type { HTTPMethod } from "./utils/constants.js";
4
4
  /**
5
- * Easily register a RegExp, string, or function with a caching
5
+ * Registers a RegExp, string, or function with a caching
6
6
  * strategy to a singleton Router instance.
7
7
  *
8
8
  * @param capture If the capture param is a `Route`, all other arguments will be ignored.
@@ -11,5 +11,5 @@ import type { HTTPMethod } from "./utils/constants.js";
11
11
  * @param method The HTTP method to match the Route against. Defaults to GET.
12
12
  * @returns The generated `Route`.
13
13
  */
14
- declare function registerRoute(capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod): Route;
15
- export { registerRoute };
14
+ export declare const registerRoute: (capture: RegExp | string | RouteMatchCallback | Route, handler?: RouteHandler, method?: HTTPMethod) => Route;
15
+ //# sourceMappingURL=registerRoute.d.ts.map
@@ -0,0 +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"}
@@ -5,5 +5,5 @@ import type { RouteHandler } from "@serwist/core";
5
5
  *
6
6
  * @param handler A callback function that returns a Promise resulting in a Response.
7
7
  */
8
- declare function setCatchHandler(handler: RouteHandler): void;
9
- export { setCatchHandler };
8
+ export declare const setCatchHandler: (handler: RouteHandler) => void;
9
+ //# sourceMappingURL=setCatchHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setCatchHandler.d.ts","sourceRoot":"","sources":["../src/setCatchHandler.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAIlD;;;;;GAKG;AACH,eAAO,MAAM,eAAe,YAAa,YAAY,KAAG,IAGvD,CAAC"}
@@ -1,6 +1,6 @@
1
1
  import type { RouteHandler } from "@serwist/core";
2
2
  /**
3
- * Define a default `handler` that's called when no routes explicitly
3
+ * Defines a default `handler` that's called when no routes explicitly
4
4
  * match the incoming request.
5
5
  *
6
6
  * Without a default handler, unmatched requests will go against the
@@ -8,5 +8,5 @@ import type { RouteHandler } from "@serwist/core";
8
8
  *
9
9
  * @param handler A callback function that returns a Promise resulting in a Response.
10
10
  */
11
- declare function setDefaultHandler(handler: RouteHandler): void;
12
- export { setDefaultHandler };
11
+ export declare const setDefaultHandler: (handler: RouteHandler) => void;
12
+ //# sourceMappingURL=setDefaultHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setDefaultHandler.d.ts","sourceRoot":"","sources":["../src/setDefaultHandler.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAIlD;;;;;;;;GAQG;AACH,eAAO,MAAM,iBAAiB,YAAa,YAAY,KAAG,IAGzD,CAAC"}
@@ -0,0 +1,8 @@
1
+ import type { Route } from "./Route.js";
2
+ /**
3
+ * Unregisters a route from the singleton Router instance.
4
+ *
5
+ * @param route The route to unregister.
6
+ */
7
+ export declare const unregisterRoute: (route: Route) => void;
8
+ //# sourceMappingURL=unregisterRoute.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unregisterRoute.d.ts","sourceRoot":"","sources":["../src/unregisterRoute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAGxC;;;;GAIG;AACH,eAAO,MAAM,eAAe,UAAW,KAAK,KAAG,IAG9C,CAAC"}
@@ -3,16 +3,13 @@ export type HTTPMethod = "DELETE" | "GET" | "HEAD" | "PATCH" | "POST" | "PUT";
3
3
  * The default HTTP method, 'GET', used when there's no specific method
4
4
  * configured for a route.
5
5
  *
6
- * @type {string}
7
- *
8
6
  * @private
9
7
  */
10
- export declare const defaultMethod: HTTPMethod;
8
+ export declare const defaultMethod = "GET";
11
9
  /**
12
10
  * The list of valid HTTP methods associated with requests that could be routed.
13
11
  *
14
- * @type {Array<string>}
15
- *
16
12
  * @private
17
13
  */
18
- export declare const validMethods: HTTPMethod[];
14
+ export declare const validMethods: ("DELETE" | "GET" | "HEAD" | "PATCH" | "POST" | "PUT")[];
15
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/utils/constants.ts"],"names":[],"mappings":"AAQA,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,GAAG,KAAK,CAAC;AAE9E;;;;;GAKG;AACH,eAAO,MAAM,aAAa,QAA6B,CAAC;AAExD;;;;GAIG;AACH,eAAO,MAAM,YAAY,0DAA2E,CAAC"}
@@ -7,3 +7,4 @@ import { Router } from "../Router.js";
7
7
  * @returns
8
8
  */
9
9
  export declare const getOrCreateDefaultRouter: () => Router;
10
+ //# sourceMappingURL=getOrCreateDefaultRouter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getOrCreateDefaultRouter.d.ts","sourceRoot":"","sources":["../../src/utils/getOrCreateDefaultRouter.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAItC;;;;;;GAMG;AACH,eAAO,MAAM,wBAAwB,QAAO,MAS3C,CAAC"}
@@ -7,3 +7,4 @@ import type { RouteHandler, RouteHandlerObject } from "@serwist/core";
7
7
  * @private
8
8
  */
9
9
  export declare const normalizeHandler: (handler: RouteHandler) => RouteHandlerObject;
10
+ //# sourceMappingURL=normalizeHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalizeHandler.d.ts","sourceRoot":"","sources":["../../src/utils/normalizeHandler.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAGtE;;;;;;GAMG;AACH,eAAO,MAAM,gBAAgB,YAAa,YAAY,KAAG,kBAqBxD,CAAC"}
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@serwist/routing",
3
- "version": "8.4.4",
3
+ "version": "9.0.0-preview.1",
4
4
  "type": "module",
5
5
  "description": "A service worker helper library to route request URLs to handlers.",
6
6
  "files": [
7
- "dist",
8
- "!dist/**/dts"
7
+ "src",
8
+ "dist"
9
9
  ],
10
10
  "keywords": [
11
11
  "serwist",
@@ -20,28 +20,30 @@
20
20
  "repository": "serwist/serwist",
21
21
  "bugs": "https://github.com/serwist/serwist/issues",
22
22
  "homepage": "https://serwist.pages.dev",
23
- "module": "./dist/index.js",
24
- "main": "./dist/index.cjs",
23
+ "main": "./dist/index.js",
25
24
  "types": "./dist/index.d.ts",
26
25
  "exports": {
27
26
  ".": {
28
- "import": {
29
- "types": "./dist/index.d.ts",
30
- "default": "./dist/index.js"
31
- },
32
- "require": {
33
- "types": "./dist/index.d.cts",
34
- "default": "./dist/index.cjs"
35
- }
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
36
29
  },
37
30
  "./package.json": "./package.json"
38
31
  },
39
32
  "dependencies": {
40
- "@serwist/core": "8.4.4"
33
+ "@serwist/core": "9.0.0-preview.1"
41
34
  },
42
35
  "devDependencies": {
43
- "rollup": "4.9.1",
44
- "@serwist/constants": "8.4.4"
36
+ "rollup": "4.9.6",
37
+ "typescript": "5.4.0-dev.20240203",
38
+ "@serwist/constants": "9.0.0-preview.1"
39
+ },
40
+ "peerDependencies": {
41
+ "typescript": ">=5.0.0"
42
+ },
43
+ "peerDependenciesMeta": {
44
+ "typescript": {
45
+ "optional": true
46
+ }
45
47
  },
46
48
  "scripts": {
47
49
  "build": "rimraf dist && cross-env NODE_ENV=production rollup --config rollup.config.js",
@@ -0,0 +1,119 @@
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, RouteMatchCallbackOptions } from "@serwist/core";
10
+ import { assert, logger } from "@serwist/core/internal";
11
+
12
+ import { Route } from "./Route.js";
13
+
14
+ export interface NavigationRouteMatchOptions {
15
+ /**
16
+ * If any of these patterns
17
+ * match the URL's pathname and search parameter, the route will handle the
18
+ * request (assuming the denylist doesn't match).
19
+ *
20
+ * @default [/./]
21
+ */
22
+ allowlist?: RegExp[];
23
+ /**
24
+ * If any of these patterns match, the route will not handle the request (even if a allowlist RegExp matches).
25
+ */
26
+ denylist?: RegExp[];
27
+ }
28
+
29
+ /**
30
+ * NavigationRoute makes it easy to create a `@serwist/routing` Route that matches for browser
31
+ * [navigation requests](https://developers.google.com/web/fundamentals/primers/service-workers/high-performance-loading#first_what_are_navigation_requests).
32
+ *
33
+ * It will only match incoming Requests whose [mode](https://fetch.spec.whatwg.org/#concept-request-mode) is set to `navigate`.
34
+ *
35
+ * You can optionally only apply this route to a subset of navigation requests
36
+ * by using one or both of the `denylist` and `allowlist` parameters.
37
+ */
38
+ export class NavigationRoute extends Route {
39
+ private readonly _allowlist: RegExp[];
40
+ private readonly _denylist: RegExp[];
41
+
42
+ /**
43
+ * If both `denylist` and `allowlist` are provided, the `denylist` will
44
+ * take precedence and the request will not match this route.
45
+ *
46
+ * The regular expressions in `allowlist` and `denylist`
47
+ * are matched against the concatenated
48
+ * [`pathname`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/pathname)
49
+ * and [`search`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search)
50
+ * portions of the requested URL.
51
+ *
52
+ * *Note*: These RegExps may be evaluated against every destination URL during
53
+ * a navigation. Avoid using
54
+ * [complex RegExps](https://github.com/GoogleChrome/workbox/issues/3077),
55
+ * or else your users may see delays when navigating your site.
56
+ *
57
+ * @param handler A callback function that returns a Promise resulting in a Response.
58
+ * @param options
59
+ */
60
+ constructor(handler: RouteHandler, { allowlist = [/./], denylist = [] }: NavigationRouteMatchOptions = {}) {
61
+ if (process.env.NODE_ENV !== "production") {
62
+ assert!.isArrayOfClass(allowlist, RegExp, {
63
+ moduleName: "@serwist/routing",
64
+ className: "NavigationRoute",
65
+ funcName: "constructor",
66
+ paramName: "options.allowlist",
67
+ });
68
+ assert!.isArrayOfClass(denylist, RegExp, {
69
+ moduleName: "@serwist/routing",
70
+ className: "NavigationRoute",
71
+ funcName: "constructor",
72
+ paramName: "options.denylist",
73
+ });
74
+ }
75
+
76
+ super((options: RouteMatchCallbackOptions) => this._match(options), handler);
77
+
78
+ this._allowlist = allowlist;
79
+ this._denylist = denylist;
80
+ }
81
+
82
+ /**
83
+ * Routes match handler.
84
+ *
85
+ * @param options
86
+ * @returns
87
+ * @private
88
+ */
89
+ private _match({ url, request }: RouteMatchCallbackOptions): boolean {
90
+ if (request && request.mode !== "navigate") {
91
+ return false;
92
+ }
93
+
94
+ const pathnameAndSearch = url.pathname + url.search;
95
+
96
+ for (const regExp of this._denylist) {
97
+ if (regExp.test(pathnameAndSearch)) {
98
+ if (process.env.NODE_ENV !== "production") {
99
+ logger.log(
100
+ `The navigation route ${pathnameAndSearch} is not being used, since the URL matches this denylist pattern: ${regExp.toString()}`,
101
+ );
102
+ }
103
+ return false;
104
+ }
105
+ }
106
+
107
+ if (this._allowlist.some((regExp) => regExp.test(pathnameAndSearch))) {
108
+ if (process.env.NODE_ENV !== "production") {
109
+ logger.debug(`The navigation route ${pathnameAndSearch} is being used.`);
110
+ }
111
+ return true;
112
+ }
113
+
114
+ if (process.env.NODE_ENV !== "production") {
115
+ logger.log(`The navigation route ${pathnameAndSearch} is not being used, since the URL being navigated to doesn't match the allowlist.`);
116
+ }
117
+ return false;
118
+ }
119
+ }
@@ -0,0 +1,74 @@
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, RouteMatchCallback, RouteMatchCallbackOptions } from "@serwist/core";
10
+ import { assert, logger } from "@serwist/core/internal";
11
+
12
+ import { Route } from "./Route.js";
13
+ import type { HTTPMethod } from "./utils/constants.js";
14
+
15
+ /**
16
+ * RegExpRoute makes it easy to create a regular expression based on a `@serwist/routing` Route.
17
+ *
18
+ * For same-origin requests the RegExp only needs to match part of the URL. For
19
+ * requests against third-party servers, you must define a RegExp that matches
20
+ * the start of the URL.
21
+ */
22
+ export class RegExpRoute extends Route {
23
+ /**
24
+ * If the regular expression contains
25
+ * [capture groups](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#grouping-back-references),
26
+ * the captured values will be passed to the `params` argument.
27
+ *
28
+ * @param regExp The regular expression to match against URLs.
29
+ * @param handler A callback function that returns a Promise resulting in a Response.
30
+ * @param method The HTTP method to match the Route, defaults to GET.
31
+ * against.
32
+ */
33
+ constructor(regExp: RegExp, handler: RouteHandler, method?: HTTPMethod) {
34
+ if (process.env.NODE_ENV !== "production") {
35
+ assert!.isInstance(regExp, RegExp, {
36
+ moduleName: "@serwist/routing",
37
+ className: "RegExpRoute",
38
+ funcName: "constructor",
39
+ paramName: "pattern",
40
+ });
41
+ }
42
+
43
+ const match: RouteMatchCallback = ({ url }: RouteMatchCallbackOptions) => {
44
+ const result = regExp.exec(url.href);
45
+
46
+ // Return immediately if there's no match.
47
+ if (!result) {
48
+ return;
49
+ }
50
+
51
+ // Require that the match start at the first character in the URL string
52
+ // if it's a cross-origin request.
53
+ // See https://github.com/GoogleChrome/workbox/issues/281 for the context
54
+ // behind this behavior.
55
+ if (url.origin !== location.origin && result.index !== 0) {
56
+ if (process.env.NODE_ENV !== "production") {
57
+ logger.debug(
58
+ `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.`,
59
+ );
60
+ }
61
+
62
+ return;
63
+ }
64
+
65
+ // If the route matches, but there aren't any capture groups defined, then
66
+ // this will return [], which is truthy and therefore sufficient to
67
+ // indicate a match.
68
+ // If there are capture groups, then it will return their values.
69
+ return result.slice(1);
70
+ };
71
+
72
+ super(match, handler, method);
73
+ }
74
+ }
package/src/Route.ts ADDED
@@ -0,0 +1,68 @@
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, RouteHandlerObject, RouteMatchCallback } from "@serwist/core";
10
+ import { assert } from "@serwist/core/internal";
11
+
12
+ import type { HTTPMethod } from "./utils/constants.js";
13
+ import { defaultMethod, validMethods } from "./utils/constants.js";
14
+ import { normalizeHandler } from "./utils/normalizeHandler.js";
15
+
16
+ /**
17
+ * A `Route` consists of a pair of callback functions, "match" and "handler".
18
+ * The "match" callback determine if a route should be used to "handle" a
19
+ * request by returning a non-falsy value if it can. The "handler" callback
20
+ * is called when there is a match and should return a Promise that resolves
21
+ * to a `Response`.
22
+ */
23
+ export class Route {
24
+ handler: RouteHandlerObject;
25
+ match: RouteMatchCallback;
26
+ method: HTTPMethod;
27
+ catchHandler?: RouteHandlerObject;
28
+
29
+ /**
30
+ * Constructor for Route class.
31
+ *
32
+ * @param match A callback function that determines whether the
33
+ * route matches a given `fetch` event by returning a non-falsy value.
34
+ * @param handler A callback function that returns a Promise resolving
35
+ * to a Response.
36
+ * @param method The HTTP method to match the Route against. Defaults
37
+ * to GET.
38
+ */
39
+ constructor(match: RouteMatchCallback, handler: RouteHandler, method: HTTPMethod = defaultMethod) {
40
+ if (process.env.NODE_ENV !== "production") {
41
+ assert!.isType(match, "function", {
42
+ moduleName: "@serwist/routing",
43
+ className: "Route",
44
+ funcName: "constructor",
45
+ paramName: "match",
46
+ });
47
+
48
+ if (method) {
49
+ assert!.isOneOf(method, validMethods, { paramName: "method" });
50
+ }
51
+ }
52
+
53
+ // These values are referenced directly by Router so cannot be
54
+ // altered by minificaton.
55
+ this.handler = normalizeHandler(handler);
56
+ this.match = match;
57
+ this.method = method;
58
+ }
59
+
60
+ /**
61
+ *
62
+ * @param handler A callback function that returns a Promise resolving
63
+ * to a Response.
64
+ */
65
+ setCatchHandler(handler: RouteHandler): void {
66
+ this.catchHandler = normalizeHandler(handler);
67
+ }
68
+ }