@tessellation/http 0.0.0-stage → 2.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 (119) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +412 -2
  3. package/dist/index.d.ts +20 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +16 -0
  6. package/dist/lib/auth/api-key.d.ts +17 -0
  7. package/dist/lib/auth/api-key.d.ts.map +1 -0
  8. package/dist/lib/auth/api-key.js +48 -0
  9. package/dist/lib/auth/jwt.d.ts +33 -0
  10. package/dist/lib/auth/jwt.d.ts.map +1 -0
  11. package/dist/lib/auth/jwt.js +227 -0
  12. package/dist/lib/auth/provide-auth.d.ts +30 -0
  13. package/dist/lib/auth/provide-auth.d.ts.map +1 -0
  14. package/dist/lib/auth/provide-auth.js +69 -0
  15. package/dist/lib/auth/strategy.d.ts +47 -0
  16. package/dist/lib/auth/strategy.d.ts.map +1 -0
  17. package/dist/lib/auth/strategy.js +18 -0
  18. package/dist/lib/compile.d.ts +46 -0
  19. package/dist/lib/compile.d.ts.map +1 -0
  20. package/dist/lib/compile.js +126 -0
  21. package/dist/lib/compression.d.ts +23 -0
  22. package/dist/lib/compression.d.ts.map +1 -0
  23. package/dist/lib/compression.js +86 -0
  24. package/dist/lib/config.d.ts +173 -0
  25. package/dist/lib/config.d.ts.map +1 -0
  26. package/dist/lib/config.js +93 -0
  27. package/dist/lib/cors.d.ts +41 -0
  28. package/dist/lib/cors.d.ts.map +1 -0
  29. package/dist/lib/cors.js +101 -0
  30. package/dist/lib/docs.d.ts +15 -0
  31. package/dist/lib/docs.d.ts.map +1 -0
  32. package/dist/lib/docs.js +93 -0
  33. package/dist/lib/engine.d.ts +83 -0
  34. package/dist/lib/engine.d.ts.map +1 -0
  35. package/dist/lib/engine.js +562 -0
  36. package/dist/lib/errors.d.ts +31 -0
  37. package/dist/lib/errors.d.ts.map +1 -0
  38. package/dist/lib/errors.js +55 -0
  39. package/dist/lib/etag.d.ts +5 -0
  40. package/dist/lib/etag.d.ts.map +1 -0
  41. package/dist/lib/etag.js +30 -0
  42. package/dist/lib/headers.d.ts +3 -0
  43. package/dist/lib/headers.d.ts.map +1 -0
  44. package/dist/lib/headers.js +14 -0
  45. package/dist/lib/json-schema.d.ts +11 -0
  46. package/dist/lib/json-schema.d.ts.map +1 -0
  47. package/dist/lib/json-schema.js +23 -0
  48. package/dist/lib/openapi.d.ts +18 -0
  49. package/dist/lib/openapi.d.ts.map +1 -0
  50. package/dist/lib/openapi.js +218 -0
  51. package/dist/lib/rate-limit.d.ts +52 -0
  52. package/dist/lib/rate-limit.d.ts.map +1 -0
  53. package/dist/lib/rate-limit.js +87 -0
  54. package/dist/lib/reply.d.ts +27 -0
  55. package/dist/lib/reply.d.ts.map +1 -0
  56. package/dist/lib/reply.js +52 -0
  57. package/dist/lib/request.d.ts +55 -0
  58. package/dist/lib/request.d.ts.map +1 -0
  59. package/dist/lib/request.js +36 -0
  60. package/dist/lib/router.d.ts +35 -0
  61. package/dist/lib/router.d.ts.map +1 -0
  62. package/dist/lib/router.js +173 -0
  63. package/dist/lib/routes.d.ts +196 -0
  64. package/dist/lib/routes.d.ts.map +1 -0
  65. package/dist/lib/routes.js +98 -0
  66. package/dist/lib/security-headers.d.ts +19 -0
  67. package/dist/lib/security-headers.d.ts.map +1 -0
  68. package/dist/lib/security-headers.js +22 -0
  69. package/dist/lib/serializer.d.ts +35 -0
  70. package/dist/lib/serializer.d.ts.map +1 -0
  71. package/dist/lib/serializer.js +147 -0
  72. package/dist/lib/server.d.ts +86 -0
  73. package/dist/lib/server.d.ts.map +1 -0
  74. package/dist/lib/server.js +255 -0
  75. package/dist/lib/testing.d.ts +21 -0
  76. package/dist/lib/testing.d.ts.map +1 -0
  77. package/dist/lib/testing.js +62 -0
  78. package/dist/lib/transports/node.d.ts +4 -0
  79. package/dist/lib/transports/node.d.ts.map +1 -0
  80. package/dist/lib/transports/node.js +249 -0
  81. package/dist/lib/transports/transport.d.ts +32 -0
  82. package/dist/lib/transports/transport.d.ts.map +1 -0
  83. package/dist/lib/transports/transport.js +1 -0
  84. package/dist/lib/transports/uws.d.ts +8 -0
  85. package/dist/lib/transports/uws.d.ts.map +1 -0
  86. package/dist/lib/transports/uws.js +246 -0
  87. package/dist/lib/websocket.d.ts +71 -0
  88. package/dist/lib/websocket.d.ts.map +1 -0
  89. package/dist/lib/websocket.js +125 -0
  90. package/package.json +67 -3
  91. package/src/index.ts +103 -0
  92. package/src/lib/auth/api-key.ts +73 -0
  93. package/src/lib/auth/jwt.ts +339 -0
  94. package/src/lib/auth/provide-auth.ts +99 -0
  95. package/src/lib/auth/strategy.ts +66 -0
  96. package/src/lib/compile.ts +207 -0
  97. package/src/lib/compression.ts +121 -0
  98. package/src/lib/config.ts +107 -0
  99. package/src/lib/cors.ts +146 -0
  100. package/src/lib/docs.ts +115 -0
  101. package/src/lib/engine.ts +770 -0
  102. package/src/lib/errors.ts +84 -0
  103. package/src/lib/etag.ts +37 -0
  104. package/src/lib/headers.ts +18 -0
  105. package/src/lib/json-schema.ts +36 -0
  106. package/src/lib/openapi.ts +299 -0
  107. package/src/lib/rate-limit.ts +142 -0
  108. package/src/lib/reply.ts +70 -0
  109. package/src/lib/request.ts +83 -0
  110. package/src/lib/router.ts +217 -0
  111. package/src/lib/routes.ts +414 -0
  112. package/src/lib/security-headers.ts +38 -0
  113. package/src/lib/serializer.ts +203 -0
  114. package/src/lib/server.ts +352 -0
  115. package/src/lib/testing.ts +88 -0
  116. package/src/lib/transports/node.ts +315 -0
  117. package/src/lib/transports/transport.ts +39 -0
  118. package/src/lib/transports/uws.ts +310 -0
  119. package/src/lib/websocket.ts +184 -0
@@ -0,0 +1,38 @@
1
+ export interface SecurityHeaderOptions {
2
+ /**
3
+ * `strict-transport-security` max-age in milliseconds, such as 180 days.
4
+ * Off unless set; only enable it when the API is served over HTTPS.
5
+ */
6
+ hsts?: number;
7
+ /** `x-frame-options`. Defaults to DENY. */
8
+ frameOptions?: 'DENY' | 'SAMEORIGIN';
9
+ /** `referrer-policy`. Defaults to no-referrer. */
10
+ referrerPolicy?: string;
11
+ /** `content-security-policy`. Off unless set. */
12
+ contentSecurityPolicy?: string;
13
+ }
14
+
15
+ /**
16
+ * Headers added to every response that does not already set them. The
17
+ * defaults suit a JSON API: no MIME sniffing, no framing, no referrers.
18
+ */
19
+ export function securityHeaders(
20
+ options: SecurityHeaderOptions = {},
21
+ ): [string, string][] {
22
+ const headers: [string, string][] = [
23
+ ['x-content-type-options', 'nosniff'],
24
+ ['x-frame-options', options.frameOptions ?? 'DENY'],
25
+ ['referrer-policy', options.referrerPolicy ?? 'no-referrer'],
26
+ ['cross-origin-opener-policy', 'same-origin'],
27
+ ];
28
+ if (options.hsts !== undefined && options.hsts > 0) {
29
+ headers.push([
30
+ 'strict-transport-security',
31
+ `max-age=${Math.floor(options.hsts / 1000)}; includeSubDomains`,
32
+ ]);
33
+ }
34
+ if (options.contentSecurityPolicy !== undefined) {
35
+ headers.push(['content-security-policy', options.contentSecurityPolicy]);
36
+ }
37
+ return headers;
38
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Response serialization driven by a route's response schema.
3
+ *
4
+ * Benchmarks on Node 26 showed that V8's `JSON.stringify` (C++, with a
5
+ * vectorized escaping scan) beats any serializer generated in JavaScript on
6
+ * string-heavy payloads: escaping checks alone cost ~28ns per string in JS.
7
+ * So V8 does the serializing, and the schema decides what is serialized: a
8
+ * compiled projection copies only declared properties, so fields a handler
9
+ * returns by accident (such as a password hash) never leak. Projection plus
10
+ * `JSON.stringify` measured within ~5% of `JSON.stringify` alone.
11
+ *
12
+ * Local references (`#/$defs/...`, which Zod emits for schemas named with
13
+ * `.meta({ id })`) are followed, including recursive ones. Parts of a schema
14
+ * without a fixed set of properties (records, open objects, unions other
15
+ * than `T | null`, other references) are passed through as-is.
16
+ */
17
+
18
+ export type JsonSchema =
19
+ | boolean
20
+ | {
21
+ type?: string | string[];
22
+ properties?: Record<string, JsonSchema>;
23
+ additionalProperties?: JsonSchema;
24
+ patternProperties?: Record<string, JsonSchema>;
25
+ items?: JsonSchema;
26
+ prefixItems?: JsonSchema[];
27
+ anyOf?: JsonSchema[];
28
+ oneOf?: JsonSchema[];
29
+ [key: string]: unknown;
30
+ };
31
+
32
+ export type Serializer = (value: unknown) => string;
33
+ type Projection = (value: unknown) => unknown;
34
+
35
+ const LOCAL_REF = /^#\/\$defs\/(.+)$/;
36
+
37
+ class Compiler {
38
+ private readonly functions: string[] = [];
39
+ /** Function names for `$defs` entries, so each is compiled once (and recursion terminates). */
40
+ private readonly definitions = new Map<string, string | undefined>();
41
+
42
+ constructor(private readonly defs: Record<string, JsonSchema>) {}
43
+
44
+ /**
45
+ * Returns the name of a generated function projecting values of `schema`,
46
+ * or undefined when values pass through unchanged.
47
+ */
48
+ compile(schema: JsonSchema): string | undefined {
49
+ if (typeof schema !== 'object') {
50
+ return undefined;
51
+ }
52
+
53
+ if (typeof schema['$ref'] === 'string') {
54
+ return this.reference(schema['$ref']);
55
+ }
56
+
57
+ const nullable = nullableInner(schema);
58
+ if (nullable !== undefined) {
59
+ const inner = this.compile(nullable);
60
+ return inner === undefined
61
+ ? undefined
62
+ : this.define(
63
+ (name) =>
64
+ `function ${name}(v) { return v === null ? null : ${inner}(v); }`,
65
+ );
66
+ }
67
+
68
+ if (
69
+ schema.type === 'array' &&
70
+ schema.items !== undefined &&
71
+ schema.prefixItems === undefined
72
+ ) {
73
+ const item = this.compile(schema.items);
74
+ return item === undefined
75
+ ? undefined
76
+ : this.define(
77
+ (name) =>
78
+ `function ${name}(v) {\n` +
79
+ ` if (!Array.isArray(v)) return v;\n` +
80
+ ` const n = v.length, out = new Array(n);\n` +
81
+ ` for (let i = 0; i < n; i++) out[i] = ${item}(v[i]);\n` +
82
+ ` return out;\n}`,
83
+ );
84
+ }
85
+
86
+ if (
87
+ schema.type === 'object' &&
88
+ schema.properties !== undefined &&
89
+ !keepsExtraProperties(schema)
90
+ ) {
91
+ const entries = Object.entries(schema.properties).map(
92
+ ([key, property]) => {
93
+ const access = `v[${JSON.stringify(key)}]`;
94
+ const fn = this.compile(property);
95
+ // A literal "__proto__" key would set the prototype; compute it instead.
96
+ const literalKey =
97
+ key === '__proto__'
98
+ ? `[${JSON.stringify(key)}]`
99
+ : JSON.stringify(key);
100
+ return `${literalKey}: ${fn === undefined ? access : `${fn}(${access})`}`;
101
+ },
102
+ );
103
+ return this.define(
104
+ (name) =>
105
+ `function ${name}(v) {\n` +
106
+ ` if (typeof v !== 'object' || v === null || Array.isArray(v) || typeof v.toJSON === 'function') return v;\n` +
107
+ ` return { ${entries.join(', ')} };\n}`,
108
+ );
109
+ }
110
+
111
+ return undefined;
112
+ }
113
+
114
+ private reference(ref: string): string | undefined {
115
+ const name = LOCAL_REF.exec(ref)?.[1];
116
+ const definition = name === undefined ? undefined : this.defs[name];
117
+ if (name === undefined || definition === undefined) {
118
+ return undefined;
119
+ }
120
+ if (this.definitions.has(name)) {
121
+ return this.definitions.get(name);
122
+ }
123
+
124
+ // Reserve a name first, so a definition referring to itself calls it.
125
+ const fn = `d${this.definitions.size}`;
126
+ this.definitions.set(name, fn);
127
+ const body = this.compile(definition);
128
+ if (body === undefined) {
129
+ this.definitions.set(name, undefined);
130
+ // Earlier references (in recursive schemas) need the function to exist.
131
+ this.functions.push(`function ${fn}(v) { return v; }`);
132
+ return undefined;
133
+ }
134
+ this.functions.push(`function ${fn}(v) { return ${body}(v); }`);
135
+ return fn;
136
+ }
137
+
138
+ source(entry: string): string {
139
+ return `${this.functions.join('\n')}\nreturn ${entry};`;
140
+ }
141
+
142
+ private define(build: (name: string) => string): string {
143
+ const name = `p${this.functions.length}`;
144
+ this.functions.push(build(name));
145
+ return name;
146
+ }
147
+ }
148
+
149
+ function keepsExtraProperties(schema: Exclude<JsonSchema, boolean>): boolean {
150
+ return (
151
+ (schema.additionalProperties !== undefined &&
152
+ schema.additionalProperties !== false) ||
153
+ schema.patternProperties !== undefined
154
+ );
155
+ }
156
+
157
+ /** For `T | null` (as `anyOf`/`oneOf` or a type list), returns the schema of `T`. */
158
+ function nullableInner(
159
+ schema: Exclude<JsonSchema, boolean>,
160
+ ): JsonSchema | undefined {
161
+ const options = schema.anyOf ?? schema.oneOf;
162
+ if (options?.length === 2 && Object.keys(schema).length === 1) {
163
+ const nonNull = options.filter(
164
+ (option) => !(typeof option === 'object' && option.type === 'null'),
165
+ );
166
+ if (nonNull.length === 1) {
167
+ return nonNull[0];
168
+ }
169
+ }
170
+ if (
171
+ Array.isArray(schema.type) &&
172
+ schema.type.length === 2 &&
173
+ schema.type.includes('null')
174
+ ) {
175
+ return { ...schema, type: schema.type.find((type) => type !== 'null') };
176
+ }
177
+ return undefined;
178
+ }
179
+
180
+ /** Compiles a projection keeping only declared properties, or undefined if none applies. */
181
+ export function compileProjection(schema: JsonSchema): Projection | undefined {
182
+ const defs =
183
+ typeof schema === 'object' &&
184
+ typeof schema['$defs'] === 'object' &&
185
+ schema['$defs'] !== null
186
+ ? (schema['$defs'] as Record<string, JsonSchema>)
187
+ : {};
188
+ const compiler = new Compiler(defs);
189
+ const entry = compiler.compile(schema);
190
+ if (entry === undefined) {
191
+ return undefined;
192
+ }
193
+ // Keys are embedded only through JSON.stringify, never as raw source.
194
+ return new Function(compiler.source(entry))() as Projection;
195
+ }
196
+
197
+ /** A serializer for values described by `schema`: projection, then `JSON.stringify`. */
198
+ export function compileSerializer(schema: JsonSchema): Serializer {
199
+ const project = compileProjection(schema);
200
+ return project === undefined
201
+ ? (value) => JSON.stringify(value)
202
+ : (value) => JSON.stringify(project(value));
203
+ }
@@ -0,0 +1,352 @@
1
+ import {
2
+ inject,
3
+ METRICS,
4
+ InjectionToken,
5
+ Injector,
6
+ Logger,
7
+ onShutdown,
8
+ onStart,
9
+ provide,
10
+ provideConfig,
11
+ Tracer,
12
+ type ProvidedIn,
13
+ type Provider,
14
+ } from '@tessellation/core';
15
+
16
+ import { AUTH_STRATEGIES } from './auth/strategy.js';
17
+ import { compileRoutes } from './compile.js';
18
+ import { Compressor } from './compression.js';
19
+ import { HttpConfig, type HttpSettings } from './config.js';
20
+ import { CorsPolicy } from './cors.js';
21
+ import { docsRoutes } from './docs.js';
22
+ import { HttpEngine } from './engine.js';
23
+ import { rateLimit } from './rate-limit.js';
24
+ import type { Middleware, RouteTree } from './routes.js';
25
+ import { securityHeaders } from './security-headers.js';
26
+ import { nodeTransport } from './transports/node.js';
27
+ import {
28
+ dispatch,
29
+ type TestRequestInit,
30
+ type TestResponse,
31
+ } from './testing.js';
32
+ import type { ListeningServer, Transport } from './transports/transport.js';
33
+
34
+ type NestedSettings =
35
+ | 'websocket'
36
+ | 'docs'
37
+ | 'cors'
38
+ | 'requestId'
39
+ | 'compression'
40
+ | 'securityHeaders'
41
+ | 'rateLimit';
42
+ const NESTED: readonly NestedSettings[] = [
43
+ 'websocket',
44
+ 'docs',
45
+ 'cors',
46
+ 'requestId',
47
+ 'compression',
48
+ 'securityHeaders',
49
+ 'rateLimit',
50
+ ];
51
+
52
+ export interface HttpOptions extends Omit<HttpSettings, NestedSettings> {
53
+ /** Route trees to serve. */
54
+ routes: readonly RouteTree[];
55
+ /** Path prefix for every route, such as `/api`. */
56
+ prefix?: string;
57
+ /** Middleware for every route, outermost first. */
58
+ middleware?: readonly Middleware[];
59
+ docs?: HttpSettings['docs'];
60
+ /** Cross-origin resource sharing; off unless origins are given. */
61
+ cors?: HttpSettings['cors'];
62
+ requestId?: HttpSettings['requestId'];
63
+ compression?: HttpSettings['compression'];
64
+ securityHeaders?: HttpSettings['securityHeaders'];
65
+ /** A rate limit for every route; off unless `limit` is given. */
66
+ rateLimit?: HttpSettings['rateLimit'];
67
+ websocket?: HttpSettings['websocket'];
68
+ }
69
+
70
+ /**
71
+ * Global middleware contributed by other modules, outermost first. Runs
72
+ * before the middleware passed to `provideHttp()`.
73
+ */
74
+ export const HTTP_MIDDLEWARE = new InjectionToken<Middleware[]>(
75
+ 'HTTP_MIDDLEWARE',
76
+ );
77
+
78
+ /** Adds global middleware from a module, such as metrics or auditing. */
79
+ export function provideHttpMiddleware(...middleware: Middleware[]): Provider[] {
80
+ return middleware.map((entry) =>
81
+ provide(HTTP_MIDDLEWARE, { useValue: entry, multi: true }),
82
+ );
83
+ }
84
+
85
+ export const HTTP_OPTIONS = new InjectionToken<HttpOptions>('HTTP_OPTIONS');
86
+
87
+ const DEFAULT_BODY_LIMIT = 1024 * 1024;
88
+
89
+ /**
90
+ * The HTTP server. Starts listening in a start hook; on shutdown it stops
91
+ * accepting connections, lets in-flight requests finish (asking clients to
92
+ * close their connections), then closes what is left.
93
+ */
94
+ export class HttpServer implements AsyncDisposable {
95
+ static readonly providedIn: ProvidedIn = null;
96
+
97
+ /** Code options with the `http` config section applied on top. */
98
+ readonly options: HttpOptions;
99
+ private readonly injector = inject(Injector);
100
+ private readonly log = inject(Logger).child('http');
101
+ private readonly plugins = inject(HTTP_MIDDLEWARE, { optional: true }) ?? [];
102
+ private readonly metrics = inject(METRICS, { optional: true });
103
+ private readonly tracer = inject(Tracer);
104
+ private readonly authStrategies =
105
+ inject(AUTH_STRATEGIES, { optional: true }) ?? [];
106
+ private engine: HttpEngine | undefined;
107
+ private server: ListeningServer | undefined;
108
+ private transportName: string | undefined;
109
+
110
+ constructor() {
111
+ const code = inject(HTTP_OPTIONS);
112
+ const config = inject(HttpConfig, { optional: true }) ?? {};
113
+ const merged: Record<string, unknown> = { ...code, ...config };
114
+ for (const key of NESTED) {
115
+ merged[key] = { ...code[key], ...config[key] };
116
+ }
117
+ this.options = merged as unknown as HttpOptions;
118
+ }
119
+
120
+ /** The bound port, once listening. */
121
+ get port(): number | undefined {
122
+ return this.server?.port;
123
+ }
124
+
125
+ /** The transport in use, once listening: `uws` or `node`. */
126
+ get transport(): string | undefined {
127
+ return this.transportName;
128
+ }
129
+
130
+ async listen(): Promise<void> {
131
+ if (this.engine !== undefined) {
132
+ return;
133
+ }
134
+
135
+ const { options } = this;
136
+ const routes = compileRoutes(options.routes, {
137
+ prefix: options.prefix,
138
+ middleware: this.globalMiddleware(),
139
+ });
140
+ const docs = options.docs ?? {};
141
+ const docsPath = docs.path ?? '/docs';
142
+ const docsEnabled = docs.enabled ?? true;
143
+ if (docsEnabled) {
144
+ routes.push(
145
+ ...docsRoutes(routes, {
146
+ path: docsPath,
147
+ securitySchemes: Object.fromEntries(
148
+ this.authStrategies
149
+ .filter((strategy) => strategy.scheme !== undefined)
150
+ .map((strategy) => [strategy.name, strategy.scheme]),
151
+ ),
152
+ title: docs.title ?? 'API',
153
+ version: docs.version ?? '1.0.0',
154
+ ...(docs.description === undefined
155
+ ? {}
156
+ : { description: docs.description }),
157
+ }),
158
+ );
159
+ }
160
+ this.engine = new HttpEngine(routes, {
161
+ injector: this.injector,
162
+ logger: this.log,
163
+ accessLog: options.accessLog ?? false,
164
+ cors: new CorsPolicy(options.cors ?? {}),
165
+ requestIdHeader:
166
+ options.requestId?.enabled === false
167
+ ? undefined
168
+ : (options.requestId?.header ?? 'x-request-id').toLowerCase(),
169
+ requestTimeout: options.requestTimeout ?? 0,
170
+ trustProxy: options.trustProxy ?? 0,
171
+ securityHeaders:
172
+ options.securityHeaders?.enabled === false
173
+ ? []
174
+ : securityHeaders(options.securityHeaders),
175
+ compressor:
176
+ options.compression?.enabled === true
177
+ ? new Compressor(options.compression)
178
+ : undefined,
179
+ observe: this.requestMetrics(),
180
+ etag: options.etag ?? false,
181
+ tracer: this.tracer.enabled ? this.tracer : undefined,
182
+ });
183
+
184
+ if (options.transport === 'none') {
185
+ this.transportName = 'none';
186
+ this.log.info('HTTP server ready without a transport', {
187
+ routes: routes.length,
188
+ });
189
+ return;
190
+ }
191
+
192
+ const transport = await this.selectTransport();
193
+ this.transportName = transport.name;
194
+ this.server = await transport.listen(
195
+ {
196
+ port: options.port ?? 8080,
197
+ host: options.host,
198
+ bodyLimit: options.bodyLimit ?? DEFAULT_BODY_LIMIT,
199
+ websocket: {
200
+ maxPayload: options.websocket?.maxPayload ?? 64 * 1024,
201
+ idleTimeout: options.websocket?.idleTimeout ?? 120_000,
202
+ },
203
+ },
204
+ this.engine.handle,
205
+ );
206
+
207
+ this.log.info('HTTP server listening', {
208
+ port: this.server.port,
209
+ transport: transport.name,
210
+ routes: routes.length,
211
+ docs: docsEnabled ? docsPath : false,
212
+ });
213
+ }
214
+
215
+ /** Request metrics, when `provideMetrics()` is used. */
216
+ private requestMetrics():
217
+ | ((method: string, route: string, status: number, seconds: number) => void)
218
+ | undefined {
219
+ const { metrics } = this;
220
+ if (metrics === null) {
221
+ return undefined;
222
+ }
223
+ const duration = metrics.histogram(
224
+ 'http_request_duration_seconds',
225
+ 'HTTP request duration in seconds, by method, route pattern and status.',
226
+ { labels: ['method', 'route', 'status'] },
227
+ );
228
+ metrics.gauge('http_requests_in_flight', 'HTTP requests being handled.', {
229
+ collect: (gauge) => gauge.set(this.engine?.pending ?? 0),
230
+ });
231
+ metrics.gauge('websocket_connections', 'Open WebSocket connections.', {
232
+ collect: (gauge) => gauge.set(this.engine?.webSocketCount ?? 0),
233
+ });
234
+ return (method, route, status, seconds) =>
235
+ duration.observe(seconds, { method, route, status });
236
+ }
237
+
238
+ /** The rate limit from config, then plugin middleware, then `provideHttp({ middleware })`. */
239
+ private globalMiddleware(): Middleware[] {
240
+ const { rateLimit: limits, middleware = [] } = this.options;
241
+ const global: Middleware[] = [];
242
+
243
+ if (limits?.limit !== undefined) {
244
+ const header = limits.keyHeader?.toLowerCase();
245
+ global.push(
246
+ rateLimit({
247
+ limit: limits.limit,
248
+ window: limits.window ?? 60_000,
249
+ name: 'global',
250
+ ...(header === undefined
251
+ ? {}
252
+ : { key: (context) => context.request.headers[header] }),
253
+ }),
254
+ );
255
+ }
256
+
257
+ global.push(...this.plugins, ...middleware);
258
+ return global;
259
+ }
260
+
261
+ /**
262
+ * Sends a request through the full pipeline in memory, without a socket.
263
+ * Use it in tests, with `http.transport: none` to skip listening.
264
+ *
265
+ * ```ts
266
+ * const response = await server.request({ method: 'POST', path: '/users', body: { name: 'Ada' } });
267
+ * expect(response.status).toBe(201);
268
+ * ```
269
+ */
270
+ request(init: TestRequestInit): Promise<TestResponse> {
271
+ if (this.engine === undefined) {
272
+ throw new Error('The HTTP server has not started.');
273
+ }
274
+ return dispatch(this.engine, init);
275
+ }
276
+
277
+ /** Sends a message to every WebSocket subscribed to `topic`, on any route. */
278
+ publish(topic: string, message: string | Uint8Array): void {
279
+ this.server?.publish(topic, message);
280
+ }
281
+
282
+ /** Graceful close: stop accepting, drain in-flight requests, close connections. */
283
+ async close(): Promise<void> {
284
+ const { server, engine } = this;
285
+ if (server === undefined || engine === undefined) {
286
+ return;
287
+ }
288
+
289
+ engine.closing = true;
290
+ server.stopAccepting();
291
+ engine.closeWebSockets(1001, 'The server is shutting down.');
292
+ if (engine.pending > 0) {
293
+ this.log.info('Waiting for in-flight requests', {
294
+ pending: engine.pending,
295
+ });
296
+ await engine.drain();
297
+ }
298
+ await this.forceClose();
299
+ }
300
+
301
+ async [Symbol.asyncDispose](): Promise<void> {
302
+ await this.forceClose();
303
+ }
304
+
305
+ private async forceClose(): Promise<void> {
306
+ const { server } = this;
307
+ if (server === undefined) {
308
+ return;
309
+ }
310
+ this.server = undefined;
311
+ await server.close();
312
+ }
313
+
314
+ private async selectTransport(): Promise<Transport> {
315
+ const choice = this.options.transport ?? 'auto';
316
+ if (choice === 'node') {
317
+ return nodeTransport;
318
+ }
319
+
320
+ try {
321
+ const { uwsTransport } = await import('./transports/uws.js');
322
+ return await uwsTransport();
323
+ } catch (error) {
324
+ if (choice === 'uws') {
325
+ throw new Error('The uws transport could not be loaded.', {
326
+ cause: error,
327
+ });
328
+ }
329
+ this.log.warn('uWebSockets.js is unavailable; using node:http', {
330
+ err: error,
331
+ });
332
+ return nodeTransport;
333
+ }
334
+ }
335
+ }
336
+
337
+ /**
338
+ * Serves routes over HTTP for the lifetime of the application.
339
+ *
340
+ * ```ts
341
+ * provideHttp({ prefix: '/api', routes: [userRoutes] })
342
+ * ```
343
+ */
344
+ export function provideHttp(options: HttpOptions): Provider[] {
345
+ return [
346
+ provide(HTTP_OPTIONS, { useValue: options }),
347
+ provideConfig(HttpConfig),
348
+ HttpServer,
349
+ onStart(() => inject(HttpServer).listen()),
350
+ onShutdown(() => inject(HttpServer).close()),
351
+ ];
352
+ }
@@ -0,0 +1,88 @@
1
+ import type { HttpEngine } from './engine.js';
2
+ import { HttpRequest, type ResponseSink } from './request.js';
3
+
4
+ export interface TestRequestInit {
5
+ method?: string;
6
+ /** Path, optionally with a query string: `/users?page=2`. */
7
+ path: string;
8
+ headers?: Record<string, string>;
9
+ /** A string or bytes are sent as-is; anything else as JSON (with content-type set). */
10
+ body?: unknown;
11
+ remoteAddress?: string;
12
+ }
13
+
14
+ export interface TestResponse {
15
+ status: number;
16
+ /** Lower-case header names. */
17
+ headers: Record<string, string>;
18
+ body: Buffer;
19
+ text(): string;
20
+ json<T = unknown>(): T;
21
+ }
22
+
23
+ class TestRequest extends HttpRequest {
24
+ readonly method: string;
25
+ readonly path: string;
26
+ readonly query: string;
27
+ readonly headers: Record<string, string | undefined>;
28
+ readonly remoteAddress: string;
29
+ private readonly bytes: Uint8Array;
30
+
31
+ constructor(init: TestRequestInit) {
32
+ super();
33
+ const queryStart = init.path.indexOf('?');
34
+ this.method = (init.method ?? 'GET').toUpperCase();
35
+ this.path = queryStart === -1 ? init.path : init.path.slice(0, queryStart);
36
+ this.query = queryStart === -1 ? '' : init.path.slice(queryStart + 1);
37
+ this.remoteAddress = init.remoteAddress ?? '127.0.0.1';
38
+ this.headers = {};
39
+ for (const [name, value] of Object.entries(init.headers ?? {})) {
40
+ this.headers[name.toLowerCase()] = value;
41
+ }
42
+
43
+ const { body } = init;
44
+ if (body === undefined) {
45
+ this.bytes = new Uint8Array(0);
46
+ } else if (typeof body === 'string') {
47
+ this.bytes = Buffer.from(body);
48
+ } else if (body instanceof Uint8Array) {
49
+ this.bytes = body;
50
+ } else {
51
+ this.bytes = Buffer.from(JSON.stringify(body));
52
+ this.headers['content-type'] ??= 'application/json';
53
+ }
54
+ }
55
+
56
+ body(): Promise<Uint8Array> {
57
+ return Promise.resolve(this.bytes);
58
+ }
59
+ }
60
+
61
+ /** Sends a request through the engine in memory: no sockets, same pipeline. */
62
+ export function dispatch(
63
+ engine: HttpEngine,
64
+ init: TestRequestInit,
65
+ ): Promise<TestResponse> {
66
+ return new Promise((resolve) => {
67
+ const sink: ResponseSink = {
68
+ aborted: false,
69
+ onAbort: () => undefined,
70
+ send(status, headers, body, head) {
71
+ const bytes =
72
+ head || body === undefined
73
+ ? Buffer.alloc(0)
74
+ : typeof body === 'string'
75
+ ? Buffer.from(body)
76
+ : Buffer.from(body.buffer, body.byteOffset, body.byteLength);
77
+ resolve({
78
+ status,
79
+ headers: { ...headers },
80
+ body: bytes,
81
+ text: () => bytes.toString('utf8'),
82
+ json: <T>() => JSON.parse(bytes.toString('utf8')) as T,
83
+ });
84
+ },
85
+ };
86
+ engine.handle(new TestRequest(init), sink);
87
+ });
88
+ }