@agoric/internal 0.3.3-other-dev-8f8782b.0 → 0.3.3-other-dev-fbe72e7.0.fbe72e7

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 (131) hide show
  1. package/README.md +7 -2
  2. package/exported.js +2 -0
  3. package/package.json +41 -19
  4. package/src/action-types.d.ts +51 -5
  5. package/src/action-types.d.ts.map +1 -1
  6. package/src/action-types.js +74 -15
  7. package/src/batched-deliver.d.ts +9 -6
  8. package/src/batched-deliver.d.ts.map +1 -1
  9. package/src/batched-deliver.js +9 -3
  10. package/src/callback.d.ts +24 -17
  11. package/src/callback.d.ts.map +1 -1
  12. package/src/callback.js +55 -61
  13. package/src/chain-storage-paths.d.ts +2 -3
  14. package/src/chain-storage-paths.d.ts.map +1 -1
  15. package/src/chain-storage-paths.js +2 -3
  16. package/src/chain-utils.d.ts +27 -0
  17. package/src/chain-utils.d.ts.map +1 -0
  18. package/src/chain-utils.js +62 -0
  19. package/src/cli-utils.d.ts +2 -0
  20. package/src/cli-utils.d.ts.map +1 -0
  21. package/src/cli-utils.js +21 -0
  22. package/src/config.d.ts +22 -12
  23. package/src/config.d.ts.map +1 -1
  24. package/src/config.js +23 -10
  25. package/src/debug.d.ts +1 -1
  26. package/src/errors.d.ts +2 -0
  27. package/src/errors.d.ts.map +1 -0
  28. package/src/errors.js +16 -0
  29. package/src/hex.d.ts +15 -0
  30. package/src/hex.d.ts.map +1 -0
  31. package/src/hex.js +105 -0
  32. package/src/index.d.ts +10 -1
  33. package/src/index.js +13 -2
  34. package/src/install-ses-debug.d.ts +2 -0
  35. package/src/install-ses-debug.d.ts.map +1 -0
  36. package/src/install-ses-debug.js +6 -0
  37. package/src/js-utils.d.ts +40 -0
  38. package/src/js-utils.d.ts.map +1 -0
  39. package/src/js-utils.js +237 -0
  40. package/src/lib-chainStorage.d.ts +59 -67
  41. package/src/lib-chainStorage.d.ts.map +1 -1
  42. package/src/lib-chainStorage.js +95 -92
  43. package/src/lib-nodejs/ava-unhandled-rejection.d.ts +13 -0
  44. package/src/lib-nodejs/ava-unhandled-rejection.d.ts.map +1 -0
  45. package/src/lib-nodejs/ava-unhandled-rejection.js +66 -0
  46. package/src/lib-nodejs/engine-gc.d.ts +3 -0
  47. package/src/lib-nodejs/engine-gc.d.ts.map +1 -0
  48. package/src/lib-nodejs/engine-gc.js +22 -0
  49. package/src/lib-nodejs/gc-and-finalize.d.ts +2 -0
  50. package/src/lib-nodejs/gc-and-finalize.d.ts.map +1 -0
  51. package/src/lib-nodejs/gc-and-finalize.js +91 -0
  52. package/src/lib-nodejs/spawnSubprocessWorker.d.ts +15 -0
  53. package/src/lib-nodejs/spawnSubprocessWorker.d.ts.map +1 -0
  54. package/src/lib-nodejs/spawnSubprocessWorker.js +89 -0
  55. package/src/lib-nodejs/waitUntilQuiescent.d.ts +2 -0
  56. package/src/lib-nodejs/waitUntilQuiescent.d.ts.map +1 -0
  57. package/src/lib-nodejs/waitUntilQuiescent.js +18 -0
  58. package/src/lib-nodejs/worker-protocol.d.ts +4 -0
  59. package/src/lib-nodejs/worker-protocol.d.ts.map +1 -0
  60. package/src/lib-nodejs/worker-protocol.js +54 -0
  61. package/src/magic-cookie-test-only.js +2 -2
  62. package/src/marshal.d.ts +33 -0
  63. package/src/marshal.d.ts.map +1 -0
  64. package/src/marshal.js +156 -0
  65. package/src/method-tools.d.ts +1 -0
  66. package/src/method-tools.d.ts.map +1 -1
  67. package/src/method-tools.js +33 -62
  68. package/src/metrics.d.ts +183 -0
  69. package/src/metrics.d.ts.map +1 -0
  70. package/src/metrics.js +476 -0
  71. package/src/module-utils.d.ts +2 -0
  72. package/src/module-utils.d.ts.map +1 -0
  73. package/src/module-utils.js +27 -0
  74. package/src/natural-sort.d.ts +2 -0
  75. package/src/natural-sort.d.ts.map +1 -0
  76. package/src/natural-sort.js +48 -0
  77. package/src/netstring.d.ts +24 -0
  78. package/src/netstring.d.ts.map +1 -0
  79. package/src/netstring.js +125 -0
  80. package/src/node/buffer-line-transform.d.ts +20 -16
  81. package/src/node/buffer-line-transform.d.ts.map +1 -1
  82. package/src/node/buffer-line-transform.js +12 -9
  83. package/src/node/createBundles.d.ts.map +1 -1
  84. package/src/node/createBundles.js +12 -3
  85. package/src/node/fs-stream.d.ts +1 -1
  86. package/src/node/fs-stream.d.ts.map +1 -1
  87. package/src/node/fs-stream.js +48 -37
  88. package/src/node/shutdown.d.ts.map +1 -1
  89. package/src/node/shutdown.js +0 -1
  90. package/src/priority-senders.d.ts +2 -1
  91. package/src/priority-senders.d.ts.map +1 -1
  92. package/src/priority-senders.js +10 -4
  93. package/src/queue.d.ts +1 -1
  94. package/src/queue.d.ts.map +1 -1
  95. package/src/queue.js +7 -8
  96. package/src/scratch.d.ts +1 -1
  97. package/src/scratch.d.ts.map +1 -1
  98. package/src/ses-utils.d.ts +68 -0
  99. package/src/ses-utils.d.ts.map +1 -0
  100. package/src/ses-utils.js +422 -0
  101. package/src/storage-test-utils.d.ts +49 -84
  102. package/src/storage-test-utils.d.ts.map +1 -1
  103. package/src/storage-test-utils.js +234 -116
  104. package/src/tagged.d.ts +152 -0
  105. package/src/testing-utils.d.ts +2 -0
  106. package/src/testing-utils.d.ts.map +1 -1
  107. package/src/testing-utils.js +44 -5
  108. package/src/tmpDir.d.ts +2 -0
  109. package/src/tmpDir.d.ts.map +1 -0
  110. package/src/tmpDir.js +17 -0
  111. package/src/tokens.d.ts +34 -0
  112. package/src/tokens.d.ts.map +1 -0
  113. package/src/tokens.js +35 -0
  114. package/src/typeCheck.d.ts +9 -0
  115. package/src/typeCheck.d.ts.map +1 -0
  116. package/src/typeCheck.js +23 -0
  117. package/src/typeGuards.d.ts +17 -0
  118. package/src/typeGuards.d.ts.map +1 -1
  119. package/src/typeGuards.js +20 -0
  120. package/src/types-index.d.ts +1 -0
  121. package/src/types-index.js +2 -0
  122. package/src/types.d.ts +83 -18
  123. package/src/types.d.ts.map +1 -0
  124. package/src/types.ts +129 -0
  125. package/src/upgrade-api.d.ts +14 -4
  126. package/src/upgrade-api.d.ts.map +1 -1
  127. package/src/upgrade-api.js +50 -18
  128. package/CHANGELOG.md +0 -106
  129. package/src/utils.d.ts +0 -67
  130. package/src/utils.d.ts.map +0 -1
  131. package/src/utils.js +0 -451
package/src/utils.d.ts DELETED
@@ -1,67 +0,0 @@
1
- export const BASIS_POINTS: 10000n;
2
- export function fromUniqueEntries<K, V>(allEntries: Iterable<[K, V]>): {};
3
- export function objectMap<O extends Record<string, any>, R>(original: O, mapFn: (value: O[keyof O], key: keyof O) => R): { [P in keyof O]: R; };
4
- export function listDifference(leftNames: Array<string | symbol>, rightNames: Array<string | symbol>): (string | symbol)[];
5
- export function throwLabeled(innerErr: Error, label: string | number, ErrorConstructor?: ErrorConstructor | undefined): never;
6
- export function applyLabelingError<A, R>(func: (...args: A[]) => R, args: A[], label?: string | number | undefined): R;
7
- /**
8
- * @template T
9
- * @typedef {{[KeyType in keyof T]: T[KeyType]} & {}} Simplify
10
- * flatten the type output to improve type hints shown in editors
11
- * https://github.com/sindresorhus/type-fest/blob/main/source/simplify.d.ts
12
- */
13
- /**
14
- * @typedef {(...args: any[]) => any} Callable
15
- */
16
- /**
17
- * @template {{}} T
18
- * @typedef {{ [K in keyof T]: T[K] extends Callable ? T[K] : DeeplyAwaited<T[K]> }} DeeplyAwaitedObject
19
- */
20
- /**
21
- * @template T
22
- * @typedef {T extends PromiseLike<any> ? Awaited<T> : T extends {} ? Simplify<DeeplyAwaitedObject<T>> : Awaited<T>} DeeplyAwaited
23
- */
24
- /**
25
- * A more constrained version of {deeplyFulfilled} for type safety until
26
- * https://github.com/endojs/endo/issues/1257
27
- * Useful in starting contracts that need all terms to be fulfilled
28
- * in order to be durable.
29
- *
30
- * @type {<T extends {}>(unfulfilledTerms: T) => Promise<DeeplyAwaited<T>>}
31
- */
32
- export const deeplyFulfilledObject: <T extends {}>(unfulfilledTerms: T) => Promise<DeeplyAwaited<T>>;
33
- export function makeMeasureSeconds(currentTimeMillisec: typeof import('perf_hooks').performance.now): <T>(fn: () => Promise<T>) => Promise<{
34
- result: T;
35
- duration: number;
36
- }>;
37
- export function makeAggregateError(errors: Error[], message?: string | undefined): Error;
38
- export function PromiseAllOrErrors<T>(items: readonly (T | PromiseLike<T>)[]): Promise<T[]>;
39
- /**
40
- * @type {<T>(
41
- * trier: () => Promise<T>,
42
- * finalizer: (error?: unknown) => Promise<void>,
43
- * ) => Promise<T>}
44
- */ export const aggregateTryFinally: <T>(trier: () => Promise<T>, finalizer: (error?: unknown) => Promise<void>) => Promise<T>;
45
- export function assertAllDefined<T extends Record<string, unknown>>(obj: T): asserts obj is AllDefined<T>;
46
- export const forever: AsyncIterable<undefined>;
47
- export function whileTrue<T>(produce: () => T): AsyncIterable<Awaited<T>>;
48
- export function untilTrue<T>(produce: () => T): AsyncIterable<Awaited<T>>;
49
- /** @type { <X, Y>(xs: X[], ys: Y[]) => [X, Y][]} */
50
- export const zip: <X, Y>(xs: X[], ys: Y[]) => [X, Y][];
51
- /** @type { <T extends Record<string, ERef<any>>>(obj: T) => Promise<{ [K in keyof T]: Awaited<T[K]>}> } */
52
- export const allValues: <T extends Record<string, any>>(obj: T) => Promise<{ [K in keyof T]: Awaited<T[K]>; }>;
53
- export function synchronizedTee<T = unknown>(sourceStream: AsyncIterator<T, void, void>, readerCount: number): AsyncGenerator<T, void, void>[];
54
- /**
55
- * <T>
56
- */
57
- export type ERef<T> = import('@endo/eventual-send').ERef<T>;
58
- /**
59
- * flatten the type output to improve type hints shown in editors
60
- * https://github.com/sindresorhus/type-fest/blob/main/source/simplify.d.ts
61
- */
62
- export type Simplify<T> = { [KeyType_1 in keyof T]: T[KeyType_1]; };
63
- export type Callable = (...args: any[]) => any;
64
- export type DeeplyAwaitedObject<T extends {}> = { [K in keyof T]: T[K] extends Callable ? T[K] : DeeplyAwaited<T[K]>; };
65
- export type DeeplyAwaited<T> = T extends PromiseLike<any> ? Awaited<T> : T extends {} ? Simplify<DeeplyAwaitedObject<T>> : Awaited<T>;
66
- export type AllDefined<T extends Record<string, unknown>> = { [P in keyof T]: Exclude<T[P], undefined>; };
67
- //# sourceMappingURL=utils.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["utils.js"],"names":[],"mappings":"AAcA,kCAAoC;AAa7B,0EAcN;AA0CM,gJAIN;AAOM,0CAHI,MAAM,MAAM,GAAG,MAAM,CAAC,cACtB,MAAM,MAAM,GAAG,MAAM,CAAC,uBAKhC;AASM,uCALI,KAAK,SACL,MAAM,GAAC,MAAM,oDAEX,KAAK,CAYjB;AAUM,uHAyBN;AAGD;;;;;GAKG;AAEH;;GAEG;AAEH;;;GAGG;AAEH;;;GAGG;AAEH;;;;;;;GAOG;AACH,qGAGE;AAUK,wDAHI,cAAc,YAAY,EAAE,WAAW,CAAC,GAAG;;cACmB,MAAM;GAW9E;AAMM,2CAHI,KAAK,EAAE,uCAcjB;AAOM,4FAeN;AAED;;;;;GAKG,CAAC,mFAFoB,OAAO,KAAK,QAAQ,IAAI,CAAC,gBAY7C;AAiBG,0GAUN;AAQD,+CAAoD;AAU7C,0EAUH;AAUG,0EAaH;AAEJ,oDAAoD;AACpD,uDAAqE;AAErE,2GAA2G;AAC3G,+GAIE;AAWK,sGAFI,MAAM,mCA4FhB;;;;sBAlbyB,OAAO,qBAAqB,EAAE,IAAI,CAAC,CAAC,CAAC;;;;;;iCAkJxC,GAAG,EAAE,KAAK,GAAG;;+BAUvB,CAAC,SAAS,YAAY,GAAG,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,CAAC,SAAS,EAAE,GAAG,SAAS,oBAAoB,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC"}
package/src/utils.js DELETED
@@ -1,451 +0,0 @@
1
- // @ts-check
2
- // @jessie-check
3
-
4
- import { E } from '@endo/far';
5
- import { deeplyFulfilled, isObject } from '@endo/marshal';
6
- import { isPromise, makePromiseKit } from '@endo/promise-kit';
7
- import { makeQueue } from '@endo/stream';
8
- import { asyncGenerate, makeSet } from 'jessie.js';
9
-
10
- const { entries, fromEntries, keys, values } = Object;
11
- const { ownKeys } = Reflect;
12
-
13
- const { details: X, quote: q, Fail } = assert;
14
-
15
- export const BASIS_POINTS = 10_000n;
16
-
17
- /** @template T @typedef {import('@endo/eventual-send').ERef<T>} ERef<T> */
18
-
19
- /**
20
- * Throws if multiple entries use the same property name. Otherwise acts
21
- * like `Object.fromEntries` but hardens the result.
22
- * Use it to protect from property names computed from user-provided data.
23
- *
24
- * @template K,V
25
- * @param {Iterable<[K,V]>} allEntries
26
- * @returns {{[k: K]: V}}
27
- */
28
- export const fromUniqueEntries = allEntries => {
29
- const entriesArray = [...allEntries];
30
- const result = harden(fromEntries(entriesArray));
31
- if (ownKeys(result).length === entriesArray.length) {
32
- return result;
33
- }
34
- const names = makeSet();
35
- for (const [name, _] of entriesArray) {
36
- if (names.has(name)) {
37
- Fail`collision on property name ${q(name)}: ${entriesArray}`;
38
- }
39
- names.add(name);
40
- }
41
- throw Fail`internal: failed to create object from unique entries`;
42
- };
43
- harden(fromUniqueEntries);
44
-
45
- /**
46
- * By analogy with how `Array.prototype.map` will map the elements of
47
- * an array to transformed elements of an array of the same shape,
48
- * `objectMap` will do likewise for the string-named own enumerable
49
- * properties of an object.
50
- *
51
- * Typical usage applies `objectMap` to a CopyRecord, i.e.,
52
- * an object for which `passStyleOf(original) === 'copyRecord'`. For these,
53
- * none of the following edge cases arise. The result will be a CopyRecord
54
- * with exactly the same property names, whose values are the mapped form of
55
- * the original's values.
56
- *
57
- * When the original is not a CopyRecord, some edge cases to be aware of
58
- * * No matter how mutable the original object, the returned object is
59
- * hardened.
60
- * * Only the string-named enumerable own properties of the original
61
- * are mapped. All other properties are ignored.
62
- * * If any of the original properties were accessors, `Object.entries`
63
- * will cause its `getter` to be called and will use the resulting
64
- * value.
65
- * * No matter whether the original property was an accessor, writable,
66
- * or configurable, all the properties of the returned object will be
67
- * non-writable, non-configurable, data properties.
68
- * * No matter what the original object may have inherited from, and
69
- * no matter whether it was a special kind of object such as an array,
70
- * the returned object will always be a plain object inheriting directly
71
- * from `Object.prototype` and whose state is only these new mapped
72
- * own properties.
73
- *
74
- * With these differences, even if the original object was not a CopyRecord,
75
- * if all the mapped values are Passable, then the returned object will be
76
- * a CopyRecord.
77
- *
78
- * @template {Record<string, any>} O
79
- * @param {O} original
80
- * @template R map result
81
- * @param {(value: O[keyof O], key: keyof O) => R} mapFn
82
- * @returns {{ [P in keyof O]: R}}
83
- */
84
- export const objectMap = (original, mapFn) => {
85
- const ents = entries(original);
86
- const mapEnts = ents.map(([k, v]) => [k, mapFn(v, k)]);
87
- return harden(fromEntries(mapEnts));
88
- };
89
- harden(objectMap);
90
-
91
- /**
92
- * @param {Array<string | symbol>} leftNames
93
- * @param {Array<string | symbol>} rightNames
94
- */
95
- export const listDifference = (leftNames, rightNames) => {
96
- const rightSet = makeSet(rightNames);
97
- return leftNames.filter(name => !rightSet.has(name));
98
- };
99
- harden(listDifference);
100
-
101
- /**
102
- * @param {Error} innerErr
103
- * @param {string|number} label
104
- * @param {ErrorConstructor} [ErrorConstructor]
105
- * @returns {never}
106
- */
107
- export const throwLabeled = (innerErr, label, ErrorConstructor = undefined) => {
108
- if (typeof label === 'number') {
109
- label = `[${label}]`;
110
- }
111
- const outerErr = assert.error(
112
- `${label}: ${innerErr.message}`,
113
- ErrorConstructor,
114
- );
115
- assert.note(outerErr, X`Caused by ${innerErr}`);
116
- throw outerErr;
117
- };
118
- harden(throwLabeled);
119
-
120
- /**
121
- * @template A,R
122
- * @param {(...args: A[]) => R} func
123
- * @param {A[]} args
124
- * @param {string|number} [label]
125
- * @returns {R}
126
- */
127
- export const applyLabelingError = (func, args, label = undefined) => {
128
- if (label === undefined) {
129
- return func(...args);
130
- }
131
- let result;
132
- try {
133
- result = func(...args);
134
- } catch (err) {
135
- throwLabeled(err, label);
136
- }
137
- if (isPromise(result)) {
138
- // If result is a rejected promise, this will return a promise with a
139
- // different rejection reason. But this confuses TypeScript because it types
140
- // that case as `Promise<never>` which is cool for a promise that will never
141
- // fulfill. But TypeScript doesn't understand that this will only happen
142
- // when `result` was a rejected promise. In only this case `R` should
143
- // already allow `Promise<never>` as a subtype.
144
- /** @type {unknown} */
145
- const relabeled = E.when(result, undefined, reason =>
146
- throwLabeled(reason, label),
147
- );
148
- return /** @type {R} */ (relabeled);
149
- } else {
150
- return result;
151
- }
152
- };
153
- harden(applyLabelingError);
154
-
155
- /**
156
- * @template T
157
- * @typedef {{[KeyType in keyof T]: T[KeyType]} & {}} Simplify
158
- * flatten the type output to improve type hints shown in editors
159
- * https://github.com/sindresorhus/type-fest/blob/main/source/simplify.d.ts
160
- */
161
-
162
- /**
163
- * @typedef {(...args: any[]) => any} Callable
164
- */
165
-
166
- /**
167
- * @template {{}} T
168
- * @typedef {{ [K in keyof T]: T[K] extends Callable ? T[K] : DeeplyAwaited<T[K]> }} DeeplyAwaitedObject
169
- */
170
-
171
- /**
172
- * @template T
173
- * @typedef {T extends PromiseLike<any> ? Awaited<T> : T extends {} ? Simplify<DeeplyAwaitedObject<T>> : Awaited<T>} DeeplyAwaited
174
- */
175
-
176
- /**
177
- * A more constrained version of {deeplyFulfilled} for type safety until
178
- * https://github.com/endojs/endo/issues/1257
179
- * Useful in starting contracts that need all terms to be fulfilled
180
- * in order to be durable.
181
- *
182
- * @type {<T extends {}>(unfulfilledTerms: T) => Promise<DeeplyAwaited<T>>}
183
- */
184
- export const deeplyFulfilledObject = async obj => {
185
- isObject(obj) || Fail`param must be an object`;
186
- return deeplyFulfilled(obj);
187
- };
188
-
189
- /**
190
- * Returns a function that uses a millisecond-based time-since-epoch capability
191
- * (such as `performance.now`) to measure execution time of an async function
192
- * and report the result in seconds to match our telemetry standard.
193
- *
194
- * @param {typeof import('perf_hooks').performance.now} currentTimeMillisec
195
- * @returns {<T>(fn: () => Promise<T>) => Promise<{ result: T, duration: number }>}
196
- */
197
- export const makeMeasureSeconds = currentTimeMillisec => {
198
- /** @param {() => any} fn */
199
- const measureSeconds = async fn => {
200
- const t0 = currentTimeMillisec();
201
- const result = await fn();
202
- const durationMillisec = currentTimeMillisec() - t0;
203
- return { result, duration: durationMillisec / 1000 };
204
- };
205
- return measureSeconds;
206
- };
207
-
208
- /**
209
- * @param {Error[]} errors
210
- * @param {string} [message]
211
- */
212
- export const makeAggregateError = (errors, message) => {
213
- const err = Error(message);
214
- Object.defineProperties(err, {
215
- name: {
216
- value: 'AggregateError',
217
- },
218
- errors: {
219
- value: errors,
220
- },
221
- });
222
- return err;
223
- };
224
-
225
- /**
226
- * @template T
227
- * @param {readonly (T | PromiseLike<T>)[]} items
228
- * @returns {Promise<T[]>}
229
- */
230
- export const PromiseAllOrErrors = async items => {
231
- return Promise.allSettled(items).then(results => {
232
- const errors = /** @type {PromiseRejectedResult[]} */ (
233
- results.filter(({ status }) => status === 'rejected')
234
- ).map(result => result.reason);
235
- if (!errors.length) {
236
- return /** @type {PromiseFulfilledResult<T>[]} */ (results).map(
237
- result => result.value,
238
- );
239
- } else if (errors.length === 1) {
240
- throw errors[0];
241
- } else {
242
- throw makeAggregateError(errors);
243
- }
244
- });
245
- };
246
-
247
- /**
248
- * @type {<T>(
249
- * trier: () => Promise<T>,
250
- * finalizer: (error?: unknown) => Promise<void>,
251
- * ) => Promise<T>}
252
- */ export const aggregateTryFinally = async (trier, finalizer) =>
253
- trier().then(
254
- async result => finalizer().then(() => result),
255
- async tryError =>
256
- finalizer(tryError)
257
- .then(
258
- () => tryError,
259
- finalizeError => makeAggregateError([tryError, finalizeError]),
260
- )
261
- .then(error => Promise.reject(error)),
262
- );
263
-
264
- /**
265
- * @template {Record<string, unknown>} T
266
- * @typedef {{[P in keyof T]: Exclude<T[P], undefined>;}} AllDefined
267
- */
268
-
269
- /**
270
- * Concise way to check values are available from object literal shorthand.
271
- * Throws error message to specify the missing values.
272
- *
273
- * @template {Record<string, unknown>} T
274
- * @param {T} obj
275
- * @throws if any value in the object entries is not defined
276
- * @returns {asserts obj is AllDefined<T>}
277
- */
278
-
279
- export const assertAllDefined = obj => {
280
- const missing = [];
281
- for (const [key, val] of Object.entries(obj)) {
282
- if (val === undefined) {
283
- missing.push(key);
284
- }
285
- }
286
- if (missing.length > 0) {
287
- Fail`missing ${q(missing)}`;
288
- }
289
- };
290
-
291
- /** @type {IteratorResult<undefined, never>} */
292
- const notDone = harden({ done: false, value: undefined });
293
-
294
- /** @type {IteratorResult<never, void>} */
295
- const alwaysDone = harden({ done: true, value: undefined });
296
-
297
- export const forever = asyncGenerate(() => notDone);
298
-
299
- /**
300
- * @template T
301
- * @param {() => T} produce
302
- * The value of `await produce()` is used for its truthiness vs falsiness.
303
- * IOW, it is coerced to a boolean so the caller need not bother doing this
304
- * themselves.
305
- * @returns {AsyncIterable<Awaited<T>>}
306
- */
307
- export const whileTrue = produce =>
308
- asyncGenerate(async () => {
309
- const value = await produce();
310
- if (!value) {
311
- return alwaysDone;
312
- }
313
- return harden({
314
- done: false,
315
- value,
316
- });
317
- });
318
-
319
- /**
320
- * @template T
321
- * @param {() => T} produce
322
- * The value of `await produce()` is used for its truthiness vs falsiness.
323
- * IOW, it is coerced to a boolean so the caller need not bother doing this
324
- * themselves.
325
- * @returns {AsyncIterable<Awaited<T>>}
326
- */
327
- export const untilTrue = produce =>
328
- asyncGenerate(async () => {
329
- const value = await produce();
330
- if (value) {
331
- return harden({
332
- done: true,
333
- value,
334
- });
335
- }
336
- return harden({
337
- done: false,
338
- value,
339
- });
340
- });
341
-
342
- /** @type { <X, Y>(xs: X[], ys: Y[]) => [X, Y][]} */
343
- export const zip = (xs, ys) => harden(xs.map((x, i) => [x, ys[+i]]));
344
-
345
- /** @type { <T extends Record<string, ERef<any>>>(obj: T) => Promise<{ [K in keyof T]: Awaited<T[K]>}> } */
346
- export const allValues = async obj => {
347
- const resolved = await Promise.all(values(obj));
348
- // @ts-expect-error cast
349
- return harden(fromEntries(zip(keys(obj), resolved)));
350
- };
351
-
352
- /**
353
- * A tee implementation where all readers are synchronized with each other.
354
- * They all consume the source stream in lockstep, and any one returning or
355
- * throwing early will affect the others.
356
- *
357
- * @template [T=unknown]
358
- * @param {AsyncIterator<T, void, void>} sourceStream
359
- * @param {number} readerCount
360
- */
361
- export const synchronizedTee = (sourceStream, readerCount) => {
362
- /** @type {IteratorReturnResult<void> | undefined} */
363
- let doneResult;
364
-
365
- /** @typedef {IteratorResult<(value: PromiseLike<IteratorResult<T>>) => void>} QueuePayload */
366
- /** @type {import('@endo/stream').AsyncQueue<QueuePayload>[]} */
367
- const queues = [];
368
-
369
- /** @returns {Promise<void>} */
370
- const pullNext = async () => {
371
- const requests = await Promise.allSettled(queues.map(queue => queue.get()));
372
- const rejections = [];
373
- /** @type {Array<(value: PromiseLike<IteratorResult<T>>) => void>} */
374
- const resolvers = [];
375
- let done = false;
376
- for (const settledResult of requests) {
377
- if (settledResult.status === 'rejected') {
378
- rejections.push(settledResult.reason);
379
- } else {
380
- done ||= !!settledResult.value.done;
381
- resolvers.push(settledResult.value.value);
382
- }
383
- }
384
- /** @type {Promise<IteratorResult<T>>} */
385
- let result;
386
- if (doneResult) {
387
- result = Promise.resolve(doneResult);
388
- } else if (rejections.length) {
389
- const error = assert.error(assert.details`Teed stream threw`);
390
- assert.note(error, assert.details`Teed rejections: ${rejections}`);
391
- result =
392
- sourceStream.throw?.(error) ||
393
- Promise.resolve(sourceStream.return?.()).then(() =>
394
- Promise.reject(error),
395
- );
396
- } else if (done) {
397
- result =
398
- sourceStream.return?.() ||
399
- Promise.resolve({ done: true, value: undefined });
400
- } else {
401
- result = sourceStream.next();
402
- }
403
- result.then(
404
- r => {
405
- if (r.done) {
406
- doneResult = r;
407
- }
408
- },
409
- () => {
410
- doneResult = { done: true, value: undefined };
411
- },
412
- );
413
- resolvers.forEach(resolve => resolve(result));
414
- return pullNext();
415
- };
416
-
417
- const readers = Array.from({ length: readerCount }).map(() => {
418
- /** @type {import('@endo/stream').AsyncQueue<QueuePayload>} */
419
- const queue = makeQueue();
420
- queues.push(queue);
421
-
422
- /** @type {AsyncGenerator<T, void, void>} */
423
- const reader = harden({
424
- async next() {
425
- /** @type {import('@endo/promise-kit').PromiseKit<IteratorResult<T>>} */
426
- const { promise, resolve } = makePromiseKit();
427
- queue.put({ value: resolve, done: false });
428
- return promise;
429
- },
430
- async return() {
431
- /** @type {import('@endo/promise-kit').PromiseKit<IteratorResult<T>>} */
432
- const { promise, resolve } = makePromiseKit();
433
- queue.put({ value: resolve, done: true });
434
- return promise;
435
- },
436
- async throw(reason) {
437
- const rejection = Promise.reject(reason);
438
- queue.put(rejection);
439
- return rejection;
440
- },
441
- // eslint-disable-next-line no-restricted-globals
442
- [Symbol.asyncIterator]() {
443
- return reader;
444
- },
445
- });
446
- return reader;
447
- });
448
-
449
- void pullNext();
450
- return readers;
451
- };