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

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 (235) hide show
  1. package/lib/api.d.ts +4 -4
  2. package/lib/api.d.ts.map +1 -1
  3. package/lib/api.js +3 -5
  4. package/lib/api.js.map +1 -1
  5. package/lib/category.d.ts.map +1 -1
  6. package/lib/category.js +3 -5
  7. package/lib/category.js.map +1 -1
  8. package/lib/codegen/boolean-string-enums.d.ts.map +1 -1
  9. package/lib/codegen/boolean-string-enums.js +2 -6
  10. package/lib/codegen/boolean-string-enums.js.map +1 -1
  11. package/lib/codegen/boolean-string-enums.test.js +3 -5
  12. package/lib/codegen/boolean-string-enums.test.js.map +1 -1
  13. package/lib/codegen/cli.d.ts +5 -4
  14. package/lib/codegen/cli.d.ts.map +1 -1
  15. package/lib/codegen/cli.js +12 -9
  16. package/lib/codegen/cli.js.map +1 -1
  17. package/lib/codegen/defer-naming.test.d.ts +2 -0
  18. package/lib/codegen/defer-naming.test.d.ts.map +1 -0
  19. package/lib/codegen/defer-naming.test.js +105 -0
  20. package/lib/codegen/defer-naming.test.js.map +1 -0
  21. package/lib/codegen/emit.d.ts.map +1 -1
  22. package/lib/codegen/emit.js +1 -3
  23. package/lib/codegen/emit.js.map +1 -1
  24. package/lib/codegen/format.d.ts +0 -12
  25. package/lib/codegen/format.d.ts.map +1 -1
  26. package/lib/codegen/format.js +10 -6
  27. package/lib/codegen/format.js.map +1 -1
  28. package/lib/codegen/generated-at.d.ts +29 -0
  29. package/lib/codegen/generated-at.d.ts.map +1 -0
  30. package/lib/codegen/generated-at.js +78 -0
  31. package/lib/codegen/generated-at.js.map +1 -0
  32. package/lib/codegen/generated-at.test.d.ts +2 -0
  33. package/lib/codegen/generated-at.test.d.ts.map +1 -0
  34. package/lib/codegen/generated-at.test.js +81 -0
  35. package/lib/codegen/generated-at.test.js.map +1 -0
  36. package/lib/codegen/generator.d.ts +4 -2
  37. package/lib/codegen/generator.d.ts.map +1 -1
  38. package/lib/codegen/generator.js +37 -75
  39. package/lib/codegen/generator.js.map +1 -1
  40. package/lib/codegen/generator.test.js +4 -9
  41. package/lib/codegen/generator.test.js.map +1 -1
  42. package/lib/codegen/graphql-client.d.ts.map +1 -1
  43. package/lib/codegen/graphql-client.js +12 -33
  44. package/lib/codegen/graphql-client.js.map +1 -1
  45. package/lib/codegen/graphql-client.test.js +4 -12
  46. package/lib/codegen/graphql-client.test.js.map +1 -1
  47. package/lib/codegen/graphql.d.ts.map +1 -1
  48. package/lib/codegen/graphql.js +7 -20
  49. package/lib/codegen/graphql.js.map +1 -1
  50. package/lib/codegen/model-diff.d.ts +10 -0
  51. package/lib/codegen/model-diff.d.ts.map +1 -0
  52. package/lib/codegen/model-diff.js +67 -0
  53. package/lib/codegen/model-diff.js.map +1 -0
  54. package/lib/codegen/naming.d.ts.map +1 -1
  55. package/lib/codegen/naming.js.map +1 -1
  56. package/lib/codegen/openapi-binary.test.js +1 -1
  57. package/lib/codegen/openapi-binary.test.js.map +1 -1
  58. package/lib/codegen/openapi-cli.d.ts +11 -11
  59. package/lib/codegen/openapi-cli.d.ts.map +1 -1
  60. package/lib/codegen/openapi-cli.js +26 -51
  61. package/lib/codegen/openapi-cli.js.map +1 -1
  62. package/lib/codegen/openapi.d.ts +9 -1
  63. package/lib/codegen/openapi.d.ts.map +1 -1
  64. package/lib/codegen/openapi.js +48 -42
  65. package/lib/codegen/openapi.js.map +1 -1
  66. package/lib/codegen/operations.d.ts.map +1 -1
  67. package/lib/codegen/operations.js.map +1 -1
  68. package/lib/codegen/pagination.d.ts.map +1 -1
  69. package/lib/codegen/pagination.js +2 -4
  70. package/lib/codegen/pagination.js.map +1 -1
  71. package/lib/codegen/patch-audit.d.ts +84 -0
  72. package/lib/codegen/patch-audit.d.ts.map +1 -0
  73. package/lib/codegen/patch-audit.js +366 -0
  74. package/lib/codegen/patch-audit.js.map +1 -0
  75. package/lib/codegen/patch-audit.test.d.ts +2 -0
  76. package/lib/codegen/patch-audit.test.d.ts.map +1 -0
  77. package/lib/codegen/patch-audit.test.js +141 -0
  78. package/lib/codegen/patch-audit.test.js.map +1 -0
  79. package/lib/codegen/patches.d.ts +59 -10
  80. package/lib/codegen/patches.d.ts.map +1 -1
  81. package/lib/codegen/patches.js +233 -63
  82. package/lib/codegen/patches.js.map +1 -1
  83. package/lib/codegen/patches.test.js +8 -4
  84. package/lib/codegen/patches.test.js.map +1 -1
  85. package/lib/codegen/prelude.js +1 -1
  86. package/lib/codegen/prelude.js.map +1 -1
  87. package/lib/codegen/proto.d.ts.map +1 -1
  88. package/lib/codegen/proto.js +2 -4
  89. package/lib/codegen/proto.js.map +1 -1
  90. package/lib/codegen/protocol-imports.test.d.ts +2 -0
  91. package/lib/codegen/protocol-imports.test.d.ts.map +1 -0
  92. package/lib/codegen/protocol-imports.test.js +36 -0
  93. package/lib/codegen/protocol-imports.test.js.map +1 -0
  94. package/lib/codegen/rewrite-operation-ids.d.ts +23 -0
  95. package/lib/codegen/rewrite-operation-ids.d.ts.map +1 -1
  96. package/lib/codegen/rewrite-operation-ids.js +97 -59
  97. package/lib/codegen/rewrite-operation-ids.js.map +1 -1
  98. package/lib/codegen/rewrite-operation-ids.test.js +19 -101
  99. package/lib/codegen/rewrite-operation-ids.test.js.map +1 -1
  100. package/lib/codegen/spec-path.d.ts +1 -1
  101. package/lib/codegen/spec-path.d.ts.map +1 -1
  102. package/lib/codegen/spec-path.js +1 -1
  103. package/lib/codegen/spec-path.js.map +1 -1
  104. package/lib/codegen/untagged-unions.test.js +1 -1
  105. package/lib/codegen/untagged-unions.test.js.map +1 -1
  106. package/lib/error-category.d.ts.map +1 -1
  107. package/lib/error-category.js.map +1 -1
  108. package/lib/errors.d.ts.map +1 -1
  109. package/lib/errors.js +7 -5
  110. package/lib/errors.js.map +1 -1
  111. package/lib/graphql.d.ts +4 -8
  112. package/lib/graphql.d.ts.map +1 -1
  113. package/lib/graphql.js +20 -48
  114. package/lib/graphql.js.map +1 -1
  115. package/lib/graphql.test.js +6 -6
  116. package/lib/graphql.test.js.map +1 -1
  117. package/lib/graphql.types.d.ts.map +1 -1
  118. package/lib/graphql.types.js.map +1 -1
  119. package/lib/json-patch.d.ts +13 -6
  120. package/lib/json-patch.d.ts.map +1 -1
  121. package/lib/json-patch.js +34 -19
  122. package/lib/json-patch.js.map +1 -1
  123. package/lib/json-patch.test.d.ts +2 -0
  124. package/lib/json-patch.test.d.ts.map +1 -0
  125. package/lib/json-patch.test.js +65 -0
  126. package/lib/json-patch.test.js.map +1 -0
  127. package/lib/pagination.d.ts.map +1 -1
  128. package/lib/pagination.js +6 -16
  129. package/lib/pagination.js.map +1 -1
  130. package/lib/pagination.test.js +3 -6
  131. package/lib/pagination.test.js.map +1 -1
  132. package/lib/protocol-http.d.ts +20 -1
  133. package/lib/protocol-http.d.ts.map +1 -1
  134. package/lib/protocol-http.js +41 -47
  135. package/lib/protocol-http.js.map +1 -1
  136. package/lib/protocol-http.test.js +20 -10
  137. package/lib/protocol-http.test.js.map +1 -1
  138. package/lib/protocol-rest.d.ts.map +1 -1
  139. package/lib/protocol-rest.js +9 -18
  140. package/lib/protocol-rest.js.map +1 -1
  141. package/lib/protocol-rest.test.d.ts +2 -0
  142. package/lib/protocol-rest.test.d.ts.map +1 -0
  143. package/lib/protocol-rest.test.js +498 -0
  144. package/lib/protocol-rest.test.js.map +1 -0
  145. package/lib/response-validation.d.ts.map +1 -1
  146. package/lib/response-validation.js.map +1 -1
  147. package/lib/response-validation.test.js +10 -5
  148. package/lib/response-validation.test.js.map +1 -1
  149. package/lib/retry-after.d.ts.map +1 -1
  150. package/lib/retry-after.js +1 -1
  151. package/lib/retry-after.js.map +1 -1
  152. package/lib/retry-after.test.d.ts +2 -0
  153. package/lib/retry-after.test.d.ts.map +1 -0
  154. package/lib/retry-after.test.js +204 -0
  155. package/lib/retry-after.test.js.map +1 -0
  156. package/lib/retry.d.ts.map +1 -1
  157. package/lib/retry.js +1 -2
  158. package/lib/retry.js.map +1 -1
  159. package/lib/retry.test.d.ts +2 -0
  160. package/lib/retry.test.d.ts.map +1 -0
  161. package/lib/retry.test.js +407 -0
  162. package/lib/retry.test.js.map +1 -0
  163. package/lib/sdks.test.d.ts +2 -0
  164. package/lib/sdks.test.d.ts.map +1 -0
  165. package/lib/sdks.test.js +76 -0
  166. package/lib/sdks.test.js.map +1 -0
  167. package/lib/testing.d.ts +2 -2
  168. package/lib/testing.d.ts.map +1 -1
  169. package/lib/testing.js +1 -1
  170. package/lib/testing.js.map +1 -1
  171. package/lib/trait.d.ts.map +1 -1
  172. package/lib/trait.js.map +1 -1
  173. package/lib/xml.d.ts.map +1 -1
  174. package/lib/xml.js +3 -7
  175. package/lib/xml.js.map +1 -1
  176. package/lib/xml.test.js +11 -12
  177. package/lib/xml.test.js.map +1 -1
  178. package/package.json +7 -10
  179. package/src/api.ts +38 -55
  180. package/src/category.ts +21 -50
  181. package/src/codegen/boolean-string-enums.test.ts +12 -28
  182. package/src/codegen/boolean-string-enums.ts +2 -10
  183. package/src/codegen/cli.ts +29 -47
  184. package/src/codegen/defer-naming.test.ts +113 -0
  185. package/src/codegen/emit.ts +2 -5
  186. package/src/codegen/format.ts +12 -10
  187. package/src/codegen/generated-at.test.ts +89 -0
  188. package/src/codegen/generated-at.ts +88 -0
  189. package/src/codegen/generator.test.ts +8 -22
  190. package/src/codegen/generator.ts +72 -191
  191. package/src/codegen/graphql-client.test.ts +12 -42
  192. package/src/codegen/graphql-client.ts +30 -95
  193. package/src/codegen/graphql.ts +22 -94
  194. package/src/codegen/model-diff.ts +67 -0
  195. package/src/codegen/naming.ts +1 -2
  196. package/src/codegen/openapi-binary.test.ts +5 -12
  197. package/src/codegen/openapi-cli.ts +38 -79
  198. package/src/codegen/openapi.ts +79 -136
  199. package/src/codegen/operations.ts +2 -5
  200. package/src/codegen/pagination.ts +4 -11
  201. package/src/codegen/patch-audit.test.ts +160 -0
  202. package/src/codegen/patch-audit.ts +480 -0
  203. package/src/codegen/patches.test.ts +14 -21
  204. package/src/codegen/patches.ts +313 -103
  205. package/src/codegen/prelude.ts +1 -1
  206. package/src/codegen/proto.ts +18 -54
  207. package/src/codegen/protocol-imports.test.ts +39 -0
  208. package/src/codegen/rewrite-operation-ids.test.ts +23 -114
  209. package/src/codegen/rewrite-operation-ids.ts +111 -98
  210. package/src/codegen/spec-path.ts +3 -6
  211. package/src/codegen/untagged-unions.test.ts +3 -7
  212. package/src/error-category.ts +5 -17
  213. package/src/errors.ts +16 -31
  214. package/src/graphql.test.ts +6 -8
  215. package/src/graphql.ts +76 -219
  216. package/src/graphql.types.ts +10 -25
  217. package/src/json-patch.test.ts +77 -0
  218. package/src/json-patch.ts +54 -60
  219. package/src/pagination.test.ts +13 -35
  220. package/src/pagination.ts +44 -111
  221. package/src/protocol-http.test.ts +36 -30
  222. package/src/protocol-http.ts +73 -138
  223. package/src/protocol-rest.test.ts +703 -0
  224. package/src/protocol-rest.ts +24 -62
  225. package/src/response-validation.test.ts +12 -18
  226. package/src/response-validation.ts +3 -12
  227. package/src/retry-after.test.ts +267 -0
  228. package/src/retry-after.ts +4 -10
  229. package/src/retry.test.ts +566 -0
  230. package/src/retry.ts +6 -21
  231. package/src/sdks.test.ts +87 -0
  232. package/src/testing.ts +4 -10
  233. package/src/trait.ts +21 -67
  234. package/src/xml.test.ts +15 -33
  235. package/src/xml.ts +9 -25
@@ -26,13 +26,13 @@
26
26
  * in the provider package — via these options or a hand-written protocol.
27
27
  */
28
28
  import * as Effect from "effect/Effect";
29
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest";
30
+ import type * as HttpClientResponse from "effect/http/HttpClientResponse";
29
31
  import * as Layer from "effect/Layer";
30
32
  import * as Redacted from "effect/Redacted";
31
33
  import type * as AST from "effect/SchemaAST";
32
- import type * as HttpClientRequest from "effect/http/HttpClientRequest";
33
- import type * as HttpClientResponse from "effect/http/HttpClientResponse";
34
34
  import * as API from "./api.ts";
35
- import { httpSymbol, makeAnnotation, type HttpTrait } from "./trait.ts";
35
+ import { HTTP_STATUS_MAP, InternalServerError } from "./errors.ts";
36
36
  import {
37
37
  buildRequest,
38
38
  getAnn,
@@ -43,17 +43,15 @@ import {
43
43
  matchTypedError,
44
44
  resolveNode,
45
45
  } from "./protocol-http.ts";
46
- import { HTTP_STATUS_MAP, InternalServerError } from "./errors.ts";
47
- import { parseRetryAfterForStatus } from "./retry-after.ts";
48
46
  import { validateResponse } from "./response-validation.ts";
47
+ import { parseRetryAfterForStatus } from "./retry-after.ts";
48
+ import { httpSymbol, makeAnnotation, type HttpTrait } from "./trait.ts";
49
49
 
50
50
  // =============================================================================
51
51
  // Traits
52
52
  // =============================================================================
53
53
 
54
- export const sensitiveValueSymbol = Symbol.for(
55
- "@distilled.cloud/core/sensitive-value",
56
- );
54
+ export const sensitiveValueSymbol = Symbol.for("@distilled.cloud/core/sensitive-value");
57
55
  /**
58
56
  * Marks a string member as sensitive (mirrors `smithy.api#sensitive`).
59
57
  * The REST protocol wraps decoded values in `Redacted` on the way out and
@@ -61,34 +59,25 @@ export const sensitiveValueSymbol = Symbol.for(
61
59
  * serialization). Takes an ignored argument so generators can inline the
62
60
  * smithy trait value (`T.SensitiveValue({})`).
63
61
  */
64
- export const SensitiveValue = (_value?: unknown) =>
65
- makeAnnotation(sensitiveValueSymbol, true);
62
+ export const SensitiveValue = (_value?: unknown) => makeAnnotation(sensitiveValueSymbol, true);
66
63
 
67
- export const rawResponseSymbol = Symbol.for(
68
- "@distilled.cloud/core/raw-response",
69
- );
64
+ export const rawResponseSymbol = Symbol.for("@distilled.cloud/core/raw-response");
70
65
  /**
71
66
  * Marks the sole output member that carries a bare (array/scalar) response
72
67
  * body (mirrors `com.distilled.openapi#rawResponse`).
73
68
  */
74
- export const RawResponse = (_value?: unknown) =>
75
- makeAnnotation(rawResponseSymbol, true);
69
+ export const RawResponse = (_value?: unknown) => makeAnnotation(rawResponseSymbol, true);
76
70
 
77
- export const rawResponseRootSymbol = Symbol.for(
78
- "@distilled.cloud/core/raw-response-root",
79
- );
71
+ export const rawResponseRootSymbol = Symbol.for("@distilled.cloud/core/raw-response-root");
80
72
  /**
81
73
  * Marks a response schema whose ENTIRE value is the response body (the
82
74
  * generator's `rootPipe` for synthesized bare-payload wrappers): the emitted
83
75
  * response type IS the payload type and the protocol returns the mapped body
84
76
  * directly.
85
77
  */
86
- export const RawResponseRoot = () =>
87
- makeAnnotation(rawResponseRootSymbol, true);
78
+ export const RawResponseRoot = () => makeAnnotation(rawResponseRootSymbol, true);
88
79
 
89
- export const binaryResponseSymbol = Symbol.for(
90
- "@distilled.cloud/core/binary-response",
91
- );
80
+ export const binaryResponseSymbol = Symbol.for("@distilled.cloud/core/binary-response");
92
81
 
93
82
  /** Decode a successful raw binary response as bytes, without text conversion. */
94
83
  export const BinaryResponse = () => makeAnnotation(binaryResponseSymbol, true);
@@ -102,8 +91,7 @@ const isPlainObject = (v: unknown): v is Record<string, unknown> =>
102
91
  typeof v === "object" &&
103
92
  !Array.isArray(v) &&
104
93
  !isOpaqueValue(v) &&
105
- (Object.getPrototypeOf(v) === Object.prototype ||
106
- Object.getPrototypeOf(v) === null);
94
+ (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
107
95
 
108
96
  /**
109
97
  * Deep-unwrap `Redacted` values in an input (plain objects/arrays only —
@@ -137,10 +125,7 @@ export const wrapSensitive = (ast: AST.AST, value: unknown): unknown => {
137
125
  const node = resolveNode(ast);
138
126
  if (node._tag === "Union") {
139
127
  // Redact every possible sensitive member, including in partial responses.
140
- return node.types.reduce<unknown>(
141
- (redacted, arm) => wrapSensitive(arm, redacted),
142
- value,
143
- );
128
+ return node.types.reduce<unknown>((redacted, arm) => wrapSensitive(arm, redacted), value);
144
129
  }
145
130
  if (node._tag === "Arrays") {
146
131
  if (!Array.isArray(value)) return value;
@@ -157,10 +142,7 @@ export const wrapSensitive = (ast: AST.AST, value: unknown): unknown => {
157
142
  const prop = byName.get(k);
158
143
  if (!prop) {
159
144
  out[k] = v;
160
- } else if (
161
- getPropAnn(prop, sensitiveValueSymbol) !== undefined &&
162
- typeof v === "string"
163
- ) {
145
+ } else if (getPropAnn(prop, sensitiveValueSymbol) !== undefined && typeof v === "string") {
164
146
  out[k] = Redacted.make(v);
165
147
  } else {
166
148
  out[k] = wrapSensitive(prop.type, v);
@@ -256,16 +238,9 @@ export interface RestProtocolOptions<C> {
256
238
  const defaultErrorEnvelope = (body: unknown): RestErrorEnvelope | undefined => {
257
239
  if (body === null || typeof body !== "object") return undefined;
258
240
  const b = body as Record<string, unknown>;
259
- const code =
260
- typeof b.code === "string" || typeof b.code === "number"
261
- ? b.code
262
- : undefined;
241
+ const code = typeof b.code === "string" || typeof b.code === "number" ? b.code : undefined;
263
242
  const message =
264
- typeof b.message === "string"
265
- ? b.message
266
- : typeof b.error === "string"
267
- ? b.error
268
- : undefined;
243
+ typeof b.message === "string" ? b.message : typeof b.error === "string" ? b.error : undefined;
269
244
  return { code, message };
270
245
  };
271
246
 
@@ -273,29 +248,19 @@ const defaultErrorEnvelope = (body: unknown): RestErrorEnvelope | undefined => {
273
248
  // but REST failures are real typed errors that operations re-surface via
274
249
  // their `errors: [...]` lists. Fail with the instance and erase the type
275
250
  // here; the generated operation annotations reintroduce it for callers.
276
- const fail = (e: unknown): Effect.Effect<never> =>
277
- Effect.fail(e) as Effect.Effect<never>;
251
+ const fail = (e: unknown): Effect.Effect<never> => Effect.fail(e) as Effect.Effect<never>;
278
252
 
279
253
  /**
280
254
  * Build a `Layer<Protocol>` for a simple REST JSON API. Assign the result to
281
255
  * a module-level const in the provider's `protocol.ts` — `API.make` memoizes
282
256
  * protocol layers by value identity.
283
257
  */
284
- export const makeRestProtocol = <C>(
285
- options: RestProtocolOptions<C>,
286
- ): Layer.Layer<API.Protocol> => {
258
+ export const makeRestProtocol = <C>(options: RestProtocolOptions<C>): Layer.Layer<API.Protocol> => {
287
259
  const errorEnvelope = options.errorEnvelope ?? defaultErrorEnvelope;
288
- const statusMap: Readonly<
289
- Record<number, (new (args: any) => any) | undefined>
290
- > = options.statusMap ?? HTTP_STATUS_MAP;
260
+ const statusMap: Readonly<Record<number, (new (args: any) => any) | undefined>> =
261
+ options.statusMap ?? HTTP_STATUS_MAP;
291
262
 
292
- const encode = ({
293
- input,
294
- inputAst,
295
- }: {
296
- readonly input: unknown;
297
- readonly inputAst: AST.AST;
298
- }) =>
263
+ const encode = ({ input, inputAst }: { readonly input: unknown; readonly inputAst: AST.AST }) =>
299
264
  Effect.gen(function* () {
300
265
  const creds = yield* options.credentials as Effect.Effect<C>;
301
266
  const http = getAnn(inputAst, httpSymbol) as HttpTrait | undefined;
@@ -358,9 +323,7 @@ export const makeRestProtocol = <C>(
358
323
 
359
324
  if (status >= 400) {
360
325
  const env = (nonJson ? undefined : errorEnvelope(json)) ?? {};
361
- const message =
362
- env.message ??
363
- (nonJson && text.trim() ? text.trim() : `HTTP ${status}`);
326
+ const message = env.message ?? (nonJson && text.trim() ? text.trim() : `HTTP ${status}`);
364
327
 
365
328
  // 1. Per-operation typed error (matcher metadata on the class).
366
329
  const typed = matchTypedError(
@@ -432,8 +395,7 @@ export const makeRestProtocol = <C>(
432
395
  API.Protocol.of({
433
396
  // Erase encode's credentials requirement (resolved on the calling
434
397
  // fiber; see RestProtocolOptions.credentials).
435
- encode: (args) =>
436
- encode(args) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
398
+ encode: (args) => encode(args) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
437
399
  decode,
438
400
  }),
439
401
  );
@@ -1,22 +1,21 @@
1
- import { describe, expect, test } from "bun:test";
2
1
  import * as Effect from "effect/Effect";
3
- import * as Layer from "effect/Layer";
4
- import * as Schema from "effect/Schema";
5
2
  import * as HttpClientRequest from "effect/http/HttpClientRequest";
6
3
  import * as HttpClientResponse from "effect/http/HttpClientResponse";
4
+ import * as Layer from "effect/Layer";
5
+ import * as Schema from "effect/Schema";
6
+ import { describe, expect, test } from "vitest";
7
7
  import * as API from "./api.ts";
8
8
  import { makeRestProtocol } from "./protocol-rest.ts";
9
9
  import * as ResponseValidation from "./response-validation.ts";
10
10
 
11
- class TestParseError extends Schema.TaggedError<TestParseError>()(
12
- "TestParseError",
13
- { body: Schema.Unknown, cause: Schema.Unknown },
14
- ) {}
11
+ class TestParseError extends Schema.TaggedError<TestParseError>()("TestParseError", {
12
+ body: Schema.Unknown,
13
+ cause: Schema.Unknown,
14
+ }) {}
15
15
 
16
- class TestUnknownError extends Schema.TaggedError<TestUnknownError>()(
17
- "TestUnknownError",
18
- { message: Schema.String },
19
- ) {}
16
+ class TestUnknownError extends Schema.TaggedError<TestUnknownError>()("TestUnknownError", {
17
+ message: Schema.String,
18
+ }) {}
20
19
 
21
20
  const TestProtocol = makeRestProtocol<{}>({
22
21
  credentials: Effect.succeed({}),
@@ -33,10 +32,7 @@ const decode = (body: string) =>
33
32
  const protocol = yield* API.Protocol;
34
33
  const request = HttpClientRequest.get("https://api.test/thing");
35
34
  return yield* protocol.decode({
36
- response: HttpClientResponse.fromWeb(
37
- request,
38
- new Response(body, { status: 200 }),
39
- ),
35
+ response: HttpClientResponse.fromWeb(request, new Response(body, { status: 200 })),
40
36
  outputAst: Output.ast,
41
37
  errors: [],
42
38
  config: {},
@@ -44,9 +40,7 @@ const decode = (body: string) =>
44
40
  }).pipe(Effect.provide(TestProtocol));
45
41
 
46
42
  const run = <A, E>(effect: Effect.Effect<A, E>, layer?: Layer.Layer<never>) =>
47
- Effect.runPromise(
48
- Effect.result(layer ? effect.pipe(Effect.provide(layer)) : effect),
49
- );
43
+ Effect.runPromise(Effect.result(layer ? effect.pipe(Effect.provide(layer)) : effect));
50
44
 
51
45
  describe("makeRestProtocol response validation", () => {
52
46
  test("lenient (default) returns a non-JSON 2xx body as text", async () => {
@@ -46,16 +46,10 @@ export const ResponseValidation = Context.Reference<Mode>(
46
46
  );
47
47
 
48
48
  /** Decode every 2xx response against its output schema; fail on mismatch. */
49
- export const strict: Layer.Layer<never> = Layer.succeed(
50
- ResponseValidation,
51
- "strict",
52
- );
49
+ export const strict: Layer.Layer<never> = Layer.succeed(ResponseValidation, "strict");
53
50
 
54
51
  /** Return 2xx responses as read, without checking them against the schema. */
55
- export const lenient: Layer.Layer<never> = Layer.succeed(
56
- ResponseValidation,
57
- "lenient",
58
- );
52
+ export const lenient: Layer.Layer<never> = Layer.succeed(ResponseValidation, "lenient");
59
53
 
60
54
  /** Whether the calling fiber is in strict mode. */
61
55
  export const isStrict: Effect.Effect<boolean> = Effect.map(
@@ -109,8 +103,5 @@ export const validateResponse = <E>(
109
103
  Effect.flatMap(ResponseValidation, (mode) =>
110
104
  mode === "lenient"
111
105
  ? Effect.succeed(value)
112
- : decoderFor(outputAst)(value).pipe(
113
- Effect.mapError(onError),
114
- Effect.as(value),
115
- ),
106
+ : decoderFor(outputAst)(value).pipe(Effect.mapError(onError), Effect.as(value)),
116
107
  );
@@ -0,0 +1,267 @@
1
+ import * as Clock from "effect/Clock";
2
+ import * as Duration from "effect/Duration";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Fiber from "effect/Fiber";
5
+ import * as HttpClient from "effect/http/HttpClient";
6
+ import * as HttpClientResponse from "effect/http/HttpClientResponse";
7
+ import * as Layer from "effect/Layer";
8
+ import * as Schema from "effect/Schema";
9
+ import * as TestClock from "effect/testing/TestClock";
10
+ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
11
+ import * as API from "./api.ts";
12
+ import { RETRYABLE_HTTP_STATUSES } from "./errors.ts";
13
+ import { makeRestProtocol } from "./protocol-rest.ts";
14
+ import {
15
+ parseRatelimit,
16
+ parseRetryAfter,
17
+ parseRetryAfterForStatus,
18
+ parseServerRetryHint,
19
+ } from "./retry-after.ts";
20
+ import * as Retry from "./retry.ts";
21
+ import * as S from "./schema.ts";
22
+ import * as T from "./trait.ts";
23
+
24
+ const NOW = Date.parse("2026-10-05T12:00:00Z");
25
+
26
+ const millis = (d: Duration.Duration | undefined) =>
27
+ d === undefined ? undefined : Duration.toMillis(d);
28
+
29
+ beforeEach(() => {
30
+ vi.spyOn(Date, "now").mockReturnValue(NOW);
31
+ // Pin retry jitter to zero so end-to-end delays are exact.
32
+ vi.spyOn(Math, "random").mockReturnValue(0);
33
+ });
34
+
35
+ afterEach(() => {
36
+ vi.restoreAllMocks();
37
+ });
38
+
39
+ describe("parseRetryAfter delay-seconds", () => {
40
+ test("parses a non-negative integer number of seconds", () => {
41
+ expect(millis(parseRetryAfter({ "retry-after": "120" }))).toBe(120_000);
42
+ expect(millis(parseRetryAfter({ "retry-after": "1" }))).toBe(1_000);
43
+ });
44
+
45
+ test("zero seconds is a zero duration, not absent", () => {
46
+ expect(millis(parseRetryAfter({ "retry-after": "0" }))).toBe(0);
47
+ });
48
+
49
+ test("surrounding whitespace is ignored", () => {
50
+ expect(millis(parseRetryAfter({ "retry-after": " 5\t" }))).toBe(5_000);
51
+ });
52
+
53
+ test("leading zeros are accepted", () => {
54
+ expect(millis(parseRetryAfter({ "retry-after": "007" }))).toBe(7_000);
55
+ });
56
+
57
+ test("signed or fractional numbers are rejected", () => {
58
+ for (const raw of ["-5", "+5", "1.5", "-0", "0.0"]) {
59
+ expect(parseRetryAfter({ "retry-after": raw })).toBeUndefined();
60
+ }
61
+ });
62
+ });
63
+
64
+ describe("parseRetryAfter HTTP-date", () => {
65
+ test("parses an IMF-fixdate relative to now", () => {
66
+ expect(millis(parseRetryAfter({ "retry-after": "Mon, 05 Oct 2026 12:00:30 GMT" }))).toBe(
67
+ 30_000,
68
+ );
69
+ });
70
+
71
+ test("parses the obsolete RFC 850 and asctime forms", () => {
72
+ expect(millis(parseRetryAfter({ "retry-after": "Monday, 05-Oct-26 12:01:00 GMT" }))).toBe(
73
+ 60_000,
74
+ );
75
+ expect(millis(parseRetryAfter({ "retry-after": "Mon Oct 5 12:00:10 2026 GMT" }))).toBe(10_000);
76
+ });
77
+
78
+ test("a date in the past is a zero duration", () => {
79
+ expect(millis(parseRetryAfter({ "retry-after": "Mon, 05 Oct 2026 11:00:00 GMT" }))).toBe(0);
80
+ });
81
+
82
+ test("a date equal to now is a zero duration", () => {
83
+ expect(millis(parseRetryAfter({ "retry-after": "Mon, 05 Oct 2026 12:00:00 GMT" }))).toBe(0);
84
+ });
85
+ });
86
+
87
+ describe("parseRetryAfter absent or invalid headers", () => {
88
+ test("no header bag, or no retry-after header, is absent", () => {
89
+ expect(parseRetryAfter(undefined)).toBeUndefined();
90
+ expect(parseRetryAfter({})).toBeUndefined();
91
+ expect(parseRetryAfter({ "retry-after": undefined })).toBeUndefined();
92
+ });
93
+
94
+ test("empty and whitespace-only values are absent", () => {
95
+ expect(parseRetryAfter({ "retry-after": "" })).toBeUndefined();
96
+ expect(parseRetryAfter({ "retry-after": " " })).toBeUndefined();
97
+ });
98
+
99
+ test("unparseable values are absent", () => {
100
+ for (const raw of ["soon", "5s", "PT5S", "tomorrow at noon"]) {
101
+ expect(parseRetryAfter({ "retry-after": raw })).toBeUndefined();
102
+ }
103
+ });
104
+
105
+ test("only the lowercase header key is read", () => {
106
+ expect(parseRetryAfter({ "Retry-After": "5" })).toBeUndefined();
107
+ });
108
+ });
109
+
110
+ describe("parseRatelimit", () => {
111
+ test("returns the reset time when the remaining quota is zero", () => {
112
+ expect(millis(parseRatelimit({ ratelimit: "r=0, t=30" }))).toBe(30_000);
113
+ expect(millis(parseRatelimit({ ratelimit: "limit=100, remaining=0, reset=30" }))).toBe(30_000);
114
+ expect(millis(parseRatelimit({ ratelimit: '"default";r=0;t=30' }))).toBe(30_000);
115
+ });
116
+
117
+ test("tolerates whitespace and key case", () => {
118
+ expect(millis(parseRatelimit({ ratelimit: " R = 0 ; T = 12 " }))).toBe(12_000);
119
+ });
120
+
121
+ test("is absent while quota remains", () => {
122
+ expect(parseRatelimit({ ratelimit: "r=5, t=30" })).toBeUndefined();
123
+ expect(parseRatelimit({ ratelimit: "limit=100, remaining=1, reset=30" })).toBeUndefined();
124
+ expect(parseRatelimit({ ratelimit: '"default";r=2;t=30' })).toBeUndefined();
125
+ });
126
+
127
+ test("is absent unless remaining is present and exactly zero", () => {
128
+ expect(parseRatelimit({ ratelimit: "t=30" })).toBeUndefined();
129
+ expect(parseRatelimit({ ratelimit: "limit=100, reset=30" })).toBeUndefined();
130
+ expect(parseRatelimit({ ratelimit: '"default";t=30' })).toBeUndefined();
131
+ expect(parseRatelimit({ ratelimit: "r=-1, t=30" })).toBeUndefined();
132
+ expect(parseRatelimit({ ratelimit: "remaining=-1, reset=30" })).toBeUndefined();
133
+ expect(parseRatelimit({ ratelimit: "r=0.5, t=30" })).toBeUndefined();
134
+ expect(parseRatelimit({ ratelimit: "r=none, t=30" })).toBeUndefined();
135
+ });
136
+
137
+ test("is absent without a usable reset", () => {
138
+ expect(parseRatelimit({ ratelimit: "r=0" })).toBeUndefined();
139
+ expect(parseRatelimit({ ratelimit: "r=0, t=-1" })).toBeUndefined();
140
+ expect(parseRatelimit({ ratelimit: "r=0, t=later" })).toBeUndefined();
141
+ });
142
+
143
+ test("is absent when the header is missing or empty", () => {
144
+ expect(parseRatelimit(undefined)).toBeUndefined();
145
+ expect(parseRatelimit({})).toBeUndefined();
146
+ expect(parseRatelimit({ ratelimit: "" })).toBeUndefined();
147
+ });
148
+ });
149
+
150
+ describe("parseServerRetryHint", () => {
151
+ test("prefers Retry-After over RateLimit", () => {
152
+ expect(millis(parseServerRetryHint({ "retry-after": "5", ratelimit: "r=0, t=30" }))).toBe(
153
+ 5_000,
154
+ );
155
+ });
156
+
157
+ test("falls back to RateLimit when Retry-After is absent or invalid", () => {
158
+ expect(millis(parseServerRetryHint({ ratelimit: "r=0, t=30" }))).toBe(30_000);
159
+ expect(millis(parseServerRetryHint({ "retry-after": "soon", ratelimit: "r=0, t=30" }))).toBe(
160
+ 30_000,
161
+ );
162
+ });
163
+
164
+ test("is absent when neither header yields a value", () => {
165
+ expect(parseServerRetryHint({ ratelimit: "r=3, t=30" })).toBeUndefined();
166
+ expect(parseServerRetryHint({ ratelimit: "t=30" })).toBeUndefined();
167
+ expect(parseServerRetryHint(undefined)).toBeUndefined();
168
+ });
169
+ });
170
+
171
+ describe("parseRetryAfterForStatus", () => {
172
+ test("returns the hint for every retryable status", () => {
173
+ for (const status of RETRYABLE_HTTP_STATUSES) {
174
+ expect(millis(parseRetryAfterForStatus(status, { "retry-after": "4" }))).toBe(4_000);
175
+ }
176
+ });
177
+
178
+ test("ignores hints on non-retryable statuses", () => {
179
+ for (const status of [200, 400, 401, 403, 404, 409, 422, 501, 521]) {
180
+ expect(parseRetryAfterForStatus(status, { "retry-after": "4" })).toBeUndefined();
181
+ }
182
+ });
183
+ });
184
+
185
+ // =============================================================================
186
+ // End to end: header → error.retryAfter → retry delay
187
+ // =============================================================================
188
+
189
+ class TestRetry extends Retry.makeRetryService("RetryAfterTest/Retry") {}
190
+
191
+ class UnknownTestError extends Schema.TaggedError<UnknownTestError>()("UnknownTestError", {
192
+ message: Schema.String,
193
+ }) {}
194
+
195
+ const TestProtocol = makeRestProtocol<{}>({
196
+ credentials: Effect.succeed({}),
197
+ baseUrl: () => "https://api.test",
198
+ headers: () => ({}),
199
+ unknownError: ({ message }) => new UnknownTestError({ message }),
200
+ parseError: ({ body }) => new UnknownTestError({ message: String(body) }),
201
+ });
202
+
203
+ const getThing = API.make(() => ({
204
+ input: S.Struct({}).pipe(T.Http({ method: "GET", uri: "/thing" })),
205
+ output: S.Struct({ ok: S.optional(S.Boolean) }),
206
+ protocol: TestProtocol,
207
+ retry: TestRetry,
208
+ })) as unknown as (input: Record<string, unknown>) => Effect.Effect<any, any, any>;
209
+
210
+ /** First response fails with `status`/`headers`, the second succeeds; returns attempt times. */
211
+ const retryDelays = async (status: number, headers: Record<string, string>) => {
212
+ const times: Array<number> = [];
213
+ const client = Layer.succeed(
214
+ HttpClient.HttpClient,
215
+ HttpClient.make((request) =>
216
+ Effect.gen(function* () {
217
+ times.push(yield* Clock.currentTimeMillis);
218
+ const response =
219
+ times.length === 1
220
+ ? new Response(JSON.stringify({ message: "nope" }), { status, headers })
221
+ : new Response(JSON.stringify({ ok: true }), { status: 200 });
222
+ return HttpClientResponse.fromWeb(request, response);
223
+ }),
224
+ ),
225
+ );
226
+ await Effect.runPromise(
227
+ Effect.gen(function* () {
228
+ const fiber = yield* Effect.forkChild(Effect.result(getThing({})));
229
+ yield* TestClock.adjust(Duration.hours(1));
230
+ return yield* Fiber.join(fiber);
231
+ }).pipe(Effect.provide(Layer.mergeAll(client, TestClock.layer()))) as Effect.Effect<
232
+ any,
233
+ never,
234
+ never
235
+ >,
236
+ );
237
+ return times.slice(1).map((t, i) => t - times[i]!);
238
+ };
239
+
240
+ describe("Retry-After feeding the default retry delay", () => {
241
+ test("delay-seconds replaces the default backoff", async () => {
242
+ expect(await retryDelays(503, { "retry-after": "3" })).toEqual([3_000]);
243
+ });
244
+
245
+ test("an HTTP-date waits until that date", async () => {
246
+ expect(await retryDelays(429, { "retry-after": "Mon, 05 Oct 2026 12:00:04 GMT" })).toEqual([
247
+ 4_000,
248
+ ]);
249
+ });
250
+
251
+ test("a RateLimit reset is used when Retry-After is absent", async () => {
252
+ expect(await retryDelays(429, { ratelimit: "r=0, t=2" })).toEqual([2_000]);
253
+ });
254
+
255
+ test("an invalid header falls back to the default backoff", async () => {
256
+ expect(await retryDelays(503, { "retry-after": "soon" })).toEqual([250]);
257
+ expect(await retryDelays(429, { "retry-after": "soon" })).toEqual([500]);
258
+ });
259
+
260
+ test("a RateLimit header with quota left falls back to the default backoff", async () => {
261
+ expect(await retryDelays(503, { ratelimit: "r=4, t=30" })).toEqual([250]);
262
+ });
263
+
264
+ test("a hint on a non-retryable status neither stamps nor triggers a retry", async () => {
265
+ expect(await retryDelays(404, { "retry-after": "3" })).toEqual([]);
266
+ });
267
+ });
@@ -34,9 +34,7 @@ export type Headers = Record<string, string | undefined> | undefined;
34
34
  *
35
35
  * Returns `undefined` when the header is missing or unparseable.
36
36
  */
37
- export const parseRetryAfter = (
38
- headers: Headers,
39
- ): Duration.Duration | undefined => {
37
+ export const parseRetryAfter = (headers: Headers): Duration.Duration | undefined => {
40
38
  const raw = headers?.["retry-after"];
41
39
  if (!raw) return undefined;
42
40
  const trimmed = raw.trim();
@@ -77,9 +75,7 @@ export const parseRetryAfter = (
77
75
  * `r` (remaining quota) is present and equals `0` — i.e., we're actually
78
76
  * rate-limited right now. Returns `undefined` otherwise.
79
77
  */
80
- export const parseRatelimit = (
81
- headers: Headers,
82
- ): Duration.Duration | undefined => {
78
+ export const parseRatelimit = (headers: Headers): Duration.Duration | undefined => {
83
79
  const raw = headers?.["ratelimit"];
84
80
  if (!raw) return undefined;
85
81
 
@@ -99,7 +95,7 @@ export const parseRatelimit = (
99
95
  else if (key === "t" || key === "reset") reset = num;
100
96
  }
101
97
 
102
- if (remaining !== undefined && remaining > 0) return undefined;
98
+ if (remaining !== 0) return undefined;
103
99
  if (reset === undefined || reset < 0) return undefined;
104
100
  return Duration.seconds(reset);
105
101
  };
@@ -108,9 +104,7 @@ export const parseRatelimit = (
108
104
  * Convenience: try `Retry-After` first, then `RateLimit`. Returns the first
109
105
  * successful parse, or `undefined` if neither header yields a usable value.
110
106
  */
111
- export const parseServerRetryHint = (
112
- headers: Headers,
113
- ): Duration.Duration | undefined =>
107
+ export const parseServerRetryHint = (headers: Headers): Duration.Duration | undefined =>
114
108
  parseRetryAfter(headers) ?? parseRatelimit(headers);
115
109
 
116
110
  /**