@encore.dev/sdk 2.0.0-beta.14 → 2.0.0-beta.16

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 (269) hide show
  1. package/README.md +144 -90
  2. package/app_meta.ts +56 -54
  3. package/config/config.test.ts +47 -13
  4. package/config/config.ts +60 -57
  5. package/config/secrets.ts +47 -50
  6. package/config/value.ts +23 -26
  7. package/cron/mod.test.ts +12 -0
  8. package/cron/mod.ts +37 -22
  9. package/dist/app_meta.d.ts +52 -50
  10. package/dist/app_meta.d.ts.map +1 -1
  11. package/dist/app_meta.js +2 -2
  12. package/dist/app_meta.js.map +1 -1
  13. package/dist/config/config.d.ts +58 -55
  14. package/dist/config/config.d.ts.map +1 -1
  15. package/dist/config/config.js +8 -9
  16. package/dist/config/config.js.map +1 -1
  17. package/dist/config/secrets.d.ts +45 -50
  18. package/dist/config/secrets.d.ts.map +1 -1
  19. package/dist/config/secrets.js +11 -9
  20. package/dist/config/secrets.js.map +1 -1
  21. package/dist/config/value.d.ts +20 -23
  22. package/dist/config/value.d.ts.map +1 -1
  23. package/dist/config/value.js +20 -23
  24. package/dist/config/value.js.map +1 -1
  25. package/dist/cron/mod.d.ts +34 -20
  26. package/dist/cron/mod.d.ts.map +1 -1
  27. package/dist/cron/mod.js +13 -13
  28. package/dist/cron/mod.js.map +1 -1
  29. package/dist/frontends/mod.d.ts +20 -19
  30. package/dist/frontends/mod.d.ts.map +1 -1
  31. package/dist/frontends/mod.js +20 -19
  32. package/dist/frontends/mod.js.map +1 -1
  33. package/dist/gateway/errors.d.ts +28 -30
  34. package/dist/gateway/errors.d.ts.map +1 -1
  35. package/dist/gateway/errors.js +29 -31
  36. package/dist/gateway/errors.js.map +1 -1
  37. package/dist/gateway/match.d.ts +54 -54
  38. package/dist/gateway/match.d.ts.map +1 -1
  39. package/dist/gateway/match.js +56 -56
  40. package/dist/gateway/match.js.map +1 -1
  41. package/dist/gateway/middleware.d.ts +62 -64
  42. package/dist/gateway/middleware.d.ts.map +1 -1
  43. package/dist/gateway/middleware.js +1 -1
  44. package/dist/gateway/middleware.js.map +1 -1
  45. package/dist/gateway/mod.d.ts +64 -67
  46. package/dist/gateway/mod.d.ts.map +1 -1
  47. package/dist/gateway/mod.js +72 -76
  48. package/dist/gateway/mod.js.map +1 -1
  49. package/dist/gateway/request.d.ts +138 -134
  50. package/dist/gateway/request.d.ts.map +1 -1
  51. package/dist/gateway/request.js +117 -108
  52. package/dist/gateway/request.js.map +1 -1
  53. package/dist/gateway/serve.d.ts +29 -34
  54. package/dist/gateway/serve.d.ts.map +1 -1
  55. package/dist/gateway/serve.js +51 -56
  56. package/dist/gateway/serve.js.map +1 -1
  57. package/dist/gateways/mod.d.ts +23 -21
  58. package/dist/gateways/mod.d.ts.map +1 -1
  59. package/dist/gateways/mod.js +25 -23
  60. package/dist/gateways/mod.js.map +1 -1
  61. package/dist/internal/otel/http.d.ts +4 -2
  62. package/dist/internal/otel/http.d.ts.map +1 -1
  63. package/dist/internal/otel/http.js +32 -5
  64. package/dist/internal/otel/http.js.map +1 -1
  65. package/dist/internal/runtime/napi/napi.cjs +6 -5
  66. package/dist/internal/runtime/napi/napi.d.cts +58 -16
  67. package/dist/internal/runtime/shutdown.d.ts +75 -57
  68. package/dist/internal/runtime/shutdown.d.ts.map +1 -1
  69. package/dist/internal/runtime/shutdown.js +88 -84
  70. package/dist/internal/runtime/shutdown.js.map +1 -1
  71. package/dist/log/logger.d.ts +43 -37
  72. package/dist/log/logger.d.ts.map +1 -1
  73. package/dist/log/logger.js +26 -25
  74. package/dist/log/logger.js.map +1 -1
  75. package/dist/metrics/mod.d.ts +133 -114
  76. package/dist/metrics/mod.d.ts.map +1 -1
  77. package/dist/metrics/mod.js +109 -101
  78. package/dist/metrics/mod.js.map +1 -1
  79. package/dist/otel.d.ts +6 -3
  80. package/dist/otel.d.ts.map +1 -1
  81. package/dist/otel.js +6 -3
  82. package/dist/otel.js.map +1 -1
  83. package/dist/pubsub/subscription.d.ts +88 -116
  84. package/dist/pubsub/subscription.d.ts.map +1 -1
  85. package/dist/pubsub/subscription.js +14 -17
  86. package/dist/pubsub/subscription.js.map +1 -1
  87. package/dist/pubsub/topic.d.ts +86 -113
  88. package/dist/pubsub/topic.d.ts.map +1 -1
  89. package/dist/pubsub/topic.js +68 -82
  90. package/dist/pubsub/topic.js.map +1 -1
  91. package/dist/redaction/mod.d.ts +62 -0
  92. package/dist/redaction/mod.d.ts.map +1 -0
  93. package/dist/redaction/mod.js +102 -0
  94. package/dist/redaction/mod.js.map +1 -0
  95. package/dist/reqctx/mod.d.ts +83 -86
  96. package/dist/reqctx/mod.d.ts.map +1 -1
  97. package/dist/reqctx/mod.js +39 -41
  98. package/dist/reqctx/mod.js.map +1 -1
  99. package/dist/services/index.d.ts +76 -75
  100. package/dist/services/index.d.ts.map +1 -1
  101. package/dist/services/index.js +73 -71
  102. package/dist/services/index.js.map +1 -1
  103. package/dist/shutdown/mod.d.ts +26 -25
  104. package/dist/shutdown/mod.d.ts.map +1 -1
  105. package/dist/shutdown/mod.js +26 -25
  106. package/dist/shutdown/mod.js.map +1 -1
  107. package/dist/storage/clickhouse/database.d.ts +113 -115
  108. package/dist/storage/clickhouse/database.d.ts.map +1 -1
  109. package/dist/storage/clickhouse/database.js +65 -79
  110. package/dist/storage/clickhouse/database.js.map +1 -1
  111. package/dist/storage/clickhouse/errors.d.ts +25 -26
  112. package/dist/storage/clickhouse/errors.d.ts.map +1 -1
  113. package/dist/storage/clickhouse/errors.js +15 -17
  114. package/dist/storage/clickhouse/errors.js.map +1 -1
  115. package/dist/storage/clickhouse/mod.d.ts +10 -10
  116. package/dist/storage/clickhouse/mod.js +10 -10
  117. package/dist/storage/objects/bucket.d.ts +230 -203
  118. package/dist/storage/objects/bucket.d.ts.map +1 -1
  119. package/dist/storage/objects/bucket.js +146 -106
  120. package/dist/storage/objects/bucket.js.map +1 -1
  121. package/dist/storage/objects/error.d.ts +4 -4
  122. package/dist/storage/objects/error.js +4 -4
  123. package/dist/storage/objects/mod.d.ts +1 -1
  124. package/dist/storage/objects/mod.d.ts.map +1 -1
  125. package/dist/storage/objects/mod.js.map +1 -1
  126. package/dist/storage/objects/refs.d.ts +2 -5
  127. package/dist/storage/objects/refs.d.ts.map +1 -1
  128. package/dist/storage/objects/refs.js.map +1 -1
  129. package/dist/storage/postgres/database.d.ts +124 -149
  130. package/dist/storage/postgres/database.d.ts.map +1 -1
  131. package/dist/storage/postgres/database.js +98 -135
  132. package/dist/storage/postgres/database.js.map +1 -1
  133. package/dist/storage/postgres/errors.d.ts +42 -48
  134. package/dist/storage/postgres/errors.d.ts.map +1 -1
  135. package/dist/storage/postgres/errors.js +44 -51
  136. package/dist/storage/postgres/errors.js.map +1 -1
  137. package/dist/storage/postgres/interval.d.ts +19 -19
  138. package/dist/storage/postgres/interval.d.ts.map +1 -1
  139. package/dist/storage/postgres/interval.js +21 -21
  140. package/dist/storage/postgres/interval.js.map +1 -1
  141. package/dist/storage/redis/bitfield.d.ts +48 -23
  142. package/dist/storage/redis/bitfield.d.ts.map +1 -1
  143. package/dist/storage/redis/bitfield.js +38 -19
  144. package/dist/storage/redis/bitfield.js.map +1 -1
  145. package/dist/storage/redis/command.d.ts +16 -12
  146. package/dist/storage/redis/command.d.ts.map +1 -1
  147. package/dist/storage/redis/command.js +16 -12
  148. package/dist/storage/redis/command.js.map +1 -1
  149. package/dist/storage/redis/commands.d.ts +99 -100
  150. package/dist/storage/redis/commands.d.ts.map +1 -1
  151. package/dist/storage/redis/commands.js +84 -85
  152. package/dist/storage/redis/commands.js.map +1 -1
  153. package/dist/storage/redis/database.d.ts +138 -122
  154. package/dist/storage/redis/database.d.ts.map +1 -1
  155. package/dist/storage/redis/database.js +120 -101
  156. package/dist/storage/redis/database.js.map +1 -1
  157. package/dist/storage/redis/mod.d.ts +52 -48
  158. package/dist/storage/redis/mod.d.ts.map +1 -1
  159. package/dist/storage/redis/mod.js +52 -48
  160. package/dist/storage/redis/mod.js.map +1 -1
  161. package/dist/storage/redis/options.d.ts +26 -24
  162. package/dist/storage/redis/options.d.ts.map +1 -1
  163. package/dist/storage/redis/options.js.map +1 -1
  164. package/dist/storage/redis/pubsub.d.ts +16 -16
  165. package/dist/storage/redis/pubsub.d.ts.map +1 -1
  166. package/dist/storage/redis/pubsub.js +14 -14
  167. package/dist/storage/redis/pubsub.js.map +1 -1
  168. package/dist/storage/redis/reply.d.ts +80 -72
  169. package/dist/storage/redis/reply.d.ts.map +1 -1
  170. package/dist/storage/redis/reply.js +53 -46
  171. package/dist/storage/redis/reply.js.map +1 -1
  172. package/dist/storage/redis/scan.d.ts +4 -4
  173. package/dist/storage/redis/scan.d.ts.map +1 -1
  174. package/dist/storage/redis/scan.js +6 -6
  175. package/dist/storage/redis/scan.js.map +1 -1
  176. package/dist/storage/redis/script.d.ts +28 -21
  177. package/dist/storage/redis/script.d.ts.map +1 -1
  178. package/dist/storage/redis/script.js +29 -22
  179. package/dist/storage/redis/script.js.map +1 -1
  180. package/dist/storage/redis/target.d.ts +17 -1
  181. package/dist/storage/redis/target.d.ts.map +1 -1
  182. package/dist/storage/redis/target.js +30 -1
  183. package/dist/storage/redis/target.js.map +1 -1
  184. package/dist/storage/redis/wire.d.ts +6 -6
  185. package/dist/storage/redis/wire.d.ts.map +1 -1
  186. package/dist/storage/redis/wire.js +6 -6
  187. package/dist/storage/redis/wire.js.map +1 -1
  188. package/dist/testing/mod.d.ts +83 -88
  189. package/dist/testing/mod.d.ts.map +1 -1
  190. package/dist/testing/mod.js +75 -81
  191. package/dist/testing/mod.js.map +1 -1
  192. package/dist/testing/playwright.d.ts +28 -32
  193. package/dist/testing/playwright.d.ts.map +1 -1
  194. package/dist/testing/playwright.js +22 -27
  195. package/dist/testing/playwright.js.map +1 -1
  196. package/dist/testing/puppeteer.d.ts +11 -12
  197. package/dist/testing/puppeteer.d.ts.map +1 -1
  198. package/dist/testing/puppeteer.js +17 -18
  199. package/dist/testing/puppeteer.js.map +1 -1
  200. package/dist/testing/system.d.ts +72 -90
  201. package/dist/testing/system.d.ts.map +1 -1
  202. package/dist/testing/system.js +90 -107
  203. package/dist/testing/system.js.map +1 -1
  204. package/dist/tracing/http.d.ts +2 -1
  205. package/dist/tracing/http.d.ts.map +1 -1
  206. package/dist/tracing/http.js +2 -1
  207. package/dist/tracing/http.js.map +1 -1
  208. package/dist/tracing/node.d.ts.map +1 -1
  209. package/dist/tracing/node.js +1 -1
  210. package/dist/tracing/node.js.map +1 -1
  211. package/dist/tsconfig.build.tsbuildinfo +1 -1
  212. package/frontends/mod.test.ts +6 -2
  213. package/frontends/mod.ts +20 -19
  214. package/gateway/errors.ts +30 -32
  215. package/gateway/match.ts +61 -57
  216. package/gateway/middleware.ts +62 -64
  217. package/gateway/mod.ts +73 -76
  218. package/gateway/request.ts +143 -140
  219. package/gateway/serve.ts +58 -63
  220. package/gateways/mod.ts +25 -23
  221. package/internal/otel/http.test.ts +50 -0
  222. package/internal/otel/http.ts +40 -5
  223. package/internal/runtime/napi/napi.cjs +6 -5
  224. package/internal/runtime/napi/napi.d.cts +58 -16
  225. package/internal/runtime/shutdown.ts +113 -101
  226. package/log/logger.test.ts +8 -0
  227. package/log/logger.ts +48 -45
  228. package/metrics/mod.ts +138 -122
  229. package/otel.ts +6 -3
  230. package/package.json +6 -1
  231. package/pubsub/subscription.ts +93 -123
  232. package/pubsub/topic.ts +96 -130
  233. package/redaction/bridge.test.ts +99 -0
  234. package/redaction/mod.test.ts +188 -0
  235. package/redaction/mod.ts +226 -0
  236. package/reqctx/mod.ts +83 -86
  237. package/services/index.ts +78 -78
  238. package/shutdown/mod.ts +26 -25
  239. package/storage/clickhouse/database.ts +115 -129
  240. package/storage/clickhouse/errors.ts +27 -29
  241. package/storage/clickhouse/mod.ts +10 -10
  242. package/storage/objects/bucket.test.ts +168 -16
  243. package/storage/objects/bucket.ts +336 -247
  244. package/storage/objects/error.ts +4 -4
  245. package/storage/objects/mod.ts +1 -0
  246. package/storage/objects/refs.ts +2 -5
  247. package/storage/postgres/database.ts +131 -164
  248. package/storage/postgres/errors.ts +45 -52
  249. package/storage/postgres/interval.ts +21 -21
  250. package/storage/redis/bitfield.ts +51 -26
  251. package/storage/redis/command.ts +16 -12
  252. package/storage/redis/commands.ts +99 -100
  253. package/storage/redis/database.ts +145 -123
  254. package/storage/redis/mod.ts +52 -48
  255. package/storage/redis/options.ts +26 -24
  256. package/storage/redis/pubsub.ts +14 -14
  257. package/storage/redis/redis.test.ts +17 -2
  258. package/storage/redis/reply.ts +85 -77
  259. package/storage/redis/scan.ts +6 -6
  260. package/storage/redis/script.ts +29 -22
  261. package/storage/redis/target.ts +34 -1
  262. package/storage/redis/wire.ts +8 -8
  263. package/testing/mod.ts +99 -105
  264. package/testing/playwright.ts +32 -37
  265. package/testing/puppeteer.ts +22 -23
  266. package/testing/system.ts +117 -133
  267. package/tracing/http.ts +2 -1
  268. package/tracing/native.test.ts +158 -8
  269. package/tracing/node.ts +1 -0
package/gateway/errors.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  /**
2
- * The code of an Encore error, which a {@link reject}ion answers with: what
3
- * went wrong, as Encore's clients read it, and the HTTP status the answer
4
- * has. They are the codes a service's errors answer with.
2
+ * Standard Encore error codes used with {@link reject}, matching the error
3
+ * codes returned by Encore services and their corresponding HTTP status codes.
5
4
  */
6
5
  export enum ErrCode {
7
6
  /** 499. */
@@ -57,41 +56,40 @@ const STATUS: Record<ErrCode, number> = {
57
56
  [ErrCode.Unauthenticated]: 401,
58
57
  };
59
58
 
60
- /** The HTTP status an answer with `code` has: 401 for
61
- * {@link ErrCode.Unauthenticated}, 404 for {@link ErrCode.NotFound}, and so
62
- * on. */
59
+ /**
60
+ * Returns the HTTP status code corresponding to `code` (e.g. 401 for
61
+ * {@link ErrCode.Unauthenticated}, 404 for {@link ErrCode.NotFound}).
62
+ */
63
63
  export function httpStatus(code: ErrCode): number {
64
64
  return STATUS[code];
65
65
  }
66
66
 
67
- /** Response headers: a record, or pairs for a header sent more than once. */
67
+ /** Response headers, either as a record or as name-value pairs for repeated headers. */
68
68
  export type Headers = Record<string, string> | ReadonlyArray<[string, string]>;
69
69
 
70
70
  /**
71
- * A Middleware's answer to a request it does not let through: `onRequest`
72
- * returns or throws one, and the gateway writes it to the client, with the
73
- * gateway's CORS headers, rather than forwarding the request.
71
+ * A middleware response that short-circuits a request in `onRequest`. Return
72
+ * or throw a `Rejection` to have the gateway respond directly to the client
73
+ * (including the gateway's CORS headers) without forwarding the request.
74
74
  *
75
- * {@link reject} answers as a service answers with an Encore error, which
76
- * Encore's clients read as one; {@link respond} answers with any response,
77
- * such as a redirect.
75
+ * Create one with {@link reject} for a standard Encore error response, or
76
+ * {@link respond} for a custom HTTP response such as a redirect.
78
77
  */
79
78
  export class Rejection extends Error {
80
79
  override name = 'Rejection';
81
80
 
82
- /** The HTTP status the request is answered with. */
81
+ /** The HTTP status code sent to the client. */
83
82
  readonly status: number;
84
- /** The Encore error code, for a {@link reject}; undefined for a
85
- * {@link respond}. */
83
+ /** The Encore error code (set for {@link reject}, undefined for {@link respond}). */
86
84
  readonly code: ErrCode | undefined;
87
- /** What went wrong, for a {@link reject}; empty for a {@link respond}. */
85
+ /** The error message (set for {@link reject}, empty for {@link respond}). */
88
86
  readonly errorMessage: string;
89
- /** The response's headers, as name and value pairs. */
87
+ /** The response headers as `[name, value]` pairs. */
90
88
  readonly headers: Array<[string, string]>;
91
- /** The response's body, for a {@link respond}. */
89
+ /** The raw response body (set for {@link respond}). */
92
90
  readonly body: Uint8Array | undefined;
93
91
 
94
- /** @internal Made by {@link reject} and {@link respond}. */
92
+ /** @internal Created by {@link reject} and {@link respond}. */
95
93
  constructor(
96
94
  status: number,
97
95
  code: ErrCode | undefined,
@@ -110,8 +108,7 @@ export class Rejection extends Error {
110
108
  this.body = body;
111
109
  }
112
110
 
113
- /** Adds a header to the response, as `Retry-After` to a 429, and returns
114
- * the rejection. */
111
+ /** Appends a header (such as `Retry-After` on a 429) and returns `this`. */
115
112
  withHeader(name: string, value: string): this {
116
113
  this.headers.push([name, value]);
117
114
  return this;
@@ -119,10 +116,10 @@ export class Rejection extends Error {
119
116
  }
120
117
 
121
118
  /**
122
- * Answers a request with an Encore error with `code` and `message`, and the
123
- * HTTP status of the code: 401 for {@link ErrCode.Unauthenticated}, 403 for
124
- * {@link ErrCode.PermissionDenied}, 429 for
125
- * {@link ErrCode.ResourceExhausted}, and so on.
119
+ * Creates a {@link Rejection} that responds with a standard Encore error
120
+ * containing `code` and `message`, using the HTTP status mapped from `code`
121
+ * (e.g. 401 for {@link ErrCode.Unauthenticated}, 403 for
122
+ * {@link ErrCode.PermissionDenied}, 429 for {@link ErrCode.ResourceExhausted}).
126
123
  *
127
124
  * ```typescript
128
125
  * return gateway.reject(ErrCode.Unauthenticated, "missing token");
@@ -130,7 +127,7 @@ export class Rejection extends Error {
130
127
  */
131
128
  export function reject(code: ErrCode, message: string): Rejection {
132
129
  if (!(code in REVERSE)) {
133
- throw new TypeError(`${String(code)} is not an ErrCode`);
130
+ throw new TypeError(`${String(code)} is not a valid ErrCode`);
134
131
  }
135
132
  return new Rejection(STATUS[code], code, message, [], undefined);
136
133
  }
@@ -140,8 +137,8 @@ const REVERSE: Record<string, true> = Object.fromEntries(
140
137
  );
141
138
 
142
139
  /**
143
- * Answers a request with `status`, `headers` and `body` as they are, as a
144
- * redirect to sign in:
140
+ * Creates a {@link Rejection} that responds directly with `status`, `headers`,
141
+ * and `body`, for example to issue a redirect:
145
142
  *
146
143
  * ```typescript
147
144
  * return gateway.respond(302, { location: "/login" });
@@ -153,7 +150,7 @@ export function respond(
153
150
  body: Uint8Array | string = new Uint8Array(),
154
151
  ): Rejection {
155
152
  if (!Number.isInteger(status) || status < 100 || status > 599) {
156
- throw new RangeError(`status ${status} is not an HTTP status`);
153
+ throw new RangeError(`status ${status} is not a valid HTTP status code`);
157
154
  }
158
155
  const pairs: Array<[string, string]> = Array.isArray(headers)
159
156
  ? headers.map(([n, v]) => [n, v])
@@ -164,8 +161,9 @@ export function respond(
164
161
  }
165
162
 
166
163
  /**
167
- * The gateway cannot be served: a Middleware is invalid, the process is not
168
- * a gateway program Encore runs, or the gateway is already served.
164
+ * Thrown when the gateway cannot be started — for example, when a middleware
165
+ * definition is invalid, the process is not running as an Encore gateway, or
166
+ * `serve` has already been called.
169
167
  */
170
168
  export class GatewayError extends Error {
171
169
  override name = 'GatewayError';
package/gateway/match.ts CHANGED
@@ -1,14 +1,14 @@
1
1
  /**
2
- * Which requests a Middleware is called for.
2
+ * Matchers that select which requests trigger a middleware.
3
3
  *
4
- * A {@link Matcher} is checked by Encore before a request reaches
5
- * JavaScript: a request no Middleware matches costs the program nothing.
6
- * Matching sees the request as the client sent it, so the header edits of an
7
- * earlier Middleware do not change which later ones are called, and a
8
- * Middleware need not read what it matches on.
4
+ * Encore evaluates every {@link Matcher} natively before a request reaches
5
+ * JavaScript, so unmatched requests incur no JS overhead. Matchers inspect the
6
+ * original client request — header edits by earlier middleware do not affect
7
+ * which later middleware run — and a middleware does not need to read a field
8
+ * in order to match on it.
9
9
  *
10
- * Matchers combine with `.and()`, `.or()` and `.not()`, or {@link allOf},
11
- * {@link anyOf} and {@link not}:
10
+ * Combine matchers with `.and()`, `.or()`, and `.not()`, or with {@link allOf},
11
+ * {@link anyOf}, and {@link not}:
12
12
  *
13
13
  * ```typescript
14
14
  * import { match } from "@encore.dev/sdk/gateway";
@@ -21,12 +21,13 @@
21
21
  * @module
22
22
  */
23
23
 
24
- /** A matcher or condition as the gateway core's JSON spells it. */
24
+ /** Serialized matcher or condition JSON consumed by the gateway core. */
25
25
  type Expr = Record<string, unknown>;
26
26
 
27
27
  /**
28
- * A condition on a request: on its service, route, method, path, headers,
29
- * query parameters or cookies. Made by this module's functions.
28
+ * A predicate over incoming requests (by service, route, method, path,
29
+ * headers, query parameters, or cookies). Construct matchers using the
30
+ * functions in this module.
30
31
  */
31
32
  export class Matcher {
32
33
  /** @internal */
@@ -37,32 +38,32 @@ export class Matcher {
37
38
  this.expr = expr;
38
39
  }
39
40
 
40
- /** Matches the requests both match. */
41
+ /** Matches requests that satisfy both this matcher and `other`. */
41
42
  and(other: Matcher): Matcher {
42
43
  return allOf(this, other);
43
44
  }
44
45
 
45
- /** Matches the requests either matches. */
46
+ /** Matches requests that satisfy either this matcher or `other`. */
46
47
  or(other: Matcher): Matcher {
47
48
  return anyOf(this, other);
48
49
  }
49
50
 
50
- /** Matches the requests this does not. */
51
+ /** Matches requests that do not satisfy this matcher. */
51
52
  not(): Matcher {
52
53
  return not(this);
53
54
  }
54
55
 
55
- /** The matcher as the gateway core's JSON spells it. */
56
+ /** Serializes the matcher to the gateway core's JSON format. */
56
57
  toJSON(): Expr {
57
58
  return this.expr;
58
59
  }
59
60
  }
60
61
 
61
62
  /**
62
- * What a header, query parameter or cookie must be, for {@link header},
63
- * {@link query} and {@link cookie}. One sent more than once satisfies a
64
- * condition, other than {@link absent}, when any of its values does. Made by
65
- * this module's functions.
63
+ * A value condition for {@link header}, {@link query}, or {@link cookie}.
64
+ * When a field appears multiple times, any condition other than {@link absent}
65
+ * matches if at least one value satisfies it. Construct conditions using the
66
+ * functions in this module.
66
67
  */
67
68
  export class Cond {
68
69
  /** @internal */
@@ -73,7 +74,7 @@ export class Cond {
73
74
  this.expr = expr;
74
75
  }
75
76
 
76
- /** The condition as the gateway core's JSON spells it. */
77
+ /** Serializes the condition to the gateway core's JSON format. */
77
78
  toJSON(): Expr {
78
79
  return this.expr;
79
80
  }
@@ -82,7 +83,9 @@ export class Cond {
82
83
  function matchers(what: string, ms: readonly Matcher[]): Expr[] {
83
84
  return ms.map(m => {
84
85
  if (!(m instanceof Matcher)) {
85
- throw new TypeError(`match.${what} takes Matchers, not ${describe(m)}`);
86
+ throw new TypeError(
87
+ `match.${what} expects Matcher arguments, got ${describe(m)}`,
88
+ );
86
89
  }
87
90
  return m.expr;
88
91
  });
@@ -91,7 +94,9 @@ function matchers(what: string, ms: readonly Matcher[]): Expr[] {
91
94
  function strings(what: string, values: readonly string[]): string[] {
92
95
  for (const v of values) {
93
96
  if (typeof v !== 'string') {
94
- throw new TypeError(`match.${what} takes strings, not ${describe(v)}`);
97
+ throw new TypeError(
98
+ `match.${what} expects string arguments, got ${describe(v)}`,
99
+ );
95
100
  }
96
101
  }
97
102
  return [...values];
@@ -105,32 +110,31 @@ function describe(v: unknown): string {
105
110
  : typeof v;
106
111
  }
107
112
 
108
- /** Matches the requests every one of `ms` matches: every request when there
109
- * are none. */
113
+ /** Matches requests that satisfy every matcher in `ms` (matches all requests when empty). */
110
114
  export function allOf(...ms: Matcher[]): Matcher {
111
115
  return new Matcher({all: matchers('allOf', ms)});
112
116
  }
113
117
 
114
- /** Matches the requests any of `ms` matches: none when there are none. */
118
+ /** Matches requests that satisfy at least one matcher in `ms` (matches no requests when empty). */
115
119
  export function anyOf(...ms: Matcher[]): Matcher {
116
120
  return new Matcher({anyOf: matchers('anyOf', ms)});
117
121
  }
118
122
 
119
- /** Matches the requests `m` does not, as `m.not()`. */
123
+ /** Matches requests that do not satisfy `m` (equivalent to `m.not()`). */
120
124
  export function not(m: Matcher): Matcher {
121
125
  return new Matcher({not: matchers('not', [m])[0]});
122
126
  }
123
127
 
124
- /** Matches the requests the gateway routes to any of `services`. */
128
+ /** Matches requests routed to any of the given `services`. */
125
129
  export function service(...services: string[]): Matcher {
126
130
  return new Matcher({service: strings('service', services)});
127
131
  }
128
132
 
129
133
  /**
130
- * Matches the requests routed by the gateway's route with `template`, such
131
- * as `/users/{id}`, answering `method`, or any method when it is undefined.
132
- * The names of the template's parameters do not matter, as they do not to
133
- * the router: `/users/{userId}` names the same route.
134
+ * Matches requests routed to the route matching `template` (e.g.
135
+ * `/users/{id}`) and `method` (or any HTTP method if `method` is `undefined`).
136
+ * Path parameter names are ignored, matching router behavior (`/users/{userId}`
137
+ * matches the same route).
134
138
  */
135
139
  export function route(method: string | undefined, template: string): Matcher {
136
140
  return new Matcher({
@@ -138,33 +142,32 @@ export function route(method: string | undefined, template: string): Matcher {
138
142
  });
139
143
  }
140
144
 
141
- /** Matches the requests with any of `methods`, such as `"POST"`. */
145
+ /** Matches requests using any of the given HTTP `methods` (e.g. `"POST"`). */
142
146
  export function method(...methods: string[]): Matcher {
143
147
  return new Matcher({method: strings('method', methods)});
144
148
  }
145
149
 
146
150
  /**
147
- * Matches the requests for exactly `path`, as the client sent it, not
148
- * percent-decoded. A trailing slash does not matter, as it does not to the
149
- * router.
151
+ * Matches requests whose raw (non-percent-decoded) path equals `path`.
152
+ * Trailing slashes are ignored, matching router behavior.
150
153
  */
151
154
  export function path(path: string): Matcher {
152
155
  return new Matcher({path: {exact: path}});
153
156
  }
154
157
 
155
158
  /**
156
- * Matches the requests whose path starts with `prefix`, by whole segments:
157
- * `/admin` matches `/admin` and `/admin/users`, not `/administrators`.
159
+ * Matches requests whose path starts with `prefix` on whole-segment boundaries
160
+ * (for example, `/admin` matches `/admin` and `/admin/users`, but not
161
+ * `/administrators`).
158
162
  */
159
163
  export function pathPrefix(prefix: string): Matcher {
160
164
  return new Matcher({path: {prefix}});
161
165
  }
162
166
 
163
167
  /**
164
- * Matches the requests whose path the glob matches: a `*` segment matches
165
- * any one segment, and a `**` segment any number of them, none included.
166
- * `/users/*` matches `/users/1`, and `/users/**` matches `/users` and
167
- * `/users/1/posts/2`.
168
+ * Matches requests whose path matches `glob`, where `*` matches a single path
169
+ * segment and `**` matches zero or more segments (e.g. `/users/*` matches
170
+ * `/users/1`, and `/users/**` matches `/users` and `/users/1/posts/2`).
168
171
  */
169
172
  export function pathGlob(glob: string): Matcher {
170
173
  return new Matcher({path: {glob}});
@@ -173,14 +176,14 @@ export function pathGlob(glob: string): Matcher {
173
176
  function field(kind: string, name: string, cond: Cond | undefined): Matcher {
174
177
  const c = cond ?? present();
175
178
  if (!(c instanceof Cond)) {
176
- throw new TypeError(`match.${kind} takes a Cond, not ${describe(c)}`);
179
+ throw new TypeError(`match.${kind} expects a Cond, got ${describe(c)}`);
177
180
  }
178
181
  return new Matcher({[kind]: {name, cond: c.expr}});
179
182
  }
180
183
 
181
184
  /**
182
- * Matches the requests whose header `name` satisfies `cond`, or is sent,
183
- * without one. Header names are case-insensitive; values are compared as
185
+ * Matches requests whose header `name` satisfies `cond`, or is present when
186
+ * `cond` is omitted. Header names are case-insensitive; values are compared as
184
187
  * sent.
185
188
  */
186
189
  export function header(name: string, cond?: Cond): Matcher {
@@ -188,51 +191,52 @@ export function header(name: string, cond?: Cond): Matcher {
188
191
  }
189
192
 
190
193
  /**
191
- * Matches the requests whose query parameter `name` satisfies `cond`, or is
192
- * sent, without one. Names are case-sensitive; values are percent-decoded
193
- * before they are compared.
194
+ * Matches requests whose query parameter `name` satisfies `cond`, or is
195
+ * present when `cond` is omitted. Parameter names are case-sensitive; values
196
+ * are percent-decoded before comparison.
194
197
  */
195
198
  export function query(name: string, cond?: Cond): Matcher {
196
199
  return field('query', name, cond);
197
200
  }
198
201
 
199
202
  /**
200
- * Matches the requests whose cookie `name` satisfies `cond`, or is sent,
201
- * without one. Names are case-sensitive; values are compared as sent.
203
+ * Matches requests whose cookie `name` satisfies `cond`, or is present when
204
+ * `cond` is omitted. Cookie names are case-sensitive; values are compared as
205
+ * sent.
202
206
  */
203
207
  export function cookie(name: string, cond?: Cond): Matcher {
204
208
  return field('cookie', name, cond);
205
209
  }
206
210
 
207
- /** Holds when the field is sent. */
211
+ /** Matches when the field is present. */
208
212
  export function present(): Cond {
209
213
  return new Cond({present: true});
210
214
  }
211
215
 
212
- /** Holds when the field is not sent. */
216
+ /** Matches when the field is absent. */
213
217
  export function absent(): Cond {
214
218
  return new Cond({absent: true});
215
219
  }
216
220
 
217
- /** Holds when the field's value is `value`. */
221
+ /** Matches when the field equals `value`. */
218
222
  export function equals(value: string): Cond {
219
223
  return new Cond({equals: value});
220
224
  }
221
225
 
222
- /** Holds when the field's value starts with `prefix`, as `"Bearer "`. */
226
+ /** Matches when the field starts with `prefix` (e.g. `"Bearer "`). */
223
227
  export function prefix(prefix: string): Cond {
224
228
  return new Cond({prefix});
225
229
  }
226
230
 
227
- /** Holds when the field's value is one of `values`. */
231
+ /** Matches when the field equals one of `values`. */
228
232
  export function oneOf(...values: string[]): Cond {
229
233
  return new Cond({oneOf: strings('oneOf', values)});
230
234
  }
231
235
 
232
236
  /**
233
- * Holds when the regular expression matches the field's whole value. In RE2
234
- * syntax, not JavaScript's: Encore checks it before a request reaches
235
- * JavaScript. An invalid one makes `serve` fail.
237
+ * Matches when `pattern` matches the field's entire value. Uses RE2 syntax
238
+ * (not JavaScript RegExp syntax) because Encore evaluates it natively. An
239
+ * invalid pattern causes `serve` to reject.
236
240
  */
237
241
  export function regex(pattern: string): Cond {
238
242
  return new Cond({regex: pattern});
@@ -3,34 +3,35 @@ import type {Matcher} from './match';
3
3
  import type {Completed, Request, Response} from './request';
4
4
 
5
5
  /**
6
- * What a Middleware's `onRequest` failing does to the request: throwing an
7
- * error that is not a {@link Rejection}, or timing out.
6
+ * Determines how the gateway handles an `onRequest` failure (an uncaught error
7
+ * that is not a {@link Rejection}, or a timeout).
8
8
  *
9
- * - `"failClosed"`, the default, refuses the request: 503 Service
10
- * Unavailable when the hook timed out, or the gateway could not hand it to
11
- * JavaScript, which a client may retry, and 500 Internal Server Error
12
- * otherwise. What a Middleware that authenticates needs, so that its
13
- * failure lets no one in.
14
- * - `"failOpen"` lets the request through, as if the hook had, untouched.
15
- * For a Middleware the request does not depend on, such as a rate limiter
16
- * whose store is down.
9
+ * - `"failClosed"` (default): rejects the request — returning 503 Service
10
+ * Unavailable if the hook timed out or could not be dispatched to JavaScript
11
+ * (allowing clients to retry), and 500 Internal Server Error otherwise. Use
12
+ * this for authentication or authorization middleware so failures never grant
13
+ * access.
14
+ * - `"failOpen"`: lets the request through unmodified, as if the hook had
15
+ * succeeded. Use this for non-critical middleware such as a rate limiter
16
+ * backed by an unavailable store.
17
17
  */
18
18
  export type ErrorPolicy = 'failClosed' | 'failOpen';
19
19
 
20
- /** What `onRequest` returns: nothing to let the request through, or a
21
- * {@link Rejection} to answer it. */
20
+ /**
21
+ * Return value of `onRequest`: return nothing to allow the request through, or
22
+ * a {@link Rejection} to answer it directly.
23
+ */
22
24
  export type Decision = void | undefined | Rejection;
23
25
 
24
26
  /**
25
- * Code the gateway runs on the public requests it serves: before they reach
26
- * a service, as they return, and once they are done.
27
+ * Middleware executed by the gateway on public requests before they reach a
28
+ * service, as responses return, and after requests finish.
27
29
  *
28
- * A Middleware is an object, or an instance of a class, with the hooks it is
29
- * called at; the others cost nothing. Each is called only for the requests
30
- * `match` matches. Middleware are called in the order `serve` is given them:
31
- * each `onRequest` sees the headers the ones before it left, and the
32
- * `onResponse` hooks run in reverse, only for the Middleware that let the
33
- * request through.
30
+ * Provide a plain object or class instance implementing only the hooks you
31
+ * need; unimplemented hooks incur no overhead. A middleware runs only on
32
+ * requests matching `match`. Middleware execute in the order passed to `serve`:
33
+ * each `onRequest` sees headers written by earlier middleware, and `onResponse`
34
+ * hooks run in reverse order only for middleware that let the request through.
34
35
  *
35
36
  * ```typescript
36
37
  * class RateLimit implements gateway.Middleware {
@@ -39,58 +40,53 @@ export type Decision = void | undefined | Rejection;
39
40
  * }
40
41
  * ```
41
42
  *
42
- * `serve` checks every Middleware before serving: that it has a hook, that
43
- * every other property whose name starts with `on` and a capital is
44
- * `onError` (no hook is left uncalled for a typo), that its settings are
45
- * valid, and that the names are unique.
43
+ * Before starting, `serve` validates every middleware: it must define at least
44
+ * one hook, have unique kebab-case names, use valid settings, and not define
45
+ * unrecognized `on[A-Z]*` properties (catching misspelled hook names).
46
46
  */
47
47
  export interface Middleware {
48
48
  /**
49
- * Names the Middleware in logs and traces, and as what answered a request
50
- * it refused ({@link Completed.rejectedBy}). Kebab-case, and unique in the
51
- * gateway. When unset, its class's name in kebab-case: `RateLimit` is
52
- * `rate-limit`; a plain object needs one.
49
+ * Unique kebab-case identifier for this middleware, used in logs, traces,
50
+ * and {@link Completed.rejectedBy}. Defaults to the class name in kebab-case
51
+ * (e.g. `RateLimit` becomes `rate-limit`); required for plain objects.
53
52
  */
54
53
  readonly name?: string;
55
54
 
56
- /** The requests it is called for; every request when unset. */
55
+ /** Requests that trigger this middleware. Matches all requests when unset. */
57
56
  readonly match?: Matcher;
58
57
 
59
58
  /**
60
- * How long `onRequest` and `onResponse` may take, in milliseconds,
61
- * counted from when the gateway handed the hook to JavaScript; 5000 when
62
- * unset. The hook has timed out then: its {@link Request.signal} aborts,
63
- * the gateway goes on without it, and `onError` decides, a Middleware
64
- * failing closed answering 503, as the gateway answers its own timeout. A
65
- * hook still waiting to run then is not run. For the later hooks of a hook
66
- * that failed or timed out, its header edits and Request Context fields
67
- * are dropped, and `state` is
68
- * the object it was before the hook: see {@link Request.state}.
59
+ * Maximum time in milliseconds allowed for `onRequest` and `onResponse`,
60
+ * measured from when the gateway enqueues the hook. Defaults to 5000 ms.
61
+ *
62
+ * On expiry, {@link Request.signal} aborts, the gateway moves on without
63
+ * waiting, and `onError` decides the outcome (`"failClosed"` responds with
64
+ * 503). Hooks that expire before starting are skipped. When a hook fails or
65
+ * times out, its header edits and Request Context changes are discarded, and
66
+ * `state` reverts to its previous reference (see {@link Request.state}).
69
67
  */
70
68
  readonly timeoutMs?: number;
71
69
 
72
- /** What `onRequest` failing does to the request; `"failClosed"` when
73
- * unset. */
70
+ /** How `onRequest` failures affect the request. Defaults to `"failClosed"`. */
74
71
  readonly onError?: ErrorPolicy;
75
72
 
76
73
  /**
77
- * Called before the request is forwarded. It may edit the request's
78
- * headers ({@link Request.setHeader}), set its Request Context fields
79
- * ({@link Request.set}) and attributes of its span
80
- * ({@link Request.setAttributes}), and narrow its later hooks
81
- * ({@link Request.skip}).
74
+ * Runs before the request is forwarded. May modify headers
75
+ * ({@link Request.setHeader}), set Request Context fields
76
+ * ({@link Request.set}) or span attributes ({@link Request.setAttributes}),
77
+ * and skip later hooks ({@link Request.skip}).
82
78
  *
83
- * Returning nothing lets the request through. Returning or throwing a
84
- * {@link Rejection} ({@link reject}, {@link respond}) answers it instead:
85
- * no later Middleware is called, and the request is not forwarded. Any
86
- * other error fails the hook, and `onError` decides.
79
+ * Return nothing to let the request through, or return/throw a
80
+ * {@link Rejection} ({@link reject} or {@link respond}) to answer the client
81
+ * immediately without calling later middleware or forwarding the request. Any
82
+ * other error fails the hook and is handled according to `onError`.
87
83
  */
88
84
  onRequest?(req: Request): Decision | Promise<Decision>;
89
85
 
90
86
  /**
91
- * Shown each chunk of the request's body as it is forwarded, `end` set
92
- * with the last. It observes: the body is forwarded whatever it does.
93
- * Under heavy load, chunks it cannot keep up with are dropped, and logged.
87
+ * Observes each chunk of the request body as it is forwarded (`end` is `true`
88
+ * on the final chunk). Forwarding does not wait on this hook; under heavy
89
+ * load, excess chunks may be dropped and logged.
94
90
  */
95
91
  onRequestBody?(
96
92
  req: Request,
@@ -98,13 +94,15 @@ export interface Middleware {
98
94
  end: boolean,
99
95
  ): void | Promise<void>;
100
96
 
101
- /** Called with the response's status and headers before they are
102
- * written. It may edit the response's headers
103
- * ({@link Response.setHeader}). */
97
+ /**
98
+ * Runs with the response status and headers before they are sent to the
99
+ * client. May modify response headers ({@link Response.setHeader}).
100
+ */
104
101
  onResponse?(req: Request, resp: Response): void | Promise<void>;
105
102
 
106
- /** Shown each chunk of the response's body, as `onRequestBody` is the
107
- * request's. */
103
+ /**
104
+ * Observes each chunk of the response body, behaving like `onRequestBody`.
105
+ */
108
106
  onResponseBody?(
109
107
  req: Request,
110
108
  chunk: Uint8Array,
@@ -112,16 +110,16 @@ export interface Middleware {
112
110
  ): void | Promise<void>;
113
111
 
114
112
  /**
115
- * Called once the request is done, off its path: the client has its
116
- * response, or never will. Called for every request the Middleware
117
- * matches, also one another Middleware answered, so it is where to log,
118
- * meter or bill requests. Under heavy load, completions it cannot keep up
119
- * with are dropped, and logged.
113
+ * Runs asynchronously after the request completes (once the client has
114
+ * received the response or disconnected). Invoked for every matched request,
115
+ * even those rejected by another middleware, making it ideal for logging,
116
+ * metrics, or billing. Under heavy load, excess events may be dropped and
117
+ * logged.
120
118
  */
121
119
  onComplete?(done: Completed): void | Promise<void>;
122
120
  }
123
121
 
124
- /** The hooks a Middleware may have, as they are named. @internal */
122
+ /** Supported middleware hook names. @internal */
125
123
  export const HOOKS = [
126
124
  'onRequest',
127
125
  'onRequestBody',
@@ -130,5 +128,5 @@ export const HOOKS = [
130
128
  'onComplete',
131
129
  ] as const;
132
130
 
133
- /** A hook's name. @internal */
131
+ /** Union of supported middleware hook names. @internal */
134
132
  export type HookName = (typeof HOOKS)[number];