itty-router 4.0.11 → 4.0.13

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 (71) hide show
  1. package/Router.js +1 -37
  2. package/Router.mjs +1 -0
  3. package/StatusError.js +1 -10
  4. package/StatusError.mjs +1 -0
  5. package/createCors.js +1 -66
  6. package/createCors.mjs +1 -0
  7. package/createResponse.d.ts +1 -1
  8. package/createResponse.js +1 -14
  9. package/createResponse.mjs +1 -0
  10. package/error.js +1 -42
  11. package/error.mjs +1 -0
  12. package/html.js +1 -16
  13. package/html.mjs +1 -0
  14. package/index.js +1 -189
  15. package/index.mjs +1 -0
  16. package/jpeg.js +1 -16
  17. package/jpeg.mjs +1 -0
  18. package/json.js +1 -16
  19. package/json.mjs +1 -0
  20. package/package.json +104 -16
  21. package/png.js +1 -16
  22. package/png.mjs +1 -0
  23. package/status.d.ts +1 -1
  24. package/status.js +1 -3
  25. package/status.mjs +1 -0
  26. package/text.js +1 -3
  27. package/text.mjs +1 -0
  28. package/webp.js +1 -16
  29. package/webp.mjs +1 -0
  30. package/websocket.js +1 -20
  31. package/websocket.mjs +1 -0
  32. package/withContent.js +1 -7
  33. package/withContent.mjs +1 -0
  34. package/withCookies.js +1 -9
  35. package/withCookies.mjs +1 -0
  36. package/withParams.js +1 -12
  37. package/withParams.mjs +1 -0
  38. package/cjs/Router.d.ts +0 -49
  39. package/cjs/Router.js +0 -39
  40. package/cjs/StatusError.d.ts +0 -10
  41. package/cjs/StatusError.js +0 -12
  42. package/cjs/createCors.d.ts +0 -12
  43. package/cjs/createCors.js +0 -68
  44. package/cjs/createResponse.d.ts +0 -7
  45. package/cjs/createResponse.js +0 -16
  46. package/cjs/error.d.ts +0 -11
  47. package/cjs/error.js +0 -44
  48. package/cjs/html.d.ts +0 -1
  49. package/cjs/html.js +0 -18
  50. package/cjs/index.d.ts +0 -15
  51. package/cjs/index.js +0 -205
  52. package/cjs/jpeg.d.ts +0 -1
  53. package/cjs/jpeg.js +0 -18
  54. package/cjs/json.d.ts +0 -1
  55. package/cjs/json.js +0 -18
  56. package/cjs/png.d.ts +0 -1
  57. package/cjs/png.js +0 -18
  58. package/cjs/status.d.ts +0 -1
  59. package/cjs/status.js +0 -5
  60. package/cjs/text.d.ts +0 -1
  61. package/cjs/text.js +0 -5
  62. package/cjs/webp.d.ts +0 -1
  63. package/cjs/webp.js +0 -18
  64. package/cjs/websocket.d.ts +0 -1
  65. package/cjs/websocket.js +0 -22
  66. package/cjs/withContent.d.ts +0 -2
  67. package/cjs/withContent.js +0 -9
  68. package/cjs/withCookies.d.ts +0 -2
  69. package/cjs/withCookies.js +0 -11
  70. package/cjs/withParams.d.ts +0 -2
  71. package/cjs/withParams.js +0 -14
package/cjs/index.js DELETED
@@ -1,205 +0,0 @@
1
- 'use strict';
2
-
3
- const Router = ({ base = '', routes = [] } = {}) =>
4
- // @ts-expect-error TypeScript doesn't know that Proxy makes this work
5
- ({
6
- __proto__: new Proxy({}, {
7
- // @ts-expect-error (we're adding an expected prop "path" to the get)
8
- get: (target, prop, receiver, path) => (route, ...handlers) => routes.push([
9
- prop.toUpperCase(),
10
- RegExp(`^${(path = (base + '/' + route).replace(/\/+(\/|$)/g, '$1')) // strip double & trailing splash
11
- .replace(/(\/?\.?):(\w+)\+/g, '($1(?<$2>*))') // greedy params
12
- .replace(/(\/?\.?):(\w+)/g, '($1(?<$2>[^$1/]+?))') // named params and image format
13
- .replace(/\./g, '\\.') // dot in path
14
- .replace(/(\/?)\*/g, '($1.*)?') // wildcard
15
- }/*$`),
16
- handlers,
17
- path, // embed clean route path
18
- ]) && receiver
19
- }),
20
- routes,
21
- async handle(request, ...args) {
22
- let response, match, url = new URL(request.url), query = request.query = { __proto__: null };
23
- for (let [k, v] of url.searchParams) {
24
- query[k] = query[k] === undefined ? v : [query[k], v].flat();
25
- }
26
- for (let [method, regex, handlers, path] of routes) {
27
- if ((method === request.method || method === 'ALL') && (match = url.pathname.match(regex))) {
28
- request.params = match.groups || {}; // embed params in request
29
- request.route = path; // embed route path in request
30
- for (let handler of handlers) {
31
- if ((response = await handler(request.proxy || request, ...args)) !== undefined)
32
- return response;
33
- }
34
- }
35
- }
36
- }
37
- });
38
-
39
- class StatusError extends Error {
40
- status;
41
- constructor(status = 500, body) {
42
- super(typeof body === 'object' ? body.error : body);
43
- typeof body === 'object' && Object.assign(this, body);
44
- this.status = status;
45
- }
46
- }
47
-
48
- const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
49
- const { headers = {}, ...rest } = options;
50
- if (body?.constructor.name === 'Response')
51
- return body;
52
- return new Response(transform ? transform(body) : body, {
53
- headers: {
54
- 'content-type': format,
55
- ...headers,
56
- },
57
- ...rest,
58
- });
59
- };
60
-
61
- const json = createResponse('application/json; charset=utf-8', JSON.stringify);
62
-
63
- const getMessage = (code) => {
64
- return ({
65
- 400: 'Bad Request',
66
- 401: 'Unauthorized',
67
- 403: 'Forbidden',
68
- 404: 'Not Found',
69
- 500: 'Internal Server Error',
70
- }[code] || 'Unknown Error');
71
- };
72
- const error = (a = 500, b) => {
73
- // handle passing an Error | StatusError directly in
74
- if (a instanceof Error) {
75
- const { message, ...err } = a;
76
- a = a.status || 500;
77
- b = {
78
- error: message || getMessage(a),
79
- ...err,
80
- };
81
- }
82
- b = {
83
- status: a,
84
- ...(typeof b === 'object' ? b : { error: b || getMessage(a) }),
85
- };
86
- return json(b, { status: a });
87
- };
88
-
89
- const status = (status) => new Response(null, { status });
90
-
91
- const text = (message, options) => new Response(message, options);
92
-
93
- const html = createResponse('text/html');
94
-
95
- const jpeg = createResponse('image/jpeg');
96
-
97
- const png = createResponse('image/png');
98
-
99
- const webp = createResponse('image/webp');
100
-
101
- // withContent - embeds any request body as request.content
102
- const withContent = async (request) => {
103
- if (request.headers.get('content-type')?.includes('json'))
104
- request.content = await request.json();
105
- };
106
-
107
- // withCookies - embeds cookies object into the request
108
- const withCookies = (r) => {
109
- r.cookies = (r.headers.get('Cookie') || '')
110
- .split(/;\s*/)
111
- .map((p) => p.split(/=(.+)/))
112
- .reduce((a, [k, v]) => (v ? ((a[k] = v), a) : a), {});
113
- };
114
-
115
- const withParams = (request) => {
116
- request.proxy = new Proxy(request.proxy || request, {
117
- get: (obj, prop) => {
118
- let p;
119
- if ((p = obj[prop]) !== undefined)
120
- return p.bind?.(request) || p;
121
- return obj?.params?.[prop];
122
- },
123
- });
124
- };
125
-
126
- // Create CORS function with default options.
127
- const createCors = (options = {}) => {
128
- // Destructure and set defaults for options.
129
- const { origins = ['*'], maxAge, methods = ['GET'], headers = {} } = options;
130
- let allowOrigin;
131
- // Initial response headers.
132
- const rHeaders = {
133
- 'content-type': 'application/json',
134
- 'Access-Control-Allow-Methods': methods.join(', '),
135
- ...headers,
136
- };
137
- // Set max age if provided.
138
- if (maxAge)
139
- rHeaders['Access-Control-Max-Age'] = maxAge;
140
- // Pre-flight function.
141
- const preflight = (r) => {
142
- // Use methods set.
143
- const useMethods = [...new Set(['OPTIONS', ...methods])];
144
- const origin = r.headers.get('origin') || '';
145
- // Set allowOrigin globally.
146
- allowOrigin = (origins.includes(origin) || origins.includes('*')) && {
147
- 'Access-Control-Allow-Origin': origin,
148
- };
149
- // Check if method is OPTIONS.
150
- if (r.method === 'OPTIONS') {
151
- const reqHeaders = {
152
- ...rHeaders,
153
- 'Access-Control-Allow-Methods': useMethods.join(', '),
154
- 'Access-Control-Allow-Headers': r.headers.get('Access-Control-Request-Headers'),
155
- ...allowOrigin,
156
- };
157
- // Handle CORS pre-flight request.
158
- return new Response(null, {
159
- headers: r.headers.get('Origin') &&
160
- r.headers.get('Access-Control-Request-Method') &&
161
- r.headers.get('Access-Control-Request-Headers')
162
- ? reqHeaders
163
- : { Allow: useMethods.join(', ') },
164
- });
165
- }
166
- };
167
- // Corsify function.
168
- const corsify = (response) => {
169
- if (!response)
170
- throw new Error('No fetch handler responded and no upstream to proxy to specified.');
171
- const { headers, status, body } = response;
172
- // Bypass for protocol shifts or redirects, or if CORS is already set.
173
- if ([101, 301, 302, 308].includes(status) ||
174
- headers.get('access-control-allow-origin'))
175
- return response;
176
- // Return new response with CORS headers.
177
- return new Response(body, {
178
- status,
179
- headers: {
180
- ...Object.fromEntries(headers),
181
- ...rHeaders,
182
- ...allowOrigin,
183
- 'content-type': headers.get('content-type'),
184
- },
185
- });
186
- };
187
- // Return corsify and preflight methods.
188
- return { corsify, preflight };
189
- };
190
-
191
- exports.Router = Router;
192
- exports.StatusError = StatusError;
193
- exports.createCors = createCors;
194
- exports.createResponse = createResponse;
195
- exports.error = error;
196
- exports.html = html;
197
- exports.jpeg = jpeg;
198
- exports.json = json;
199
- exports.png = png;
200
- exports.status = status;
201
- exports.text = text;
202
- exports.webp = webp;
203
- exports.withContent = withContent;
204
- exports.withCookies = withCookies;
205
- exports.withParams = withParams;
package/cjs/jpeg.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const jpeg: import("./createResponse").ResponseFormatter;
package/cjs/jpeg.js DELETED
@@ -1,18 +0,0 @@
1
- 'use strict';
2
-
3
- const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
4
- const { headers = {}, ...rest } = options;
5
- if (body?.constructor.name === 'Response')
6
- return body;
7
- return new Response(transform ? transform(body) : body, {
8
- headers: {
9
- 'content-type': format,
10
- ...headers,
11
- },
12
- ...rest,
13
- });
14
- };
15
-
16
- const jpeg = createResponse('image/jpeg');
17
-
18
- exports.jpeg = jpeg;
package/cjs/json.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const json: import("./createResponse").ResponseFormatter;
package/cjs/json.js DELETED
@@ -1,18 +0,0 @@
1
- 'use strict';
2
-
3
- const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
4
- const { headers = {}, ...rest } = options;
5
- if (body?.constructor.name === 'Response')
6
- return body;
7
- return new Response(transform ? transform(body) : body, {
8
- headers: {
9
- 'content-type': format,
10
- ...headers,
11
- },
12
- ...rest,
13
- });
14
- };
15
-
16
- const json = createResponse('application/json; charset=utf-8', JSON.stringify);
17
-
18
- exports.json = json;
package/cjs/png.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const png: import("./createResponse").ResponseFormatter;
package/cjs/png.js DELETED
@@ -1,18 +0,0 @@
1
- 'use strict';
2
-
3
- const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
4
- const { headers = {}, ...rest } = options;
5
- if (body?.constructor.name === 'Response')
6
- return body;
7
- return new Response(transform ? transform(body) : body, {
8
- headers: {
9
- 'content-type': format,
10
- ...headers,
11
- },
12
- ...rest,
13
- });
14
- };
15
-
16
- const png = createResponse('image/png');
17
-
18
- exports.png = png;
package/cjs/status.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const status: (status: number) => Response;
package/cjs/status.js DELETED
@@ -1,5 +0,0 @@
1
- 'use strict';
2
-
3
- const status = (status) => new Response(null, { status });
4
-
5
- exports.status = status;
package/cjs/text.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const text: (message: string, options?: ResponseInit) => Response;
package/cjs/text.js DELETED
@@ -1,5 +0,0 @@
1
- 'use strict';
2
-
3
- const text = (message, options) => new Response(message, options);
4
-
5
- exports.text = text;
package/cjs/webp.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare const webp: import("./createResponse").ResponseFormatter;
package/cjs/webp.js DELETED
@@ -1,18 +0,0 @@
1
- 'use strict';
2
-
3
- const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
4
- const { headers = {}, ...rest } = options;
5
- if (body?.constructor.name === 'Response')
6
- return body;
7
- return new Response(transform ? transform(body) : body, {
8
- headers: {
9
- 'content-type': format,
10
- ...headers,
11
- },
12
- ...rest,
13
- });
14
- };
15
-
16
- const webp = createResponse('image/webp');
17
-
18
- exports.webp = webp;
@@ -1 +0,0 @@
1
- export declare const websocket: (client: WebSocket, options?: object) => Response;
package/cjs/websocket.js DELETED
@@ -1,22 +0,0 @@
1
- 'use strict';
2
-
3
- const createResponse = (format = 'text/plain; charset=utf-8', transform) => (body, options = {}) => {
4
- const { headers = {}, ...rest } = options;
5
- if (body?.constructor.name === 'Response')
6
- return body;
7
- return new Response(transform ? transform(body) : body, {
8
- headers: {
9
- 'content-type': format,
10
- ...headers,
11
- },
12
- ...rest,
13
- });
14
- };
15
-
16
- const websocket = (client, options = {}) => createResponse()(null, {
17
- status: 101,
18
- webSocket: client,
19
- ...options,
20
- });
21
-
22
- exports.websocket = websocket;
@@ -1,2 +0,0 @@
1
- import { IRequest } from './Router';
2
- export declare const withContent: (request: IRequest) => Promise<void>;
@@ -1,9 +0,0 @@
1
- 'use strict';
2
-
3
- // withContent - embeds any request body as request.content
4
- const withContent = async (request) => {
5
- if (request.headers.get('content-type')?.includes('json'))
6
- request.content = await request.json();
7
- };
8
-
9
- exports.withContent = withContent;
@@ -1,2 +0,0 @@
1
- import { IRequest } from './Router';
2
- export declare const withCookies: (r: IRequest) => void;
@@ -1,11 +0,0 @@
1
- 'use strict';
2
-
3
- // withCookies - embeds cookies object into the request
4
- const withCookies = (r) => {
5
- r.cookies = (r.headers.get('Cookie') || '')
6
- .split(/;\s*/)
7
- .map((p) => p.split(/=(.+)/))
8
- .reduce((a, [k, v]) => (v ? ((a[k] = v), a) : a), {});
9
- };
10
-
11
- exports.withCookies = withCookies;
@@ -1,2 +0,0 @@
1
- import { IRequest } from './Router';
2
- export declare const withParams: (request: IRequest) => void;
package/cjs/withParams.js DELETED
@@ -1,14 +0,0 @@
1
- 'use strict';
2
-
3
- const withParams = (request) => {
4
- request.proxy = new Proxy(request.proxy || request, {
5
- get: (obj, prop) => {
6
- let p;
7
- if ((p = obj[prop]) !== undefined)
8
- return p.bind?.(request) || p;
9
- return obj?.params?.[prop];
10
- },
11
- });
12
- };
13
-
14
- exports.withParams = withParams;