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

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 (291) hide show
  1. package/LICENSE +201 -0
  2. package/lib/_bundle/aws.js +2 -0
  3. package/lib/_bundle/aws.js.map +1 -0
  4. package/lib/_bundle/base.js +5 -0
  5. package/lib/_bundle/base.js.map +1 -0
  6. package/lib/_bundle/graphql.js +3 -0
  7. package/lib/_bundle/graphql.js.map +1 -0
  8. package/lib/_bundle/grpc.js +2 -0
  9. package/lib/_bundle/grpc.js.map +1 -0
  10. package/lib/_bundle/rest.js +2 -0
  11. package/lib/_bundle/rest.js.map +1 -0
  12. package/lib/_bundle/xml.js +4 -0
  13. package/lib/_bundle/xml.js.map +1 -0
  14. package/lib/annotations.d.ts +17 -0
  15. package/lib/annotations.d.ts.map +1 -0
  16. package/lib/annotations.js +2 -0
  17. package/lib/annotations.js.map +1 -0
  18. package/lib/api.d.ts +174 -18
  19. package/lib/api.d.ts.map +1 -1
  20. package/lib/api.js +1 -178
  21. package/lib/category.d.ts +4 -4
  22. package/lib/category.d.ts.map +1 -1
  23. package/lib/category.js +1 -280
  24. package/lib/chunks.d.ts +3 -0
  25. package/lib/chunks.d.ts.map +1 -0
  26. package/lib/chunks.js +1 -0
  27. package/lib/config.d.ts +68 -0
  28. package/lib/config.d.ts.map +1 -0
  29. package/lib/config.js +1 -0
  30. package/lib/crypto.d.ts +76 -0
  31. package/lib/crypto.d.ts.map +1 -0
  32. package/lib/crypto.js +1 -0
  33. package/lib/error-category.d.ts +1 -1
  34. package/lib/error-category.d.ts.map +1 -1
  35. package/lib/error-category.js +1 -46
  36. package/lib/errors.d.ts +64 -72
  37. package/lib/errors.d.ts.map +1 -1
  38. package/lib/errors.js +1 -186
  39. package/lib/graphql.d.ts +403 -0
  40. package/lib/graphql.d.ts.map +1 -0
  41. package/lib/graphql.js +1 -0
  42. package/lib/graphql.types.d.ts +12 -0
  43. package/lib/graphql.types.d.ts.map +1 -0
  44. package/lib/graphql.types.js +1 -0
  45. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  46. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  47. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  48. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  49. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  50. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  51. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  52. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  53. package/lib/grpc-transport-node-http2.d.ts +19 -0
  54. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  55. package/lib/grpc-transport-node-http2.js +2 -0
  56. package/lib/grpc-transport-node-http2.js.map +1 -0
  57. package/lib/grpc-transport.d.ts +76 -0
  58. package/lib/grpc-transport.d.ts.map +1 -0
  59. package/lib/grpc-transport.js +1 -0
  60. package/lib/hpack.d.ts +34 -0
  61. package/lib/hpack.d.ts.map +1 -0
  62. package/lib/hpack.js +2 -0
  63. package/lib/hpack.js.map +1 -0
  64. package/lib/index.d.ts +32 -0
  65. package/lib/index.d.ts.map +1 -0
  66. package/lib/index.js +17 -0
  67. package/lib/pagination.d.ts +101 -24
  68. package/lib/pagination.d.ts.map +1 -1
  69. package/lib/pagination.js +1 -182
  70. package/lib/plain-values.d.ts +10 -0
  71. package/lib/plain-values.d.ts.map +1 -0
  72. package/lib/plain-values.js +2 -0
  73. package/lib/plain-values.js.map +1 -0
  74. package/lib/protobuf.d.ts +92 -0
  75. package/lib/protobuf.d.ts.map +1 -0
  76. package/lib/protobuf.js +1 -0
  77. package/lib/protocol-grpc.d.ts +86 -0
  78. package/lib/protocol-grpc.d.ts.map +1 -0
  79. package/lib/protocol-grpc.js +1 -0
  80. package/lib/protocol-http.d.ts +102 -23
  81. package/lib/protocol-http.d.ts.map +1 -1
  82. package/lib/protocol-http.js +1 -554
  83. package/lib/protocol-rest.d.ts +120 -50
  84. package/lib/protocol-rest.d.ts.map +1 -1
  85. package/lib/protocol-rest.js +1 -242
  86. package/lib/query.d.ts +29 -0
  87. package/lib/query.d.ts.map +1 -0
  88. package/lib/query.js +1 -0
  89. package/lib/response-validation-strict.d.ts +48 -0
  90. package/lib/response-validation-strict.d.ts.map +1 -0
  91. package/lib/response-validation-strict.js +1 -0
  92. package/lib/response-validation.d.ts +86 -0
  93. package/lib/response-validation.d.ts.map +1 -0
  94. package/lib/response-validation.js +1 -0
  95. package/lib/retry-after.d.ts +3 -3
  96. package/lib/retry-after.d.ts.map +1 -1
  97. package/lib/retry-after.js +1 -112
  98. package/lib/retry.d.ts +48 -29
  99. package/lib/retry.d.ts.map +1 -1
  100. package/lib/retry.js +1 -210
  101. package/lib/schema-lite-impl.d.ts +158 -0
  102. package/lib/schema-lite-impl.d.ts.map +1 -0
  103. package/lib/schema-lite-impl.js +1 -0
  104. package/lib/schema-lite-typed.d.ts +41 -0
  105. package/lib/schema-lite-typed.d.ts.map +1 -0
  106. package/lib/schema-lite-typed.js +1 -0
  107. package/lib/schema-lite.d.ts +40 -0
  108. package/lib/schema-lite.d.ts.map +1 -0
  109. package/lib/schema-lite.js +1 -0
  110. package/lib/schema.d.ts +21 -7
  111. package/lib/schema.d.ts.map +1 -1
  112. package/lib/schema.js +1 -48
  113. package/lib/sdk-error.d.ts +27 -0
  114. package/lib/sdk-error.d.ts.map +1 -0
  115. package/lib/sdk-error.js +1 -0
  116. package/lib/sensitive.d.ts +28 -0
  117. package/lib/sensitive.d.ts.map +1 -0
  118. package/lib/sensitive.js +2 -0
  119. package/lib/sensitive.js.map +1 -0
  120. package/lib/telemetry-debug.d.ts +6 -0
  121. package/lib/telemetry-debug.d.ts.map +1 -0
  122. package/lib/telemetry-debug.js +2 -0
  123. package/lib/telemetry-debug.js.map +1 -0
  124. package/lib/telemetry-hooks.d.ts +32 -0
  125. package/lib/telemetry-hooks.d.ts.map +1 -0
  126. package/lib/telemetry-hooks.js +2 -0
  127. package/lib/telemetry-hooks.js.map +1 -0
  128. package/lib/telemetry-host-rules.d.ts +23 -0
  129. package/lib/telemetry-host-rules.d.ts.map +1 -0
  130. package/lib/telemetry-host-rules.js +2 -0
  131. package/lib/telemetry-host-rules.js.map +1 -0
  132. package/lib/telemetry-lambda-context.d.ts +17 -0
  133. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  134. package/lib/telemetry-lambda-context.js +2 -0
  135. package/lib/telemetry-lambda-context.js.map +1 -0
  136. package/lib/telemetry-message-context.d.ts +52 -0
  137. package/lib/telemetry-message-context.d.ts.map +1 -0
  138. package/lib/telemetry-message-context.js +2 -0
  139. package/lib/telemetry-message-context.js.map +1 -0
  140. package/lib/telemetry-metrics.d.ts +6 -0
  141. package/lib/telemetry-metrics.d.ts.map +1 -0
  142. package/lib/telemetry-metrics.js +2 -0
  143. package/lib/telemetry-metrics.js.map +1 -0
  144. package/lib/telemetry-name-template.d.ts +13 -0
  145. package/lib/telemetry-name-template.d.ts.map +1 -0
  146. package/lib/telemetry-name-template.js +2 -0
  147. package/lib/telemetry-name-template.js.map +1 -0
  148. package/lib/telemetry-stream.d.ts +11 -0
  149. package/lib/telemetry-stream.d.ts.map +1 -0
  150. package/lib/telemetry-stream.js +2 -0
  151. package/lib/telemetry-stream.js.map +1 -0
  152. package/lib/telemetry-xray.d.ts +28 -0
  153. package/lib/telemetry-xray.d.ts.map +1 -0
  154. package/lib/telemetry-xray.js +2 -0
  155. package/lib/telemetry-xray.js.map +1 -0
  156. package/lib/telemetry.d.ts +288 -0
  157. package/lib/telemetry.d.ts.map +1 -0
  158. package/lib/telemetry.js +3 -0
  159. package/lib/telemetry.js.map +1 -0
  160. package/lib/trait.d.ts +71 -20
  161. package/lib/trait.d.ts.map +1 -1
  162. package/lib/trait.js +1 -107
  163. package/lib/unknown-error.d.ts +18 -0
  164. package/lib/unknown-error.d.ts.map +1 -0
  165. package/lib/unknown-error.js +1 -0
  166. package/lib/xml.d.ts +44 -0
  167. package/lib/xml.d.ts.map +1 -0
  168. package/lib/xml.js +1 -0
  169. package/package.json +13 -13
  170. package/src/annotations.ts +53 -0
  171. package/src/api.ts +1370 -200
  172. package/src/category.ts +76 -106
  173. package/src/chunks.ts +30 -0
  174. package/src/config.ts +245 -0
  175. package/src/crypto.ts +202 -0
  176. package/src/error-category.ts +16 -29
  177. package/src/errors.ts +75 -75
  178. package/src/graphql.ts +1778 -0
  179. package/src/graphql.types.ts +105 -0
  180. package/src/grpc-transport-cloudflare-http2.ts +494 -0
  181. package/src/grpc-transport-cloudflare-sockets.ts +299 -0
  182. package/src/grpc-transport-node-http2.ts +234 -0
  183. package/src/grpc-transport.ts +118 -0
  184. package/src/hpack.ts +331 -0
  185. package/src/index.ts +31 -0
  186. package/src/pagination.ts +368 -94
  187. package/src/plain-values.ts +41 -0
  188. package/src/protobuf.ts +1332 -0
  189. package/src/protocol-grpc.ts +641 -0
  190. package/src/protocol-http.ts +622 -322
  191. package/src/protocol-rest.ts +440 -227
  192. package/src/query.ts +39 -0
  193. package/src/response-validation-strict.ts +327 -0
  194. package/src/response-validation.ts +161 -0
  195. package/src/retry-after.ts +7 -13
  196. package/src/retry.ts +96 -110
  197. package/src/schema-lite-impl.ts +550 -0
  198. package/src/schema-lite-typed.ts +44 -0
  199. package/src/schema-lite.ts +44 -0
  200. package/src/schema.ts +259 -15
  201. package/src/sdk-error.ts +33 -0
  202. package/src/sensitive.ts +154 -0
  203. package/src/telemetry-debug.ts +179 -0
  204. package/src/telemetry-hooks.ts +33 -0
  205. package/src/telemetry-host-rules.ts +39 -0
  206. package/src/telemetry-lambda-context.ts +46 -0
  207. package/src/telemetry-message-context.ts +170 -0
  208. package/src/telemetry-metrics.ts +69 -0
  209. package/src/telemetry-name-template.ts +26 -0
  210. package/src/telemetry-stream.ts +100 -0
  211. package/src/telemetry-xray.ts +66 -0
  212. package/src/telemetry.ts +832 -0
  213. package/src/trait.ts +106 -67
  214. package/src/unknown-error.ts +38 -0
  215. package/src/xml.ts +346 -0
  216. package/lib/api.js.map +0 -1
  217. package/lib/category.js.map +0 -1
  218. package/lib/codegen/cli.d.ts +0 -29
  219. package/lib/codegen/cli.d.ts.map +0 -1
  220. package/lib/codegen/cli.js +0 -165
  221. package/lib/codegen/cli.js.map +0 -1
  222. package/lib/codegen/emit.d.ts +0 -129
  223. package/lib/codegen/emit.d.ts.map +0 -1
  224. package/lib/codegen/emit.js +0 -105
  225. package/lib/codegen/emit.js.map +0 -1
  226. package/lib/codegen/format.d.ts +0 -23
  227. package/lib/codegen/format.d.ts.map +0 -1
  228. package/lib/codegen/format.js +0 -28
  229. package/lib/codegen/format.js.map +0 -1
  230. package/lib/codegen/generator.d.ts +0 -334
  231. package/lib/codegen/generator.d.ts.map +0 -1
  232. package/lib/codegen/generator.js +0 -691
  233. package/lib/codegen/generator.js.map +0 -1
  234. package/lib/codegen/graph.d.ts +0 -36
  235. package/lib/codegen/graph.d.ts.map +0 -1
  236. package/lib/codegen/graph.js +0 -136
  237. package/lib/codegen/graph.js.map +0 -1
  238. package/lib/codegen/members.d.ts +0 -25
  239. package/lib/codegen/members.d.ts.map +0 -1
  240. package/lib/codegen/members.js +0 -55
  241. package/lib/codegen/members.js.map +0 -1
  242. package/lib/codegen/naming.d.ts +0 -29
  243. package/lib/codegen/naming.d.ts.map +0 -1
  244. package/lib/codegen/naming.js +0 -74
  245. package/lib/codegen/naming.js.map +0 -1
  246. package/lib/codegen/openapi-cli.d.ts +0 -38
  247. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  248. package/lib/codegen/openapi-cli.js +0 -107
  249. package/lib/codegen/openapi-cli.js.map +0 -1
  250. package/lib/codegen/openapi.d.ts +0 -115
  251. package/lib/codegen/openapi.d.ts.map +0 -1
  252. package/lib/codegen/openapi.js +0 -1220
  253. package/lib/codegen/openapi.js.map +0 -1
  254. package/lib/codegen/operations.d.ts +0 -24
  255. package/lib/codegen/operations.d.ts.map +0 -1
  256. package/lib/codegen/operations.js +0 -56
  257. package/lib/codegen/operations.js.map +0 -1
  258. package/lib/codegen/pagination.d.ts +0 -39
  259. package/lib/codegen/pagination.d.ts.map +0 -1
  260. package/lib/codegen/pagination.js +0 -33
  261. package/lib/codegen/pagination.js.map +0 -1
  262. package/lib/codegen/prelude.d.ts +0 -15
  263. package/lib/codegen/prelude.d.ts.map +0 -1
  264. package/lib/codegen/prelude.js +0 -60
  265. package/lib/codegen/prelude.js.map +0 -1
  266. package/lib/error-category.js.map +0 -1
  267. package/lib/errors.js.map +0 -1
  268. package/lib/json-patch.d.ts +0 -44
  269. package/lib/json-patch.d.ts.map +0 -1
  270. package/lib/json-patch.js +0 -174
  271. package/lib/json-patch.js.map +0 -1
  272. package/lib/pagination.js.map +0 -1
  273. package/lib/protocol-http.js.map +0 -1
  274. package/lib/protocol-rest.js.map +0 -1
  275. package/lib/retry-after.js.map +0 -1
  276. package/lib/retry.js.map +0 -1
  277. package/lib/schema.js.map +0 -1
  278. package/lib/trait.js.map +0 -1
  279. package/src/codegen/cli.ts +0 -268
  280. package/src/codegen/emit.ts +0 -207
  281. package/src/codegen/format.ts +0 -47
  282. package/src/codegen/generator.ts +0 -1153
  283. package/src/codegen/graph.ts +0 -151
  284. package/src/codegen/members.ts +0 -71
  285. package/src/codegen/naming.ts +0 -86
  286. package/src/codegen/openapi-cli.ts +0 -166
  287. package/src/codegen/openapi.ts +0 -1450
  288. package/src/codegen/operations.ts +0 -76
  289. package/src/codegen/pagination.ts +0 -71
  290. package/src/codegen/prelude.ts +0 -70
  291. package/src/json-patch.ts +0 -222
@@ -1,157 +1,115 @@
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 HttpClientRequest from "effect/http/HttpClientRequest";
5
+ import type * as HttpClientResponse from "effect/http/HttpClientResponse";
6
+ import * as Layer from "effect/Layer";
7
+ import type * as AST from "effect/SchemaAST";
8
+ import { rawResponseRootSymbol, resolveNode } from "./annotations.ts";
9
+ import * as API from "./api.ts";
10
+ import { HTTP_STATUS_MAP, InternalServerError } from "./errors.ts";
11
+ import { recordPageHeaders } from "./pagination.ts";
12
+ import { unwrapRedactedDeep } from "./plain-values.ts";
13
+ import {
14
+ buildRequest,
15
+ getAnn,
16
+ getProps,
17
+ hasPropAnn,
18
+ mapKeys,
19
+ mapsVerbatim,
20
+ matchTypedError,
21
+ responseHeaderMembers,
22
+ withResponseHeaders,
23
+ type ResponseHeaderMember,
24
+ } from "./protocol-http.ts";
25
+ import { checkResponse, withholdActual } from "./response-validation.ts";
26
+ import { parseRetryAfterForStatus } from "./retry-after.ts";
27
+ import { holdsSensitive, sensitiveValueSymbol, wrapSensitive } from "./sensitive.ts";
1
28
  /**
2
29
  * Generic REST protocol factory for simple bearer/header-auth JSON APIs
3
- * (Neon, Fly.io, PlanetScale, Supabase, Turso, …).
30
+ * (Neon, Fly.io, PlanetScale, Supabase, Turso, ...).
4
31
  *
5
32
  * `makeRestProtocol(options)` builds a core {@link API.Protocol} layer:
6
33
  *
7
34
  * request: credentials resolved from the CALLING fiber's context on every
8
- * request (the layer itself is memoized per process — see
35
+ * request (the layer itself is memoized per process -- see
9
36
  * `core/api`), auth headers + base URL from the provider's
10
37
  * options, request built by `buildRequest` from
11
38
  * `core/protocol-http` (deep-unwrapping any `Redacted` input
12
39
  * values first)
13
40
  *
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
41
+ * response: 2xx JSON -> optional `transformResponse` -> recursive wire->TS
42
+ * key mapping (`mapKeys`) -> in strict mode, a schema check
43
+ * failing with the provider's `parseError` (see
44
+ * `core/response-validation`) -> `Redacted` wrapping of members
45
+ * marked with {@link SensitiveValue}; non-2xx -> typed error:
46
+ * the provider's `classifyError`, then per-op matcher
47
+ * classes (`matchTypedError`), then the status
18
48
  * map (default `HTTP_STATUS_MAP`), then an `InternalServerError`
19
49
  * for unmapped 5xx, then the provider's `unknownError` fallback
20
- * — with `retryAfter` durations stamped from the standard hint
50
+ * -- with `retryAfter` durations stamped from the standard hint
21
51
  * headers on retryable statuses.
22
52
  *
23
53
  * Anything provider-specific (envelope quirks, bespoke error codes) belongs
24
- * in the provider package — via these options or a hand-written protocol.
54
+ * in the provider package -- via these options or a hand-written protocol.
25
55
  */
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";
56
+ import * as Telemetry from "./telemetry.ts";
57
+ import { httpSymbol, makeAnnotation, type HttpTrait } from "./trait.ts";
58
+ import type { UnknownErrorProps } from "./unknown-error.ts";
45
59
 
46
60
  // =============================================================================
47
61
  // Traits
48
62
  // =============================================================================
49
63
 
50
- export const sensitiveValueSymbol = Symbol.for(
51
- "@distilled.cloud/core/sensitive-value",
52
- );
64
+ export { sensitiveValueSymbol };
53
65
  /**
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
66
+ * Marks a string member, map value or list element as sensitive (mirrors
67
+ * `smithy.api#sensitive`). The REST protocol wraps decoded values in
68
+ * `Redacted` on the way out (an untyped `S.Unknown` value whole) and
56
69
  * accepts `string | Redacted<string>` on the way in (unwrapped before
57
70
  * serialization). Takes an ignored argument so generators can inline the
58
71
  * smithy trait value (`T.SensitiveValue({})`).
59
72
  */
60
- export const SensitiveValue = (_value?: unknown) =>
61
- makeAnnotation(sensitiveValueSymbol, true);
73
+ export const SensitiveValue = (_value?: unknown) => makeAnnotation(sensitiveValueSymbol, true);
62
74
 
63
- export const rawResponseSymbol = Symbol.for(
64
- "@distilled.cloud/core/raw-response",
65
- );
75
+ export const rawResponseSymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/raw-response");
66
76
  /**
67
77
  * Marks the sole output member that carries a bare (array/scalar) response
68
78
  * body (mirrors `com.distilled.openapi#rawResponse`).
69
79
  */
70
- export const RawResponse = (_value?: unknown) =>
71
- makeAnnotation(rawResponseSymbol, true);
80
+ export const RawResponse = (_value?: unknown) => makeAnnotation(rawResponseSymbol, true);
72
81
 
73
- export const rawResponseRootSymbol = Symbol.for(
74
- "@distilled.cloud/core/raw-response-root",
75
- );
76
82
  /**
77
83
  * Marks a response schema whose ENTIRE value is the response body (the
78
84
  * generator's `rootPipe` for synthesized bare-payload wrappers): the emitted
79
85
  * response type IS the payload type and the protocol returns the mapped body
80
86
  * directly.
81
87
  */
82
- export const RawResponseRoot = () =>
83
- makeAnnotation(rawResponseRootSymbol, true);
88
+ export { rawResponseRootSymbol };
89
+ export const RawResponseRoot = () => makeAnnotation(rawResponseRootSymbol, true);
90
+
91
+ export const binaryResponseSymbol = /*@__PURE__*/ Symbol.for(
92
+ "@distilled.cloud/core/binary-response",
93
+ );
94
+
95
+ /** Decode a successful raw binary response as bytes, without text conversion. */
96
+ export const BinaryResponse = () => makeAnnotation(binaryResponseSymbol, true);
84
97
 
85
98
  // =============================================================================
86
99
  // Value helpers
87
100
  // =============================================================================
88
101
 
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);
102
+ export { unwrapRedactedDeep };
96
103
 
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
- };
104
+ export { wrapSensitive };
116
105
 
117
106
  /**
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.
107
+ * Whether any member, map value or list element reachable from `ast` is
108
+ * marked {@link SensitiveValue}. Such an output is decoded through
109
+ * {@link wrapSensitive}, and its parse errors withhold the response body (see
110
+ * {@link checkSuccess}, which every REST-style protocol's success path uses).
121
111
  */
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
- };
112
+ export const hasSensitiveMember: (ast: AST.AST) => boolean = holdsSensitive;
155
113
 
156
114
  // =============================================================================
157
115
  // Protocol factory
@@ -168,6 +126,28 @@ export interface RestErrorInfo {
168
126
  readonly headers: Record<string, string | undefined>;
169
127
  }
170
128
 
129
+ /**
130
+ * The core {@link UnknownErrorProps} of a failure, for an SDK's
131
+ * `unknownError`: `new UnknownNeonError(unknownErrorProps(info))`. A number
132
+ * code becomes its string.
133
+ */
134
+ export const unknownErrorProps = (info: RestErrorInfo): UnknownErrorProps => ({
135
+ status: info.status,
136
+ code: info.code === undefined ? undefined : String(info.code),
137
+ message: info.message,
138
+ body: info.body,
139
+ });
140
+
141
+ /**
142
+ * A 2xx body that failed strict validation, or a non-JSON 2xx body for an
143
+ * output with sensitive members, for the `parseError` option.
144
+ */
145
+ export interface RestParseErrorInfo {
146
+ /** `"[REDACTED]"` when the output has sensitive members. */
147
+ readonly body: unknown;
148
+ readonly cause: unknown;
149
+ }
150
+
171
151
  export interface RestErrorEnvelope {
172
152
  readonly code?: string | number;
173
153
  readonly message?: string;
@@ -175,18 +155,30 @@ export interface RestErrorEnvelope {
175
155
 
176
156
  export interface RestProtocolOptions<C> {
177
157
  /**
178
- * Resolve credentials ON THE CALLING FIBER — evaluated per request, never
158
+ * Resolve credentials ON THE CALLING FIBER -- evaluated per request, never
179
159
  * 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
160
+ * are picked up. Either an effect, or -- for the distilled
161
+ * credentials-service convention -- the `Credentials` service key whose
162
+ * value is that effect (read from the calling fiber's context; an
163
+ * already-resolved `Effect.succeed` value costs no extra fiber step). Its
164
+ * error/requirement channels are
183
165
  * erased at the protocol boundary (Protocol effects carry none) and
184
166
  * reintroduced for callers by the generated `<Sdk>OpError` /
185
167
  * `<Sdk>OpContext` annotations.
186
168
  */
187
- readonly credentials: Effect.Effect<C, any, any>;
188
- /** API base URL from the resolved credentials. */
189
- readonly baseUrl: (credentials: C) => string;
169
+ readonly credentials: Effect.Effect<C, any, any> | Context.Key<any, Effect.Effect<C, any, any>>;
170
+ /**
171
+ * API base URL from the resolved credentials. Receives the operation's
172
+ * route so APIs with more than one endpoint (e.g. S2's account vs
173
+ * per-basin hosts, chosen by path) can route per request; single-endpoint
174
+ * providers ignore the argument. A THROWN error (e.g. a required scope
175
+ * missing from the credentials) is caught and surfaced on the calling
176
+ * effect's error channel rather than dying as a defect.
177
+ */
178
+ readonly baseUrl: (
179
+ credentials: C,
180
+ target: { readonly uri: string; readonly method: string },
181
+ ) => string;
190
182
  /** Auth (and any fixed) headers from the resolved credentials. */
191
183
  readonly headers: (credentials: C) => Record<string, string>;
192
184
  /**
@@ -196,35 +188,52 @@ export interface RestProtocolOptions<C> {
196
188
  */
197
189
  readonly errorEnvelope?: (body: unknown) => RestErrorEnvelope | undefined;
198
190
  /**
199
- * HTTP status → error class constructed as `new Cls({ message, retryAfter
191
+ * HTTP status -> error class constructed as `new Cls({ message, retryAfter
200
192
  * })`. Default: core `HTTP_STATUS_MAP`. Consulted after per-op typed error
201
193
  * matching; unmapped 5xx fall back to `InternalServerError`, everything
202
194
  * else to {@link unknownError}.
203
195
  */
204
196
  readonly statusMap?: Readonly<Record<number, new (args: any) => any>>;
205
- /** Fallback error for failures nothing else matched. */
197
+ /**
198
+ * The provider's own reading of a failure, consulted before per-op typed
199
+ * matching and the status map: return the error to fail with, or
200
+ * `undefined` to decode the failure as usual. For rules a status alone
201
+ * can't express, e.g. a 403 that is a rate limit because of its headers.
202
+ */
203
+ readonly classifyError?: (info: RestErrorInfo) => unknown;
204
+ /**
205
+ * Fallback error for failures nothing else matched: the SDK's
206
+ * `Unknown<Sdk>Error`, built from {@link unknownErrorProps}. Only non-5xx
207
+ * statuses reach it (unmapped 5xx are `InternalServerError`), so the class
208
+ * carries no retryable category.
209
+ */
206
210
  readonly unknownError: (info: RestErrorInfo) => unknown;
211
+ /**
212
+ * The SDK's `<Sdk>ParseError`, raised when a 2xx body does not match the
213
+ * operation's output schema in strict mode (see
214
+ * `core/response-validation`), and in every mode when a 2xx body for an
215
+ * output with sensitive members is not JSON. `body` is the parsed JSON, or
216
+ * the raw text when the body wasn't JSON, and `"[REDACTED]"` for an output
217
+ * with sensitive members; `cause` is the schema error, or `"Invalid JSON
218
+ * response"`.
219
+ */
220
+ readonly parseError: (info: RestParseErrorInfo) => unknown;
207
221
  /** Transform the parsed 2xx JSON before decoding (e.g. stripNulls). */
208
222
  readonly transformResponse?: (body: unknown) => unknown;
209
223
  /** Passed through to `buildRequest` (member-header transforms). */
210
224
  readonly mapMemberHeader?: (name: string, value: string) => string;
211
225
  /** Passed through to `buildRequest` (wire names for unmodeled input keys). */
212
226
  readonly unknownKeyToWire?: (key: string) => string;
227
+ /** Passed through to `buildRequest`: send `{}` when a bodied call has no body members. */
228
+ readonly emptyJsonBody?: boolean;
213
229
  }
214
230
 
215
231
  const defaultErrorEnvelope = (body: unknown): RestErrorEnvelope | undefined => {
216
232
  if (body === null || typeof body !== "object") return undefined;
217
233
  const b = body as Record<string, unknown>;
218
- const code =
219
- typeof b.code === "string" || typeof b.code === "number"
220
- ? b.code
221
- : undefined;
234
+ const code = typeof b.code === "string" || typeof b.code === "number" ? b.code : undefined;
222
235
  const message =
223
- typeof b.message === "string"
224
- ? b.message
225
- : typeof b.error === "string"
226
- ? b.error
227
- : undefined;
236
+ typeof b.message === "string" ? b.message : typeof b.error === "string" ? b.error : undefined;
228
237
  return { code, message };
229
238
  };
230
239
 
@@ -232,136 +241,340 @@ const defaultErrorEnvelope = (body: unknown): RestErrorEnvelope | undefined => {
232
241
  // but REST failures are real typed errors that operations re-surface via
233
242
  // their `errors: [...]` lists. Fail with the instance and erase the type
234
243
  // 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>;
244
+ const fail = (e: unknown): Effect.Effect<never> => Effect.fail(e) as Effect.Effect<never>;
245
+
246
+ // =============================================================================
247
+ // 2xx bodies
248
+ // =============================================================================
249
+
250
+ /** A 2xx body a protocol read, for {@link checkSuccess}. */
251
+ export interface SuccessBody {
252
+ /** The value to check and return: the body mapped onto the output's TS names. */
253
+ readonly value: unknown;
254
+ /** What a parse error reports as `body` for an output without sensitive members. */
255
+ readonly body: unknown;
256
+ /** Whether the body was not JSON. */
257
+ readonly nonJson: boolean;
258
+ }
259
+
260
+ /** The outcome of {@link checkSuccess}: the value, or the parse error's fields. */
261
+ export type SuccessCheck =
262
+ | { readonly ok: true; readonly value: unknown }
263
+ | { readonly ok: false; readonly error: RestParseErrorInfo };
264
+
265
+ /**
266
+ * Check a 2xx body against the operation's output schema and deliver its
267
+ * sensitive values as `Redacted`. Every REST-style protocol ends its success
268
+ * path here, so all of them treat a body that can hold a secret alike:
269
+ *
270
+ * - The checked value comes back through {@link wrapSensitive}.
271
+ * - A mismatch (validating modes, see `core/response-validation`) reports
272
+ * `read.body` and the schema error.
273
+ * - For an output with sensitive members ({@link hasSensitiveMember}), a
274
+ * non-JSON body fails in every mode with `"Invalid JSON response"`, and a
275
+ * mismatch reports `body: "[REDACTED]"` and the schema error without the
276
+ * value it found (`withholdActual`).
277
+ *
278
+ * Synchronous, for protocols that already hold the calling fiber's context;
279
+ * {@link validateSuccess} is the `Effect` form.
280
+ */
281
+ export const checkSuccess = (
282
+ context: Context.Context<any>,
283
+ outputAst: AST.AST,
284
+ read: SuccessBody,
285
+ ): SuccessCheck => {
286
+ const sensitive = hasSensitiveMember(outputAst);
287
+ if (read.nonJson && sensitive) {
288
+ return { ok: false, error: { body: "[REDACTED]", cause: "Invalid JSON response" } };
289
+ }
290
+ const invalid = checkResponse(context, outputAst, read.value);
291
+ if (invalid !== undefined) {
292
+ return {
293
+ ok: false,
294
+ error: sensitive
295
+ ? { body: "[REDACTED]", cause: withholdActual(invalid) }
296
+ : { body: read.body, cause: invalid },
297
+ };
298
+ }
299
+ return { ok: true, value: sensitive ? wrapSensitive(outputAst, read.value) : read.value };
300
+ };
301
+
302
+ /**
303
+ * {@link checkSuccess} on the calling fiber, failing with `parseError` (the
304
+ * SDK's `<Sdk>ParseError`) built from the withheld-or-not fields.
305
+ */
306
+ export const validateSuccess = <E>(
307
+ outputAst: AST.AST,
308
+ read: SuccessBody,
309
+ parseError: (info: RestParseErrorInfo) => E,
310
+ ): Effect.Effect<unknown, E> =>
311
+ Effect.withFiber((fiber) => {
312
+ const checked = checkSuccess(fiber.context as Context.Context<any>, outputAst, read);
313
+ return checked.ok ? Effect.succeed(checked.value) : Effect.fail(parseError(checked.error));
314
+ });
315
+
316
+ /** Per-operation decode facts, read from the output schema once. */
317
+ interface DecodePlan {
318
+ readonly binary: boolean;
319
+ readonly verbatim: boolean;
320
+ /**
321
+ * A member of a structure output that receives the whole body
322
+ * (`T.RawResponse()` next to header members), e.g. a bare JSON array with
323
+ * its next-page token in a response header.
324
+ */
325
+ readonly bodyMember: AST.PropertySignature | undefined;
326
+ /** The output is a bare string, so an empty body decodes to `""`. */
327
+ readonly text: boolean;
328
+ /** Members read from response headers (`T.Header`). */
329
+ readonly headers: ReadonlyArray<ResponseHeaderMember>;
330
+ }
331
+
332
+ const decodePlans = /*@__PURE__*/ new WeakMap<AST.AST, DecodePlan>();
333
+ const decodePlanFor = (outputAst: AST.AST): DecodePlan => {
334
+ let plan = decodePlans.get(outputAst);
335
+ if (plan === undefined) {
336
+ plan = {
337
+ binary: getAnn(outputAst, binaryResponseSymbol) !== undefined,
338
+ verbatim: mapsVerbatim(outputAst, "decode"),
339
+ text: resolveNode(outputAst)._tag === "String",
340
+ headers: responseHeaderMembers(outputAst),
341
+ bodyMember: getProps(outputAst).find((prop) => hasPropAnn(prop, rawResponseSymbol)),
342
+ };
343
+ decodePlans.set(outputAst, plan);
344
+ }
345
+ return plan;
346
+ };
347
+
348
+ /**
349
+ * The outcome of decoding a response body: the value, or the failure the
350
+ * call fails with. Plain data, so decoding stays synchronous.
351
+ */
352
+ type Decoded =
353
+ | { readonly ok: true; readonly value: unknown }
354
+ | { readonly ok: false; readonly error: unknown };
237
355
 
238
356
  /**
239
357
  * 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
358
+ * a module-level const in the provider's `protocol.ts` -- `API.make` memoizes
241
359
  * protocol layers by value identity.
242
360
  */
243
- export const makeRestProtocol = <C>(
244
- options: RestProtocolOptions<C>,
245
- ): Layer.Layer<API.Protocol> => {
361
+ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Layer<API.Protocol> => {
246
362
  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,
363
+ const statusMap: Readonly<Record<number, (new (args: any) => any) | undefined>> =
364
+ options.statusMap ?? HTTP_STATUS_MAP;
365
+ const credentialsKey = Context.isKey(options.credentials)
366
+ ? (options.credentials as Context.Key<any, Effect.Effect<C, any, any>>)
367
+ : undefined;
368
+ const credentialsEffect = options.credentials as Effect.Effect<C>;
369
+
370
+ /** The calling fiber's credentials, then `f` on them. */
371
+ const withCredentials = <B>(
372
+ context: Context.Context<any>,
373
+ f: (creds: C) => Effect.Effect<B, any, any>,
374
+ ): Effect.Effect<B, any, any> =>
375
+ API.withValue(
376
+ credentialsKey === undefined ? credentialsEffect : Context.get(context, credentialsKey),
377
+ f,
378
+ );
379
+
380
+ /**
381
+ * The request; fails with the error a refusing `baseUrl` threw, or with
382
+ * `InvalidInput` for a label that would address another resource.
383
+ */
384
+ const requestFor = (
385
+ creds: C,
386
+ input: unknown,
387
+ inputAst: AST.AST,
388
+ ): Effect.Effect<HttpClientRequest.HttpClientRequest> => {
389
+ const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
390
+ let baseUrl: string;
391
+ try {
392
+ baseUrl = options.baseUrl(creds, {
393
+ uri: http?.uri ?? "",
394
+ method: http?.method ?? "",
267
395
  });
268
- });
396
+ } catch (e) {
397
+ // A baseUrl that refuses the route (missing scope in the
398
+ // credentials) fails the call with that error, typed for callers by
399
+ // the operation's declared error channel.
400
+ return fail(e);
401
+ }
402
+ return buildRequest({
403
+ input: unwrapRedactedDeep(input),
404
+ inputAst,
405
+ baseUrl,
406
+ headers: options.headers(creds),
407
+ mapMemberHeader: options.mapMemberHeader,
408
+ unknownKeyToWire: options.unknownKeyToWire,
409
+ emptyJsonBody: options.emptyJsonBody,
410
+ }) as Effect.Effect<HttpClientRequest.HttpClientRequest>;
411
+ };
269
412
 
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
- );
413
+ /** Map a read response body to the call's outcome. */
414
+ const decodeText = (
415
+ context: Context.Context<any>,
416
+ status: number,
417
+ headers: Record<string, string | undefined>,
418
+ text: string,
419
+ outputAst: AST.AST,
420
+ errorClasses: ReadonlyArray<unknown>,
421
+ ): Decoded => {
422
+ // Read as text and parse tolerantly -- error pages are often non-JSON.
423
+ let json: unknown;
424
+ let nonJson = false;
425
+ if (text.trim().length > 0) {
426
+ try {
427
+ json = JSON.parse(text);
428
+ } catch {
429
+ nonJson = true;
286
430
  }
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
- }
295
- }
296
- const status = response.status;
297
- const headers = response.headers as Record<string, string | undefined>;
431
+ }
298
432
 
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}`);
433
+ if (status >= 400) {
434
+ const env = (nonJson ? undefined : errorEnvelope(json)) ?? {};
435
+ const message = env.message ?? (nonJson && text.trim() ? text.trim() : `HTTP ${status}`);
304
436
 
305
- // 1. Per-operation typed error (matcher metadata on the class).
306
- const typed = matchTypedError(errorClasses, status, [
437
+ // 0. The provider's own reading of the failure.
438
+ if (options.classifyError) {
439
+ const classified = options.classifyError({
440
+ status,
441
+ code: env.code,
442
+ message,
443
+ body: nonJson ? text : json,
444
+ headers,
445
+ });
446
+ if (classified !== undefined) return { ok: false, error: classified };
447
+ }
448
+
449
+ // 1. Per-operation typed error (matcher metadata on the class).
450
+ const typed = matchTypedError(
451
+ errorClasses,
452
+ status,
453
+ [
307
454
  {
308
455
  code: typeof env.code === "number" ? env.code : undefined,
309
456
  message,
310
457
  },
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
- }
458
+ ],
459
+ { body: nonJson ? text : json, headers },
460
+ );
461
+ if (typed !== undefined) return { ok: false, error: typed };
336
462
 
337
- // 4. Provider fallback.
338
- return yield* fail(
339
- options.unknownError({
340
- status,
341
- code: env.code,
463
+ // 2. Status-mapped class (retryAfter only stamps on retryable
464
+ // statuses -- parseRetryAfterForStatus gates on that).
465
+ const StatusErrorClass = statusMap[status];
466
+ if (StatusErrorClass) {
467
+ return {
468
+ ok: false,
469
+ error: new StatusErrorClass({
342
470
  message,
343
- body: nonJson ? text : json,
344
- headers,
471
+ retryAfter: parseRetryAfterForStatus(status, headers),
345
472
  }),
346
- );
473
+ };
347
474
  }
348
475
 
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"));
476
+ // 3. Unmapped 5xx (e.g. proxy-specific statuses) -> retryable server
477
+ // error rather than the unknown fallback.
478
+ if (status >= 500) {
479
+ return {
480
+ ok: false,
481
+ error: new InternalServerError({
482
+ message,
483
+ retryAfter: parseRetryAfterForStatus(status, headers),
484
+ }),
485
+ };
486
+ }
487
+
488
+ // 4. Provider fallback.
489
+ return {
490
+ ok: false,
491
+ error: options.unknownError({
492
+ status,
493
+ code: env.code,
494
+ message,
495
+ body: nonJson ? text : json,
496
+ headers,
497
+ }),
498
+ };
499
+ }
500
+
501
+ // 2xx: the response body IS the payload (no envelope). Wire->TS key
502
+ // mapping is schema-driven; `RawResponseRoot` responses are the body
503
+ // verbatim (mapKeys handles arrays/scalars structurally either way).
504
+ // Strict mode (core/response-validation) checks the mapped body against
505
+ // the output schema -- a non-JSON body reaches it as a string and fails
506
+ // there unless the operation's output is itself a string. For an output
507
+ // with sensitive members, a non-JSON body fails in every mode and parse
508
+ // errors withhold the body.
509
+ const plan = decodePlanFor(outputAst);
510
+ let body: unknown = nonJson ? text : (json ?? (plan.text ? "" : {}));
511
+ if (options.transformResponse) body = options.transformResponse(body);
512
+ const mapped =
513
+ plan.bodyMember !== undefined
514
+ ? { [plan.bodyMember.name]: mapKeys(plan.bodyMember.type, body, "decode") }
515
+ : plan.verbatim
516
+ ? body
517
+ : mapKeys(outputAst, body, "decode");
518
+ const checked = checkSuccess(context, outputAst, {
519
+ value: withResponseHeaders(plan.headers, mapped, headers),
520
+ body: nonJson ? text : json,
521
+ nonJson,
355
522
  });
523
+ return checked.ok ? checked : { ok: false, error: options.parseError(checked.error) };
524
+ };
525
+
526
+ const decodeResponse = (
527
+ context: Context.Context<any>,
528
+ response: HttpClientResponse.HttpClientResponse,
529
+ outputAst: AST.AST,
530
+ errorClasses: ReadonlyArray<unknown>,
531
+ ): Effect.Effect<unknown> =>
532
+ // A body read that fails (reset or abort mid-body) fails the call with
533
+ // its `HttpClientError`, which every operation's error channel declares.
534
+ (response.status >= 200 && response.status < 300 && decodePlanFor(outputAst).binary
535
+ ? Effect.map(response.arrayBuffer, (bytes) => new Uint8Array(bytes))
536
+ : Effect.flatMap(response.text, (text) => {
537
+ recordPageHeaders(context, response.headers);
538
+ const decoded = decodeText(
539
+ context,
540
+ response.status,
541
+ response.headers as Record<string, string | undefined>,
542
+ text ?? "",
543
+ outputAst,
544
+ errorClasses,
545
+ );
546
+ return decoded.ok ? Effect.succeed(decoded.value) : fail(decoded.error);
547
+ })) as Effect.Effect<unknown>;
548
+
549
+ const call = (op: API.PreparedOperation, input: unknown): Effect.Effect<unknown> =>
550
+ Effect.withFiber((fiber) => {
551
+ const context = fiber.context as Context.Context<any>;
552
+ return withCredentials(context, (creds) => {
553
+ const client = Context.get(context, HttpClient.HttpClient);
554
+ return Effect.flatMap(requestFor(creds, input, op.inputAst), (request) =>
555
+ Effect.flatMap(Telemetry.execute(context, client, request), (response) =>
556
+ decodeResponse(context, response, op.outputAst, op.errors),
557
+ ),
558
+ );
559
+ });
560
+ }) as Effect.Effect<unknown>;
356
561
 
357
562
  return Layer.succeed(
358
563
  API.Protocol,
359
564
  API.Protocol.of({
360
565
  // Erase encode's credentials requirement (resolved on the calling
361
566
  // fiber; see RestProtocolOptions.credentials).
362
- encode: (args) =>
363
- encode(args) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
364
- decode,
567
+ encode: ({ input, inputAst }) =>
568
+ Effect.withFiber((fiber) =>
569
+ withCredentials(fiber.context as Context.Context<any>, (creds) =>
570
+ requestFor(creds, input, inputAst),
571
+ ),
572
+ ) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
573
+ decode: ({ response, outputAst, errors }) =>
574
+ Effect.withFiber((fiber) =>
575
+ decodeResponse(fiber.context as Context.Context<any>, response, outputAst, errors),
576
+ ),
577
+ call,
365
578
  }),
366
579
  );
367
580
  };