@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,150 @@
1
+ /**
2
+ * What a protocol is, typed by the errors it declares.
3
+ *
4
+ * An operation fails with three groups of errors, each named for where it
5
+ * is declared:
6
+ *
7
+ * 1. on the operation its `errors` list
8
+ * 2. on the service its `serviceErrors` list, the same for every
9
+ * operation of the service
10
+ * 3. on the protocol the {@link Protocol}'s own error type: what the
11
+ * code that builds requests and reads responses
12
+ * fails with (a response it can't parse, mostly)
13
+ *
14
+ * `API.make` adds the three together. A protocol never names an error of
15
+ * groups 1 and 2: it receives their classes, matches a failed response
16
+ * against them, and fails with the instance as a {@link DeclaredError}.
17
+ * Everything else it fails with is in its own type, and passes through to
18
+ * every operation that names the protocol. Nobody writes that list: the
19
+ * compiler reads it from the protocol's code ({@link ErrorOf}, and
20
+ * {@link ProtocolOf} for a protocol written by hand).
21
+ *
22
+ * export const NeonProtocol = restProtocol({ ... });
23
+ * export type NeonOpError = NeonServiceError | ErrorOf<typeof NeonProtocol>;
24
+ *
25
+ * Types only: this module has no runtime code.
26
+ */
27
+ import type * as Effect from "effect/Effect";
28
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest";
29
+ import type * as HttpClientResponse from "effect/http/HttpClientResponse";
30
+ import type * as AST from "effect/SchemaAST";
31
+ import type * as Stream from "effect/Stream";
32
+ import type { PreparedOperation, ProtocolOperationConfig } from "./api.ts";
33
+
34
+ declare const declaredError: unique symbol;
35
+
36
+ /**
37
+ * An error of group 1 or 2 as a protocol sees it: an instance of a class
38
+ * that the operation or its service declares. A protocol can construct one
39
+ * from a {@link DeclaredErrorClass} and fail with it; `API.make` puts the
40
+ * real classes in the operation's error type.
41
+ */
42
+ export interface DeclaredError {
43
+ readonly [declaredError]: true;
44
+ }
45
+
46
+ /** A class that the operation or its service declares, as a protocol receives it. */
47
+ export type DeclaredErrorClass = new (props: any) => DeclaredError;
48
+
49
+ /** What {@link Protocol.encode} receives. */
50
+ export interface EncodeArgs {
51
+ readonly input: unknown;
52
+ readonly inputAst: AST.AST;
53
+ /** The operation's config (the same object on every call of the operation). */
54
+ readonly config: ProtocolOperationConfig;
55
+ }
56
+
57
+ /** What {@link Protocol.decode} receives. */
58
+ export interface DecodeArgs {
59
+ readonly response: HttpClientResponse.HttpClientResponse;
60
+ readonly outputAst: AST.AST;
61
+ /** The operation's declared classes, then its service's. */
62
+ readonly errors: ReadonlyArray<DeclaredErrorClass>;
63
+ /** The operation's config (the same object on every call of the operation). */
64
+ readonly config: ProtocolOperationConfig;
65
+ }
66
+
67
+ /** One operation as {@link Protocol.call} and {@link Protocol.stream} see it. */
68
+ export interface Operation extends Omit<PreparedOperation, "errors"> {
69
+ /** The operation's declared classes, then its service's. */
70
+ readonly errors: ReadonlyArray<DeclaredErrorClass>;
71
+ }
72
+
73
+ /**
74
+ * How an SDK turns an input into an HTTP request and a response into an
75
+ * output. `ProtocolError` is what the protocol declares (group 3), and
76
+ * `Requirements` is what its methods read from the calling fiber
77
+ * (credentials, a region).
78
+ *
79
+ * A request that was not sent has no response to match, so `encode` fails
80
+ * with the protocol's errors only.
81
+ */
82
+ export interface Protocol<ProtocolError, Requirements = never> {
83
+ readonly encode: (
84
+ args: EncodeArgs,
85
+ ) => Effect.Effect<HttpClientRequest.HttpClientRequest, ProtocolError, Requirements>;
86
+ readonly decode: (
87
+ args: DecodeArgs,
88
+ ) => Effect.Effect<unknown, DeclaredError | ProtocolError, Requirements>;
89
+ /**
90
+ * Optional whole call. When present, `API.make` runs a call as
91
+ * `call(operation, input)` in place of encode, send, decode. It reads the
92
+ * `HttpClient` from the calling fiber and produces the same request,
93
+ * result and errors as `encode` and `decode`.
94
+ */
95
+ readonly call?: (
96
+ operation: Operation,
97
+ input: unknown,
98
+ ) => Effect.Effect<unknown, DeclaredError | ProtocolError, Requirements>;
99
+ /**
100
+ * Server streaming (see `API.makeStreaming`): each response message as it
101
+ * arrives, decoded as one element of the output's `items`. Ending the
102
+ * stream early cancels the call. A protocol that can't stream leaves it
103
+ * out; one that streams only some operations fails the others with
104
+ * `API.cannotStream`.
105
+ */
106
+ readonly stream?: (
107
+ operation: Operation,
108
+ input: unknown,
109
+ ) => Stream.Stream<unknown, DeclaredError | ProtocolError, Requirements>;
110
+ }
111
+
112
+ /** What the methods of `P` return: its effects and its stream. */
113
+ type Outcome<P> = P[Extract<keyof P, keyof Protocol<unknown>>] extends infer Method
114
+ ? Method extends (...args: any) => infer Result
115
+ ? Result
116
+ : never
117
+ : never;
118
+
119
+ /**
120
+ * The errors a protocol declares (group 3), read from what its methods fail
121
+ * with. An SDK uses it to name what every operation fails with besides its
122
+ * own errors: `<Sdk>ServiceError | ErrorOf<typeof <Sdk>Protocol>`.
123
+ */
124
+ export type ErrorOf<P> =
125
+ Outcome<P> extends infer Result
126
+ ? Result extends Effect.Effect<any, infer Failure, any>
127
+ ? Exclude<Failure, DeclaredError>
128
+ : Result extends Stream.Stream<any, infer Failure, any>
129
+ ? Exclude<Failure, DeclaredError>
130
+ : never
131
+ : never;
132
+
133
+ /** What a protocol's methods read from the calling fiber. */
134
+ export type RequirementsOf<P> =
135
+ Outcome<P> extends infer Result
136
+ ? Result extends Effect.Effect<any, any, infer Requirements>
137
+ ? Requirements
138
+ : Result extends Stream.Stream<any, any, infer Requirements>
139
+ ? Requirements
140
+ : never
141
+ : never;
142
+
143
+ /**
144
+ * The type of a protocol written by hand, read from its methods, so that
145
+ * nobody lists its errors:
146
+ *
147
+ * const methods = { encode, decode } satisfies Protocol<unknown, unknown>;
148
+ * export const GcpProtocol: ProtocolOf<typeof methods> = methods;
149
+ */
150
+ export type ProtocolOf<Methods> = Protocol<ErrorOf<Methods>, RequirementsOf<Methods>>;
package/src/query.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Query combinators for GraphQL SDKs.
3
+ *
4
+ * Import this module next to a generated client:
5
+ *
6
+ * import { Query } from "@distilled.cloud/core/query"
7
+ * import { Railway } from "@distilled.cloud/railway"
8
+ *
9
+ * `Query.fn` takes a **builder** (plain function, not `Effect.gen`) that
10
+ * returns a plan of `Query<Value>` and `Effect` values. It walks Map /
11
+ * Filter / FlatMap / Of, posts one GraphQL document, then interprets the
12
+ * plan. Roots (`Railway.me`) come from the generated SDK; they are not
13
+ * combinators.
14
+ *
15
+ * @see {@link file://./graphql.ts} for the algebra, compiler, and transport.
16
+ */
17
+ import {
18
+ filterQuery,
19
+ flatMapQuery,
20
+ itemsQuery,
21
+ mapQuery,
22
+ ofQuery,
23
+ pagesQuery,
24
+ queryFn,
25
+ type Query as QueryType,
26
+ } from "./graphql.ts";
27
+
28
+ export type Query<Value, Error = never> = QueryType<Value, Error>;
29
+ export type { PlanError, QueryError, UnwrapPlan } from "./graphql.ts";
30
+
31
+ export const Query = {
32
+ fn: queryFn,
33
+ filter: filterQuery,
34
+ map: mapQuery,
35
+ flatMap: flatMapQuery,
36
+ of: ofQuery,
37
+ pages: pagesQuery,
38
+ items: itemsQuery,
39
+ };
@@ -0,0 +1,333 @@
1
+ /**
2
+ * The strict response checker: validates a decoded response against its
3
+ * output AST without Effect Schema.
4
+ *
5
+ * Generated output schemas are lite nodes (`schema-lite-impl.ts`); the
6
+ * checker accepts what Effect Schema's decoder accepted for the schema
7
+ * `toEffect` built from them (`response-validation-strict.test.ts` compares
8
+ * the two on random schemas and values). Each AST node compiles once to a
9
+ * closure, so a check walks the value only.
10
+ *
11
+ * Two modes: `additionalProperties` lets keys an object does not model
12
+ * through (Effect's default), `strict` (`exact`) rejects them (Effect's
13
+ * `onExcessProperty: "error"`). In both, an index signature covers only the
14
+ * keys the object does not declare (OpenAPI `additionalProperties`), and an
15
+ * empty struct accepts any object (generated code's opaque output).
16
+ *
17
+ * Hand-written protocols may pass real Effect ASTs. Their structure is
18
+ * checked the same way; refinement `checks` run, but a real `Declaration`
19
+ * with type parameters and `TemplateLiteral` contents are not checked.
20
+ */
21
+ import type * as AST from "effect/SchemaAST";
22
+ import type { Node } from "./schema-lite-impl.ts";
23
+
24
+ /** A response that does not match its output schema (the `cause` of a strict `<Sdk>ParseError`). */
25
+ export class SchemaMismatch extends Error {
26
+ override readonly name = "SchemaError";
27
+ /** Where in the response the mismatch is, outermost key first. */
28
+ readonly path: ReadonlyArray<PropertyKey>;
29
+ /** What the schema expected there, e.g. `string`. */
30
+ readonly expected: string;
31
+ readonly actual: unknown;
32
+ constructor(path: ReadonlyArray<PropertyKey>, expected: string, actual: unknown) {
33
+ super(
34
+ `Expected ${expected}, got ${show(actual)}${path.length ? ` at ${JSON.stringify(path.map((k) => (typeof k === "symbol" ? String(k) : k)))}` : ""}`,
35
+ );
36
+ this.path = path;
37
+ this.expected = expected;
38
+ this.actual = actual;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * `mismatch` with its offending value replaced by `"[REDACTED]"`, for a parse
44
+ * error that withholds the body (the value may be a secret).
45
+ */
46
+ export const withholdActual = (mismatch: SchemaMismatch): SchemaMismatch =>
47
+ new SchemaMismatch(mismatch.path, mismatch.expected, "[REDACTED]");
48
+
49
+ /**
50
+ * Validate `input` synchronously: `undefined` when it matches, else the
51
+ * mismatch.
52
+ */
53
+ export type Decode = (input: unknown) => SchemaMismatch | undefined;
54
+
55
+ const show = (u: unknown): string => {
56
+ if (u === MISSING) return "nothing (missing key)";
57
+ if (u === undefined) return "undefined";
58
+ if (typeof u === "string") return JSON.stringify(u.length > 40 ? `${u.slice(0, 40)}...` : u);
59
+ if (Array.isArray(u)) return "an array";
60
+ if (u !== null && typeof u === "object") return "an object";
61
+ return String(u);
62
+ };
63
+
64
+ /** A failed check: the path is filled in on the way out, innermost key first. */
65
+ interface Fail {
66
+ readonly path: PropertyKey[];
67
+ readonly expected: string;
68
+ readonly actual: unknown;
69
+ }
70
+ type Check = (u: unknown) => Fail | undefined;
71
+
72
+ const MISSING: unique symbol = Symbol("missing");
73
+ /**
74
+ * The node compiler, built on the first strict check: importing this module
75
+ * (every REST program does, through the protocol) allocates almost nothing.
76
+ */
77
+ const makeCompile = (exact: boolean): ((n: Node) => Check) => {
78
+ const fail = (expected: string, actual: unknown): Fail => ({ path: [], expected, actual });
79
+ const ok: Check = () => undefined;
80
+ // Effect's rule (SchemaAST.requiresOwnProperty, since 4.1.3): a field named
81
+ // after an `Object.prototype` member is present only as an own property,
82
+ // so `{}` has no `constructor`.
83
+ const prototypeKeys = new Set<PropertyKey>(Reflect.ownKeys(Object.prototype)).add("__proto__");
84
+ const ownOnly = (name: PropertyKey) =>
85
+ prototypeKeys.has(typeof name === "number" ? String(name) : name);
86
+ const typeOf =
87
+ (t: string): Check =>
88
+ (u) =>
89
+ typeof u === t ? undefined : fail(t, u);
90
+
91
+ const compiled = new WeakMap<object, Check>();
92
+
93
+ const compile = (n: Node): Check => {
94
+ let c = compiled.get(n);
95
+ if (c === undefined) {
96
+ // A node reached again while it compiles (only through Suspend) calls
97
+ // through this slot.
98
+ let self: Check | undefined;
99
+ compiled.set(n, (u) => self!(u));
100
+ self = c = withChecks(n, build(n));
101
+ compiled.set(n, c);
102
+ }
103
+ return c;
104
+ };
105
+
106
+ /** Effect refinements (`checks`) on real nodes run after the structural check. */
107
+ const withChecks = (n: Node, base: Check): Check => {
108
+ const checks = (n as { checks?: ReadonlyArray<any> }).checks;
109
+ if (!checks?.length || isLite(n)) return base;
110
+ const flat: any[] = [];
111
+ const add = (c: any) => (c._tag === "FilterGroup" ? c.checks.forEach(add) : flat.push(c));
112
+ checks.forEach(add);
113
+ return (u) => {
114
+ const f = base(u);
115
+ if (f) return f;
116
+ for (const c of flat) {
117
+ const r = c.run(u, n, {});
118
+ if (r !== undefined && r !== true)
119
+ return fail(String(c.annotations?.expected ?? "a valid value"), u);
120
+ }
121
+ return undefined;
122
+ };
123
+ };
124
+
125
+ const isLite = (n: Node): boolean => (n as any)["~lite"] === true;
126
+
127
+ const isOptional = (n: Node): boolean => n.context?.isOptional === true;
128
+
129
+ const build = (n: Node): Check => {
130
+ // A real node that decodes from another form is checked in that form (the
131
+ // body as read); lite encodings are type-side only.
132
+ const encoding = (n as { encoding?: ReadonlyArray<{ to: Node }> }).encoding;
133
+ if (encoding?.length && !isLite(n)) return compile(encoding[encoding.length - 1]!.to);
134
+ switch (n._tag) {
135
+ case "String":
136
+ case "TemplateLiteral":
137
+ return typeOf("string");
138
+ case "Number":
139
+ return typeOf("number");
140
+ case "Boolean":
141
+ return typeOf("boolean");
142
+ case "BigInt":
143
+ return typeOf("bigint");
144
+ case "Symbol":
145
+ return typeOf("symbol");
146
+ case "Null":
147
+ return (u) => (u === null ? undefined : fail("null", u));
148
+ case "Undefined":
149
+ return (u) => (u === undefined ? undefined : fail("undefined", u));
150
+ case "Never":
151
+ return (u) => fail("never", u);
152
+ case "Literal":
153
+ case "UniqueSymbol": {
154
+ const lit = n._tag === "Literal" ? n.literal : (n as any).symbol;
155
+ return (u) => (u === lit ? undefined : fail(show(lit), u));
156
+ }
157
+ case "Enum": {
158
+ const values = ((n as any).enums as ReadonlyArray<readonly [string, unknown]>).map(
159
+ (e) => e[1],
160
+ );
161
+ return (u) => (values.includes(u) ? undefined : fail("an enum value", u));
162
+ }
163
+ case "ObjectKeyword":
164
+ return (u) =>
165
+ (typeof u === "object" && u !== null) || typeof u === "function"
166
+ ? undefined
167
+ : fail("object | function", u);
168
+ case "Union":
169
+ return union(n);
170
+ case "Arrays":
171
+ return arrays(n);
172
+ case "Objects":
173
+ return objects(n);
174
+ case "Suspend": {
175
+ let inner: Check | undefined;
176
+ return (u) => (inner ??= compile(n.thunk!()))(u);
177
+ }
178
+ case "Declaration": {
179
+ if (isLite(n)) {
180
+ const check = n.check;
181
+ const name = String(n.annotations?.identifier ?? "a valid value");
182
+ return check ? (u) => (check(u) ? undefined : fail(name, u)) : ok;
183
+ }
184
+ return declaration(n);
185
+ }
186
+ default:
187
+ // Unknown, Any, Void (Effect's `void` accepts any value) and anything
188
+ // without structure.
189
+ return ok;
190
+ }
191
+ };
192
+
193
+ /** A real Effect declaration without type parameters runs its own parser (synchronous ones only). */
194
+ const declaration = (n: Node): Check => {
195
+ const run = (n as any).run as ((tps: ReadonlyArray<unknown>) => any) | undefined;
196
+ if (!run || n.typeParameters?.length) return ok;
197
+ let parse: any;
198
+ return (u) => {
199
+ const exit = (parse ??= run([]))(u, n, {});
200
+ return exit?._tag === "Failure"
201
+ ? fail(String(n.annotations?.identifier ?? n.annotations?.expected ?? "a valid value"), u)
202
+ : undefined;
203
+ };
204
+ };
205
+
206
+ const union = (n: Node): Check => {
207
+ const members = n.types!.map(compile);
208
+ return (u) => {
209
+ let first: Fail | undefined;
210
+ for (let i = 0; i < members.length; i++) {
211
+ const f = members[i]!(u);
212
+ if (f === undefined) return undefined;
213
+ first ??= f;
214
+ }
215
+ return members.length === 1 ? first : fail("a union member", u);
216
+ };
217
+ };
218
+
219
+ const arrays = (n: Node): Check => {
220
+ const elements = (n.elements ?? []).map((e) => [compile(e), isOptional(e)] as const);
221
+ const rest = (n.rest ?? []).map(compile);
222
+ const head = rest[0];
223
+ const tail = rest.slice(1);
224
+ return (u) => {
225
+ if (!Array.isArray(u)) return fail("array", u);
226
+ const len = u.length;
227
+ for (let i = 0; i < elements.length; i++) {
228
+ const [check, optional] = elements[i]!;
229
+ if (i >= len) {
230
+ if (optional) continue;
231
+ return at(fail("an element", MISSING), i);
232
+ }
233
+ const f = check(u[i]);
234
+ if (f) return at(f, i);
235
+ }
236
+ if (head === undefined) {
237
+ return len > elements.length
238
+ ? at(fail("never", u[elements.length]), elements.length)
239
+ : undefined;
240
+ }
241
+ const end = len - tail.length;
242
+ if (end < elements.length) return at(fail("an element", MISSING), len);
243
+ for (let i = elements.length; i < end; i++) {
244
+ const f = head(u[i]);
245
+ if (f) return at(f, i);
246
+ }
247
+ for (let j = 0; j < tail.length; j++) {
248
+ const f = tail[j]!(u[end + j]);
249
+ if (f) return at(f, end + j);
250
+ }
251
+ return undefined;
252
+ };
253
+ };
254
+
255
+ const at = (f: Fail, key: PropertyKey): Fail => {
256
+ f.path.push(key);
257
+ return f;
258
+ };
259
+
260
+ const objects = (n: Node): Check => {
261
+ const props = (n.propertySignatures ?? []).map(
262
+ (p) => [p.name, compile(p.type), isOptional(p.type), ownOnly(p.name)] as const,
263
+ );
264
+ const index = (n.indexSignatures ?? []).map(
265
+ (s) => [compile(s.parameter), compile(s.type)] as const,
266
+ );
267
+ const known = new Set(props.map((p) => p[0]));
268
+ // Effect's empty struct is TypeScript's `{}`: any value but null and undefined.
269
+ // Exact mode leaves it open too: generated code emits `{}` for outputs
270
+ // it does not model.
271
+ if (props.length === 0 && index.length === 0) {
272
+ return (u) => (u === null || u === undefined ? fail("{}", u) : undefined);
273
+ }
274
+ return (u) => {
275
+ if (typeof u !== "object" || u === null || Array.isArray(u)) return fail("object", u);
276
+ const o = u as Record<PropertyKey, unknown>;
277
+ for (let i = 0; i < props.length; i++) {
278
+ const [name, check, optional, own] = props[i]!;
279
+ if (!(Object.hasOwn(o, name) || (!own && name in o))) {
280
+ if (optional) continue;
281
+ return at(fail("a value", MISSING), name);
282
+ }
283
+ const f = check(o[name]);
284
+ if (f) return at(f, name);
285
+ }
286
+ if (index.length || exact) {
287
+ for (const key of Object.keys(o)) {
288
+ if (known.has(key)) continue;
289
+ let covered = false;
290
+ for (const [param, check] of index) {
291
+ if (param(key) !== undefined) continue;
292
+ covered = true;
293
+ const f = check(o[key]);
294
+ if (f) return at(f, key);
295
+ }
296
+ if (exact && !covered) {
297
+ return at(fail("no value (the schema does not model this key)", o[key]), key);
298
+ }
299
+ }
300
+ }
301
+ return undefined;
302
+ };
303
+ };
304
+
305
+ return compile;
306
+ };
307
+ let compileNode: ((n: Node) => Check) | undefined;
308
+ let compileExact: ((n: Node) => Check) | undefined;
309
+
310
+ /**
311
+ * The checker for an output AST: compiled once per node and mode, then
312
+ * reused. `exact` also rejects keys an object does not model (the `strict`
313
+ * mode); without it they pass (`additionalProperties`).
314
+ */
315
+ export const decoderFor = (ast: AST.AST, exact = false): Decode => {
316
+ const decoders = exact ? exactDecoders : openDecoders;
317
+ let decode = decoders.get(ast);
318
+ if (decode === undefined) {
319
+ const check = exact
320
+ ? (compileExact ??= makeCompile(true))(ast as unknown as Node)
321
+ : (compileNode ??= makeCompile(false))(ast as unknown as Node);
322
+ decode = (input) => {
323
+ const f = check(input);
324
+ return f === undefined
325
+ ? undefined
326
+ : new SchemaMismatch(f.path.reverse(), f.expected, f.actual);
327
+ };
328
+ decoders.set(ast, decode);
329
+ }
330
+ return decode;
331
+ };
332
+ const openDecoders = /*@__PURE__*/ new WeakMap<AST.AST, Decode>();
333
+ const exactDecoders = /*@__PURE__*/ new WeakMap<AST.AST, Decode>();
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Response validation mode, shared by every distilled SDK.
3
+ *
4
+ * Generated SDKs carry a schema for every operation's output. What a
5
+ * protocol does with it on a 2xx response depends on the mode:
6
+ *
7
+ * lenient (default): the response is returned as the protocol read it.
8
+ * A body that does not match the declared output type
9
+ * (a missing member, a wrong primitive, a non-JSON
10
+ * body) still succeeds, except that a non-JSON body for
11
+ * an output with sensitive members fails in every mode
12
+ * (REST-style protocols through core's `checkSuccess`
13
+ * in `protocol-rest`, plus ZeroSSL and AWS).
14
+ * additionalProperties: the response is checked against the output
15
+ * schema, and a mismatch fails the call with the SDK's
16
+ * `<Sdk>ParseError` (AWS: `ParseError`). Keys the
17
+ * schema does not model are allowed and kept.
18
+ * strict: as `additionalProperties`, and a key the schema does
19
+ * not model also fails the call, at any depth. Open
20
+ * objects (an index signature, e.g. OpenAPI
21
+ * `additionalProperties`) and empty structs (opaque
22
+ * outputs) still accept any key.
23
+ *
24
+ * The mode is one {@link ResponseValidation} reference keyed by a string, so
25
+ * a single `Layer` switches every distilled SDK in a program -- AWS,
26
+ * Cloudflare, Neon, ... -- at once, and nests like any other Effect service:
27
+ *
28
+ * ```ts
29
+ * import { ResponseValidation } from "@distilled.cloud/core";
30
+ *
31
+ * // whole program
32
+ * program.pipe(Effect.provide(ResponseValidation.strict));
33
+ *
34
+ * // one call back to lenient inside a strict program
35
+ * Neon.getProject({ projectId }).pipe(Effect.provide(ResponseValidation.lenient));
36
+ * ```
37
+ *
38
+ * The mode is set only by these layers; without one, every call is lenient.
39
+ */
40
+ import * as Context from "effect/Context";
41
+ import * as Effect from "effect/Effect";
42
+ import * as Layer from "effect/Layer";
43
+ import type * as AST from "effect/SchemaAST";
44
+ import { type Decode, decoderFor, SchemaMismatch } from "./response-validation-strict.ts";
45
+
46
+ export { SchemaMismatch, withholdActual } from "./response-validation-strict.ts";
47
+
48
+ export type Mode = "lenient" | "additionalProperties" | "strict";
49
+
50
+ /**
51
+ * The active validation mode. Read by protocols at call time on the calling
52
+ * fiber; `lenient` unless an {@link additionalProperties} or {@link strict}
53
+ * layer is provided.
54
+ */
55
+ export const ResponseValidation = /*@__PURE__*/ Context.Reference<Mode>(
56
+ "@distilled.cloud/core/ResponseValidation",
57
+ { defaultValue: () => "lenient" },
58
+ );
59
+
60
+ /**
61
+ * The checker the validating modes use (`exact`: reject unmodeled keys). The
62
+ * `additionalProperties` and `strict` layers provide it, so the checker is
63
+ * bundled only with programs that validate.
64
+ */
65
+ export const StrictDecoder = /*@__PURE__*/ Context.Reference<
66
+ ((ast: AST.AST, exact: boolean) => Decode) | undefined
67
+ >("@distilled.cloud/core/ResponseValidation/StrictDecoder", { defaultValue: () => undefined });
68
+
69
+ /**
70
+ * A layer that is also the `Context` it provides. `Effect.provide` treats a
71
+ * `Context` as a plain `provideContext`, so `Effect.provide(strict)` around
72
+ * a single call costs a context merge instead of a layer build (scope, memo
73
+ * map and a few fibers steps per call); every other use sees an ordinary
74
+ * `Layer`. The context state is read through the prototype.
75
+ */
76
+ const layerOfContext = (context: Context.Context<never>): Layer.Layer<never> => {
77
+ const layer = Layer.succeedContext(context);
78
+ const both = Object.create(context);
79
+ const layerProto = Object.getPrototypeOf(layer);
80
+ for (const key of Reflect.ownKeys(layerProto)) {
81
+ if (key !== "pipe") both[key] = layerProto[key];
82
+ }
83
+ both.build = (layer as unknown as { build: unknown }).build;
84
+ return both;
85
+ };
86
+
87
+ /**
88
+ * Check every 2xx response against its output schema and fail on a
89
+ * mismatch, including any key the schema does not model.
90
+ */
91
+ export const strict: Layer.Layer<never> = /*@__PURE__*/ layerOfContext(
92
+ /*@__PURE__*/ Context.add(
93
+ /*@__PURE__*/ Context.make(ResponseValidation, "strict"),
94
+ StrictDecoder,
95
+ decoderFor,
96
+ ),
97
+ );
98
+
99
+ /**
100
+ * Check every 2xx response against its output schema and fail on a
101
+ * mismatch; keys the schema does not model are allowed.
102
+ */
103
+ export const additionalProperties: Layer.Layer<never> = /*@__PURE__*/ layerOfContext(
104
+ /*@__PURE__*/ Context.add(
105
+ /*@__PURE__*/ Context.make(ResponseValidation, "additionalProperties"),
106
+ StrictDecoder,
107
+ decoderFor,
108
+ ),
109
+ );
110
+
111
+ /** Return 2xx responses as read, without checking them against the schema. */
112
+ export const lenient: Layer.Layer<never> = /*@__PURE__*/ layerOfContext(
113
+ /*@__PURE__*/ Context.make(ResponseValidation, "lenient"),
114
+ );
115
+
116
+ /** Whether the calling fiber validates responses (any mode but lenient). */
117
+ export const isValidating: Effect.Effect<boolean> = /*@__PURE__*/ Effect.map(
118
+ ResponseValidation,
119
+ (mode) => mode !== "lenient",
120
+ );
121
+
122
+ /**
123
+ * For a 2xx body the protocol could not read into the shape it transforms
124
+ * (e.g. invalid JSON): fail with `error` when validating, succeed with
125
+ * `asRead` (usually the body text) in lenient mode.
126
+ */
127
+ export const failUnlessLenient = <A, E>(error: E, asRead: A): Effect.Effect<A, E> =>
128
+ Effect.flatMap(ResponseValidation, (mode) =>
129
+ mode === "lenient" ? Effect.succeed(asRead) : Effect.fail(error),
130
+ );
131
+
132
+ /**
133
+ * The schema error for `value` against `outputAst` when validating,
134
+ * `undefined` when it matches or the mode is lenient. Synchronous, for
135
+ * protocols that already hold the calling fiber's context.
136
+ */
137
+ export const checkResponse = (
138
+ context: Context.Context<any>,
139
+ outputAst: AST.AST,
140
+ value: unknown,
141
+ ): SchemaMismatch | undefined => {
142
+ const mode = Context.get(context, ResponseValidation);
143
+ if (mode === "lenient") return undefined;
144
+ const decoderOf = Context.get(context, StrictDecoder);
145
+ if (!decoderOf) {
146
+ // The mode was set without the layer that brings its decoder: the
147
+ // response can't be checked, so the call fails as a mismatch.
148
+ return new SchemaMismatch([], `the ResponseValidation.${mode} layer`, mode);
149
+ }
150
+ return decoderOf(outputAst, mode === "strict")(value);
151
+ };
152
+
153
+ export const validateResponse = <E>(
154
+ outputAst: AST.AST,
155
+ value: unknown,
156
+ onError: (cause: SchemaMismatch) => E,
157
+ ): Effect.Effect<unknown, E> =>
158
+ Effect.withFiber((fiber) => {
159
+ const error = checkResponse(fiber.context as Context.Context<any>, outputAst, value);
160
+ return error === undefined ? Effect.succeed(value) : Effect.fail(onError(error));
161
+ });