@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,55 @@
1
+ import type { ProvidedIn } from '@tessellation/core';
2
+ import type { WebSocketSession } from './websocket.js';
3
+ /**
4
+ * An incoming request, independent of the transport serving it. Inject it in
5
+ * request-scoped providers; handlers and middleware receive it in their
6
+ * context.
7
+ */
8
+ export declare abstract class HttpRequest {
9
+ static readonly providedIn: ProvidedIn;
10
+ /** Upper-case method, such as `GET`. */
11
+ abstract readonly method: string;
12
+ /** Path without the query string, as sent (not decoded). */
13
+ abstract readonly path: string;
14
+ /** Query string without the leading `?`; empty if there is none. */
15
+ abstract readonly query: string;
16
+ /** Headers with lower-case names. */
17
+ abstract readonly headers: Readonly<Record<string, string | undefined>>;
18
+ /** The client's IP address. */
19
+ abstract readonly remoteAddress: string;
20
+ /**
21
+ * The request id (from the `x-request-id` header when valid, otherwise
22
+ * generated). Undefined when request ids are disabled.
23
+ */
24
+ id: string | undefined;
25
+ /** Proxies in front of the server whose `x-forwarded-for` entries are trusted. Set by the server. */
26
+ trustedProxies: number;
27
+ /**
28
+ * The client's address. With `http.trustProxy` set to the number of proxies
29
+ * in front of the server, it is read from `x-forwarded-for`; otherwise it
30
+ * is the connection's address.
31
+ */
32
+ get clientIp(): string;
33
+ /**
34
+ * The request body. Rejects with a 413 `HttpError` when it exceeds the
35
+ * configured body limit. Can be called more than once.
36
+ */
37
+ abstract body(): Promise<Uint8Array>;
38
+ /** A header by case-insensitive name. */
39
+ header(name: string): string | undefined;
40
+ }
41
+ /** Where a transport writes the response for one request. */
42
+ export interface ResponseSink {
43
+ /** True once the client has disconnected; sending is then a no-op. */
44
+ readonly aborted: boolean;
45
+ /** Calls `handler` if the client disconnects before the response is sent. */
46
+ onAbort(handler: () => void): void;
47
+ /** Completes a WebSocket handshake; present only for upgrade requests. */
48
+ upgrade?(session: WebSocketSession): void;
49
+ /**
50
+ * Sends the whole response. For HEAD requests (`head`), headers are sent
51
+ * with the body's length but without the body.
52
+ */
53
+ send(status: number, headers: Readonly<Record<string, string>>, body: string | Uint8Array | undefined, head: boolean): void;
54
+ }
55
+ //# sourceMappingURL=request.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../../src/lib/request.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAA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,MAAM,EAAE,MAAM,CAAC,CAAC,EACzC,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,EACrC,IAAI,EAAE,OAAO,GACZ,IAAI,CAAC;CACT"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * An incoming request, independent of the transport serving it. Inject it in
3
+ * request-scoped providers; handlers and middleware receive it in their
4
+ * context.
5
+ */
6
+ export class HttpRequest {
7
+ static providedIn = null;
8
+ /**
9
+ * The request id (from the `x-request-id` header when valid, otherwise
10
+ * generated). Undefined when request ids are disabled.
11
+ */
12
+ id;
13
+ /** Proxies in front of the server whose `x-forwarded-for` entries are trusted. Set by the server. */
14
+ trustedProxies = 0;
15
+ /**
16
+ * The client's address. With `http.trustProxy` set to the number of proxies
17
+ * in front of the server, it is read from `x-forwarded-for`; otherwise it
18
+ * is the connection's address.
19
+ */
20
+ get clientIp() {
21
+ if (this.trustedProxies === 0) {
22
+ return this.remoteAddress;
23
+ }
24
+ const chain = (this.headers['x-forwarded-for'] ?? '')
25
+ .split(',')
26
+ .map((entry) => entry.trim())
27
+ .filter((entry) => entry !== '');
28
+ chain.push(this.remoteAddress);
29
+ return (chain[Math.max(0, chain.length - 1 - this.trustedProxies)] ??
30
+ this.remoteAddress);
31
+ }
32
+ /** A header by case-insensitive name. */
33
+ header(name) {
34
+ return this.headers[name.toLowerCase()];
35
+ }
36
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * A segment trie router. Patterns are made of static segments, `:name`
3
+ * parameters (one segment) and a final `*` or `*name` wildcard (the rest of
4
+ * the path). Matching prefers static segments, then parameters, then
5
+ * wildcards, and backtracks so a more specific route never hides another.
6
+ */
7
+ export type RouteMatch<T> = {
8
+ kind: 'found';
9
+ value: T;
10
+ params: string[];
11
+ } | {
12
+ kind: 'method-not-allowed';
13
+ allowed: string[];
14
+ } | {
15
+ kind: 'not-found';
16
+ };
17
+ export interface PatternSegment {
18
+ kind: 'static' | 'param' | 'wildcard';
19
+ value: string;
20
+ }
21
+ /** Splits a pattern such as `/users/:id/*rest` into segments. */
22
+ export declare function parsePattern(pattern: string): PatternSegment[];
23
+ export declare class Router<T> {
24
+ private readonly root;
25
+ /** Registers a route. Returns its parameter names in match order. */
26
+ add(method: string, pattern: string, value: T): string[];
27
+ /**
28
+ * Finds the route for a method and path. HEAD falls back to GET. A trailing
29
+ * slash is ignored. Parameter values are returned undecoded.
30
+ */
31
+ find(method: string, path: string): RouteMatch<T>;
32
+ private walk;
33
+ private pick;
34
+ }
35
+ //# sourceMappingURL=router.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../src/lib/router.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAaH,MAAM,MAAM,UAAU,CAAC,CAAC,IACpB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,CAAC,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,GAC7C;IAAE,IAAI,EAAE,oBAAoB,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAA;CAAE,GACjD;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,CAAC;AAE1B,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,QAAQ,GAAG,OAAO,GAAG,UAAU,CAAC;IACtC,KAAK,EAAE,MAAM,CAAC;CACf;AAED,iEAAiE;AACjE,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,cAAc,EAAE,CA6B9D;AAED,qBAAa,MAAM,CAAC,CAAC;IACnB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAiB;IAEtC,qEAAqE;IACrE,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,EAAE;IAmDxD;;;OAGG;IACH,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,CAAC,CAAC,CAAC;IAqBjD,OAAO,CAAC,IAAI;IA0DZ,OAAO,CAAC,IAAI;CAkBb"}
@@ -0,0 +1,173 @@
1
+ /**
2
+ * A segment trie router. Patterns are made of static segments, `:name`
3
+ * parameters (one segment) and a final `*` or `*name` wildcard (the rest of
4
+ * the path). Matching prefers static segments, then parameters, then
5
+ * wildcards, and backtracks so a more specific route never hides another.
6
+ */
7
+ const PARAM_NAME = /^[A-Za-z_]\w*$/;
8
+ class Node {
9
+ statics;
10
+ param;
11
+ paramName;
12
+ wildcard;
13
+ wildcardName;
14
+ handlers;
15
+ }
16
+ /** Splits a pattern such as `/users/:id/*rest` into segments. */
17
+ export function parsePattern(pattern) {
18
+ if (!pattern.startsWith('/')) {
19
+ throw new Error(`Route path "${pattern}" must start with "/".`);
20
+ }
21
+ const parts = pattern === '/' ? [] : pattern.slice(1).split('/');
22
+ return parts.map((part, index) => {
23
+ if (part.startsWith(':')) {
24
+ const name = part.slice(1);
25
+ if (!PARAM_NAME.test(name)) {
26
+ throw new Error(`Invalid parameter name "${name}" in "${pattern}".`);
27
+ }
28
+ return { kind: 'param', value: name };
29
+ }
30
+ if (part.startsWith('*')) {
31
+ if (index !== parts.length - 1) {
32
+ throw new Error(`A wildcard must be the last segment of "${pattern}".`);
33
+ }
34
+ const name = part.slice(1) || '*';
35
+ if (name !== '*' && !PARAM_NAME.test(name)) {
36
+ throw new Error(`Invalid wildcard name "${name}" in "${pattern}".`);
37
+ }
38
+ return { kind: 'wildcard', value: name };
39
+ }
40
+ if (part === '') {
41
+ throw new Error(`Route path "${pattern}" has an empty segment.`);
42
+ }
43
+ return { kind: 'static', value: part };
44
+ });
45
+ }
46
+ export class Router {
47
+ root = new Node();
48
+ /** Registers a route. Returns its parameter names in match order. */
49
+ add(method, pattern, value) {
50
+ const names = [];
51
+ let node = this.root;
52
+ for (const segment of parsePattern(pattern)) {
53
+ if (segment.kind === 'static') {
54
+ node.statics ??= new Map();
55
+ let next = node.statics.get(segment.value);
56
+ if (next === undefined) {
57
+ next = new Node();
58
+ node.statics.set(segment.value, next);
59
+ }
60
+ node = next;
61
+ }
62
+ else if (segment.kind === 'param') {
63
+ if (node.param !== undefined && node.paramName !== segment.value) {
64
+ throw new Error(`Route "${pattern}" names a parameter ":${segment.value}" where another route uses ":${node.paramName}".`);
65
+ }
66
+ node.param ??= new Node();
67
+ node.paramName = segment.value;
68
+ names.push(segment.value);
69
+ node = node.param;
70
+ }
71
+ else {
72
+ if (node.wildcard !== undefined &&
73
+ node.wildcardName !== segment.value) {
74
+ throw new Error(`Route "${pattern}" names a wildcard "*${segment.value}" where another route uses "*${node.wildcardName}".`);
75
+ }
76
+ node.wildcard ??= new Map();
77
+ node.wildcardName = segment.value;
78
+ names.push(segment.value);
79
+ if (node.wildcard.has(method)) {
80
+ throw new Error(`Duplicate route ${method} ${pattern}.`);
81
+ }
82
+ node.wildcard.set(method, value);
83
+ return names;
84
+ }
85
+ }
86
+ node.handlers ??= new Map();
87
+ if (node.handlers.has(method)) {
88
+ throw new Error(`Duplicate route ${method} ${pattern}.`);
89
+ }
90
+ node.handlers.set(method, value);
91
+ return names;
92
+ }
93
+ /**
94
+ * Finds the route for a method and path. HEAD falls back to GET. A trailing
95
+ * slash is ignored. Parameter values are returned undecoded.
96
+ */
97
+ find(method, path) {
98
+ if (path.length > 1 && path.endsWith('/')) {
99
+ path = path.slice(0, -1);
100
+ }
101
+ const params = [];
102
+ const allowed = new Set();
103
+ const value = this.walk(this.root, path, 1, method, params, allowed);
104
+ if (value !== undefined) {
105
+ return { kind: 'found', value, params };
106
+ }
107
+ if (allowed.size > 0) {
108
+ if (allowed.has('GET')) {
109
+ allowed.add('HEAD');
110
+ }
111
+ return { kind: 'method-not-allowed', allowed: [...allowed].sort() };
112
+ }
113
+ return { kind: 'not-found' };
114
+ }
115
+ walk(node, path, start, method, params, allowed) {
116
+ if (start >= path.length) {
117
+ const found = this.pick(node.handlers, method, allowed);
118
+ if (found !== undefined) {
119
+ return found;
120
+ }
121
+ // "/docs/*" also matches "/docs" with an empty wildcard.
122
+ if (node.wildcard !== undefined) {
123
+ const wildcard = this.pick(node.wildcard, method, allowed);
124
+ if (wildcard !== undefined) {
125
+ params.push('');
126
+ return wildcard;
127
+ }
128
+ }
129
+ return undefined;
130
+ }
131
+ const slash = path.indexOf('/', start);
132
+ const end = slash === -1 ? path.length : slash;
133
+ const next = end + 1;
134
+ if (node.statics !== undefined) {
135
+ const child = node.statics.get(path.slice(start, end));
136
+ if (child !== undefined) {
137
+ const found = this.walk(child, path, next, method, params, allowed);
138
+ if (found !== undefined) {
139
+ return found;
140
+ }
141
+ }
142
+ }
143
+ if (node.param !== undefined && end > start) {
144
+ params.push(path.slice(start, end));
145
+ const found = this.walk(node.param, path, next, method, params, allowed);
146
+ if (found !== undefined) {
147
+ return found;
148
+ }
149
+ params.pop();
150
+ }
151
+ if (node.wildcard !== undefined) {
152
+ const found = this.pick(node.wildcard, method, allowed);
153
+ if (found !== undefined) {
154
+ params.push(path.slice(start));
155
+ return found;
156
+ }
157
+ }
158
+ return undefined;
159
+ }
160
+ pick(handlers, method, allowed) {
161
+ if (handlers === undefined) {
162
+ return undefined;
163
+ }
164
+ const found = handlers.get(method) ??
165
+ (method === 'HEAD' ? handlers.get('GET') : undefined);
166
+ if (found === undefined) {
167
+ for (const key of handlers.keys()) {
168
+ allowed.add(key);
169
+ }
170
+ }
171
+ return found;
172
+ }
173
+ }
@@ -0,0 +1,196 @@
1
+ import type { InferSchemaOutput, Provider, StandardSchemaV1 } from '@tessellation/core';
2
+ import type { Reply } from './reply.js';
3
+ import type { HttpRequest } from './request.js';
4
+ import { type WebSocketHandlers } from './websocket.js';
5
+ type Schema = StandardSchemaV1;
6
+ type Output<S> = S extends Schema ? InferSchemaOutput<S> : never;
7
+ type Simplify<T> = {
8
+ [K in keyof T]: T[K];
9
+ } & {};
10
+ type MaybePromise<T> = T | Promise<T>;
11
+ /** An object type with no keys. */
12
+ type Empty = Record<never, never>;
13
+ /** Parameter names in a path, typed as strings: `/:id/*rest` → `{ id; rest }`. */
14
+ export type PathParams<Path extends string> = Path extends `${string}:${infer Param}/${infer Rest}` ? {
15
+ [K in Param]: string;
16
+ } & PathParams<`/${Rest}`> : Path extends `${string}:${infer Param}` ? {
17
+ [K in Param]: string;
18
+ } : Path extends `${string}*${infer Name}` ? {
19
+ [K in Name extends '' ? '*' : Name]: string;
20
+ } : Empty;
21
+ /** Params introduced by a path segment, with a schema's output replacing strings. */
22
+ type OwnParams<Path extends string, ParamsSchema> = ParamsSchema extends Schema ? Omit<PathParams<Path>, keyof Output<ParamsSchema>> & Output<ParamsSchema> : PathParams<Path>;
23
+ /** One schema for 200, or schemas per status code. */
24
+ export type ResponseSchemas = Schema | {
25
+ readonly [status: number]: Schema;
26
+ };
27
+ type ResponseBody<R> = R extends Schema ? Output<R> : R extends {
28
+ readonly [status: number]: Schema;
29
+ } ? Output<R[keyof R]> : unknown;
30
+ /**
31
+ * What a handler may return: a body (sent as 200), a `Reply` for another
32
+ * status or headers, or `undefined` for 204.
33
+ */
34
+ export type HandlerResult<R> = ResponseBody<R> | Reply<ResponseBody<R>> | Reply<undefined> | undefined;
35
+ /** Query parameters without a schema: repeated keys become arrays. */
36
+ export type RawQuery = Record<string, string | string[]>;
37
+ export interface RequestContext<Params, Query, Body> {
38
+ readonly params: Params;
39
+ readonly query: Query;
40
+ readonly body: Body;
41
+ readonly request: HttpRequest;
42
+ /**
43
+ * Aborted when the client disconnects or the request times out. Pass it
44
+ * to database calls and `fetch` so abandoned work stops.
45
+ */
46
+ readonly signal: AbortSignal;
47
+ }
48
+ export interface MiddlewareContext {
49
+ readonly request: HttpRequest;
50
+ /** Aborted when the client disconnects or the request times out. */
51
+ readonly signal: AbortSignal;
52
+ /** The matched route's method and full path pattern. */
53
+ readonly route: {
54
+ readonly method: string;
55
+ readonly path: string;
56
+ };
57
+ }
58
+ /**
59
+ * Runs around the handler. Call `next()` to continue; it resolves to the
60
+ * reply (errors thrown later in the chain are already turned into error
61
+ * replies). Return a reply without calling `next()` to answer early, or throw
62
+ * an `HttpError`. Middleware runs in the request's injection context.
63
+ */
64
+ export type Middleware = (context: MiddlewareContext, next: () => Promise<Reply>) => MaybePromise<Reply>;
65
+ /** OpenAPI documentation for a route. */
66
+ export interface RouteDocs {
67
+ summary?: string;
68
+ description?: string;
69
+ /** Added to the tags of enclosing groups. */
70
+ tags?: readonly string[];
71
+ operationId?: string;
72
+ deprecated?: boolean;
73
+ /** Leave the route out of the OpenAPI document. */
74
+ hidden?: boolean;
75
+ }
76
+ export interface RouteOptions<Parent, Path extends string, ParamsSchema, QuerySchema, BodySchema, Response> extends RouteDocs {
77
+ /** Validates (and may convert) this route's own path parameters. */
78
+ params?: ParamsSchema;
79
+ query?: QuerySchema;
80
+ /** Validates a JSON body; requests with another content type get 415. */
81
+ body?: BodySchema;
82
+ /**
83
+ * Response schemas. They document the route and drive fast, compiled JSON
84
+ * serialization that only writes declared properties.
85
+ */
86
+ response?: Response;
87
+ middleware?: readonly Middleware[];
88
+ /** Providers created once per request, in a child of the app injector. */
89
+ providers?: readonly Provider[];
90
+ handler: (context: RequestContext<Simplify<Parent & OwnParams<Path, ParamsSchema>>, QuerySchema extends Schema ? Output<QuerySchema> : RawQuery, BodySchema extends Schema ? Output<BodySchema> : undefined>) => MaybePromise<HandlerResult<Response>>;
91
+ }
92
+ export interface GroupOptions<ParamsSchema> {
93
+ /** Validates the group's own path parameters, for every route inside. */
94
+ params?: ParamsSchema;
95
+ middleware?: readonly Middleware[];
96
+ /** Request-scoped providers for every route inside. */
97
+ providers?: readonly Provider[];
98
+ /** OpenAPI tags for every route inside. */
99
+ tags?: readonly string[];
100
+ /** Leave every route inside out of the OpenAPI document. */
101
+ hidden?: boolean;
102
+ }
103
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';
104
+ export interface WebSocketRouteOptions<Parent, Path extends string, ParamsSchema, QuerySchema, Data> extends WebSocketHandlers<Data> {
105
+ params?: ParamsSchema;
106
+ query?: QuerySchema;
107
+ /** Runs before the upgrade, like route middleware (authentication, rate limits). */
108
+ middleware?: readonly Middleware[];
109
+ providers?: readonly Provider[];
110
+ /**
111
+ * Accepts the connection and returns its `data`, or throws (such as
112
+ * `unauthorized()`) to refuse it with that response.
113
+ */
114
+ upgrade?: (context: RequestContext<Simplify<Parent & OwnParams<Path, ParamsSchema>>, QuerySchema extends Schema ? Output<QuerySchema> : RawQuery, undefined>) => Data | Promise<Data>;
115
+ }
116
+ export interface RouteDefinition {
117
+ readonly kind: 'route';
118
+ readonly method: HttpMethod;
119
+ readonly path: string;
120
+ readonly options: RouteOptions<any, string, any, any, any, any> & {
121
+ websocket?: WebSocketHandlers<any>;
122
+ };
123
+ }
124
+ export interface GroupDefinition {
125
+ readonly kind: 'group';
126
+ readonly path: string;
127
+ readonly options: GroupOptions<Schema | undefined>;
128
+ readonly children: readonly RouteNode[];
129
+ }
130
+ export type RouteNode = RouteDefinition | GroupDefinition;
131
+ /**
132
+ * A group of routes. `Expects` is the params it needs from where it is
133
+ * included; `include()` checks that the enclosing groups provide them.
134
+ */
135
+ export interface RouteTree<Expects extends object = Empty> extends GroupDefinition {
136
+ /** Type-only marker, contravariant in `Expects`. */
137
+ readonly __expects?: (params: Expects) => void;
138
+ }
139
+ type Build<Params> = (r: RouteBuilder<Params>) => readonly RouteNode[];
140
+ /**
141
+ * Defines routes. Its type parameter is the params already available from
142
+ * enclosing groups; the builder for a group's children carries the group's
143
+ * params too, so handlers see every param on their path, typed.
144
+ */
145
+ export declare class RouteBuilder<Params> {
146
+ get<const Path extends string, P extends Schema | undefined = undefined, Q extends Schema | undefined = undefined, R extends ResponseSchemas | undefined = undefined>(path: Path, options: RouteOptions<Params, Path, P, Q, undefined, R>): RouteDefinition;
147
+ post<const Path extends string, P extends Schema | undefined = undefined, Q extends Schema | undefined = undefined, B extends Schema | undefined = undefined, R extends ResponseSchemas | undefined = undefined>(path: Path, options: RouteOptions<Params, Path, P, Q, B, R>): RouteDefinition;
148
+ put<const Path extends string, P extends Schema | undefined = undefined, Q extends Schema | undefined = undefined, B extends Schema | undefined = undefined, R extends ResponseSchemas | undefined = undefined>(path: Path, options: RouteOptions<Params, Path, P, Q, B, R>): RouteDefinition;
149
+ patch<const Path extends string, P extends Schema | undefined = undefined, Q extends Schema | undefined = undefined, B extends Schema | undefined = undefined, R extends ResponseSchemas | undefined = undefined>(path: Path, options: RouteOptions<Params, Path, P, Q, B, R>): RouteDefinition;
150
+ delete<const Path extends string, P extends Schema | undefined = undefined, Q extends Schema | undefined = undefined, B extends Schema | undefined = undefined, R extends ResponseSchemas | undefined = undefined>(path: Path, options: RouteOptions<Params, Path, P, Q, B, R>): RouteDefinition;
151
+ options<const Path extends string, P extends Schema | undefined = undefined, Q extends Schema | undefined = undefined, R extends ResponseSchemas | undefined = undefined>(path: Path, options: RouteOptions<Params, Path, P, Q, undefined, R>): RouteDefinition;
152
+ /**
153
+ * A WebSocket endpoint. The upgrade request goes through middleware and
154
+ * validation like any route; handlers then run in its async context, so
155
+ * `requirePrincipal()` and request log fields keep working.
156
+ *
157
+ * ```ts
158
+ * r.websocket('/rooms/:room', {
159
+ * middleware: [authenticated()],
160
+ * upgrade: ({ params }) => ({ room: params.room, user: requirePrincipal().id }),
161
+ * open: (socket) => socket.subscribe(socket.data.room),
162
+ * message: (socket, text) => socket.publish(socket.data.room, text),
163
+ * })
164
+ * ```
165
+ */
166
+ websocket<const Path extends string, P extends Schema | undefined = undefined, Q extends Schema | undefined = undefined, D = undefined>(path: Path, options: WebSocketRouteOptions<Params, Path, P, Q, D>): RouteDefinition;
167
+ /** A nested group: its path, params, middleware and providers apply to its children. */
168
+ group<const Path extends string>(path: Path, build: Build<Simplify<Params & PathParams<Path>>>): GroupDefinition;
169
+ group<const Path extends string, P extends Schema | undefined = undefined>(path: Path, options: GroupOptions<P>, build: Build<Simplify<Params & OwnParams<Path, P>>>): GroupDefinition;
170
+ /** Includes routes defined elsewhere, such as in another file. */
171
+ include(tree: RouteTree<Params & object>): GroupDefinition;
172
+ }
173
+ interface RoutesFunction<Expects extends object> {
174
+ <const Path extends string>(path: Path, build: Build<Simplify<Expects & PathParams<Path>>>): RouteTree<Expects>;
175
+ <const Path extends string, P extends Schema | undefined = undefined>(path: Path, options: GroupOptions<P>, build: Build<Simplify<Expects & OwnParams<Path, P>>>): RouteTree<Expects>;
176
+ }
177
+ /**
178
+ * Defines a tree of routes under a path.
179
+ *
180
+ * ```ts
181
+ * export const userRoutes = routes('/users', (r) => [
182
+ * r.get('/', { handler: () => inject(UserService).list() }),
183
+ * r.group('/:userId', { params: z.object({ userId: z.uuid() }) }, (r) => [
184
+ * r.get('/', { handler: ({ params }) => inject(UserService).get(params.userId) }),
185
+ * ]),
186
+ * ]);
187
+ * ```
188
+ *
189
+ * Use `routes.withParams<{ userId: string }>()` for routes that are included
190
+ * under a group providing those params.
191
+ */
192
+ export declare const routes: RoutesFunction<Empty> & {
193
+ withParams<Expects extends object>(): RoutesFunction<Expects>;
194
+ };
195
+ export {};
196
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/lib/routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EACjB,QAAQ,EACR,gBAAgB,EACjB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAGL,KAAK,iBAAiB,EACvB,MAAM,gBAAgB,CAAC;AAExB,KAAK,MAAM,GAAG,gBAAgB,CAAC;AAC/B,KAAK,MAAM,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,GAAG,iBAAiB,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;AACjE,KAAK,QAAQ,CAAC,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAAE,GA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jD,SAAS,CAAC,OAAO,CAAC,CAAC;IACtB,CAAC,KAAK,CAAC,IAAI,SAAS,MAAM,EAAE,CAAC,SAAS,MAAM,GAAG,SAAS,GAAG,SAAS,EAClE,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,EACxB,KAAK,EAAE,KAAK,CAAC,QAAQ,CAAC,OAAO,GAAG,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,GACnD,SAAS,CAAC,OAAO,CAAC,CAAC;CACvB;AAUD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,MAAM,EAAE,cAAc,CAAC,KAAK,CAAC,GAAG;IAC3C,UAAU,CAAC,OAAO,SAAS,MAAM,KAAK,cAAc,CAAC,OAAO,CAAC,CAAC;CAG9D,CAAC"}
@@ -0,0 +1,98 @@
1
+ import { captureContext, UpgradeReply, } from './websocket.js';
2
+ /**
3
+ * Defines routes. Its type parameter is the params already available from
4
+ * enclosing groups; the builder for a group's children carries the group's
5
+ * params too, so handlers see every param on their path, typed.
6
+ */
7
+ export class RouteBuilder {
8
+ get(path, options) {
9
+ return route('GET', path, options);
10
+ }
11
+ post(path, options) {
12
+ return route('POST', path, options);
13
+ }
14
+ put(path, options) {
15
+ return route('PUT', path, options);
16
+ }
17
+ patch(path, options) {
18
+ return route('PATCH', path, options);
19
+ }
20
+ delete(path, options) {
21
+ return route('DELETE', path, options);
22
+ }
23
+ options(path, options) {
24
+ return route('OPTIONS', path, options);
25
+ }
26
+ /**
27
+ * A WebSocket endpoint. The upgrade request goes through middleware and
28
+ * validation like any route; handlers then run in its async context, so
29
+ * `requirePrincipal()` and request log fields keep working.
30
+ *
31
+ * ```ts
32
+ * r.websocket('/rooms/:room', {
33
+ * middleware: [authenticated()],
34
+ * upgrade: ({ params }) => ({ room: params.room, user: requirePrincipal().id }),
35
+ * open: (socket) => socket.subscribe(socket.data.room),
36
+ * message: (socket, text) => socket.publish(socket.data.room, text),
37
+ * })
38
+ * ```
39
+ */
40
+ websocket(path, options) {
41
+ const { upgrade, open, message, close, ...rest } = options;
42
+ return route('GET', path, {
43
+ ...rest,
44
+ hidden: true,
45
+ websocket: { open, message, close },
46
+ handler: async (context) => {
47
+ const data = upgrade === undefined ? undefined : await upgrade(context);
48
+ // Captured here, inside middleware, so handlers see what it set up.
49
+ return new UpgradeReply(data, captureContext());
50
+ },
51
+ });
52
+ }
53
+ group(path, optionsOrBuild, build) {
54
+ return group(path, optionsOrBuild, build);
55
+ }
56
+ /** Includes routes defined elsewhere, such as in another file. */
57
+ include(tree) {
58
+ return tree;
59
+ }
60
+ }
61
+ const builder = new RouteBuilder();
62
+ /** Builds a definition; typed options are erased here, once. */
63
+ function route(method, path, options) {
64
+ const erased = options;
65
+ if (typeof erased.handler !== 'function') {
66
+ throw new Error(`Route ${method} ${path} needs a handler function.`);
67
+ }
68
+ return { kind: 'route', method, path, options: erased };
69
+ }
70
+ function group(path, optionsOrBuild, build) {
71
+ const options = typeof optionsOrBuild === 'function' ? {} : optionsOrBuild;
72
+ const buildChildren = typeof optionsOrBuild === 'function' ? optionsOrBuild : build;
73
+ if (buildChildren === undefined) {
74
+ throw new Error(`Group "${path}" needs a function that returns its routes.`);
75
+ }
76
+ return { kind: 'group', path, options, children: buildChildren(builder) };
77
+ }
78
+ function createRoutes() {
79
+ return ((path, optionsOrBuild, build) => group(path, optionsOrBuild, build));
80
+ }
81
+ /**
82
+ * Defines a tree of routes under a path.
83
+ *
84
+ * ```ts
85
+ * export const userRoutes = routes('/users', (r) => [
86
+ * r.get('/', { handler: () => inject(UserService).list() }),
87
+ * r.group('/:userId', { params: z.object({ userId: z.uuid() }) }, (r) => [
88
+ * r.get('/', { handler: ({ params }) => inject(UserService).get(params.userId) }),
89
+ * ]),
90
+ * ]);
91
+ * ```
92
+ *
93
+ * Use `routes.withParams<{ userId: string }>()` for routes that are included
94
+ * under a group providing those params.
95
+ */
96
+ export const routes = Object.assign(createRoutes(), {
97
+ withParams: () => createRoutes(),
98
+ });
@@ -0,0 +1,19 @@
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
+ * Headers added to every response that does not already set them. The
16
+ * defaults suit a JSON API: no MIME sniffing, no framing, no referrers.
17
+ */
18
+ export declare function securityHeaders(options?: SecurityHeaderOptions): [string, string][];
19
+ //# sourceMappingURL=security-headers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"security-headers.d.ts","sourceRoot":"","sources":["../../src/lib/security-headers.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,2CAA2C;IAC3C,YAAY,CAAC,EAAE,MAAM,GAAG,YAAY,CAAC;IACrC,kDAAkD;IAClD,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,iDAAiD;IACjD,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAC7B,OAAO,GAAE,qBAA0B,GAClC,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAiBpB"}