@distilled.cloud/core 1.0.0-rc.2 → 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 (321) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +33 -0
  3. package/lib/_bundle/aws.js +2 -0
  4. package/lib/_bundle/aws.js.map +1 -0
  5. package/lib/_bundle/base.js +5 -0
  6. package/lib/_bundle/base.js.map +1 -0
  7. package/lib/_bundle/graphql.js +3 -0
  8. package/lib/_bundle/graphql.js.map +1 -0
  9. package/lib/_bundle/grpc.js +3 -0
  10. package/lib/_bundle/grpc.js.map +1 -0
  11. package/lib/_bundle/rest.js +2 -0
  12. package/lib/_bundle/rest.js.map +1 -0
  13. package/lib/_bundle/xml.js +4 -0
  14. package/lib/_bundle/xml.js.map +1 -0
  15. package/lib/annotations.d.ts +17 -0
  16. package/lib/annotations.d.ts.map +1 -0
  17. package/lib/annotations.js +2 -0
  18. package/lib/annotations.js.map +1 -0
  19. package/lib/api.d.ts +220 -51
  20. package/lib/api.d.ts.map +1 -1
  21. package/lib/api.js +1 -178
  22. package/lib/category.d.ts +19 -16
  23. package/lib/category.d.ts.map +1 -1
  24. package/lib/category.js +1 -280
  25. package/lib/chunks.d.ts +3 -0
  26. package/lib/chunks.d.ts.map +1 -0
  27. package/lib/chunks.js +1 -0
  28. package/lib/config.d.ts +81 -0
  29. package/lib/config.d.ts.map +1 -0
  30. package/lib/config.js +1 -0
  31. package/lib/crypto.d.ts +76 -0
  32. package/lib/crypto.d.ts.map +1 -0
  33. package/lib/crypto.js +1 -0
  34. package/lib/error-category.d.ts +1 -1
  35. package/lib/error-category.d.ts.map +1 -1
  36. package/lib/error-category.js +1 -46
  37. package/lib/errors.d.ts +99 -74
  38. package/lib/errors.d.ts.map +1 -1
  39. package/lib/errors.js +1 -186
  40. package/lib/graphql.d.ts +420 -0
  41. package/lib/graphql.d.ts.map +1 -0
  42. package/lib/graphql.js +1 -0
  43. package/lib/graphql.types.d.ts +11 -0
  44. package/lib/graphql.types.d.ts.map +1 -0
  45. package/lib/graphql.types.js +1 -0
  46. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  47. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  48. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  49. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  50. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  51. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  52. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  53. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  54. package/lib/grpc-transport-node-http2.d.ts +19 -0
  55. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  56. package/lib/grpc-transport-node-http2.js +2 -0
  57. package/lib/grpc-transport-node-http2.js.map +1 -0
  58. package/lib/grpc-transport.d.ts +111 -0
  59. package/lib/grpc-transport.d.ts.map +1 -0
  60. package/lib/grpc-transport.js +1 -0
  61. package/lib/hpack.d.ts +34 -0
  62. package/lib/hpack.d.ts.map +1 -0
  63. package/lib/hpack.js +2 -0
  64. package/lib/hpack.js.map +1 -0
  65. package/lib/index.d.ts +32 -0
  66. package/lib/index.d.ts.map +1 -0
  67. package/lib/index.js +17 -0
  68. package/lib/max-message-bytes.d.ts +42 -0
  69. package/lib/max-message-bytes.d.ts.map +1 -0
  70. package/lib/max-message-bytes.js +2 -0
  71. package/lib/max-message-bytes.js.map +1 -0
  72. package/lib/ndjson.d.ts +3 -0
  73. package/lib/ndjson.d.ts.map +1 -0
  74. package/lib/ndjson.js +2 -0
  75. package/lib/ndjson.js.map +1 -0
  76. package/lib/pagination.d.ts +105 -25
  77. package/lib/pagination.d.ts.map +1 -1
  78. package/lib/pagination.js +1 -182
  79. package/lib/plain-values.d.ts +21 -0
  80. package/lib/plain-values.d.ts.map +1 -0
  81. package/lib/plain-values.js +2 -0
  82. package/lib/plain-values.js.map +1 -0
  83. package/lib/protobuf.d.ts +85 -0
  84. package/lib/protobuf.d.ts.map +1 -0
  85. package/lib/protobuf.js +1 -0
  86. package/lib/protocol-grpc.d.ts +123 -0
  87. package/lib/protocol-grpc.d.ts.map +1 -0
  88. package/lib/protocol-grpc.js +1 -0
  89. package/lib/protocol-http.d.ts +206 -25
  90. package/lib/protocol-http.d.ts.map +1 -1
  91. package/lib/protocol-http.js +1 -554
  92. package/lib/protocol-rest.d.ts +258 -64
  93. package/lib/protocol-rest.d.ts.map +1 -1
  94. package/lib/protocol-rest.js +1 -242
  95. package/lib/protocol.d.ts +113 -0
  96. package/lib/protocol.d.ts.map +1 -0
  97. package/lib/protocol.js +0 -0
  98. package/lib/query.d.ts +29 -0
  99. package/lib/query.d.ts.map +1 -0
  100. package/lib/query.js +1 -0
  101. package/lib/response-validation-strict.d.ts +48 -0
  102. package/lib/response-validation-strict.d.ts.map +1 -0
  103. package/lib/response-validation-strict.js +1 -0
  104. package/lib/response-validation.d.ts +86 -0
  105. package/lib/response-validation.d.ts.map +1 -0
  106. package/lib/response-validation.js +1 -0
  107. package/lib/retry-after.d.ts +4 -4
  108. package/lib/retry-after.d.ts.map +1 -1
  109. package/lib/retry-after.js +1 -112
  110. package/lib/retry-state.d.ts +26 -0
  111. package/lib/retry-state.d.ts.map +1 -0
  112. package/lib/retry-state.js +2 -0
  113. package/lib/retry-state.js.map +1 -0
  114. package/lib/retry.d.ts +141 -42
  115. package/lib/retry.d.ts.map +1 -1
  116. package/lib/retry.js +1 -210
  117. package/lib/schema-lite-impl.d.ts +179 -0
  118. package/lib/schema-lite-impl.d.ts.map +1 -0
  119. package/lib/schema-lite-impl.js +1 -0
  120. package/lib/schema-lite-typed.d.ts +41 -0
  121. package/lib/schema-lite-typed.d.ts.map +1 -0
  122. package/lib/schema-lite-typed.js +1 -0
  123. package/lib/schema-lite.d.ts +41 -0
  124. package/lib/schema-lite.d.ts.map +1 -0
  125. package/lib/schema-lite.js +1 -0
  126. package/lib/schema.d.ts +21 -7
  127. package/lib/schema.d.ts.map +1 -1
  128. package/lib/schema.js +1 -48
  129. package/lib/sdk-error.d.ts +31 -0
  130. package/lib/sdk-error.d.ts.map +1 -0
  131. package/lib/sdk-error.js +1 -0
  132. package/lib/send.d.ts +37 -0
  133. package/lib/send.d.ts.map +1 -0
  134. package/lib/send.js +2 -0
  135. package/lib/send.js.map +1 -0
  136. package/lib/sensitive.d.ts +28 -0
  137. package/lib/sensitive.d.ts.map +1 -0
  138. package/lib/sensitive.js +2 -0
  139. package/lib/sensitive.js.map +1 -0
  140. package/lib/telemetry-debug.d.ts +6 -0
  141. package/lib/telemetry-debug.d.ts.map +1 -0
  142. package/lib/telemetry-debug.js +2 -0
  143. package/lib/telemetry-debug.js.map +1 -0
  144. package/lib/telemetry-hooks.d.ts +32 -0
  145. package/lib/telemetry-hooks.d.ts.map +1 -0
  146. package/lib/telemetry-hooks.js +2 -0
  147. package/lib/telemetry-hooks.js.map +1 -0
  148. package/lib/telemetry-host-rules.d.ts +23 -0
  149. package/lib/telemetry-host-rules.d.ts.map +1 -0
  150. package/lib/telemetry-host-rules.js +2 -0
  151. package/lib/telemetry-host-rules.js.map +1 -0
  152. package/lib/telemetry-lambda-context.d.ts +17 -0
  153. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  154. package/lib/telemetry-lambda-context.js +2 -0
  155. package/lib/telemetry-lambda-context.js.map +1 -0
  156. package/lib/telemetry-message-context.d.ts +52 -0
  157. package/lib/telemetry-message-context.d.ts.map +1 -0
  158. package/lib/telemetry-message-context.js +2 -0
  159. package/lib/telemetry-message-context.js.map +1 -0
  160. package/lib/telemetry-metrics.d.ts +6 -0
  161. package/lib/telemetry-metrics.d.ts.map +1 -0
  162. package/lib/telemetry-metrics.js +2 -0
  163. package/lib/telemetry-metrics.js.map +1 -0
  164. package/lib/telemetry-name-template.d.ts +13 -0
  165. package/lib/telemetry-name-template.d.ts.map +1 -0
  166. package/lib/telemetry-name-template.js +2 -0
  167. package/lib/telemetry-name-template.js.map +1 -0
  168. package/lib/telemetry-stream.d.ts +11 -0
  169. package/lib/telemetry-stream.d.ts.map +1 -0
  170. package/lib/telemetry-stream.js +2 -0
  171. package/lib/telemetry-stream.js.map +1 -0
  172. package/lib/telemetry-xray.d.ts +28 -0
  173. package/lib/telemetry-xray.d.ts.map +1 -0
  174. package/lib/telemetry-xray.js +2 -0
  175. package/lib/telemetry-xray.js.map +1 -0
  176. package/lib/telemetry.d.ts +317 -0
  177. package/lib/telemetry.d.ts.map +1 -0
  178. package/lib/telemetry.js +3 -0
  179. package/lib/telemetry.js.map +1 -0
  180. package/lib/token-cache.d.ts +31 -0
  181. package/lib/token-cache.d.ts.map +1 -0
  182. package/lib/token-cache.js +2 -0
  183. package/lib/token-cache.js.map +1 -0
  184. package/lib/trait.d.ts +94 -20
  185. package/lib/trait.d.ts.map +1 -1
  186. package/lib/trait.js +1 -107
  187. package/lib/unknown-error.d.ts +18 -0
  188. package/lib/unknown-error.d.ts.map +1 -0
  189. package/lib/unknown-error.js +1 -0
  190. package/lib/xml.d.ts +44 -0
  191. package/lib/xml.d.ts.map +1 -0
  192. package/lib/xml.js +1 -0
  193. package/package.json +13 -13
  194. package/src/annotations.ts +53 -0
  195. package/src/api.ts +1597 -234
  196. package/src/category.ts +97 -134
  197. package/src/chunks.ts +30 -0
  198. package/src/config.ts +261 -0
  199. package/src/crypto.ts +202 -0
  200. package/src/error-category.ts +16 -29
  201. package/src/errors.ts +99 -77
  202. package/src/graphql.ts +1817 -0
  203. package/src/graphql.types.ts +120 -0
  204. package/src/grpc-transport-cloudflare-http2.ts +569 -0
  205. package/src/grpc-transport-cloudflare-sockets.ts +368 -0
  206. package/src/grpc-transport-node-http2.ts +307 -0
  207. package/src/grpc-transport.ts +287 -0
  208. package/src/hpack.ts +331 -0
  209. package/src/index.ts +31 -0
  210. package/src/max-message-bytes.ts +58 -0
  211. package/src/ndjson.ts +55 -0
  212. package/src/pagination.ts +379 -94
  213. package/src/plain-values.ts +70 -0
  214. package/src/protobuf.ts +1367 -0
  215. package/src/protocol-grpc.ts +811 -0
  216. package/src/protocol-http.ts +1045 -371
  217. package/src/protocol-rest.ts +908 -255
  218. package/src/protocol.ts +150 -0
  219. package/src/query.ts +39 -0
  220. package/src/response-validation-strict.ts +333 -0
  221. package/src/response-validation.ts +161 -0
  222. package/src/retry-after.ts +8 -14
  223. package/src/retry-state.ts +105 -0
  224. package/src/retry.ts +260 -145
  225. package/src/schema-lite-impl.ts +621 -0
  226. package/src/schema-lite-typed.ts +44 -0
  227. package/src/schema-lite.ts +45 -0
  228. package/src/schema.ts +259 -15
  229. package/src/sdk-error.ts +37 -0
  230. package/src/send.ts +156 -0
  231. package/src/sensitive.ts +188 -0
  232. package/src/telemetry-debug.ts +179 -0
  233. package/src/telemetry-hooks.ts +33 -0
  234. package/src/telemetry-host-rules.ts +39 -0
  235. package/src/telemetry-lambda-context.ts +46 -0
  236. package/src/telemetry-message-context.ts +170 -0
  237. package/src/telemetry-metrics.ts +69 -0
  238. package/src/telemetry-name-template.ts +26 -0
  239. package/src/telemetry-stream.ts +100 -0
  240. package/src/telemetry-xray.ts +66 -0
  241. package/src/telemetry.ts +800 -0
  242. package/src/token-cache.ts +117 -0
  243. package/src/trait.ts +139 -67
  244. package/src/unknown-error.ts +38 -0
  245. package/src/xml.ts +346 -0
  246. package/lib/api.js.map +0 -1
  247. package/lib/category.js.map +0 -1
  248. package/lib/codegen/cli.d.ts +0 -29
  249. package/lib/codegen/cli.d.ts.map +0 -1
  250. package/lib/codegen/cli.js +0 -165
  251. package/lib/codegen/cli.js.map +0 -1
  252. package/lib/codegen/emit.d.ts +0 -129
  253. package/lib/codegen/emit.d.ts.map +0 -1
  254. package/lib/codegen/emit.js +0 -105
  255. package/lib/codegen/emit.js.map +0 -1
  256. package/lib/codegen/format.d.ts +0 -23
  257. package/lib/codegen/format.d.ts.map +0 -1
  258. package/lib/codegen/format.js +0 -28
  259. package/lib/codegen/format.js.map +0 -1
  260. package/lib/codegen/generator.d.ts +0 -334
  261. package/lib/codegen/generator.d.ts.map +0 -1
  262. package/lib/codegen/generator.js +0 -691
  263. package/lib/codegen/generator.js.map +0 -1
  264. package/lib/codegen/graph.d.ts +0 -36
  265. package/lib/codegen/graph.d.ts.map +0 -1
  266. package/lib/codegen/graph.js +0 -136
  267. package/lib/codegen/graph.js.map +0 -1
  268. package/lib/codegen/members.d.ts +0 -25
  269. package/lib/codegen/members.d.ts.map +0 -1
  270. package/lib/codegen/members.js +0 -55
  271. package/lib/codegen/members.js.map +0 -1
  272. package/lib/codegen/naming.d.ts +0 -29
  273. package/lib/codegen/naming.d.ts.map +0 -1
  274. package/lib/codegen/naming.js +0 -74
  275. package/lib/codegen/naming.js.map +0 -1
  276. package/lib/codegen/openapi-cli.d.ts +0 -38
  277. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  278. package/lib/codegen/openapi-cli.js +0 -107
  279. package/lib/codegen/openapi-cli.js.map +0 -1
  280. package/lib/codegen/openapi.d.ts +0 -115
  281. package/lib/codegen/openapi.d.ts.map +0 -1
  282. package/lib/codegen/openapi.js +0 -1220
  283. package/lib/codegen/openapi.js.map +0 -1
  284. package/lib/codegen/operations.d.ts +0 -24
  285. package/lib/codegen/operations.d.ts.map +0 -1
  286. package/lib/codegen/operations.js +0 -56
  287. package/lib/codegen/operations.js.map +0 -1
  288. package/lib/codegen/pagination.d.ts +0 -39
  289. package/lib/codegen/pagination.d.ts.map +0 -1
  290. package/lib/codegen/pagination.js +0 -33
  291. package/lib/codegen/pagination.js.map +0 -1
  292. package/lib/codegen/prelude.d.ts +0 -15
  293. package/lib/codegen/prelude.d.ts.map +0 -1
  294. package/lib/codegen/prelude.js +0 -60
  295. package/lib/codegen/prelude.js.map +0 -1
  296. package/lib/error-category.js.map +0 -1
  297. package/lib/errors.js.map +0 -1
  298. package/lib/json-patch.d.ts +0 -44
  299. package/lib/json-patch.d.ts.map +0 -1
  300. package/lib/json-patch.js +0 -174
  301. package/lib/json-patch.js.map +0 -1
  302. package/lib/pagination.js.map +0 -1
  303. package/lib/protocol-http.js.map +0 -1
  304. package/lib/protocol-rest.js.map +0 -1
  305. package/lib/retry-after.js.map +0 -1
  306. package/lib/retry.js.map +0 -1
  307. package/lib/schema.js.map +0 -1
  308. package/lib/trait.js.map +0 -1
  309. package/src/codegen/cli.ts +0 -268
  310. package/src/codegen/emit.ts +0 -207
  311. package/src/codegen/format.ts +0 -47
  312. package/src/codegen/generator.ts +0 -1153
  313. package/src/codegen/graph.ts +0 -151
  314. package/src/codegen/members.ts +0 -71
  315. package/src/codegen/naming.ts +0 -86
  316. package/src/codegen/openapi-cli.ts +0 -166
  317. package/src/codegen/openapi.ts +0 -1450
  318. package/src/codegen/operations.ts +0 -76
  319. package/src/codegen/pagination.ts +0 -71
  320. package/src/codegen/prelude.ts +0 -70
  321. package/src/json-patch.ts +0 -222
@@ -0,0 +1,287 @@
1
+ /**
2
+ * How gRPC calls reach a server.
3
+ *
4
+ * A transport is an Effect `HttpClient`: it sends the request
5
+ * `protocol-grpc` builds (`POST`, `application/grpc`, one frame) and returns
6
+ * the response with its body as a stream, so a server-streaming call reads
7
+ * each message as it arrives. gRPC puts the call's status in the trailers;
8
+ * a transport that can read them hands them over with {@link respond}, and
9
+ * the protocol reads them with {@link trailersOf} once the body has ended.
10
+ *
11
+ * By default `protocol-grpc` sends through the caller's `HttpClient`
12
+ * (`fetch`), which works where a proxy bridges HTTP/1.1 to gRPC (envoy) and
13
+ * puts the status in the headers. A transport built here is Effect code: the
14
+ * body is an Effect `Stream` read in the caller's fiber, and the trailers an
15
+ * `Effect` that fails when the transport can't read them, so no failure
16
+ * turns into an empty value on the way. Provide a different transport for one
17
+ * scope with {@link layer}:
18
+ *
19
+ * - `@distilled.cloud/core/grpc-transport-node-http2` speaks HTTP/2 with
20
+ * `node:http2`, for servers that offer nothing else;
21
+ * - `@distilled.cloud/core/grpc-transport-cloudflare-sockets` speaks HTTP/1.1
22
+ * over a `cloudflare:sockets` TLS socket, for a Cloudflare Worker calling a
23
+ * gRPC server that is itself behind Cloudflare (a Worker's `fetch` to such
24
+ * a site takes Cloudflare's internal path, which resets gRPC upstreams);
25
+ * - `@distilled.cloud/core/grpc-transport-cloudflare-http2` speaks HTTP/2
26
+ * over a `cloudflare:sockets` socket, for a Cloudflare Worker calling a
27
+ * server that offers nothing else (workerd has no working `node:http2`).
28
+ *
29
+ * None is imported by this module, so a bundle only carries the ones it
30
+ * provides.
31
+ */
32
+ import * as Context from "effect/Context";
33
+ import * as Deferred from "effect/Deferred";
34
+ import * as Effect from "effect/Effect";
35
+ import * as Cookies from "effect/http/Cookies";
36
+ import * as Headers from "effect/http/Headers";
37
+ import type * as HttpClient from "effect/http/HttpClient";
38
+ import * as HttpClientError from "effect/http/HttpClientError";
39
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
40
+ import * as HttpClientResponse from "effect/http/HttpClientResponse";
41
+ import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage";
42
+ import * as UrlParams from "effect/http/UrlParams";
43
+ import * as Inspectable from "effect/Inspectable";
44
+ import * as Layer from "effect/Layer";
45
+ import * as Option from "effect/Option";
46
+ import { pipeArguments } from "effect/Pipeable";
47
+ import type * as Schema from "effect/Schema";
48
+ import * as Stream from "effect/Stream";
49
+
50
+ /**
51
+ * The `HttpClient` gRPC calls go through. `undefined` (the default) sends
52
+ * through the caller's `HttpClient`.
53
+ */
54
+ export const GrpcTransport = /*@__PURE__*/ Context.Reference<HttpClient.HttpClient | undefined>(
55
+ "@distilled.cloud/core/GrpcTransport",
56
+ { defaultValue: () => undefined },
57
+ );
58
+
59
+ /** Send gRPC calls in this scope through `client`. */
60
+ export const layer = (client: HttpClient.HttpClient): Layer.Layer<never> =>
61
+ Layer.succeed(GrpcTransport, client);
62
+
63
+ /** Header and trailer names are lowercase; values as received. */
64
+ export type Trailers = Readonly<Record<string, string>>;
65
+
66
+ /** What a transport hands over for a response. */
67
+ export interface Reply {
68
+ readonly status: number;
69
+ readonly headers: Trailers;
70
+ /**
71
+ * The body as it arrives. It runs in the fiber that reads the response, so
72
+ * that fiber's interruption and finalizers reach the connection.
73
+ */
74
+ readonly body: Stream.Stream<Uint8Array, unknown>;
75
+ /** The trailers, once the body has ended. Fails when they can't be read. */
76
+ readonly trailers: Effect.Effect<Trailers, unknown>;
77
+ /**
78
+ * Whether the trailers always arrive. HTTP/2 delivers them end to end;
79
+ * over HTTP/1.1 a bridging proxy may drop them, so the protocol then
80
+ * treats a reply with messages and no status as OK.
81
+ * @default true
82
+ */
83
+ readonly reliableTrailers?: boolean;
84
+ }
85
+
86
+ // Keyed by the request the transport sent, which a response keeps as
87
+ // `response.request` through the wrappers `HttpClient` puts around it.
88
+ const repliesByRequest = /*@__PURE__*/ new WeakMap<HttpClientRequest.HttpClientRequest, Reply>();
89
+
90
+ /**
91
+ * Whether `status` is a final HTTP status a response can carry (200 to 599).
92
+ * A transport fails the call with a transport error for any other.
93
+ */
94
+ export const isResponseStatus = (status: number): boolean =>
95
+ Number.isInteger(status) && status >= 200 && status <= 599;
96
+
97
+ /**
98
+ * Whether a response with `status` has no body (RFC 9110 sections 15.3.5,
99
+ * 15.3.6 and 15.4.5). Its transport lets the connection go at once.
100
+ */
101
+ export const hasNoBody = (status: number): boolean =>
102
+ status === 204 || status === 205 || status === 304;
103
+
104
+ /** HTTP/2 error code (RFC 9113 section 7) -> gRPC status, where it isn't INTERNAL. */
105
+ const RESET_STATUS: ReadonlyMap<number, readonly [status: number, message: string]> =
106
+ /*@__PURE__*/ new Map([
107
+ [0x0, [13, "the server reset the stream without a grpc-status"]],
108
+ [0x7, [14, "the server refused the stream"]],
109
+ [0x8, [1, "the server cancelled the call"]],
110
+ [0xb, [8, "the server asked to slow down"]],
111
+ [0xc, [7, "the connection is not secure enough"]],
112
+ ]);
113
+
114
+ /**
115
+ * The trailers of a stream the server reset with the HTTP/2 error `code`
116
+ * before it sent a status: the gRPC status the gRPC over HTTP/2 spec maps
117
+ * the code to (`PROTOCOL-HTTP2.md`, "Errors"), as grpc-js does. The call
118
+ * fails like any other gRPC error: `REFUSED_STREAM` (the server did no work)
119
+ * as `UNAVAILABLE`, which retries, `NO_ERROR` and unknown codes as
120
+ * `INTERNAL`, which doesn't.
121
+ */
122
+ export const resetTrailers = (code: number): Trailers => {
123
+ const [status, message] = RESET_STATUS.get(code) ?? [13, "the server reset the stream"];
124
+ return { "grpc-status": String(status), "grpc-message": `${message} (HTTP/2 error ${code})` };
125
+ };
126
+
127
+ /**
128
+ * The reply for a stream the server reset with the HTTP/2 error `code`
129
+ * before its response headers: a gRPC reply of trailers alone, carrying
130
+ * {@link resetTrailers}.
131
+ */
132
+ export const resetReply = (code: number): Reply => ({
133
+ status: 200,
134
+ headers: { "content-type": "application/grpc" },
135
+ body: Stream.empty,
136
+ trailers: Effect.succeed(resetTrailers(code)),
137
+ });
138
+
139
+ /**
140
+ * Build a transport's response from its {@link Reply}. Fails with the
141
+ * `TypeError` of a head that is no valid HTTP head (a header name that is no
142
+ * token, a value with a line break), as `fetch` would. A response with
143
+ * {@link hasNoBody} has an empty body and no trailers.
144
+ */
145
+ export const respond = (
146
+ request: HttpClientRequest.HttpClientRequest,
147
+ reply: Reply,
148
+ ): Effect.Effect<HttpClientResponse.HttpClientResponse, unknown> =>
149
+ Effect.try({
150
+ try: () => new globalThis.Headers(reply.headers as Record<string, string>),
151
+ catch: (cause) => cause,
152
+ }).pipe(
153
+ Effect.map(() => {
154
+ const kept = hasNoBody(reply.status)
155
+ ? { ...reply, body: Stream.empty, trailers: Effect.succeed({}) }
156
+ : reply;
157
+ repliesByRequest.set(request, kept);
158
+ return new ReplyResponse(request, kept);
159
+ }),
160
+ );
161
+
162
+ /**
163
+ * Whether `response` came from a transport whose trailers always arrive
164
+ * ({@link Reply.reliableTrailers}), so a missing status is an error.
165
+ */
166
+ export const hasTrailers = (response: HttpClientResponse.HttpClientResponse): boolean => {
167
+ const reply = repliesByRequest.get(response.request);
168
+ return reply !== undefined && (reply.reliableTrailers ?? true);
169
+ };
170
+
171
+ /**
172
+ * The trailers of a response a transport built with {@link respond}, read
173
+ * after its body; empty for any other response (`fetch` exposes none). A
174
+ * transport that can't read them fails with a `DecodeError`.
175
+ */
176
+ export const trailersOf = (
177
+ response: HttpClientResponse.HttpClientResponse,
178
+ ): Effect.Effect<Trailers, HttpClientError.HttpClientError> => {
179
+ const reply = repliesByRequest.get(response.request);
180
+ return reply === undefined
181
+ ? Effect.succeed({})
182
+ : Effect.mapError(reply.trailers, (cause) => decodeError(response, cause));
183
+ };
184
+
185
+ const decodeError = (response: HttpClientResponse.HttpClientResponse, cause: unknown) =>
186
+ new HttpClientError.HttpClientError({
187
+ reason: new HttpClientError.DecodeError({ request: response.request, response, cause }),
188
+ });
189
+
190
+ /**
191
+ * An `HttpClientResponse` over a {@link Reply}, built like Effect's own web
192
+ * response, with the body read from the transport's stream.
193
+ */
194
+ class ReplyResponse extends Inspectable.Class implements HttpClientResponse.HttpClientResponse {
195
+ readonly [HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId;
196
+ readonly [HttpClientResponse.TypeId] = HttpClientResponse.TypeId;
197
+ readonly headers: Headers.Headers;
198
+ readonly cookies: Cookies.Cookies;
199
+ readonly remoteAddress = Option.none<string>();
200
+ /** The body, read once and shared by `arrayBuffer`, `text` and `json`. */
201
+ private bytes?: Deferred.Deferred<Uint8Array, HttpClientError.HttpClientError>;
202
+ readonly request: HttpClientRequest.HttpClientRequest;
203
+ private readonly reply: Reply;
204
+
205
+ constructor(request: HttpClientRequest.HttpClientRequest, reply: Reply) {
206
+ super();
207
+ this.request = request;
208
+ this.reply = reply;
209
+ this.headers = Headers.fromInput(reply.headers);
210
+ const setCookie = reply.headers["set-cookie"];
211
+ this.cookies = setCookie === undefined ? Cookies.empty : Cookies.fromSetCookie(setCookie);
212
+ }
213
+
214
+ get status(): number {
215
+ return this.reply.status;
216
+ }
217
+
218
+ get url(): string {
219
+ const url = HttpClientRequest.toUrl(this.request);
220
+ if (Option.isNone(url)) return "";
221
+ url.value.hash = "";
222
+ return url.value.href;
223
+ }
224
+
225
+ get stream(): Stream.Stream<Uint8Array, HttpClientError.HttpClientError> {
226
+ return Stream.mapError(this.reply.body, (cause) => decodeError(this, cause));
227
+ }
228
+
229
+ private get body(): Effect.Effect<Uint8Array, HttpClientError.HttpClientError> {
230
+ return Effect.suspend(() => {
231
+ if (this.bytes !== undefined) return Deferred.await(this.bytes);
232
+ const bytes = (this.bytes = Deferred.makeUnsafe());
233
+ return Effect.flatMap(Deferred.into(Stream.mkUint8Array(this.stream), bytes), () =>
234
+ Deferred.await(bytes),
235
+ );
236
+ });
237
+ }
238
+
239
+ get arrayBuffer(): Effect.Effect<ArrayBuffer, HttpClientError.HttpClientError> {
240
+ return Effect.map(this.body, (bytes) => bytes.slice().buffer as ArrayBuffer);
241
+ }
242
+
243
+ get text(): Effect.Effect<string, HttpClientError.HttpClientError> {
244
+ return Effect.map(this.body, (bytes) => new TextDecoder().decode(bytes));
245
+ }
246
+
247
+ get json(): Effect.Effect<Schema.Json, HttpClientError.HttpClientError> {
248
+ return Effect.flatMap(this.text, (text) =>
249
+ Effect.try({
250
+ try: () => (text === "" ? null : (JSON.parse(text) as Schema.Json)),
251
+ catch: (cause) => decodeError(this, cause),
252
+ }),
253
+ );
254
+ }
255
+
256
+ get urlParamsBody(): Effect.Effect<UrlParams.UrlParams, HttpClientError.HttpClientError> {
257
+ return Effect.map(this.text, (text) => UrlParams.fromInput(new URLSearchParams(text)));
258
+ }
259
+
260
+ get formData(): Effect.Effect<FormData, HttpClientError.HttpClientError> {
261
+ return Effect.fail(decodeError(this, new Error("a gRPC transport reads no form data")));
262
+ }
263
+
264
+ get upgrade(): Effect.Effect<never, HttpClientError.HttpClientError> {
265
+ return Effect.fail(
266
+ new HttpClientError.HttpClientError({
267
+ reason: new HttpClientError.StatusCodeError({
268
+ request: this.request,
269
+ response: this,
270
+ description: "a gRPC transport cannot hand over the connection of an HTTP upgrade",
271
+ }),
272
+ }),
273
+ );
274
+ }
275
+
276
+ toJSON(): unknown {
277
+ return HttpIncomingMessage.inspect(this, {
278
+ _id: "HttpClientResponse",
279
+ request: this.request.toJSON(),
280
+ status: this.status,
281
+ });
282
+ }
283
+
284
+ pipe() {
285
+ return pipeArguments(this, arguments);
286
+ }
287
+ }
package/src/hpack.ts ADDED
@@ -0,0 +1,331 @@
1
+ /**
2
+ * HPACK (RFC 7541), the header compression of HTTP/2, for a client that
3
+ * speaks HTTP/2 without a platform implementation
4
+ * (`grpc-transport-cloudflare-http2`).
5
+ *
6
+ * {@link makeDecoder} reads everything a server may send: the static and
7
+ * dynamic tables, every literal form, and Huffman-coded strings.
8
+ * {@link encode} writes the simplest valid form, each field as a literal
9
+ * with no indexing and no Huffman coding, so a connection keeps no encoder
10
+ * state.
11
+ */
12
+
13
+ /** A header block that breaks RFC 7541. HTTP/2 treats it as a connection error. */
14
+ export class HpackError extends Error {}
15
+
16
+ /** A header field: a lowercase name and its value. */
17
+ export type HeaderField = readonly [name: string, value: string];
18
+
19
+ /** RFC 7541 Appendix A. Index 1 is the first entry. */
20
+ const STATIC_TABLE: ReadonlyArray<HeaderField> = [
21
+ [":authority", ""],
22
+ [":method", "GET"],
23
+ [":method", "POST"],
24
+ [":path", "/"],
25
+ [":path", "/index.html"],
26
+ [":scheme", "http"],
27
+ [":scheme", "https"],
28
+ [":status", "200"],
29
+ [":status", "204"],
30
+ [":status", "206"],
31
+ [":status", "304"],
32
+ [":status", "400"],
33
+ [":status", "404"],
34
+ [":status", "500"],
35
+ ["accept-charset", ""],
36
+ ["accept-encoding", "gzip, deflate"],
37
+ ["accept-language", ""],
38
+ ["accept-ranges", ""],
39
+ ["accept", ""],
40
+ ["access-control-allow-origin", ""],
41
+ ["age", ""],
42
+ ["allow", ""],
43
+ ["authorization", ""],
44
+ ["cache-control", ""],
45
+ ["content-disposition", ""],
46
+ ["content-encoding", ""],
47
+ ["content-language", ""],
48
+ ["content-length", ""],
49
+ ["content-location", ""],
50
+ ["content-range", ""],
51
+ ["content-type", ""],
52
+ ["cookie", ""],
53
+ ["date", ""],
54
+ ["etag", ""],
55
+ ["expect", ""],
56
+ ["expires", ""],
57
+ ["from", ""],
58
+ ["host", ""],
59
+ ["if-match", ""],
60
+ ["if-modified-since", ""],
61
+ ["if-none-match", ""],
62
+ ["if-range", ""],
63
+ ["if-unmodified-since", ""],
64
+ ["last-modified", ""],
65
+ ["link", ""],
66
+ ["location", ""],
67
+ ["max-forwards", ""],
68
+ ["proxy-authenticate", ""],
69
+ ["proxy-authorization", ""],
70
+ ["range", ""],
71
+ ["referer", ""],
72
+ ["refresh", ""],
73
+ ["retry-after", ""],
74
+ ["server", ""],
75
+ ["set-cookie", ""],
76
+ ["strict-transport-security", ""],
77
+ ["transfer-encoding", ""],
78
+ ["user-agent", ""],
79
+ ["vary", ""],
80
+ ["via", ""],
81
+ ["www-authenticate", ""],
82
+ ];
83
+
84
+ /**
85
+ * RFC 7541 Appendix B: the bit length of each symbol's code (the 256 octets,
86
+ * then EOS). The code is canonical, so the codes themselves follow from the
87
+ * lengths: symbols ordered by length, then by value, count up from zero.
88
+ */
89
+ const HUFFMAN_BITS: ReadonlyArray<number> = [
90
+ 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 30, 28,
91
+ 28, 28, 28, 28, 28, 28, 28, 28, 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6, 5, 5, 5,
92
+ 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10, 13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
93
+ 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6, 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5, 6,
94
+ 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28, 20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23,
95
+ 23, 23, 24, 23, 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24, 22, 21, 20, 22,
96
+ 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23, 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22,
97
+ 23, 22, 22, 23, 26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25, 19, 21, 26, 27,
98
+ 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27, 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25,
99
+ 24, 24, 26, 23, 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26, 30,
100
+ ];
101
+
102
+ const EOS = 256;
103
+
104
+ /**
105
+ * The code as a binary tree in one array. Node `n` keeps its two branches at
106
+ * `2n` and `2n + 1`: a positive entry is the next node, a negative one is a
107
+ * symbol (`-(symbol + 1)`).
108
+ */
109
+ const buildHuffmanTree = (): number[] => {
110
+ // The sort is stable, so codes of one length stay in symbol order.
111
+ const symbols = HUFFMAN_BITS.map((bits, symbol) => ({ bits, symbol })).sort(
112
+ (a, b) => a.bits - b.bits,
113
+ );
114
+ const tree = [0, 0];
115
+ let code = 0;
116
+ let previous = 0;
117
+ for (const { bits, symbol } of symbols) {
118
+ code <<= bits - previous;
119
+ previous = bits;
120
+ let node = 0;
121
+ for (let bit = bits - 1; bit >= 0; bit--) {
122
+ const slot = node * 2 + ((code >>> bit) & 1);
123
+ if (bit === 0) tree[slot] = -(symbol + 1);
124
+ else {
125
+ if (tree[slot] === 0) {
126
+ tree[slot] = tree.length / 2;
127
+ tree.push(0, 0);
128
+ }
129
+ node = tree[slot]!;
130
+ }
131
+ }
132
+ code++;
133
+ }
134
+ return tree;
135
+ };
136
+
137
+ let huffmanTree: number[] | undefined;
138
+
139
+ /** Decode a Huffman-coded string (RFC 7541 section 5.2). */
140
+ export const huffmanDecode = (bytes: Uint8Array): Uint8Array => {
141
+ const tree = (huffmanTree ??= buildHuffmanTree());
142
+ const out: number[] = [];
143
+ let node = 0;
144
+ // The bits read since the last symbol: at the end they are the padding,
145
+ // which must be fewer than 8 bits, all ones.
146
+ let pending = 0;
147
+ let ones = true;
148
+ for (const byte of bytes) {
149
+ for (let bit = 7; bit >= 0; bit--) {
150
+ const value = (byte >>> bit) & 1;
151
+ const next = tree[node * 2 + value]!;
152
+ if (next < 0) {
153
+ const symbol = -next - 1;
154
+ if (symbol === EOS) throw new HpackError("Huffman string contains EOS");
155
+ out.push(symbol);
156
+ node = 0;
157
+ pending = 0;
158
+ ones = true;
159
+ } else {
160
+ node = next;
161
+ pending++;
162
+ if (value === 0) ones = false;
163
+ }
164
+ }
165
+ }
166
+ if (pending > 7 || !ones) throw new HpackError("invalid Huffman padding");
167
+ return Uint8Array.from(out);
168
+ };
169
+
170
+ // Header octets are opaque; one character per octet keeps them all, as
171
+ // `node:http2` does.
172
+ const textOf = (bytes: Uint8Array): string => {
173
+ let out = "";
174
+ for (let i = 0; i < bytes.length; i += 8192) {
175
+ out += String.fromCharCode(...bytes.subarray(i, i + 8192));
176
+ }
177
+ return out;
178
+ };
179
+
180
+ interface Entry {
181
+ readonly name: string;
182
+ readonly value: string;
183
+ /** RFC 7541 section 4.1: the octets of the name and value, plus 32. */
184
+ readonly size: number;
185
+ }
186
+
187
+ /** Reads the header blocks of one connection, in the order they arrive. */
188
+ export interface HpackDecoder {
189
+ /** The fields of one complete header block. */
190
+ decode(block: Uint8Array): HeaderField[];
191
+ }
192
+
193
+ /**
194
+ * A decoder for one connection. `maxTableSize` is the dynamic table size
195
+ * this end allows (`SETTINGS_HEADER_TABLE_SIZE`, 4096 unless set).
196
+ */
197
+ export const makeDecoder = (maxTableSize = 4096): HpackDecoder => {
198
+ // Newest first, so dynamic index 62 is `dynamic[0]`.
199
+ const dynamic: Entry[] = [];
200
+ let size = 0;
201
+ let limit = maxTableSize;
202
+
203
+ const evict = () => {
204
+ while (size > limit) size -= dynamic.pop()!.size;
205
+ };
206
+
207
+ const lookup = (index: number): { readonly name: string; readonly value: string } => {
208
+ if (index >= 1 && index <= STATIC_TABLE.length) {
209
+ const [name, value] = STATIC_TABLE[index - 1]!;
210
+ return { name, value };
211
+ }
212
+ const entry = dynamic[index - STATIC_TABLE.length - 1];
213
+ if (entry === undefined) throw new HpackError(`no header at index ${index}`);
214
+ return entry;
215
+ };
216
+
217
+ return {
218
+ decode(block) {
219
+ const fields: HeaderField[] = [];
220
+ let at = 0;
221
+
222
+ // Every caller has checked that the octet the integer starts in is there.
223
+ const integer = (prefix: number): number => {
224
+ const max = 2 ** prefix - 1;
225
+ let value = block[at++]! & max;
226
+ if (value < max) return value;
227
+ for (let shift = 0; ; shift += 7) {
228
+ if (at >= block.length) throw new HpackError("header block ends inside an integer");
229
+ if (shift > 28) throw new HpackError("integer is too large");
230
+ const byte = block[at++]!;
231
+ value += (byte & 0x7f) * 2 ** shift;
232
+ if ((byte & 0x80) === 0) return value;
233
+ }
234
+ };
235
+
236
+ const string = (): { readonly text: string; readonly octets: number } => {
237
+ const first = block[at];
238
+ if (first === undefined) throw new HpackError("header block ends inside a string");
239
+ const huffman = (first & 0x80) !== 0;
240
+ const length = integer(7);
241
+ if (at + length > block.length) throw new HpackError("header block ends inside a string");
242
+ const raw = block.subarray(at, at + length);
243
+ at += length;
244
+ const bytes = huffman ? huffmanDecode(raw) : raw;
245
+ return { text: textOf(bytes), octets: bytes.length };
246
+ };
247
+
248
+ const literal = (prefix: number, index: boolean) => {
249
+ const nameIndex = integer(prefix);
250
+ let name: string;
251
+ let nameOctets: number;
252
+ if (nameIndex === 0) {
253
+ const read = string();
254
+ name = read.text;
255
+ nameOctets = read.octets;
256
+ } else {
257
+ name = lookup(nameIndex).name;
258
+ nameOctets = name.length;
259
+ }
260
+ const value = string();
261
+ fields.push([name, value.text]);
262
+ if (index) {
263
+ const entry = { name, value: value.text, size: nameOctets + value.octets + 32 };
264
+ dynamic.unshift(entry);
265
+ size += entry.size;
266
+ evict();
267
+ }
268
+ };
269
+
270
+ while (at < block.length) {
271
+ const first = block[at]!;
272
+ if ((first & 0x80) !== 0) {
273
+ const { name, value } = lookup(integer(7));
274
+ fields.push([name, value]);
275
+ } else if ((first & 0x40) !== 0) {
276
+ literal(6, true);
277
+ } else if ((first & 0x20) !== 0) {
278
+ // RFC 7541 section 4.2: only at the start of a block.
279
+ if (fields.length > 0) {
280
+ throw new HpackError("dynamic table size update after a header field");
281
+ }
282
+ const next = integer(5);
283
+ if (next > maxTableSize) throw new HpackError("dynamic table size exceeds the limit");
284
+ limit = next;
285
+ evict();
286
+ } else {
287
+ // Without indexing (0000) and never indexed (0001) read the same.
288
+ literal(4, false);
289
+ }
290
+ }
291
+ return fields;
292
+ },
293
+ };
294
+ };
295
+
296
+ const encoder = /*@__PURE__*/ new TextEncoder();
297
+
298
+ const pushInteger = (out: number[], value: number, prefix: number, flags: number) => {
299
+ const max = 2 ** prefix - 1;
300
+ if (value < max) {
301
+ out.push(flags | value);
302
+ return;
303
+ }
304
+ out.push(flags | max);
305
+ let rest = value - max;
306
+ while (rest >= 128) {
307
+ out.push((rest % 128) | 0x80);
308
+ rest = Math.floor(rest / 128);
309
+ }
310
+ out.push(rest);
311
+ };
312
+
313
+ const pushString = (out: number[], text: string) => {
314
+ const bytes = encoder.encode(text);
315
+ pushInteger(out, bytes.length, 7, 0);
316
+ for (const byte of bytes) out.push(byte);
317
+ };
318
+
319
+ /**
320
+ * A header block for `fields`, each a literal without indexing (RFC 7541
321
+ * section 6.2.2). Names must be lowercase, pseudo-headers first.
322
+ */
323
+ export const encode = (fields: ReadonlyArray<HeaderField>): Uint8Array => {
324
+ const out: number[] = [];
325
+ for (const [name, value] of fields) {
326
+ out.push(0);
327
+ pushString(out, name);
328
+ pushString(out, value);
329
+ }
330
+ return Uint8Array.from(out);
331
+ };
package/src/index.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * `@distilled.cloud/core` -- the runtime shared by every distilled SDK.
3
+ *
4
+ * ```ts
5
+ * import { ResponseValidation, Retry } from "@distilled.cloud/core";
6
+ *
7
+ * program.pipe(Effect.provide(ResponseValidation.strict));
8
+ * ```
9
+ *
10
+ * Each namespace is also importable on its own subpath
11
+ * (`@distilled.cloud/core/response-validation`, ...); generated SDKs use the
12
+ * subpaths. The code generator and test helpers live in the unpublished
13
+ * `@distilled.cloud/dev` package.
14
+ */
15
+ export * as API from "./api.ts";
16
+ export * as Category from "./category.ts";
17
+ export * as Errors from "./errors.ts";
18
+ export * as GraphQL from "./graphql.ts";
19
+ export * as GrpcTransport from "./grpc-transport.ts";
20
+ export * as Pagination from "./pagination.ts";
21
+ export * as ProtocolGrpc from "./protocol-grpc.ts";
22
+ export * as ProtocolHttp from "./protocol-http.ts";
23
+ export * as ProtocolRest from "./protocol-rest.ts";
24
+ export { Query } from "./query.ts";
25
+ export * as Crypto from "./crypto.ts";
26
+ export * as ResponseValidation from "./response-validation.ts";
27
+ export * as Retry from "./retry.ts";
28
+ export * as RetryAfter from "./retry-after.ts";
29
+ export * as Sensitive from "./sensitive.ts";
30
+ export * as Telemetry from "./telemetry.ts";
31
+ export * as Trait from "./trait.ts";