@distilled.cloud/core 1.0.0-rc.15 → 1.0.0-rc.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (312) hide show
  1. package/lib/api.d.ts +118 -13
  2. package/lib/api.d.ts.map +1 -1
  3. package/lib/api.js +755 -147
  4. package/lib/api.js.map +1 -1
  5. package/lib/category.d.ts.map +1 -1
  6. package/lib/category.js +146 -146
  7. package/lib/category.js.map +1 -1
  8. package/lib/chunks.d.ts +3 -0
  9. package/lib/chunks.d.ts.map +1 -0
  10. package/lib/chunks.js +11 -0
  11. package/lib/chunks.js.map +1 -0
  12. package/lib/codegen/boolean-string-enums.js +36 -36
  13. package/lib/codegen/chunk.d.ts +7 -0
  14. package/lib/codegen/chunk.d.ts.map +1 -0
  15. package/lib/codegen/chunk.js +139 -0
  16. package/lib/codegen/chunk.js.map +1 -0
  17. package/lib/codegen/cli.d.ts.map +1 -1
  18. package/lib/codegen/cli.js +28 -14
  19. package/lib/codegen/cli.js.map +1 -1
  20. package/lib/codegen/datafy.d.ts +14 -0
  21. package/lib/codegen/datafy.d.ts.map +1 -0
  22. package/lib/codegen/datafy.js +853 -0
  23. package/lib/codegen/datafy.js.map +1 -0
  24. package/lib/codegen/dedupe.d.ts +5 -0
  25. package/lib/codegen/dedupe.d.ts.map +1 -0
  26. package/lib/codegen/dedupe.js +153 -0
  27. package/lib/codegen/dedupe.js.map +1 -0
  28. package/lib/codegen/emit.js +56 -56
  29. package/lib/codegen/format.js +18 -18
  30. package/lib/codegen/generated-at.js +29 -29
  31. package/lib/codegen/generator.d.ts.map +1 -1
  32. package/lib/codegen/generator.js +92 -84
  33. package/lib/codegen/generator.js.map +1 -1
  34. package/lib/codegen/graph.js +36 -36
  35. package/lib/codegen/graphql-client.d.ts +2 -0
  36. package/lib/codegen/graphql-client.d.ts.map +1 -1
  37. package/lib/codegen/graphql-client.js +55 -26
  38. package/lib/codegen/graphql-client.js.map +1 -1
  39. package/lib/codegen/graphql.js +113 -113
  40. package/lib/codegen/latin1.d.ts +3 -0
  41. package/lib/codegen/latin1.d.ts.map +1 -0
  42. package/lib/codegen/latin1.js +126 -0
  43. package/lib/codegen/latin1.js.map +1 -0
  44. package/lib/codegen/members.d.ts +7 -0
  45. package/lib/codegen/members.d.ts.map +1 -1
  46. package/lib/codegen/members.js +26 -19
  47. package/lib/codegen/members.js.map +1 -1
  48. package/lib/codegen/model-diff.js +6 -6
  49. package/lib/codegen/naming.js +19 -19
  50. package/lib/codegen/openapi-cli.js +15 -15
  51. package/lib/codegen/openapi.d.ts +17 -0
  52. package/lib/codegen/openapi.d.ts.map +1 -1
  53. package/lib/codegen/openapi.js +323 -169
  54. package/lib/codegen/openapi.js.map +1 -1
  55. package/lib/codegen/operations.js +14 -14
  56. package/lib/codegen/pagination.js +11 -11
  57. package/lib/codegen/patch-audit.js +57 -57
  58. package/lib/codegen/patches.js +79 -79
  59. package/lib/codegen/prelude.js +19 -19
  60. package/lib/codegen/privatize.d.ts +21 -0
  61. package/lib/codegen/privatize.d.ts.map +1 -0
  62. package/lib/codegen/privatize.js +176 -0
  63. package/lib/codegen/privatize.js.map +1 -0
  64. package/lib/codegen/proto.js +25 -25
  65. package/lib/codegen/pure.d.ts +6 -0
  66. package/lib/codegen/pure.d.ts.map +1 -0
  67. package/lib/codegen/pure.js +91 -0
  68. package/lib/codegen/pure.js.map +1 -0
  69. package/lib/codegen/rewrite-operation-ids.js +108 -108
  70. package/lib/codegen/spec-path.js +57 -57
  71. package/lib/codegen/table.d.ts +5 -0
  72. package/lib/codegen/table.d.ts.map +1 -0
  73. package/lib/codegen/table.js +249 -0
  74. package/lib/codegen/table.js.map +1 -0
  75. package/lib/config.d.ts +27 -0
  76. package/lib/config.d.ts.map +1 -0
  77. package/lib/config.js +161 -0
  78. package/lib/config.js.map +1 -0
  79. package/lib/crypto.d.ts +76 -0
  80. package/lib/crypto.d.ts.map +1 -0
  81. package/lib/crypto.js +130 -0
  82. package/lib/crypto.js.map +1 -0
  83. package/lib/debug.d.ts +2 -0
  84. package/lib/debug.d.ts.map +1 -0
  85. package/lib/debug.js +8 -0
  86. package/lib/debug.js.map +1 -0
  87. package/lib/error-category.d.ts +1 -1
  88. package/lib/error-category.d.ts.map +1 -1
  89. package/lib/error-category.js +7 -6
  90. package/lib/error-category.js.map +1 -1
  91. package/lib/errors.d.ts +62 -62
  92. package/lib/errors.d.ts.map +1 -1
  93. package/lib/errors.js +117 -114
  94. package/lib/errors.js.map +1 -1
  95. package/lib/graphql.d.ts +31 -20
  96. package/lib/graphql.d.ts.map +1 -1
  97. package/lib/graphql.js +150 -119
  98. package/lib/graphql.js.map +1 -1
  99. package/lib/graphql.types.js +4 -3
  100. package/lib/graphql.types.js.map +1 -1
  101. package/lib/index.d.ts +3 -2
  102. package/lib/index.d.ts.map +1 -1
  103. package/lib/index.js +15 -14
  104. package/lib/index.js.map +1 -1
  105. package/lib/json-patch.d.ts +2 -2
  106. package/lib/json-patch.js +28 -28
  107. package/lib/pagination.d.ts +9 -25
  108. package/lib/pagination.d.ts.map +1 -1
  109. package/lib/pagination.js +95 -90
  110. package/lib/pagination.js.map +1 -1
  111. package/lib/plain-values.d.ts +10 -0
  112. package/lib/plain-values.d.ts.map +1 -0
  113. package/lib/plain-values.js +40 -0
  114. package/lib/plain-values.js.map +1 -0
  115. package/lib/protocol-http.d.ts +50 -14
  116. package/lib/protocol-http.d.ts.map +1 -1
  117. package/lib/protocol-http.js +351 -178
  118. package/lib/protocol-http.js.map +1 -1
  119. package/lib/protocol-rest.d.ts +38 -25
  120. package/lib/protocol-rest.d.ts.map +1 -1
  121. package/lib/protocol-rest.js +238 -130
  122. package/lib/protocol-rest.js.map +1 -1
  123. package/lib/query.js +16 -16
  124. package/lib/response-validation-strict.d.ts +48 -0
  125. package/lib/response-validation-strict.d.ts.map +1 -0
  126. package/lib/response-validation-strict.js +284 -0
  127. package/lib/response-validation-strict.js.map +1 -0
  128. package/lib/response-validation.d.ts +43 -25
  129. package/lib/response-validation.d.ts.map +1 -1
  130. package/lib/response-validation.js +112 -70
  131. package/lib/response-validation.js.map +1 -1
  132. package/lib/retry-after.d.ts +3 -3
  133. package/lib/retry-after.js +49 -49
  134. package/lib/retry.d.ts +48 -29
  135. package/lib/retry.d.ts.map +1 -1
  136. package/lib/retry.js +142 -154
  137. package/lib/retry.js.map +1 -1
  138. package/lib/schema-lite-impl.d.ts +158 -0
  139. package/lib/schema-lite-impl.d.ts.map +1 -0
  140. package/lib/schema-lite-impl.js +341 -0
  141. package/lib/schema-lite-impl.js.map +1 -0
  142. package/lib/schema-lite-typed.d.ts +41 -0
  143. package/lib/schema-lite-typed.d.ts.map +1 -0
  144. package/lib/schema-lite-typed.js +27 -0
  145. package/lib/schema-lite-typed.js.map +1 -0
  146. package/lib/schema-lite.d.ts +40 -0
  147. package/lib/schema-lite.d.ts.map +1 -0
  148. package/lib/schema-lite.js +31 -0
  149. package/lib/schema-lite.js.map +1 -0
  150. package/lib/schema.d.ts +20 -6
  151. package/lib/schema.d.ts.map +1 -1
  152. package/lib/schema.js +202 -30
  153. package/lib/schema.js.map +1 -1
  154. package/lib/testing.d.ts +3 -2
  155. package/lib/testing.d.ts.map +1 -1
  156. package/lib/testing.js +22 -21
  157. package/lib/testing.js.map +1 -1
  158. package/lib/trait.d.ts +13 -13
  159. package/lib/trait.d.ts.map +1 -1
  160. package/lib/trait.js +80 -80
  161. package/lib/trait.js.map +1 -1
  162. package/lib/xml.d.ts +1 -1
  163. package/lib/xml.d.ts.map +1 -1
  164. package/lib/xml.js +38 -26
  165. package/lib/xml.js.map +1 -1
  166. package/package.json +9 -7
  167. package/src/api.ts +1079 -180
  168. package/src/category.ts +33 -33
  169. package/src/chunks.ts +30 -0
  170. package/src/codegen/chunk.ts +147 -0
  171. package/src/codegen/cli.ts +27 -1
  172. package/src/codegen/datafy.ts +874 -0
  173. package/src/codegen/dedupe.ts +173 -0
  174. package/src/codegen/generator.ts +10 -3
  175. package/src/codegen/graphql-client.ts +49 -15
  176. package/src/codegen/latin1.ts +131 -0
  177. package/src/codegen/members.ts +8 -0
  178. package/src/codegen/openapi.ts +194 -3
  179. package/src/codegen/privatize.ts +200 -0
  180. package/src/codegen/pure.ts +94 -0
  181. package/src/codegen/table.ts +254 -0
  182. package/src/config.ts +216 -0
  183. package/src/crypto.ts +202 -0
  184. package/src/debug.ts +8 -0
  185. package/src/error-category.ts +2 -1
  186. package/src/errors.ts +65 -56
  187. package/src/graphql.ts +109 -62
  188. package/src/graphql.types.ts +9 -7
  189. package/src/index.ts +3 -2
  190. package/src/json-patch.ts +2 -2
  191. package/src/pagination.ts +37 -18
  192. package/src/plain-values.ts +41 -0
  193. package/src/protocol-http.ts +378 -145
  194. package/src/protocol-rest.ts +337 -169
  195. package/src/response-validation-strict.ts +327 -0
  196. package/src/response-validation.ts +101 -50
  197. package/src/retry-after.ts +3 -3
  198. package/src/retry.ts +94 -93
  199. package/src/schema-lite-impl.ts +550 -0
  200. package/src/schema-lite-typed.ts +44 -0
  201. package/src/schema-lite.ts +44 -0
  202. package/src/schema.ts +258 -14
  203. package/src/testing.ts +4 -2
  204. package/src/trait.ts +36 -28
  205. package/src/xml.ts +31 -17
  206. package/lib/codegen/boolean-string-enums.test.d.ts +0 -2
  207. package/lib/codegen/boolean-string-enums.test.d.ts.map +0 -1
  208. package/lib/codegen/boolean-string-enums.test.js +0 -275
  209. package/lib/codegen/boolean-string-enums.test.js.map +0 -1
  210. package/lib/codegen/defer-naming.test.d.ts +0 -2
  211. package/lib/codegen/defer-naming.test.d.ts.map +0 -1
  212. package/lib/codegen/defer-naming.test.js +0 -105
  213. package/lib/codegen/defer-naming.test.js.map +0 -1
  214. package/lib/codegen/generated-at.test.d.ts +0 -2
  215. package/lib/codegen/generated-at.test.d.ts.map +0 -1
  216. package/lib/codegen/generated-at.test.js +0 -81
  217. package/lib/codegen/generated-at.test.js.map +0 -1
  218. package/lib/codegen/generator.test.d.ts +0 -2
  219. package/lib/codegen/generator.test.d.ts.map +0 -1
  220. package/lib/codegen/generator.test.js +0 -121
  221. package/lib/codegen/generator.test.js.map +0 -1
  222. package/lib/codegen/graphql-client.test.d.ts +0 -2
  223. package/lib/codegen/graphql-client.test.d.ts.map +0 -1
  224. package/lib/codegen/graphql-client.test.js +0 -171
  225. package/lib/codegen/graphql-client.test.js.map +0 -1
  226. package/lib/codegen/openapi-binary.test.d.ts +0 -2
  227. package/lib/codegen/openapi-binary.test.d.ts.map +0 -1
  228. package/lib/codegen/openapi-binary.test.js +0 -67
  229. package/lib/codegen/openapi-binary.test.js.map +0 -1
  230. package/lib/codegen/patch-audit.test.d.ts +0 -2
  231. package/lib/codegen/patch-audit.test.d.ts.map +0 -1
  232. package/lib/codegen/patch-audit.test.js +0 -141
  233. package/lib/codegen/patch-audit.test.js.map +0 -1
  234. package/lib/codegen/patches.test.d.ts +0 -2
  235. package/lib/codegen/patches.test.d.ts.map +0 -1
  236. package/lib/codegen/patches.test.js +0 -155
  237. package/lib/codegen/patches.test.js.map +0 -1
  238. package/lib/codegen/protocol-imports.test.d.ts +0 -2
  239. package/lib/codegen/protocol-imports.test.d.ts.map +0 -1
  240. package/lib/codegen/protocol-imports.test.js +0 -36
  241. package/lib/codegen/protocol-imports.test.js.map +0 -1
  242. package/lib/codegen/rewrite-operation-ids.test.d.ts +0 -2
  243. package/lib/codegen/rewrite-operation-ids.test.d.ts.map +0 -1
  244. package/lib/codegen/rewrite-operation-ids.test.js +0 -451
  245. package/lib/codegen/rewrite-operation-ids.test.js.map +0 -1
  246. package/lib/codegen/untagged-unions.test.d.ts +0 -2
  247. package/lib/codegen/untagged-unions.test.d.ts.map +0 -1
  248. package/lib/codegen/untagged-unions.test.js +0 -80
  249. package/lib/codegen/untagged-unions.test.js.map +0 -1
  250. package/lib/fixtures/xml/upstream-validator.json +0 -397
  251. package/lib/graphql.test.d.ts +0 -2
  252. package/lib/graphql.test.d.ts.map +0 -1
  253. package/lib/graphql.test.js +0 -151
  254. package/lib/graphql.test.js.map +0 -1
  255. package/lib/json-patch.test.d.ts +0 -2
  256. package/lib/json-patch.test.d.ts.map +0 -1
  257. package/lib/json-patch.test.js +0 -65
  258. package/lib/json-patch.test.js.map +0 -1
  259. package/lib/pagination.test.d.ts +0 -2
  260. package/lib/pagination.test.d.ts.map +0 -1
  261. package/lib/pagination.test.js +0 -131
  262. package/lib/pagination.test.js.map +0 -1
  263. package/lib/protocol-http.test.d.ts +0 -2
  264. package/lib/protocol-http.test.d.ts.map +0 -1
  265. package/lib/protocol-http.test.js +0 -228
  266. package/lib/protocol-http.test.js.map +0 -1
  267. package/lib/protocol-rest.test.d.ts +0 -2
  268. package/lib/protocol-rest.test.d.ts.map +0 -1
  269. package/lib/protocol-rest.test.js +0 -498
  270. package/lib/protocol-rest.test.js.map +0 -1
  271. package/lib/response-validation.test.d.ts +0 -2
  272. package/lib/response-validation.test.d.ts.map +0 -1
  273. package/lib/response-validation.test.js +0 -72
  274. package/lib/response-validation.test.js.map +0 -1
  275. package/lib/retry-after.test.d.ts +0 -2
  276. package/lib/retry-after.test.d.ts.map +0 -1
  277. package/lib/retry-after.test.js +0 -204
  278. package/lib/retry-after.test.js.map +0 -1
  279. package/lib/retry.test.d.ts +0 -2
  280. package/lib/retry.test.d.ts.map +0 -1
  281. package/lib/retry.test.js +0 -407
  282. package/lib/retry.test.js.map +0 -1
  283. package/lib/sdks.test.d.ts +0 -2
  284. package/lib/sdks.test.d.ts.map +0 -1
  285. package/lib/sdks.test.js +0 -76
  286. package/lib/sdks.test.js.map +0 -1
  287. package/lib/xml.test.d.ts +0 -2
  288. package/lib/xml.test.d.ts.map +0 -1
  289. package/lib/xml.test.js +0 -210
  290. package/lib/xml.test.js.map +0 -1
  291. package/src/codegen/boolean-string-enums.test.ts +0 -299
  292. package/src/codegen/defer-naming.test.ts +0 -113
  293. package/src/codegen/generated-at.test.ts +0 -89
  294. package/src/codegen/generator.test.ts +0 -137
  295. package/src/codegen/graphql-client.test.ts +0 -189
  296. package/src/codegen/openapi-binary.test.ts +0 -91
  297. package/src/codegen/patch-audit.test.ts +0 -160
  298. package/src/codegen/patches.test.ts +0 -188
  299. package/src/codegen/protocol-imports.test.ts +0 -39
  300. package/src/codegen/rewrite-operation-ids.test.ts +0 -472
  301. package/src/codegen/untagged-unions.test.ts +0 -85
  302. package/src/fixtures/xml/upstream-validator.json +0 -397
  303. package/src/graphql.test.ts +0 -198
  304. package/src/json-patch.test.ts +0 -77
  305. package/src/pagination.test.ts +0 -169
  306. package/src/protocol-http.test.ts +0 -276
  307. package/src/protocol-rest.test.ts +0 -703
  308. package/src/response-validation.test.ts +0 -89
  309. package/src/retry-after.test.ts +0 -267
  310. package/src/retry.test.ts +0 -566
  311. package/src/sdks.test.ts +0 -87
  312. package/src/xml.test.ts +0 -251
@@ -1,49 +1,56 @@
1
1
  /**
2
2
  * Generic REST protocol factory for simple bearer/header-auth JSON APIs
3
- * (Neon, Fly.io, PlanetScale, Supabase, Turso, …).
3
+ * (Neon, Fly.io, PlanetScale, Supabase, Turso, ...).
4
4
  *
5
5
  * `makeRestProtocol(options)` builds a core {@link API.Protocol} layer:
6
6
  *
7
7
  * request: credentials resolved from the CALLING fiber's context on every
8
- * request (the layer itself is memoized per process — see
8
+ * request (the layer itself is memoized per process -- see
9
9
  * `core/api`), auth headers + base URL from the provider's
10
10
  * options, request built by `buildRequest` from
11
11
  * `core/protocol-http` (deep-unwrapping any `Redacted` input
12
12
  * values first)
13
13
  *
14
- * response: 2xx JSON → optional `transformResponse` → recursive wire→TS
15
- * key mapping (`mapKeys`) → in strict mode, a schema check
14
+ * response: 2xx JSON -> optional `transformResponse` -> recursive wire->TS
15
+ * key mapping (`mapKeys`) -> in strict mode, a schema check
16
16
  * failing with the provider's `parseError` (see
17
- * `core/response-validation`) → `Redacted` wrapping of members
18
- * marked with {@link SensitiveValue}; non-2xx → typed error:
17
+ * `core/response-validation`) -> `Redacted` wrapping of members
18
+ * marked with {@link SensitiveValue}; non-2xx -> typed error:
19
19
  * per-op matcher classes (`matchTypedError`), then the status
20
20
  * map (default `HTTP_STATUS_MAP`), then an `InternalServerError`
21
21
  * for unmapped 5xx, then the provider's `unknownError` fallback
22
- * — with `retryAfter` durations stamped from the standard hint
22
+ * -- with `retryAfter` durations stamped from the standard hint
23
23
  * headers on retryable statuses.
24
24
  *
25
25
  * Anything provider-specific (envelope quirks, bespoke error codes) belongs
26
- * in the provider package — via these options or a hand-written protocol.
26
+ * in the provider package -- via these options or a hand-written protocol.
27
27
  */
28
+ import * as Context from "effect/Context";
28
29
  import * as Effect from "effect/Effect";
30
+ import * as HttpClient from "effect/http/HttpClient";
29
31
  import type * as HttpClientRequest from "effect/http/HttpClientRequest";
30
32
  import type * as HttpClientResponse from "effect/http/HttpClientResponse";
31
33
  import * as Layer from "effect/Layer";
32
34
  import * as Redacted from "effect/Redacted";
33
35
  import type * as AST from "effect/SchemaAST";
34
36
  import * as API from "./api.ts";
37
+ import { debugHttp } from "./debug.ts";
35
38
  import { HTTP_STATUS_MAP, InternalServerError } from "./errors.ts";
39
+ import { isOpaqueValue, unwrapRedactedDeep } from "./plain-values.ts";
36
40
  import {
37
41
  buildRequest,
38
42
  getAnn,
39
43
  getPropAnn,
40
44
  getProps,
41
- isOpaqueValue,
42
45
  mapKeys,
46
+ mapsVerbatim,
43
47
  matchTypedError,
44
48
  resolveNode,
49
+ responseHeaderMembers,
50
+ withResponseHeaders,
51
+ type ResponseHeaderMember,
45
52
  } from "./protocol-http.ts";
46
- import { validateResponse } from "./response-validation.ts";
53
+ import { checkResponse, withholdActual } from "./response-validation.ts";
47
54
  import { parseRetryAfterForStatus } from "./retry-after.ts";
48
55
  import { httpSymbol, makeAnnotation, type HttpTrait } from "./trait.ts";
49
56
 
@@ -51,7 +58,9 @@ import { httpSymbol, makeAnnotation, type HttpTrait } from "./trait.ts";
51
58
  // Traits
52
59
  // =============================================================================
53
60
 
54
- export const sensitiveValueSymbol = Symbol.for("@distilled.cloud/core/sensitive-value");
61
+ export const sensitiveValueSymbol = /*@__PURE__*/ Symbol.for(
62
+ "@distilled.cloud/core/sensitive-value",
63
+ );
55
64
  /**
56
65
  * Marks a string member as sensitive (mirrors `smithy.api#sensitive`).
57
66
  * The REST protocol wraps decoded values in `Redacted` on the way out and
@@ -61,14 +70,16 @@ export const sensitiveValueSymbol = Symbol.for("@distilled.cloud/core/sensitive-
61
70
  */
62
71
  export const SensitiveValue = (_value?: unknown) => makeAnnotation(sensitiveValueSymbol, true);
63
72
 
64
- export const rawResponseSymbol = Symbol.for("@distilled.cloud/core/raw-response");
73
+ export const rawResponseSymbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/raw-response");
65
74
  /**
66
75
  * Marks the sole output member that carries a bare (array/scalar) response
67
76
  * body (mirrors `com.distilled.openapi#rawResponse`).
68
77
  */
69
78
  export const RawResponse = (_value?: unknown) => makeAnnotation(rawResponseSymbol, true);
70
79
 
71
- export const rawResponseRootSymbol = Symbol.for("@distilled.cloud/core/raw-response-root");
80
+ export const rawResponseRootSymbol = /*@__PURE__*/ Symbol.for(
81
+ "@distilled.cloud/core/raw-response-root",
82
+ );
72
83
  /**
73
84
  * Marks a response schema whose ENTIRE value is the response body (the
74
85
  * generator's `rootPipe` for synthesized bare-payload wrappers): the emitted
@@ -77,7 +88,9 @@ export const rawResponseRootSymbol = Symbol.for("@distilled.cloud/core/raw-respo
77
88
  */
78
89
  export const RawResponseRoot = () => makeAnnotation(rawResponseRootSymbol, true);
79
90
 
80
- export const binaryResponseSymbol = Symbol.for("@distilled.cloud/core/binary-response");
91
+ export const binaryResponseSymbol = /*@__PURE__*/ Symbol.for(
92
+ "@distilled.cloud/core/binary-response",
93
+ );
81
94
 
82
95
  /** Decode a successful raw binary response as bytes, without text conversion. */
83
96
  export const BinaryResponse = () => makeAnnotation(binaryResponseSymbol, true);
@@ -86,32 +99,7 @@ export const BinaryResponse = () => makeAnnotation(binaryResponseSymbol, true);
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 || Object.getPrototypeOf(v) === null);
95
-
96
- /**
97
- * Deep-unwrap `Redacted` values in an input (plain objects/arrays only —
98
- * class instances, files, and binary payloads pass through untouched).
99
- * Sensitive input members accept `string | Redacted<string>`; the wire wants
100
- * the raw string.
101
- */
102
- export const unwrapRedactedDeep = (value: unknown): unknown => {
103
- if (Redacted.isRedacted(value)) return Redacted.value(value);
104
- if (Array.isArray(value)) return value.map(unwrapRedactedDeep);
105
- if (isPlainObject(value)) {
106
- const out: Record<string, unknown> = {};
107
- for (const [k, v] of Object.entries(value)) {
108
- if (v === undefined) continue;
109
- out[k] = unwrapRedactedDeep(v);
110
- }
111
- return out;
112
- }
113
- return value;
114
- };
102
+ export { unwrapRedactedDeep };
115
103
 
116
104
  /**
117
105
  * Walk a decoded (TS-named) value alongside its schema AST, wrapping members
@@ -153,6 +141,37 @@ export const wrapSensitive = (ast: AST.AST, value: unknown): unknown => {
153
141
  return value;
154
142
  };
155
143
 
144
+ const sensitiveOutputs = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
145
+
146
+ /**
147
+ * Whether any member reachable from `ast` is marked {@link SensitiveValue}.
148
+ * Parse errors for such an output withhold the response body (see
149
+ * {@link RestParseErrorInfo}); hand-written protocols use this to do the same.
150
+ */
151
+ export const hasSensitiveMember = (ast: AST.AST): boolean => {
152
+ const cached = sensitiveOutputs.get(ast);
153
+ if (cached !== undefined) return cached;
154
+ const seen = new Set<AST.AST>();
155
+ const visit = (node: AST.AST): boolean => {
156
+ node = resolveNode(node);
157
+ if (seen.has(node)) return false;
158
+ seen.add(node);
159
+ if (node._tag === "Union") return node.types.some(visit);
160
+ if (node._tag === "Arrays") {
161
+ return [...node.elements, ...node.rest].some(
162
+ (e) => getAnn(e, sensitiveValueSymbol) !== undefined || visit(e),
163
+ );
164
+ }
165
+ if (node._tag !== "Objects") return false;
166
+ return [...node.propertySignatures, ...node.indexSignatures].some(
167
+ (member) => getAnn(member.type, sensitiveValueSymbol) !== undefined || visit(member.type),
168
+ );
169
+ };
170
+ const result = visit(ast);
171
+ sensitiveOutputs.set(ast, result);
172
+ return result;
173
+ };
174
+
156
175
  // =============================================================================
157
176
  // Protocol factory
158
177
  // =============================================================================
@@ -168,8 +187,12 @@ export interface RestErrorInfo {
168
187
  readonly headers: Record<string, string | undefined>;
169
188
  }
170
189
 
171
- /** A 2xx body that failed strict validation, for the `parseError` option. */
190
+ /**
191
+ * A 2xx body that failed strict validation, or a non-JSON 2xx body for an
192
+ * output with sensitive members, for the `parseError` option.
193
+ */
172
194
  export interface RestParseErrorInfo {
195
+ /** `"[REDACTED]"` when the output has sensitive members. */
173
196
  readonly body: unknown;
174
197
  readonly cause: unknown;
175
198
  }
@@ -181,16 +204,18 @@ export interface RestErrorEnvelope {
181
204
 
182
205
  export interface RestProtocolOptions<C> {
183
206
  /**
184
- * Resolve credentials ON THE CALLING FIBER — evaluated per request, never
207
+ * Resolve credentials ON THE CALLING FIBER -- evaluated per request, never
185
208
  * at layer build time, so context-provided credentials and token refreshes
186
- * are picked up. Typically `Effect.gen(function* () { const resolve =
187
- * yield* Credentials; return yield* resolve; })` for the distilled
188
- * credentials-service convention. Its error/requirement channels are
209
+ * are picked up. Either an effect, or -- for the distilled
210
+ * credentials-service convention -- the `Credentials` service key whose
211
+ * value is that effect (read from the calling fiber's context; an
212
+ * already-resolved `Effect.succeed` value costs no extra fiber step). Its
213
+ * error/requirement channels are
189
214
  * erased at the protocol boundary (Protocol effects carry none) and
190
215
  * reintroduced for callers by the generated `<Sdk>OpError` /
191
216
  * `<Sdk>OpContext` annotations.
192
217
  */
193
- readonly credentials: Effect.Effect<C, any, any>;
218
+ readonly credentials: Effect.Effect<C, any, any> | Context.Key<any, Effect.Effect<C, any, any>>;
194
219
  /**
195
220
  * API base URL from the resolved credentials. Receives the operation's
196
221
  * route so APIs with more than one endpoint (e.g. S2's account vs
@@ -212,7 +237,7 @@ export interface RestProtocolOptions<C> {
212
237
  */
213
238
  readonly errorEnvelope?: (body: unknown) => RestErrorEnvelope | undefined;
214
239
  /**
215
- * HTTP status → error class constructed as `new Cls({ message, retryAfter
240
+ * HTTP status -> error class constructed as `new Cls({ message, retryAfter
216
241
  * })`. Default: core `HTTP_STATUS_MAP`. Consulted after per-op typed error
217
242
  * matching; unmapped 5xx fall back to `InternalServerError`, everything
218
243
  * else to {@link unknownError}.
@@ -223,8 +248,11 @@ export interface RestProtocolOptions<C> {
223
248
  /**
224
249
  * The SDK's `<Sdk>ParseError`, raised when a 2xx body does not match the
225
250
  * operation's output schema in strict mode (see
226
- * `core/response-validation`). `body` is the parsed JSON, or the raw text
227
- * when the body wasn't JSON; `cause` is the schema error.
251
+ * `core/response-validation`), and in every mode when a 2xx body for an
252
+ * output with sensitive members is not JSON. `body` is the parsed JSON, or
253
+ * the raw text when the body wasn't JSON, and `"[REDACTED]"` for an output
254
+ * with sensitive members; `cause` is the schema error, or `"Invalid JSON
255
+ * response"`.
228
256
  */
229
257
  readonly parseError: (info: RestParseErrorInfo) => unknown;
230
258
  /** Transform the parsed 2xx JSON before decoding (e.g. stripNulls). */
@@ -250,153 +278,293 @@ const defaultErrorEnvelope = (body: unknown): RestErrorEnvelope | undefined => {
250
278
  // here; the generated operation annotations reintroduce it for callers.
251
279
  const fail = (e: unknown): Effect.Effect<never> => Effect.fail(e) as Effect.Effect<never>;
252
280
 
281
+ /** Whether {@link wrapSensitive} can change any value of `root`. Cached per schema. */
282
+ export const hasSensitive = (root: AST.AST): boolean => {
283
+ let result = sensitiveCache.get(root);
284
+ if (result !== undefined) return result;
285
+ result = false;
286
+ const seen = new Set<AST.AST>();
287
+ const stack: AST.AST[] = [root];
288
+ walk: while (stack.length > 0) {
289
+ const ast = stack.pop()!;
290
+ if (seen.has(ast)) continue;
291
+ seen.add(ast);
292
+ const node = resolveNode(ast);
293
+ if (node._tag === "Union") {
294
+ for (const t of (node as AST.Union).types) stack.push(t);
295
+ } else if (node._tag === "Arrays") {
296
+ const elem = (node as any).rest?.[0] as AST.AST | undefined;
297
+ if (elem) stack.push(elem);
298
+ } else if (node._tag === "Objects") {
299
+ for (const p of getProps(node)) {
300
+ if (getPropAnn(p, sensitiveValueSymbol) !== undefined) {
301
+ result = true;
302
+ break walk;
303
+ }
304
+ stack.push(p.type);
305
+ }
306
+ }
307
+ }
308
+ sensitiveCache.set(root, result);
309
+ return result;
310
+ };
311
+ const sensitiveCache = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
312
+
313
+ /** Per-operation decode facts, read from the output schema once. */
314
+ interface DecodePlan {
315
+ readonly binary: boolean;
316
+ readonly verbatim: boolean;
317
+ readonly sensitive: boolean;
318
+ /** Parse errors withhold the body (see {@link hasSensitiveMember}). */
319
+ readonly withholdBody: boolean;
320
+ /** Members read from response headers (`T.Header`). */
321
+ readonly headers: ReadonlyArray<ResponseHeaderMember>;
322
+ }
323
+
324
+ const decodePlans = /*@__PURE__*/ new WeakMap<AST.AST, DecodePlan>();
325
+ const decodePlanFor = (outputAst: AST.AST): DecodePlan => {
326
+ let plan = decodePlans.get(outputAst);
327
+ if (plan === undefined) {
328
+ plan = {
329
+ binary: getAnn(outputAst, binaryResponseSymbol) !== undefined,
330
+ verbatim: mapsVerbatim(outputAst, "decode"),
331
+ sensitive: hasSensitive(outputAst),
332
+ withholdBody: hasSensitiveMember(outputAst),
333
+ headers: responseHeaderMembers(outputAst),
334
+ };
335
+ decodePlans.set(outputAst, plan);
336
+ }
337
+ return plan;
338
+ };
339
+
340
+ /**
341
+ * The outcome of decoding a response body: the value, or the failure the
342
+ * call fails with. Plain data, so decoding stays synchronous.
343
+ */
344
+ type Decoded =
345
+ | { readonly ok: true; readonly value: unknown }
346
+ | { readonly ok: false; readonly error: unknown };
347
+
253
348
  /**
254
349
  * Build a `Layer<Protocol>` for a simple REST JSON API. Assign the result to
255
- * a module-level const in the provider's `protocol.ts` — `API.make` memoizes
350
+ * a module-level const in the provider's `protocol.ts` -- `API.make` memoizes
256
351
  * protocol layers by value identity.
257
352
  */
258
353
  export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Layer<API.Protocol> => {
259
354
  const errorEnvelope = options.errorEnvelope ?? defaultErrorEnvelope;
260
355
  const statusMap: Readonly<Record<number, (new (args: any) => any) | undefined>> =
261
356
  options.statusMap ?? HTTP_STATUS_MAP;
357
+ const credentialsKey = Context.isKey(options.credentials)
358
+ ? (options.credentials as Context.Key<any, Effect.Effect<C, any, any>>)
359
+ : undefined;
360
+ const credentialsEffect = options.credentials as Effect.Effect<C>;
262
361
 
263
- const encode = ({ input, inputAst }: { readonly input: unknown; readonly inputAst: AST.AST }) =>
264
- Effect.gen(function* () {
265
- const creds = yield* options.credentials as Effect.Effect<C>;
266
- const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
267
- let baseUrl: string;
268
- try {
269
- baseUrl = options.baseUrl(creds, {
270
- uri: http?.uri ?? "",
271
- method: http?.method ?? "",
272
- });
273
- } catch (e) {
274
- // A baseUrl that refuses the route (missing scope in the
275
- // credentials) fails the call with that error, typed for callers by
276
- // the operation's declared error channel.
277
- return yield* Effect.fail(e);
278
- }
279
- return buildRequest({
280
- input: unwrapRedactedDeep(input),
281
- inputAst,
282
- baseUrl,
283
- headers: options.headers(creds),
284
- mapMemberHeader: options.mapMemberHeader,
285
- unknownKeyToWire: options.unknownKeyToWire,
362
+ /** The calling fiber's credentials, then `f` on them. */
363
+ const withCredentials = <B>(
364
+ context: Context.Context<any>,
365
+ f: (creds: C) => Effect.Effect<B, any, any>,
366
+ ): Effect.Effect<B, any, any> =>
367
+ API.withValue(
368
+ credentialsKey === undefined ? credentialsEffect : Context.get(context, credentialsKey),
369
+ f,
370
+ );
371
+
372
+ /** The request, or the error a refusing `baseUrl` threw. */
373
+ const requestFor = (
374
+ creds: C,
375
+ input: unknown,
376
+ inputAst: AST.AST,
377
+ ): HttpClientRequest.HttpClientRequest | { readonly refused: unknown } => {
378
+ const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
379
+ let baseUrl: string;
380
+ try {
381
+ baseUrl = options.baseUrl(creds, {
382
+ uri: http?.uri ?? "",
383
+ method: http?.method ?? "",
286
384
  });
385
+ } catch (e) {
386
+ // A baseUrl that refuses the route (missing scope in the
387
+ // credentials) fails the call with that error, typed for callers by
388
+ // the operation's declared error channel.
389
+ return { refused: e };
390
+ }
391
+ return buildRequest({
392
+ input: unwrapRedactedDeep(input),
393
+ inputAst,
394
+ baseUrl,
395
+ headers: options.headers(creds),
396
+ mapMemberHeader: options.mapMemberHeader,
397
+ unknownKeyToWire: options.unknownKeyToWire,
287
398
  });
399
+ };
288
400
 
289
- const decode = ({
290
- response,
291
- outputAst,
292
- errors: errorClasses,
293
- }: {
294
- readonly response: HttpClientResponse.HttpClientResponse;
295
- readonly outputAst: AST.AST;
296
- readonly errors: ReadonlyArray<unknown>;
297
- }) =>
298
- Effect.gen(function* () {
299
- if (
300
- response.status >= 200 &&
301
- response.status < 300 &&
302
- getAnn(outputAst, binaryResponseSymbol) !== undefined
303
- ) {
304
- const bytes = yield* response.arrayBuffer.pipe(Effect.orDie);
305
- return new Uint8Array(bytes);
306
- }
307
- // Read as text and parse tolerantly — error pages are often non-JSON.
308
- const text = (yield* response.text.pipe(Effect.orDie)) ?? "";
309
- if (process.env.DISTILLED_DEBUG_HTTP) {
310
- console.error(`[distilled] <- ${response.status}`);
311
- }
312
- let json: unknown;
313
- let nonJson = false;
314
- if (text.trim().length > 0) {
315
- try {
316
- json = JSON.parse(text);
317
- } catch {
318
- nonJson = true;
319
- }
401
+ /** Map a read response body to the call's outcome. */
402
+ const decodeText = (
403
+ context: Context.Context<any>,
404
+ status: number,
405
+ headers: Record<string, string | undefined>,
406
+ text: string,
407
+ outputAst: AST.AST,
408
+ errorClasses: ReadonlyArray<unknown>,
409
+ ): Decoded => {
410
+ // Read as text and parse tolerantly -- error pages are often non-JSON.
411
+ if (debugHttp()) {
412
+ console.error(`[distilled] <- ${status}`);
413
+ }
414
+ let json: unknown;
415
+ let nonJson = false;
416
+ if (text.trim().length > 0) {
417
+ try {
418
+ json = JSON.parse(text);
419
+ } catch {
420
+ nonJson = true;
320
421
  }
321
- const status = response.status;
322
- const headers = response.headers as Record<string, string | undefined>;
422
+ }
323
423
 
324
- if (status >= 400) {
325
- const env = (nonJson ? undefined : errorEnvelope(json)) ?? {};
326
- const message = env.message ?? (nonJson && text.trim() ? text.trim() : `HTTP ${status}`);
424
+ if (status >= 400) {
425
+ const env = (nonJson ? undefined : errorEnvelope(json)) ?? {};
426
+ const message = env.message ?? (nonJson && text.trim() ? text.trim() : `HTTP ${status}`);
327
427
 
328
- // 1. Per-operation typed error (matcher metadata on the class).
329
- const typed = matchTypedError(
330
- errorClasses,
331
- status,
332
- [
333
- {
334
- code: typeof env.code === "number" ? env.code : undefined,
335
- message,
336
- },
337
- ],
338
- { body: nonJson ? text : json, headers },
339
- );
340
- if (typed !== undefined) return yield* fail(typed);
341
-
342
- // 2. Status-mapped class (retryAfter only stamps on retryable
343
- // statuses — parseRetryAfterForStatus gates on that).
344
- const StatusErrorClass = statusMap[status];
345
- if (StatusErrorClass) {
346
- return yield* fail(
347
- new StatusErrorClass({
348
- message,
349
- retryAfter: parseRetryAfterForStatus(status, headers),
350
- }),
351
- );
352
- }
428
+ // 1. Per-operation typed error (matcher metadata on the class).
429
+ const typed = matchTypedError(
430
+ errorClasses,
431
+ status,
432
+ [
433
+ {
434
+ code: typeof env.code === "number" ? env.code : undefined,
435
+ message,
436
+ },
437
+ ],
438
+ { body: nonJson ? text : json, headers },
439
+ );
440
+ if (typed !== undefined) return { ok: false, error: typed };
353
441
 
354
- // 3. Unmapped 5xx (e.g. proxy-specific statuses) → retryable server
355
- // error rather than the unknown fallback.
356
- if (status >= 500) {
357
- return yield* fail(
358
- new InternalServerError({
359
- message,
360
- retryAfter: parseRetryAfterForStatus(status, headers),
361
- }),
362
- );
363
- }
442
+ // 2. Status-mapped class (retryAfter only stamps on retryable
443
+ // statuses -- parseRetryAfterForStatus gates on that).
444
+ const StatusErrorClass = statusMap[status];
445
+ if (StatusErrorClass) {
446
+ return {
447
+ ok: false,
448
+ error: new StatusErrorClass({
449
+ message,
450
+ retryAfter: parseRetryAfterForStatus(status, headers),
451
+ }),
452
+ };
453
+ }
364
454
 
365
- // 4. Provider fallback.
366
- return yield* fail(
367
- options.unknownError({
368
- status,
369
- code: env.code,
455
+ // 3. Unmapped 5xx (e.g. proxy-specific statuses) -> retryable server
456
+ // error rather than the unknown fallback.
457
+ if (status >= 500) {
458
+ return {
459
+ ok: false,
460
+ error: new InternalServerError({
370
461
  message,
371
- body: nonJson ? text : json,
372
- headers,
462
+ retryAfter: parseRetryAfterForStatus(status, headers),
373
463
  }),
374
- );
464
+ };
375
465
  }
376
466
 
377
- // 2xx: the response body IS the payload (no envelope). Wire→TS key
378
- // mapping is schema-driven; `RawResponseRoot` responses are the body
379
- // verbatim (mapKeys handles arrays/scalars structurally either way).
380
- // Strict mode (core/response-validation) checks the mapped body against
381
- // the output schema — a non-JSON body reaches it as a string and fails
382
- // there unless the operation's output is itself a string.
383
- let body: unknown = nonJson ? text : (json ?? {});
384
- if (options.transformResponse) body = options.transformResponse(body);
385
- const mapped = yield* validateResponse(
386
- outputAst,
387
- mapKeys(outputAst, body, "decode"),
388
- (cause) => options.parseError({ body: nonJson ? text : json, cause }),
389
- ).pipe(Effect.catch(fail));
390
- return wrapSensitive(outputAst, mapped);
391
- });
467
+ // 4. Provider fallback.
468
+ return {
469
+ ok: false,
470
+ error: options.unknownError({
471
+ status,
472
+ code: env.code,
473
+ message,
474
+ body: nonJson ? text : json,
475
+ headers,
476
+ }),
477
+ };
478
+ }
479
+
480
+ // 2xx: the response body IS the payload (no envelope). Wire->TS key
481
+ // mapping is schema-driven; `RawResponseRoot` responses are the body
482
+ // verbatim (mapKeys handles arrays/scalars structurally either way).
483
+ // Strict mode (core/response-validation) checks the mapped body against
484
+ // the output schema -- a non-JSON body reaches it as a string and fails
485
+ // there unless the operation's output is itself a string. For an output
486
+ // with sensitive members, a non-JSON body fails in every mode and parse
487
+ // errors withhold the body.
488
+ const plan = decodePlanFor(outputAst);
489
+ if (nonJson && plan.withholdBody) {
490
+ return {
491
+ ok: false,
492
+ error: options.parseError({ body: "[REDACTED]", cause: "Invalid JSON response" }),
493
+ };
494
+ }
495
+ let body: unknown = nonJson ? text : (json ?? {});
496
+ if (options.transformResponse) body = options.transformResponse(body);
497
+ const mapped = withResponseHeaders(
498
+ plan.headers,
499
+ plan.verbatim ? body : mapKeys(outputAst, body, "decode"),
500
+ headers,
501
+ );
502
+ const invalid = checkResponse(context, outputAst, mapped);
503
+ if (invalid !== undefined) {
504
+ return {
505
+ ok: false,
506
+ error: options.parseError({
507
+ body: plan.withholdBody ? "[REDACTED]" : nonJson ? text : json,
508
+ cause: plan.withholdBody ? withholdActual(invalid) : invalid,
509
+ }),
510
+ };
511
+ }
512
+ return { ok: true, value: plan.sensitive ? wrapSensitive(outputAst, mapped) : mapped };
513
+ };
514
+
515
+ const decodeResponse = (
516
+ context: Context.Context<any>,
517
+ response: HttpClientResponse.HttpClientResponse,
518
+ outputAst: AST.AST,
519
+ errorClasses: ReadonlyArray<unknown>,
520
+ ): Effect.Effect<unknown> =>
521
+ response.status >= 200 && response.status < 300 && decodePlanFor(outputAst).binary
522
+ ? Effect.map(Effect.orDie(response.arrayBuffer), (bytes) => new Uint8Array(bytes))
523
+ : Effect.matchEffect(response.text, {
524
+ onFailure: Effect.die,
525
+ onSuccess: (text) => {
526
+ const decoded = decodeText(
527
+ context,
528
+ response.status,
529
+ response.headers as Record<string, string | undefined>,
530
+ text ?? "",
531
+ outputAst,
532
+ errorClasses,
533
+ );
534
+ return decoded.ok ? Effect.succeed(decoded.value) : fail(decoded.error);
535
+ },
536
+ });
537
+
538
+ const call = (op: API.PreparedOperation, input: unknown): Effect.Effect<unknown> =>
539
+ Effect.withFiber((fiber) => {
540
+ const context = fiber.context as Context.Context<any>;
541
+ return withCredentials(context, (creds) => {
542
+ const request = requestFor(creds, input, op.inputAst);
543
+ if ("refused" in request) return fail(request.refused);
544
+ const client = Context.get(context, HttpClient.HttpClient);
545
+ return Effect.flatMap(client.execute(request), (response) =>
546
+ decodeResponse(context, response, op.outputAst, op.errors),
547
+ );
548
+ });
549
+ }) as Effect.Effect<unknown>;
392
550
 
393
551
  return Layer.succeed(
394
552
  API.Protocol,
395
553
  API.Protocol.of({
396
554
  // Erase encode's credentials requirement (resolved on the calling
397
555
  // fiber; see RestProtocolOptions.credentials).
398
- encode: (args) => encode(args) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
399
- decode,
556
+ encode: ({ input, inputAst }) =>
557
+ Effect.withFiber((fiber) =>
558
+ withCredentials(fiber.context as Context.Context<any>, (creds) => {
559
+ const request = requestFor(creds, input, inputAst);
560
+ return "refused" in request ? fail(request.refused) : Effect.succeed(request);
561
+ }),
562
+ ) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
563
+ decode: ({ response, outputAst, errors }) =>
564
+ Effect.withFiber((fiber) =>
565
+ decodeResponse(fiber.context as Context.Context<any>, response, outputAst, errors),
566
+ ),
567
+ call,
400
568
  }),
401
569
  );
402
570
  };