@distilled.cloud/core 1.0.0-rc.2 → 1.0.0-rc.21

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 (321) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +33 -0
  3. package/lib/_bundle/aws.js +2 -0
  4. package/lib/_bundle/aws.js.map +1 -0
  5. package/lib/_bundle/base.js +5 -0
  6. package/lib/_bundle/base.js.map +1 -0
  7. package/lib/_bundle/graphql.js +3 -0
  8. package/lib/_bundle/graphql.js.map +1 -0
  9. package/lib/_bundle/grpc.js +3 -0
  10. package/lib/_bundle/grpc.js.map +1 -0
  11. package/lib/_bundle/rest.js +2 -0
  12. package/lib/_bundle/rest.js.map +1 -0
  13. package/lib/_bundle/xml.js +4 -0
  14. package/lib/_bundle/xml.js.map +1 -0
  15. package/lib/annotations.d.ts +17 -0
  16. package/lib/annotations.d.ts.map +1 -0
  17. package/lib/annotations.js +2 -0
  18. package/lib/annotations.js.map +1 -0
  19. package/lib/api.d.ts +220 -51
  20. package/lib/api.d.ts.map +1 -1
  21. package/lib/api.js +1 -178
  22. package/lib/category.d.ts +19 -16
  23. package/lib/category.d.ts.map +1 -1
  24. package/lib/category.js +1 -280
  25. package/lib/chunks.d.ts +3 -0
  26. package/lib/chunks.d.ts.map +1 -0
  27. package/lib/chunks.js +1 -0
  28. package/lib/config.d.ts +81 -0
  29. package/lib/config.d.ts.map +1 -0
  30. package/lib/config.js +1 -0
  31. package/lib/crypto.d.ts +76 -0
  32. package/lib/crypto.d.ts.map +1 -0
  33. package/lib/crypto.js +1 -0
  34. package/lib/error-category.d.ts +1 -1
  35. package/lib/error-category.d.ts.map +1 -1
  36. package/lib/error-category.js +1 -46
  37. package/lib/errors.d.ts +99 -74
  38. package/lib/errors.d.ts.map +1 -1
  39. package/lib/errors.js +1 -186
  40. package/lib/graphql.d.ts +420 -0
  41. package/lib/graphql.d.ts.map +1 -0
  42. package/lib/graphql.js +1 -0
  43. package/lib/graphql.types.d.ts +11 -0
  44. package/lib/graphql.types.d.ts.map +1 -0
  45. package/lib/graphql.types.js +1 -0
  46. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  47. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  48. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  49. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  50. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  51. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  52. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  53. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  54. package/lib/grpc-transport-node-http2.d.ts +19 -0
  55. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  56. package/lib/grpc-transport-node-http2.js +2 -0
  57. package/lib/grpc-transport-node-http2.js.map +1 -0
  58. package/lib/grpc-transport.d.ts +111 -0
  59. package/lib/grpc-transport.d.ts.map +1 -0
  60. package/lib/grpc-transport.js +1 -0
  61. package/lib/hpack.d.ts +34 -0
  62. package/lib/hpack.d.ts.map +1 -0
  63. package/lib/hpack.js +2 -0
  64. package/lib/hpack.js.map +1 -0
  65. package/lib/index.d.ts +32 -0
  66. package/lib/index.d.ts.map +1 -0
  67. package/lib/index.js +17 -0
  68. package/lib/max-message-bytes.d.ts +42 -0
  69. package/lib/max-message-bytes.d.ts.map +1 -0
  70. package/lib/max-message-bytes.js +2 -0
  71. package/lib/max-message-bytes.js.map +1 -0
  72. package/lib/ndjson.d.ts +3 -0
  73. package/lib/ndjson.d.ts.map +1 -0
  74. package/lib/ndjson.js +2 -0
  75. package/lib/ndjson.js.map +1 -0
  76. package/lib/pagination.d.ts +105 -25
  77. package/lib/pagination.d.ts.map +1 -1
  78. package/lib/pagination.js +1 -182
  79. package/lib/plain-values.d.ts +21 -0
  80. package/lib/plain-values.d.ts.map +1 -0
  81. package/lib/plain-values.js +2 -0
  82. package/lib/plain-values.js.map +1 -0
  83. package/lib/protobuf.d.ts +85 -0
  84. package/lib/protobuf.d.ts.map +1 -0
  85. package/lib/protobuf.js +1 -0
  86. package/lib/protocol-grpc.d.ts +123 -0
  87. package/lib/protocol-grpc.d.ts.map +1 -0
  88. package/lib/protocol-grpc.js +1 -0
  89. package/lib/protocol-http.d.ts +206 -25
  90. package/lib/protocol-http.d.ts.map +1 -1
  91. package/lib/protocol-http.js +1 -554
  92. package/lib/protocol-rest.d.ts +258 -64
  93. package/lib/protocol-rest.d.ts.map +1 -1
  94. package/lib/protocol-rest.js +1 -242
  95. package/lib/protocol.d.ts +113 -0
  96. package/lib/protocol.d.ts.map +1 -0
  97. package/lib/protocol.js +0 -0
  98. package/lib/query.d.ts +29 -0
  99. package/lib/query.d.ts.map +1 -0
  100. package/lib/query.js +1 -0
  101. package/lib/response-validation-strict.d.ts +48 -0
  102. package/lib/response-validation-strict.d.ts.map +1 -0
  103. package/lib/response-validation-strict.js +1 -0
  104. package/lib/response-validation.d.ts +86 -0
  105. package/lib/response-validation.d.ts.map +1 -0
  106. package/lib/response-validation.js +1 -0
  107. package/lib/retry-after.d.ts +4 -4
  108. package/lib/retry-after.d.ts.map +1 -1
  109. package/lib/retry-after.js +1 -112
  110. package/lib/retry-state.d.ts +26 -0
  111. package/lib/retry-state.d.ts.map +1 -0
  112. package/lib/retry-state.js +2 -0
  113. package/lib/retry-state.js.map +1 -0
  114. package/lib/retry.d.ts +141 -42
  115. package/lib/retry.d.ts.map +1 -1
  116. package/lib/retry.js +1 -210
  117. package/lib/schema-lite-impl.d.ts +179 -0
  118. package/lib/schema-lite-impl.d.ts.map +1 -0
  119. package/lib/schema-lite-impl.js +1 -0
  120. package/lib/schema-lite-typed.d.ts +41 -0
  121. package/lib/schema-lite-typed.d.ts.map +1 -0
  122. package/lib/schema-lite-typed.js +1 -0
  123. package/lib/schema-lite.d.ts +41 -0
  124. package/lib/schema-lite.d.ts.map +1 -0
  125. package/lib/schema-lite.js +1 -0
  126. package/lib/schema.d.ts +21 -7
  127. package/lib/schema.d.ts.map +1 -1
  128. package/lib/schema.js +1 -48
  129. package/lib/sdk-error.d.ts +31 -0
  130. package/lib/sdk-error.d.ts.map +1 -0
  131. package/lib/sdk-error.js +1 -0
  132. package/lib/send.d.ts +37 -0
  133. package/lib/send.d.ts.map +1 -0
  134. package/lib/send.js +2 -0
  135. package/lib/send.js.map +1 -0
  136. package/lib/sensitive.d.ts +28 -0
  137. package/lib/sensitive.d.ts.map +1 -0
  138. package/lib/sensitive.js +2 -0
  139. package/lib/sensitive.js.map +1 -0
  140. package/lib/telemetry-debug.d.ts +6 -0
  141. package/lib/telemetry-debug.d.ts.map +1 -0
  142. package/lib/telemetry-debug.js +2 -0
  143. package/lib/telemetry-debug.js.map +1 -0
  144. package/lib/telemetry-hooks.d.ts +32 -0
  145. package/lib/telemetry-hooks.d.ts.map +1 -0
  146. package/lib/telemetry-hooks.js +2 -0
  147. package/lib/telemetry-hooks.js.map +1 -0
  148. package/lib/telemetry-host-rules.d.ts +23 -0
  149. package/lib/telemetry-host-rules.d.ts.map +1 -0
  150. package/lib/telemetry-host-rules.js +2 -0
  151. package/lib/telemetry-host-rules.js.map +1 -0
  152. package/lib/telemetry-lambda-context.d.ts +17 -0
  153. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  154. package/lib/telemetry-lambda-context.js +2 -0
  155. package/lib/telemetry-lambda-context.js.map +1 -0
  156. package/lib/telemetry-message-context.d.ts +52 -0
  157. package/lib/telemetry-message-context.d.ts.map +1 -0
  158. package/lib/telemetry-message-context.js +2 -0
  159. package/lib/telemetry-message-context.js.map +1 -0
  160. package/lib/telemetry-metrics.d.ts +6 -0
  161. package/lib/telemetry-metrics.d.ts.map +1 -0
  162. package/lib/telemetry-metrics.js +2 -0
  163. package/lib/telemetry-metrics.js.map +1 -0
  164. package/lib/telemetry-name-template.d.ts +13 -0
  165. package/lib/telemetry-name-template.d.ts.map +1 -0
  166. package/lib/telemetry-name-template.js +2 -0
  167. package/lib/telemetry-name-template.js.map +1 -0
  168. package/lib/telemetry-stream.d.ts +11 -0
  169. package/lib/telemetry-stream.d.ts.map +1 -0
  170. package/lib/telemetry-stream.js +2 -0
  171. package/lib/telemetry-stream.js.map +1 -0
  172. package/lib/telemetry-xray.d.ts +28 -0
  173. package/lib/telemetry-xray.d.ts.map +1 -0
  174. package/lib/telemetry-xray.js +2 -0
  175. package/lib/telemetry-xray.js.map +1 -0
  176. package/lib/telemetry.d.ts +317 -0
  177. package/lib/telemetry.d.ts.map +1 -0
  178. package/lib/telemetry.js +3 -0
  179. package/lib/telemetry.js.map +1 -0
  180. package/lib/token-cache.d.ts +31 -0
  181. package/lib/token-cache.d.ts.map +1 -0
  182. package/lib/token-cache.js +2 -0
  183. package/lib/token-cache.js.map +1 -0
  184. package/lib/trait.d.ts +94 -20
  185. package/lib/trait.d.ts.map +1 -1
  186. package/lib/trait.js +1 -107
  187. package/lib/unknown-error.d.ts +18 -0
  188. package/lib/unknown-error.d.ts.map +1 -0
  189. package/lib/unknown-error.js +1 -0
  190. package/lib/xml.d.ts +44 -0
  191. package/lib/xml.d.ts.map +1 -0
  192. package/lib/xml.js +1 -0
  193. package/package.json +13 -13
  194. package/src/annotations.ts +53 -0
  195. package/src/api.ts +1597 -234
  196. package/src/category.ts +97 -134
  197. package/src/chunks.ts +30 -0
  198. package/src/config.ts +261 -0
  199. package/src/crypto.ts +202 -0
  200. package/src/error-category.ts +16 -29
  201. package/src/errors.ts +99 -77
  202. package/src/graphql.ts +1817 -0
  203. package/src/graphql.types.ts +120 -0
  204. package/src/grpc-transport-cloudflare-http2.ts +569 -0
  205. package/src/grpc-transport-cloudflare-sockets.ts +368 -0
  206. package/src/grpc-transport-node-http2.ts +307 -0
  207. package/src/grpc-transport.ts +287 -0
  208. package/src/hpack.ts +331 -0
  209. package/src/index.ts +31 -0
  210. package/src/max-message-bytes.ts +58 -0
  211. package/src/ndjson.ts +55 -0
  212. package/src/pagination.ts +379 -94
  213. package/src/plain-values.ts +70 -0
  214. package/src/protobuf.ts +1367 -0
  215. package/src/protocol-grpc.ts +811 -0
  216. package/src/protocol-http.ts +1045 -371
  217. package/src/protocol-rest.ts +908 -255
  218. package/src/protocol.ts +150 -0
  219. package/src/query.ts +39 -0
  220. package/src/response-validation-strict.ts +333 -0
  221. package/src/response-validation.ts +161 -0
  222. package/src/retry-after.ts +8 -14
  223. package/src/retry-state.ts +105 -0
  224. package/src/retry.ts +260 -145
  225. package/src/schema-lite-impl.ts +621 -0
  226. package/src/schema-lite-typed.ts +44 -0
  227. package/src/schema-lite.ts +45 -0
  228. package/src/schema.ts +259 -15
  229. package/src/sdk-error.ts +37 -0
  230. package/src/send.ts +156 -0
  231. package/src/sensitive.ts +188 -0
  232. package/src/telemetry-debug.ts +179 -0
  233. package/src/telemetry-hooks.ts +33 -0
  234. package/src/telemetry-host-rules.ts +39 -0
  235. package/src/telemetry-lambda-context.ts +46 -0
  236. package/src/telemetry-message-context.ts +170 -0
  237. package/src/telemetry-metrics.ts +69 -0
  238. package/src/telemetry-name-template.ts +26 -0
  239. package/src/telemetry-stream.ts +100 -0
  240. package/src/telemetry-xray.ts +66 -0
  241. package/src/telemetry.ts +800 -0
  242. package/src/token-cache.ts +117 -0
  243. package/src/trait.ts +139 -67
  244. package/src/unknown-error.ts +38 -0
  245. package/src/xml.ts +346 -0
  246. package/lib/api.js.map +0 -1
  247. package/lib/category.js.map +0 -1
  248. package/lib/codegen/cli.d.ts +0 -29
  249. package/lib/codegen/cli.d.ts.map +0 -1
  250. package/lib/codegen/cli.js +0 -165
  251. package/lib/codegen/cli.js.map +0 -1
  252. package/lib/codegen/emit.d.ts +0 -129
  253. package/lib/codegen/emit.d.ts.map +0 -1
  254. package/lib/codegen/emit.js +0 -105
  255. package/lib/codegen/emit.js.map +0 -1
  256. package/lib/codegen/format.d.ts +0 -23
  257. package/lib/codegen/format.d.ts.map +0 -1
  258. package/lib/codegen/format.js +0 -28
  259. package/lib/codegen/format.js.map +0 -1
  260. package/lib/codegen/generator.d.ts +0 -334
  261. package/lib/codegen/generator.d.ts.map +0 -1
  262. package/lib/codegen/generator.js +0 -691
  263. package/lib/codegen/generator.js.map +0 -1
  264. package/lib/codegen/graph.d.ts +0 -36
  265. package/lib/codegen/graph.d.ts.map +0 -1
  266. package/lib/codegen/graph.js +0 -136
  267. package/lib/codegen/graph.js.map +0 -1
  268. package/lib/codegen/members.d.ts +0 -25
  269. package/lib/codegen/members.d.ts.map +0 -1
  270. package/lib/codegen/members.js +0 -55
  271. package/lib/codegen/members.js.map +0 -1
  272. package/lib/codegen/naming.d.ts +0 -29
  273. package/lib/codegen/naming.d.ts.map +0 -1
  274. package/lib/codegen/naming.js +0 -74
  275. package/lib/codegen/naming.js.map +0 -1
  276. package/lib/codegen/openapi-cli.d.ts +0 -38
  277. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  278. package/lib/codegen/openapi-cli.js +0 -107
  279. package/lib/codegen/openapi-cli.js.map +0 -1
  280. package/lib/codegen/openapi.d.ts +0 -115
  281. package/lib/codegen/openapi.d.ts.map +0 -1
  282. package/lib/codegen/openapi.js +0 -1220
  283. package/lib/codegen/openapi.js.map +0 -1
  284. package/lib/codegen/operations.d.ts +0 -24
  285. package/lib/codegen/operations.d.ts.map +0 -1
  286. package/lib/codegen/operations.js +0 -56
  287. package/lib/codegen/operations.js.map +0 -1
  288. package/lib/codegen/pagination.d.ts +0 -39
  289. package/lib/codegen/pagination.d.ts.map +0 -1
  290. package/lib/codegen/pagination.js +0 -33
  291. package/lib/codegen/pagination.js.map +0 -1
  292. package/lib/codegen/prelude.d.ts +0 -15
  293. package/lib/codegen/prelude.d.ts.map +0 -1
  294. package/lib/codegen/prelude.js +0 -60
  295. package/lib/codegen/prelude.js.map +0 -1
  296. package/lib/error-category.js.map +0 -1
  297. package/lib/errors.js.map +0 -1
  298. package/lib/json-patch.d.ts +0 -44
  299. package/lib/json-patch.d.ts.map +0 -1
  300. package/lib/json-patch.js +0 -174
  301. package/lib/json-patch.js.map +0 -1
  302. package/lib/pagination.js.map +0 -1
  303. package/lib/protocol-http.js.map +0 -1
  304. package/lib/protocol-rest.js.map +0 -1
  305. package/lib/retry-after.js.map +0 -1
  306. package/lib/retry.js.map +0 -1
  307. package/lib/schema.js.map +0 -1
  308. package/lib/trait.js.map +0 -1
  309. package/src/codegen/cli.ts +0 -268
  310. package/src/codegen/emit.ts +0 -207
  311. package/src/codegen/format.ts +0 -47
  312. package/src/codegen/generator.ts +0 -1153
  313. package/src/codegen/graph.ts +0 -151
  314. package/src/codegen/members.ts +0 -71
  315. package/src/codegen/naming.ts +0 -86
  316. package/src/codegen/openapi-cli.ts +0 -166
  317. package/src/codegen/openapi.ts +0 -1450
  318. package/src/codegen/operations.ts +0 -76
  319. package/src/codegen/pagination.ts +0 -71
  320. package/src/codegen/prelude.ts +0 -70
  321. package/src/json-patch.ts +0 -222
@@ -1,157 +1,188 @@
1
+ import * as Context from "effect/Context";
2
+ import * as Effect from "effect/Effect";
3
+ import * as HttpClient from "effect/http/HttpClient";
4
+ import type * as HttpClientError from "effect/http/HttpClientError";
5
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest";
6
+ import type * as HttpClientResponse from "effect/http/HttpClientResponse";
7
+ import type * as Schema from "effect/Schema";
8
+ import type * as AST from "effect/SchemaAST";
9
+ import type * as Stream from "effect/Stream";
10
+ import { rawResponseRootSymbol, resolveNode } from "./annotations.ts";
11
+ import * as API from "./api.ts";
12
+ import { HTTP_STATUS_MAP, InternalServerError } from "./errors.ts";
13
+ import { recordPageHeaders } from "./pagination.ts";
14
+ import { isEffectStream, unwrapRedactedDeep } from "./plain-values.ts";
15
+ import {
16
+ binaryBodySymbol,
17
+ buildRequest,
18
+ getAnn,
19
+ getProps,
20
+ hasPropAnn,
21
+ mapKeys,
22
+ mapsVerbatim,
23
+ matchTypedError,
24
+ responseErrorFields,
25
+ responseHeaderMembers,
26
+ unsendable,
27
+ withResponseHeaders,
28
+ type InvalidInput,
29
+ type ResponseHeaderMember,
30
+ } from "./protocol-http.ts";
31
+ import type {
32
+ DecodeArgs,
33
+ EncodeArgs,
34
+ Operation,
35
+ DeclaredError,
36
+ DeclaredErrorClass,
37
+ Protocol,
38
+ } from "./protocol.ts";
39
+ import { checkResponse, withholdActual } from "./response-validation.ts";
40
+ import { parseRetryAfterForStatus } from "./retry-after.ts";
41
+ import * as Lite from "./schema-lite-impl.ts";
42
+ import { SdkError } from "./sdk-error.ts";
43
+ import * as Send from "./send.ts";
44
+ import { holdsSensitive, sensitiveValueSymbol, wrapSensitive } from "./sensitive.ts";
1
45
  /**
2
46
  * Generic REST protocol factory for simple bearer/header-auth JSON APIs
3
- * (Neon, Fly.io, PlanetScale, Supabase, Turso, …).
47
+ * (Neon, Fly.io, PlanetScale, Supabase, Turso, ...).
4
48
  *
5
- * `makeRestProtocol(options)` builds a core {@link API.Protocol} layer:
49
+ * `restProtocol(options)` builds a core protocol (core/protocol):
6
50
  *
7
51
  * request: credentials resolved from the CALLING fiber's context on every
8
- * request (the layer itself is memoized per process — see
9
- * `core/api`), auth headers + base URL from the provider's
52
+ * request, auth headers + base URL from the provider's
10
53
  * options, request built by `buildRequest` from
11
54
  * `core/protocol-http` (deep-unwrapping any `Redacted` input
12
55
  * values first)
13
56
  *
14
- * response: 2xx JSON → optional `transformResponse` → recursive wire→TS
15
- * key mapping (`mapKeys`) → `Redacted` wrapping of members
16
- * marked with {@link SensitiveValue}; non-2xx → typed error:
17
- * per-op matcher classes (`matchTypedError`), then the status
18
- * map (default `HTTP_STATUS_MAP`), then an `InternalServerError`
19
- * for unmapped 5xx, then the provider's `unknownError` fallback
20
- * — with `retryAfter` durations stamped from the standard hint
57
+ * response: 2xx JSON -> optional `transformResponse` -> recursive wire->TS
58
+ * key mapping (`mapKeys`) -> in strict mode, a schema check
59
+ * failing with the provider's `parseError` (see
60
+ * `core/response-validation`) -> `Redacted` wrapping of members
61
+ * marked with {@link SensitiveValue}; non-2xx -> typed error:
62
+ * the provider's `classifyError`, then a class the operation
63
+ * or its service declares (by its matchers, `matchTypedError`,
64
+ * or by status for one of core's status classes), then an
65
+ * `InternalServerError` for any other 5xx, then the provider's
66
+ * `unknownError` fallback
67
+ * -- with `retryAfter` durations stamped from the standard hint
21
68
  * headers on retryable statuses.
22
69
  *
70
+ * stream: an `API.makeStreaming` operation with a `framing` config
71
+ * ({@link StreamFraming}) emits each frame of the body as it
72
+ * arrives, decoded as one element of the output's `items`; a
73
+ * plain call collects them.
74
+ *
23
75
  * Anything provider-specific (envelope quirks, bespoke error codes) belongs
24
- * in the provider package — via these options or a hand-written protocol.
76
+ * in the provider package -- via these options or a hand-written protocol.
25
77
  */
26
- import * as Effect from "effect/Effect";
27
- import * as Layer from "effect/Layer";
28
- import * as Redacted from "effect/Redacted";
29
- import type * as AST from "effect/SchemaAST";
30
- import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
31
- import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
32
- import * as API from "./api.ts";
33
- import { makeAnnotation } from "./trait.ts";
34
- import {
35
- buildRequest,
36
- getPropAnn,
37
- getProps,
38
- isOpaqueValue,
39
- mapKeys,
40
- matchTypedError,
41
- resolveNode,
42
- } from "./protocol-http.ts";
43
- import { HTTP_STATUS_MAP, InternalServerError } from "./errors.ts";
44
- import { parseRetryAfterForStatus } from "./retry-after.ts";
78
+ import { httpSymbol, makeAnnotation, type HttpTrait } from "./trait.ts";
79
+ import type { UnknownErrorProps } from "./unknown-error.ts";
45
80
 
46
81
  // =============================================================================
47
82
  // Traits
48
83
  // =============================================================================
49
84
 
50
- export const sensitiveValueSymbol = Symbol.for(
51
- "@distilled.cloud/core/sensitive-value",
52
- );
85
+ export { sensitiveValueSymbol };
53
86
  /**
54
- * Marks a string member as sensitive (mirrors `smithy.api#sensitive`).
55
- * The REST protocol wraps decoded values in `Redacted` on the way out and
87
+ * Marks a string member, map value or list element as sensitive (mirrors
88
+ * `smithy.api#sensitive`). The REST protocol wraps decoded values in
89
+ * `Redacted` on the way out (an untyped `S.Unknown` value whole) and
56
90
  * accepts `string | Redacted<string>` on the way in (unwrapped before
57
91
  * serialization). Takes an ignored argument so generators can inline the
58
92
  * smithy trait value (`T.SensitiveValue({})`).
59
93
  */
60
- export const SensitiveValue = (_value?: unknown) =>
61
- makeAnnotation(sensitiveValueSymbol, true);
94
+ export const SensitiveValue = (_value?: unknown) => makeAnnotation(sensitiveValueSymbol, true);
62
95
 
63
- export const rawResponseSymbol = Symbol.for(
64
- "@distilled.cloud/core/raw-response",
65
- );
96
+ export const rawResponseSymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/raw-response");
66
97
  /**
67
98
  * Marks the sole output member that carries a bare (array/scalar) response
68
99
  * body (mirrors `com.distilled.openapi#rawResponse`).
69
100
  */
70
- export const RawResponse = (_value?: unknown) =>
71
- makeAnnotation(rawResponseSymbol, true);
101
+ export const RawResponse = (_value?: unknown) => makeAnnotation(rawResponseSymbol, true);
72
102
 
73
- export const rawResponseRootSymbol = Symbol.for(
74
- "@distilled.cloud/core/raw-response-root",
75
- );
76
103
  /**
77
104
  * Marks a response schema whose ENTIRE value is the response body (the
78
105
  * generator's `rootPipe` for synthesized bare-payload wrappers): the emitted
79
106
  * response type IS the payload type and the protocol returns the mapped body
80
107
  * directly.
81
108
  */
82
- export const RawResponseRoot = () =>
83
- makeAnnotation(rawResponseRootSymbol, true);
109
+ export { rawResponseRootSymbol };
110
+ export const RawResponseRoot = () => makeAnnotation(rawResponseRootSymbol, true);
111
+
112
+ export const binaryResponseSymbol = /*@__PURE__*/ Symbol.for(
113
+ "@distilled.cloud/core/binary-response",
114
+ );
115
+
116
+ /**
117
+ * Decode a successful raw binary response as a {@link BinaryStream} of the
118
+ * body, never read as text or into one buffer. On a whole output, the
119
+ * output is the stream. On the `RawResponse()` member of a structure
120
+ * output, that member gets the stream and the structure's `Header` members
121
+ * get their response headers (a download's `Content-Type`).
122
+ */
123
+ export const BinaryResponse = () => makeAnnotation(binaryResponseSymbol, true);
124
+
125
+ /**
126
+ * A binary download's body, read as it arrives. It fails with the
127
+ * `HttpClientError` of a read that breaks off (a connection reset).
128
+ * `Stream.mkUint8Array` collects it into one buffer.
129
+ */
130
+ export type BinaryStream = Stream.Stream<Uint8Array, HttpClientError.HttpClientError>;
131
+
132
+ /**
133
+ * A lite declaration whose type guard strict validation applies. Lite
134
+ * `declare` keeps no guard, so the node carries it as `check`.
135
+ */
136
+ const declared = <A>(check: (u: unknown) => boolean, annotations: Lite.Annotations) =>
137
+ Lite.fromNode({
138
+ _tag: "Declaration",
139
+ typeParameters: [],
140
+ check,
141
+ annotations,
142
+ }) as unknown as Schema.Schema<A>;
143
+
144
+ /** The schema of a {@link BinaryStream}, for a binary download's body member. */
145
+ export const BinaryStream = /*@__PURE__*/ declared<BinaryStream>(isEffectStream, {
146
+ identifier: "BinaryStream",
147
+ });
148
+
149
+ /**
150
+ * A binary upload's body from a stream: a `T.HttpBody()` member may take
151
+ * one, and the protocol sends it as it is pulled, without buffering it.
152
+ * A stream can be sent once, so a call with one is never retried. With no
153
+ * modeled `Content-Length` member set, the body goes out chunked.
154
+ */
155
+ export type UploadStream = Stream.Stream<Uint8Array, unknown>;
156
+
157
+ /** A raw request body (`T.HttpBody()` on a binary member): what `buildRequest` sends verbatim. */
158
+ export type RawBody = string | Uint8Array | ArrayBuffer | Blob | UploadStream;
159
+
160
+ /** The schema of a {@link RawBody}, for a binary upload's body member. */
161
+ export const RawBody = /*@__PURE__*/ declared<RawBody>(
162
+ (u) =>
163
+ typeof u === "string" ||
164
+ u instanceof Uint8Array ||
165
+ u instanceof ArrayBuffer ||
166
+ u instanceof Blob ||
167
+ isEffectStream(u),
168
+ { identifier: "RawBody", [binaryBodySymbol]: true },
169
+ );
84
170
 
85
171
  // =============================================================================
86
172
  // Value helpers
87
173
  // =============================================================================
88
174
 
89
- const isPlainObject = (v: unknown): v is Record<string, unknown> =>
90
- v !== null &&
91
- typeof v === "object" &&
92
- !Array.isArray(v) &&
93
- !isOpaqueValue(v) &&
94
- (Object.getPrototypeOf(v) === Object.prototype ||
95
- Object.getPrototypeOf(v) === null);
175
+ export { unwrapRedactedDeep };
96
176
 
97
- /**
98
- * Deep-unwrap `Redacted` values in an input (plain objects/arrays only —
99
- * class instances, files, and binary payloads pass through untouched).
100
- * Sensitive input members accept `string | Redacted<string>`; the wire wants
101
- * the raw string.
102
- */
103
- export const unwrapRedactedDeep = (value: unknown): unknown => {
104
- if (Redacted.isRedacted(value)) return Redacted.value(value);
105
- if (Array.isArray(value)) return value.map(unwrapRedactedDeep);
106
- if (isPlainObject(value)) {
107
- const out: Record<string, unknown> = {};
108
- for (const [k, v] of Object.entries(value)) {
109
- if (v === undefined) continue;
110
- out[k] = unwrapRedactedDeep(v);
111
- }
112
- return out;
113
- }
114
- return value;
115
- };
177
+ export { wrapSensitive };
116
178
 
117
179
  /**
118
- * Walk a decoded (TS-named) value alongside its schema AST, wrapping members
119
- * marked {@link SensitiveValue} in `Redacted`. Keys the schema doesn't model
120
- * pass through verbatim.
180
+ * Whether any member, map value or list element reachable from `ast` is
181
+ * marked {@link SensitiveValue}. Such an output is decoded through
182
+ * {@link wrapSensitive}, and its parse errors withhold the response body (see
183
+ * {@link checkSuccess}, which every REST-style protocol's success path uses).
121
184
  */
122
- export const wrapSensitive = (ast: AST.AST, value: unknown): unknown => {
123
- if (value === null || typeof value !== "object" || isOpaqueValue(value)) {
124
- return value;
125
- }
126
- const node = resolveNode(ast);
127
- if (node._tag === "Arrays") {
128
- if (!Array.isArray(value)) return value;
129
- const elem = (node as any).rest?.[0] as AST.AST | undefined;
130
- return elem ? value.map((v) => wrapSensitive(elem, v)) : value;
131
- }
132
- if (node._tag === "Objects" && !Array.isArray(value)) {
133
- const props = getProps(node);
134
- if (props.length === 0) return value;
135
- const byName = new Map(props.map((p) => [String(p.name), p]));
136
- const out: Record<string, unknown> = {};
137
- for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
138
- if (v === undefined) continue;
139
- const prop = byName.get(k);
140
- if (!prop) {
141
- out[k] = v;
142
- } else if (
143
- getPropAnn(prop, sensitiveValueSymbol) !== undefined &&
144
- typeof v === "string"
145
- ) {
146
- out[k] = Redacted.make(v);
147
- } else {
148
- out[k] = wrapSensitive(prop.type, v);
149
- }
150
- }
151
- return out;
152
- }
153
- return value;
154
- };
185
+ export const hasSensitiveMember: (ast: AST.AST) => boolean = holdsSensitive;
155
186
 
156
187
  // =============================================================================
157
188
  // Protocol factory
@@ -168,27 +199,91 @@ export interface RestErrorInfo {
168
199
  readonly headers: Record<string, string | undefined>;
169
200
  }
170
201
 
202
+ /**
203
+ * The core {@link UnknownErrorProps} of a failure, for an SDK's
204
+ * `unknownError`: `new UnknownNeonError(unknownErrorProps(info))`. A number
205
+ * code becomes its string.
206
+ */
207
+ export const unknownErrorProps = (info: RestErrorInfo): UnknownErrorProps => ({
208
+ status: info.status,
209
+ code: info.code === undefined ? undefined : String(info.code),
210
+ message: info.message,
211
+ body: info.body,
212
+ });
213
+
214
+ /**
215
+ * A 2xx body that failed strict validation, or a non-JSON 2xx body for an
216
+ * output with sensitive members, for the `parseError` option.
217
+ */
218
+ export interface RestParseErrorInfo {
219
+ /** `"[REDACTED]"` when the output has sensitive members. */
220
+ readonly body: unknown;
221
+ readonly cause: unknown;
222
+ }
223
+
171
224
  export interface RestErrorEnvelope {
172
225
  readonly code?: string | number;
173
226
  readonly message?: string;
174
227
  }
175
228
 
176
- export interface RestProtocolOptions<C> {
229
+ /**
230
+ * What this module's own code fails with, whatever the options: the errors
231
+ * every REST protocol declares. A label that would address another resource
232
+ * (`InvalidInput`), a request it can't build or an operation it can't
233
+ * stream (`SdkError`), the transport or a body read (`HttpClientError`), and
234
+ * a 5xx response that neither the operation nor its service declares
235
+ * (`InternalServerError`, which the retry policy retries).
236
+ */
237
+ export type RestProtocolError =
238
+ | InvalidInput
239
+ | SdkError
240
+ | HttpClientError.HttpClientError
241
+ | InternalServerError;
242
+
243
+ /**
244
+ * Options of {@link restProtocol}. The type parameters after `Credentials`
245
+ * are what each option fails with or reads; `restProtocol` infers them from
246
+ * the options, and they are the errors its protocol declares.
247
+ */
248
+ export interface RestProtocolOptions<
249
+ Credentials,
250
+ CredentialsError,
251
+ CredentialsRequirements,
252
+ RouteError,
253
+ ClassifiedError,
254
+ UnknownError,
255
+ ParseError,
256
+ > {
257
+ /**
258
+ * Resolve credentials ON THE CALLING FIBER -- evaluated per request, so
259
+ * context-provided credentials and token refreshes are picked up. Either
260
+ * an effect, or -- for the distilled credentials-service convention --
261
+ * the `Credentials` service key whose value is that effect (read from the calling fiber's context; an
262
+ * already-resolved `Effect.succeed` value costs no extra fiber step). What
263
+ * it fails with (declared on the credentials) reaches every operation
264
+ * through the protocol, and what it reads is the protocol's requirement.
265
+ */
266
+ readonly credentials:
267
+ | Effect.Effect<Credentials, CredentialsError, CredentialsRequirements>
268
+ | Context.Key<CredentialsRequirements, Effect.Effect<Credentials, CredentialsError>>;
177
269
  /**
178
- * Resolve credentials ON THE CALLING FIBER — evaluated per request, never
179
- * at layer build time, so context-provided credentials and token refreshes
180
- * are picked up. Typically `Effect.gen(function* () { const resolve =
181
- * yield* Credentials; return yield* resolve; })` for the distilled
182
- * credentials-service convention. Its error/requirement channels are
183
- * erased at the protocol boundary (Protocol effects carry none) and
184
- * reintroduced for callers by the generated `<Sdk>OpError` /
185
- * `<Sdk>OpContext` annotations.
270
+ * API base URL from the resolved credentials. Receives the operation's
271
+ * route so APIs with more than one endpoint (e.g. S2's account vs
272
+ * per-basin hosts, chosen by path) can route per request; single-endpoint
273
+ * providers ignore the argument. `server` is the operation's host name
274
+ * (`T.Http({ server })`) for APIs that serve some operations from another
275
+ * host; map it to a base URL from the credentials. To refuse a route (e.g.
276
+ * a required scope missing from the credentials), return `Effect.fail` of
277
+ * the error the call fails with. A THROWN error fails the call with
278
+ * `SdkError`, as anything thrown under a call does (the defect boundary,
279
+ * `./api.ts`).
186
280
  */
187
- readonly credentials: Effect.Effect<C, any, any>;
188
- /** API base URL from the resolved credentials. */
189
- readonly baseUrl: (credentials: C) => string;
281
+ readonly baseUrl: (
282
+ credentials: Credentials,
283
+ target: { readonly uri: string; readonly method: string; readonly server?: string | undefined },
284
+ ) => string | Effect.Effect<never, RouteError>;
190
285
  /** Auth (and any fixed) headers from the resolved credentials. */
191
- readonly headers: (credentials: C) => Record<string, string>;
286
+ readonly headers: (credentials: Credentials) => Record<string, string>;
192
287
  /**
193
288
  * Extract `{ code?, message? }` from a parsed non-2xx JSON body. Default:
194
289
  * lenient `{ code?, message? | error? }` (covers the common REST error
@@ -196,172 +291,730 @@ export interface RestProtocolOptions<C> {
196
291
  */
197
292
  readonly errorEnvelope?: (body: unknown) => RestErrorEnvelope | undefined;
198
293
  /**
199
- * HTTP status → error class constructed as `new Cls({ message, retryAfter
200
- * })`. Default: core `HTTP_STATUS_MAP`. Consulted after per-op typed error
201
- * matching; unmapped 5xx fall back to `InternalServerError`, everything
202
- * else to {@link unknownError}.
294
+ * JSON pointer to the object that holds a failure's fields when the
295
+ * provider nests them, e.g. `"/error"` for `{ error: { status, details } }`.
296
+ * A typed error's declared fields are read there first, then at the top
297
+ * level of the body.
298
+ */
299
+ readonly errorFieldsAt?: string;
300
+ /**
301
+ * The provider's own reading of a failure, consulted before the classes
302
+ * the operation and its service declare: return the error to fail with, or
303
+ * `undefined` to decode the failure as usual. For rules a status alone
304
+ * can't express, e.g. a 403 that is a rate limit because of its headers.
203
305
  */
204
- readonly statusMap?: Readonly<Record<number, new (args: any) => any>>;
205
- /** Fallback error for failures nothing else matched. */
206
- readonly unknownError: (info: RestErrorInfo) => unknown;
306
+ readonly classifyError?: (info: RestErrorInfo) => ClassifiedError | undefined;
307
+ /**
308
+ * Fallback error for failures nothing else matched: the SDK's
309
+ * `Unknown<Sdk>Error`, built from {@link unknownErrorProps}. Only non-5xx
310
+ * statuses reach it (an undeclared 5xx is `InternalServerError`), so the
311
+ * class carries no retryable category.
312
+ */
313
+ readonly unknownError: (info: RestErrorInfo) => UnknownError;
314
+ /**
315
+ * The SDK's `<Sdk>ParseError`, raised when a 2xx body does not match the
316
+ * operation's output schema in strict mode (see
317
+ * `core/response-validation`), and in every mode when a 2xx body for an
318
+ * output with sensitive members is not JSON. `body` is the parsed JSON, or
319
+ * the raw text when the body wasn't JSON, and `"[REDACTED]"` for an output
320
+ * with sensitive members; `cause` is the schema error, or `"Invalid JSON
321
+ * response"`.
322
+ */
323
+ readonly parseError: (info: RestParseErrorInfo) => ParseError;
207
324
  /** Transform the parsed 2xx JSON before decoding (e.g. stripNulls). */
208
325
  readonly transformResponse?: (body: unknown) => unknown;
209
326
  /** Passed through to `buildRequest` (member-header transforms). */
210
327
  readonly mapMemberHeader?: (name: string, value: string) => string;
211
328
  /** Passed through to `buildRequest` (wire names for unmodeled input keys). */
212
329
  readonly unknownKeyToWire?: (key: string) => string;
330
+ /** Passed through to `buildRequest`: send `{}` when a bodied call has no body members. */
331
+ readonly emptyJsonBody?: boolean;
332
+ }
333
+
334
+ /**
335
+ * The body of a streamed 2xx response, for {@link StreamFraming.stream}.
336
+ * `Failure` is what the call fails with.
337
+ */
338
+ export interface FramedBody<Failure> {
339
+ readonly body: Stream.Stream<Uint8Array, Failure>;
340
+ /**
341
+ * Decode one parsed frame as one element of the output's `items`, as a
342
+ * 2xx body decodes (key mapping, strict validation, `Redacted`).
343
+ */
344
+ readonly item: (json: unknown, text: string) => Effect.Effect<unknown, Failure>;
345
+ /** The SDK's parse error for a frame that is not JSON. */
346
+ readonly invalid: (text: string) => Failure;
347
+ }
348
+
349
+ /** A plain call's framed body, read whole: the output JSON, or not JSON. */
350
+ export interface CollectedBody {
351
+ readonly json: unknown;
352
+ readonly nonJson: boolean;
353
+ }
354
+
355
+ /**
356
+ * How a server-streaming operation's body is framed (`API.makeStreaming`,
357
+ * output `{ items }`): its `framing` config, e.g. `ndjson` from
358
+ * core/ndjson. An operation without one can't stream (`.stream()` fails
359
+ * with `SdkError`, see `API.cannotStream`).
360
+ */
361
+ export interface StreamFraming {
362
+ /**
363
+ * A plain call's whole body as `{ items }`, or `undefined` when the
364
+ * response's `Content-Type` is not this framing (decoded as usual).
365
+ */
366
+ readonly collect: (text: string, contentType: string | undefined) => CollectedBody | undefined;
367
+ /**
368
+ * Each frame as it arrives, through `item`. `open` sends the request and
369
+ * fails with the operation's typed error on a failed status.
370
+ */
371
+ readonly stream: <Failure, Requirements>(
372
+ open: Effect.Effect<FramedBody<Failure>, Failure, Requirements>,
373
+ ) => Stream.Stream<unknown, Failure, Requirements>;
213
374
  }
214
375
 
215
376
  const defaultErrorEnvelope = (body: unknown): RestErrorEnvelope | undefined => {
216
377
  if (body === null || typeof body !== "object") return undefined;
217
378
  const b = body as Record<string, unknown>;
218
- const code =
219
- typeof b.code === "string" || typeof b.code === "number"
220
- ? b.code
221
- : undefined;
379
+ const code = typeof b.code === "string" || typeof b.code === "number" ? b.code : undefined;
222
380
  const message =
223
- typeof b.message === "string"
224
- ? b.message
225
- : typeof b.error === "string"
226
- ? b.error
227
- : undefined;
381
+ typeof b.message === "string" ? b.message : typeof b.error === "string" ? b.error : undefined;
228
382
  return { code, message };
229
383
  };
230
384
 
231
- // Bridge: Protocol.decode is typed as Effect<unknown> (no error channel),
232
- // but REST failures are real typed errors that operations re-surface via
233
- // their `errors: [...]` lists. Fail with the instance and erase the type
234
- // here; the generated operation annotations reintroduce it for callers.
235
- const fail = (e: unknown): Effect.Effect<never> =>
236
- Effect.fail(e) as Effect.Effect<never>;
385
+ // =============================================================================
386
+ // 2xx bodies
387
+ // =============================================================================
388
+
389
+ /** A 2xx body a protocol read, for {@link checkSuccess}. */
390
+ export interface SuccessBody {
391
+ /** The value to check and return: the body mapped onto the output's TS names. */
392
+ readonly value: unknown;
393
+ /** What a parse error reports as `body` for an output without sensitive members. */
394
+ readonly body: unknown;
395
+ /** Whether the body was not JSON. */
396
+ readonly nonJson: boolean;
397
+ }
398
+
399
+ /** The outcome of {@link checkSuccess}: the value, or the parse error's fields. */
400
+ export type SuccessCheck =
401
+ | { readonly ok: true; readonly value: unknown }
402
+ | { readonly ok: false; readonly error: RestParseErrorInfo };
403
+
404
+ /**
405
+ * Check a 2xx body against the operation's output schema and deliver its
406
+ * sensitive values as `Redacted`. Every REST-style protocol ends its success
407
+ * path here, so all of them treat a body that can hold a secret alike:
408
+ *
409
+ * - The checked value comes back through {@link wrapSensitive}.
410
+ * - A mismatch (validating modes, see `core/response-validation`) reports
411
+ * `read.body` and the schema error.
412
+ * - For an output with sensitive members ({@link hasSensitiveMember}), a
413
+ * non-JSON body fails in every mode with `"Invalid JSON response"`, and a
414
+ * mismatch reports `body: "[REDACTED]"` and the schema error without the
415
+ * value it found (`withholdActual`).
416
+ *
417
+ * Synchronous, for protocols that already hold the calling fiber's context;
418
+ * {@link validateSuccess} is the `Effect` form.
419
+ */
420
+ export const checkSuccess = (
421
+ context: Context.Context<any>,
422
+ outputAst: AST.AST,
423
+ read: SuccessBody,
424
+ ): SuccessCheck => {
425
+ const sensitive = hasSensitiveMember(outputAst);
426
+ if (read.nonJson && sensitive) {
427
+ return { ok: false, error: { body: "[REDACTED]", cause: "Invalid JSON response" } };
428
+ }
429
+ const invalid = checkResponse(context, outputAst, read.value);
430
+ if (invalid !== undefined) {
431
+ return {
432
+ ok: false,
433
+ error: sensitive
434
+ ? { body: "[REDACTED]", cause: withholdActual(invalid) }
435
+ : { body: read.body, cause: invalid },
436
+ };
437
+ }
438
+ return { ok: true, value: sensitive ? wrapSensitive(outputAst, read.value) : read.value };
439
+ };
440
+
441
+ /**
442
+ * {@link checkSuccess} on the calling fiber, failing with `parseError` (the
443
+ * SDK's `<Sdk>ParseError`) built from the withheld-or-not fields.
444
+ */
445
+ export const validateSuccess = <E>(
446
+ outputAst: AST.AST,
447
+ read: SuccessBody,
448
+ parseError: (info: RestParseErrorInfo) => E,
449
+ ): Effect.Effect<unknown, E> =>
450
+ Effect.withFiber((fiber) => {
451
+ const checked = checkSuccess(fiber.context as Context.Context<any>, outputAst, read);
452
+ return checked.ok ? Effect.succeed(checked.value) : Effect.fail(parseError(checked.error));
453
+ });
454
+
455
+ /** Per-operation decode facts, read from the output schema once. */
456
+ interface DecodePlan {
457
+ /** The whole output is the body's bytes. */
458
+ readonly binary: boolean;
459
+ /** The structure member that gets the body's bytes, next to its header members. */
460
+ readonly binaryMember: string | undefined;
461
+ readonly verbatim: boolean;
462
+ /**
463
+ * A member of a structure output that receives the whole body
464
+ * (`T.RawResponse()` next to header members), e.g. a bare JSON array with
465
+ * its next-page token in a response header.
466
+ */
467
+ readonly bodyMember: AST.PropertySignature | undefined;
468
+ /** The output is a bare string, so an empty body decodes to `""`. */
469
+ readonly text: boolean;
470
+ /** Members read from response headers (`T.Header`). */
471
+ readonly headers: ReadonlyArray<ResponseHeaderMember>;
472
+ }
473
+
474
+ const decodePlans = /*@__PURE__*/ new WeakMap<AST.AST, DecodePlan>();
475
+ const decodePlanFor = (outputAst: AST.AST): DecodePlan => {
476
+ let plan = decodePlans.get(outputAst);
477
+ if (plan === undefined) {
478
+ const bodyMember = getProps(outputAst).find((prop) => hasPropAnn(prop, rawResponseSymbol));
479
+ plan = {
480
+ binary: getAnn(outputAst, binaryResponseSymbol) !== undefined,
481
+ binaryMember:
482
+ bodyMember !== undefined && hasPropAnn(bodyMember, binaryResponseSymbol)
483
+ ? String(bodyMember.name)
484
+ : undefined,
485
+ verbatim: mapsVerbatim(outputAst, "decode"),
486
+ text: resolveNode(outputAst)._tag === "String",
487
+ headers: responseHeaderMembers(outputAst),
488
+ bodyMember,
489
+ };
490
+ decodePlans.set(outputAst, plan);
491
+ }
492
+ return plan;
493
+ };
494
+
495
+ /**
496
+ * Read a 2xx response of a binary output ({@link BinaryResponse}) as a
497
+ * {@link BinaryStream}: the stream itself for a binary whole output, or the
498
+ * structure with the stream in its body member and its header members
499
+ * filled. `undefined` when the output is not binary. The call returns once
500
+ * the headers arrive; a body read that fails later (reset or abort
501
+ * mid-body) fails the stream with its `HttpClientError`. For hand-written
502
+ * protocols too, so every SDK decodes a download the same way.
503
+ */
504
+ export const readBinaryResponse = (
505
+ response: HttpClientResponse.HttpClientResponse,
506
+ outputAst: AST.AST,
507
+ ): Effect.Effect<unknown> | undefined => {
508
+ const plan = decodePlanFor(outputAst);
509
+ const body: BinaryStream = response.stream;
510
+ if (plan.binary) return Effect.succeed(body);
511
+ const member = plan.binaryMember;
512
+ if (member === undefined) return undefined;
513
+ return Effect.succeed(
514
+ withResponseHeaders(
515
+ plan.headers,
516
+ { [member]: body },
517
+ response.headers as Record<string, string | undefined>,
518
+ ),
519
+ );
520
+ };
521
+
522
+ /**
523
+ * The outcome of decoding a response body: the value, or the failure the
524
+ * call fails with. Plain data, so decoding stays synchronous.
525
+ */
526
+ type Decoded<Failure> =
527
+ | { readonly ok: true; readonly value: unknown }
528
+ | { readonly ok: false; readonly error: Failure };
237
529
 
238
530
  /**
239
- * Build a `Layer<Protocol>` for a simple REST JSON API. Assign the result to
240
- * a module-level const in the provider's `protocol.ts` — `API.make` memoizes
241
- * protocol layers by value identity.
531
+ * The class core has for `status`, when the operation or its service
532
+ * declares it: a list of declared errors can hold core's status classes
533
+ * (`Unauthorized`, `TooManyRequests`, ...), which are matched by status.
534
+ * For a protocol that reads failed responses itself.
242
535
  */
243
- export const makeRestProtocol = <C>(
244
- options: RestProtocolOptions<C>,
245
- ): Layer.Layer<API.Protocol> => {
536
+ export const declaredStatusClass = (
537
+ status: number,
538
+ declared: ReadonlyArray<DeclaredErrorClass>,
539
+ ): DeclaredErrorClass | undefined => {
540
+ const core: unknown = (HTTP_STATUS_MAP as Readonly<Record<number, unknown>>)[status];
541
+ return core === undefined ? undefined : declared.find((cls) => cls === core);
542
+ };
543
+
544
+ /**
545
+ * The methods of {@link restProtocol}, for either form of `credentials`.
546
+ * For the protocols core builds on them (core/protocol-grpc).
547
+ */
548
+ export const restProtocolMethods = <
549
+ Credentials,
550
+ CredentialsError = never,
551
+ CredentialsRequirements = never,
552
+ RouteError = never,
553
+ ClassifiedError = never,
554
+ UnknownError = never,
555
+ ParseError = never,
556
+ >(
557
+ options: RestProtocolOptions<
558
+ Credentials,
559
+ CredentialsError,
560
+ CredentialsRequirements,
561
+ RouteError,
562
+ ClassifiedError,
563
+ UnknownError,
564
+ ParseError
565
+ >,
566
+ ): Protocol<
567
+ CredentialsError | RouteError | ClassifiedError | UnknownError | ParseError | RestProtocolError,
568
+ CredentialsRequirements
569
+ > => {
570
+ /** What a request that can't be built fails with. */
571
+ type RequestError = RouteError | InvalidInput | SdkError;
572
+ /** Everything a call fails with. */
573
+ type Failure =
574
+ | DeclaredError
575
+ | ClassifiedError
576
+ | UnknownError
577
+ | ParseError
578
+ | CredentialsError
579
+ | RequestError
580
+ | InternalServerError
581
+ | HttpClientError.HttpClientError;
582
+
246
583
  const errorEnvelope = options.errorEnvelope ?? defaultErrorEnvelope;
247
- const statusMap: Readonly<
248
- Record<number, (new (args: any) => any) | undefined>
249
- > = options.statusMap ?? HTTP_STATUS_MAP;
250
-
251
- const encode = ({
252
- input,
253
- inputAst,
254
- }: {
255
- readonly input: unknown;
256
- readonly inputAst: AST.AST;
257
- }) =>
258
- Effect.gen(function* () {
259
- const creds = yield* options.credentials as Effect.Effect<C>;
260
- return buildRequest({
261
- input: unwrapRedactedDeep(input),
262
- inputAst,
263
- baseUrl: options.baseUrl(creds),
264
- headers: options.headers(creds),
265
- mapMemberHeader: options.mapMemberHeader,
266
- unknownKeyToWire: options.unknownKeyToWire,
267
- });
584
+ // Told apart once, not per call.
585
+ const credentials = options.credentials;
586
+ const credentialsKey = Context.isKey(credentials) ? credentials : undefined;
587
+ const credentialsEffect = Context.isKey(credentials) ? undefined : credentials;
588
+
589
+ /** The calling fiber's credentials, then `f` on them. */
590
+ const withCredentials = <B, E>(
591
+ context: Context.Context<any>,
592
+ f: (creds: Credentials) => Effect.Effect<B, E>,
593
+ ): Effect.Effect<B, CredentialsError | E, CredentialsRequirements> =>
594
+ API.withValue(credentialsEffect ?? Context.get(context, credentialsKey!), f);
595
+
596
+ /**
597
+ * The request; fails with the error a refusing `baseUrl` returned, or with
598
+ * `InvalidInput` for a label that would address another resource.
599
+ */
600
+ const requestFor = (
601
+ creds: Credentials,
602
+ input: unknown,
603
+ inputAst: AST.AST,
604
+ ): Effect.Effect<HttpClientRequest.HttpClientRequest, RequestError> => {
605
+ const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
606
+ const baseUrl = options.baseUrl(creds, {
607
+ uri: http?.uri ?? "",
608
+ method: http?.method ?? "",
609
+ server: http?.server,
268
610
  });
611
+ // A baseUrl that refuses the route (missing scope in the credentials)
612
+ // returns the failure.
613
+ if (typeof baseUrl !== "string") return baseUrl;
614
+ let plain: unknown;
615
+ try {
616
+ plain = unwrapRedactedDeep(input);
617
+ } catch (cause) {
618
+ // An input that contains itself: the walk overflows the stack.
619
+ return Effect.fail(unsendable(cause));
620
+ }
621
+ return buildRequest({
622
+ input: plain,
623
+ inputAst,
624
+ baseUrl,
625
+ headers: options.headers(creds),
626
+ mapMemberHeader: options.mapMemberHeader,
627
+ unknownKeyToWire: options.unknownKeyToWire,
628
+ emptyJsonBody: options.emptyJsonBody,
629
+ });
630
+ };
269
631
 
270
- const decode = ({
271
- response,
272
- outputAst,
273
- errors: errorClasses,
274
- }: {
275
- readonly response: HttpClientResponse.HttpClientResponse;
276
- readonly outputAst: AST.AST;
277
- readonly errors: ReadonlyArray<unknown>;
278
- }) =>
279
- Effect.gen(function* () {
280
- // Read as text and parse tolerantly — error pages are often non-JSON.
281
- const text = (yield* response.text.pipe(Effect.orDie)) ?? "";
282
- if (process.env.DISTILLED_DEBUG_HTTP) {
283
- console.error(
284
- `[distilled] <- ${response.status} ${text.slice(0, 400)}`,
285
- );
632
+ /** Map a read response body to the call's outcome. */
633
+ const decodeText = (
634
+ context: Context.Context<any>,
635
+ status: number,
636
+ headers: Record<string, string | undefined>,
637
+ text: string,
638
+ outputAst: AST.AST,
639
+ errorClasses: ReadonlyArray<DeclaredErrorClass>,
640
+ framing: StreamFraming | undefined,
641
+ ): Decoded<Failure> => {
642
+ // Read as text and parse tolerantly -- error pages are often non-JSON.
643
+ let json: unknown;
644
+ let nonJson = false;
645
+ if (text.trim().length > 0) {
646
+ try {
647
+ json = JSON.parse(text);
648
+ } catch {
649
+ nonJson = true;
286
650
  }
287
- let json: unknown;
288
- let nonJson = false;
289
- if (text.trim().length > 0) {
290
- try {
291
- json = JSON.parse(text);
292
- } catch {
293
- nonJson = true;
294
- }
651
+ }
652
+
653
+ if (status >= 400) {
654
+ const env = (nonJson ? undefined : errorEnvelope(json)) ?? {};
655
+ const message = env.message ?? (nonJson && text.trim() ? text.trim() : `HTTP ${status}`);
656
+
657
+ // 0. The provider's own reading of the failure.
658
+ if (options.classifyError) {
659
+ const classified = options.classifyError({
660
+ status,
661
+ code: env.code,
662
+ message,
663
+ body: nonJson ? text : json,
664
+ headers,
665
+ });
666
+ if (classified !== undefined) return { ok: false, error: classified };
295
667
  }
296
- const status = response.status;
297
- const headers = response.headers as Record<string, string | undefined>;
298
668
 
299
- if (status >= 400) {
300
- const env = (nonJson ? undefined : errorEnvelope(json)) ?? {};
301
- const message =
302
- env.message ??
303
- (nonJson && text.trim() ? text.trim() : `HTTP ${status}`);
669
+ // The body and headers every error below carries.
670
+ const response = { body: nonJson ? text : json, headers, fieldsAt: options.errorFieldsAt };
304
671
 
305
- // 1. Per-operation typed error (matcher metadata on the class).
306
- const typed = matchTypedError(errorClasses, status, [
672
+ // 1. A declared error whose matcher fits (the operation's classes,
673
+ // then its service's).
674
+ const typed = matchTypedError(
675
+ errorClasses,
676
+ status,
677
+ [
307
678
  {
308
679
  code: typeof env.code === "number" ? env.code : undefined,
309
680
  message,
310
681
  },
311
- ]);
312
- if (typed !== undefined) return yield* fail(typed);
313
-
314
- // 2. Status-mapped class (retryAfter only stamps on retryable
315
- // statuses — parseRetryAfterForStatus gates on that).
316
- const StatusErrorClass = statusMap[status];
317
- if (StatusErrorClass) {
318
- return yield* fail(
319
- new StatusErrorClass({
320
- message,
321
- retryAfter: parseRetryAfterForStatus(status, headers),
322
- }),
323
- );
324
- }
325
-
326
- // 3. Unmapped 5xx (e.g. proxy-specific statuses) → retryable server
327
- // error rather than the unknown fallback.
328
- if (status >= 500) {
329
- return yield* fail(
330
- new InternalServerError({
331
- message,
332
- retryAfter: parseRetryAfterForStatus(status, headers),
333
- }),
334
- );
335
- }
336
-
337
- // 4. Provider fallback.
338
- return yield* fail(
339
- options.unknownError({
340
- status,
341
- code: env.code,
682
+ ],
683
+ response,
684
+ );
685
+ if (typed !== undefined) return { ok: false, error: typed };
686
+
687
+ // 2. Core's class for the status, when declared (retryAfter only
688
+ // stamps on retryable statuses -- parseRetryAfterForStatus gates
689
+ // on that).
690
+ const StatusErrorClass = declaredStatusClass(status, errorClasses);
691
+ if (StatusErrorClass) {
692
+ return {
693
+ ok: false,
694
+ error: new StatusErrorClass({
342
695
  message,
343
- body: nonJson ? text : json,
344
- headers,
696
+ ...responseErrorFields(undefined, response),
697
+ retryAfter: parseRetryAfterForStatus(status, headers),
345
698
  }),
346
- );
699
+ };
347
700
  }
348
701
 
349
- // 2xx: the response body IS the payload (no envelope). Wire→TS key
350
- // mapping is schema-driven; `RawResponseRoot` responses are the body
351
- // verbatim (mapKeys handles arrays/scalars structurally either way).
352
- let body: unknown = nonJson ? text : (json ?? {});
353
- if (options.transformResponse) body = options.transformResponse(body);
354
- return wrapSensitive(outputAst, mapKeys(outputAst, body, "decode"));
702
+ // 3. Any other 5xx (e.g. proxy-specific statuses) -> retryable server
703
+ // error rather than the unknown fallback.
704
+ if (status >= 500) {
705
+ return {
706
+ ok: false,
707
+ error: new InternalServerError({
708
+ message,
709
+ ...responseErrorFields(undefined, response),
710
+ retryAfter: parseRetryAfterForStatus(status, headers),
711
+ }),
712
+ };
713
+ }
714
+
715
+ // 4. Provider fallback.
716
+ return {
717
+ ok: false,
718
+ error: options.unknownError({
719
+ status,
720
+ code: env.code,
721
+ message,
722
+ body: nonJson ? text : json,
723
+ headers,
724
+ }),
725
+ };
726
+ }
727
+
728
+ // A framed (streamed) body that a plain call collects: its frames are
729
+ // the output's `items`.
730
+ const collected = framing?.collect(text, headers["content-type"]);
731
+ return collected === undefined
732
+ ? decodeSuccess(context, headers, text, json, nonJson, outputAst)
733
+ : decodeSuccess(context, headers, text, collected.json, collected.nonJson, outputAst);
734
+ };
735
+
736
+ /**
737
+ * A 2xx body: the response body IS the payload (no envelope). Wire->TS
738
+ * key mapping is schema-driven; `RawResponseRoot` responses are the body
739
+ * verbatim (mapKeys handles arrays/scalars structurally either way).
740
+ * Strict mode (core/response-validation) checks the mapped body against
741
+ * the output schema -- a non-JSON body reaches it as a string and fails
742
+ * there unless the operation's output is itself a string. For an output
743
+ * with sensitive members, a non-JSON body fails in every mode and parse
744
+ * errors withhold the body.
745
+ */
746
+ const decodeSuccess = (
747
+ context: Context.Context<any>,
748
+ headers: Record<string, string | undefined>,
749
+ text: string,
750
+ json: unknown,
751
+ nonJson: boolean,
752
+ outputAst: AST.AST,
753
+ ): Decoded<ParseError> => {
754
+ const plan = decodePlanFor(outputAst);
755
+ let body: unknown = nonJson ? text : json === undefined ? (plan.text ? "" : {}) : json;
756
+ if (options.transformResponse) body = options.transformResponse(body);
757
+ const mapped =
758
+ plan.bodyMember !== undefined
759
+ ? { [plan.bodyMember.name]: mapKeys(plan.bodyMember.type, body, "decode") }
760
+ : plan.verbatim
761
+ ? body
762
+ : mapKeys(outputAst, body, "decode");
763
+ const checked = checkSuccess(context, outputAst, {
764
+ value: withResponseHeaders(plan.headers, mapped, headers),
765
+ body: nonJson ? text : json,
766
+ nonJson,
355
767
  });
768
+ return checked.ok ? checked : { ok: false, error: options.parseError(checked.error) };
769
+ };
356
770
 
357
- return Layer.succeed(
358
- API.Protocol,
359
- API.Protocol.of({
360
- // Erase encode's credentials requirement (resolved on the calling
361
- // fiber; see RestProtocolOptions.credentials).
362
- encode: (args) =>
363
- encode(args) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
364
- decode,
365
- }),
366
- );
771
+ const decodeResponse = (
772
+ context: Context.Context<any>,
773
+ response: HttpClientResponse.HttpClientResponse,
774
+ outputAst: AST.AST,
775
+ errorClasses: ReadonlyArray<DeclaredErrorClass>,
776
+ framing: StreamFraming | undefined,
777
+ ): Effect.Effect<unknown, Failure> =>
778
+ // A body read that fails (reset or abort mid-body) fails the call with
779
+ // its `HttpClientError`, a protocol error.
780
+ (response.status >= 200 && response.status < 300
781
+ ? readBinaryResponse(response, outputAst)
782
+ : undefined) ??
783
+ Effect.flatMap(response.text, (text) => {
784
+ recordPageHeaders(context, response.headers);
785
+ const decoded = decodeText(
786
+ context,
787
+ response.status,
788
+ response.headers as Record<string, string | undefined>,
789
+ text ?? "",
790
+ outputAst,
791
+ errorClasses,
792
+ framing,
793
+ );
794
+ return decoded.ok ? Effect.succeed(decoded.value) : Effect.fail(decoded.error);
795
+ });
796
+
797
+ /**
798
+ * Send `op`'s request on the calling fiber, then `receive` its response:
799
+ * decode it ({@link decodeCall}), or open it as a stream
800
+ * ({@link openFramed}).
801
+ */
802
+ const send = <A>(
803
+ op: Operation,
804
+ input: unknown,
805
+ receive: (
806
+ context: Context.Context<any>,
807
+ response: HttpClientResponse.HttpClientResponse,
808
+ ) => Effect.Effect<A, Failure>,
809
+ ): Effect.Effect<A, Failure, CredentialsRequirements> =>
810
+ Effect.withFiber((fiber) => {
811
+ const context = fiber.context as Context.Context<any>;
812
+ return withCredentials(context, (creds) => {
813
+ const client = Context.get(context, HttpClient.HttpClient);
814
+ return Effect.flatMap(requestFor(creds, input, op.inputAst), (request) =>
815
+ Effect.flatMap(Send.send(context, client, request), (response) =>
816
+ receive(context, response),
817
+ ),
818
+ );
819
+ });
820
+ });
821
+
822
+ /** A plain call's response, decoded. */
823
+ const decodeCall =
824
+ (op: Operation) =>
825
+ (context: Context.Context<any>, response: HttpClientResponse.HttpClientResponse) =>
826
+ decodeResponse(
827
+ context,
828
+ response,
829
+ op.outputAst,
830
+ op.errors,
831
+ op.config.framing as StreamFraming | undefined,
832
+ );
833
+
834
+ /**
835
+ * A streaming call's response: its body and a frame decoder. A failed
836
+ * status fails with the operation's typed error, as a plain call does.
837
+ */
838
+ const openFramed =
839
+ (op: Operation) =>
840
+ (
841
+ context: Context.Context<any>,
842
+ response: HttpClientResponse.HttpClientResponse,
843
+ ): Effect.Effect<FramedBody<Failure>, Failure> =>
844
+ response.status >= 400
845
+ ? Effect.flatMap(
846
+ decodeResponse(context, response, op.outputAst, op.errors, undefined),
847
+ // A failed status always decodes to a failure.
848
+ () =>
849
+ Effect.fail(
850
+ new SdkError({ message: `HTTP ${response.status} decoded as a success` }),
851
+ ),
852
+ )
853
+ : Effect.succeed({
854
+ body: response.stream,
855
+ item: (json, text) => {
856
+ const headers = response.headers as Record<string, string | undefined>;
857
+ // A frame schema of its own (an operation that streams only when
858
+ // its input asks), else one element of the output's `items`.
859
+ const itemAst = op.config.items?.ast;
860
+ if (itemAst !== undefined) {
861
+ const decoded = decodeSuccess(context, headers, text, json, false, itemAst);
862
+ return decoded.ok ? Effect.succeed(decoded.value) : Effect.fail(decoded.error);
863
+ }
864
+ const decoded = decodeSuccess(
865
+ context,
866
+ headers,
867
+ text,
868
+ { items: [json] },
869
+ false,
870
+ op.outputAst,
871
+ );
872
+ return decoded.ok
873
+ ? Effect.succeed(
874
+ (decoded.value as { readonly items: ReadonlyArray<unknown> }).items[0],
875
+ )
876
+ : Effect.fail(decoded.error);
877
+ },
878
+ invalid: (text) =>
879
+ options.parseError({
880
+ body: hasSensitiveMember(op.outputAst) ? "[REDACTED]" : text,
881
+ cause: "Invalid JSON frame",
882
+ }),
883
+ });
884
+
885
+ return {
886
+ // The credentials are resolved on the calling fiber (see
887
+ // RestProtocolOptions.credentials).
888
+ encode: ({ input, inputAst }: EncodeArgs) =>
889
+ Effect.withFiber((fiber) =>
890
+ withCredentials(fiber.context as Context.Context<any>, (creds) =>
891
+ requestFor(creds, input, inputAst),
892
+ ),
893
+ ),
894
+ decode: ({ response, outputAst, errors, config }: DecodeArgs) =>
895
+ Effect.withFiber((fiber) =>
896
+ decodeResponse(
897
+ fiber.context as Context.Context<any>,
898
+ response,
899
+ outputAst,
900
+ errors,
901
+ config.framing as StreamFraming | undefined,
902
+ ),
903
+ ),
904
+ call: (op, input) => send(op, input, decodeCall(op)),
905
+ stream: (op, input) => {
906
+ const framing = op.config.framing as StreamFraming | undefined;
907
+ return framing === undefined
908
+ ? API.cannotStream(op)
909
+ : framing.stream(send(op, input, openFramed(op)));
910
+ },
911
+ };
367
912
  };
913
+
914
+ /**
915
+ * {@link restProtocol}'s options for one form of `credentials`. The service
916
+ * key and the effect are separate signatures: a key is also an effect (of
917
+ * the service), so one signature for both could not tell which it is given.
918
+ */
919
+ type TypedRestOptions<
920
+ CredentialsSource,
921
+ Credentials,
922
+ RouteError,
923
+ ClassifiedError,
924
+ UnknownError,
925
+ ParseError,
926
+ > = Omit<
927
+ RestProtocolOptions<
928
+ Credentials,
929
+ never,
930
+ never,
931
+ RouteError,
932
+ ClassifiedError,
933
+ UnknownError,
934
+ ParseError
935
+ >,
936
+ "credentials"
937
+ > & {
938
+ /** See {@link RestProtocolOptions.credentials}. */
939
+ readonly credentials: CredentialsSource;
940
+ };
941
+
942
+ /**
943
+ * The protocol for a simple REST JSON API (core/protocol). Assign the
944
+ * result to a module-level const in the provider's `protocol.ts`:
945
+ *
946
+ * export const NeonProtocol = restProtocol({ ... });
947
+ *
948
+ * A failed response becomes, in this order: what `classifyError` returns, a
949
+ * class the operation or its service declares (by its matchers, or by status
950
+ * for one of core's status classes), `InternalServerError` for any other
951
+ * 5xx, and `unknownError` for the rest. The protocol declares what the
952
+ * options and {@link RestProtocolError} fail with: the result's type lists
953
+ * them, so no SDK writes that list by hand.
954
+ */
955
+ export function restProtocol<
956
+ Credentials,
957
+ CredentialsError = never,
958
+ CredentialsRequirements = never,
959
+ RouteError = never,
960
+ ClassifiedError = never,
961
+ UnknownError = never,
962
+ ParseError = never,
963
+ >(
964
+ options: TypedRestOptions<
965
+ Context.Key<CredentialsRequirements, Effect.Effect<Credentials, CredentialsError>>,
966
+ Credentials,
967
+ RouteError,
968
+ ClassifiedError,
969
+ UnknownError,
970
+ ParseError
971
+ >,
972
+ ): Protocol<
973
+ CredentialsError | RouteError | ClassifiedError | UnknownError | ParseError | RestProtocolError,
974
+ CredentialsRequirements
975
+ >;
976
+ export function restProtocol<
977
+ Credentials,
978
+ CredentialsError = never,
979
+ CredentialsRequirements = never,
980
+ RouteError = never,
981
+ ClassifiedError = never,
982
+ UnknownError = never,
983
+ ParseError = never,
984
+ >(
985
+ options: TypedRestOptions<
986
+ Effect.Effect<Credentials, CredentialsError, CredentialsRequirements>,
987
+ Credentials,
988
+ RouteError,
989
+ ClassifiedError,
990
+ UnknownError,
991
+ ParseError
992
+ >,
993
+ ): Protocol<
994
+ CredentialsError | RouteError | ClassifiedError | UnknownError | ParseError | RestProtocolError,
995
+ CredentialsRequirements
996
+ >;
997
+ export function restProtocol<
998
+ Credentials,
999
+ CredentialsError,
1000
+ CredentialsRequirements,
1001
+ RouteError,
1002
+ ClassifiedError,
1003
+ UnknownError,
1004
+ ParseError,
1005
+ >(
1006
+ options: RestProtocolOptions<
1007
+ Credentials,
1008
+ CredentialsError,
1009
+ CredentialsRequirements,
1010
+ RouteError,
1011
+ ClassifiedError,
1012
+ UnknownError,
1013
+ ParseError
1014
+ >,
1015
+ ): Protocol<
1016
+ CredentialsError | RouteError | ClassifiedError | UnknownError | ParseError | RestProtocolError,
1017
+ CredentialsRequirements
1018
+ > {
1019
+ return restProtocolMethods(options);
1020
+ }