@aztec/foundation 0.0.1-commit.f504929 → 0.0.1-commit.f5a9928

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 (288) hide show
  1. package/dest/bigint-buffer/index.d.ts +1 -1
  2. package/dest/bigint-buffer/index.d.ts.map +1 -1
  3. package/dest/bigint-buffer/index.js +6 -1
  4. package/dest/branded-types/block_number.d.ts +3 -3
  5. package/dest/branded-types/block_number.d.ts.map +1 -1
  6. package/dest/branded-types/block_number.js +15 -4
  7. package/dest/branded-types/buffer32_hash.d.ts +27 -0
  8. package/dest/branded-types/buffer32_hash.d.ts.map +1 -0
  9. package/dest/branded-types/buffer32_hash.js +12 -0
  10. package/dest/branded-types/checkpoint_number.d.ts +9 -3
  11. package/dest/branded-types/checkpoint_number.d.ts.map +1 -1
  12. package/dest/branded-types/checkpoint_number.js +11 -0
  13. package/dest/branded-types/epoch.d.ts +2 -2
  14. package/dest/branded-types/epoch.d.ts.map +1 -1
  15. package/dest/branded-types/index.d.ts +2 -1
  16. package/dest/branded-types/index.d.ts.map +1 -1
  17. package/dest/branded-types/index.js +1 -0
  18. package/dest/branded-types/index_within_checkpoint.d.ts +2 -2
  19. package/dest/branded-types/index_within_checkpoint.d.ts.map +1 -1
  20. package/dest/branded-types/slot.d.ts +5 -2
  21. package/dest/branded-types/slot.d.ts.map +1 -1
  22. package/dest/branded-types/slot.js +3 -0
  23. package/dest/buffer/buffer16.d.ts +3 -1
  24. package/dest/buffer/buffer16.d.ts.map +1 -1
  25. package/dest/buffer/buffer32.d.ts +28 -61
  26. package/dest/buffer/buffer32.d.ts.map +1 -1
  27. package/dest/buffer/buffer32.js +29 -63
  28. package/dest/buffer/index.d.ts +2 -1
  29. package/dest/buffer/index.d.ts.map +1 -1
  30. package/dest/buffer/index.js +1 -0
  31. package/dest/buffer/utils.d.ts +3 -0
  32. package/dest/buffer/utils.d.ts.map +1 -0
  33. package/dest/buffer/utils.js +7 -0
  34. package/dest/collection/array.d.ts +11 -1
  35. package/dest/collection/array.d.ts.map +1 -1
  36. package/dest/collection/array.js +33 -0
  37. package/dest/collection/index.d.ts +3 -1
  38. package/dest/collection/index.d.ts.map +1 -1
  39. package/dest/collection/index.js +2 -0
  40. package/dest/collection/lru_map.d.ts +41 -0
  41. package/dest/collection/lru_map.d.ts.map +1 -0
  42. package/dest/collection/lru_map.js +119 -0
  43. package/dest/collection/lru_set.d.ts +35 -0
  44. package/dest/collection/lru_set.d.ts.map +1 -0
  45. package/dest/collection/lru_set.js +95 -0
  46. package/dest/committable/committable.js +1 -1
  47. package/dest/config/env_var.d.ts +2 -2
  48. package/dest/config/env_var.d.ts.map +1 -1
  49. package/dest/config/index.d.ts +67 -37
  50. package/dest/config/index.d.ts.map +1 -1
  51. package/dest/config/index.js +72 -71
  52. package/dest/config/network_config.d.ts +13 -45
  53. package/dest/config/network_config.d.ts.map +1 -1
  54. package/dest/config/network_config.js +3 -1
  55. package/dest/config/network_name.d.ts +2 -2
  56. package/dest/config/network_name.d.ts.map +1 -1
  57. package/dest/config/network_name.js +1 -3
  58. package/dest/config/secret_value.d.ts +2 -2
  59. package/dest/config/secret_value.d.ts.map +1 -1
  60. package/dest/crypto/aes128/index.d.ts +2 -1
  61. package/dest/crypto/aes128/index.d.ts.map +1 -1
  62. package/dest/crypto/aes128/index.js +11 -2
  63. package/dest/crypto/bls/bn254_keystore.d.ts +10 -177
  64. package/dest/crypto/bls/bn254_keystore.d.ts.map +1 -1
  65. package/dest/crypto/bls/bn254_keystore.js +22 -34
  66. package/dest/crypto/poseidon/index.d.ts +1 -1
  67. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  68. package/dest/crypto/poseidon/index.js +40 -33
  69. package/dest/crypto/schnorr/index.d.ts +8 -7
  70. package/dest/crypto/schnorr/index.d.ts.map +1 -1
  71. package/dest/crypto/schnorr/index.js +6 -6
  72. package/dest/crypto/schnorr/signature.d.ts +9 -29
  73. package/dest/crypto/schnorr/signature.d.ts.map +1 -1
  74. package/dest/crypto/schnorr/signature.js +20 -36
  75. package/dest/curves/bls12/field.d.ts +3 -3
  76. package/dest/curves/bls12/field.d.ts.map +1 -1
  77. package/dest/curves/bls12/field.js +0 -5
  78. package/dest/curves/bls12/point.d.ts +2 -2
  79. package/dest/curves/bls12/point.d.ts.map +1 -1
  80. package/dest/curves/bn254/field.d.ts +23 -19
  81. package/dest/curves/bn254/field.d.ts.map +1 -1
  82. package/dest/curves/bn254/field.js +23 -17
  83. package/dest/curves/grumpkin/point.d.ts +14 -28
  84. package/dest/curves/grumpkin/point.d.ts.map +1 -1
  85. package/dest/curves/grumpkin/point.js +29 -43
  86. package/dest/eth-address/index.d.ts +2 -2
  87. package/dest/eth-address/index.d.ts.map +1 -1
  88. package/dest/eth-address/index.js +0 -3
  89. package/dest/eth-signature/eth_signature.d.ts +2 -2
  90. package/dest/eth-signature/eth_signature.d.ts.map +1 -1
  91. package/dest/fifo/fifo_frame_reader.d.ts +41 -0
  92. package/dest/fifo/fifo_frame_reader.d.ts.map +1 -0
  93. package/dest/fifo/fifo_frame_reader.js +74 -0
  94. package/dest/fifo/index.d.ts +2 -0
  95. package/dest/fifo/index.d.ts.map +1 -0
  96. package/dest/fifo/index.js +1 -0
  97. package/dest/fifo_set/fifo_set.d.ts +15 -0
  98. package/dest/fifo_set/fifo_set.d.ts.map +1 -0
  99. package/dest/fifo_set/fifo_set.js +39 -0
  100. package/dest/fifo_set/index.d.ts +2 -0
  101. package/dest/fifo_set/index.d.ts.map +1 -0
  102. package/dest/fifo_set/index.js +1 -0
  103. package/dest/iterable/first.d.ts +8 -0
  104. package/dest/iterable/first.d.ts.map +1 -0
  105. package/dest/iterable/first.js +11 -0
  106. package/dest/iterable/index.d.ts +2 -1
  107. package/dest/iterable/index.d.ts.map +1 -1
  108. package/dest/iterable/index.js +1 -0
  109. package/dest/json-rpc/client/fetch.d.ts +8 -3
  110. package/dest/json-rpc/client/fetch.d.ts.map +1 -1
  111. package/dest/json-rpc/client/fetch.js +11 -7
  112. package/dest/json-rpc/client/safe_json_rpc_client.d.ts +1 -1
  113. package/dest/json-rpc/client/safe_json_rpc_client.d.ts.map +1 -1
  114. package/dest/json-rpc/client/safe_json_rpc_client.js +2 -2
  115. package/dest/json-rpc/client/undici.d.ts +14 -3
  116. package/dest/json-rpc/client/undici.d.ts.map +1 -1
  117. package/dest/json-rpc/client/undici.js +47 -14
  118. package/dest/json-rpc/fixtures/test_state.d.ts +4 -8
  119. package/dest/json-rpc/fixtures/test_state.d.ts.map +1 -1
  120. package/dest/json-rpc/fixtures/test_state.js +57 -17
  121. package/dest/json-rpc/server/safe_json_rpc_server.d.ts +49 -11
  122. package/dest/json-rpc/server/safe_json_rpc_server.d.ts.map +1 -1
  123. package/dest/json-rpc/server/safe_json_rpc_server.js +159 -40
  124. package/dest/log/aws-logger-config.d.ts +8 -0
  125. package/dest/log/aws-logger-config.d.ts.map +1 -0
  126. package/dest/log/aws-logger-config.js +55 -0
  127. package/dest/log/pino-logger.d.ts +1 -1
  128. package/dest/log/pino-logger.d.ts.map +1 -1
  129. package/dest/log/pino-logger.js +29 -8
  130. package/dest/noir/noir_package_config.d.ts +19 -104
  131. package/dest/noir/noir_package_config.d.ts.map +1 -1
  132. package/dest/noir/noir_package_config.js +1 -1
  133. package/dest/promise/running-promise.d.ts +8 -2
  134. package/dest/promise/running-promise.d.ts.map +1 -1
  135. package/dest/promise/running-promise.js +17 -5
  136. package/dest/promise/utils.d.ts +14 -1
  137. package/dest/promise/utils.d.ts.map +1 -1
  138. package/dest/promise/utils.js +20 -0
  139. package/dest/queue/batch_queue.d.ts +1 -1
  140. package/dest/queue/batch_queue.d.ts.map +1 -1
  141. package/dest/queue/batch_queue.js +1 -0
  142. package/dest/retry/index.d.ts +31 -3
  143. package/dest/retry/index.d.ts.map +1 -1
  144. package/dest/retry/index.js +44 -2
  145. package/dest/schemas/api.d.ts +12 -10
  146. package/dest/schemas/api.d.ts.map +1 -1
  147. package/dest/schemas/api.js +7 -1
  148. package/dest/schemas/parse.d.ts +4 -4
  149. package/dest/schemas/parse.d.ts.map +1 -1
  150. package/dest/schemas/parse.js +6 -5
  151. package/dest/schemas/schemas.d.ts +15 -15
  152. package/dest/schemas/types.d.ts +3 -3
  153. package/dest/schemas/types.d.ts.map +1 -1
  154. package/dest/schemas/utils.d.ts +7 -11
  155. package/dest/schemas/utils.d.ts.map +1 -1
  156. package/dest/schemas/utils.js +2 -18
  157. package/dest/serialize/buffer_reader.d.ts +1 -1
  158. package/dest/serialize/buffer_reader.d.ts.map +1 -1
  159. package/dest/serialize/buffer_reader.js +5 -0
  160. package/dest/serialize/buffer_sink.d.ts +134 -0
  161. package/dest/serialize/buffer_sink.d.ts.map +1 -0
  162. package/dest/serialize/buffer_sink.js +297 -0
  163. package/dest/serialize/index.d.ts +2 -1
  164. package/dest/serialize/index.d.ts.map +1 -1
  165. package/dest/serialize/index.js +1 -0
  166. package/dest/serialize/serialize.d.ts +1 -32
  167. package/dest/serialize/serialize.d.ts.map +1 -1
  168. package/dest/serialize/serialize.js +0 -21
  169. package/dest/string/index.js +1 -1
  170. package/dest/testing/files/index.d.ts +2 -3
  171. package/dest/testing/files/index.d.ts.map +1 -1
  172. package/dest/testing/files/index.js +1 -2
  173. package/dest/timer/index.d.ts +2 -2
  174. package/dest/timer/index.d.ts.map +1 -1
  175. package/dest/timer/index.js +1 -1
  176. package/dest/timer/timeout.d.ts +3 -1
  177. package/dest/timer/timeout.d.ts.map +1 -1
  178. package/dest/timer/timeout.js +26 -0
  179. package/dest/transport/dispatch/create_dispatch_proxy.d.ts +11 -2
  180. package/dest/transport/dispatch/create_dispatch_proxy.d.ts.map +1 -1
  181. package/dest/transport/index.d.ts +1 -2
  182. package/dest/transport/index.d.ts.map +1 -1
  183. package/dest/transport/index.js +0 -1
  184. package/dest/trees/balanced_merkle_tree_root.d.ts +2 -3
  185. package/dest/trees/balanced_merkle_tree_root.d.ts.map +1 -1
  186. package/dest/trees/balanced_merkle_tree_root.js +2 -3
  187. package/dest/trees/hasher.d.ts +3 -2
  188. package/dest/trees/hasher.d.ts.map +1 -1
  189. package/dest/trees/hasher.js +5 -5
  190. package/dest/trees/indexed_merkle_tree_calculator.d.ts +1 -1
  191. package/dest/trees/indexed_merkle_tree_calculator.d.ts.map +1 -1
  192. package/dest/trees/indexed_merkle_tree_calculator.js +5 -1
  193. package/dest/trees/membership_witness.d.ts +2 -6
  194. package/dest/trees/membership_witness.d.ts.map +1 -1
  195. package/dest/trees/membership_witness.js +0 -9
  196. package/dest/trees/merkle_tree_calculator.d.ts +4 -2
  197. package/dest/trees/merkle_tree_calculator.d.ts.map +1 -1
  198. package/dest/trees/merkle_tree_calculator.js +1 -5
  199. package/dest/trees/sibling_path.d.ts +13 -14
  200. package/dest/trees/sibling_path.d.ts.map +1 -1
  201. package/dest/trees/sibling_path.js +23 -28
  202. package/dest/trees/unbalanced_merkle_tree_root.d.ts +2 -3
  203. package/dest/trees/unbalanced_merkle_tree_root.d.ts.map +1 -1
  204. package/dest/trees/unbalanced_merkle_tree_root.js +2 -3
  205. package/dest/types/index.d.ts +23 -1
  206. package/dest/types/index.d.ts.map +1 -1
  207. package/dest/types/index.js +15 -0
  208. package/package.json +6 -4
  209. package/src/bigint-buffer/index.ts +6 -1
  210. package/src/branded-types/block_number.ts +20 -2
  211. package/src/branded-types/buffer32_hash.ts +38 -0
  212. package/src/branded-types/checkpoint_number.ts +16 -1
  213. package/src/branded-types/epoch.ts +1 -1
  214. package/src/branded-types/index.ts +1 -0
  215. package/src/branded-types/index_within_checkpoint.ts +1 -1
  216. package/src/branded-types/slot.ts +6 -1
  217. package/src/buffer/buffer16.ts +3 -0
  218. package/src/buffer/buffer32.ts +39 -68
  219. package/src/buffer/index.ts +1 -0
  220. package/src/buffer/utils.ts +8 -0
  221. package/src/collection/array.ts +34 -0
  222. package/src/collection/index.ts +2 -0
  223. package/src/collection/lru_map.ts +143 -0
  224. package/src/collection/lru_set.ts +115 -0
  225. package/src/committable/committable.ts +1 -1
  226. package/src/config/env_var.ts +65 -25
  227. package/src/config/index.ts +143 -122
  228. package/src/config/network_config.ts +2 -0
  229. package/src/config/network_name.ts +2 -5
  230. package/src/config/secret_value.ts +1 -1
  231. package/src/crypto/aes128/index.ts +11 -2
  232. package/src/crypto/bls/bn254_keystore.ts +33 -43
  233. package/src/crypto/poseidon/index.ts +42 -34
  234. package/src/crypto/schnorr/index.ts +9 -8
  235. package/src/crypto/schnorr/signature.ts +17 -46
  236. package/src/curves/bls12/field.ts +0 -7
  237. package/src/curves/bn254/field.ts +35 -34
  238. package/src/curves/grumpkin/point.ts +23 -40
  239. package/src/eth-address/index.ts +0 -4
  240. package/src/fifo/fifo_frame_reader.ts +98 -0
  241. package/src/fifo/index.ts +1 -0
  242. package/src/fifo_set/fifo_set.ts +52 -0
  243. package/src/fifo_set/index.ts +1 -0
  244. package/src/iterable/first.ts +14 -0
  245. package/src/iterable/index.ts +1 -0
  246. package/src/json-rpc/client/fetch.ts +19 -5
  247. package/src/json-rpc/client/safe_json_rpc_client.ts +2 -2
  248. package/src/json-rpc/client/undici.ts +54 -12
  249. package/src/json-rpc/fixtures/test_state.ts +10 -10
  250. package/src/json-rpc/server/safe_json_rpc_server.ts +204 -47
  251. package/src/log/aws-logger-config.ts +32 -0
  252. package/src/log/pino-logger.ts +33 -6
  253. package/src/noir/noir_package_config.ts +32 -20
  254. package/src/promise/running-promise.ts +20 -7
  255. package/src/promise/utils.ts +31 -0
  256. package/src/queue/batch_queue.ts +1 -0
  257. package/src/retry/index.ts +66 -4
  258. package/src/schemas/api.ts +25 -25
  259. package/src/schemas/parse.ts +9 -6
  260. package/src/schemas/schemas.ts +4 -4
  261. package/src/schemas/types.ts +2 -2
  262. package/src/schemas/utils.ts +4 -38
  263. package/src/serialize/buffer_reader.ts +5 -0
  264. package/src/serialize/buffer_sink.ts +350 -0
  265. package/src/serialize/index.ts +1 -0
  266. package/src/serialize/serialize.ts +0 -50
  267. package/src/string/index.ts +1 -1
  268. package/src/testing/files/index.ts +1 -2
  269. package/src/timer/index.ts +1 -1
  270. package/src/timer/timeout.ts +31 -0
  271. package/src/transport/dispatch/create_dispatch_proxy.ts +11 -1
  272. package/src/transport/index.ts +0 -1
  273. package/src/trees/balanced_merkle_tree_root.ts +2 -5
  274. package/src/trees/hasher.ts +6 -3
  275. package/src/trees/indexed_merkle_tree_calculator.ts +5 -1
  276. package/src/trees/membership_witness.ts +0 -8
  277. package/src/trees/merkle_tree_calculator.ts +4 -10
  278. package/src/trees/sibling_path.ts +24 -30
  279. package/src/trees/unbalanced_merkle_tree_root.ts +2 -5
  280. package/src/types/index.ts +47 -0
  281. package/dest/crypto/serialize.d.ts +0 -51
  282. package/dest/crypto/serialize.d.ts.map +0 -1
  283. package/dest/crypto/serialize.js +0 -68
  284. package/dest/transport/dispatch/create_dispatch_fn.d.ts +0 -25
  285. package/dest/transport/dispatch/create_dispatch_fn.d.ts.map +0 -1
  286. package/dest/transport/dispatch/create_dispatch_fn.js +0 -17
  287. package/src/crypto/serialize.ts +0 -85
  288. package/src/transport/dispatch/create_dispatch_fn.ts +0 -35
@@ -1,3 +1,4 @@
1
+ import { InterruptError } from '../error/index.js';
1
2
  import { type Logger, createLogger } from '../log/pino-logger.js';
2
3
  import { InterruptibleSleep } from '../sleep/index.js';
3
4
  import { type PromiseWithResolvers, promiseWithResolvers } from './utils.js';
@@ -49,7 +50,8 @@ export class RunningPromise {
49
50
 
50
51
  const poll = async () => {
51
52
  while (this.running) {
52
- const hasRequested = this.requested !== undefined;
53
+ const requested = this.requested;
54
+ this.requested = undefined;
53
55
  try {
54
56
  await this.fn();
55
57
  } catch (err) {
@@ -61,9 +63,8 @@ export class RunningPromise {
61
63
  }
62
64
 
63
65
  // If an immediate run had been requested *before* the function started running, resolve the request.
64
- if (hasRequested) {
65
- this.requested!.resolve();
66
- this.requested = undefined;
66
+ if (requested) {
67
+ requested.resolve();
67
68
  }
68
69
 
69
70
  // If no immediate run was requested, sleep for the polling interval.
@@ -71,6 +72,12 @@ export class RunningPromise {
71
72
  await this.interruptibleSleep.sleep(this.pollingIntervalMS);
72
73
  }
73
74
  }
75
+
76
+ // A trigger that arrived after the final pass started will never be served by any pass, so settle it as
77
+ // failed rather than leaving its caller waiting forever.
78
+ const unserved = this.requested;
79
+ this.requested = undefined;
80
+ unserved?.reject(new InterruptError('RunningPromise stopped before serving trigger'));
74
81
  };
75
82
  this.runningPromise = poll();
76
83
  return this;
@@ -99,9 +106,15 @@ export class RunningPromise {
99
106
 
100
107
  /**
101
108
  * Triggers an immediate run of the function, bypassing the polling interval.
102
- * If the function is currently running, it will be allowed to continue and then called again immediately.
109
+ *
110
+ * Resolves only after a complete run of the function that *started after* this call: a run already in flight is
111
+ * allowed to finish first, and the function is then called again. Concurrent callers coalesce onto a single such
112
+ * run. Rejects if the loop stops (via `stop()` or an error handler requesting exit) before that run happens.
113
+ *
114
+ * Calling this from inside the function itself and awaiting the result deadlocks, since the awaited run cannot
115
+ * start until the current one returns. That usage is not supported.
103
116
  */
104
- public async trigger() {
117
+ public async trigger(): Promise<void> {
105
118
  if (!this.running) {
106
119
  return this.fn();
107
120
  }
@@ -112,7 +125,7 @@ export class RunningPromise {
112
125
  this.requested = requested;
113
126
  this.interruptibleSleep.interrupt();
114
127
  }
115
- await requested!.promise;
128
+ await requested.promise;
116
129
  }
117
130
 
118
131
  /**
@@ -1,3 +1,34 @@
1
+ /**
2
+ * Like `Promise.all`, but runs every promise to completion before resolving or rejecting.
3
+ *
4
+ * `Promise.all` rejects as soon as one input rejects, abandoning the still-running siblings. When those siblings have
5
+ * side effects, the caller observes the rejection and reacts to the failure while the abandoned work is still
6
+ * producing effects. This helper instead guarantees that by the time it rejects, no input is still running.
7
+ *
8
+ * The signature mirrors `Promise.all`'s declaration in TypeScript's standard library, so call sites type exactly as
9
+ * they did with `Promise.all` (in particular, heterogeneous tuples keep their per-position types).
10
+ */
11
+ export async function allToCompletion<T extends readonly unknown[] | []>(
12
+ promises: T,
13
+ ): Promise<{ -readonly [P in keyof T]: Awaited<T[P]> }> {
14
+ const results = await Promise.allSettled<unknown>(promises);
15
+ const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected');
16
+ if (failures.length === 1) {
17
+ // Rethrow a lone failure as-is so error identity is preserved for callers that inspect error types.
18
+ throw failures[0].reason;
19
+ } else if (failures.length > 1) {
20
+ throw new AggregateError(
21
+ failures.map(failure => failure.reason),
22
+ `${failures.length} of ${results.length} concurrent operations failed: ${failures
23
+ .map(failure => (failure.reason instanceof Error ? failure.reason.message : String(failure.reason)))
24
+ .join(' | ')}`,
25
+ );
26
+ }
27
+ return results.map(result => (result as PromiseFulfilledResult<unknown>).value) as {
28
+ -readonly [P in keyof T]: Awaited<T[P]>;
29
+ };
30
+ }
31
+
1
32
  export type PromiseWithResolvers<T> = {
2
33
  promise: Promise<T>;
3
34
  resolve: (value: T) => void;
@@ -105,6 +105,7 @@ export class BatchQueue<T, K extends string | number> {
105
105
  return Promise.resolve();
106
106
  }
107
107
 
108
+ this.flushCurrentBatch();
108
109
  this.container.end();
109
110
  return runningPromise;
110
111
  }
@@ -1,7 +1,7 @@
1
1
  import { TimeoutError } from '../error/index.js';
2
2
  import { type Logger, createLogger } from '../log/index.js';
3
3
  import { sleep } from '../sleep/index.js';
4
- import { Timer } from '../timer/index.js';
4
+ import { type DateProvider, Timer } from '../timer/index.js';
5
5
 
6
6
  /** An error that indicates that the operation should not be retried. */
7
7
  export class NoRetryError extends Error {}
@@ -72,6 +72,34 @@ export async function retry<Result>(
72
72
  }
73
73
  }
74
74
 
75
+ /**
76
+ * Timeout specification accepted by {@link retryUntil}. Either a plain number of seconds, an explicit
77
+ * `{ timeout }` in seconds, or an absolute `{ deadline }` with an optional {@link DateProvider} used to
78
+ * read the current time. A deadline is converted to the remaining seconds at call time; a deadline that
79
+ * has already passed yields a zero remaining budget, matching the immediate-timeout semantics of a
80
+ * non-positive numeric timeout.
81
+ */
82
+ export type RetryUntilTimeout = number | { timeout: number } | { deadline: Date; dateProvider?: DateProvider };
83
+
84
+ /**
85
+ * Resolves a {@link RetryUntilTimeout} to a numeric timeout in seconds for the legacy timer-based loop.
86
+ * A numeric/`{ timeout }` value passes through unchanged (0 means never time out, negative times out on the
87
+ * first interval). A `{ deadline }` is the remaining seconds until the deadline; when the deadline is already
88
+ * at or past `now` it resolves to a negative value so the loop times out immediately instead of being read as
89
+ * the never-timeout sentinel 0.
90
+ */
91
+ function resolveRetryUntilTimeoutSeconds(timeout: RetryUntilTimeout): number {
92
+ if (typeof timeout === 'number') {
93
+ return timeout;
94
+ }
95
+ if ('deadline' in timeout) {
96
+ const now = timeout.dateProvider?.now() ?? Date.now();
97
+ const remainingSeconds = (timeout.deadline.getTime() - now) / 1000;
98
+ return remainingSeconds > 0 ? remainingSeconds : -1;
99
+ }
100
+ return timeout.timeout;
101
+ }
102
+
75
103
  /**
76
104
  * Retry an asynchronous function until it returns a truthy value or the specified timeout is exceeded.
77
105
  * The function is retried periodically with a fixed interval between attempts. The operation can be named for better error messages.
@@ -79,16 +107,20 @@ export async function retry<Result>(
79
107
  *
80
108
  * @param fn - The asynchronous function to be retried, which should return a truthy value upon success or undefined otherwise.
81
109
  * @param name - The optional name of the operation, used for generating timeout error message.
82
- * @param timeout - The optional maximum time, in seconds, to keep retrying before throwing a timeout error. Defaults to 0 (never timeout).
110
+ * @param timeout - The maximum time to keep retrying before throwing a timeout error. Accepts a number of
111
+ * seconds (0 = never time out), an explicit `{ timeout }` in seconds, or an absolute `{ deadline }` with an
112
+ * optional `dateProvider`. A deadline already in the past times out on the first interval, the same as a
113
+ * zero/negative numeric timeout. Defaults to 0 (never timeout).
83
114
  * @param interval - The optional interval, in seconds, between retry attempts. Defaults to 1 second.
84
115
  * @returns A Promise that resolves with the successful (truthy) result of the provided function, or rejects if timeout is exceeded.
85
116
  */
86
117
  export async function retryUntil<T>(
87
118
  fn: () => (T | undefined) | Promise<T | undefined>,
88
119
  name = '',
89
- timeout = 0,
120
+ timeout: RetryUntilTimeout = 0,
90
121
  interval = 1,
91
122
  ) {
123
+ const timeoutSeconds = resolveRetryUntilTimeoutSeconds(timeout);
92
124
  const timer = new Timer();
93
125
  while (true) {
94
126
  const result = await fn();
@@ -98,12 +130,42 @@ export async function retryUntil<T>(
98
130
 
99
131
  await sleep(interval * 1000);
100
132
 
101
- if (timeout && timer.s() > timeout) {
133
+ if (timeoutSeconds && timer.s() > timeoutSeconds) {
102
134
  throw new TimeoutError(name ? `Timeout awaiting ${name}` : 'Timeout');
103
135
  }
104
136
  }
105
137
  }
106
138
 
139
+ /**
140
+ * Retry an asynchronous function until it returns a truthy value or the maximum number of retries is exceeded.
141
+ * The function is retried periodically with a fixed interval between attempts.
142
+ *
143
+ * @param fn - The asynchronous function to be retried, which should return a truthy value upon success or undefined otherwise.
144
+ * @param name - The optional name of the operation, used for generating error messages.
145
+ * @param maxRetries - The maximum number of retry attempts before throwing an error.
146
+ * @param retryInterval - The optional interval, in seconds, between retry attempts. Defaults to 1 second.
147
+ * @returns A Promise that resolves with the successful (truthy) result of the provided function, or rejects if retries are exhausted.
148
+ */
149
+ export async function retryTimes<T>(
150
+ fn: () => (T | undefined) | Promise<T | undefined>,
151
+ name = '',
152
+ maxRetries: number,
153
+ retryInterval = 1,
154
+ ) {
155
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
156
+ const result = await fn();
157
+ if (result) {
158
+ return result;
159
+ }
160
+
161
+ if (attempt < maxRetries) {
162
+ await sleep(retryInterval * 1000);
163
+ }
164
+ }
165
+
166
+ throw new Error(name ? `Retries exhausted awaiting ${name}` : 'Retries exhausted');
167
+ }
168
+
107
169
  /**
108
170
  * Convenience wrapper around retryUntil with fast polling for tests.
109
171
  * Uses 10s timeout and 100ms polling interval by default.
@@ -2,32 +2,19 @@ import type { z } from 'zod';
2
2
 
3
3
  import type { ZodNullableOptional } from './utils.js';
4
4
 
5
- // Forces usage of ZodNullableOptional in parameters schemas so we properly accept nulls for optional parameters.
6
- type ZodParameterTypeFor<T> = undefined extends T
7
- ? ZodNullableOptional<z.ZodType<T, z.ZodTypeDef, any>>
8
- : z.ZodType<T, z.ZodTypeDef, any>;
9
-
10
- type ZodReturnTypeFor<T> = z.ZodType<T, z.ZodTypeDef, any>;
11
-
12
- // This monstruosity is used for mapping function arguments to their schema representation.
13
- // The complexity is required to satisfy ZodTuple which requires a fixed length tuple and
14
- // has a very annoying type of [] | [ZodTypeAny, ...ZodTypeAny], and most types fail to match
15
- // the second option. While a purely recursive approach works, it fails when trying to deal
16
- // with optional arguments (ie optional items in the tuple), and ts does not really like them
17
- // during a recursion and fails with infinite stack depth.
18
- // This type appears to satisfy everyone. Everyone but me.
19
- type ZodMapParameterTypes<T> = T extends []
20
- ? []
21
- : T extends [item: infer Head, ...infer Rest]
22
- ? [ZodParameterTypeFor<Head>, ...{ [K in keyof Rest]: ZodParameterTypeFor<Rest[K]> }]
23
- : T extends [item?: infer Head, ...infer Rest]
24
- ? [ZodNullableOptional<ZodParameterTypeFor<Head>>, ...{ [K in keyof Rest]: ZodParameterTypeFor<Rest[K]> }]
25
- : never;
5
+ // Forces usage of schemas that accept nulls for optional parameters.
6
+ type ZodParameterTypeFor<T> = undefined extends T ? ZodNullableOptional<z.ZodType<T, any>> : z.ZodType<T, any>;
7
+
8
+ type ZodReturnTypeFor<T> = z.ZodType<T, any>;
9
+
10
+ type ZodMapParameterTypes<T extends readonly unknown[]> = {
11
+ [K in keyof T]-?: ZodParameterTypeFor<T[K]>;
12
+ };
26
13
 
27
14
  /** Maps all functions in an interface to their schema representation. */
28
15
  export type ApiSchemaFor<T> = {
29
16
  [K in keyof T]: T[K] extends (...args: infer Args) => Promise<infer Ret>
30
- ? z.ZodFunction<z.ZodTuple<ZodMapParameterTypes<Args>, z.ZodUnknown>, ZodReturnTypeFor<Ret>>
17
+ ? z.ZodFunction<z.ZodTuple<ZodMapParameterTypes<Args>, null>, ZodReturnTypeFor<Ret>>
31
18
  : never;
32
19
  };
33
20
 
@@ -37,11 +24,24 @@ export type ApiSchema = {
37
24
  };
38
25
 
39
26
  /** Return whether an API schema defines a valid function schema for a given method name. */
40
- export function schemaHasMethod(schema: ApiSchema, methodName: string) {
27
+ export function schemaHasMethod<T extends ApiSchema>(
28
+ schema: T,
29
+ methodName: string,
30
+ ): methodName is Extract<keyof T, string> {
41
31
  return (
42
32
  typeof methodName === 'string' &&
43
33
  Object.hasOwn(schema, methodName) &&
44
- typeof schema[methodName].parameters === 'function' &&
45
- typeof schema[methodName].returnType === 'function'
34
+ schema[methodName].def.input !== undefined &&
35
+ schema[methodName].def.output !== undefined
46
36
  );
47
37
  }
38
+
39
+ /** Returns the parameter tuple schema for an API method schema. */
40
+ export function getSchemaParameters<T extends z.ZodFunction<z.ZodTuple<any, any>, z.ZodTypeAny>>(schema: T) {
41
+ return schema.def.input;
42
+ }
43
+
44
+ /** Returns the return value schema for an API method schema. */
45
+ export function getSchemaReturnType<T extends z.ZodFunction<z.ZodTuple<any, any>, z.ZodTypeAny>>(schema: T) {
46
+ return schema.def.output;
47
+ }
@@ -4,16 +4,19 @@ import { times } from '../collection/array.js';
4
4
 
5
5
  /** Parses the given arguments using a tuple from the provided schemas. */
6
6
  export function parse<T extends [] | [z.ZodTypeAny, ...z.ZodTypeAny[]]>(args: IArguments, ...schemas: T) {
7
- return z.tuple(schemas).parse(args);
7
+ return schemas.length === 0
8
+ ? z.tuple([]).parse(args)
9
+ : z.tuple(schemas as [z.ZodTypeAny, ...z.ZodTypeAny[]]).parse(args);
8
10
  }
9
11
 
10
12
  /**
11
13
  * Parses the given arguments against a tuple, allowing empty for optional items.
12
- * @dev Zod doesn't like tuplues with optional items. See https://github.com/colinhacks/zod/discussions/949.
14
+ * @dev Zod doesn't like tuples with optional items. See https://github.com/colinhacks/zod/discussions/949.
13
15
  */
14
- export function parseWithOptionals<T extends z.AnyZodTuple>(args: any[], schema: T): Promise<T['_output']> {
15
- const missingCount = schema.items.length - args.length;
16
- const optionalCount = schema.items.filter(isOptional).length;
16
+ export function parseWithOptionals<T extends z.ZodTuple<any, any>>(args: any[], schema: T): Promise<z.output<T>> {
17
+ const items = schema.def.items;
18
+ const missingCount = items.length - args.length;
19
+ const optionalCount = items.filter(isOptional).length;
17
20
  const toParse =
18
21
  missingCount > 0 && missingCount <= optionalCount ? args.concat(times(missingCount, () => undefined)) : args;
19
22
  return schema.parseAsync(toParse);
@@ -24,6 +27,6 @@ function isOptional(schema: z.ZodTypeAny) {
24
27
  return schema.isOptional();
25
28
  } catch {
26
29
  // See https://github.com/colinhacks/zod/issues/1911
27
- return schema._def.typeName === 'ZodOptional';
30
+ return schema.def.type === 'optional';
28
31
  }
29
32
  }
@@ -44,15 +44,15 @@ export const schemas = {
44
44
  ]),
45
45
 
46
46
  /** Coerces any input to bigint. */
47
- BigInt: z.union([z.bigint(), z.number(), z.string()]).pipe(z.coerce.bigint()),
47
+ BigInt: z.union([z.bigint(), z.number(), z.string()]).pipe(z.coerce.bigint<string | number | bigint>()),
48
48
 
49
49
  /** Coerces any input to integer number. */
50
- Integer: z.union([z.bigint(), z.number(), z.string()]).pipe(z.coerce.number().int()),
50
+ Integer: z.union([z.bigint(), z.number(), z.string()]).pipe(z.coerce.number<string | number | bigint>().int()),
51
51
 
52
52
  /** Coerces input to UInt32. */
53
53
  UInt32: z.union([z.bigint(), z.number(), z.string()]).pipe(
54
54
  z.coerce
55
- .number()
55
+ .number<string | number | bigint>()
56
56
  .int()
57
57
  .min(0)
58
58
  .max(2 ** 32 - 1),
@@ -61,7 +61,7 @@ export const schemas = {
61
61
  /** Coerces input to UInt64. */
62
62
  UInt64: z.union([z.bigint(), z.number(), z.string()]).pipe(
63
63
  z.coerce
64
- .bigint()
64
+ .bigint<string | number | bigint>()
65
65
  .min(0n)
66
66
  .max(2n ** 64n - 1n),
67
67
  ),
@@ -1,6 +1,6 @@
1
1
  import type { ZodType } from 'zod';
2
2
 
3
- export type ZodFor<T> = ZodType<T, any, any>;
3
+ export type ZodFor<T> = ZodType<T, any>;
4
4
 
5
5
  /**
6
6
  * Creates a schema validator that enforces all properties of type T are present in the schema.
@@ -26,7 +26,7 @@ export type ZodFor<T> = ZodType<T, any, any>;
26
26
  * ```
27
27
  */
28
28
  export function zodFor<T>() {
29
- return (schema => schema) as <S extends ZodType<any, any, any>>(
29
+ return (schema => schema) as <S extends ZodType<any, any>>(
30
30
  schema: keyof T extends keyof S['_output']
31
31
  ? keyof S['_output'] extends keyof T
32
32
  ? S
@@ -1,16 +1,4 @@
1
- import {
2
- OK,
3
- type ParseInput,
4
- type ParseReturnType,
5
- ZodFirstPartyTypeKind,
6
- type ZodObject,
7
- ZodOptional,
8
- ZodParsedType,
9
- type ZodRawShape,
10
- type ZodType,
11
- type ZodTypeAny,
12
- z,
13
- } from 'zod';
1
+ import { type ZodObject, type ZodRawShape, type ZodType, type ZodTypeAny, z } from 'zod';
14
2
 
15
3
  import { pick } from '../collection/object.js';
16
4
  import { isHex, withoutHexPrefix } from '../string/index.js';
@@ -41,24 +29,7 @@ export const bufferSchema: ZodFor<Buffer> = z.union([
41
29
  z.instanceof(Buffer),
42
30
  ]);
43
31
 
44
- export class ZodNullableOptional<T extends ZodTypeAny> extends ZodOptional<T> {
45
- _isNullableOptional = true;
46
-
47
- override _parse(input: ParseInput): ParseReturnType<this['_output']> {
48
- const parsedType = this._getType(input);
49
- if (parsedType === ZodParsedType.undefined || parsedType === ZodParsedType.null) {
50
- return OK(undefined);
51
- }
52
- return this._def.innerType._parse(input);
53
- }
54
-
55
- static override create<T extends ZodTypeAny>(type: T): ZodNullableOptional<T> {
56
- return new ZodNullableOptional({
57
- innerType: type,
58
- typeName: ZodFirstPartyTypeKind.ZodOptional,
59
- }) as any;
60
- }
61
- }
32
+ export type ZodNullableOptional<T extends ZodTypeAny> = ZodType<z.output<T> | undefined, z.input<T> | null | undefined>;
62
33
 
63
34
  /**
64
35
  * Declares a parameter as optional. Use this over z.optional in order to accept nulls as undefineds.
@@ -66,7 +37,7 @@ export class ZodNullableOptional<T extends ZodTypeAny> extends ZodOptional<T> {
66
37
  * need to convert nulls to undefineds as we parse.
67
38
  */
68
39
  export function optional<T extends ZodTypeAny>(schema: T) {
69
- return ZodNullableOptional.create(schema);
40
+ return schema.nullish().transform(value => value ?? undefined);
70
41
  }
71
42
 
72
43
  type ToJsonIs<T, TRet> = T extends { toJSON(): TRet } ? T : never;
@@ -83,7 +54,6 @@ export function hexSchemaFor<TClass extends { fromString(str: string): any } | {
83
54
  TClass extends { fromString(str: string): infer TInstance } | { fromBuffer(buf: Buffer): infer TInstance }
84
55
  ? ToJsonIs<TInstance, string>
85
56
  : never,
86
- any,
87
57
  string
88
58
  > {
89
59
  const stringSchema = refinement ? z.string().refine(refinement, `Not a valid instance`) : z.string();
@@ -101,11 +71,7 @@ export function hexSchemaFor<TClass extends { fromString(str: string): any } | {
101
71
  export function bufferSchemaFor<TClass extends { fromBuffer(buf: Buffer): any }>(
102
72
  klazz: TClass,
103
73
  refinement?: (buf: Buffer) => boolean,
104
- ): ZodType<
105
- TClass extends { fromBuffer(buf: Buffer): infer TInstance } ? ToJsonIs<TInstance, Buffer> : never,
106
- any,
107
- string
108
- > {
74
+ ): ZodType<TClass extends { fromBuffer(buf: Buffer): infer TInstance } ? ToJsonIs<TInstance, Buffer> : never, string> {
109
75
  return bufferSchema.refine(refinement ?? (() => true), 'Not a valid buffer').transform(klazz.fromBuffer.bind(klazz));
110
76
  }
111
77
 
@@ -255,6 +255,11 @@ export class BufferReader {
255
255
  if (maxSize !== undefined && size > maxSize) {
256
256
  throw new Error(`Vector size ${size} exceeds maximum allowed ${maxSize}`);
257
257
  }
258
+ // Every element consumes at least one byte, so a size beyond the bytes left is unsatisfiable. Reject it
259
+ // up front rather than relying on each item deserializer to bounds-check as the loop runs out of input.
260
+ if (size > this.remainingBytes()) {
261
+ throw new Error(`Vector size ${size} exceeds remaining buffer length ${this.remainingBytes()}`);
262
+ }
258
263
  const result = new Array<T>(size);
259
264
  for (let i = 0; i < size; i++) {
260
265
  result[i] = itemDeserializer.fromBuffer(this);