@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
package/src/pagination.ts CHANGED
@@ -5,6 +5,10 @@
5
5
  * - Page-based: page/per_page with a page number that advances
6
6
  * - Cursor-based: cursor/limit with an opaque next-cursor string
7
7
  * - Token-based (AWS style): NextToken/MaxResults continuation tokens
8
+ * - Relay (GraphQL connections): after/first with a `pageInfo` block whose
9
+ * `hasNextPage` -- not the cursor -- marks the end
10
+ * - Link: the next page's token is a query parameter of the `rel="next"` URL
11
+ * in the `Link` response header (RFC 8288; GitHub, Okta, Sentry)
8
12
  * - Single: one-shot list endpoints that still expose the paginated surface
9
13
  *
10
14
  * Each SDK stores a {@link PaginatedTrait} on its operations (sourced from the
@@ -12,8 +16,11 @@
12
16
  * {@link PaginationStrategy}; these shared utilities handle the streaming.
13
17
  * Ported from the distilled repo's `core/pagination`.
14
18
  */
19
+ import type * as Arr from "effect/Array";
20
+ import * as Context from "effect/Context";
15
21
  import * as Effect from "effect/Effect";
16
22
  import * as Stream from "effect/Stream";
23
+ import { SdkError } from "./sdk-error.ts";
17
24
 
18
25
  /**
19
26
  * Get a value from an object using a dot-separated path (e.g.
@@ -31,6 +38,34 @@ export const getPath = (obj: unknown, path: string): unknown => {
31
38
  return current;
32
39
  };
33
40
 
41
+ /**
42
+ * Collect the items a dot-separated path selects, flattening arrays as it
43
+ * goes. Unlike {@link getPath} (which walks a single value and is used for
44
+ * cursors/tokens), every segment here fans out over whatever the previous one
45
+ * produced, so a path may cross a list:
46
+ *
47
+ * - `"items"` on `{ items: [a, b] }` -> `[a, b]` (the common flat case)
48
+ * - `"edges.node"` on a Relay connection -> every edge's `node`
49
+ *
50
+ * `null`/`undefined` links are dropped rather than propagated, so a partially
51
+ * null page yields the items it does have instead of nothing.
52
+ */
53
+ export const getItems = (obj: unknown, path: string): readonly unknown[] => {
54
+ let current: unknown[] = [obj];
55
+ for (const part of path.split(".")) {
56
+ const next: unknown[] = [];
57
+ for (const value of current) {
58
+ if (value == null || typeof value !== "object") continue;
59
+ const child = (value as Record<string, unknown>)[part];
60
+ if (Array.isArray(child)) {
61
+ for (const item of child) next.push(item);
62
+ } else if (child != null) next.push(child);
63
+ }
64
+ current = next;
65
+ }
66
+ return current;
67
+ };
68
+
34
69
  // ============================================================================
35
70
  // Pagination Trait
36
71
  // ============================================================================
@@ -38,36 +73,56 @@ export const getPath = (obj: unknown, path: string): unknown => {
38
73
  /** Pagination trait describing how to navigate between pages. */
39
74
  export interface PaginatedTrait {
40
75
  /** Pagination strategy */
41
- readonly mode?: "token" | "page" | "cursor" | "single";
42
- /** The name of the input member containing the page/cursor token */
76
+ readonly mode?: "token" | "page" | "cursor" | "relay" | "link" | "keyset" | "single";
77
+ /**
78
+ * The name of the input member containing the page/cursor token. In link
79
+ * mode it is also the query parameter read from the `rel="next"` URL.
80
+ */
43
81
  readonly inputToken?: string;
44
- /** The path to the output member containing the next page/cursor token */
82
+ /**
83
+ * The path to the output member containing the next page/cursor token. In
84
+ * keyset mode it is a path within one item: the key the next page starts
85
+ * after.
86
+ */
45
87
  readonly outputToken?: string;
46
- /** The path to the output member containing the paginated items */
88
+ /**
89
+ * The path to the output member containing the paginated items. Segments
90
+ * may cross arrays -- `"edges.node"` walks every edge and collects its
91
+ * `node` (see {@link getItems}).
92
+ */
47
93
  readonly items?: string;
48
94
  /** The name of the input member that limits page size */
49
95
  readonly pageSize?: string;
96
+ /**
97
+ * Relay extension: the path to the boolean that says whether another page
98
+ * exists (`"pageInfo.hasNextPage"`). Relay connections keep returning the
99
+ * last page's `endCursor` after the end, so the cursor alone can't
100
+ * terminate traversal -- see {@link paginateRelay}.
101
+ */
102
+ readonly hasNextPage?: string;
50
103
  }
51
104
 
52
- export type PaginationStrategy = <
53
- Input extends Record<string, unknown>,
54
- Output,
55
- E,
56
- R,
57
- >(
105
+ export type PaginationStrategy = <Input extends Record<string, unknown>, Output, E, R>(
58
106
  operation: (input: Input) => Effect.Effect<Output, E, R>,
59
107
  input: Input,
60
108
  pagination: PaginatedTrait,
61
109
  ) => Stream.Stream<Output, E, R>;
62
110
 
63
- const missingPaginationConfig = (kind: string) => Stream.die(new Error(kind));
111
+ /**
112
+ * The stream of a paginated operation whose trait lacks a field its
113
+ * strategy reads: it fails with {@link SdkError} (part of every
114
+ * operation's error channel, so the strategy's `E` is cast to hold it).
115
+ * The generator refuses such traits.
116
+ */
117
+ export const missingPaginationConfig = (message: string): Stream.Stream<never> =>
118
+ Stream.fail(new SdkError({ message })) as Stream.Stream<never>;
64
119
 
65
120
  /**
66
121
  * Whether a continuation token/cursor returned by a paginated operation
67
122
  * means "no more pages".
68
123
  *
69
124
  * APIs mark the terminal page by omitting the output token, returning it
70
- * as `null`, or — for several services (e.g. SSM, CloudWatch Logs) — as an
125
+ * as `null`, or -- for several services (e.g. SSM, CloudWatch Logs) -- as an
71
126
  * empty string. Treating `""` as a live token re-requests the first page
72
127
  * forever (or fails with a ValidationException). Object tokens (e.g.
73
128
  * DynamoDB's `LastEvaluatedKey`) are always truthy and unaffected.
@@ -77,12 +132,11 @@ export const isTerminalToken = (token: unknown): boolean =>
77
132
 
78
133
  /**
79
134
  * Stream for single-shot list endpoints that still expose the paginated
80
- * surface — emits exactly one page.
135
+ * surface -- emits exactly one page.
81
136
  */
82
137
  export const paginateSingle: PaginationStrategy = (operation, input) =>
83
- Stream.make(input).pipe(
84
- Stream.mapEffect((requestPayload) => operation(requestPayload)),
85
- );
138
+ // `Stream.fromEffect` keeps `mapEffect`'s concurrency machinery out of bundles.
139
+ Stream.fromEffect(Effect.suspend(() => operation(input)));
86
140
 
87
141
  // ============================================================================
88
142
  // Page-based Pagination
@@ -93,12 +147,7 @@ export const paginateSingle: PaginationStrategy = (operation, input) =>
93
147
  * `outputToken` when it advances; otherwise the page number is incremented,
94
148
  * terminating when a page comes back with no items (or no token).
95
149
  */
96
- export const paginatePageNumber = <
97
- Input extends Record<string, unknown>,
98
- Output,
99
- E,
100
- R,
101
- >(
150
+ export const paginatePageNumber = <Input extends Record<string, unknown>, Output, E, R>(
102
151
  operation: (input: Input) => Effect.Effect<Output, E, R>,
103
152
  input: Input,
104
153
  pagination: PaginatedTrait,
@@ -106,13 +155,10 @@ export const paginatePageNumber = <
106
155
  const inputToken = pagination.inputToken;
107
156
  const outputToken = pagination.outputToken;
108
157
  if (!inputToken || !outputToken) {
109
- return missingPaginationConfig(
110
- "Page-number pagination requires inputToken and outputToken",
111
- );
158
+ return missingPaginationConfig("Page-number pagination requires inputToken and outputToken");
112
159
  }
113
160
  type State = { page: number; done: boolean };
114
- const startPage =
115
- typeof input[inputToken] === "number" ? (input[inputToken] as number) : 1;
161
+ const startPage = typeof input[inputToken] === "number" ? (input[inputToken] as number) : 1;
116
162
 
117
163
  return Stream.unfold({ page: startPage, done: false } as State, (state) =>
118
164
  Effect.gen(function* () {
@@ -121,30 +167,24 @@ export const paginatePageNumber = <
121
167
  const requestPayload = { ...input, [inputToken]: state.page } as Input;
122
168
  const response = yield* operation(requestPayload);
123
169
 
124
- const nextPage = getPath(response, outputToken) as
125
- | number
126
- | null
127
- | undefined;
170
+ const nextPage = getPath(response, outputToken) as number | null | undefined;
128
171
 
129
172
  // Some APIs report the CURRENT page at `outputToken` rather than the
130
173
  // next one (e.g. Cloudflare's `result_info.page`). Taking that value as
131
174
  // the next page re-requests the same page forever. Only accept an
132
175
  // *advancing* page number; otherwise advance by one and terminate when
133
- // a page comes back with no items (or the token is absent).
176
+ // a page comes back with no items (or the token is absent). A `null`
177
+ // items member (e.g. `result: null`) is an empty page, as in `getItems`.
134
178
  const items = pagination.items
135
- ? (getPath(response, pagination.items) as
136
- | readonly unknown[]
137
- | undefined)
179
+ ? (getPath(response, pagination.items) as readonly unknown[] | null | undefined)
138
180
  : undefined;
139
181
 
140
182
  const nextState: State = {
141
- page:
142
- typeof nextPage === "number" && nextPage > state.page
143
- ? nextPage
144
- : state.page + 1,
183
+ page: typeof nextPage === "number" && nextPage > state.page ? nextPage : state.page + 1,
145
184
  done:
146
185
  nextPage === null ||
147
186
  nextPage === undefined ||
187
+ items === null ||
148
188
  (items !== undefined && items.length === 0),
149
189
  };
150
190
 
@@ -158,15 +198,11 @@ export const paginatePageNumber = <
158
198
  // ============================================================================
159
199
 
160
200
  /**
161
- * Stream of pages using cursor-based pagination — follow `outputToken`
162
- * cursors until one comes back absent.
201
+ * Stream of pages using cursor-based pagination -- follow `outputToken`
202
+ * cursors until one comes back absent or repeats a previously requested cursor.
203
+ * Empty pages still advance when they return a new cursor.
163
204
  */
164
- export const paginateCursor = <
165
- Input extends Record<string, unknown>,
166
- Output,
167
- E,
168
- R,
169
- >(
205
+ export const paginateCursor = <Input extends Record<string, unknown>, Output, E, R>(
170
206
  operation: (input: Input) => Effect.Effect<Output, E, R>,
171
207
  input: Input,
172
208
  pagination: PaginatedTrait,
@@ -174,15 +210,186 @@ export const paginateCursor = <
174
210
  const inputToken = pagination.inputToken;
175
211
  const outputToken = pagination.outputToken;
176
212
  if (!inputToken || !outputToken) {
177
- return missingPaginationConfig(
178
- "Cursor pagination requires inputToken and outputToken",
213
+ return missingPaginationConfig("Cursor pagination requires inputToken and outputToken");
214
+ }
215
+ type State = { cursor: string | undefined; done: boolean };
216
+ const startCursor =
217
+ typeof input[inputToken] === "string" ? (input[inputToken] as string) : undefined;
218
+
219
+ return Stream.suspend(() => {
220
+ // Cursor history belongs to this traversal, not to the reusable stream.
221
+ const requestedCursors = new Set<string>();
222
+ return Stream.unfold({ cursor: startCursor, done: false } as State, (state) =>
223
+ Effect.gen(function* () {
224
+ if (state.done) return undefined;
225
+ if (state.cursor !== undefined) requestedCursors.add(state.cursor);
226
+
227
+ const requestPayload = {
228
+ ...input,
229
+ ...(state.cursor ? { [inputToken]: state.cursor } : {}),
230
+ } as Input;
231
+
232
+ const response = yield* operation(requestPayload);
233
+
234
+ const nextCursor = getPath(response, outputToken) as string | null | undefined;
235
+
236
+ const nextState: State = {
237
+ cursor: nextCursor ?? undefined,
238
+ done:
239
+ isTerminalToken(nextCursor) || (nextCursor != null && requestedCursors.has(nextCursor)),
240
+ };
241
+
242
+ return [response, nextState] as const;
243
+ }),
179
244
  );
245
+ });
246
+ };
247
+
248
+ // ============================================================================
249
+ // Token-based Pagination (AWS style)
250
+ // ============================================================================
251
+
252
+ /**
253
+ * Stream of pages using token-based pagination -- pass `outputToken` back as
254
+ * `inputToken` until it comes back absent or repeats a token already sent.
255
+ * Some APIs never omit the token: CloudWatch Logs `GetLogEvents` marks the end
256
+ * of a stream by echoing the `nextToken` it was sent. Empty pages still
257
+ * advance when they return a new token.
258
+ */
259
+ export const paginateToken = <Input extends Record<string, unknown>, Output, E, R>(
260
+ operation: (input: Input) => Effect.Effect<Output, E, R>,
261
+ input: Input,
262
+ pagination: PaginatedTrait,
263
+ ): Stream.Stream<Output, E, R> => {
264
+ const inputToken = pagination.inputToken;
265
+ const outputToken = pagination.outputToken;
266
+ if (!inputToken || !outputToken) {
267
+ return missingPaginationConfig("Token pagination requires inputToken and outputToken");
180
268
  }
269
+ type State = { token: unknown; done: boolean };
270
+ const startToken = input[inputToken];
271
+
272
+ return Stream.suspend(() => {
273
+ // Token history belongs to this traversal, not to the reusable stream.
274
+ // Only string tokens are tracked; object tokens (DynamoDB keys) are not.
275
+ const requestedTokens = new Set<string>();
276
+ return Stream.unfold({ token: startToken, done: false } as State, (state) =>
277
+ Effect.gen(function* () {
278
+ if (state.done) return undefined;
279
+ if (typeof state.token === "string") requestedTokens.add(state.token);
280
+
281
+ const requestPayload =
282
+ state.token !== undefined ? ({ ...input, [inputToken]: state.token } as Input) : input;
283
+
284
+ const response = yield* operation(requestPayload);
285
+
286
+ const nextToken = getPath(response, outputToken);
287
+
288
+ const nextState: State = {
289
+ token: nextToken,
290
+ done:
291
+ isTerminalToken(nextToken) ||
292
+ (typeof nextToken === "string" && requestedTokens.has(nextToken)),
293
+ };
294
+
295
+ return [response, nextState] as const;
296
+ }),
297
+ );
298
+ });
299
+ };
300
+
301
+ // ============================================================================
302
+ // Keyset Pagination
303
+ // ============================================================================
304
+
305
+ /** `input` with the value at the dot-separated `path` replaced (copying each level). */
306
+ const setPath = (input: Record<string, unknown>, path: string, value: unknown): any => {
307
+ const [head, ...rest] = path.split(".");
308
+ const key = head!;
309
+ if (rest.length === 0) return { ...input, [key]: value };
310
+ const child = input[key];
311
+ return {
312
+ ...input,
313
+ [key]: setPath(
314
+ child !== null && typeof child === "object" ? (child as Record<string, unknown>) : {},
315
+ rest.join("."),
316
+ value,
317
+ ),
318
+ };
319
+ };
320
+
321
+ /**
322
+ * Stream of pages using keyset pagination: the next request starts after
323
+ * the key of the page's last item. `inputToken` is the input member the key
324
+ * goes to and `outputToken` the key's path within an item (both may be
325
+ * dot-separated: Modal's `List*` calls take `pagination.createdBefore` and
326
+ * key on each item's `createdAt`). Traversal ends on an empty page, a page
327
+ * smaller than the requested `pageSize`, or a key that doesn't advance.
328
+ */
329
+ export const paginateKeyset = <Input extends Record<string, unknown>, Output, E, R>(
330
+ operation: (input: Input) => Effect.Effect<Output, E, R>,
331
+ input: Input,
332
+ pagination: PaginatedTrait,
333
+ ): Stream.Stream<Output, E, R> => {
334
+ const { inputToken, outputToken, items } = pagination;
335
+ if (!inputToken || !outputToken || !items) {
336
+ return missingPaginationConfig("Keyset pagination requires inputToken, outputToken and items");
337
+ }
338
+ const limit = pagination.pageSize ? getPath(input, pagination.pageSize) : undefined;
339
+ type State = { request: Input; key: unknown } | undefined;
340
+ return Stream.unfold({ request: input, key: getPath(input, inputToken) } as State, (state) =>
341
+ state === undefined
342
+ ? Effect.succeed(undefined)
343
+ : Effect.map(operation(state.request), (response) => {
344
+ const page = getItems(response, items);
345
+ const key = page.length > 0 ? getPath(page[page.length - 1], outputToken) : undefined;
346
+ const done =
347
+ page.length === 0 ||
348
+ isTerminalToken(key) ||
349
+ key === state.key ||
350
+ (typeof limit === "number" && page.length < limit);
351
+ return [
352
+ response,
353
+ done ? undefined : { request: setPath(state.request, inputToken, key), key },
354
+ ] as const;
355
+ }),
356
+ );
357
+ };
358
+
359
+ // ============================================================================
360
+ // Relay Pagination (GraphQL connections)
361
+ // ============================================================================
362
+
363
+ /**
364
+ * Stream of pages over a Relay connection -- pass `pageInfo.endCursor` back as
365
+ * `after` for as long as `pageInfo.hasNextPage` is true.
366
+ *
367
+ * Relay is cursor pagination with one twist that breaks
368
+ * {@link paginateCursor}: the terminal page still carries an `endCursor` (it
369
+ * points at the last edge, not at "nothing left"). Only `hasNextPage`
370
+ * distinguishes "more to fetch" from "that was everything", so this strategy
371
+ * reads the boolean and treats the cursor as a pure position marker. A
372
+ * connection that omits `pageInfo` entirely (or returns an empty page) also
373
+ * terminates, so a malformed response can't spin forever.
374
+ */
375
+ export const paginateRelay = <Input extends Record<string, unknown>, Output, E, R>(
376
+ operation: (input: Input) => Effect.Effect<Output, E, R>,
377
+ input: Input,
378
+ pagination: PaginatedTrait,
379
+ ): Stream.Stream<Output, E, R> => {
380
+ const inputToken = pagination.inputToken;
381
+ const outputToken = pagination.outputToken;
382
+ if (!inputToken || !outputToken) {
383
+ return missingPaginationConfig("Relay pagination requires inputToken and outputToken");
384
+ }
385
+ // `pageInfo.endCursor` -> `pageInfo.hasNextPage` when the trait doesn't say.
386
+ const hasNextPath =
387
+ pagination.hasNextPage ??
388
+ `${outputToken.split(".").slice(0, -1).concat("hasNextPage").join(".")}`;
389
+
181
390
  type State = { cursor: string | undefined; done: boolean };
182
391
  const startCursor =
183
- typeof input[inputToken] === "string"
184
- ? (input[inputToken] as string)
185
- : undefined;
392
+ typeof input[inputToken] === "string" ? (input[inputToken] as string) : undefined;
186
393
 
187
394
  return Stream.unfold({ cursor: startCursor, done: false } as State, (state) =>
188
395
  Effect.gen(function* () {
@@ -195,14 +402,24 @@ export const paginateCursor = <
195
402
 
196
403
  const response = yield* operation(requestPayload);
197
404
 
198
- const nextCursor = getPath(response, outputToken) as
199
- | string
200
- | null
201
- | undefined;
405
+ const nextCursor = getPath(response, outputToken) as string | null | undefined;
406
+ const hasNext = getPath(response, hasNextPath) === true;
407
+ // An empty page means the connection is exhausted regardless of what
408
+ // `hasNextPage` claims -- re-requesting the same cursor would loop.
409
+ const emptyPage =
410
+ pagination.items !== undefined && getItems(response, pagination.items).length === 0;
411
+ // A connection that keeps returning the same `endCursor` with
412
+ // `hasNextPage: true` (Railway `projects` has done this) would
413
+ // otherwise paginate forever.
414
+ const stuckCursor =
415
+ state.cursor !== undefined &&
416
+ nextCursor !== undefined &&
417
+ nextCursor !== null &&
418
+ nextCursor === state.cursor;
202
419
 
203
420
  const nextState: State = {
204
421
  cursor: nextCursor ?? undefined,
205
- done: isTerminalToken(nextCursor),
422
+ done: !hasNext || isTerminalToken(nextCursor) || emptyPage || stuckCursor,
206
423
  };
207
424
 
208
425
  return [response, nextState] as const;
@@ -211,49 +428,89 @@ export const paginateCursor = <
211
428
  };
212
429
 
213
430
  // ============================================================================
214
- // Token-based Pagination (AWS style)
431
+ // Link-header Pagination (RFC 8288)
215
432
  // ============================================================================
216
433
 
434
+ /** Where the protocol puts a call's response headers during a link traversal. */
435
+ interface PageHeadersSlot {
436
+ headers: Readonly<Record<string, string | undefined>> | undefined;
437
+ }
438
+
439
+ const PageHeaders = /*@__PURE__*/ Context.Reference<PageHeadersSlot | undefined>(
440
+ "@distilled.cloud/core/Pagination/PageHeaders",
441
+ { defaultValue: () => undefined },
442
+ );
443
+
217
444
  /**
218
- * Stream of pages using token-based pagination — pass `outputToken` back as
219
- * `inputToken` until it comes back absent.
445
+ * Hand a response's headers to the link traversal running on this fiber, if
446
+ * any. Protocols call it for every response they decode; outside
447
+ * {@link paginateLink} it does nothing.
220
448
  */
221
- export const paginateToken = <
222
- Input extends Record<string, unknown>,
223
- Output,
224
- E,
225
- R,
226
- >(
449
+ export const recordPageHeaders = (
450
+ context: Context.Context<never>,
451
+ headers: Readonly<Record<string, string | undefined>>,
452
+ ): void => {
453
+ const slot = Context.get(context, PageHeaders);
454
+ if (slot !== undefined) slot.headers = headers;
455
+ };
456
+
457
+ /**
458
+ * The URL of the `rel="next"` link in a `Link` header value, e.g.
459
+ * `<https://api.github.com/repositories/1/issues?page=2>; rel="next", <...>; rel="last"`.
460
+ */
461
+ export const nextLink = (header: string | undefined): string | undefined => {
462
+ if (header === undefined) return undefined;
463
+ for (const link of header.split(/,\s*(?=<)/)) {
464
+ const match = /^\s*<([^>]*)>(.*)$/.exec(link);
465
+ const rel = match && /;\s*rel\s*=\s*"?([^";]*)"?/i.exec(match[2]!);
466
+ if (rel && rel[1]!.toLowerCase().split(/\s+/).includes("next")) return match![1];
467
+ }
468
+ return undefined;
469
+ };
470
+
471
+ /**
472
+ * Stream of pages that follows the `Link` response header: each request
473
+ * takes `inputToken` from the query of the previous response's `rel="next"`
474
+ * URL, and traversal ends when a response has no next link (or its token
475
+ * repeats the current one). The response body carries no token, so this
476
+ * works for APIs whose list responses are bare arrays.
477
+ *
478
+ * The protocol must report response headers through
479
+ * {@link recordPageHeaders} (the REST protocol does); otherwise traversal
480
+ * stops after the first page.
481
+ */
482
+ export const paginateLink = <Input extends Record<string, unknown>, Output, E, R>(
227
483
  operation: (input: Input) => Effect.Effect<Output, E, R>,
228
484
  input: Input,
229
485
  pagination: PaginatedTrait,
230
486
  ): Stream.Stream<Output, E, R> => {
231
487
  const inputToken = pagination.inputToken;
232
- const outputToken = pagination.outputToken;
233
- if (!inputToken || !outputToken) {
234
- return missingPaginationConfig(
235
- "Token pagination requires inputToken and outputToken",
236
- );
488
+ if (!inputToken) {
489
+ return missingPaginationConfig("Link pagination requires inputToken");
237
490
  }
238
491
  type State = { token: unknown; done: boolean };
239
- const startToken = input[inputToken];
240
492
 
241
- return Stream.unfold({ token: startToken, done: false } as State, (state) =>
493
+ return Stream.unfold({ token: input[inputToken], done: false } as State, (state) =>
242
494
  Effect.gen(function* () {
243
495
  if (state.done) return undefined;
244
496
 
245
497
  const requestPayload =
246
- state.token !== undefined
247
- ? ({ ...input, [inputToken]: state.token } as Input)
248
- : input;
249
-
250
- const response = yield* operation(requestPayload);
251
-
252
- const nextToken = getPath(response, outputToken);
498
+ state.token !== undefined ? ({ ...input, [inputToken]: state.token } as Input) : input;
499
+ const slot: PageHeadersSlot = { headers: undefined };
500
+ const response = yield* Effect.provideService(operation(requestPayload), PageHeaders, slot);
501
+
502
+ const next = nextLink(slot.headers?.["link"]);
503
+ // The token goes back as the query text it came as (`page=2` -> "2");
504
+ // query members are sent as text either way.
505
+ const token =
506
+ next === undefined
507
+ ? undefined
508
+ : (new URL(next, "http://_").searchParams.get(inputToken) ?? undefined);
253
509
 
254
510
  const nextState: State = {
255
- token: nextToken,
256
- done: isTerminalToken(nextToken),
511
+ token,
512
+ done:
513
+ isTerminalToken(token) || (state.token !== undefined && token === String(state.token)),
257
514
  };
258
515
 
259
516
  return [response, nextState] as const;
@@ -265,11 +522,7 @@ export const paginateToken = <
265
522
  * Shared default pagination dispatcher for SDKs that use generic
266
523
  * token/cursor/page traversal.
267
524
  */
268
- export const paginateWithDefaults: PaginationStrategy = (
269
- operation,
270
- input,
271
- pagination,
272
- ) => {
525
+ export const paginateWithDefaults: PaginationStrategy = (operation, input, pagination) => {
273
526
  const mode = pagination.mode ?? "token";
274
527
 
275
528
  switch (mode) {
@@ -277,6 +530,12 @@ export const paginateWithDefaults: PaginationStrategy = (
277
530
  return paginatePageNumber(operation, input, pagination);
278
531
  case "cursor":
279
532
  return paginateCursor(operation, input, pagination);
533
+ case "relay":
534
+ return paginateRelay(operation, input, pagination);
535
+ case "link":
536
+ return paginateLink(operation, input, pagination);
537
+ case "keyset":
538
+ return paginateKeyset(operation, input, pagination);
280
539
  case "single":
281
540
  return paginateSingle(operation, input, pagination);
282
541
  case "token":
@@ -293,16 +552,42 @@ export const paginateWithDefaults: PaginationStrategy = (
293
552
  * Extracts individual items from a page stream.
294
553
  *
295
554
  * @param pages - A stream of page responses
296
- * @param itemsPath - Dot-separated path to the items array in the page
555
+ * @param itemsPath - Dot-separated path to the items in the page; segments may
556
+ * cross arrays (see {@link getItems})
297
557
  * @returns A Stream of individual items
298
558
  */
299
559
  export const extractItems = <Output, Item, E, R>(
300
560
  pages: Stream.Stream<Output, E, R>,
301
561
  itemsPath: string,
562
+ ): Stream.Stream<Item, E, R> => flattenPages(pages, (page) => getItems(page, itemsPath));
563
+
564
+ /**
565
+ * The items of a stream of pages that are themselves the lists (bare-array
566
+ * responses).
567
+ */
568
+ export const extractArrayItems = <Output, Item, E, R>(
569
+ pages: Stream.Stream<Output, E, R>,
570
+ ): Stream.Stream<Item, E, R> => flattenPages(pages, (page) => (Array.isArray(page) ? page : []));
571
+
572
+ const flattenPages = <Output, Item, E, R>(
573
+ pages: Stream.Stream<Output, E, R>,
574
+ itemsOf: (page: Output) => readonly unknown[],
302
575
  ): Stream.Stream<Item, E, R> =>
303
- pages.pipe(
304
- Stream.flatMap((page) => {
305
- const items = getPath(page, itemsPath) as readonly Item[] | undefined;
306
- return Stream.fromIterable(items ?? []);
307
- }),
308
- );
576
+ // Flattens each pulled chunk of pages directly, skipping pages with no
577
+ // items. `Stream.flatMap` / `flattenIterable` would do the same but pull in
578
+ // Effect's concurrent-merge machinery (Queue, Semaphore, ...): about 5 KB
579
+ // gzip in every bundle that uses a paginated operation.
580
+ Stream.transformPull(pages, (pull) => {
581
+ // Same error channel as `pull` (its `Done` included), so the stream ends where the pages end.
582
+ const next: Effect.Effect<Arr.NonEmptyReadonlyArray<Item>, unknown> = Effect.flatMap(
583
+ pull,
584
+ (chunk) => {
585
+ const items: Item[] = [];
586
+ for (const page of chunk) for (const item of itemsOf(page)) items.push(item as Item);
587
+ return items.length > 0
588
+ ? Effect.succeed(items as unknown as Arr.NonEmptyReadonlyArray<Item>)
589
+ : next;
590
+ },
591
+ );
592
+ return Effect.succeed(next);
593
+ }) as unknown as Stream.Stream<Item, E, R>;