@thi.ng/server 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,42 @@
1
+ # Change Log
2
+
3
+ - **Last updated**: 2025-01-29T16:25:48Z
4
+ - **Generator**: [thi.ng/monopub](https://thi.ng/monopub)
5
+
6
+ All notable changes to this project will be documented in this file.
7
+ Only versions published since **2022-01-01** are listed here.
8
+ Please consult the Git history for older version information.
9
+ See [Conventional Commits](https://conventionalcommits.org/) for commit guidelines.
10
+
11
+ **Note:** Unlisted _patch_ versions only involve non-code or otherwise excluded changes
12
+ and/or version bumps of transitive dependencies.
13
+
14
+ ## [0.1.0](https://github.com/thi-ng/umbrella/tree/@thi.ng/server@0.1.0) (2025-01-29)
15
+
16
+ #### 🚀 Features
17
+
18
+ - migrate/import as new pkg ([61035bb](https://github.com/thi-ng/umbrella/commit/61035bb))
19
+ - re-import various security header interceptors ([036b9b2](https://github.com/thi-ng/umbrella/commit/036b9b2))
20
+ - add interceptors:
21
+ - `crossOriginOpenerPolicy()`
22
+ - `crossOriginResourcePolicy()`
23
+ - `referrerPolicy()`
24
+ - `strictTransportSecurity()`
25
+ - add/update tests
26
+ - update sendFile(), staticFiles() and compression handling ([9f4d25a](https://github.com/thi-ng/umbrella/commit/9f4d25a))
27
+ - add support for brotli, gzip, deflate
28
+ - refactor sendFile() internals
29
+ - disable compression by default
30
+ - import refactored cacheControl() interceptor ([4eff206](https://github.com/thi-ng/umbrella/commit/4eff206))
31
+ - update pkg deps & exports
32
+ - update tests
33
+ - re-add etag support/handlers ([13fb75e](https://github.com/thi-ng/umbrella/commit/13fb75e))
34
+ - add `StaticOpts.etag`
35
+ - update `staticFiles()` HEAD/GET handlers
36
+ - add `Server.unmodified()`
37
+ - add `etagFileTimeModified()`
38
+ - add `etagFileHash()`
39
+ - add `isUnmodified()` helper
40
+ - remove "content-length" header from HEAD handler
41
+ - update tests
42
+ - add `server()` factory function (syntax sugar) ([ee22ea1](https://github.com/thi-ng/umbrella/commit/ee22ea1))
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,235 @@
1
+ <!-- This file is generated - DO NOT EDIT! -->
2
+ <!-- Please see: https://github.com/thi-ng/umbrella/blob/develop/CONTRIBUTING.md#changes-to-readme-files -->
3
+ # ![@thi.ng/server](https://media.thi.ng/umbrella/banners-20230807/thing-server.svg?ab80455e)
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@thi.ng/server.svg)](https://www.npmjs.com/package/@thi.ng/server)
6
+ ![npm downloads](https://img.shields.io/npm/dm/@thi.ng/server.svg)
7
+ [![Mastodon Follow](https://img.shields.io/mastodon/follow/109331703950160316?domain=https%3A%2F%2Fmastodon.thi.ng&style=social)](https://mastodon.thi.ng/@toxi)
8
+
9
+ > [!NOTE]
10
+ > This is one of 201 standalone projects, maintained as part
11
+ > of the [@thi.ng/umbrella](https://github.com/thi-ng/umbrella/) monorepo
12
+ > and anti-framework.
13
+ >
14
+ > 🚀 Please help me to work full-time on these projects by [sponsoring me on
15
+ > GitHub](https://github.com/sponsors/postspectacular). Thank you! ❤️
16
+
17
+ - [About](#about)
18
+ - [Main features](#main-features)
19
+ - [Interceptors](#interceptors)
20
+ - [Available interceptors](#available-interceptors)
21
+ - [Custom interceptors](#custom-interceptors)
22
+ - [Using interceptors](#using-interceptors)
23
+ - [Status](#status)
24
+ - [Installation](#installation)
25
+ - [Dependencies](#dependencies)
26
+ - [API](#api)
27
+ - [Usage example](#usage-example)
28
+ - [Authors](#authors)
29
+ - [License](#license)
30
+
31
+ ## About
32
+
33
+ Minimal HTTP server with declarative routing, static file serving and freely extensible via pre/post interceptors.
34
+
35
+ The [`Server`](https://docs.thi.ng/umbrella/server/classes/Server.html) provides
36
+ a thin veneer around the standard `node:http` / `node:https` default server
37
+ implementations.
38
+
39
+ ### Main features
40
+
41
+ - Declarative & parametric routing (incl. validation and coercion of route
42
+ params)
43
+ - Multiple HTTP methods per route
44
+ - Composable & customizable interceptors (global for all routes and/or for
45
+ indidual routes & HTTP methods)
46
+ - Asynchronous route handler processing
47
+ - Automatic parsing of cookies and URL query strings (incl. nested params)
48
+ - Configurable file serving (`ReadableStream`-based) with automatic MIME-type
49
+ detection and support for Etags, as well as Brotli, Gzip and Deflate compression
50
+ - Utilities for parsing form-encoded multipart request bodies
51
+
52
+ ### Interceptors
53
+
54
+ Interceptors are additionally injected handlers (aka middleware) which are
55
+ pre/post-processed before/after a route's main handler and can be used for
56
+ validation, cancellation or other side effects. Each single interceptor can have
57
+ a `pre` and/or `post` phase function. Post-phase interceptors are processed in
58
+ reverse order. See
59
+ [`Interceptor`](https://docs.thi.ng/umbrella/server/interfaces/Interceptor.html)
60
+ for more details.
61
+
62
+ #### Available interceptors
63
+
64
+ - [`authenticateWith()`](https://docs.thi.ng/umbrella/server/functions/authenticateWith.html)
65
+ - [`cacheControl()`](https://docs.thi.ng/umbrella/server/functions/cacheControl.html)
66
+ - [`crossOriginOpenerPolicy()`](https://docs.thi.ng/umbrella/server/functions/crossOriginOpenerPolicy.html)
67
+ - [`crossOriginResourcePolicy()`](https://docs.thi.ng/umbrella/server/functions/crossOriginResourcePolicy.html)
68
+ - [`injectHeaders()`](https://docs.thi.ng/umbrella/server/functions/injectHeaders.html)
69
+ - [`logRequest()`](https://docs.thi.ng/umbrella/server/functions/logRequest.html)
70
+ - [`logResponse()`](https://docs.thi.ng/umbrella/server/functions/logResponse.html)
71
+ - [`referrerPolicy()`](https://docs.thi.ng/umbrella/server/functions/referrerPolicy.html)
72
+ - [`serverSession()`](https://docs.thi.ng/umbrella/server/functions/serverSession.html)
73
+ - [`strictTransportSecurity()`](https://docs.thi.ng/umbrella/server/functions/strictTransportSecurity.html)
74
+
75
+ #### Custom interceptors
76
+
77
+ An example interceptor to log request and response headers:
78
+
79
+ ```ts
80
+ import type { Interceptor } from "@thi.ng/server";
81
+
82
+ export const log: Interceptor = {
83
+ pre: (ctx) => ctx.logger.debug("request headers", ctx.req.headers),
84
+ post: (ctx) => ctx.logger.debug("response headers", ctx.res.getHeaders()),
85
+ };
86
+ ```
87
+
88
+ #### Using interceptors
89
+
90
+ An example route definition with route and HTTP-method specific interceptor(s):
91
+
92
+ ```ts
93
+ import { cacheControl } from "@thi.ng/server";
94
+
95
+ {
96
+ id: "hello",
97
+ match: "/random",
98
+ handlers: {
99
+ get: {
100
+ fn: (ctx) => ctx.res.writeHead(200).end(String(Math.random())),
101
+ intercept: [
102
+ cacheControl({ noCache: true }),
103
+ ]
104
+ }
105
+ }
106
+ }
107
+ ```
108
+
109
+ ## Status
110
+
111
+ **ALPHA** - bleeding edge / work-in-progress
112
+
113
+ [Search or submit any issues for this package](https://github.com/thi-ng/umbrella/issues?q=%5Bserver%5D+in%3Atitle)
114
+
115
+ ## Installation
116
+
117
+ ```bash
118
+ yarn add @thi.ng/server
119
+ ```
120
+
121
+ ESM import:
122
+
123
+ ```ts
124
+ import * as ser from "@thi.ng/server";
125
+ ```
126
+
127
+ Browser ESM import:
128
+
129
+ ```html
130
+ <script type="module" src="https://esm.run/@thi.ng/server"></script>
131
+ ```
132
+
133
+ [JSDelivr documentation](https://www.jsdelivr.com/)
134
+
135
+ For Node.js REPL:
136
+
137
+ ```js
138
+ const ser = await import("@thi.ng/server");
139
+ ```
140
+
141
+ Package sizes (brotli'd, pre-treeshake): ESM: 3.75 KB
142
+
143
+ ## Dependencies
144
+
145
+ - [@thi.ng/api](https://github.com/thi-ng/umbrella/tree/develop/packages/api)
146
+ - [@thi.ng/arrays](https://github.com/thi-ng/umbrella/tree/develop/packages/arrays)
147
+ - [@thi.ng/cache](https://github.com/thi-ng/umbrella/tree/develop/packages/cache)
148
+ - [@thi.ng/checks](https://github.com/thi-ng/umbrella/tree/develop/packages/checks)
149
+ - [@thi.ng/errors](https://github.com/thi-ng/umbrella/tree/develop/packages/errors)
150
+ - [@thi.ng/file-io](https://github.com/thi-ng/umbrella/tree/develop/packages/file-io)
151
+ - [@thi.ng/logger](https://github.com/thi-ng/umbrella/tree/develop/packages/logger)
152
+ - [@thi.ng/mime](https://github.com/thi-ng/umbrella/tree/develop/packages/mime)
153
+ - [@thi.ng/paths](https://github.com/thi-ng/umbrella/tree/develop/packages/paths)
154
+ - [@thi.ng/router](https://github.com/thi-ng/umbrella/tree/develop/packages/router)
155
+ - [@thi.ng/strings](https://github.com/thi-ng/umbrella/tree/develop/packages/strings)
156
+ - [@thi.ng/uuid](https://github.com/thi-ng/umbrella/tree/develop/packages/uuid)
157
+
158
+ Note: @thi.ng/api is in _most_ cases a type-only import (not used at runtime)
159
+
160
+ ## API
161
+
162
+ [Generated API docs](https://docs.thi.ng/umbrella/server/)
163
+
164
+ ### Usage example
165
+
166
+ ```ts tangle:export/readme-hello.ts
167
+ import {
168
+ server, staticFiles, cacheControl, etagFileHash, logRequest
169
+ } from "@thi.ng/server";
170
+
171
+ const app = server({
172
+ routes: [
173
+ // define a route for static files
174
+ staticFiles({
175
+ compress: true,
176
+ etag: etagFileHash(),
177
+ // route specific interceptors
178
+ intercept: [
179
+ cacheControl({ maxAge: 3600 })
180
+ ]
181
+ }),
182
+ // parametric route
183
+ {
184
+ id: "hello",
185
+ match: "/hello/?name",
186
+ // optional validator(s)
187
+ validate: {
188
+ name: { check: (x) => /^[a-z]+$/i.test(x) },
189
+ },
190
+ // each route can specify handlers for various HTTP methods
191
+ handlers: {
192
+ get: async ({ match, res }) =>
193
+ res.writeHead(200, { "content-type": "text/plain"})
194
+ .end(`hello, ${match.params!.name.toLowerCase()}!`)
195
+ },
196
+ },
197
+ // another route to demonstrate role/usage of route IDs
198
+ // here we simply attempt to redirect to the above `hello` route
199
+ {
200
+ id: "alias",
201
+ match: "/alias/?name",
202
+ handlers: {
203
+ get: ({ server, match, res }) =>
204
+ server.redirectToRoute(res, { id: "hello", params: match.params })
205
+ }
206
+ }
207
+ ],
208
+ // global interceptors (used for all routes)
209
+ intercept: [
210
+ logRequest(),
211
+ ]
212
+ });
213
+
214
+ await app.start();
215
+ // [INFO] server: starting server: http://localhost:8080
216
+ ```
217
+
218
+ ## Authors
219
+
220
+ - [Karsten Schmidt](https://thi.ng)
221
+
222
+ If this project contributes to an academic publication, please cite it as:
223
+
224
+ ```bibtex
225
+ @misc{thing-server,
226
+ title = "@thi.ng/server",
227
+ author = "Karsten Schmidt",
228
+ note = "https://thi.ng/server",
229
+ year = 2024
230
+ }
231
+ ```
232
+
233
+ ## License
234
+
235
+ &copy; 2024 - 2025 Karsten Schmidt // Apache License 2.0
package/api.d.ts ADDED
@@ -0,0 +1,114 @@
1
+ import type { Fn, Maybe, MaybePromise } from "@thi.ng/api";
2
+ import type { ILogger } from "@thi.ng/logger";
3
+ import type { Route, RouteMatch } from "@thi.ng/router";
4
+ import type { IncomingMessage, ServerResponse } from "node:http";
5
+ import type { Server } from "./server.js";
6
+ import type { ServerSession } from "./interceptors/session.js";
7
+ export interface ServerOpts {
8
+ logger: ILogger;
9
+ /**
10
+ * SSL configuration
11
+ */
12
+ ssl: {
13
+ key: string;
14
+ cert: string;
15
+ };
16
+ /**
17
+ * Host name this server should respond to.
18
+ *
19
+ * @defaultValue `localhost`
20
+ */
21
+ host: string;
22
+ /**
23
+ * Port number.
24
+ *
25
+ * @defaultValue 443 / 8080
26
+ */
27
+ port: number;
28
+ /**
29
+ * Initial list of routes (more can be added dynamically via
30
+ * {@link Server.addRoutes}).
31
+ */
32
+ routes: ServerRoute[];
33
+ /**
34
+ * Route prefix. Default: `/`. All routes are assumed to have this prefix
35
+ * prepended. If given, the prefix MUST end with `/`.
36
+ */
37
+ prefix: string;
38
+ /**
39
+ * If true (default), the trailing slash of a given route input string will
40
+ * be removed before matching.
41
+ */
42
+ trim: boolean;
43
+ /**
44
+ * Interceptors (aka pre/post middlewares) which are to be applied to all
45
+ * route handlers (in the given order).
46
+ */
47
+ intercept: Interceptor[];
48
+ }
49
+ export interface ServerRoute extends Route {
50
+ handlers: Partial<Record<Method, RequestHandler>>;
51
+ }
52
+ export interface CompiledServerRoute extends Route {
53
+ handlers: Partial<Record<Method, CompiledHandler>>;
54
+ }
55
+ export interface RequestCtx {
56
+ server: Server;
57
+ logger: ILogger;
58
+ req: IncomingMessage;
59
+ res: ServerResponse;
60
+ route: CompiledServerRoute;
61
+ match: RouteMatch;
62
+ path: string;
63
+ query: Record<string, any>;
64
+ cookies?: Record<string, string>;
65
+ session?: ServerSession;
66
+ [id: string]: any;
67
+ }
68
+ export type HandlerResult = MaybePromise<Maybe<RequestCtx> | void>;
69
+ export type RequestHandler = Fn<RequestCtx, HandlerResult> | InterceptedRequestHandler;
70
+ export interface InterceptedRequestHandler {
71
+ fn: Fn<RequestCtx, HandlerResult>;
72
+ /**
73
+ * List of interceptors which will be executed when processing the main
74
+ * handler {@link InterceptedRequestHandler.fn}.
75
+ *
76
+ * @remarks
77
+ * Handler-specific interceptors will be appended to the list global
78
+ * interceptors (aka {@link ServerOpts.intercept}). Processing then happens
79
+ * in this order:
80
+ *
81
+ * - {@link Interceptor.pre} interceptors in the order given
82
+ * - {@link InterceptedRequestHandler.fn} main handler
83
+ * - {@link Interceptor.post} interceptors in the REVERSE order given
84
+ *
85
+ * If an interceptor function returns false, further processing stops and
86
+ * response will be closed.
87
+ */
88
+ intercept: Interceptor[];
89
+ }
90
+ export interface CompiledHandler {
91
+ fn: Fn<RequestCtx, HandlerResult>;
92
+ pre?: Fn<RequestCtx, InterceptorResult>[];
93
+ post?: Fn<RequestCtx, InterceptorResult>[];
94
+ }
95
+ export interface Interceptor {
96
+ /**
97
+ * Interceptor function which will be run BEFORE the main route handler (aka
98
+ * {@link InterceptedRequestHandler.fn}). If an interceptor needs to cancel
99
+ * the request processing it must return `false`. In this case any further
100
+ * pre-interceptors, the main handler and all post-interceptors will be
101
+ * skipped.
102
+ */
103
+ pre?: Fn<RequestCtx, InterceptorResult>;
104
+ /**
105
+ * Interceptor function which will be run AFTER the main route handler (aka
106
+ * {@link InterceptedRequestHandler.fn}). If an interceptor needs to cancel
107
+ * the request processing it must return `false`. In this case any further
108
+ * post-interceptors will be skipped.
109
+ */
110
+ post?: Fn<RequestCtx, InterceptorResult>;
111
+ }
112
+ export type InterceptorResult = MaybePromise<boolean>;
113
+ export type Method = "get" | "put" | "post" | "delete" | "head" | "options" | "patch";
114
+ //# sourceMappingURL=api.d.ts.map
package/api.js ADDED
File without changes
package/index.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ export * from "./api.js";
2
+ export * from "./server.js";
3
+ export * from "./static.js";
4
+ export * from "./interceptors/auth-route.js";
5
+ export * from "./interceptors/cache-control.js";
6
+ export * from "./interceptors/inject-headers.js";
7
+ export * from "./interceptors/logging.js";
8
+ export * from "./interceptors/referrer-policy.js";
9
+ export * from "./interceptors/session.js";
10
+ export * from "./interceptors/strict-transport.js";
11
+ export * from "./interceptors/x-origin-opener.js";
12
+ export * from "./interceptors/x-origin-resource.js";
13
+ export * from "./utils/cookies.js";
14
+ export * from "./utils/cache.js";
15
+ export * from "./utils/formdata.js";
16
+ export * from "./utils/multipart.js";
17
+ //# sourceMappingURL=index.d.ts.map
package/index.js ADDED
@@ -0,0 +1,16 @@
1
+ export * from "./api.js";
2
+ export * from "./server.js";
3
+ export * from "./static.js";
4
+ export * from "./interceptors/auth-route.js";
5
+ export * from "./interceptors/cache-control.js";
6
+ export * from "./interceptors/inject-headers.js";
7
+ export * from "./interceptors/logging.js";
8
+ export * from "./interceptors/referrer-policy.js";
9
+ export * from "./interceptors/session.js";
10
+ export * from "./interceptors/strict-transport.js";
11
+ export * from "./interceptors/x-origin-opener.js";
12
+ export * from "./interceptors/x-origin-resource.js";
13
+ export * from "./utils/cookies.js";
14
+ export * from "./utils/cache.js";
15
+ export * from "./utils/formdata.js";
16
+ export * from "./utils/multipart.js";
@@ -0,0 +1,18 @@
1
+ import type { Predicate } from "@thi.ng/api";
2
+ import type { Interceptor, RequestCtx } from "../api.js";
3
+ /**
4
+ * Pre-interceptor. Checks if current route has `auth` flag enabled and if so
5
+ * applies given predicate function to {@link RequestCtx}. If the predicate
6
+ * returns false, the server responds with {@link Server.unauthorized} and any
7
+ * following pre-interceptors and the main route handler will be skipped. Only
8
+ * post-interceptors (if any) will still be executed.
9
+ *
10
+ * @remarks
11
+ * If this interceptor is used with the {@link serverSession} interceptor, it
12
+ * MUST come after it, otherwise the session information will not yet be
13
+ * available in the context object given to the predicate.
14
+ *
15
+ * @param pred
16
+ */
17
+ export declare const authenticateWith: (pred: Predicate<RequestCtx>) => Interceptor;
18
+ //# sourceMappingURL=auth-route.d.ts.map
@@ -0,0 +1,12 @@
1
+ const authenticateWith = (pred) => ({
2
+ pre: (ctx) => {
3
+ if (ctx.route.auth && !pred(ctx)) {
4
+ ctx.server.unauthorized(ctx.res);
5
+ return false;
6
+ }
7
+ return true;
8
+ }
9
+ });
10
+ export {
11
+ authenticateWith
12
+ };