@cfworker/web 1.9.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.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Jeremy Danyow
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,91 @@
1
+ # @cfworker/web
2
+
3
+ ![](https://badgen.net/bundlephobia/minzip/@cfworker/web)
4
+ ![](https://badgen.net/bundlephobia/min/@cfworker/web)
5
+ ![](https://badgen.net/bundlephobia/dependency-count/@cfworker/web)
6
+ ![](https://badgen.net/bundlephobia/tree-shaking/@cfworker/web)
7
+ ![](https://badgen.net/npm/types/@cfworker/web?icon=typescript)
8
+
9
+ Web framework for Cloudflare Workers and service workers, inspired by Koa and fastify.
10
+
11
+ ```ts
12
+ import {
13
+ Application,
14
+ Middleware,
15
+ Router,
16
+ validate,
17
+ normalizePathnameMiddleware
18
+ } from '@cfworker/web';
19
+
20
+ const router = new Router();
21
+
22
+ // Add the homepage route.
23
+ router.get('/', ({ res }) => {
24
+ res.body = `
25
+ <h1>@cfworker/web demo</h1>
26
+ <h2 id="example-routes">Example routes</h2>
27
+ <ol aria-labelledby="example-routes">
28
+ <li><a href="/greetings/hello">A valid greeting</a></li>
29
+ <li><a href="/greetings/hell">An invalid greeting</a></li>
30
+ <li><a href="/error">A route with a bug</a></li>
31
+ </ol>
32
+ <img src="favicon.ico" alt="cfworker logo">`;
33
+ });
34
+
35
+ // Add a greeting route with validation.
36
+ router.get(
37
+ '/greetings/:greeting',
38
+ validate({
39
+ params: {
40
+ required: ['greeting'],
41
+ properties: {
42
+ greeting: {
43
+ minLength: 5,
44
+ maxLength: 10
45
+ }
46
+ }
47
+ }
48
+ }),
49
+ ({ req, res }) => {
50
+ res.body = req.params;
51
+ }
52
+ );
53
+
54
+ // Add a route to demonstrate exception handling.
55
+ router.get('/error', () => {
56
+ // @ts-ignore - this route has a bug!
57
+ req.this.method.does.not.exist();
58
+ });
59
+
60
+ // Favicon route for fun :)
61
+ router.get('/favicon.ico', ({ res }) => {
62
+ res.type = 'image/svg+xml';
63
+ res.body = `
64
+ <svg xmlns="http://www.w3.org/2000/svg" baseProfile="full" width="200" height="200">
65
+ <rect width="100%" height="100%" fill="#F38020"/>
66
+ <text font-size="120" font-family="Arial, Helvetica, sans-serif" text-anchor="end" fill="#FFF" x="185" y="185">W</text>
67
+ </svg>`;
68
+ });
69
+
70
+ // Simple CORS middleware.
71
+ const cors: Middleware = async ({ res }, next) => {
72
+ res.headers.set('access-control-allow-origin', '*');
73
+ await next();
74
+ };
75
+
76
+ // Compose the application
77
+ new Application()
78
+ .use(normalizePathnameMiddleware)
79
+ .use(cors)
80
+ .use(router.middleware)
81
+ .listen();
82
+ ```
83
+
84
+ [To run this example](/packages/examples/web/index.ts):
85
+
86
+ ```
87
+ git clone https://github.com/cfworker/cfworker
88
+ cd cfworker
89
+ npm install
90
+ npm run start-web --workspace=@cfworker/examples
91
+ ```
@@ -0,0 +1,12 @@
1
+ export declare class Accepts {
2
+ private readonly headers;
3
+ private _type;
4
+ private _language;
5
+ private _encoding;
6
+ private _charset;
7
+ constructor(headers: Headers);
8
+ type<T extends string>(...values: T[]): T | false;
9
+ language<T extends string>(...values: T[]): T | false;
10
+ encoding<T extends string>(...values: T[]): T | false;
11
+ charset<T extends string>(...values: T[]): T | false;
12
+ }
@@ -0,0 +1,77 @@
1
+ import { preferredCharsets } from 'negotiator/lib/charset.js';
2
+ import { preferredEncodings } from 'negotiator/lib/encoding.js';
3
+ import { preferredLanguages } from 'negotiator/lib/language.js';
4
+ import { preferredMediaTypes } from 'negotiator/lib/mediaType.js';
5
+ const parseAccept = preferredMediaTypes;
6
+ const parseAcceptLanguage = preferredLanguages;
7
+ const parseAcceptEncoding = preferredEncodings;
8
+ const parseAcceptCharset = preferredCharsets;
9
+ export class Accepts {
10
+ headers;
11
+ _type = undefined;
12
+ _language = undefined;
13
+ _encoding = undefined;
14
+ _charset = undefined;
15
+ constructor(headers) {
16
+ this.headers = headers;
17
+ }
18
+ type(...values) {
19
+ if (!this._type) {
20
+ const header = this.headers.get('accept');
21
+ this._type = header ? parseAccept(header.toLowerCase()) : [];
22
+ }
23
+ for (const accepted of this._type) {
24
+ for (const value of values) {
25
+ if (value === accepted ||
26
+ (accepted.startsWith('*') && value.endsWith(accepted.substr(1))) ||
27
+ (accepted.endsWith('*') &&
28
+ value.startsWith(accepted.substr(0, accepted.length - 2)))) {
29
+ return value;
30
+ }
31
+ }
32
+ }
33
+ return false;
34
+ }
35
+ language(...values) {
36
+ if (!this._language) {
37
+ const header = this.headers.get('accept-language');
38
+ this._language = header ? parseAcceptLanguage(header.toLowerCase()) : [];
39
+ }
40
+ for (const accepted of this._language) {
41
+ for (const value of values) {
42
+ if (value === accepted || value.startsWith(accepted)) {
43
+ return value;
44
+ }
45
+ }
46
+ }
47
+ return false;
48
+ }
49
+ encoding(...values) {
50
+ if (!this._encoding) {
51
+ const header = this.headers.get('accept-encoding');
52
+ this._encoding = header ? parseAcceptEncoding(header.toLowerCase()) : [];
53
+ }
54
+ for (const accepted of this._encoding) {
55
+ for (const value of values) {
56
+ if (value === accepted) {
57
+ return value;
58
+ }
59
+ }
60
+ }
61
+ return false;
62
+ }
63
+ charset(...values) {
64
+ if (!this._charset) {
65
+ const header = this.headers.get('accept-charset');
66
+ this._charset = header ? parseAcceptCharset(header.toLowerCase()) : [];
67
+ }
68
+ for (const accepted of this._charset) {
69
+ for (const value of values) {
70
+ if (value === accepted) {
71
+ return value;
72
+ }
73
+ }
74
+ }
75
+ return false;
76
+ }
77
+ }
@@ -0,0 +1,8 @@
1
+ import { Middleware } from './middleware.js';
2
+ export declare class Application {
3
+ private readonly middleware;
4
+ use(middleware: Middleware): this;
5
+ listen(): void;
6
+ private handleFetch;
7
+ private invokeMiddleware;
8
+ }
@@ -0,0 +1,39 @@
1
+ import statuses from 'statuses';
2
+ import { Context } from './context.js';
3
+ import { HttpError } from './http-error.js';
4
+ import { composeMiddleware } from './middleware.js';
5
+ const resolved = Promise.resolve();
6
+ export class Application {
7
+ middleware = [];
8
+ use(middleware) {
9
+ this.middleware.push(middleware);
10
+ return this;
11
+ }
12
+ listen() {
13
+ const middleware = composeMiddleware(this.middleware);
14
+ addEventListener('fetch', event => this.handleFetch(event, middleware));
15
+ }
16
+ handleFetch(event, middleware) {
17
+ const context = new Context(event);
18
+ event.respondWith(Promise.race([
19
+ this.invokeMiddleware(context, middleware),
20
+ context.responded
21
+ ]));
22
+ }
23
+ async invokeMiddleware(context, middleware) {
24
+ try {
25
+ await middleware(context, () => resolved);
26
+ return context.res.create();
27
+ }
28
+ catch (err) {
29
+ console.error(err);
30
+ if (err instanceof HttpError) {
31
+ return err.toResponse();
32
+ }
33
+ const status = 500;
34
+ const statusText = statuses[500];
35
+ const headers = { 'content-type': 'text/plain' };
36
+ return new Response(statusText, { status, statusText, headers });
37
+ }
38
+ }
39
+ }
@@ -0,0 +1,14 @@
1
+ import { Cookies } from './cookies.js';
2
+ import { Req } from './req.js';
3
+ import { ResponseBuilder } from './response-builder.js';
4
+ export declare class Context {
5
+ private readonly event;
6
+ readonly req: Req;
7
+ readonly res: ResponseBuilder;
8
+ readonly cookies: Cookies;
9
+ readonly respondWith: (response: Response) => void;
10
+ readonly responded: Promise<Response>;
11
+ readonly state: any;
12
+ constructor(event: FetchEvent);
13
+ waitUntil(promise: Promise<any>): void;
14
+ }
@@ -0,0 +1,26 @@
1
+ import { Cookies } from './cookies.js';
2
+ import { Req } from './req.js';
3
+ import { ResponseBuilder } from './response-builder.js';
4
+ export class Context {
5
+ event;
6
+ req;
7
+ res;
8
+ cookies;
9
+ respondWith;
10
+ responded;
11
+ state;
12
+ constructor(event) {
13
+ this.event = event;
14
+ const request = event.request;
15
+ this.req = new Req(request);
16
+ this.res = new ResponseBuilder();
17
+ this.cookies = new Cookies(request.headers, this.res.headers);
18
+ this.responded = new Promise(resolve => {
19
+ this.respondWith = resolve;
20
+ });
21
+ this.state = {};
22
+ }
23
+ waitUntil(promise) {
24
+ this.event.waitUntil(promise);
25
+ }
26
+ }
@@ -0,0 +1,8 @@
1
+ import { CookieSerializeOptions } from 'cookie';
2
+ export declare class Cookies {
3
+ private readonly responseHeaders;
4
+ private readonly requestCookies;
5
+ constructor(requestHeaders: Headers, responseHeaders: Headers);
6
+ get(name: string): string | null;
7
+ set(name: string, val: string, options?: CookieSerializeOptions): void;
8
+ }
@@ -0,0 +1,17 @@
1
+ import { parse as parseCookie, serialize as serializeCookie } from 'cookie';
2
+ const noCookies = Object.create(null);
3
+ export class Cookies {
4
+ responseHeaders;
5
+ requestCookies;
6
+ constructor(requestHeaders, responseHeaders) {
7
+ this.responseHeaders = responseHeaders;
8
+ const cookie = requestHeaders.get('cookie');
9
+ this.requestCookies = cookie ? parseCookie(cookie) : noCookies;
10
+ }
11
+ get(name) {
12
+ return this.requestCookies[name] || null;
13
+ }
14
+ set(name, val, options) {
15
+ this.responseHeaders.append('Set-Cookie', serializeCookie(name, val, options));
16
+ }
17
+ }
@@ -0,0 +1,7 @@
1
+ export declare class HttpError extends Error {
2
+ readonly status: number;
3
+ readonly statusText: string;
4
+ readonly body: string | object;
5
+ constructor(status: number, body: string | object);
6
+ toResponse(): Response;
7
+ }
@@ -0,0 +1,31 @@
1
+ import statuses from 'statuses';
2
+ export class HttpError extends Error {
3
+ status;
4
+ statusText;
5
+ body;
6
+ constructor(status, body) {
7
+ const statusText = statuses[statuses(status)];
8
+ super(statusText);
9
+ this.name = this.constructor.name;
10
+ if (typeof Error.captureStackTrace === 'function') {
11
+ Error.captureStackTrace(this, this.constructor);
12
+ }
13
+ this.status = status;
14
+ this.statusText = statusText;
15
+ this.body = body;
16
+ }
17
+ toResponse() {
18
+ let body = this.body || this.statusText;
19
+ let contentType;
20
+ if (typeof body === 'string') {
21
+ contentType = 'text/plain';
22
+ }
23
+ else {
24
+ contentType = 'application/json';
25
+ body = JSON.stringify(body);
26
+ }
27
+ const { status, statusText } = this;
28
+ const headers = { 'content-type': contentType };
29
+ return new Response(body, { status, statusText, headers });
30
+ }
31
+ }
@@ -0,0 +1,13 @@
1
+ export { escape as htmlEncode } from 'html-escaper';
2
+ export * from './accepts.js';
3
+ export * from './application.js';
4
+ export * from './context.js';
5
+ export * from './cookies.js';
6
+ export * from './http-error.js';
7
+ export * from './middleware.js';
8
+ export * from './normalize-pathname.js';
9
+ export * from './req.js';
10
+ export * from './response-builder.js';
11
+ export * from './router.js';
12
+ export * from './to-object.js';
13
+ export * from './validate.js';
package/dist/index.js ADDED
@@ -0,0 +1,13 @@
1
+ export { escape as htmlEncode } from 'html-escaper';
2
+ export * from './accepts.js';
3
+ export * from './application.js';
4
+ export * from './context.js';
5
+ export * from './cookies.js';
6
+ export * from './http-error.js';
7
+ export * from './middleware.js';
8
+ export * from './normalize-pathname.js';
9
+ export * from './req.js';
10
+ export * from './response-builder.js';
11
+ export * from './router.js';
12
+ export * from './to-object.js';
13
+ export * from './validate.js';
@@ -0,0 +1,4 @@
1
+ import compose, { Middleware as GenericMiddleware } from 'koa-compose';
2
+ import { Context } from './context.js';
3
+ export declare type Middleware = GenericMiddleware<Context>;
4
+ export declare const composeMiddleware: typeof compose;
@@ -0,0 +1,2 @@
1
+ import compose from 'koa-compose';
2
+ export const composeMiddleware = compose;
@@ -0,0 +1,3 @@
1
+ import { Middleware } from './middleware';
2
+ export declare function normalizePathname(pathname: string): string;
3
+ export declare const normalizePathnameMiddleware: Middleware;
@@ -0,0 +1,17 @@
1
+ import { HttpError } from './http-error';
2
+ export function normalizePathname(pathname) {
3
+ return decodeURIComponent(pathname).replace(/\/\/+/g, '/').normalize();
4
+ }
5
+ export const normalizePathnameMiddleware = async ({ req }, next) => {
6
+ const pathname = req.url.pathname;
7
+ try {
8
+ req.url.pathname = normalizePathname(pathname);
9
+ }
10
+ catch (err) {
11
+ if (err instanceof URIError) {
12
+ throw new HttpError(400, `Unable to decode pathname "${pathname}".`);
13
+ }
14
+ throw err;
15
+ }
16
+ await next();
17
+ };
package/dist/req.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { Reviver } from 'secure-json-parse';
2
+ import { Accepts } from './accepts.js';
3
+ export declare class Req {
4
+ readonly raw: Request;
5
+ readonly method: string;
6
+ readonly url: URL;
7
+ readonly headers: Headers;
8
+ readonly params: Record<string, string>;
9
+ readonly accepts: Accepts;
10
+ readonly body: ReqBody;
11
+ constructor(request: Request);
12
+ }
13
+ export declare class ReqBody {
14
+ private readonly request;
15
+ private _arrayBuffer;
16
+ private _formData;
17
+ private _json;
18
+ private _text;
19
+ constructor(request: Request);
20
+ arrayBuffer(): Promise<ArrayBuffer>;
21
+ formData(): Promise<FormData>;
22
+ json(reviver?: Reviver): Promise<any>;
23
+ text(): Promise<string>;
24
+ }