@endo/promise-kit 0.2.42 → 0.2.43

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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,17 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ### [0.2.43](https://github.com/endojs/endo/compare/@endo/promise-kit@0.2.42...@endo/promise-kit@0.2.43) (2022-06-28)
7
+
8
+
9
+ ### Features
10
+
11
+ * **promise-kit:** Add non-leaky promise race helper ([505815c](https://github.com/endojs/endo/commit/505815cdb02512d2de6ba0ac73c1130626eebf77))
12
+ * **promise-kit:** detach promise from resolvers after use ([d6e9fba](https://github.com/endojs/endo/commit/d6e9fbae05d9d42bdf7fb79c83893141b0348010))
13
+ * **promise-kit:** Make leak-free race a fully compliant drop-in replacement ([14fbba4](https://github.com/endojs/endo/commit/14fbba496a564add617d4c151726fbfc271e1f4c))
14
+
15
+
16
+
6
17
  ### [0.2.42](https://github.com/endojs/endo/compare/@endo/promise-kit@0.2.41...@endo/promise-kit@0.2.42) (2022-06-11)
7
18
 
8
19
  **Note:** Version bump only for package @endo/promise-kit
package/index.js CHANGED
@@ -3,37 +3,15 @@
3
3
 
4
4
  /// <reference types="ses"/>
5
5
 
6
- /** @type {PromiseConstructor} */
7
- const BestPipelinablePromise = globalThis.HandledPromise || Promise;
6
+ import { makeReleasingExecutorKit } from './src/promise-executor-kit.js';
7
+ import { memoRace } from './src/memo-race.js';
8
8
 
9
- /**
10
- * @template T
11
- * @typedef {Object} PromiseKit A reified Promise
12
- * @property {(value: ERef<T>) => void} resolve
13
- * @property {(reason: any) => void} reject
14
- * @property {Promise<T>} promise
15
- */
9
+ export * from './src/is-promise.js';
10
+ // eslint-disable-next-line import/export
11
+ export * from './src/types.js';
16
12
 
17
- /**
18
- * PromiseRecord is deprecated in favor of PromiseKit.
19
- *
20
- * @template T
21
- * @typedef {PromiseKit<T>} PromiseRecord
22
- */
23
-
24
- /**
25
- * @template T
26
- * @typedef {T | PromiseLike<T>} ERef
27
- * A reference of some kind for to an object of type T. It may be a direct
28
- * reference to a local T. It may be a local presence for a remote T. It may
29
- * be a promise for a local or remote T. Or it may even be a thenable
30
- * (a promise-like non-promise with a "then" method) for a T.
31
- */
32
-
33
- /**
34
- * Needed to prevent type errors where functions are detected to be undefined.
35
- */
36
- const NOOP_INITIALIZER = harden(() => {});
13
+ /** @type {PromiseConstructor} */
14
+ const BestPipelinablePromise = globalThis.HandledPromise || Promise;
37
15
 
38
16
  /**
39
17
  * makePromiseKit() builds a Promise object, and returns a record
@@ -41,31 +19,33 @@ const NOOP_INITIALIZER = harden(() => {});
41
19
  * and rejecting it.
42
20
  *
43
21
  * @template T
44
- * @returns {PromiseKit<T>}
22
+ * @returns {import('./src/types.js').PromiseKit<T>}
45
23
  */
46
24
  export function makePromiseKit() {
47
- /** @type {(value: ERef<T>) => void} */
48
- let resolve = NOOP_INITIALIZER;
49
- /** @type {(reason: unknown) => void} */
50
- let reject = NOOP_INITIALIZER;
25
+ const { resolve, reject, executor } = makeReleasingExecutorKit();
51
26
 
52
- /** @type {Promise<T>} */
53
- const promise = new BestPipelinablePromise((res, rej) => {
54
- resolve = res;
55
- reject = rej;
56
- });
27
+ const promise = new BestPipelinablePromise(executor);
57
28
 
58
29
  return harden({ promise, resolve, reject });
59
30
  }
60
31
  harden(makePromiseKit);
61
32
 
33
+ // NB: Another implementation for Promise.race would be to use the releasing executor,
34
+ // However while it would no longer leak the raced promise objects themselves, it would
35
+ // still leak reactions on the non-resolved promises contending for the race.
36
+
62
37
  /**
63
- * Determine if the argument is a Promise.
38
+ * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
39
+ * or rejected.
64
40
  *
65
- * @param {any} maybePromise The value to examine
66
- * @returns {maybePromise is Promise} Whether it is a promise
41
+ * Unlike `Promise.race` it cleans up after itself so a non-resolved value doesn't hold onto
42
+ * the result promise.
43
+ *
44
+ * @template T
45
+ * @param {Iterable<T>} values An iterable of Promises.
46
+ * @returns {Promise<Awaited<T>>} A new Promise.
67
47
  */
68
- export function isPromise(maybePromise) {
69
- return Promise.resolve(maybePromise) === maybePromise;
48
+ export function racePromises(values) {
49
+ return harden(memoRace.call(BestPipelinablePromise, values));
70
50
  }
71
- harden(isPromise);
51
+ harden(racePromises);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@endo/promise-kit",
3
- "version": "0.2.42",
3
+ "version": "0.2.43",
4
4
  "description": "Helper for making promises",
5
5
  "keywords": [
6
6
  "promise"
@@ -20,6 +20,7 @@
20
20
  "module": "./index.js",
21
21
  "exports": {
22
22
  ".": "./index.js",
23
+ "./shim.js": "./shim.js",
23
24
  "./package.json": "./package.json"
24
25
  },
25
26
  "scripts": {
@@ -34,11 +35,11 @@
34
35
  "test:xs": "exit 0"
35
36
  },
36
37
  "dependencies": {
37
- "ses": "^0.15.16"
38
+ "ses": "^0.15.17"
38
39
  },
39
40
  "devDependencies": {
40
- "@endo/eslint-config": "^0.5.0",
41
- "@endo/ses-ava": "^0.2.26",
41
+ "@endo/eslint-config": "^0.5.1",
42
+ "@endo/ses-ava": "^0.2.27",
42
43
  "ava": "^3.12.1",
43
44
  "babel-eslint": "^10.0.3",
44
45
  "c8": "^7.7.3",
@@ -79,5 +80,5 @@
79
80
  "engines": {
80
81
  "node": ">=11.0"
81
82
  },
82
- "gitHead": "7be9306df5e5eae280134cbbaf0d3886b4e51536"
83
+ "gitHead": "a311acb02115271fbda6953734d0b4f52aa85892"
83
84
  }
package/shim.js ADDED
@@ -0,0 +1,4 @@
1
+ import { memoRace } from './src/memo-race.js';
2
+
3
+ // Unconditionally replace with a non-leaking version
4
+ Promise.race = memoRace;
@@ -0,0 +1,12 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * Determine if the argument is a Promise.
5
+ *
6
+ * @param {unknown} maybePromise The value to examine
7
+ * @returns {maybePromise is Promise} Whether it is a promise
8
+ */
9
+ export function isPromise(maybePromise) {
10
+ return Promise.resolve(maybePromise) === maybePromise;
11
+ }
12
+ harden(isPromise);
@@ -0,0 +1,154 @@
1
+ // @ts-check
2
+ /*
3
+ Initial version authored by Brian Kim:
4
+ https://github.com/nodejs/node/issues/17469#issuecomment-685216777
5
+
6
+ This is free and unencumbered software released into the public domain.
7
+
8
+ Anyone is free to copy, modify, publish, use, compile, sell, or
9
+ distribute this software, either in source code form or as a compiled
10
+ binary, for any purpose, commercial or non-commercial, and by any
11
+ means.
12
+
13
+ In jurisdictions that recognize copyright laws, the author or authors
14
+ of this software dedicate any and all copyright interest in the
15
+ software to the public domain. We make this dedication for the benefit
16
+ of the public at large and to the detriment of our heirs and
17
+ successors. We intend this dedication to be an overt act of
18
+ relinquishment in perpetuity of all present and future rights to this
19
+ software under copyright law.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
24
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
25
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
26
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
27
+ OTHER DEALINGS IN THE SOFTWARE.
28
+
29
+ For more information, please refer to <http://unlicense.org/>
30
+ */
31
+
32
+ const isObject = value => Object(value) === value;
33
+
34
+ /**
35
+ * @template [T=any]
36
+ * @typedef {object} Deferred
37
+ * @property {(value?: import("./types.js").ERef<T> ) => void} resolve
38
+ * @property {(err?: any ) => void} reject
39
+ */
40
+
41
+ /**
42
+ * @typedef { never
43
+ * | {settled: false, deferreds: Set<Deferred>}
44
+ * | {settled: true, deferreds?: undefined}
45
+ * } PromiseMemoRecord
46
+ */
47
+
48
+ // Keys are the values passed to race, values are a record of data containing a
49
+ // set of deferreds and whether the value has settled.
50
+ /** @type {WeakMap<object, PromiseMemoRecord>} */
51
+ const knownPromises = new WeakMap();
52
+
53
+ /**
54
+ * @param {PromiseMemoRecord | undefined} record
55
+ * @returns {Set<Deferred>}
56
+ */
57
+ const markSettled = record => {
58
+ if (!record || record.settled) {
59
+ return new Set();
60
+ }
61
+
62
+ const { deferreds } = record;
63
+ Object.assign(record, {
64
+ deferreds: undefined,
65
+ settled: true,
66
+ });
67
+ Object.freeze(record);
68
+ return deferreds;
69
+ };
70
+
71
+ /**
72
+ *
73
+ * @param {any} value
74
+ * @returns {PromiseMemoRecord}
75
+ */
76
+ const getMemoRecord = value => {
77
+ if (!isObject(value)) {
78
+ // If the contender is a primitive, attempting to use it as a key in the
79
+ // weakmap would throw an error. Luckily, it is safe to call
80
+ // `Promise.resolve(contender).then` on a primitive value multiple times
81
+ // because the promise fulfills immediately. So we fake a settled record.
82
+ return { settled: true };
83
+ }
84
+
85
+ let record = knownPromises.get(value);
86
+
87
+ if (!record) {
88
+ record = { deferreds: new Set(), settled: false };
89
+ knownPromises.set(value, record);
90
+ // This call to `then` happens once for the lifetime of the value.
91
+ Promise.resolve(value).then(
92
+ val => {
93
+ for (const { resolve } of markSettled(record)) {
94
+ resolve(val);
95
+ }
96
+ },
97
+ err => {
98
+ for (const { reject } of markSettled(record)) {
99
+ reject(err);
100
+ }
101
+ },
102
+ );
103
+ }
104
+ return record;
105
+ };
106
+
107
+ const { race } = {
108
+ /**
109
+ * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
110
+ * or rejected.
111
+ *
112
+ * Unlike `Promise.race` it cleans up after itself so a non-resolved value doesn't hold onto
113
+ * the result promise.
114
+ *
115
+ * @template T
116
+ * @template {PromiseConstructor} [P=PromiseConstructor]
117
+ * @this {P}
118
+ * @param {Iterable<T>} values An iterable of Promises.
119
+ * @returns {Promise<Awaited<T>>} A new Promise.
120
+ */
121
+ race(values) {
122
+ let deferred;
123
+ /** @type {T[]} */
124
+ const cachedValues = [];
125
+ const C = this;
126
+ const result = new C((resolve, reject) => {
127
+ deferred = { resolve, reject };
128
+ for (const value of values) {
129
+ cachedValues.push(value);
130
+ const { settled, deferreds } = getMemoRecord(value);
131
+ if (settled) {
132
+ // If the contender is settled (including primitives), it is safe
133
+ // to call `Promise.resolve(value).then` on it.
134
+ C.resolve(value).then(resolve, reject);
135
+ } else {
136
+ deferreds.add(deferred);
137
+ }
138
+ }
139
+ });
140
+
141
+ // The finally callback executes when any value settles, preventing any of
142
+ // the unresolved values from retaining a reference to the resolved value.
143
+ return result.finally(() => {
144
+ for (const value of cachedValues) {
145
+ const { deferreds } = getMemoRecord(value);
146
+ if (deferreds) {
147
+ deferreds.delete(deferred);
148
+ }
149
+ }
150
+ });
151
+ },
152
+ };
153
+
154
+ export { race as memoRace };
@@ -0,0 +1,56 @@
1
+ // @ts-check
2
+
3
+ /// <reference types="ses"/>
4
+
5
+ /**
6
+ * @template T
7
+ * @callback PromiseExecutor The promise executor
8
+ * @param {(value: import('./types.js').ERef<T>) => void} resolve
9
+ * @param {(reason: any) => void} reject
10
+ */
11
+
12
+ /**
13
+ * makeReleasingExecutorKit() builds resolve/reject functions which drop references
14
+ * to the resolve/reject functions gathered from an executor to be used with a
15
+ * promise constructor.
16
+ *
17
+ * @template T
18
+ * @returns {Pick<import('./types.js').PromiseKit<T>, 'resolve' | 'reject'> & { executor: PromiseExecutor<T>}}
19
+ */
20
+ export const makeReleasingExecutorKit = () => {
21
+ /** @type {null | undefined | ((value: import('./types.js').ERef<T>) => void)} */
22
+ let internalResolve;
23
+ /** @type {null | undefined | ((reason: unknown) => void)} */
24
+ let internalReject;
25
+
26
+ /** @param {import('./types.js').ERef<T>} value */
27
+ const resolve = value => {
28
+ if (internalResolve) {
29
+ internalResolve(value);
30
+ internalResolve = null;
31
+ internalReject = null;
32
+ } else {
33
+ assert(internalResolve === null);
34
+ }
35
+ };
36
+
37
+ /** @param {unknown} reason */
38
+ const reject = reason => {
39
+ if (internalReject) {
40
+ internalReject(reason);
41
+ internalResolve = null;
42
+ internalReject = null;
43
+ } else {
44
+ assert(internalReject === null);
45
+ }
46
+ };
47
+
48
+ const executor = (res, rej) => {
49
+ assert(internalResolve === undefined && internalReject === undefined);
50
+ internalResolve = res;
51
+ internalReject = rej;
52
+ };
53
+
54
+ return { resolve, reject, executor };
55
+ };
56
+ harden(makeReleasingExecutorKit);
package/src/types.js ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @template T
3
+ * @typedef {object} PromiseKit A reified Promise
4
+ * @property {(value: ERef<T>) => void} resolve
5
+ * @property {(reason: any) => void} reject
6
+ * @property {Promise<T>} promise
7
+ */
8
+
9
+ /**
10
+ * PromiseRecord is deprecated in favor of PromiseKit.
11
+ *
12
+ * @template T
13
+ * @typedef {PromiseKit<T>} PromiseRecord
14
+ */
15
+
16
+ /**
17
+ * @template T
18
+ * @typedef {T | PromiseLike<T>} ERef
19
+ * A reference of some kind for to an object of type T. It may be a direct
20
+ * reference to a local T. It may be a local presence for a remote T. It may
21
+ * be a promise for a local or remote T. Or it may even be a thenable
22
+ * (a promise-like non-promise with a "then" method) for a T.
23
+ */
24
+
25
+ export {};