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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. package/LICENSE +201 -0
  2. package/lib/_bundle/aws.js +2 -0
  3. package/lib/_bundle/aws.js.map +1 -0
  4. package/lib/_bundle/base.js +5 -0
  5. package/lib/_bundle/base.js.map +1 -0
  6. package/lib/_bundle/graphql.js +3 -0
  7. package/lib/_bundle/graphql.js.map +1 -0
  8. package/lib/_bundle/grpc.js +2 -0
  9. package/lib/_bundle/grpc.js.map +1 -0
  10. package/lib/_bundle/rest.js +2 -0
  11. package/lib/_bundle/rest.js.map +1 -0
  12. package/lib/_bundle/xml.js +4 -0
  13. package/lib/_bundle/xml.js.map +1 -0
  14. package/lib/annotations.d.ts +17 -0
  15. package/lib/annotations.d.ts.map +1 -0
  16. package/lib/annotations.js +2 -0
  17. package/lib/annotations.js.map +1 -0
  18. package/lib/api.d.ts +174 -18
  19. package/lib/api.d.ts.map +1 -1
  20. package/lib/api.js +1 -178
  21. package/lib/category.d.ts +4 -4
  22. package/lib/category.d.ts.map +1 -1
  23. package/lib/category.js +1 -280
  24. package/lib/chunks.d.ts +3 -0
  25. package/lib/chunks.d.ts.map +1 -0
  26. package/lib/chunks.js +1 -0
  27. package/lib/config.d.ts +68 -0
  28. package/lib/config.d.ts.map +1 -0
  29. package/lib/config.js +1 -0
  30. package/lib/crypto.d.ts +76 -0
  31. package/lib/crypto.d.ts.map +1 -0
  32. package/lib/crypto.js +1 -0
  33. package/lib/error-category.d.ts +1 -1
  34. package/lib/error-category.d.ts.map +1 -1
  35. package/lib/error-category.js +1 -46
  36. package/lib/errors.d.ts +64 -72
  37. package/lib/errors.d.ts.map +1 -1
  38. package/lib/errors.js +1 -186
  39. package/lib/graphql.d.ts +403 -0
  40. package/lib/graphql.d.ts.map +1 -0
  41. package/lib/graphql.js +1 -0
  42. package/lib/graphql.types.d.ts +12 -0
  43. package/lib/graphql.types.d.ts.map +1 -0
  44. package/lib/graphql.types.js +1 -0
  45. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  46. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  47. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  48. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  49. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  50. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  51. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  52. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  53. package/lib/grpc-transport-node-http2.d.ts +19 -0
  54. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  55. package/lib/grpc-transport-node-http2.js +2 -0
  56. package/lib/grpc-transport-node-http2.js.map +1 -0
  57. package/lib/grpc-transport.d.ts +76 -0
  58. package/lib/grpc-transport.d.ts.map +1 -0
  59. package/lib/grpc-transport.js +1 -0
  60. package/lib/hpack.d.ts +34 -0
  61. package/lib/hpack.d.ts.map +1 -0
  62. package/lib/hpack.js +2 -0
  63. package/lib/hpack.js.map +1 -0
  64. package/lib/index.d.ts +32 -0
  65. package/lib/index.d.ts.map +1 -0
  66. package/lib/index.js +17 -0
  67. package/lib/pagination.d.ts +101 -24
  68. package/lib/pagination.d.ts.map +1 -1
  69. package/lib/pagination.js +1 -182
  70. package/lib/plain-values.d.ts +10 -0
  71. package/lib/plain-values.d.ts.map +1 -0
  72. package/lib/plain-values.js +2 -0
  73. package/lib/plain-values.js.map +1 -0
  74. package/lib/protobuf.d.ts +92 -0
  75. package/lib/protobuf.d.ts.map +1 -0
  76. package/lib/protobuf.js +1 -0
  77. package/lib/protocol-grpc.d.ts +86 -0
  78. package/lib/protocol-grpc.d.ts.map +1 -0
  79. package/lib/protocol-grpc.js +1 -0
  80. package/lib/protocol-http.d.ts +102 -23
  81. package/lib/protocol-http.d.ts.map +1 -1
  82. package/lib/protocol-http.js +1 -554
  83. package/lib/protocol-rest.d.ts +120 -50
  84. package/lib/protocol-rest.d.ts.map +1 -1
  85. package/lib/protocol-rest.js +1 -242
  86. package/lib/query.d.ts +29 -0
  87. package/lib/query.d.ts.map +1 -0
  88. package/lib/query.js +1 -0
  89. package/lib/response-validation-strict.d.ts +48 -0
  90. package/lib/response-validation-strict.d.ts.map +1 -0
  91. package/lib/response-validation-strict.js +1 -0
  92. package/lib/response-validation.d.ts +86 -0
  93. package/lib/response-validation.d.ts.map +1 -0
  94. package/lib/response-validation.js +1 -0
  95. package/lib/retry-after.d.ts +3 -3
  96. package/lib/retry-after.d.ts.map +1 -1
  97. package/lib/retry-after.js +1 -112
  98. package/lib/retry.d.ts +48 -29
  99. package/lib/retry.d.ts.map +1 -1
  100. package/lib/retry.js +1 -210
  101. package/lib/schema-lite-impl.d.ts +158 -0
  102. package/lib/schema-lite-impl.d.ts.map +1 -0
  103. package/lib/schema-lite-impl.js +1 -0
  104. package/lib/schema-lite-typed.d.ts +41 -0
  105. package/lib/schema-lite-typed.d.ts.map +1 -0
  106. package/lib/schema-lite-typed.js +1 -0
  107. package/lib/schema-lite.d.ts +40 -0
  108. package/lib/schema-lite.d.ts.map +1 -0
  109. package/lib/schema-lite.js +1 -0
  110. package/lib/schema.d.ts +21 -7
  111. package/lib/schema.d.ts.map +1 -1
  112. package/lib/schema.js +1 -48
  113. package/lib/sdk-error.d.ts +27 -0
  114. package/lib/sdk-error.d.ts.map +1 -0
  115. package/lib/sdk-error.js +1 -0
  116. package/lib/sensitive.d.ts +28 -0
  117. package/lib/sensitive.d.ts.map +1 -0
  118. package/lib/sensitive.js +2 -0
  119. package/lib/sensitive.js.map +1 -0
  120. package/lib/telemetry-debug.d.ts +6 -0
  121. package/lib/telemetry-debug.d.ts.map +1 -0
  122. package/lib/telemetry-debug.js +2 -0
  123. package/lib/telemetry-debug.js.map +1 -0
  124. package/lib/telemetry-hooks.d.ts +32 -0
  125. package/lib/telemetry-hooks.d.ts.map +1 -0
  126. package/lib/telemetry-hooks.js +2 -0
  127. package/lib/telemetry-hooks.js.map +1 -0
  128. package/lib/telemetry-host-rules.d.ts +23 -0
  129. package/lib/telemetry-host-rules.d.ts.map +1 -0
  130. package/lib/telemetry-host-rules.js +2 -0
  131. package/lib/telemetry-host-rules.js.map +1 -0
  132. package/lib/telemetry-lambda-context.d.ts +17 -0
  133. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  134. package/lib/telemetry-lambda-context.js +2 -0
  135. package/lib/telemetry-lambda-context.js.map +1 -0
  136. package/lib/telemetry-message-context.d.ts +52 -0
  137. package/lib/telemetry-message-context.d.ts.map +1 -0
  138. package/lib/telemetry-message-context.js +2 -0
  139. package/lib/telemetry-message-context.js.map +1 -0
  140. package/lib/telemetry-metrics.d.ts +6 -0
  141. package/lib/telemetry-metrics.d.ts.map +1 -0
  142. package/lib/telemetry-metrics.js +2 -0
  143. package/lib/telemetry-metrics.js.map +1 -0
  144. package/lib/telemetry-name-template.d.ts +13 -0
  145. package/lib/telemetry-name-template.d.ts.map +1 -0
  146. package/lib/telemetry-name-template.js +2 -0
  147. package/lib/telemetry-name-template.js.map +1 -0
  148. package/lib/telemetry-stream.d.ts +11 -0
  149. package/lib/telemetry-stream.d.ts.map +1 -0
  150. package/lib/telemetry-stream.js +2 -0
  151. package/lib/telemetry-stream.js.map +1 -0
  152. package/lib/telemetry-xray.d.ts +28 -0
  153. package/lib/telemetry-xray.d.ts.map +1 -0
  154. package/lib/telemetry-xray.js +2 -0
  155. package/lib/telemetry-xray.js.map +1 -0
  156. package/lib/telemetry.d.ts +288 -0
  157. package/lib/telemetry.d.ts.map +1 -0
  158. package/lib/telemetry.js +3 -0
  159. package/lib/telemetry.js.map +1 -0
  160. package/lib/trait.d.ts +71 -20
  161. package/lib/trait.d.ts.map +1 -1
  162. package/lib/trait.js +1 -107
  163. package/lib/unknown-error.d.ts +18 -0
  164. package/lib/unknown-error.d.ts.map +1 -0
  165. package/lib/unknown-error.js +1 -0
  166. package/lib/xml.d.ts +44 -0
  167. package/lib/xml.d.ts.map +1 -0
  168. package/lib/xml.js +1 -0
  169. package/package.json +13 -13
  170. package/src/annotations.ts +53 -0
  171. package/src/api.ts +1370 -200
  172. package/src/category.ts +76 -106
  173. package/src/chunks.ts +30 -0
  174. package/src/config.ts +245 -0
  175. package/src/crypto.ts +202 -0
  176. package/src/error-category.ts +16 -29
  177. package/src/errors.ts +75 -75
  178. package/src/graphql.ts +1778 -0
  179. package/src/graphql.types.ts +105 -0
  180. package/src/grpc-transport-cloudflare-http2.ts +494 -0
  181. package/src/grpc-transport-cloudflare-sockets.ts +299 -0
  182. package/src/grpc-transport-node-http2.ts +234 -0
  183. package/src/grpc-transport.ts +118 -0
  184. package/src/hpack.ts +331 -0
  185. package/src/index.ts +31 -0
  186. package/src/pagination.ts +368 -94
  187. package/src/plain-values.ts +41 -0
  188. package/src/protobuf.ts +1332 -0
  189. package/src/protocol-grpc.ts +641 -0
  190. package/src/protocol-http.ts +622 -322
  191. package/src/protocol-rest.ts +440 -227
  192. package/src/query.ts +39 -0
  193. package/src/response-validation-strict.ts +327 -0
  194. package/src/response-validation.ts +161 -0
  195. package/src/retry-after.ts +7 -13
  196. package/src/retry.ts +96 -110
  197. package/src/schema-lite-impl.ts +550 -0
  198. package/src/schema-lite-typed.ts +44 -0
  199. package/src/schema-lite.ts +44 -0
  200. package/src/schema.ts +259 -15
  201. package/src/sdk-error.ts +33 -0
  202. package/src/sensitive.ts +154 -0
  203. package/src/telemetry-debug.ts +179 -0
  204. package/src/telemetry-hooks.ts +33 -0
  205. package/src/telemetry-host-rules.ts +39 -0
  206. package/src/telemetry-lambda-context.ts +46 -0
  207. package/src/telemetry-message-context.ts +170 -0
  208. package/src/telemetry-metrics.ts +69 -0
  209. package/src/telemetry-name-template.ts +26 -0
  210. package/src/telemetry-stream.ts +100 -0
  211. package/src/telemetry-xray.ts +66 -0
  212. package/src/telemetry.ts +832 -0
  213. package/src/trait.ts +106 -67
  214. package/src/unknown-error.ts +38 -0
  215. package/src/xml.ts +346 -0
  216. package/lib/api.js.map +0 -1
  217. package/lib/category.js.map +0 -1
  218. package/lib/codegen/cli.d.ts +0 -29
  219. package/lib/codegen/cli.d.ts.map +0 -1
  220. package/lib/codegen/cli.js +0 -165
  221. package/lib/codegen/cli.js.map +0 -1
  222. package/lib/codegen/emit.d.ts +0 -129
  223. package/lib/codegen/emit.d.ts.map +0 -1
  224. package/lib/codegen/emit.js +0 -105
  225. package/lib/codegen/emit.js.map +0 -1
  226. package/lib/codegen/format.d.ts +0 -23
  227. package/lib/codegen/format.d.ts.map +0 -1
  228. package/lib/codegen/format.js +0 -28
  229. package/lib/codegen/format.js.map +0 -1
  230. package/lib/codegen/generator.d.ts +0 -334
  231. package/lib/codegen/generator.d.ts.map +0 -1
  232. package/lib/codegen/generator.js +0 -691
  233. package/lib/codegen/generator.js.map +0 -1
  234. package/lib/codegen/graph.d.ts +0 -36
  235. package/lib/codegen/graph.d.ts.map +0 -1
  236. package/lib/codegen/graph.js +0 -136
  237. package/lib/codegen/graph.js.map +0 -1
  238. package/lib/codegen/members.d.ts +0 -25
  239. package/lib/codegen/members.d.ts.map +0 -1
  240. package/lib/codegen/members.js +0 -55
  241. package/lib/codegen/members.js.map +0 -1
  242. package/lib/codegen/naming.d.ts +0 -29
  243. package/lib/codegen/naming.d.ts.map +0 -1
  244. package/lib/codegen/naming.js +0 -74
  245. package/lib/codegen/naming.js.map +0 -1
  246. package/lib/codegen/openapi-cli.d.ts +0 -38
  247. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  248. package/lib/codegen/openapi-cli.js +0 -107
  249. package/lib/codegen/openapi-cli.js.map +0 -1
  250. package/lib/codegen/openapi.d.ts +0 -115
  251. package/lib/codegen/openapi.d.ts.map +0 -1
  252. package/lib/codegen/openapi.js +0 -1220
  253. package/lib/codegen/openapi.js.map +0 -1
  254. package/lib/codegen/operations.d.ts +0 -24
  255. package/lib/codegen/operations.d.ts.map +0 -1
  256. package/lib/codegen/operations.js +0 -56
  257. package/lib/codegen/operations.js.map +0 -1
  258. package/lib/codegen/pagination.d.ts +0 -39
  259. package/lib/codegen/pagination.d.ts.map +0 -1
  260. package/lib/codegen/pagination.js +0 -33
  261. package/lib/codegen/pagination.js.map +0 -1
  262. package/lib/codegen/prelude.d.ts +0 -15
  263. package/lib/codegen/prelude.d.ts.map +0 -1
  264. package/lib/codegen/prelude.js +0 -60
  265. package/lib/codegen/prelude.js.map +0 -1
  266. package/lib/error-category.js.map +0 -1
  267. package/lib/errors.js.map +0 -1
  268. package/lib/json-patch.d.ts +0 -44
  269. package/lib/json-patch.d.ts.map +0 -1
  270. package/lib/json-patch.js +0 -174
  271. package/lib/json-patch.js.map +0 -1
  272. package/lib/pagination.js.map +0 -1
  273. package/lib/protocol-http.js.map +0 -1
  274. package/lib/protocol-rest.js.map +0 -1
  275. package/lib/retry-after.js.map +0 -1
  276. package/lib/retry.js.map +0 -1
  277. package/lib/schema.js.map +0 -1
  278. package/lib/trait.js.map +0 -1
  279. package/src/codegen/cli.ts +0 -268
  280. package/src/codegen/emit.ts +0 -207
  281. package/src/codegen/format.ts +0 -47
  282. package/src/codegen/generator.ts +0 -1153
  283. package/src/codegen/graph.ts +0 -151
  284. package/src/codegen/members.ts +0 -71
  285. package/src/codegen/naming.ts +0 -86
  286. package/src/codegen/openapi-cli.ts +0 -166
  287. package/src/codegen/openapi.ts +0 -1450
  288. package/src/codegen/operations.ts +0 -76
  289. package/src/codegen/pagination.ts +0 -71
  290. package/src/codegen/prelude.ts +0 -70
  291. package/src/json-patch.ts +0 -222
@@ -0,0 +1,641 @@
1
+ /**
2
+ * gRPC (binary protobuf) protocol for proto-sourced SDKs.
3
+ *
4
+ * Proto SDKs are generated as REST-shaped operations: each RPC is
5
+ * `POST /<package>.<Service>/<Method>` with a proto3 JSON body. Servers that
6
+ * accept JSON (Connect, grpc-gateway) use {@link makeRestProtocol} directly.
7
+ * Servers that only speak gRPC use this protocol, which builds the request
8
+ * with the REST protocol and speaks gRPC on the wire:
9
+ *
10
+ * - **Request**: the proto3 JSON body is transcoded to one protobuf message
11
+ * ({@link encodeMessage}) in one gRPC frame, sent as `application/grpc`.
12
+ * - **Transport**: the call goes through the `HttpClient` the
13
+ * `GrpcTransport` reference holds, or the caller's `HttpClient` when it
14
+ * holds none (see `@distilled.cloud/core/grpc-transport`). Plain `fetch`
15
+ * works where a proxy bridges HTTP/1.1 to gRPC (envoy).
16
+ * - **Status**: the call's `grpc-status` is read from the trailers, or from
17
+ * the headers of a trailers-only reply. A transport that can't see
18
+ * trailers (`fetch`) leaves only the headers; a reply with message frames
19
+ * and no status there is treated as OK.
20
+ * - **Errors**: a non-zero status becomes the operation's typed error. The
21
+ * REST decoder receives `{ code, status, message }` (`{ code: 5, status:
22
+ * "NOT_FOUND", ... }`) with the HTTP status grpc-gateway maps the code to
23
+ * (`NOT_FOUND` -> 404, `UNAVAILABLE` -> 503, ...), so error matchers key on
24
+ * the numeric gRPC `code`, and categories and retries follow the HTTP
25
+ * status.
26
+ * - **Response**: protobuf messages are transcoded back to proto3 JSON and
27
+ * decoded by the operation's output schema, so schemas, sensitive values
28
+ * and response validation behave exactly as for REST.
29
+ *
30
+ * A server-streaming method's output is `{ items: [message, ...] }`. Calling
31
+ * the operation collects the whole stream; its `.stream(input)` (see
32
+ * `API.makeStreaming`) emits each message as it arrives, and stopping the
33
+ * stream cancels the call.
34
+ *
35
+ * {@link Deadline} bounds calls in its scope: it is sent as `grpc-timeout`
36
+ * and enforced here, and a call that runs past it fails with
37
+ * `DEADLINE_EXCEEDED` (code 4).
38
+ */
39
+ import * as Context from "effect/Context";
40
+ import * as Duration from "effect/Duration";
41
+ import * as Effect from "effect/Effect";
42
+ import type * as HttpBody from "effect/http/HttpBody";
43
+ import * as HttpClient from "effect/http/HttpClient";
44
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
45
+ import * as HttpClientResponse from "effect/http/HttpClientResponse";
46
+ import * as Layer from "effect/Layer";
47
+ import * as Stream from "effect/Stream";
48
+ import * as API from "./api.ts";
49
+ import { GrpcTransport, hasTrailers, trailersOf } from "./grpc-transport.ts";
50
+ import {
51
+ decodeMessage,
52
+ encodeMessage,
53
+ frame,
54
+ FrameReader,
55
+ type ProtoDescriptors,
56
+ } from "./protobuf.ts";
57
+ import { InvalidInput, matchTypedError } from "./protocol-http.ts";
58
+ import { makeRestProtocol, type RestProtocolOptions } from "./protocol-rest.ts";
59
+ import { SdkError } from "./sdk-error.ts";
60
+ import * as Telemetry from "./telemetry.ts";
61
+
62
+ /** gRPC status code -> name. */
63
+ export const GRPC_STATUS_NAMES: Readonly<Record<number, string>> = {
64
+ 0: "OK",
65
+ 1: "CANCELLED",
66
+ 2: "UNKNOWN",
67
+ 3: "INVALID_ARGUMENT",
68
+ 4: "DEADLINE_EXCEEDED",
69
+ 5: "NOT_FOUND",
70
+ 6: "ALREADY_EXISTS",
71
+ 7: "PERMISSION_DENIED",
72
+ 8: "RESOURCE_EXHAUSTED",
73
+ 9: "FAILED_PRECONDITION",
74
+ 10: "ABORTED",
75
+ 11: "OUT_OF_RANGE",
76
+ 12: "UNIMPLEMENTED",
77
+ 13: "INTERNAL",
78
+ 14: "UNAVAILABLE",
79
+ 15: "DATA_LOSS",
80
+ 16: "UNAUTHENTICATED",
81
+ };
82
+
83
+ /** gRPC status code -> HTTP status (grpc-gateway's mapping). */
84
+ export const GRPC_HTTP_STATUS: Readonly<Record<number, number>> = {
85
+ 0: 200,
86
+ 1: 499,
87
+ 2: 500,
88
+ 3: 400,
89
+ 4: 504,
90
+ 5: 404,
91
+ 6: 409,
92
+ 7: 403,
93
+ 8: 429,
94
+ 9: 400,
95
+ 10: 409,
96
+ 11: 400,
97
+ 12: 501,
98
+ 13: 500,
99
+ 14: 503,
100
+ 15: 500,
101
+ 16: 401,
102
+ };
103
+
104
+ /**
105
+ * The deadline of gRPC calls in its scope, from when each call starts.
106
+ * `undefined` (the default) sets none.
107
+ *
108
+ * ```ts
109
+ * router.taskExecWait(input).pipe(Effect.provideService(Deadline, "30 seconds"));
110
+ * ```
111
+ */
112
+ export const Deadline = /*@__PURE__*/ Context.Reference<Duration.Input | undefined>(
113
+ "@distilled.cloud/core/protocol-grpc/Deadline",
114
+ { defaultValue: () => undefined },
115
+ );
116
+
117
+ export interface GrpcProtocolOptions<C> extends RestProtocolOptions<C> {
118
+ /** The SDK's generated descriptors (`src/descriptors.ts`). */
119
+ readonly descriptors: ProtoDescriptors;
120
+ /**
121
+ * The error for a non-zero status no typed error matched, from its gRPC
122
+ * code. By default the REST decoder classifies it by the HTTP status the
123
+ * code maps to (`UNAVAILABLE` -> `ServiceUnavailable`, which retries), which
124
+ * keeps retries working but merges codes that share a status
125
+ * (`INVALID_ARGUMENT`, `FAILED_PRECONDITION` and `OUT_OF_RANGE` are all
126
+ * `BadRequest`).
127
+ */
128
+ readonly statusError?: (info: StatusInfo) => unknown;
129
+ }
130
+
131
+ /** A non-OK gRPC status, as `statusError` receives it. */
132
+ export interface StatusInfo {
133
+ readonly code: number;
134
+ readonly message: string;
135
+ /** `google.rpc.Status.details` from `grpc-status-details-bin`, as proto3 JSON `Any`s. */
136
+ readonly details: ReadonlyArray<unknown>;
137
+ readonly headers: Readonly<Record<string, string>>;
138
+ }
139
+
140
+ /** gRPC's mapping of an HTTP status, for a reply that carries no gRPC status. */
141
+ export const HTTP_GRPC_STATUS: Readonly<Record<number, number>> = {
142
+ 400: 13,
143
+ 401: 16,
144
+ 403: 7,
145
+ 404: 12,
146
+ 429: 14,
147
+ 502: 14,
148
+ 503: 14,
149
+ 504: 14,
150
+ };
151
+
152
+ const STATUS_DESCRIPTORS: ProtoDescriptors = {
153
+ messages: {
154
+ "google.rpc.Status": [
155
+ [1, "code", "int32"],
156
+ [2, "message", "string"],
157
+ [3, "details", "message", "google.protobuf.Any", 1],
158
+ ],
159
+ },
160
+ enums: {},
161
+ methods: {},
162
+ };
163
+
164
+ /** The details of `grpc-status-details-bin` (base64, padding optional). */
165
+ const detailsOf = (raw: string | undefined): ReadonlyArray<unknown> => {
166
+ if (!raw) return [];
167
+ try {
168
+ const padded = raw.padEnd(raw.length + ((4 - (raw.length % 4)) % 4), "=");
169
+ const bin = atob(padded.replace(/-/g, "+").replace(/_/g, "/"));
170
+ const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
171
+ const status = decodeMessage(STATUS_DESCRIPTORS, "google.rpc.Status", bytes) as {
172
+ readonly details: ReadonlyArray<unknown>;
173
+ };
174
+ return status.details;
175
+ } catch {
176
+ // Malformed details don't hide the status itself.
177
+ return [];
178
+ }
179
+ };
180
+
181
+ type Headers = Readonly<Record<string, string | undefined>>;
182
+
183
+ const textDecoder = /*@__PURE__*/ new TextDecoder();
184
+
185
+ /**
186
+ * The SDK can't make the call (a broken descriptor table, or a REST
187
+ * encode/decode result gRPC can't use). Protocol effects are typed
188
+ * `never`; SdkError is part of every operation's declared error channel.
189
+ */
190
+ const sdkFailure = (message: string): Effect.Effect<never> =>
191
+ Effect.fail(new SdkError({ message })) as Effect.Effect<never>;
192
+
193
+ const methodPath = (url: string): string => {
194
+ try {
195
+ return new URL(url).pathname;
196
+ } catch {
197
+ return url;
198
+ }
199
+ };
200
+
201
+ /** The JSON a REST request carries, or `undefined` for an empty body. */
202
+ const jsonBody = (body: HttpBody.Uint8Array | HttpBody.Raw | HttpBody.Empty): unknown => {
203
+ switch (body._tag) {
204
+ case "Empty":
205
+ return undefined;
206
+ case "Uint8Array": {
207
+ const text = textDecoder.decode(body.body);
208
+ return text ? JSON.parse(text) : undefined;
209
+ }
210
+ case "Raw":
211
+ return typeof body.body === "string" && body.body ? JSON.parse(body.body) : body.body;
212
+ }
213
+ };
214
+
215
+ const jsonResponse = (
216
+ request: HttpClientRequest.HttpClientRequest,
217
+ status: number,
218
+ headers: Record<string, string>,
219
+ value: unknown,
220
+ ): HttpClientResponse.HttpClientResponse =>
221
+ HttpClientResponse.fromWeb(
222
+ request,
223
+ new Response(JSON.stringify(value), {
224
+ status,
225
+ headers: { ...headers, "content-type": "application/json" },
226
+ }),
227
+ );
228
+
229
+ const plainHeaders = (headers: Headers) => {
230
+ const out: Record<string, string> = {};
231
+ for (const key in headers) {
232
+ const v = headers[key];
233
+ if (v !== undefined && key !== "content-length" && key !== "content-type") out[key] = v;
234
+ }
235
+ return out;
236
+ };
237
+
238
+ const statusOf = (value: string | undefined): number | undefined =>
239
+ value === undefined || value === "" ? undefined : Number(value);
240
+
241
+ /** `text` percent-decoded, or as sent when it is not percent-encoded. */
242
+ const percentDecoded = (text: string): string => {
243
+ try {
244
+ return decodeURIComponent(text);
245
+ } catch {
246
+ return text;
247
+ }
248
+ };
249
+
250
+ const messageOf = (raw: string | undefined, status: number): string =>
251
+ percentDecoded(raw ?? "") || GRPC_STATUS_NAMES[status] || `gRPC status ${status}`;
252
+
253
+ /** A `grpc-timeout` value for `ms` (at most 8 digits per the spec). */
254
+ const grpcTimeout = (ms: number): string => {
255
+ const rounded = Math.max(1, Math.ceil(ms));
256
+ if (rounded < 1e8) return `${rounded}m`;
257
+ const seconds = Math.ceil(rounded / 1000);
258
+ return seconds < 1e8 ? `${seconds}S` : `${Math.min(99_999_999, Math.ceil(seconds / 3600))}H`;
259
+ };
260
+
261
+ type DecodeArgs = Omit<Parameters<API.ProtocolShape["decode"]>[0], "response">;
262
+
263
+ /**
264
+ * A gRPC protocol over the given REST protocol options. See the module
265
+ * documentation for the wire behavior.
266
+ */
267
+ export const makeGrpcProtocol = <C>(options: GrpcProtocolOptions<C>): Layer.Layer<API.Protocol> =>
268
+ Layer.effect(
269
+ API.Protocol,
270
+ Effect.map(Effect.service(API.Protocol), (rest) => {
271
+ const d = options.descriptors;
272
+ const methodOf = (url: string) => d.methods[methodPath(url)];
273
+
274
+ /** The REST request as one gRPC frame of protobuf. */
275
+ const encode: API.ProtocolShape["encode"] = (args) =>
276
+ Effect.flatMap(rest.encode(args), (request) => {
277
+ const method = methodOf(request.url);
278
+ if (!method) return sdkFailure(`no gRPC descriptor for ${request.url}`);
279
+ const body = request.body;
280
+ if (body._tag !== "Empty" && body._tag !== "Uint8Array" && body._tag !== "Raw") {
281
+ return sdkFailure(`gRPC requests need a JSON body, got ${body._tag}`);
282
+ }
283
+ let payload: Uint8Array;
284
+ try {
285
+ payload = encodeMessage(d, method[0], jsonBody(body) ?? {});
286
+ } catch (cause) {
287
+ // The encode channel is typed `never`; InvalidInput is part of
288
+ // every operation's declared error channel.
289
+ return Effect.fail(
290
+ new InvalidInput({
291
+ member: method[0],
292
+ message: cause instanceof Error ? cause.message : String(cause),
293
+ }),
294
+ ) as unknown as Effect.Effect<HttpClientRequest.HttpClientRequest>;
295
+ }
296
+ return Effect.succeed(
297
+ request.pipe(
298
+ HttpClientRequest.bodyUint8Array(frame(payload), "application/grpc"),
299
+ HttpClientRequest.setHeader("te", "trailers"),
300
+ ),
301
+ );
302
+ });
303
+
304
+ /** A gRPC status as the operation's typed error. */
305
+ const failWith = (
306
+ args: DecodeArgs,
307
+ request: HttpClientRequest.HttpClientRequest,
308
+ headers: Headers,
309
+ status: number,
310
+ message: string | undefined,
311
+ details: ReadonlyArray<unknown> = [],
312
+ ): Effect.Effect<never> => {
313
+ const httpStatus = GRPC_HTTP_STATUS[status] ?? 500;
314
+ const body = {
315
+ code: status,
316
+ status: GRPC_STATUS_NAMES[status] ?? String(status),
317
+ message: messageOf(message, status),
318
+ details,
319
+ };
320
+ if (options.statusError !== undefined) {
321
+ const plain = plainHeaders(headers);
322
+ const typed = matchTypedError(
323
+ args.errors,
324
+ httpStatus,
325
+ [{ code: status, message: body.message }],
326
+ { body, headers: plain },
327
+ );
328
+ return Effect.fail(
329
+ typed ??
330
+ options.statusError({ code: status, message: body.message, details, headers: plain }),
331
+ ) as Effect.Effect<never>;
332
+ }
333
+ return Effect.flatMap(
334
+ rest.decode({
335
+ ...args,
336
+ response: jsonResponse(request, httpStatus, plainHeaders(headers), body),
337
+ }),
338
+ () => sdkFailure(`gRPC status ${status} decoded as a success`),
339
+ );
340
+ };
341
+
342
+ /**
343
+ * The call's failure, if any, once its body has ended. The status is in
344
+ * the trailers, or in the headers of a trailers-only reply (one with no
345
+ * body); a status in the headers of a reply with a body is ignored. A
346
+ * transport that reads trailers must deliver one; over `fetch`, which
347
+ * can't, a reply with messages and no status is OK.
348
+ */
349
+ const endOf = (
350
+ args: DecodeArgs,
351
+ response: HttpClientResponse.HttpClientResponse,
352
+ trailers: Readonly<Record<string, string>>,
353
+ sawBody: boolean,
354
+ ): Effect.Effect<void> => {
355
+ const headers = response.headers as Headers;
356
+ const readsTrailers = hasTrailers(response);
357
+ const source =
358
+ trailers["grpc-status"] !== undefined
359
+ ? trailers
360
+ : !sawBody || !readsTrailers
361
+ ? headers
362
+ : undefined;
363
+ const status = statusOf(source?.["grpc-status"]);
364
+ if (source === undefined || status === undefined) {
365
+ if (readsTrailers) {
366
+ return failWith(
367
+ args,
368
+ response.request,
369
+ headers,
370
+ 13,
371
+ "server ended the call without a grpc-status",
372
+ );
373
+ }
374
+ return sawBody
375
+ ? Effect.void
376
+ : failWith(
377
+ args,
378
+ response.request,
379
+ headers,
380
+ 2,
381
+ "gRPC response carried no message and no grpc-status",
382
+ );
383
+ }
384
+ return status === 0
385
+ ? Effect.void
386
+ : failWith(
387
+ args,
388
+ response.request,
389
+ headers,
390
+ status,
391
+ source["grpc-message"],
392
+ detailsOf(source["grpc-status-details-bin"]),
393
+ );
394
+ };
395
+
396
+ /** A malformed frame (compressed, truncated): gRPC's INTERNAL. */
397
+ const badFrame = (
398
+ args: DecodeArgs,
399
+ response: HttpClientResponse.HttpClientResponse,
400
+ cause: unknown,
401
+ ) =>
402
+ failWith(
403
+ args,
404
+ response.request,
405
+ response.headers as Headers,
406
+ 13,
407
+ cause instanceof Error ? cause.message : String(cause),
408
+ );
409
+
410
+ /**
411
+ * A reply that isn't gRPC: a status other than 200, or another content
412
+ * type. The REST decoder classifies a non-200 by its HTTP status; with
413
+ * `statusError`, it maps as gRPC specifies (503 -> UNAVAILABLE, ...).
414
+ */
415
+ const notGrpc = (
416
+ args: DecodeArgs,
417
+ response: HttpClientResponse.HttpClientResponse,
418
+ ): Effect.Effect<never> | undefined => {
419
+ const headers = response.headers as Headers;
420
+ const isGrpc = (headers["content-type"] ?? "").startsWith("application/grpc");
421
+ if (response.status === 200 && isGrpc) return undefined;
422
+ if (response.status !== 200 && options.statusError === undefined) {
423
+ return rest.decode({ ...args, response }) as Effect.Effect<never>;
424
+ }
425
+ if (response.status !== 200) {
426
+ return failWith(
427
+ args,
428
+ response.request,
429
+ headers,
430
+ HTTP_GRPC_STATUS[response.status] ?? 2,
431
+ `HTTP ${response.status}`,
432
+ );
433
+ }
434
+ return failWith(
435
+ args,
436
+ response.request,
437
+ headers,
438
+ 2,
439
+ `unexpected content-type ${JSON.stringify(headers["content-type"] ?? "")}`,
440
+ );
441
+ };
442
+
443
+ /** A reply value decoded by the operation's output schema. */
444
+ const succeedWith = (
445
+ args: DecodeArgs,
446
+ request: HttpClientRequest.HttpClientRequest,
447
+ headers: Headers,
448
+ value: unknown,
449
+ ) =>
450
+ rest.decode({
451
+ ...args,
452
+ response: jsonResponse(request, 200, plainHeaders(headers), value),
453
+ });
454
+
455
+ const parseFailure = (body: unknown, cause: unknown): Effect.Effect<never> =>
456
+ Effect.fail(options.parseError({ body, cause })) as Effect.Effect<never>;
457
+
458
+ const deadlineMillis = (context: Context.Context<any>): number | undefined => {
459
+ const deadline = Context.get(context, Deadline);
460
+ return deadline === undefined ? undefined : Duration.toMillis(deadline);
461
+ };
462
+
463
+ /** Send a call through the transport in scope, with the deadline in scope. */
464
+ const send = (
465
+ context: Context.Context<any>,
466
+ operation: API.PreparedOperation,
467
+ input: unknown,
468
+ ms: number | undefined,
469
+ ) =>
470
+ Effect.flatMap(
471
+ encode({ input, inputAst: operation.inputAst, config: operation.config }),
472
+ (encoded) => {
473
+ const request =
474
+ ms === undefined
475
+ ? encoded
476
+ : HttpClientRequest.setHeader(encoded, "grpc-timeout", grpcTimeout(ms));
477
+ const client =
478
+ Context.get(context, GrpcTransport) ?? Context.get(context, HttpClient.HttpClient);
479
+ return Telemetry.execute(context, client, request);
480
+ },
481
+ );
482
+
483
+ /** Decode a whole reply (its body read to the end). */
484
+ const decode: API.ProtocolShape["decode"] = (args) => {
485
+ const { response } = args;
486
+ const failed = notGrpc(args, response);
487
+ if (failed) return failed;
488
+ const headers = response.headers as Headers;
489
+ const request = response.request;
490
+ const method = methodOf(request.url);
491
+ if (!method) return sdkFailure(`no gRPC descriptor for ${request.url}`);
492
+ // Protocol effects carry no error type: callers see the operation's.
493
+ return Effect.flatMap(response.arrayBuffer as Effect.Effect<ArrayBuffer>, (buffer) =>
494
+ Effect.flatMap(trailersOf(response), (trailers) => {
495
+ const reader = new FrameReader();
496
+ let frames: Uint8Array[];
497
+ try {
498
+ frames = reader.push(new Uint8Array(buffer));
499
+ } catch (cause) {
500
+ return Effect.flatMap(endOf(args, response, trailers, true), () =>
501
+ badFrame(args, response, cause),
502
+ );
503
+ }
504
+ return Effect.flatMap(endOf(args, response, trailers, buffer.byteLength > 0), () => {
505
+ if (reader.rest !== 0) return badFrame(args, response, "truncated gRPC frame");
506
+ const [, responseType, stream] = method;
507
+ if (!stream && frames.length !== 1) {
508
+ return failWith(
509
+ args,
510
+ request,
511
+ headers,
512
+ 12,
513
+ `expected one response message, got ${frames.length}`,
514
+ );
515
+ }
516
+ let value: unknown;
517
+ try {
518
+ value = stream
519
+ ? { items: frames.map((f) => decodeMessage(d, responseType, f)) }
520
+ : decodeMessage(d, responseType, frames[0]!);
521
+ } catch (cause) {
522
+ return parseFailure(buffer, cause);
523
+ }
524
+ return succeedWith(args, request, headers, value);
525
+ });
526
+ }),
527
+ );
528
+ };
529
+
530
+ const deadlineExceeded = (args: DecodeArgs, url: string) =>
531
+ failWith(args, HttpClientRequest.post(url), {}, 4, "Deadline Exceeded");
532
+
533
+ return API.Protocol.of({
534
+ encode,
535
+ decode,
536
+ call: (operation, input) =>
537
+ Effect.withFiber((fiber) => {
538
+ const context = fiber.context as Context.Context<any>;
539
+ const args: DecodeArgs = {
540
+ outputAst: operation.outputAst,
541
+ errors: operation.errors,
542
+ config: operation.config,
543
+ };
544
+ const ms = deadlineMillis(context);
545
+ const run = Effect.flatMap(
546
+ send(
547
+ context,
548
+ operation,
549
+ input,
550
+ ms,
551
+ ) as Effect.Effect<HttpClientResponse.HttpClientResponse>,
552
+ (response) => decode({ ...args, response }),
553
+ );
554
+ return ms === undefined
555
+ ? run
556
+ : Effect.timeoutOrElse(run, {
557
+ duration: ms,
558
+ orElse: () => deadlineExceeded(args, ""),
559
+ });
560
+ }),
561
+ stream: (operation, input) =>
562
+ Stream.unwrap(
563
+ Effect.withFiber((fiber) => {
564
+ const context = fiber.context as Context.Context<any>;
565
+ const args: DecodeArgs = {
566
+ outputAst: operation.outputAst,
567
+ errors: operation.errors,
568
+ config: operation.config,
569
+ };
570
+ const ms = deadlineMillis(context);
571
+ const messages = Effect.map(
572
+ send(
573
+ context,
574
+ operation,
575
+ input,
576
+ ms,
577
+ ) as Effect.Effect<HttpClientResponse.HttpClientResponse>,
578
+ (response) => streamReply(args, response),
579
+ );
580
+ const stream = Stream.unwrap(messages);
581
+ return Effect.succeed(
582
+ ms === undefined
583
+ ? stream
584
+ : Stream.interruptWhen(
585
+ stream,
586
+ Effect.flatMap(Effect.sleep(ms), () => deadlineExceeded(args, "")),
587
+ ),
588
+ );
589
+ }),
590
+ ),
591
+ });
592
+
593
+ /** Each message of a server stream, decoded as it arrives. */
594
+ function streamReply(
595
+ args: DecodeArgs,
596
+ response: HttpClientResponse.HttpClientResponse,
597
+ ): Stream.Stream<unknown, unknown> {
598
+ const headers = response.headers as Headers;
599
+ const request = response.request;
600
+ const failed = notGrpc(args, response);
601
+ if (failed) return Stream.fromEffect(failed);
602
+ const method = methodOf(request.url);
603
+ if (!method) return Stream.fromEffect(sdkFailure(`no gRPC descriptor for ${request.url}`));
604
+ const [, responseType] = method;
605
+ const reader = new FrameReader();
606
+ const item = (payload: Uint8Array) => {
607
+ let value: unknown;
608
+ try {
609
+ value = decodeMessage(d, responseType, payload);
610
+ } catch (cause) {
611
+ return parseFailure(payload, cause);
612
+ }
613
+ return Effect.map(
614
+ succeedWith(args, request, headers, { items: [value] }),
615
+ (decoded) => (decoded as { readonly items: ReadonlyArray<unknown> }).items[0],
616
+ );
617
+ };
618
+ const messages = Stream.flatMap(response.stream, (chunk) =>
619
+ Stream.fromIterableEffect(
620
+ Effect.suspend(() => {
621
+ if (chunk.length > 0) sawBody = true;
622
+ let frames: Uint8Array[];
623
+ try {
624
+ frames = reader.push(chunk);
625
+ } catch (cause) {
626
+ return badFrame(args, response, cause);
627
+ }
628
+ return Effect.forEach(frames, item);
629
+ }),
630
+ ),
631
+ );
632
+ let sawBody = false;
633
+ const end = Effect.flatMap(trailersOf(response), (trailers) =>
634
+ Effect.flatMap(endOf(args, response, trailers, sawBody), () =>
635
+ reader.rest !== 0 ? badFrame(args, response, "truncated gRPC frame") : Effect.void,
636
+ ),
637
+ );
638
+ return Stream.concat(messages, Stream.drain(Stream.fromEffect(end)));
639
+ }
640
+ }),
641
+ ).pipe(Layer.provide(makeRestProtocol(options)));