async-browser-context 0.2.1 → 0.2.3

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 (42) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +4 -1
  3. package/dist/babel/async-generator-helpers.d.ts +17 -0
  4. package/dist/babel/async-generator-helpers.d.ts.map +1 -0
  5. package/dist/babel/async-generator-helpers.js +40 -0
  6. package/dist/babel/async-generator-helpers.js.map +1 -0
  7. package/dist/babel/bind-generators.d.ts.map +1 -1
  8. package/dist/babel/bind-generators.js +17 -5
  9. package/dist/babel/bind-generators.js.map +1 -1
  10. package/dist/babel/preset.d.ts +11 -6
  11. package/dist/babel/preset.d.ts.map +1 -1
  12. package/dist/babel/preset.js +15 -6
  13. package/dist/babel/preset.js.map +1 -1
  14. package/dist/babel/skip-runtime.d.ts +16 -0
  15. package/dist/babel/skip-runtime.d.ts.map +1 -0
  16. package/dist/babel/skip-runtime.js +29 -0
  17. package/dist/babel/skip-runtime.js.map +1 -0
  18. package/dist/core/async-generator.d.ts +36 -0
  19. package/dist/core/async-generator.d.ts.map +1 -0
  20. package/dist/core/async-generator.js +132 -0
  21. package/dist/core/async-generator.js.map +1 -0
  22. package/dist/core/coroutine.d.ts +13 -3
  23. package/dist/core/coroutine.d.ts.map +1 -1
  24. package/dist/core/coroutine.js +104 -35
  25. package/dist/core/coroutine.js.map +1 -1
  26. package/dist/node/runtime.d.ts +13 -2
  27. package/dist/node/runtime.d.ts.map +1 -1
  28. package/dist/node/runtime.js +45 -24
  29. package/dist/node/runtime.js.map +1 -1
  30. package/dist/runtime.d.ts +4 -2
  31. package/dist/runtime.d.ts.map +1 -1
  32. package/dist/runtime.js +4 -2
  33. package/dist/runtime.js.map +1 -1
  34. package/package.json +3 -2
  35. package/src/babel/async-generator-helpers.ts +49 -0
  36. package/src/babel/bind-generators.ts +17 -5
  37. package/src/babel/preset.ts +15 -6
  38. package/src/babel/skip-runtime.ts +32 -0
  39. package/src/core/async-generator.ts +159 -0
  40. package/src/core/coroutine.ts +107 -35
  41. package/src/node/runtime.ts +47 -23
  42. package/src/runtime.ts +4 -2
@@ -0,0 +1,159 @@
1
+ /**
2
+ * The async generators of transformed code. `@babel/plugin-transform-async-generator-functions`
3
+ * changes each async generator into a sync generator and its helper `wrapAsyncGenerator`.
4
+ * The helper continued each step in a `then` callback, and a `then` callback is slow in
5
+ * Firefox. The preset replaces the helper with `asyncGenerator` of the runtime, and the
6
+ * helper `OverloadYield` with the class of this module. The driver in this module then
7
+ * continues each step with a native `await`.
8
+ *
9
+ * The protocol is the protocol of the Babel 8 helper: the body gives
10
+ * `new OverloadYield(value, 0)` for an `await`, and `new OverloadYield(promise, 1)` for a
11
+ * step of `yield*`. Each other value is a `yield`.
12
+ */
13
+
14
+ /**
15
+ * The value that the body gives for an `await` (kind 0) or for a step of `yield*` (kind 1).
16
+ * The Babel helpers `awaitAsyncGenerator` and `asyncGeneratorDelegate` make it with `new`.
17
+ */
18
+ export class OverloadYield {
19
+ v : unknown;
20
+ readonly k : 0 | 1;
21
+ constructor(value : unknown, kind : 0 | 1) {
22
+ this.v = value;
23
+ this.k = kind;
24
+ }
25
+ }
26
+
27
+ /** The methods of a generator that a request of the consumer starts. */
28
+ export type ResumeKey = "next" | "throw" | "return";
29
+
30
+ /**
31
+ * This function does one step of the body: `generator[key](argument)`. The browser runtime sets
32
+ * the context of the generator around the step. `resumed` is `true` for a step after an
33
+ * `await` of the driver.
34
+ */
35
+ export type AsyncGeneratorStep = (key : ResumeKey, argument : unknown, resumed : boolean) => IteratorResult<unknown, unknown>;
36
+
37
+ interface Request {
38
+ readonly key : ResumeKey;
39
+ readonly argument : unknown;
40
+ readonly resolve : (result : IteratorResult<unknown, unknown>) => void;
41
+ readonly reject : (error : unknown) => void;
42
+ next : Request | undefined;
43
+ }
44
+
45
+ type Invoke = (key : ResumeKey, argument : unknown) => Promise<IteratorResult<unknown, unknown>>;
46
+
47
+ /** The key of the request function of each async generator object. */
48
+ const INVOKE : unique symbol = Symbol("async-browser-context/invoke");
49
+
50
+ function invokeOf(target : object) : Invoke {
51
+ const invoke = (target as { [INVOKE]? : Invoke })[INVOKE];
52
+ if (invoke === undefined) {
53
+ throw new TypeError("The object is not an async generator of async-browser-context");
54
+ }
55
+ return invoke;
56
+ }
57
+
58
+ /** The prototype of the async generator objects of transformed code. */
59
+ const AsyncGeneratorPrototype = {
60
+ next(this : object, value? : unknown) : Promise<IteratorResult<unknown, unknown>> {
61
+ return invokeOf(this)("next", value);
62
+ },
63
+ throw(this : object, error? : unknown) : Promise<IteratorResult<unknown, unknown>> {
64
+ return invokeOf(this)("throw", error);
65
+ },
66
+ return(this : object, value? : unknown) : Promise<IteratorResult<unknown, unknown>> {
67
+ return invokeOf(this)("return", value);
68
+ },
69
+ [Symbol.asyncIterator]<T>(this : T) : T {
70
+ return this;
71
+ },
72
+ [Symbol.toStringTag] : "AsyncGenerator",
73
+ };
74
+
75
+ /**
76
+ * This function makes an async generator object. The object queues the requests of the
77
+ * consumer, and starts one request at a time, as the Babel helper does. `enter` starts the
78
+ * driver: the Node.js runtime starts it in the context of the generator.
79
+ */
80
+ export function createAsyncGenerator(
81
+ step : AsyncGeneratorStep,
82
+ NativePromise : PromiseConstructor,
83
+ enter : (start : () => Promise<void>) => Promise<void> = (start) => start(),
84
+ ) : AsyncGenerator<unknown, unknown, unknown> {
85
+ let first : Request | undefined;
86
+ let last : Request | undefined;
87
+
88
+ /** This function starts the requests in the queue, one after the other, until the queue is empty. */
89
+ const run = async (key : ResumeKey, argument : unknown) : Promise<void> => {
90
+ // The directive tells the Babel preset not to change this function (src/babel/skip-runtime.ts)
91
+ "async-browser-context runtime";
92
+ let resumed = false;
93
+ for (;;) {
94
+ let failed = false;
95
+ let settled : unknown;
96
+ let done = false;
97
+ try {
98
+ let result = step(key, argument, resumed);
99
+ for (;;) {
100
+ const yielded : unknown = result.value;
101
+ const overloaded = yielded instanceof OverloadYield;
102
+ let value : unknown;
103
+ try {
104
+ value = await (overloaded ? yielded.v : yielded);
105
+ } catch (error) {
106
+ resumed = true;
107
+ key = "throw";
108
+ result = step("throw", error, true);
109
+ continue;
110
+ }
111
+ resumed = true;
112
+ if (overloaded) {
113
+ const nextKey : ResumeKey = key === "return" && yielded.k === 1 ? "return" : "next";
114
+ if (yielded.k === 0 || Boolean((value as { done? : unknown }).done)) {
115
+ key = nextKey;
116
+ result = step(nextKey, value, true);
117
+ continue;
118
+ }
119
+ value = step(nextKey, value, true).value;
120
+ }
121
+ settled = value;
122
+ done = result.done === true;
123
+ break;
124
+ }
125
+ } catch (error) {
126
+ failed = true;
127
+ settled = error;
128
+ }
129
+ // A request always waits in the queue while the driver runs
130
+ const request = first as Request;
131
+ first = request.next;
132
+ if (failed) {
133
+ request.reject(settled);
134
+ } else {
135
+ request.resolve({ value : settled, done });
136
+ }
137
+ if (first === undefined) {
138
+ last = undefined;
139
+ return;
140
+ }
141
+ key = first.key;
142
+ argument = first.argument;
143
+ }
144
+ };
145
+
146
+ const invoke : Invoke = (key, argument) => new NativePromise((resolve, reject) => {
147
+ const request : Request = { key, argument, resolve, reject, next : undefined };
148
+ if (last === undefined) {
149
+ first = last = request;
150
+ void enter(() => run(key, argument));
151
+ } else {
152
+ last = last.next = request;
153
+ }
154
+ });
155
+
156
+ const generator = Object.create(AsyncGeneratorPrototype) as AsyncGenerator<unknown, unknown, unknown>;
157
+ Object.defineProperty(generator, INVOKE, { value : invoke });
158
+ return generator;
159
+ }
@@ -1,3 +1,4 @@
1
+ import { createAsyncGenerator, OverloadYield } from "./async-generator.js";
1
2
  import { applyWithHooks, store, type Frame } from "./store.js";
2
3
 
3
4
  /**
@@ -32,46 +33,116 @@ export function coroutine<T, A extends unknown[], R>(
32
33
  generatorFunction : (this : T, ...args : A) => Generator<unknown, R, unknown>,
33
34
  name? : string,
34
35
  ) : (this : T, ...args : A) => Promise<R> {
35
- const { Promise : NativePromise, promiseThen, promiseResolve } = store.intrinsics;
36
+ const { promiseResolve } = store.intrinsics;
36
37
  return function asyncFunction(this : T, ...args : A) : Promise<R> {
37
38
  // The context of the call. The body can change it with AsyncLocalStorage.enterWith.
38
39
  let frame : Frame = store.current;
39
- const generator = generatorFunction.apply(this, args);
40
- return new NativePromise<R>((resolve, reject) => {
41
- /** `resumed` is `true` for a step after an `await`. Only these steps start the hook methods. */
42
- const step = (resume : (argument : unknown) => IteratorResult<unknown, R>, argument : unknown, resumed : boolean) : void => {
43
- const previous = store.current;
44
- store.current = frame;
45
- let result : IteratorResult<unknown, R>;
46
- let awaited : Promise<unknown>;
40
+ let generator : Generator<unknown, R, unknown>;
41
+ const next = (value : unknown) : IteratorResult<unknown, R> => generator.next(value);
42
+ const throwInto = (error : unknown) : IteratorResult<unknown, R> => generator.throw(error);
43
+
44
+ /**
45
+ * This function does one step of the body in the context of the async function, and sets
46
+ * the previous context again. `resumed` is `true` for a step after an `await`. Only these
47
+ * steps start the hook methods. The function gives the value to await.
48
+ */
49
+ const step = (resume : (argument : unknown) => IteratorResult<unknown, R>, argument : unknown, resumed : boolean) : IteratorResult<unknown, R> => {
50
+ const previous = store.current;
51
+ store.current = frame;
52
+ try {
53
+ const hooks = resumed ? store.hooks : undefined;
54
+ const result = hooks === undefined
55
+ ? resume(argument)
56
+ : applyWithHooks(hooks, namedForHooks(generatorFunction, name), "await", resume, undefined, [argument]);
57
+ const value : unknown = result.value;
58
+ if (!result.done && ((typeof value === "object" && value !== null) || typeof value === "function")) {
59
+ // Promise.resolve reads the "then" property of an object. Do it in the context of the body, as await does.
60
+ // The result object is new for each step, so the change is not visible to other code.
61
+ (result as { value : unknown }).value = promiseResolve(value);
62
+ }
63
+ return result;
64
+ } finally {
65
+ frame = store.current;
66
+ store.current = previous;
67
+ }
68
+ };
69
+
70
+ /**
71
+ * The driver is a native async function: its `await` is faster than a `then` callback,
72
+ * mostly in Firefox. Each `await` takes the same number of microtask turns as the
73
+ * `await` of the source. Between the steps, the context of the caller stays current.
74
+ */
75
+ const drive = async () : Promise<R> => {
76
+ // The directive tells the Babel preset not to change this function (src/babel/skip-runtime.ts)
77
+ "async-browser-context runtime";
78
+ // In the driver, an error of the parameters rejects the promise, as with a native async function
79
+ generator = generatorFunction.apply(this, args);
80
+ let result = step(next, undefined, false);
81
+ while (result.done !== true) {
82
+ let value : unknown;
47
83
  try {
48
- const hooks = resumed ? store.hooks : undefined;
49
- result = hooks === undefined
50
- ? resume(argument)
51
- : applyWithHooks(hooks, namedForHooks(generatorFunction, name), "await", resume, undefined, [argument]);
52
- if (result.done) {
53
- frame = store.current;
54
- store.current = previous;
55
- resolve(result.value);
56
- return;
57
- }
58
- // Promise.resolve reads a "then" property of the value. Do it in the context of the body, as await does.
59
- awaited = promiseResolve(result.value);
84
+ value = await result.value;
60
85
  } catch (error) {
61
- store.current = previous;
62
- reject(error);
63
- return;
86
+ result = step(throwInto, error, true);
87
+ continue;
88
+ }
89
+ result = step(next, value, true);
90
+ }
91
+ return result.value;
92
+ };
93
+ return drive();
94
+ };
95
+ }
96
+
97
+ /** This function gives `true` for a value that can have a `then` property: an object or a function. */
98
+ function isObject(value : unknown) : value is object {
99
+ return (typeof value === "object" && value !== null) || typeof value === "function";
100
+ }
101
+
102
+ /**
103
+ * This function gives a function that makes an async generator object, which operates
104
+ * `generatorFunction`. The preset gives this function in place of the helper
105
+ * `wrapAsyncGenerator` of `@babel/plugin-transform-async-generator-functions`.
106
+ *
107
+ * Each step of the body operates in the context of the call that made the generator
108
+ * (rule C5). The driver continues each step with a native `await` (`async-generator.ts`).
109
+ */
110
+ export function asyncGenerator<T, A extends unknown[]>(
111
+ generatorFunction : (this : T, ...args : A) => Generator<unknown, unknown, unknown>,
112
+ ) : (this : T, ...args : A) => AsyncGenerator<unknown, unknown, unknown> {
113
+ const { Promise : NativePromise, promiseResolve } = store.intrinsics;
114
+ return function makeAsyncGenerator(this : T, ...args : A) : AsyncGenerator<unknown, unknown, unknown> {
115
+ let frame : Frame = store.current;
116
+ const generator = generatorFunction.apply(this, args);
117
+ const methods : Record<ResumeMethod, (argument : unknown) => IteratorResult<unknown, unknown>> = {
118
+ next : (argument) => generator.next(argument),
119
+ throw : (argument) => generator.throw(argument),
120
+ return : (argument) => generator.return(argument),
121
+ };
122
+ const step = (key : ResumeMethod, argument : unknown, resumed : boolean) : IteratorResult<unknown, unknown> => {
123
+ const previous = store.current;
124
+ store.current = frame;
125
+ try {
126
+ const hooks = resumed ? store.hooks : undefined;
127
+ const result = hooks === undefined
128
+ ? methods[key](argument)
129
+ : applyWithHooks(hooks, generatorFunction, "await", methods[key], undefined, [argument]);
130
+ // Read the "then" property of an awaited or yielded object in the context of the body, as await and yield do
131
+ const value : unknown = result.value;
132
+ if (value instanceof OverloadYield) {
133
+ if (isObject(value.v)) {
134
+ value.v = promiseResolve(value.v);
135
+ }
136
+ } else if (isObject(value)) {
137
+ (result as { value : unknown }).value = promiseResolve(value);
64
138
  }
139
+ return result;
140
+ } finally {
65
141
  frame = store.current;
66
142
  store.current = previous;
67
- promiseThen.call(awaited, onFulfilled, onRejected);
68
- };
69
- const next = (value : unknown) : IteratorResult<unknown, R> => generator.next(value);
70
- const throwInto = (error : unknown) : IteratorResult<unknown, R> => generator.throw(error);
71
- const onFulfilled = (value : unknown) : void => step(next, value, true);
72
- const onRejected = (error : unknown) : void => step(throwInto, error, true);
73
- step(next, undefined, false);
74
- });
143
+ }
144
+ };
145
+ return createAsyncGenerator(step, NativePromise);
75
146
  };
76
147
  }
77
148
 
@@ -84,9 +155,10 @@ type ResumeMethod = "next" | "throw" | "return";
84
155
  * proposal specifies (`GeneratorStart` and `GeneratorResume`). After each step,
85
156
  * the context of the caller is current again.
86
157
  *
87
- * The preset changes each generator function so that it gives
88
- * `bindGenerator(generator)`. The function works with sync generators and
89
- * with the async generators of `@babel/plugin-transform-async-generator-functions`.
158
+ * The preset changes each sync generator function so that it gives
159
+ * `bindGenerator(generator)`. An async generator does not need it, because
160
+ * `asyncGenerator` keeps the context itself. The function also works with
161
+ * async generator objects, for example in the output of older versions.
90
162
  */
91
163
  export function bindGenerator<I extends AnyIterator>(generator : I) : I {
92
164
  let frame : Frame = store.current;
@@ -7,32 +7,56 @@
7
7
  * @packageDocumentation
8
8
  */
9
9
  import { AsyncLocalStorage } from "node:async_hooks";
10
+ import { createAsyncGenerator, type ResumeKey } from "../core/async-generator.js";
10
11
 
11
- /** This function gives an async function that operates `generatorFunction`. */
12
+ export { OverloadYield } from "../core/async-generator.js";
13
+
14
+ /**
15
+ * This function gives an async function that operates `generatorFunction`. The function is
16
+ * a native async function: each `await` of the source becomes one native `await`, with
17
+ * the same microtask turns. An error of the parameters rejects the promise.
18
+ */
12
19
  export function coroutine<T, A extends unknown[], R>(generatorFunction : (this : T, ...args : A) => Generator<unknown, R, unknown>) : (this : T, ...args : A) => Promise<R> {
13
- return function asyncFunction(this : T, ...args : A) : Promise<R> {
20
+ return async function asyncFunction(this : T, ...args : A) : Promise<R> {
21
+ // The directive tells the Babel preset not to change this function (src/babel/skip-runtime.ts)
22
+ "async-browser-context runtime";
23
+ const generator = generatorFunction.apply(this, args);
24
+ let result = generator.next();
25
+ while (result.done !== true) {
26
+ let value : unknown;
27
+ try {
28
+ value = await result.value;
29
+ } catch (error) {
30
+ result = generator.throw(error);
31
+ continue;
32
+ }
33
+ result = generator.next(value);
34
+ }
35
+ return result.value;
36
+ };
37
+ }
38
+
39
+ /**
40
+ * This function gives a function that makes an async generator object, which operates
41
+ * `generatorFunction`. The preset gives it in place of the helper `wrapAsyncGenerator` of
42
+ * Babel. The driver starts in a snapshot of the context of the creation (rule C5). The
43
+ * native `AsyncLocalStorage` keeps that context through the `await` of the driver.
44
+ */
45
+ export function asyncGenerator<T, A extends unknown[]>(
46
+ generatorFunction : (this : T, ...args : A) => Generator<unknown, unknown, unknown>,
47
+ ) : (this : T, ...args : A) => AsyncGenerator<unknown, unknown, unknown> {
48
+ return function makeAsyncGenerator(this : T, ...args : A) : AsyncGenerator<unknown, unknown, unknown> {
49
+ let snapshot = AsyncLocalStorage.snapshot();
14
50
  const generator = generatorFunction.apply(this, args);
15
- return new Promise<R>((resolve, reject) => {
16
- const step = (method : "next" | "throw", argument : unknown) : void => {
17
- let result : IteratorResult<unknown, R>;
18
- let awaited : Promise<unknown>;
19
- try {
20
- result = method === "next" ? generator.next(argument) : generator.throw(argument);
21
- if (result.done) {
22
- resolve(result.value);
23
- return;
24
- }
25
- awaited = Promise.resolve(result.value);
26
- } catch (error) {
27
- reject(error);
28
- return;
29
- }
30
- awaited.then(onFulfilled, onRejected);
31
- };
32
- const onFulfilled = (value : unknown) : void => step("next", value);
33
- const onRejected = (error : unknown) : void => step("throw", error);
34
- step("next", undefined);
35
- });
51
+ const step = (key : ResumeKey, argument : unknown) : IteratorResult<unknown, unknown> => {
52
+ try {
53
+ return generator[key](argument);
54
+ } finally {
55
+ // The body can change its context with enterWith before it stops
56
+ snapshot = AsyncLocalStorage.snapshot();
57
+ }
58
+ };
59
+ return createAsyncGenerator(step, Promise, (start) => snapshot(start));
36
60
  };
37
61
  }
38
62
 
package/src/runtime.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  /**
2
2
  * The runtime of the code that the Babel preset transforms. The transformed
3
- * code imports `coroutine` and `bindGenerator` from this module. When the
3
+ * code imports `coroutine`, `bindGenerator`, `asyncGenerator` and
4
+ * `OverloadYield` from this module. When the
4
5
  * module loads, it installs the patches of the runtime.
5
6
  *
6
7
  * @packageDocumentation
7
8
  */
8
9
  import "./install.js";
9
10
 
10
- export { bindGenerator, coroutine } from "./core/coroutine.js";
11
+ export { OverloadYield } from "./core/async-generator.js";
12
+ export { asyncGenerator, bindGenerator, coroutine } from "./core/coroutine.js";