@distilled.cloud/core 1.0.0-rc.15 → 1.0.0-rc.16

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 (312) hide show
  1. package/lib/api.d.ts +118 -13
  2. package/lib/api.d.ts.map +1 -1
  3. package/lib/api.js +755 -147
  4. package/lib/api.js.map +1 -1
  5. package/lib/category.d.ts.map +1 -1
  6. package/lib/category.js +146 -146
  7. package/lib/category.js.map +1 -1
  8. package/lib/chunks.d.ts +3 -0
  9. package/lib/chunks.d.ts.map +1 -0
  10. package/lib/chunks.js +11 -0
  11. package/lib/chunks.js.map +1 -0
  12. package/lib/codegen/boolean-string-enums.js +36 -36
  13. package/lib/codegen/chunk.d.ts +7 -0
  14. package/lib/codegen/chunk.d.ts.map +1 -0
  15. package/lib/codegen/chunk.js +139 -0
  16. package/lib/codegen/chunk.js.map +1 -0
  17. package/lib/codegen/cli.d.ts.map +1 -1
  18. package/lib/codegen/cli.js +28 -14
  19. package/lib/codegen/cli.js.map +1 -1
  20. package/lib/codegen/datafy.d.ts +14 -0
  21. package/lib/codegen/datafy.d.ts.map +1 -0
  22. package/lib/codegen/datafy.js +853 -0
  23. package/lib/codegen/datafy.js.map +1 -0
  24. package/lib/codegen/dedupe.d.ts +5 -0
  25. package/lib/codegen/dedupe.d.ts.map +1 -0
  26. package/lib/codegen/dedupe.js +153 -0
  27. package/lib/codegen/dedupe.js.map +1 -0
  28. package/lib/codegen/emit.js +56 -56
  29. package/lib/codegen/format.js +18 -18
  30. package/lib/codegen/generated-at.js +29 -29
  31. package/lib/codegen/generator.d.ts.map +1 -1
  32. package/lib/codegen/generator.js +92 -84
  33. package/lib/codegen/generator.js.map +1 -1
  34. package/lib/codegen/graph.js +36 -36
  35. package/lib/codegen/graphql-client.d.ts +2 -0
  36. package/lib/codegen/graphql-client.d.ts.map +1 -1
  37. package/lib/codegen/graphql-client.js +55 -26
  38. package/lib/codegen/graphql-client.js.map +1 -1
  39. package/lib/codegen/graphql.js +113 -113
  40. package/lib/codegen/latin1.d.ts +3 -0
  41. package/lib/codegen/latin1.d.ts.map +1 -0
  42. package/lib/codegen/latin1.js +126 -0
  43. package/lib/codegen/latin1.js.map +1 -0
  44. package/lib/codegen/members.d.ts +7 -0
  45. package/lib/codegen/members.d.ts.map +1 -1
  46. package/lib/codegen/members.js +26 -19
  47. package/lib/codegen/members.js.map +1 -1
  48. package/lib/codegen/model-diff.js +6 -6
  49. package/lib/codegen/naming.js +19 -19
  50. package/lib/codegen/openapi-cli.js +15 -15
  51. package/lib/codegen/openapi.d.ts +17 -0
  52. package/lib/codegen/openapi.d.ts.map +1 -1
  53. package/lib/codegen/openapi.js +323 -169
  54. package/lib/codegen/openapi.js.map +1 -1
  55. package/lib/codegen/operations.js +14 -14
  56. package/lib/codegen/pagination.js +11 -11
  57. package/lib/codegen/patch-audit.js +57 -57
  58. package/lib/codegen/patches.js +79 -79
  59. package/lib/codegen/prelude.js +19 -19
  60. package/lib/codegen/privatize.d.ts +21 -0
  61. package/lib/codegen/privatize.d.ts.map +1 -0
  62. package/lib/codegen/privatize.js +176 -0
  63. package/lib/codegen/privatize.js.map +1 -0
  64. package/lib/codegen/proto.js +25 -25
  65. package/lib/codegen/pure.d.ts +6 -0
  66. package/lib/codegen/pure.d.ts.map +1 -0
  67. package/lib/codegen/pure.js +91 -0
  68. package/lib/codegen/pure.js.map +1 -0
  69. package/lib/codegen/rewrite-operation-ids.js +108 -108
  70. package/lib/codegen/spec-path.js +57 -57
  71. package/lib/codegen/table.d.ts +5 -0
  72. package/lib/codegen/table.d.ts.map +1 -0
  73. package/lib/codegen/table.js +249 -0
  74. package/lib/codegen/table.js.map +1 -0
  75. package/lib/config.d.ts +27 -0
  76. package/lib/config.d.ts.map +1 -0
  77. package/lib/config.js +161 -0
  78. package/lib/config.js.map +1 -0
  79. package/lib/crypto.d.ts +76 -0
  80. package/lib/crypto.d.ts.map +1 -0
  81. package/lib/crypto.js +130 -0
  82. package/lib/crypto.js.map +1 -0
  83. package/lib/debug.d.ts +2 -0
  84. package/lib/debug.d.ts.map +1 -0
  85. package/lib/debug.js +8 -0
  86. package/lib/debug.js.map +1 -0
  87. package/lib/error-category.d.ts +1 -1
  88. package/lib/error-category.d.ts.map +1 -1
  89. package/lib/error-category.js +7 -6
  90. package/lib/error-category.js.map +1 -1
  91. package/lib/errors.d.ts +62 -62
  92. package/lib/errors.d.ts.map +1 -1
  93. package/lib/errors.js +117 -114
  94. package/lib/errors.js.map +1 -1
  95. package/lib/graphql.d.ts +31 -20
  96. package/lib/graphql.d.ts.map +1 -1
  97. package/lib/graphql.js +150 -119
  98. package/lib/graphql.js.map +1 -1
  99. package/lib/graphql.types.js +4 -3
  100. package/lib/graphql.types.js.map +1 -1
  101. package/lib/index.d.ts +3 -2
  102. package/lib/index.d.ts.map +1 -1
  103. package/lib/index.js +15 -14
  104. package/lib/index.js.map +1 -1
  105. package/lib/json-patch.d.ts +2 -2
  106. package/lib/json-patch.js +28 -28
  107. package/lib/pagination.d.ts +9 -25
  108. package/lib/pagination.d.ts.map +1 -1
  109. package/lib/pagination.js +95 -90
  110. package/lib/pagination.js.map +1 -1
  111. package/lib/plain-values.d.ts +10 -0
  112. package/lib/plain-values.d.ts.map +1 -0
  113. package/lib/plain-values.js +40 -0
  114. package/lib/plain-values.js.map +1 -0
  115. package/lib/protocol-http.d.ts +50 -14
  116. package/lib/protocol-http.d.ts.map +1 -1
  117. package/lib/protocol-http.js +351 -178
  118. package/lib/protocol-http.js.map +1 -1
  119. package/lib/protocol-rest.d.ts +38 -25
  120. package/lib/protocol-rest.d.ts.map +1 -1
  121. package/lib/protocol-rest.js +238 -130
  122. package/lib/protocol-rest.js.map +1 -1
  123. package/lib/query.js +16 -16
  124. package/lib/response-validation-strict.d.ts +48 -0
  125. package/lib/response-validation-strict.d.ts.map +1 -0
  126. package/lib/response-validation-strict.js +284 -0
  127. package/lib/response-validation-strict.js.map +1 -0
  128. package/lib/response-validation.d.ts +43 -25
  129. package/lib/response-validation.d.ts.map +1 -1
  130. package/lib/response-validation.js +112 -70
  131. package/lib/response-validation.js.map +1 -1
  132. package/lib/retry-after.d.ts +3 -3
  133. package/lib/retry-after.js +49 -49
  134. package/lib/retry.d.ts +48 -29
  135. package/lib/retry.d.ts.map +1 -1
  136. package/lib/retry.js +142 -154
  137. package/lib/retry.js.map +1 -1
  138. package/lib/schema-lite-impl.d.ts +158 -0
  139. package/lib/schema-lite-impl.d.ts.map +1 -0
  140. package/lib/schema-lite-impl.js +341 -0
  141. package/lib/schema-lite-impl.js.map +1 -0
  142. package/lib/schema-lite-typed.d.ts +41 -0
  143. package/lib/schema-lite-typed.d.ts.map +1 -0
  144. package/lib/schema-lite-typed.js +27 -0
  145. package/lib/schema-lite-typed.js.map +1 -0
  146. package/lib/schema-lite.d.ts +40 -0
  147. package/lib/schema-lite.d.ts.map +1 -0
  148. package/lib/schema-lite.js +31 -0
  149. package/lib/schema-lite.js.map +1 -0
  150. package/lib/schema.d.ts +20 -6
  151. package/lib/schema.d.ts.map +1 -1
  152. package/lib/schema.js +202 -30
  153. package/lib/schema.js.map +1 -1
  154. package/lib/testing.d.ts +3 -2
  155. package/lib/testing.d.ts.map +1 -1
  156. package/lib/testing.js +22 -21
  157. package/lib/testing.js.map +1 -1
  158. package/lib/trait.d.ts +13 -13
  159. package/lib/trait.d.ts.map +1 -1
  160. package/lib/trait.js +80 -80
  161. package/lib/trait.js.map +1 -1
  162. package/lib/xml.d.ts +1 -1
  163. package/lib/xml.d.ts.map +1 -1
  164. package/lib/xml.js +38 -26
  165. package/lib/xml.js.map +1 -1
  166. package/package.json +9 -7
  167. package/src/api.ts +1079 -180
  168. package/src/category.ts +33 -33
  169. package/src/chunks.ts +30 -0
  170. package/src/codegen/chunk.ts +147 -0
  171. package/src/codegen/cli.ts +27 -1
  172. package/src/codegen/datafy.ts +874 -0
  173. package/src/codegen/dedupe.ts +173 -0
  174. package/src/codegen/generator.ts +10 -3
  175. package/src/codegen/graphql-client.ts +49 -15
  176. package/src/codegen/latin1.ts +131 -0
  177. package/src/codegen/members.ts +8 -0
  178. package/src/codegen/openapi.ts +194 -3
  179. package/src/codegen/privatize.ts +200 -0
  180. package/src/codegen/pure.ts +94 -0
  181. package/src/codegen/table.ts +254 -0
  182. package/src/config.ts +216 -0
  183. package/src/crypto.ts +202 -0
  184. package/src/debug.ts +8 -0
  185. package/src/error-category.ts +2 -1
  186. package/src/errors.ts +65 -56
  187. package/src/graphql.ts +109 -62
  188. package/src/graphql.types.ts +9 -7
  189. package/src/index.ts +3 -2
  190. package/src/json-patch.ts +2 -2
  191. package/src/pagination.ts +37 -18
  192. package/src/plain-values.ts +41 -0
  193. package/src/protocol-http.ts +378 -145
  194. package/src/protocol-rest.ts +337 -169
  195. package/src/response-validation-strict.ts +327 -0
  196. package/src/response-validation.ts +101 -50
  197. package/src/retry-after.ts +3 -3
  198. package/src/retry.ts +94 -93
  199. package/src/schema-lite-impl.ts +550 -0
  200. package/src/schema-lite-typed.ts +44 -0
  201. package/src/schema-lite.ts +44 -0
  202. package/src/schema.ts +258 -14
  203. package/src/testing.ts +4 -2
  204. package/src/trait.ts +36 -28
  205. package/src/xml.ts +31 -17
  206. package/lib/codegen/boolean-string-enums.test.d.ts +0 -2
  207. package/lib/codegen/boolean-string-enums.test.d.ts.map +0 -1
  208. package/lib/codegen/boolean-string-enums.test.js +0 -275
  209. package/lib/codegen/boolean-string-enums.test.js.map +0 -1
  210. package/lib/codegen/defer-naming.test.d.ts +0 -2
  211. package/lib/codegen/defer-naming.test.d.ts.map +0 -1
  212. package/lib/codegen/defer-naming.test.js +0 -105
  213. package/lib/codegen/defer-naming.test.js.map +0 -1
  214. package/lib/codegen/generated-at.test.d.ts +0 -2
  215. package/lib/codegen/generated-at.test.d.ts.map +0 -1
  216. package/lib/codegen/generated-at.test.js +0 -81
  217. package/lib/codegen/generated-at.test.js.map +0 -1
  218. package/lib/codegen/generator.test.d.ts +0 -2
  219. package/lib/codegen/generator.test.d.ts.map +0 -1
  220. package/lib/codegen/generator.test.js +0 -121
  221. package/lib/codegen/generator.test.js.map +0 -1
  222. package/lib/codegen/graphql-client.test.d.ts +0 -2
  223. package/lib/codegen/graphql-client.test.d.ts.map +0 -1
  224. package/lib/codegen/graphql-client.test.js +0 -171
  225. package/lib/codegen/graphql-client.test.js.map +0 -1
  226. package/lib/codegen/openapi-binary.test.d.ts +0 -2
  227. package/lib/codegen/openapi-binary.test.d.ts.map +0 -1
  228. package/lib/codegen/openapi-binary.test.js +0 -67
  229. package/lib/codegen/openapi-binary.test.js.map +0 -1
  230. package/lib/codegen/patch-audit.test.d.ts +0 -2
  231. package/lib/codegen/patch-audit.test.d.ts.map +0 -1
  232. package/lib/codegen/patch-audit.test.js +0 -141
  233. package/lib/codegen/patch-audit.test.js.map +0 -1
  234. package/lib/codegen/patches.test.d.ts +0 -2
  235. package/lib/codegen/patches.test.d.ts.map +0 -1
  236. package/lib/codegen/patches.test.js +0 -155
  237. package/lib/codegen/patches.test.js.map +0 -1
  238. package/lib/codegen/protocol-imports.test.d.ts +0 -2
  239. package/lib/codegen/protocol-imports.test.d.ts.map +0 -1
  240. package/lib/codegen/protocol-imports.test.js +0 -36
  241. package/lib/codegen/protocol-imports.test.js.map +0 -1
  242. package/lib/codegen/rewrite-operation-ids.test.d.ts +0 -2
  243. package/lib/codegen/rewrite-operation-ids.test.d.ts.map +0 -1
  244. package/lib/codegen/rewrite-operation-ids.test.js +0 -451
  245. package/lib/codegen/rewrite-operation-ids.test.js.map +0 -1
  246. package/lib/codegen/untagged-unions.test.d.ts +0 -2
  247. package/lib/codegen/untagged-unions.test.d.ts.map +0 -1
  248. package/lib/codegen/untagged-unions.test.js +0 -80
  249. package/lib/codegen/untagged-unions.test.js.map +0 -1
  250. package/lib/fixtures/xml/upstream-validator.json +0 -397
  251. package/lib/graphql.test.d.ts +0 -2
  252. package/lib/graphql.test.d.ts.map +0 -1
  253. package/lib/graphql.test.js +0 -151
  254. package/lib/graphql.test.js.map +0 -1
  255. package/lib/json-patch.test.d.ts +0 -2
  256. package/lib/json-patch.test.d.ts.map +0 -1
  257. package/lib/json-patch.test.js +0 -65
  258. package/lib/json-patch.test.js.map +0 -1
  259. package/lib/pagination.test.d.ts +0 -2
  260. package/lib/pagination.test.d.ts.map +0 -1
  261. package/lib/pagination.test.js +0 -131
  262. package/lib/pagination.test.js.map +0 -1
  263. package/lib/protocol-http.test.d.ts +0 -2
  264. package/lib/protocol-http.test.d.ts.map +0 -1
  265. package/lib/protocol-http.test.js +0 -228
  266. package/lib/protocol-http.test.js.map +0 -1
  267. package/lib/protocol-rest.test.d.ts +0 -2
  268. package/lib/protocol-rest.test.d.ts.map +0 -1
  269. package/lib/protocol-rest.test.js +0 -498
  270. package/lib/protocol-rest.test.js.map +0 -1
  271. package/lib/response-validation.test.d.ts +0 -2
  272. package/lib/response-validation.test.d.ts.map +0 -1
  273. package/lib/response-validation.test.js +0 -72
  274. package/lib/response-validation.test.js.map +0 -1
  275. package/lib/retry-after.test.d.ts +0 -2
  276. package/lib/retry-after.test.d.ts.map +0 -1
  277. package/lib/retry-after.test.js +0 -204
  278. package/lib/retry-after.test.js.map +0 -1
  279. package/lib/retry.test.d.ts +0 -2
  280. package/lib/retry.test.d.ts.map +0 -1
  281. package/lib/retry.test.js +0 -407
  282. package/lib/retry.test.js.map +0 -1
  283. package/lib/sdks.test.d.ts +0 -2
  284. package/lib/sdks.test.d.ts.map +0 -1
  285. package/lib/sdks.test.js +0 -76
  286. package/lib/sdks.test.js.map +0 -1
  287. package/lib/xml.test.d.ts +0 -2
  288. package/lib/xml.test.d.ts.map +0 -1
  289. package/lib/xml.test.js +0 -210
  290. package/lib/xml.test.js.map +0 -1
  291. package/src/codegen/boolean-string-enums.test.ts +0 -299
  292. package/src/codegen/defer-naming.test.ts +0 -113
  293. package/src/codegen/generated-at.test.ts +0 -89
  294. package/src/codegen/generator.test.ts +0 -137
  295. package/src/codegen/graphql-client.test.ts +0 -189
  296. package/src/codegen/openapi-binary.test.ts +0 -91
  297. package/src/codegen/patch-audit.test.ts +0 -160
  298. package/src/codegen/patches.test.ts +0 -188
  299. package/src/codegen/protocol-imports.test.ts +0 -39
  300. package/src/codegen/rewrite-operation-ids.test.ts +0 -472
  301. package/src/codegen/untagged-unions.test.ts +0 -85
  302. package/src/fixtures/xml/upstream-validator.json +0 -397
  303. package/src/graphql.test.ts +0 -198
  304. package/src/json-patch.test.ts +0 -77
  305. package/src/pagination.test.ts +0 -169
  306. package/src/protocol-http.test.ts +0 -276
  307. package/src/protocol-rest.test.ts +0 -703
  308. package/src/response-validation.test.ts +0 -89
  309. package/src/retry-after.test.ts +0 -267
  310. package/src/retry.test.ts +0 -566
  311. package/src/sdks.test.ts +0 -87
  312. package/src/xml.test.ts +0 -251
package/src/api.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import * as Context from "effect/Context";
2
+ import type * as Duration from "effect/Duration";
2
3
  import * as Effect from "effect/Effect";
4
+ import * as Exit from "effect/Exit";
3
5
  import * as HttpClient from "effect/http/HttpClient";
4
6
  import type * as HttpClientError from "effect/http/HttpClientError";
5
7
  import type * as HttpClientRequest from "effect/http/HttpClientRequest";
@@ -13,8 +15,16 @@ import type * as AST from "effect/SchemaAST";
13
15
  import * as Scope from "effect/Scope";
14
16
  import type * as Stream from "effect/Stream";
15
17
  import { SingleShotGen } from "effect/Utils";
18
+ import { isThrottling } from "./category.ts";
16
19
  import * as Pagination from "./pagination.ts";
17
- import { makeDefault, type Policy as RetryPolicy } from "./retry.ts";
20
+ import {
21
+ type Backoff,
22
+ defaultOptions,
23
+ type Options as RetryOptions,
24
+ type Policy as RetryPolicy,
25
+ resolveServerRetryHintCapMs,
26
+ serverHintMillis,
27
+ } from "./retry.ts";
18
28
 
19
29
  //#region Protocol
20
30
 
@@ -51,34 +61,75 @@ export interface ProtocolOperationConfig {
51
61
  *
52
62
  * Swap implementations by providing a different `Layer<Protocol>`.
53
63
  */
54
- export class Protocol extends Context.Service<
55
- Protocol,
56
- {
57
- readonly encode: (args: {
58
- readonly input: unknown;
59
- readonly inputAst: AST.AST;
60
- /** The operation's config (memoized per operation — see {@link ProtocolOperationConfig}). */
61
- readonly config: ProtocolOperationConfig;
62
- }) => Effect.Effect<HttpClientRequest.HttpClientRequest>;
63
- readonly decode: (args: {
64
- readonly response: HttpClientResponse.HttpClientResponse;
65
- readonly outputAst: AST.AST;
64
+ export class Protocol
65
+ extends /*@__PURE__*/ Context.Service<
66
+ Protocol,
67
+ {
68
+ readonly encode: (args: {
69
+ readonly input: unknown;
70
+ readonly inputAst: AST.AST;
71
+ /** The operation's config (memoized per operation -- see {@link ProtocolOperationConfig}). */
72
+ readonly config: ProtocolOperationConfig;
73
+ }) => Effect.Effect<HttpClientRequest.HttpClientRequest>;
74
+ readonly decode: (args: {
75
+ readonly response: HttpClientResponse.HttpClientResponse;
76
+ readonly outputAst: AST.AST;
77
+ /**
78
+ * The operation's declared error classes (from `OperationConfig.errors`).
79
+ * Protocols use these to surface wire failures as the operation's typed
80
+ * errors -- e.g. by consulting matcher metadata stamped on the class.
81
+ */
82
+ readonly errors: ReadonlyArray<ApiErrorClass>;
83
+ /** The operation's config (memoized per operation -- see {@link ProtocolOperationConfig}). */
84
+ readonly config: ProtocolOperationConfig;
85
+ }) => Effect.Effect<unknown>;
66
86
  /**
67
- * The operation's declared error classes (from `OperationConfig.errors`).
68
- * Protocols use these to surface wire failures as the operation's typed
69
- * errors — e.g. by consulting matcher metadata stamped on the class.
87
+ * Optional whole-call implementation. When present, `API.make` runs a
88
+ * call as `call(operation, input)` instead of encode -> HttpClient ->
89
+ * decode, so a protocol can read the context once, build the request
90
+ * synchronously and decode the response without intermediate effects.
91
+ * It must read the `HttpClient` from the calling fiber's context and
92
+ * produce the same request, result and errors as encode/decode.
70
93
  */
71
- readonly errors: ReadonlyArray<ApiErrorClass>;
72
- /** The operation's config (memoized per operation — see {@link ProtocolOperationConfig}). */
73
- readonly config: ProtocolOperationConfig;
74
- }) => Effect.Effect<unknown>;
75
- }
76
- >()("Protocol") {}
94
+ readonly call?: (operation: PreparedOperation, input: unknown) => Effect.Effect<unknown>;
95
+ }
96
+ >()("Protocol") {}
97
+
98
+ /** The service a protocol layer provides. */
99
+ export type ProtocolShape = (typeof Protocol)["Service"];
100
+
101
+ /**
102
+ * One operation as a protocol's {@link Protocol.call} sees it. Built once per
103
+ * operation on its first call; the same object is passed on every call.
104
+ */
105
+ export interface PreparedOperation {
106
+ readonly config: ProtocolOperationConfig;
107
+ readonly inputAst: AST.AST;
108
+ readonly outputAst: AST.AST;
109
+ readonly errors: ReadonlyArray<ApiErrorClass>;
110
+ /** Per-operation slot owned by the operation's protocol (compiled codecs). */
111
+ compiled?: unknown;
112
+ }
77
113
 
78
114
  //#endregion
79
115
 
80
116
  //#region Make
81
117
 
118
+ /**
119
+ * Run `f` on the value of `effect` -- directly when `effect` is already a
120
+ * successful `Exit` (e.g. a `Credentials` service holding
121
+ * `Effect.succeed(config)`), so a resolved value costs no fiber step.
122
+ */
123
+ export const withValue = <A, B>(
124
+ effect: Effect.Effect<A, any, any>,
125
+ f: (a: A) => Effect.Effect<B, any, any>,
126
+ ): Effect.Effect<B, any, any> =>
127
+ Exit.isExit(effect)
128
+ ? Exit.isSuccess(effect)
129
+ ? f(effect.value as A)
130
+ : (effect as unknown as Effect.Effect<never, any>)
131
+ : Effect.flatMap(effect, f);
132
+
82
133
  export type ApiErrorClass = {
83
134
  new (...args: any[]): {
84
135
  readonly _tag: string;
@@ -87,11 +138,11 @@ export type ApiErrorClass = {
87
138
  };
88
139
 
89
140
  /**
90
- * The shape of a generated SDK operation — usable two ways (mirrors the
141
+ * The shape of a generated SDK operation -- usable two ways (mirrors the
91
142
  * distilled repo's OperationMethod):
92
143
  *
93
- * 1. Direct call: `yield* operation(input)` — an Effect with requirements.
94
- * 2. Yield first: `const fn = yield* operation` — captures the current
144
+ * 1. Direct call: `yield* operation(input)` -- an Effect with requirements.
145
+ * 2. Yield first: `const fn = yield* operation` -- captures the current
95
146
  * context and returns a requirement-free call function.
96
147
  *
97
148
  * Generated service files annotate every exported operation with this type
@@ -103,11 +154,22 @@ export type OperationMethod<I, O, E, R> = Effect.Effect<
103
154
  never,
104
155
  R
105
156
  > &
106
- ((input: I) => Effect.Effect<O, E, R>);
157
+ ((input: I) => Effect.Effect<O, E, R>) &
158
+ OperationSchemas<I, O>;
159
+
160
+ /**
161
+ * An operation's request and response schemas, built on first access.
162
+ * Generated modules export operations, errors and types; the schemas
163
+ * themselves are module-private, so this is how to reach them as values.
164
+ */
165
+ export interface OperationSchemas<I, O> {
166
+ readonly input: S.Codec<I, any>;
167
+ readonly output: S.Codec<O, any>;
168
+ }
107
169
 
108
170
  // NOTE: request/response ASTs are handed to the protocol RAW (Suspend nodes
109
171
  // included). Pre-resolving Suspends here would drop annotations that sit on
110
- // intermediate nodes — e.g. a bare-payload response whose payload type is
172
+ // intermediate nodes -- e.g. a bare-payload response whose payload type is
111
173
  // itself a suspended schema carries its EnvelopePayloadRoot marker on the
112
174
  // inner Suspend, and unwrapping it silently degrades decode to the struct
113
175
  // path. The protocol helpers (core/protocol-http getAnn/getProps) descend
@@ -116,19 +178,22 @@ export type OperationMethod<I, O, E, R> = Effect.Effect<
116
178
 
117
179
  /**
118
180
  * Protocol layers are built once per process and shared by every operation
119
- * call (keyed by layer value identity — generated operations all reference the
181
+ * call (keyed by layer value identity -- generated operations all reference the
120
182
  * same module-level layer const). The build runs against a process-lifetime
121
183
  * scope, and concurrent first calls are deduplicated through a private
122
184
  * MemoMap.
123
185
  *
124
186
  * Contract for protocol implementations: the layer build must not capture
125
- * per-call context. Anything call-dependent — credentials, per-request
126
- * options — must be resolved inside `encode`/`decode`, which execute on the
187
+ * per-call context. Anything call-dependent -- credentials, per-request
188
+ * options -- must be resolved inside `encode`/`decode`, which execute on the
127
189
  * calling fiber and therefore see the caller's services on every request.
128
190
  */
129
- const protocolMemoMap = Layer.makeMemoMapUnsafe();
130
- const protocolScope = Scope.makeUnsafe();
131
- const protocolContexts = new WeakMap<Layer.Layer<Protocol, any, any>, Context.Context<Protocol>>();
191
+ const protocolMemoMap = /*@__PURE__*/ Layer.makeMemoMapUnsafe();
192
+ const protocolScope = /*@__PURE__*/ Scope.makeUnsafe();
193
+ const protocolContexts = /*@__PURE__*/ new WeakMap<
194
+ Layer.Layer<Protocol, any, any>,
195
+ Context.Context<Protocol>
196
+ >();
132
197
 
133
198
  const protocolContext = <PE, PR>(
134
199
  layer: Layer.Layer<Protocol, PE, PR>,
@@ -154,7 +219,7 @@ export interface OperationConfig<
154
219
  /**
155
220
  * The protocol layer that knows how to encode/decode this operation's wire
156
221
  * format. Built once per process and shared across all operations that
157
- * reference the same layer value — it must resolve call-dependent services
222
+ * reference the same layer value -- it must resolve call-dependent services
158
223
  * (credentials etc.) inside encode/decode, not at build time.
159
224
  */
160
225
  protocol: Layer.Layer<Protocol, PE, PR>;
@@ -180,31 +245,240 @@ export interface OperationConfig<
180
245
  * Wrap one operation call with the caller-provided retry policy, if the
181
246
  * operation declares a retry tag and the context carries a policy for it.
182
247
  */
248
+ /** Delay before retry `attempt` (0-based) under `b`, in milliseconds. */
249
+ const backoffDelay = (b: Backoff, attempt: number, error: unknown): Effect.Effect<number> => {
250
+ const base = Math.min(b.baseMs * b.factor ** attempt, b.capMs);
251
+ const jitter = () => Math.random() * (b.jitterMs ?? 0);
252
+ if (b.serverHint && (error as { retryAfter?: unknown } | null)?.retryAfter !== undefined) {
253
+ return Effect.map(resolveServerRetryHintCapMs(), (capMs) => {
254
+ const hint = serverHintMillis(error, capMs);
255
+ return (hint ?? base) + jitter();
256
+ });
257
+ }
258
+ const floored =
259
+ b.minThrottleMs !== undefined && base < b.minThrottleMs && isThrottling(error)
260
+ ? b.minThrottleMs
261
+ : base;
262
+ return Effect.succeed(floored + jitter());
263
+ };
264
+
265
+ const NO_BACKOFF: Backoff = { baseMs: 0, factor: 1, capMs: 0 };
266
+
267
+ /**
268
+ * Wrap one operation call with the caller-provided retry policy, if the
269
+ * operation declares a retry tag. The call runs once with no retry
270
+ * machinery; the policy is read only after a failure. Built-in policies are
271
+ * {@link Backoff} data run by a small loop; a caller-supplied `schedule`
272
+ * runs under `Effect.retry`, with the first failure replayed as attempt one
273
+ * so delays and counts match running the whole call under it.
274
+ */
183
275
  const applyRetry = (
184
276
  base: Effect.Effect<any, any, any>,
185
277
  retryKey: Context.Key<any, RetryPolicy> | undefined,
186
278
  ): Effect.Effect<any, any, any> =>
187
279
  retryKey === undefined
188
280
  ? base
189
- : Effect.flatMap(Effect.serviceOption(retryKey), (opt) =>
190
- Effect.gen(function* () {
191
- const lastError = yield* Ref.make<unknown>(undefined);
192
- // No policy in context → makeDefault (transient/throttling/server
193
- // errors, capped exponential backoff + jitter, honors server
194
- // retryAfter hints). Mirrors the distilled client.
195
- const policy = Option.isSome(opt) ? opt.value : makeDefault;
196
- const opts = typeof policy === "function" ? policy(lastError) : policy;
197
- if (!opts.while) return yield* base;
198
- return yield* base.pipe(
199
- Effect.tapError((e) => Ref.set(lastError, e)),
200
- Effect.retry({
201
- while: (e: unknown) => opts.while!(e),
202
- ...(opts.schedule ? { schedule: opts.schedule as any } : {}),
203
- }),
281
+ : Effect.catch(base, (error) =>
282
+ Effect.flatMap(Effect.serviceOption(retryKey), (opt) => {
283
+ if (Option.isNone(opt)) return retryWith(base, defaultOptions, error);
284
+ const policy = opt.value;
285
+ if (typeof policy !== "function") return retryWith(base, policy, error);
286
+ return Effect.flatMap(Ref.make<unknown>(error), (lastError) =>
287
+ retryWith(
288
+ Effect.tapError(base, (e) => Ref.set(lastError, e)),
289
+ policy(lastError),
290
+ error,
291
+ ),
204
292
  );
205
293
  }),
206
294
  );
207
295
 
296
+ const retryWith = (
297
+ base: Effect.Effect<any, any, any>,
298
+ opts: RetryOptions,
299
+ error: unknown,
300
+ ): Effect.Effect<any, any, any> => {
301
+ const keepGoing = opts.while;
302
+ if (!keepGoing || !keepGoing(error)) return Effect.fail(error);
303
+ if (opts.schedule) {
304
+ // Drive the caller's schedule through its own `step`, as Effect.retry
305
+ // does, without importing the Schedule module into every bundle: the
306
+ // first failure is the schedule's first input; a step that fails means
307
+ // the schedule is done.
308
+ const schedule = opts.schedule as unknown as {
309
+ readonly step: Effect.Effect<
310
+ (now: number, input: unknown) => Effect.Effect<readonly [unknown, Duration.Input], unknown>
311
+ >;
312
+ };
313
+ return Effect.flatMap(schedule.step, (next) => {
314
+ const loop = (e: unknown): Effect.Effect<any, any, any> =>
315
+ !keepGoing(e)
316
+ ? Effect.fail(e)
317
+ : Effect.clockWith((clock) =>
318
+ Effect.matchEffect(next(clock.currentTimeMillisUnsafe(), e), {
319
+ onFailure: () => Effect.fail(e),
320
+ onSuccess: ([, delay]) =>
321
+ Effect.flatMap(Effect.sleep(delay), () => Effect.catch(base, loop)),
322
+ }),
323
+ );
324
+ return loop(error);
325
+ });
326
+ }
327
+ const b = opts.backoff ?? NO_BACKOFF;
328
+ const step = (e: unknown, n: number): Effect.Effect<any, any, any> =>
329
+ !keepGoing(e) || (b.maxRetries !== undefined && n >= b.maxRetries)
330
+ ? Effect.fail(e)
331
+ : Effect.flatMap(backoffDelay(b, n, e), (ms) =>
332
+ Effect.flatMap(Effect.sleep(ms), () => Effect.catch(base, (next) => step(next, n + 1))),
333
+ );
334
+ return step(error, 0);
335
+ };
336
+
337
+ /**
338
+ * Per-operation state. Kept to one small object per exported operation:
339
+ * importing a service module creates every operation in it, so anything
340
+ * allocated here is paid hundreds of times per import (EC2 has 807
341
+ * operations) whether or not the operation is ever called.
342
+ */
343
+ interface OperationState {
344
+ readonly configFn: () => OperationConfig<any, any, any, any, any>;
345
+ prepared?: Prepared;
346
+ /** Paginated operations only. */
347
+ readonly strategy?: Pagination.PaginationStrategy;
348
+ }
349
+
350
+ interface Prepared extends PreparedOperation {
351
+ readonly cfg: OperationConfig<any, any, any, any, any>;
352
+ /** The built protocol service, once its layer has been built. */
353
+ service?: ProtocolShape;
354
+ }
355
+
356
+ const stateKey = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/api/OperationState");
357
+
358
+ // Lazily resolve the operation config + schema ASTs on first call, not at
359
+ // module-load time. Generated SDKs wrap each request/response schema in
360
+ // `Schema.suspend(() => ...)`; forcing them here (rather than when the
361
+ // `export const` is evaluated) keeps importing a service module cheap and
362
+ // only pays the schema-construction cost for operations that are actually
363
+ // called. Memoized so subsequent calls are free.
364
+ const prepare = (state: OperationState): Prepared => {
365
+ if (state.prepared) return state.prepared;
366
+ const cfg = state.configFn();
367
+ return (state.prepared = {
368
+ cfg,
369
+ config: cfg,
370
+ inputAst: cfg.input!.ast,
371
+ outputAst: cfg.output!.ast,
372
+ errors: cfg.errors ?? [],
373
+ compiled: undefined,
374
+ service: undefined,
375
+ });
376
+ };
377
+
378
+ const stateOf = (op: unknown): OperationState => (op as Record<symbol, OperationState>)[stateKey]!;
379
+
380
+ const defineState = (op: unknown, state: OperationState): OperationState => {
381
+ Object.defineProperty(op, stateKey, { value: state });
382
+ return state;
383
+ };
384
+
385
+ const runWith = (
386
+ p: Prepared,
387
+ protocol: ProtocolShape,
388
+ input: unknown,
389
+ ): Effect.Effect<any, any, any> => {
390
+ if (protocol.call !== undefined) return protocol.call(p, input);
391
+ const { cfg, inputAst, outputAst, errors } = p;
392
+ return Effect.flatMap(HttpClient.HttpClient, (client) =>
393
+ Effect.flatMap(protocol.encode({ input, inputAst, config: cfg }), (request) =>
394
+ Effect.flatMap(client.execute(request), (response) =>
395
+ protocol.decode({ response, outputAst, errors, config: cfg }),
396
+ ),
397
+ ),
398
+ );
399
+ };
400
+
401
+ const callOperation = (state: OperationState, input: unknown): Effect.Effect<any, any, any> => {
402
+ // Warm path: the operation is prepared and its protocol built, so the call
403
+ // is whatever the protocol returns, with no wrapper effects around it.
404
+ const p = state.prepared;
405
+ if (p?.service !== undefined) return applyRetry(runWith(p, p.service, input), p.cfg.retry);
406
+ return Effect.suspend(() => {
407
+ const prepared = prepare(state);
408
+ const call = Effect.flatMap(protocolContext(prepared.cfg.protocol), (protocolCtx) => {
409
+ const service = (prepared.service = Context.get(protocolCtx, Protocol));
410
+ return runWith(prepared, service, input);
411
+ });
412
+ return applyRetry(call, prepared.cfg.retry);
413
+ });
414
+ };
415
+
416
+ /**
417
+ * `const fn = yield* operation`: a requirement-free call function over the
418
+ * current context. The captured context is a FALLBACK, not a snapshot:
419
+ * entries present on the calling fiber at call time win, so per-call
420
+ * overrides -- e.g. providing `Endpoint` with a discovered data-plane address
421
+ * around one invocation -- take effect instead of being shadowed by the
422
+ * context captured at yield time.
423
+ */
424
+ const bindContext = (op: (input: unknown) => Effect.Effect<any, any, any>) =>
425
+ Effect.map(
426
+ Effect.context(),
427
+ (context) => (input: unknown) =>
428
+ // `Context` is contravariant, so `Context<never>` is not assignable
429
+ // to the `Context<any>` updateContext expects -- the widening cast is
430
+ // sound (the merge only ever adds entries).
431
+ Effect.updateContext(op(input), (current): Context.Context<any> =>
432
+ Context.merge(context, current),
433
+ ),
434
+ );
435
+
436
+ /**
437
+ * Shared by every operation function (its prototype; it inherits from
438
+ * `Function.prototype`, so operations stay ordinary callables). Makes the
439
+ * operation yieldable -- `yield* operation` returns a requirement-free call
440
+ * function, mirroring the distilled repo's OperationMethod -- and carries the
441
+ * debug/introspection surface (`op.input` / `.output` / `.errors` /
442
+ * `.operationName` / `.pagination`) as lazy getters, so importing a service
443
+ * module doesn't force its suspended schemas.
444
+ */
445
+ const OperationProto: object = /*@__PURE__*/ Object.setPrototypeOf(
446
+ {
447
+ [Symbol.iterator](this: any) {
448
+ return new SingleShotGen(this.asEffect());
449
+ },
450
+ pipe(this: any) {
451
+ return pipeArguments(this.asEffect(), arguments);
452
+ },
453
+ asEffect(this: any) {
454
+ return bindContext(this);
455
+ },
456
+ get input() {
457
+ return prepare(stateOf(this)).cfg.input;
458
+ },
459
+ get output() {
460
+ return prepare(stateOf(this)).cfg.output;
461
+ },
462
+ get errors() {
463
+ return prepare(stateOf(this)).cfg.errors ?? [];
464
+ },
465
+ get operationName() {
466
+ return prepare(stateOf(this)).cfg.operationName;
467
+ },
468
+ get pagination() {
469
+ return (prepare(stateOf(this)).cfg as PaginatedOperationConfig<any, any, any, any>)
470
+ .pagination;
471
+ },
472
+ },
473
+ Function.prototype,
474
+ );
475
+
476
+ const makeOperation = (state: OperationState, proto: object): any => {
477
+ const fn = (input: unknown) => callOperation(state, input);
478
+ defineState(fn, state);
479
+ return Object.setPrototypeOf(fn, proto);
480
+ };
481
+
208
482
  export function make<
209
483
  I extends S.Top,
210
484
  O extends S.Top,
@@ -219,101 +493,7 @@ export function make<
219
493
  InstanceType<E[number]> | PE | HttpClientError.HttpClientError,
220
494
  PR | HttpClient.HttpClient
221
495
  > {
222
- // Lazily resolve the operation config + schema ASTs on first call, not at
223
- // module-load time. Generated SDKs wrap each request/response schema in
224
- // `Schema.suspend(() => ...)`; forcing them here (rather than when the
225
- // `export const` is evaluated) keeps importing a service module cheap and
226
- // only pays the schema-construction cost for operations that are actually
227
- // called. Memoized so subsequent calls are free.
228
- interface Prepared {
229
- readonly cfg: OperationConfig<I, O, PE, PR, E>;
230
- readonly inputAst: AST.AST;
231
- readonly outputAst: AST.AST;
232
- }
233
- let prepared: Prepared | undefined;
234
- const prepare = (): Prepared => {
235
- if (prepared) return prepared;
236
- const cfg = configFn();
237
- prepared = {
238
- cfg,
239
- inputAst: cfg.input!.ast,
240
- outputAst: cfg.output!.ast,
241
- };
242
- return prepared;
243
- };
244
- const fn = (input: unknown) =>
245
- Effect.suspend(() => {
246
- const { cfg, inputAst, outputAst } = prepare();
247
- const call = Effect.flatMap(protocolContext(cfg.protocol), (protocolCtx) =>
248
- Effect.gen(function* () {
249
- const protocol = yield* Protocol;
250
- const client = yield* HttpClient.HttpClient;
251
- const request = yield* protocol.encode({
252
- input,
253
- inputAst,
254
- config: cfg,
255
- });
256
- const response = yield* client.execute(request);
257
- return yield* protocol.decode({
258
- response,
259
- outputAst,
260
- errors: cfg.errors ?? [],
261
- config: cfg,
262
- });
263
- }).pipe(Effect.provideContext(protocolCtx)),
264
- );
265
- return applyRetry(call, cfg.retry);
266
- });
267
-
268
- // Make the operation itself yieldable: `yield* operation` captures the
269
- // current context and returns a requirement-free call function (mirrors
270
- // the distilled repo's OperationMethod). The captured context is a
271
- // FALLBACK, not a snapshot: entries present on the calling fiber at call
272
- // time win, so per-call overrides — e.g. providing `Endpoint` with a
273
- // discovered data-plane address around one invocation — take effect
274
- // instead of being shadowed by the context captured at yield time.
275
- const Proto = {
276
- [Symbol.iterator](this: any) {
277
- return new SingleShotGen(this.asEffect());
278
- },
279
- pipe(this: any) {
280
- return pipeArguments(this.asEffect(), arguments);
281
- },
282
- asEffect() {
283
- return Effect.map(
284
- Effect.context(),
285
- (context) => (input: unknown) =>
286
- // `Context` is contravariant, so `Context<never>` is not assignable
287
- // to the `Context<any>` updateContext expects — the widening cast is
288
- // sound (the merge only ever adds entries).
289
- Effect.updateContext(fn(input), (current): Context.Context<any> =>
290
- Context.merge(context, current),
291
- ),
292
- );
293
- },
294
- };
295
- Object.assign(fn, Proto);
296
-
297
- // Debug/introspection surface carried over from the distilled client:
298
- // the operation's metadata is readable off the exported callable
299
- // (e.g. `iam.listRoles.input` / `.output` / `.errors` / `.operationName`
300
- // / `.pagination`). Lazy getters, so importing a service module doesn't
301
- // force its suspended schemas.
302
- Object.defineProperties(fn, {
303
- input: { get: () => prepare().cfg.input, configurable: true },
304
- output: { get: () => prepare().cfg.output, configurable: true },
305
- errors: { get: () => prepare().cfg.errors ?? [], configurable: true },
306
- operationName: {
307
- get: () => prepare().cfg.operationName,
308
- configurable: true,
309
- },
310
- pagination: {
311
- get: () => (prepare().cfg as PaginatedOperationConfig<I, O, PE, PR, E>).pagination,
312
- configurable: true,
313
- },
314
- });
315
-
316
- return fn as any;
496
+ return makeOperation({ configFn }, OperationProto);
317
497
  }
318
498
 
319
499
  //#endregion
@@ -325,7 +505,7 @@ export function make<
325
505
  * element of the page response itself, or of its `result` member.
326
506
  *
327
507
  * It can only see shapes it was taught, so any other envelope
328
- * (`{ branches: […] }`, `{ data: […] }`, …) lands on `unknown` — which is
508
+ * (`{ branches: [...] }`, `{ data: [...] }`, ...) lands on `unknown` -- which is
329
509
  * why generators pass the item type EXPLICITLY as
330
510
  * {@link PaginatedOperationMethod}'s `Item` argument, resolved from the
331
511
  * pagination trait's `items` path against the response shape. This default
@@ -345,7 +525,7 @@ export type PaginatedItem<A> =
345
525
  * `.pages(input)` streaming every page response and `.items(input)` streaming
346
526
  * the individual items across pages.
347
527
  *
348
- * Used twice in {@link PaginatedOperationMethod} — once with the operation's
528
+ * Used twice in {@link PaginatedOperationMethod} -- once with the operation's
349
529
  * requirements (`R`) for the direct-call style, once with `R = never` for the
350
530
  * value `yield* operation` hands back, which has the caller's context baked in.
351
531
  */
@@ -357,7 +537,7 @@ export interface PaginatedCall<I, O, E, R, Item> {
357
537
 
358
538
  /**
359
539
  * A paginated operation: usable both ways an {@link OperationMethod} is, with
360
- * `.pages` / `.items` on BOTH — the operation object for
540
+ * `.pages` / `.items` on BOTH -- the operation object for
361
541
  * `yield* op.items(input)`, and the requirement-free call function for
362
542
  * `const op = yield* operation; yield* op.items(input)` (distilled #145).
363
543
  */
@@ -366,7 +546,8 @@ export type PaginatedOperationMethod<I, O, E, R, Item = PaginatedItem<O>> = Effe
366
546
  never,
367
547
  R
368
548
  > &
369
- PaginatedCall<I, O, E, R, Item>;
549
+ PaginatedCall<I, O, E, R, Item> &
550
+ OperationSchemas<I, O>;
370
551
 
371
552
  export interface PaginatedOperationConfig<
372
553
  I extends S.Top,
@@ -379,6 +560,53 @@ export interface PaginatedOperationConfig<
379
560
  pagination: Pagination.PaginatedTrait;
380
561
  }
381
562
 
563
+ /** `.pages` / `.items` over any call function (the operation itself or a context-bound one). */
564
+ const streamsOf = (state: OperationState, call: (input: any) => Effect.Effect<any, any, any>) => {
565
+ const pag = () => (prepare(state).cfg as PaginatedOperationConfig<any, any, any, any>).pagination;
566
+ // Data operations carry their strategy in the config.
567
+ const paginate =
568
+ state.strategy ??
569
+ (prepare(state).cfg as { strategy?: Pagination.PaginationStrategy }).strategy ??
570
+ Pagination.paginateWithDefaults;
571
+ const pages = (input: Record<string, unknown>) => paginate(call, input, pag());
572
+ const items = (input: Record<string, unknown>) => {
573
+ const p = pag();
574
+ return p.items ? Pagination.extractItems(pages(input), p.items) : pages(input);
575
+ };
576
+ return { pages, items };
577
+ };
578
+
579
+ /**
580
+ * `.pages` / `.items` are getters that build the stream functions on first
581
+ * access and cache them on the operation, so they cost nothing until used
582
+ * and stay detachable (`const { items } = op` works).
583
+ */
584
+ const streamGetter = (name: "pages" | "items") =>
585
+ function (this: any) {
586
+ const fns = streamsOf(stateOf(this), this);
587
+ Object.defineProperties(this, {
588
+ pages: { value: fns.pages, configurable: true },
589
+ items: { value: fns.items, configurable: true },
590
+ });
591
+ return fns[name];
592
+ };
593
+
594
+ const PaginatedOperationProto: object = /*@__PURE__*/ Object.create(OperationProto, {
595
+ pages: { get: /*@__PURE__*/ streamGetter("pages"), configurable: true },
596
+ items: { get: /*@__PURE__*/ streamGetter("items"), configurable: true },
597
+ // `yield* operation` returns a fresh context-bound function; give it
598
+ // `.pages` / `.items` too (distilled #145). Same fallback (not snapshot)
599
+ // semantics as the plain operation.
600
+ asEffect: {
601
+ value(this: any) {
602
+ const state = stateOf(this);
603
+ return Effect.map(bindContext(this), (call) => Object.assign(call, streamsOf(state, call)));
604
+ },
605
+ configurable: true,
606
+ writable: true,
607
+ },
608
+ });
609
+
382
610
  /**
383
611
  * Like {@link make}, plus `.pages()` / `.items()` streaming built on the
384
612
  * operation's pagination trait. The SDK can pass a provider-specific
@@ -401,43 +629,714 @@ export function makePaginated<
401
629
  InstanceType<E[number]> | PE | HttpClientError.HttpClientError,
402
630
  PR | HttpClient.HttpClient
403
631
  > {
404
- const fn: any = make(configFn);
405
- // configFn is a cheap object literal over already-constructed consts —
406
- // re-invoking it here just reads the pagination trait (memoized).
407
- let pagination: Pagination.PaginatedTrait | undefined;
408
- const pag = () => (pagination ??= configFn().pagination);
409
- const paginate = strategy ?? Pagination.paginateWithDefaults;
410
-
411
- // The streams are built over a CALL FUNCTION, so the same code serves both
412
- // call styles: the operation itself (requirements intact), and the
413
- // context-bound function `yield* operation` hands back — whose streams
414
- // inherit that captured context and so need nothing after the yield.
415
- const withStreams = (call: (input: any) => Effect.Effect<any, any, any>): any => {
416
- const pages = (input: Record<string, unknown>) => paginate(call, input, pag());
417
- const items = (input: Record<string, unknown>) => {
418
- const p = pag();
419
- return p.items ? Pagination.extractItems(pages(input), p.items) : pages(input);
420
- };
421
- return Object.assign(call, { pages, items });
632
+ return makeOperation(strategy ? { configFn, strategy } : { configFn }, PaginatedOperationProto);
633
+ }
634
+
635
+ //#endregion
636
+
637
+ //#region Data operations
638
+
639
+ /**
640
+ * Generated operations described by data instead of code.
641
+ *
642
+ * A service module holds each operation as one arrow that is both the
643
+ * callable operation and the holder of its description:
644
+ *
645
+ * export const getFile = API.op((i) => i === API.D ? ['{input:#1,...};__more', [__0, __4, ...]] : API.call(getFile, i));
646
+ *
647
+ * Called with {@link D}, it returns `[data, refs]`: `;`-separated entries
648
+ * in a small expression language (below) and the values they name. `refs[0]`
649
+ * is the schema-lite `at` (lazy schema wrapper). Schemas reached by more
650
+ * than one operation live in shared holders, `function __d3() { return
651
+ * [data, refs]; }`, named in `refs` so a bundler keeps only the holders an
652
+ * operation reaches. Entry 0 of an operation is its config; the rest are
653
+ * schemas and thunk bodies. Evaluating an entry calls the same
654
+ * constructors the code form called, in the same order, so the result is
655
+ * the same schema.
656
+ *
657
+ * Importing a module allocates one function per operation and one per
658
+ * holder; the data stays text in the module source until first use. A
659
+ * holder's refs may also be values built from module code on first use
660
+ * (service traits, endpoint rules), which its value entries name.
661
+ *
662
+ * Grammar (`;` never appears outside an entry separator; strings escape it):
663
+ *
664
+ * $N refs[N]
665
+ * #N #R:N schema entry N of this holder / of the holder refs[R] (lazy, memoized)
666
+ * ~N ~R:N value entry N of this holder / of refs[R] (a constant, evaluated once)
667
+ * >N thunk `() => entry N`
668
+ * "..." -1.5 true false null JSON literal u undefined
669
+ * {k:e,"k":e} object [e,e] array
670
+ * e(a,b) call e.name member e.name(a,b) method call e@"X" e.annotate({ identifier: "X" })
671
+ */
672
+ export const D: unique symbol = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/api/D") as any;
673
+
674
+ type DataFn = (i?: unknown) => any;
675
+
676
+ interface Source {
677
+ readonly fn: DataFn;
678
+ e?: string[];
679
+ r?: ReadonlyArray<any>;
680
+ b?: (j: number) => unknown;
681
+ readonly c: unknown[];
682
+ /** Data error classes: the built base class. */
683
+ k?: Function;
684
+ }
685
+
686
+ const sources = /*@__PURE__*/ new WeakMap<DataFn, Source>();
687
+
688
+ const sourceOf = (fn: DataFn): Source => {
689
+ let src = sources.get(fn);
690
+ if (!src) sources.set(fn, (src = { fn, c: [] }));
691
+ if (!src.e) {
692
+ // Called with itself as `this`: a lazy error placeholder finds its data by it.
693
+ const [s, r] = fn.call(fn, D);
694
+ src.e = s.split(";");
695
+ src.r = r;
696
+ }
697
+ return src;
698
+ };
699
+
700
+ /** Schema `j` of a holder, wrapped by `at` (lazy until first use). */
701
+ const schemaOf = (src: Source, j: number): unknown =>
702
+ (src.c[j] ??= src.r![0]((src.b ??= (k: number) => evalEntry(src, k)), j));
703
+
704
+ /** A schema of a holder, for module-level code (error classes) that names one at import. */
705
+ export const schema = (fn: DataFn, j: number): any => schemaOf(sourceOf(fn), j);
706
+
707
+ const TOKEN = /"(?:[^"\\]|\\.)*"|[\w$.+-]*/y;
708
+ const NAME = /[\w$]*/y;
709
+
710
+ const evalEntry = (src: Source, j: number): any => {
711
+ const s = src.e![j]!;
712
+ const r = src.r!;
713
+ let p = 0;
714
+ const tok = (re = NAME): string => {
715
+ re.lastIndex = p;
716
+ const t = re.exec(s)![0];
717
+ p += t.length;
718
+ return t;
719
+ };
720
+ const list = (close: string): any[] => {
721
+ const a: any[] = [];
722
+ if (s[p] === close) p++;
723
+ else
724
+ do a.push(expr());
725
+ while (s[p++] !== close);
726
+ return a;
422
727
  };
728
+ const expr = (): any => {
729
+ let v: any;
730
+ const c = s[p++]!;
731
+ if (c === "{") {
732
+ v = {};
733
+ if (s[p] === "}") p++;
734
+ else
735
+ do {
736
+ const k = tok(TOKEN);
737
+ p++;
738
+ v[k[0] === '"' ? JSON.parse(k) : k] = expr();
739
+ } while (s[p++] !== "}");
740
+ } else if (c === "[") v = list("]");
741
+ else if ("$#~>".includes(c)) {
742
+ let h = src;
743
+ let k = +tok();
744
+ if (s[p] === ":") {
745
+ p++;
746
+ h = sourceOf(r[k]);
747
+ k = +tok();
748
+ }
749
+ // A value entry is evaluated once, unwrapped.
750
+ v =
751
+ c === "$"
752
+ ? r[k]
753
+ : c === ">"
754
+ ? () => evalEntry(src, k)
755
+ : c === "#"
756
+ ? schemaOf(h, k)
757
+ : (h.c[k] ??= evalEntry(h, k));
758
+ } else {
759
+ p--;
760
+ const t = tok(TOKEN);
761
+ v = t === "u" ? undefined : JSON.parse(t);
762
+ }
763
+ for (;;) {
764
+ const d = s[p++];
765
+ if (d === "(") v = v(...list(")"));
766
+ else if (d === "@") v = v.annotate({ identifier: JSON.parse(tok(TOKEN)) });
767
+ else if (d === ".") {
768
+ const name = tok();
769
+ v = s[p] === "(" ? (p++, v[name](...list(")"))) : v[name];
770
+ } else return (p--, v);
771
+ }
772
+ };
773
+ return expr();
774
+ };
775
+
776
+ // A data operation gets its state on first use, from this inherited getter.
777
+ // Its descriptors are written inline: nothing keeps them after the prototype is made.
778
+ const dataState = function (this: DataFn): OperationState {
779
+ return defineState(this, { configFn: () => evalEntry(sourceOf(this), 0) });
780
+ };
781
+ let dataProto: object | undefined;
782
+ let dataPaginatedProto: object | undefined;
783
+ /**
784
+ * While a lazy service loads its full module (see {@link lazyService}), the module's
785
+ * definitions go to it instead (kind 0 operation, 1 paginated, 2 error class).
786
+ */
787
+ let definer: ((fn: DataFn, kind: 0 | 1 | 2) => unknown) | undefined;
788
+
789
+ /** Runs `f` with `d` receiving the definitions it evaluates. */
790
+ const defining = (d: typeof definer, f: () => void): void => {
791
+ const outer = definer;
792
+ definer = d;
793
+ try {
794
+ f();
795
+ } finally {
796
+ definer = outer;
797
+ }
798
+ };
799
+
800
+ /**
801
+ * The data of an operation whose name recurs in its strings: `%` in them
802
+ * stands for `stem` (a literal `%` is escaped).
803
+ */
804
+ export const named = (stem: string, data: string, refs: unknown): [string, unknown] => [
805
+ data.replaceAll("%", stem),
806
+ refs,
807
+ ];
808
+
809
+ const asOp = (fn: DataFn): any =>
810
+ Object.setPrototypeOf(
811
+ fn,
812
+ (dataProto ??= Object.create(OperationProto, {
813
+ [stateKey]: { get: dataState, configurable: true },
814
+ })),
815
+ );
816
+
817
+ const asOpPaginated = (fn: DataFn): any =>
818
+ Object.setPrototypeOf(
819
+ fn,
820
+ (dataPaginatedProto ??= Object.create(PaginatedOperationProto, {
821
+ [stateKey]: { get: dataState, configurable: true },
822
+ })),
823
+ );
824
+
825
+ /** An operation described by data (see the region header). */
826
+ export const op = (fn: DataFn): any => (definer ? definer(fn, 0) : asOp(fn));
827
+
828
+ /** A paginated operation described by data; its config may name a `strategy`. */
829
+ export const opPaginated = (fn: DataFn): any => (definer ? definer(fn, 1) : asOpPaginated(fn));
830
+
831
+ /** The call path of a data operation. */
832
+ export const call = (op: unknown, input: unknown): Effect.Effect<any, any, any> =>
833
+ callOperation(stateOf(op), input);
834
+
835
+ /**
836
+ * Generated error classes described by data:
837
+ *
838
+ * export const Oops = API.error(function Oops(i) {
839
+ * return API.newError(i, new.target, ['$1()("Oops",{...})', [...]]);
840
+ * });
841
+ *
842
+ * The function is the class callers see: `new Oops(props)` constructs, a
843
+ * plain call returns the data. Entry 0 of the data is the expression the
844
+ * class extended (e.g. `S.TaggedError()(...).pipe(category)`). The first
845
+ * `new`, or the first read of a static the function does not own (`ast`,
846
+ * `fields`, `identifier`, error matchers, ...), builds that base class and
847
+ * puts it underneath: the function's statics and prototype then inherit
848
+ * from it as `class Oops extends Base {}` did, so `instanceof`, `_tag`,
849
+ * categories and subclasses behave as before. Until then an error class
850
+ * costs one function. The `in` operator sees only `Function` members until
851
+ * the class is built.
852
+ */
853
+ const errorBase = (f: any): Function | undefined => {
854
+ // `f` may be a subclass: find the data class it extends.
855
+ while (f && Object.getPrototypeOf(f) !== lazyErrorStatics && !sources.get(f)?.k)
856
+ f = Object.getPrototypeOf(f);
857
+ if (!f) return undefined;
858
+ const src = sourceOf(f);
859
+ if (!src.k) {
860
+ const base = evalEntry(src, 0) as Function;
861
+ src.k = base;
862
+ Object.setPrototypeOf(f, base);
863
+ Object.setPrototypeOf(f.prototype, base.prototype);
864
+ }
865
+ return src.k;
866
+ };
867
+
868
+ // The statics of an unbuilt error class: `Function.prototype` members answer
869
+ // directly; any other read builds the class, then reads again. Made on first
870
+ // use, so bundles without data errors drop it.
871
+ let lazyErrorStatics: object | undefined;
872
+ const LazyErrorStatics = (): object =>
873
+ (lazyErrorStatics ??= new Proxy(Object.create(Function.prototype), {
874
+ get: (target, key, receiver) =>
875
+ key in target || !errorBase(receiver)
876
+ ? Reflect.get(target, key, receiver)
877
+ : Reflect.get(receiver, key, receiver),
878
+ }));
879
+
880
+ const asError = (fn: DataFn): any => Object.setPrototypeOf(fn, LazyErrorStatics());
423
881
 
424
- // `yield* operation` runs through `make`'s Proto.asEffect, which builds a
425
- // fresh arrow and would drop `.pages` / `.items` (distilled #145). Override
426
- // it here — Proto's `[Symbol.iterator]`/`pipe` dispatch on `this`, so both
427
- // pick this up. Only paginated operations pay for it. Same fallback (not
428
- // snapshot) semantics as Proto.asEffect: call-time fiber entries win over
429
- // the captured context.
430
- fn.asEffect = () =>
431
- Effect.map(Effect.context(), (context) =>
432
- withStreams((input: unknown) =>
433
- // Same contravariance widening as Proto.asEffect above.
434
- Effect.updateContext(fn(input), (current): Context.Context<any> =>
435
- Context.merge(context, current),
882
+ /** An error class described by data (see {@link errorBase}). */
883
+ export const error = (fn: DataFn): any => (definer ? definer(fn, 2) : asError(fn));
884
+
885
+ /**
886
+ * The body of a data error class: with `new`, an instance of the built
887
+ * base whose prototype is `newTarget`'s; called plainly, the class's data.
888
+ */
889
+ export const newError = (props: unknown, newTarget: Function | undefined, data: unknown): any =>
890
+ newTarget ? Reflect.construct(errorBase(newTarget)!, [props], newTarget) : data;
891
+
892
+ //#endregion
893
+
894
+ //#region Lazy service modules
895
+
896
+ /**
897
+ * Node loads a service module as a stub (`lib/services/<name>.js`): one cheap
898
+ * placeholder per operation and error class, no operation data. Its first
899
+ * use loads the full module (`lib/services.full/<name>.js`, what bundlers
900
+ * get) with `require(esm)`.
901
+ *
902
+ * const { o, e, E } = API.lazyService(import.meta.url, "../services.full/sqs.js", "oop", [$0], at, len);
903
+ * export const { OverLimit, QueueDoesNotExist } = E; // or OverLimit = e("OverLimit"), ...
904
+ * export const addPermission = o(), _1 = o(), listQueues = o();
905
+ *
906
+ * Generated stubs reach this through their package's `_bundle/lazy.js`,
907
+ * which passes its own URL and the namespaces every stub imports.
908
+ *
909
+ * `kinds` has one letter per operation definition of the full module: `o`
910
+ * plain, `p` paginated. While the stub's load evaluates the full module,
911
+ * `op` / `opPaginated` / `error` hand back the stub's placeholders in
912
+ * definition order instead of new values, and each placeholder takes the
913
+ * data function it stands for: the full module's operations, error lists
914
+ * and exports are the very objects the stub exported.
915
+ *
916
+ * With a slice index (below), a placeholder's first use evaluates only what
917
+ * its operation reaches instead of the whole full module. A full module that
918
+ * was imported directly (lib code names services through the package, so
919
+ * Node resolves the stub; only explicit `services.full` imports do) keeps
920
+ * its own objects, separate from the stub's.
921
+ */
922
+ interface LazyService {
923
+ readonly url: string;
924
+ readonly spec: string;
925
+ readonly kinds: string;
926
+ /** Namespaces of the full module's imports, when it has a slice index. */
927
+ readonly ns: readonly any[] | undefined;
928
+ /** Byte range of the slice index, a comment at the end of the full module. */
929
+ readonly at: number | undefined;
930
+ readonly len: number | undefined;
931
+ /** The slice index (see {@link sliced}); false: load the whole module. */
932
+ ix?: SliceIndex | false;
933
+ readonly o: any[];
934
+ readonly e: any[];
935
+ /** Data functions by placeholder, filled while the full module loads. */
936
+ od?: DataFn[];
937
+ ed?: DataFn[];
938
+ oi: number;
939
+ ei: number;
940
+ }
941
+
942
+ const define = (svc: LazyService, fn: DataFn, kind: 0 | 1 | 2): any => {
943
+ if (kind === 2) {
944
+ const i = svc.ei++;
945
+ if (i >= svc.e.length) throw new Error(`distilled: ${svc.spec}: error ${i} has no stub`);
946
+ svc.ed![i] = fn;
947
+ return svc.e[i];
948
+ }
949
+ const i = svc.oi++;
950
+ if (i >= svc.o.length || (svc.kinds[i] === "p") !== (kind === 1))
951
+ throw new Error(`distilled: ${svc.spec}: operation ${i} does not match its stub`);
952
+ svc.od![i] = fn;
953
+ return svc.o[i];
954
+ };
955
+
956
+ const load = (svc: LazyService): void => {
957
+ if (svc.od) return;
958
+ svc.od = [];
959
+ svc.ed = [];
960
+ try {
961
+ defining(
962
+ (fn, kind) => define(svc, fn, kind),
963
+ () =>
964
+ (globalThis as any).process.getBuiltinModule("node:module").createRequire(svc.url)(
965
+ svc.spec,
436
966
  ),
437
- ),
438
967
  );
968
+ } catch (e) {
969
+ svc.od = svc.ed = undefined;
970
+ svc.oi = svc.ei = 0;
971
+ throw e;
972
+ }
973
+ if (svc.oi !== svc.o.length || svc.ei !== svc.e.length)
974
+ throw new Error(
975
+ `distilled: ${svc.spec} defined ${svc.oi} of ${svc.o.length} operations and ${svc.ei} of ${svc.e.length} errors (was it imported directly before?)`,
976
+ );
977
+ };
978
+
979
+ /**
980
+ * Per-operation loading. bundle-lib ends a full module with a comment
981
+ * holding its slice index (see scripts/lazy-services.ts): for every top-level
982
+ * declaration, the byte range of its expression and the declarations it may
983
+ * read. A placeholder's first use evaluates only its own data function and,
984
+ * on demand, what that reaches -- one `Function` per declaration, the
985
+ * module's imports and its dependencies passed in as parameters -- instead
986
+ * of the whole module. Function declarations (the shared schema holders)
987
+ * become forwarding functions compiled on their first call, so cycles
988
+ * between them need no order. Without an index, or where code generation
989
+ * from strings is disallowed, the whole module is loaded instead.
990
+ */
991
+ interface SliceIndex {
992
+ readonly file: string;
993
+ /** Open while a burst of evaluations runs; closed in a microtask. */
994
+ fd?: number;
995
+ /** The index text, and where its sections start. */
996
+ readonly raw: string;
997
+ readonly imports: number;
998
+ readonly importsAt: number;
999
+ readonly tableAt: number;
1000
+ readonly linesAt: number;
1001
+ /** Split on first use. */
1002
+ specs?: string[];
1003
+ readonly importValues: unknown[];
1004
+ /** Values by declaration; `busy` marks one being evaluated. */
1005
+ readonly v: unknown[];
1006
+ }
1007
+
1008
+ const busy = {};
1009
+
1010
+ const node = (m: string): any => (globalThis as any).process?.getBuiltinModule?.(m);
1011
+
1012
+ /** Reads `length` bytes at `position` of the full module. */
1013
+ const read = (ix: { file: string; fd?: number }, position: number, length: number): string => {
1014
+ const fs = node("node:fs");
1015
+ if (ix.fd === undefined) {
1016
+ ix.fd = fs.openSync(ix.file, "r") as number;
1017
+ queueMicrotask(() => {
1018
+ fs.closeSync(ix.fd);
1019
+ ix.fd = undefined;
1020
+ });
1021
+ }
1022
+ const buf = (globalThis as any).Buffer.allocUnsafe(length);
1023
+ fs.readSync(ix.fd, buf, 0, length, position);
1024
+ return buf.toString("utf8", 0, length);
1025
+ };
1026
+
1027
+ const indexOf = (file: string, raw: string): SliceIndex => {
1028
+ const importsAt = raw.indexOf("\n") + 1;
1029
+ const tableAt = raw.indexOf("\n", importsAt) + 1;
1030
+ return {
1031
+ file,
1032
+ raw,
1033
+ imports: parseInt(raw),
1034
+ importsAt,
1035
+ tableAt,
1036
+ linesAt: raw.indexOf("\n", tableAt) + 1,
1037
+ importValues: [],
1038
+ v: [],
1039
+ };
1040
+ };
1041
+
1042
+ const fileOf = (svc: LazyService): string =>
1043
+ // A plain POSIX file URL is its path (URL parsing costs ~0.1 ms the first time).
1044
+ /^file:\/\/\/[^%?#]*$/.test(svc.url) && (globalThis as any).process.platform !== "win32"
1045
+ ? svc.url.slice(7, svc.url.lastIndexOf("/") + 1) + svc.spec
1046
+ : node("node:url").fileURLToPath(new URL(svc.spec, svc.url));
1047
+
1048
+ const sliced = (svc: LazyService): SliceIndex | false => {
1049
+ if (svc.ix !== undefined) return svc.ix;
1050
+ svc.ix = false;
1051
+ if (svc.at === undefined || svc.od) return false;
1052
+ try {
1053
+ Function("");
1054
+ const file = fileOf(svc);
1055
+ svc.ix = indexOf(file, read({ file }, svc.at, svc.len!));
1056
+ svc.od = [];
1057
+ svc.ed = [];
1058
+ } catch {}
1059
+ return svc.ix;
1060
+ };
1061
+
1062
+ /**
1063
+ * The first lazy service of a process reads its slice index right after it
1064
+ * is imported (in a microtask, so before the import settles), instead of on
1065
+ * its first call: that read also pays Node's one-time costs of the slice path
1066
+ * (~0.2 ms). Later services read theirs on first use; nothing else is read
1067
+ * ahead, so importing a whole provider holds one index.
1068
+ */
1069
+ let primed = false;
1070
+ const prime = (svc: LazyService): void => {
1071
+ primed = true;
1072
+ queueMicrotask(() => {
1073
+ const ix = sliced(svc);
1074
+ // The first read of an export through a module namespace is slow.
1075
+ if (ix && ix.imports > 0) importOf(svc, ix, 0);
1076
+ });
1077
+ };
1078
+
1079
+ /** The index line of declaration `k`. */
1080
+ const lineOf = (ix: SliceIndex, k: number): string => {
1081
+ const at = ix.tableAt + 5 * k;
1082
+ return ix.raw.slice(
1083
+ ix.linesAt + parseInt(ix.raw.slice(at, at + 5), 36),
1084
+ ix.linesAt + parseInt(ix.raw.slice(at + 5, at + 10), 36) - 1,
1085
+ );
1086
+ };
1087
+
1088
+ const nameOf = (ix: SliceIndex, k: number): string => lineOf(ix, k).split("|")[0]!.split(" ")[3]!;
1089
+
1090
+ const importSpec = (ix: SliceIndex, j: number): string[] =>
1091
+ (ix.specs ??= ix.raw.slice(ix.importsAt, ix.tableAt - 1).split(" "))[j]!.split(":");
1092
+
1093
+ const importOf = (svc: LazyService, ix: SliceIndex, j: number): unknown => {
1094
+ if (j in ix.importValues) return ix.importValues[j];
1095
+ const [, source, name] = importSpec(ix, j);
1096
+ return (ix.importValues[j] = svc.ns![+source!][name!]);
1097
+ };
1098
+
1099
+ /** A top-level name of the full module: imports first, then declarations. */
1100
+ const refOf = (svc: LazyService, ix: SliceIndex, j: number): unknown =>
1101
+ j < ix.imports ? importOf(svc, ix, j) : valueOf(svc, ix, j - ix.imports);
1102
+
1103
+ /**
1104
+ * Evaluates declaration `k` that is not a data function in its generated
1105
+ * shape: compiled with its dependencies in scope; a function with plain
1106
+ * parameters from its body, so it is parsed once, bound to those values.
1107
+ */
1108
+ const evaluate = (svc: LazyService, ix: SliceIndex, k: number): any => {
1109
+ const [head, fn, depText] = lineOf(ix, k).split("|");
1110
+ const deps = depText ? depText.split(" ").map((x) => parseInt(x, 36)) : [];
1111
+ const names = deps.map((j) =>
1112
+ j < ix.imports ? importSpec(ix, j)[0]! : nameOf(ix, j - ix.imports),
1113
+ );
1114
+ const values = deps.map((j) => refOf(svc, ix, j));
1115
+ const url = `\n//# sourceURL=${ix.file}#${nameOf(ix, k)}`;
1116
+ if (fn && fn[0] !== "(") {
1117
+ const [params, range] = fn.split(";");
1118
+ const [start, end, expr] = range!.split(" ").map((x) => parseInt(x, 36));
1119
+ return compileBody(
1120
+ ix,
1121
+ names,
1122
+ values,
1123
+ params ? params.split(",") : [],
1124
+ start!,
1125
+ end!,
1126
+ expr!,
1127
+ url,
1128
+ );
1129
+ }
1130
+ const [, start, end] = head!.split(" ").map((x) => parseInt(x, 36));
1131
+ let text: string;
1132
+ if (fn?.[0] === "(") {
1133
+ // Functions it passes compile on their first call (many never are): it
1134
+ // reads the text around them only.
1135
+ const args = fn.slice(1).split(",");
1136
+ const outer = { names: names.slice(), values: values.slice() };
1137
+ text = "";
1138
+ let at = start!;
1139
+ args.forEach((arg, i) => {
1140
+ const [a, b, bs, be, expr] = arg.split(" ").map((x) => parseInt(x, 36));
1141
+ const params = arg.split(" ")[5];
1142
+ let compiled: Function | undefined;
1143
+ names.push(`$lazy${i}`);
1144
+ values.push(function (this: unknown) {
1145
+ compiled ??= compileBody(
1146
+ ix,
1147
+ outer.names,
1148
+ outer.values,
1149
+ params ? params.split("+") : [],
1150
+ bs!,
1151
+ be!,
1152
+ expr!,
1153
+ url,
1154
+ );
1155
+ return compiled.apply(this, arguments);
1156
+ });
1157
+ text += `${read(ix, at, a! - at)}$lazy${i}`;
1158
+ at = b!;
1159
+ });
1160
+ text += read(ix, at, end! - at);
1161
+ } else text = read(ix, start!, end! - start!);
1162
+ return Function(...names, `"use strict";return(${text}\n)${url}`)(...values);
1163
+ };
1164
+
1165
+ /**
1166
+ * A function with plain parameters, compiled from its body (parsed once)
1167
+ * with `names` in scope bound to `values`; its parameters shadow them.
1168
+ */
1169
+ const compileBody = (
1170
+ ix: SliceIndex,
1171
+ names: string[],
1172
+ values: unknown[],
1173
+ own: string[],
1174
+ start: number,
1175
+ end: number,
1176
+ expr: number,
1177
+ url: string,
1178
+ ): Function => {
1179
+ const text = read(ix, start, end - start);
1180
+ const keep = names.map((n) => !own.includes(n));
1181
+ return Function(
1182
+ ...names.filter((_, i) => keep[i]),
1183
+ ...own,
1184
+ // A block: the body's own declarations shadow the names in scope, as they did.
1185
+ `"use strict";${expr ? `return(${text}\n)` : `{${text}\n}`}${url}`,
1186
+ ).bind(undefined, ...values.filter((_, i) => keep[i]));
1187
+ };
1188
+
1189
+ /**
1190
+ * The data function of a data line (`=stem;start end;refs`): reads the data
1191
+ * and resolves its refs, compiling nothing.
1192
+ */
1193
+ const dataFn = (svc: LazyService, ix: SliceIndex, fn: string): [string, unknown[]] => {
1194
+ const [stem, range, refs] = fn.slice(1).split(";");
1195
+ const sp = range!.indexOf(" ");
1196
+ const start = parseInt(range!, 36);
1197
+ const data = read(ix, start, parseInt(range!.slice(sp + 1), 36) - start);
1198
+ const values: unknown[] = [];
1199
+ if (refs)
1200
+ for (const x of refs.split(",")) {
1201
+ const j = parseInt(x, 36);
1202
+ values.push(j < ix.imports ? importOf(svc, ix, j) : slot(svc, ix, j - ix.imports, false));
1203
+ }
1204
+ return [stem ? data.replaceAll("%", stem) : data, values];
1205
+ };
1206
+
1207
+ /**
1208
+ * The value declaration `k` of the full module has; with `own`, for an
1209
+ * operation or error class, its data function instead of its placeholder.
1210
+ */
1211
+ const slot = (svc: LazyService, ix: SliceIndex, k: number, own: boolean): any => {
1212
+ if (!own) {
1213
+ if (k in ix.v) return ix.v[k] === busy ? undefined : ix.v[k];
1214
+ const ops = svc.o.length;
1215
+ if (k < ops) return (ix.v[k] = svc.o[k]);
1216
+ if (k < ops + svc.e.length) return (ix.v[k] = svc.e[k - ops]);
1217
+ }
1218
+ const at = ix.tableAt + 5 * k;
1219
+ const line = ix.raw.slice(
1220
+ ix.linesAt + parseInt(ix.raw.slice(at, at + 5), 36),
1221
+ ix.linesAt + parseInt(ix.raw.slice(at + 5, at + 10), 36) - 1,
1222
+ );
1223
+ const bar = line.indexOf("|");
1224
+ if (line[bar + 1] === "=") {
1225
+ const fn = dataFn.bind(undefined, svc, ix, line.slice(bar + 1)) as DataFn;
1226
+ return own ? fn : (ix.v[k] = fn);
1227
+ }
1228
+ if (own) return evaluate(svc, ix, k);
1229
+ if (line[0] === "1") {
1230
+ // A function declaration: compiled on its first call, so cycles need no order.
1231
+ let fn: Function | undefined;
1232
+ return (ix.v[k] = function (this: unknown) {
1233
+ return (fn ??= evaluate(svc, ix, k)).apply(this, arguments);
1234
+ });
1235
+ }
1236
+ ix.v[k] = busy;
1237
+ return (ix.v[k] = evaluate(svc, ix, k));
1238
+ };
1239
+
1240
+ const valueOf = (svc: LazyService, ix: SliceIndex, k: number): unknown => slot(svc, ix, k, false);
1241
+
1242
+ /** The data function of placeholder `i` (`kind` 0: operation, 1: error class). */
1243
+ const dataOf = (svc: LazyService, kind: 0 | 1, i: number): DataFn => {
1244
+ const loaded = kind === 0 ? svc.od : svc.ed;
1245
+ if (loaded?.[i]) return loaded[i]!;
1246
+ const ix = sliced(svc);
1247
+ if (!ix) {
1248
+ load(svc);
1249
+ return (kind === 0 ? svc.od : svc.ed)![i]!;
1250
+ }
1251
+ return ((kind === 0 ? svc.od : svc.ed)![i] = slot(
1252
+ svc,
1253
+ ix,
1254
+ kind === 0 ? i : svc.o.length + i,
1255
+ true,
1256
+ ));
1257
+ };
439
1258
 
440
- return withStreams(fn);
1259
+ /**
1260
+ * The placeholders of a lazy service module (see the region header): `o()`
1261
+ * and `e()` make the next operation / error class. A placeholder finds its
1262
+ * data by its index; it closes over nothing of its own, so it costs one
1263
+ * function.
1264
+ */
1265
+ export const lazyService = (
1266
+ url: string,
1267
+ spec: string,
1268
+ kinds: string,
1269
+ ns?: readonly any[],
1270
+ at?: number,
1271
+ len?: number,
1272
+ ): { readonly o: () => any; readonly e: (name: string) => any; readonly E: any } => {
1273
+ const svc: LazyService = { url, spec, kinds, ns, at, len, o: [], e: [], oi: 0, ei: 0 };
1274
+ if (!primed && at !== undefined && !(globalThis as any).process?.env?.NOPRIME) prime(svc);
1275
+ return {
1276
+ o: () => {
1277
+ const paginated = kinds[svc.o.length] === "p";
1278
+ const f: DataFn = function op(x) {
1279
+ return x === D ? dataOf(svc, 0, svc.o.indexOf(op))(D) : call(op, x);
1280
+ };
1281
+ svc.o.push(paginated ? asOpPaginated(f) : asOp(f));
1282
+ return f;
1283
+ },
1284
+ e: (name: string) => {
1285
+ // A computed key names the function without a property of its own.
1286
+ const f = {
1287
+ [name]: function (this: unknown, x: unknown) {
1288
+ return new.target
1289
+ ? newError(x, new.target, undefined)
1290
+ : dataOf(svc, 1, svc.e.indexOf(this))(x);
1291
+ },
1292
+ }[name]!;
1293
+ svc.e.push(asError(f));
1294
+ return f;
1295
+ },
1296
+ // Destructured once by the stub: each property read makes the error class of that name.
1297
+ get E() {
1298
+ const e = this.e;
1299
+ return new Proxy({}, { get: (_, name) => e(name as string) });
1300
+ },
1301
+ };
1302
+ };
1303
+
1304
+ /**
1305
+ * A service barrel's stand-in for `export * as sqs from "./sqs.js"` in Node:
1306
+ * a namespace whose module is loaded (`require(esm)`) on first access, so
1307
+ * importing a provider's barrel loads no service module. Reads, `in`,
1308
+ * `Object.keys` and spreading see the module's exports; it is read-only.
1309
+ */
1310
+ interface LazyNamespace {
1311
+ readonly url: string;
1312
+ readonly spec: string;
1313
+ ns?: any;
441
1314
  }
442
1315
 
1316
+ const namespaceOf = (t: LazyNamespace): any =>
1317
+ (t.ns ??= (globalThis as any).process.getBuiltinModule("node:module").createRequire(t.url)(
1318
+ t.spec,
1319
+ ));
1320
+
1321
+ let lazyNamespaceHandler: ProxyHandler<LazyNamespace> | undefined;
1322
+
1323
+ export const lazyNamespace = (url: string, spec: string): any =>
1324
+ new Proxy<LazyNamespace>(
1325
+ { url, spec },
1326
+ (lazyNamespaceHandler ??= {
1327
+ get: (t, k) => namespaceOf(t)[k],
1328
+ has: (t, k) => k in namespaceOf(t),
1329
+ ownKeys: (t) => Reflect.ownKeys(namespaceOf(t)),
1330
+ getOwnPropertyDescriptor: (t, k) => {
1331
+ const d = Reflect.getOwnPropertyDescriptor(namespaceOf(t), k);
1332
+ // The target does not hold these: a proxy may only report them configurable.
1333
+ return d && { ...d, configurable: true };
1334
+ },
1335
+ getPrototypeOf: () => null,
1336
+ set: () => false,
1337
+ defineProperty: () => false,
1338
+ deleteProperty: () => false,
1339
+ }),
1340
+ );
1341
+
443
1342
  //#endregion