@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/serve.ts CHANGED
@@ -1,12 +1,10 @@
1
1
  /**
2
- * Serving the gateway, and handing the events of its hooks to the
3
- * Middleware.
2
+ * Gateway registration and hook event dispatcher.
4
3
  *
5
- * The Middleware are registered with the runtime's gateway variant, whose
6
- * thread hands the events of their hooks to the event loop in batches. Each
7
- * Middleware's events for one request run in a lane: one at a time, in the
8
- * order the host queued them; lanes run concurrently. A `request` or
9
- * `response` event the host awaits an answer to is answered once its hook
4
+ * Middleware are registered with the native gateway runtime, which delivers
5
+ * hook events to the JS event loop in batches. Events for a given
6
+ * `(middleware, request)` pair run sequentially in a lane; separate lanes run
7
+ * concurrently. Blocking `request` and `response` events resolve once the hook
10
8
  * returns, throws, or times out.
11
9
  */
12
10
 
@@ -36,7 +34,7 @@ import {
36
34
  type NativeView,
37
35
  } from './request';
38
36
 
39
- /** The runtime's gateway functions, of its gateway variant. @internal */
37
+ /** Native gateway runtime bindings. @internal */
40
38
  export interface GatewayNative {
41
39
  gatewayRegister(specJson: string): number;
42
40
  gatewayServe(
@@ -69,7 +67,7 @@ export interface GatewayNative {
69
67
  gatewayDropped(): number;
70
68
  }
71
69
 
72
- /** A hook event as the native runtime hands it on. @internal */
70
+ /** Hook event delivered by the native runtime. @internal */
73
71
  export interface RawEvent {
74
72
  kind:
75
73
  | 'request'
@@ -80,7 +78,7 @@ export interface RawEvent {
80
78
  | 'finish';
81
79
  middleware: number;
82
80
  request: number;
83
- /** What an answer names; 0 when none is awaited. */
81
+ /** Event ID to reply to, or 0 when no reply is expected. */
84
82
  eventId: number;
85
83
  view?: NativeView;
86
84
  chunk?: Uint8Array;
@@ -92,7 +90,7 @@ export interface RawEvent {
92
90
 
93
91
  /** @internal */
94
92
  export interface RawCompleted {
95
- /** 0 when none was written. */
93
+ /** 0 when no status was written. */
96
94
  status: number;
97
95
  rejectedBy?: string | null;
98
96
  error?: string | null;
@@ -103,7 +101,7 @@ export interface RawCompleted {
103
101
  responseBodySize: number;
104
102
  }
105
103
 
106
- /** The hooks, as the gateway core's Interest JSON names them. */
104
+ /** Maps JS hook names to the gateway core's Interest JSON hook names. */
107
105
  const CORE_HOOKS: Record<HookName, string> = {
108
106
  onRequest: 'request',
109
107
  onRequestBody: 'requestBody',
@@ -112,10 +110,11 @@ const CORE_HOOKS: Record<HookName, string> = {
112
110
  onComplete: 'complete',
113
111
  };
114
112
 
115
- /** What a Middleware is shown: everything, which the binding hands to
116
- * JavaScript only as a hook reads it. Cookies are parsed from the `Cookie`
117
- * headers then, so a request whose Middleware reads none is not parsed for
118
- * them. */
113
+ /**
114
+ * Fields exposed to middleware on demand. Cookies are parsed lazily from
115
+ * `Cookie` headers so requests whose middleware never reads cookies skip
116
+ * cookie parsing.
117
+ */
119
118
  const READS = {
120
119
  headers: ['*'],
121
120
  query: ['*'],
@@ -130,7 +129,7 @@ const POLICIES: ReadonlySet<string> = new Set<ErrorPolicy>([
130
129
  ]);
131
130
  const NAME = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
132
131
 
133
- /** `RateLimit` as `rate-limit`, `JWTAuth` as `jwt-auth`. @internal */
132
+ /** Converts a class name to kebab-case (e.g. `RateLimit` -> `rate-limit`, `JWTAuth` -> `jwt-auth`). @internal */
134
133
  export function kebab(className: string): string {
135
134
  return className
136
135
  .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
@@ -139,7 +138,7 @@ export function kebab(className: string): string {
139
138
  .toLowerCase();
140
139
  }
141
140
 
142
- /** A Middleware as the dispatcher calls it. @internal */
141
+ /** Validated middleware entry used by the dispatcher. @internal */
143
142
  export interface Registered {
144
143
  mw: Middleware;
145
144
  name: string;
@@ -148,7 +147,7 @@ export interface Registered {
148
147
  onError: ErrorPolicy;
149
148
  }
150
149
 
151
- /** The properties of `mw` and its prototypes, but Object's. */
150
+ /** Collects own and inherited property names of `mw`, excluding `Object.prototype`. */
152
151
  function properties(mw: object): Set<string> {
153
152
  const names = new Set<string>();
154
153
  for (
@@ -171,7 +170,7 @@ function closest(name: string): string {
171
170
  return best ? `; did you mean ${best}?` : '.';
172
171
  }
173
172
 
174
- /** The edit distance between `a` and `b`. */
173
+ /** Computes Levenshtein edit distance between `a` and `b`. */
175
174
  function distance(a: string, b: string): number {
176
175
  let row = Array.from({length: b.length + 1}, (_, j) => j);
177
176
  for (let i = 1; i <= a.length; i++) {
@@ -189,25 +188,25 @@ function distance(a: string, b: string): number {
189
188
  }
190
189
 
191
190
  /**
192
- * The Middleware `serve` is given, checked as far as JavaScript can tell;
193
- * the gateway checks the rest when it is served.
191
+ * Validates middleware passed to `serve` before registering them with the
192
+ * native gateway.
194
193
  * @internal
195
194
  */
196
195
  export function check(middleware: readonly unknown[]): Registered[] {
197
196
  if (middleware.length === 0) {
198
- throw new GatewayError('gateway.serve takes at least one Middleware');
197
+ throw new GatewayError('gateway.serve requires at least one Middleware');
199
198
  }
200
199
  const seen = new Set<string>();
201
200
  return middleware.map((value, i) => {
202
201
  if (typeof value === 'function') {
203
202
  throw new GatewayError(
204
- `gateway.serve takes Middleware objects; argument ${i} is a class or function: ` +
205
- 'instantiate it, as new Auth()',
203
+ `gateway.serve expects Middleware instances; argument ${i} is a class or function — ` +
204
+ 'instantiate it first (e.g. new Auth())',
206
205
  );
207
206
  }
208
207
  if (typeof value !== 'object' || value === null) {
209
208
  throw new GatewayError(
210
- `gateway.serve takes Middleware objects; argument ${i} is ${value === null ? 'null' : typeof value}`,
209
+ `gateway.serve expects Middleware objects; argument ${i} is ${value === null ? 'null' : typeof value}`,
211
210
  );
212
211
  }
213
212
  const mw = value as Middleware;
@@ -217,17 +216,17 @@ export function check(middleware: readonly unknown[]): Registered[] {
217
216
  const where = anonymous ? `middleware ${i}` : className;
218
217
  if (name === undefined) {
219
218
  throw new GatewayError(
220
- `middleware ${i} has no name: a Middleware given as a plain object sets one, as {name: "auth", ...}`,
219
+ `middleware ${i} has no name: plain-object middleware must specify a name (e.g. {name: "auth", ...})`,
221
220
  );
222
221
  }
223
222
  if (typeof name !== 'string' || !NAME.test(name)) {
224
223
  throw new GatewayError(
225
- `${where}'s name is ${JSON.stringify(name)}, which is not kebab-case, as "rate-limit"`,
224
+ `${where}'s name ${JSON.stringify(name)} is not kebab-case (e.g. "rate-limit")`,
226
225
  );
227
226
  }
228
227
  if (mw.match !== undefined && !(mw.match instanceof Matcher)) {
229
228
  throw new GatewayError(
230
- `${where}.match must be a Matcher, from the gateway's match functions, or unset`,
229
+ `${where}.match must be a Matcher from the gateway's match helpers, or undefined`,
231
230
  );
232
231
  }
233
232
  const timeoutMs = mw.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -237,13 +236,13 @@ export function check(middleware: readonly unknown[]): Registered[] {
237
236
  timeoutMs <= 0
238
237
  ) {
239
238
  throw new GatewayError(
240
- `${where}.timeoutMs must be a positive number of milliseconds, not ${String(timeoutMs)}`,
239
+ `${where}.timeoutMs must be a positive number of milliseconds, got ${String(timeoutMs)}`,
241
240
  );
242
241
  }
243
242
  const onError = mw.onError ?? 'failClosed';
244
243
  if (!POLICIES.has(onError)) {
245
244
  throw new GatewayError(
246
- `${where}.onError must be "failClosed" or "failOpen", not ${JSON.stringify(onError)}`,
245
+ `${where}.onError must be "failClosed" or "failOpen", got ${JSON.stringify(onError)}`,
247
246
  );
248
247
  }
249
248
  const hooks = new Set<HookName>();
@@ -251,9 +250,9 @@ export function check(middleware: readonly unknown[]): Registered[] {
251
250
  if (!/^on[A-Z]/.test(prop) || prop === 'onError') continue;
252
251
  if (!(HOOKS as readonly string[]).includes(prop)) {
253
252
  throw new GatewayError(
254
- `${where}.${prop} is not a Middleware hook${closest(prop)} The hooks are ` +
255
- `${HOOKS.join(', ')}; no other property may start with "on" and a capital, ` +
256
- 'but onError.',
253
+ `${where}.${prop} is not a Middleware hook${closest(prop)} Valid hooks are ` +
254
+ `${HOOKS.join(', ')}; no other property may start with "on" followed by a capital letter ` +
255
+ 'except onError.',
257
256
  );
258
257
  }
259
258
  const hook = (mw as unknown as Record<string, unknown>)[prop];
@@ -265,12 +264,12 @@ export function check(middleware: readonly unknown[]): Registered[] {
265
264
  }
266
265
  if (hooks.size === 0) {
267
266
  throw new GatewayError(
268
- `middleware ${JSON.stringify(name)} (${where}) has no hook: define one of ${HOOKS.join(', ')}`,
267
+ `middleware ${JSON.stringify(name)} (${where}) has no hook: define at least one of ${HOOKS.join(', ')}`,
269
268
  );
270
269
  }
271
270
  if (seen.has(name)) {
272
271
  throw new GatewayError(
273
- `two middleware are named ${JSON.stringify(name)}: set name on one of them`,
272
+ `two middleware are named ${JSON.stringify(name)}: give each middleware a unique name`,
274
273
  );
275
274
  }
276
275
  seen.add(name);
@@ -278,8 +277,7 @@ export function check(middleware: readonly unknown[]): Registered[] {
278
277
  });
279
278
  }
280
279
 
281
- /** `reg` as the gateway core registers it, as JSON: its name, Interest and
282
- * limits. @internal */
280
+ /** Serializes a validated middleware registration to JSON for the gateway core. @internal */
283
281
  export function spec(reg: Registered): string {
284
282
  const interest: Record<string, unknown> = {
285
283
  hooks: HOOKS.filter(h => reg.hooks.has(h)).map(h => CORE_HOOKS[h]),
@@ -294,14 +292,14 @@ export function spec(reg: Registered): string {
294
292
  });
295
293
  }
296
294
 
297
- /** One Middleware's events for one request, and its state for it. */
295
+ /** Queued events and state for one middleware on one request. */
298
296
  interface LaneState extends Lane {
299
297
  events: RawEvent[];
300
298
  running: boolean;
301
299
  request: Request | undefined;
302
300
  }
303
301
 
304
- /** How a hook with a timeout ended. */
302
+ /** Result of executing a timed hook. */
305
303
  type Outcome<T> =
306
304
  | {kind: 'returned'; value: T}
307
305
  | {kind: 'threw'; error: unknown}
@@ -310,12 +308,12 @@ type Outcome<T> =
310
308
  /** Never aborts. */
311
309
  const NEVER = new AbortController().signal;
312
310
 
313
- /** Hands the host's hook events to the Middleware. @internal */
311
+ /** Dispatches native gateway hook events to registered middleware. @internal */
314
312
  export class Dispatcher {
315
313
  private readonly lanes = new Map<string, LaneState>();
316
314
  private readonly running = new Set<Promise<void>>();
317
315
  private markClosed!: () => void;
318
- /** Resolves once the host has said no events will come. */
316
+ /** Resolves once the host indicates no further events will arrive. */
319
317
  readonly closed = new Promise<void>(resolve => (this.markClosed = resolve));
320
318
 
321
319
  constructor(
@@ -323,7 +321,7 @@ export class Dispatcher {
323
321
  private readonly mws: ReadonlyMap<number, Registered>,
324
322
  ) {}
325
323
 
326
- /** Takes a batch, or null once the host has closed. */
324
+ /** Enqueues a batch of events, or `null` when the host closes the stream. */
327
325
  deliver(events: RawEvent[] | null): void {
328
326
  if (events === null) {
329
327
  this.markClosed();
@@ -351,7 +349,7 @@ export class Dispatcher {
351
349
  }
352
350
  }
353
351
 
354
- /** Waits for every lane to have handled its events. */
352
+ /** Waits until all active lanes finish processing their queued events. */
355
353
  async drained(): Promise<void> {
356
354
  while (this.running.size > 0) {
357
355
  await Promise.allSettled([...this.running]);
@@ -366,7 +364,7 @@ export class Dispatcher {
366
364
  try {
367
365
  await this.handle(lane, event);
368
366
  } catch (err) {
369
- log.error(err, 'cannot handle a gateway middleware event');
367
+ log.error(err, 'failed to handle gateway middleware event');
370
368
  }
371
369
  }
372
370
  } finally {
@@ -382,7 +380,7 @@ export class Dispatcher {
382
380
  this.native.gatewayFail(
383
381
  event.eventId,
384
382
  event.kind === 'request' ? 'request' : 'response',
385
- `no middleware is registered as ${event.middleware}`,
383
+ `no middleware is registered with id ${event.middleware}`,
386
384
  'error',
387
385
  ),
388
386
  );
@@ -430,16 +428,15 @@ export class Dispatcher {
430
428
  }
431
429
  }
432
430
 
433
- /** The request of `lane`, or one known only by its id, should its request
434
- * event not have reached the lane. */
431
+ /** Returns the lane's `Request`, creating a minimal stub if no `request` event arrived. */
435
432
  private request(reg: Registered, lane: LaneState, id: number): Request {
436
433
  return (lane.request ??= new Request(reg.name, id, undefined, lane));
437
434
  }
438
435
 
439
- /** What is left of the hook's timeout, in milliseconds: the gateway times
440
- * it from when it queued the hook, so a hook that waited has less.
441
- * Undefined when the gateway no longer waits for it: the timeout passed,
442
- * and the gateway went on without it. */
436
+ /**
437
+ * Returns the remaining timeout budget in milliseconds, or `undefined` if
438
+ * the gateway is no longer waiting for this event.
439
+ */
443
440
  private remaining(reg: Registered, eventId: number): number | undefined {
444
441
  const waited = this.native.gatewayWaited(eventId);
445
442
  return waited === null || waited === undefined
@@ -613,18 +610,17 @@ export class Dispatcher {
613
610
  );
614
611
  }
615
612
 
616
- /** Answers a hook: whether the gateway took the answer, false when it no
617
- * longer waited for one. */
613
+ /** Replies to a hook, returning `false` if the gateway is no longer waiting. */
618
614
  private answer(answer: () => boolean): boolean {
619
615
  try {
620
616
  return Boolean(answer());
621
617
  } catch (err) {
622
- log.error(err, 'cannot answer a gateway middleware hook');
618
+ log.error(err, 'failed to send gateway middleware hook response');
623
619
  return false;
624
620
  }
625
621
  }
626
622
 
627
- /** Calls a hook nothing awaits the answer of, logging what it throws. */
623
+ /** Runs a fire-and-forget hook and logs any error it throws. */
628
624
  private async guard(
629
625
  reg: Registered,
630
626
  hook: HookName,
@@ -638,10 +634,10 @@ export class Dispatcher {
638
634
  }
639
635
  }
640
636
 
641
- /** Calls `hook` with the request's trace and Request Context as the
642
- * current ones, so the spans it starts and the calls it makes are part of
643
- * the trace, and carry the fields. The context holds the request's fields
644
- * themselves, so the calls carry those the hook sets as it sets them. */
637
+ /**
638
+ * Runs `hook` with the request's active trace context and live Request
639
+ * Context fields so spans and downstream service calls inherit both.
640
+ */
645
641
  private traced(req: Request, hook: () => unknown): Promise<unknown> {
646
642
  let ctx = reqfields.withLiveFields(req.fields, activeContext());
647
643
  const sc = req.spanContext;
@@ -652,8 +648,7 @@ export class Dispatcher {
652
648
  }
653
649
  }
654
650
 
655
- /** How `hook` ended, within `ms`: a hook that ends later has its error, if
656
- * any, given to `late`. */
651
+ /** Races `hook` against a `ms` timeout, reporting any late rejection to `late`. */
657
652
  function within<T>(
658
653
  hook: Promise<T>,
659
654
  ms: number,
@@ -707,7 +702,7 @@ function completed(req: Request, done: RawCompleted | undefined): Completed {
707
702
  };
708
703
  }
709
704
 
710
- /** `error` for the gateway's records: its name and message. */
705
+ /** Formats an error's name and message for gateway logs and failure reports. */
711
706
  function describe(error: unknown): string {
712
707
  if (error instanceof Error) {
713
708
  return error.message ? `${error.name}: ${error.message}` : error.name;
package/gateways/mod.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * Where the app's gateways are reached.
2
+ * Look up the URLs where the application's API gateways are served.
3
3
  *
4
- * {@link url} is a gateway's URL in the environment the code runs in, as to
5
- * hand a client outside the app the address of its API:
4
+ * {@link url} returns a gateway's base URL in the current environment, for
5
+ * example when giving an external client a webhook or callback address:
6
6
  *
7
7
  * ```ts
8
8
  * import * as gateways from '@encore.dev/sdk/gateways';
@@ -10,14 +10,15 @@
10
10
  * const callback = `${gateways.url('api')}/webhooks/stripe`;
11
11
  * ```
12
12
  *
13
- * A service calls the app's other services with `@encore.dev/sdk/services`,
14
- * not through a gateway. A gateway's middleware is `@encore.dev/sdk/gateway`'s.
13
+ * To call other services within the same application, use
14
+ * `@encore.dev/sdk/services` instead of going through a gateway. For writing
15
+ * gateway middleware, use `@encore.dev/sdk/gateway`.
15
16
  *
16
- * Looking a gateway's URL up links the calling service to it. Encore reads the
17
- * link from the code, as it reads which services a service depends on: so the
18
- * name must be a string literal, written as the gateway declares it, the
19
- * function must be called directly rather than passed around, and the call
20
- * must be in a service.
17
+ * Calling `url()` registers a dependency from the calling service to that
18
+ * gateway. Because Encore resolves these references statically, the gateway
19
+ * name must be a string literal matching the gateway's declared name, `url`
20
+ * must be called directly (not aliased or passed around), and the call must
21
+ * appear inside a service.
21
22
  *
22
23
  * @module
23
24
  */
@@ -25,17 +26,18 @@
25
26
  import {appMeta} from '../app_meta';
26
27
 
27
28
  /**
28
- * The URL `gateway` is reached at in this environment, without a trailing
29
- * slash: a path goes after it, `` `${url("api")}/webhooks/stripe` ``. It is the
30
- * first of the gateway's origins, as {@link appMeta} lists them.
29
+ * Returns the base URL where `gateway` is served in this environment, without
30
+ * a trailing slash (so paths can be appended directly, e.g.
31
+ * `` `${url("api")}/webhooks/stripe` ``). This is the first origin listed for
32
+ * the gateway in {@link appMeta}.
31
33
  *
32
- * The name is the one the gateway is declared with, in its
33
- * `encore.gateway.json` or as the service hosting it: `public_api` does not
34
- * find `public-api`.
34
+ * The name must match the gateway's declared name in `encore.gateway.json` (or
35
+ * the hosting service's name): for example, `"public_api"` will not match
36
+ * `"public-api"`.
35
37
  *
36
- * Throws if the runtime knows no URL for `gateway`: the app has no gateway of
37
- * that name, which Encore's parser reports, or the environment gives it no
38
- * origins.
38
+ * Throws if no URL is available for `gateway` — either because no gateway with
39
+ * that name exists in the app (which Encore's parser reports) or because no
40
+ * origins are configured for it in this environment.
39
41
  *
40
42
  * @example
41
43
  * import {url} from "@encore.dev/sdk/gateways";
@@ -45,15 +47,15 @@ export function url(gateway: string): string {
45
47
  const gw = appMeta().gateways[gateway];
46
48
  if (gw === undefined) {
47
49
  throw new Error(
48
- `encore: no URL is known for gateway ${JSON.stringify(gateway)}: the app has no ` +
49
- 'gateway of that name',
50
+ `encore: no URL is known for gateway ${JSON.stringify(gateway)}: ` +
51
+ 'no gateway with that name exists in this app',
50
52
  );
51
53
  }
52
54
  const found = gw.origins[0]?.replace(/\/+$/, '');
53
55
  if (!found) {
54
56
  throw new Error(
55
- `encore: no URL is known for gateway ${JSON.stringify(gateway)}: the environment ` +
56
- 'gives it no origins',
57
+ `encore: no URL is known for gateway ${JSON.stringify(gateway)}: ` +
58
+ 'no origins are configured for it in this environment',
57
59
  );
58
60
  }
59
61
  return found;
@@ -0,0 +1,50 @@
1
+ import {expect, test} from 'bun:test';
2
+
3
+ // Isolate mocks from native runtime tests.
4
+ test('HTTP span attributes use only redactor results', () => {
5
+ const child = Bun.spawnSync({
6
+ cmd: [
7
+ process.execPath,
8
+ '-e',
9
+ `
10
+ import {mock, expect} from 'bun:test';
11
+ let safe = {route:'/items/{id}',path:'/items/REDACTED',query:'token=REDACTED'};
12
+ let unavailable = false;
13
+ mock.module('../../otel', () => ({tracerProvider() {throw new Error('unused');}}));
14
+ mock.module('../../reqctx/mod', () => ({extract() {throw new Error('unused');}}));
15
+ mock.module('./propagator', () => ({W3CPropagator: class {}}));
16
+ mock.module('../../redaction/mod', () => ({redactor: () => ({
17
+ http(method, target) {
18
+ expect(method).toBe('GET');
19
+ expect(target).toBe('/items/private?token=secret');
20
+ return {requestUrl() {
21
+ if (unavailable) throw new Error('unavailable policy');
22
+ return safe;
23
+ }, request(input) {
24
+ expect(input).toEqual({headers: [['user-agent', 'agent-private']]});
25
+ return {headers: safe.route ? [['user-agent', '[REDACTED]']] : []};
26
+ }};
27
+ },
28
+ })}));
29
+ const {recordSafeHTTPRequest} = await import('./http');
30
+ const attrs = () => {
31
+ const attributes = {};
32
+ recordSafeHTTPRequest(attributes, 'GET', '/items/private?token=secret', 'agent-private');
33
+ return attributes;
34
+ };
35
+ expect(attrs()).toEqual({'http.route':'/items/{id}','url.path':'/items/REDACTED','url.query':'token=REDACTED','user_agent.original':'[REDACTED]'});
36
+ safe = {route:null,path:null,query:null};
37
+ expect(attrs()).toEqual({});
38
+ safe = {route:'/items',path:'/items',query:''};
39
+ expect(attrs()).toEqual({'http.route':'/items','url.path':'/items','user_agent.original':'[REDACTED]'});
40
+ unavailable = true;
41
+ expect(attrs()).toEqual({});
42
+ `,
43
+ ],
44
+ cwd: import.meta.dir,
45
+ });
46
+ if (child.exitCode !== 0) {
47
+ throw new Error(child.stdout.toString() + child.stderr.toString());
48
+ }
49
+ expect(child.exitCode).toBe(0);
50
+ });
@@ -8,6 +8,7 @@ import {
8
8
  type TextMapGetter,
9
9
  } from '@opentelemetry/api';
10
10
  import {tracerProvider} from '../../otel';
11
+ import {redactor} from '../../redaction/mod';
11
12
  import {extract, type HeaderSource} from '../../reqctx/mod';
12
13
  import {W3CPropagator} from './propagator';
13
14
 
@@ -25,11 +26,35 @@ const methods = new Set([
25
26
  'TRACE',
26
27
  ]);
27
28
 
29
+ /** Record only request values approved by the deployed route policy. */
30
+ export function recordSafeHTTPRequest(
31
+ attributes: Attributes,
32
+ method: string,
33
+ target: string,
34
+ userAgent?: string,
35
+ ): void {
36
+ try {
37
+ const http = redactor().http(method, target);
38
+ const {route, path, query} = http.requestUrl();
39
+ if (route !== null) attributes['http.route'] = route;
40
+ if (path !== null) attributes['url.path'] = path;
41
+ if (query) attributes['url.query'] = query;
42
+ if (userAgent) {
43
+ const {headers} = http.request({headers: [['user-agent', userAgent]]});
44
+ const safe = headers.find(([name]) => name === 'user-agent')?.[1];
45
+ if (safe) attributes['user_agent.original'] = safe;
46
+ }
47
+ } catch {
48
+ // Invalid or unavailable policy must not fall back to raw values.
49
+ }
50
+ }
51
+
28
52
  export function startHTTPSpan<Headers extends HeaderSource>(
29
53
  headers: Headers,
30
54
  getter: TextMapGetter<Headers>,
31
55
  requestMethod: string,
32
56
  url: URL,
57
+ target = url.pathname + url.search,
33
58
  ) {
34
59
  const parent = extract(
35
60
  headers,
@@ -50,20 +75,30 @@ export function startHTTPSpan<Headers extends HeaderSource>(
50
75
  url.port ||
51
76
  (url.protocol === 'https:' ? '443' : url.protocol === 'http:' ? '80' : '');
52
77
  if (port) attributes['server.port'] = Number(port);
78
+ const agent = getter.get(headers, 'user-agent');
79
+ recordSafeHTTPRequest(
80
+ attributes,
81
+ requestMethod,
82
+ target,
83
+ Array.isArray(agent) ? agent[0] : agent,
84
+ );
53
85
 
86
+ const route = attributes['http.route'] as string | undefined;
54
87
  const span = tracerProvider()
55
88
  .getTracer('encore')
56
89
  .startSpan(
57
- method === '_OTHER' ? 'HTTP' : method,
58
- {
59
- kind: SpanKind.SERVER,
60
- attributes,
61
- },
90
+ httpSpanName(method, route),
91
+ {kind: SpanKind.SERVER, attributes},
62
92
  parent,
63
93
  );
64
94
  return {span, context: trace.setSpan(parent, span)};
65
95
  }
66
96
 
97
+ function httpSpanName(method: string, route?: string): string {
98
+ const name = method === '_OTHER' ? 'HTTP' : method;
99
+ return route === undefined ? name : `${name} ${route}`;
100
+ }
101
+
67
102
  export function recordHTTPStatus(span: Span, status: number): void {
68
103
  span.setAttribute('http.response.status_code', status);
69
104
  if (status >= 500 && status <= 599) {
@@ -1,5 +1,5 @@
1
1
  // The version of the runtime this JS bundle was generated for.
2
- const version = "v2.0.0-beta.14";
2
+ const version = "v2.0.0-beta.16";
3
3
 
4
4
  // Load the native module. ENCORE_RUNTIME_LIB overrides the location; by
5
5
  // default the library is found by walking up from this file (which the
@@ -188,7 +188,7 @@ const {
188
188
  ConfigWatch,
189
189
  Cursor,
190
190
  Decimal,
191
- DownloadStream,
191
+ Download,
192
192
  EnvironmentType,
193
193
  GatewayHeaders,
194
194
  GatewayView,
@@ -247,7 +247,7 @@ module.exports = {
247
247
  ConfigWatch,
248
248
  Cursor,
249
249
  Decimal,
250
- DownloadStream,
250
+ Download,
251
251
  EnvironmentType,
252
252
  GatewayHeaders,
253
253
  GatewayView,
@@ -301,8 +301,9 @@ if (version !== Runtime.version() && installedRuntimeLib) {
301
301
  );
302
302
  }
303
303
  if (version !== Runtime.version()) {
304
- console.warn(`⚠️ WARNING: The version of the Encore runtime this JS bundle was built for (${version}) does not match the version of the Encore runtime it is running in (${Runtime.version()}).
304
+ const runtimeVersion = Runtime.version().replace(/^v/, "");
305
+ console.warn(`⚠️ WARNING: this @encore.dev/sdk was built for the Encore runtime ${version}, but it is running in the Encore runtime ${Runtime.version()}.
305
306
  This may cause unexpected behaviour in your application.
306
307
 
307
- To resolve this, try update your Encore CLI using "encore version update" and then update the dependencies in your package.json file using "npm install @encore.dev/sdk@latest" (and "npm install encore.dev@latest" if you use the API framework).`);
308
+ To resolve this, install the SDK of the runtime's version: "npm install @encore.dev/sdk@${runtimeVersion}" (and "@encore.dev/framework@${runtimeVersion}" if you use the API framework). If the SDK is the newer, upgrade Encore with "encore version upgrade" instead.`);
308
309
  }