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

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