async-browser-context 0.2.4 → 0.3.0

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 (140) hide show
  1. package/CHANGELOG.md +88 -0
  2. package/README.md +45 -30
  3. package/dist/babel/async-generator-helpers.d.ts +6 -6
  4. package/dist/babel/async-generator-helpers.d.ts.map +1 -1
  5. package/dist/babel/async-generator-helpers.js +33 -22
  6. package/dist/babel/async-generator-helpers.js.map +1 -1
  7. package/dist/babel/async-generator-resources.d.ts +14 -0
  8. package/dist/babel/async-generator-resources.d.ts.map +1 -0
  9. package/dist/babel/async-generator-resources.js +38 -0
  10. package/dist/babel/async-generator-resources.js.map +1 -0
  11. package/dist/babel/bind-generators.d.ts +1 -1
  12. package/dist/babel/bind-generators.d.ts.map +1 -1
  13. package/dist/babel/bind-generators.js +88 -44
  14. package/dist/babel/bind-generators.js.map +1 -1
  15. package/dist/babel/name-coroutines.d.ts +14 -8
  16. package/dist/babel/name-coroutines.d.ts.map +1 -1
  17. package/dist/babel/name-coroutines.js +160 -39
  18. package/dist/babel/name-coroutines.js.map +1 -1
  19. package/dist/babel/preset.d.ts +24 -13
  20. package/dist/babel/preset.d.ts.map +1 -1
  21. package/dist/babel/preset.js +37 -9
  22. package/dist/babel/preset.js.map +1 -1
  23. package/dist/babel/runtime-calls.d.ts +22 -0
  24. package/dist/babel/runtime-calls.d.ts.map +1 -0
  25. package/dist/babel/runtime-calls.js +69 -0
  26. package/dist/babel/runtime-calls.js.map +1 -0
  27. package/dist/babel/skip-runtime.d.ts +18 -11
  28. package/dist/babel/skip-runtime.d.ts.map +1 -1
  29. package/dist/babel/skip-runtime.js +52 -16
  30. package/dist/babel/skip-runtime.js.map +1 -1
  31. package/dist/babel/static-members.d.ts +4 -0
  32. package/dist/babel/static-members.d.ts.map +1 -0
  33. package/dist/babel/static-members.js +112 -0
  34. package/dist/babel/static-members.js.map +1 -0
  35. package/dist/core/async-generator.d.ts +26 -8
  36. package/dist/core/async-generator.d.ts.map +1 -1
  37. package/dist/core/async-generator.js +162 -44
  38. package/dist/core/async-generator.js.map +1 -1
  39. package/dist/core/async-local-storage.d.ts +3 -0
  40. package/dist/core/async-local-storage.d.ts.map +1 -1
  41. package/dist/core/async-local-storage.js +3 -0
  42. package/dist/core/async-local-storage.js.map +1 -1
  43. package/dist/core/callback-hook.d.ts +3 -3
  44. package/dist/core/coroutine.d.ts +6 -2
  45. package/dist/core/coroutine.d.ts.map +1 -1
  46. package/dist/core/coroutine.js +35 -21
  47. package/dist/core/coroutine.js.map +1 -1
  48. package/dist/core/function-name.d.ts +9 -0
  49. package/dist/core/function-name.d.ts.map +1 -0
  50. package/dist/core/function-name.js +12 -0
  51. package/dist/core/function-name.js.map +1 -0
  52. package/dist/core/hooks.d.ts +2 -1
  53. package/dist/core/hooks.d.ts.map +1 -1
  54. package/dist/core/hooks.js +21 -6
  55. package/dist/core/hooks.js.map +1 -1
  56. package/dist/core/snapshot.d.ts +2 -1
  57. package/dist/core/snapshot.d.ts.map +1 -1
  58. package/dist/core/snapshot.js +7 -3
  59. package/dist/core/snapshot.js.map +1 -1
  60. package/dist/core/store.d.ts +28 -0
  61. package/dist/core/store.d.ts.map +1 -1
  62. package/dist/core/store.js +90 -20
  63. package/dist/core/store.js.map +1 -1
  64. package/dist/core/variable.d.ts +2 -1
  65. package/dist/core/variable.d.ts.map +1 -1
  66. package/dist/core/variable.js +5 -2
  67. package/dist/core/variable.js.map +1 -1
  68. package/dist/node/index.d.ts +10 -4
  69. package/dist/node/index.d.ts.map +1 -1
  70. package/dist/node/index.js +51 -16
  71. package/dist/node/index.js.map +1 -1
  72. package/dist/node/runtime.d.ts +7 -6
  73. package/dist/node/runtime.d.ts.map +1 -1
  74. package/dist/node/runtime.js +29 -16
  75. package/dist/node/runtime.js.map +1 -1
  76. package/dist/opentelemetry/context-manager.d.ts.map +1 -1
  77. package/dist/opentelemetry/context-manager.js +172 -13
  78. package/dist/opentelemetry/context-manager.js.map +1 -1
  79. package/dist/patches/callbacks.d.ts.map +1 -1
  80. package/dist/patches/callbacks.js +84 -29
  81. package/dist/patches/callbacks.js.map +1 -1
  82. package/dist/patches/events.d.ts.map +1 -1
  83. package/dist/patches/events.js +203 -91
  84. package/dist/patches/events.js.map +1 -1
  85. package/dist/patches/handler-interfaces.d.ts +3 -2
  86. package/dist/patches/handler-interfaces.d.ts.map +1 -1
  87. package/dist/patches/handler-interfaces.js +3 -2
  88. package/dist/patches/handler-interfaces.js.map +1 -1
  89. package/dist/patches/promise.d.ts +3 -0
  90. package/dist/patches/promise.d.ts.map +1 -1
  91. package/dist/patches/promise.js +13 -5
  92. package/dist/patches/promise.js.map +1 -1
  93. package/dist/patches/streams.d.ts.map +1 -1
  94. package/dist/patches/streams.js +36 -16
  95. package/dist/patches/streams.js.map +1 -1
  96. package/dist/patches/timers.d.ts.map +1 -1
  97. package/dist/patches/timers.js +17 -5
  98. package/dist/patches/timers.js.map +1 -1
  99. package/dist/patches/to-string.d.ts +4 -0
  100. package/dist/patches/to-string.d.ts.map +1 -1
  101. package/dist/patches/to-string.js +12 -6
  102. package/dist/patches/to-string.js.map +1 -1
  103. package/dist/runtime.d.ts +3 -3
  104. package/dist/runtime.d.ts.map +1 -1
  105. package/dist/runtime.js +3 -3
  106. package/dist/runtime.js.map +1 -1
  107. package/dist/vite/plugin.d.ts +7 -2
  108. package/dist/vite/plugin.d.ts.map +1 -1
  109. package/dist/vite/plugin.js +30 -6
  110. package/dist/vite/plugin.js.map +1 -1
  111. package/package.json +49 -25
  112. package/src/babel/async-generator-helpers.ts +34 -23
  113. package/src/babel/async-generator-resources.ts +40 -0
  114. package/src/babel/bind-generators.ts +91 -47
  115. package/src/babel/name-coroutines.ts +170 -41
  116. package/src/babel/preset.ts +47 -15
  117. package/src/babel/runtime-calls.ts +73 -0
  118. package/src/babel/skip-runtime.ts +58 -18
  119. package/src/babel/static-members.ts +117 -0
  120. package/src/core/async-generator.ts +169 -46
  121. package/src/core/async-local-storage.ts +3 -0
  122. package/src/core/callback-hook.ts +3 -3
  123. package/src/core/coroutine.ts +35 -21
  124. package/src/core/function-name.ts +11 -0
  125. package/src/core/hooks.ts +23 -6
  126. package/src/core/snapshot.ts +8 -3
  127. package/src/core/store.ts +107 -21
  128. package/src/core/variable.ts +6 -2
  129. package/src/node/index.ts +62 -19
  130. package/src/node/runtime.ts +33 -15
  131. package/src/opentelemetry/context-manager.ts +188 -13
  132. package/src/patches/callbacks.ts +87 -30
  133. package/src/patches/events.ts +249 -103
  134. package/src/patches/handler-interfaces.ts +3 -2
  135. package/src/patches/promise.ts +17 -13
  136. package/src/patches/streams.ts +36 -16
  137. package/src/patches/timers.ts +17 -5
  138. package/src/patches/to-string.ts +12 -6
  139. package/src/runtime.ts +3 -3
  140. package/src/vite/plugin.ts +38 -8
@@ -0,0 +1,73 @@
1
+ import { types, type NodePath } from "@babel/core";
2
+
3
+ /**
4
+ * The directive that marks a native async function of the runtime. If the
5
+ * preset changes that function, the function uses `coroutine` to operate
6
+ * `coroutine`, without end. A directive stays in the code after TypeScript,
7
+ * esbuild (also in the dependency bundles of the Vite dev server), Rollup and
8
+ * webpack, but a comment does not.
9
+ */
10
+ export const RUNTIME_DIRECTIVE = "async-browser-context runtime";
11
+
12
+ /** This function gives `true` if `node` is a function with the directive of the runtime. */
13
+ export function isRuntimeFunction(node : types.Node) : boolean {
14
+ return types.isFunction(node)
15
+ && node.body.type === "BlockStatement"
16
+ && node.body.directives.some((directive) => directive.value.value === RUNTIME_DIRECTIVE);
17
+ }
18
+
19
+ /**
20
+ * This function gives `true` if `node` is `require(runtime)`, also inside at most three helper calls or members,
21
+ * for example `_interopRequireWildcard(require(runtime))`. It gives `false` for `null` and `undefined`.
22
+ */
23
+ function containsRequireOf(node : types.Node | null | undefined, runtime : string, depth = 0) : boolean {
24
+ if (depth > 3) {
25
+ return false;
26
+ }
27
+ if (types.isCallExpression(node)) {
28
+ if (types.isIdentifier(node.callee, { name : "require" }) && types.isStringLiteral(node.arguments[0], { value : runtime })) {
29
+ return true;
30
+ }
31
+ return node.arguments.some((argument) => containsRequireOf(argument as types.Node, runtime, depth + 1));
32
+ }
33
+ // Stryker disable next-line ConditionalExpression: of the other nodes, only an optional member has an object, and the tools do not give one here
34
+ return types.isMemberExpression(node) && containsRequireOf(node.object, runtime, depth + 1);
35
+ }
36
+
37
+ /** This function gives the initial value of the variable that `identifier` names, if a variable declaration gives it. */
38
+ function initOf(identifier : NodePath<types.Identifier>) : types.Node | null | undefined {
39
+ const binding = identifier.scope.getBinding(identifier.node.name);
40
+ return binding?.path.isVariableDeclarator() === true ? (binding.path.node as types.VariableDeclarator).init : undefined;
41
+ }
42
+
43
+ /**
44
+ * This function gives `true` if `callee` is the function `name` of the runtime. It accepts the
45
+ * forms of the output of the preset:
46
+ *
47
+ * - an import: `_coroutine` from `import { coroutine as _coroutine } from runtime`
48
+ * - CommonJS: `_runtime.coroutine` or `(0, _runtime.coroutine)` with `_runtime = require(runtime)`
49
+ * - CommonJS of a script: `_coroutine` with `var _coroutine = require(runtime).coroutine`
50
+ * - the local name that Babel gives, `_coroutine` and `_coroutine2`, for the output of another tool.
51
+ */
52
+ export function isRuntimeCallee(callee : NodePath, runtime : string, name : string) : boolean {
53
+ let target : NodePath = callee;
54
+ if (target.isSequenceExpression()) {
55
+ const expressions = target.get("expressions");
56
+ target = expressions[expressions.length - 1] as NodePath;
57
+ }
58
+ if (target.isIdentifier()) {
59
+ if (target.referencesImport(runtime, name)) {
60
+ return true;
61
+ }
62
+ const init = initOf(target);
63
+ if (types.isMemberExpression(init) && types.isIdentifier(init.property, { name }) && containsRequireOf(init.object, runtime)) {
64
+ return true;
65
+ }
66
+ return new RegExp(`^_${name}\\d*$`).test(target.node.name);
67
+ }
68
+ if (target.isMemberExpression() && !target.node.computed && types.isIdentifier(target.node.property, { name })) {
69
+ const object = target.get("object");
70
+ return object.isIdentifier() ? containsRequireOf(initOf(object), runtime) : containsRequireOf(object.node, runtime);
71
+ }
72
+ return false;
73
+ }
@@ -1,32 +1,72 @@
1
- import type { NodePath, PluginObject, PluginPass, types } from "@babel/core";
1
+ import type { NodePath, PluginAPI, PluginObject, PluginPass, types, Visitor } from "@babel/core";
2
+ import { isRuntimeFunction } from "./runtime-calls.js";
3
+
4
+ export { RUNTIME_DIRECTIVE } from "./runtime-calls.js";
5
+
6
+ /** This function skips a function with the directive of the runtime. */
7
+ function skipRuntimeFunction(functionPath : NodePath<types.Function>) : void {
8
+ if (isRuntimeFunction(functionPath.node)) {
9
+ functionPath.skip();
10
+ }
11
+ }
2
12
 
3
13
  /**
4
- * The directive that marks a native async function of the runtime. If the
5
- * preset changes that function, the function uses `coroutine` to operate
6
- * `coroutine`, without end. A directive stays in the code after TypeScript,
7
- * esbuild (also in the dependency bundles of the Vite dev server), Rollup and
8
- * webpack, but a comment does not.
14
+ * This function gives a new visitor that skips each function with the directive of the runtime.
15
+ * Babel changes a visitor object when it prepares it (explode). Thus each use gets its own object,
16
+ * and two copies of Babel in one process do not share it.
9
17
  */
10
- export const RUNTIME_DIRECTIVE = "async-browser-context runtime";
11
-
12
- function isRuntimeFunction(node : types.Function) : boolean {
13
- return node.body.type === "BlockStatement" && node.body.directives.some((directive) => directive.value.value === RUNTIME_DIRECTIVE);
18
+ function skipRuntimeVisitor() : Visitor<PluginPass> {
19
+ return { Function : skipRuntimeFunction };
14
20
  }
15
21
 
16
22
  /**
17
- * The first plugin of the preset. It skips each function with the directive,
18
- * so that no other plugin of the preset changes it. Bundlers that apply the
19
- * preset to `node_modules` thus do not change the runtime.
23
+ * The first plugin of the preset. It skips each function with the directive of the runtime
24
+ * (runtime-calls.ts), so that the plugins of the main traversal do not change it. The plugins
25
+ * of the preset with their own traversal also skip it (refer to `withRuntimeSkipped`). Bundlers that
26
+ * apply the preset to `node_modules` thus do not change the runtime.
20
27
  */
21
28
  export function skipRuntimePlugin() : PluginObject<PluginPass> {
22
29
  return {
23
30
  name : "async-browser-context/skip-runtime",
24
- visitor : {
25
- Function(functionPath : NodePath<types.Function>) {
26
- if (isRuntimeFunction(functionPath.node)) {
27
- functionPath.skip();
31
+ visitor : skipRuntimeVisitor(),
32
+ };
33
+ }
34
+
35
+ /** A Babel plugin: a function that gets the API of Babel, the options and the folder. */
36
+ export type PluginFactory = (api : PluginAPI, options : object, dirname : string) => PluginObject<PluginPass>;
37
+
38
+ /**
39
+ * The plugin of Babel for async generators changes the async generators and the `for await`
40
+ * loops in its own traversal. It starts that traversal in its `Program` visitor. The skip of the main
41
+ * traversal does not apply to that traversal. This function gives a plugin that operates as
42
+ * `factory`. But it puts the visitor of `skipRuntimePlugin` in front of each traversal that the `Program` visitor
43
+ * starts.
44
+ *
45
+ * The function uses the traversal of the Babel that loads the plugin (`api.traverse`).
46
+ * If the plugin has no `Program` function, it stays as it is.
47
+ */
48
+ export function withRuntimeSkipped(factory : PluginFactory) : PluginFactory {
49
+ return function runtimeSkipped(api, options, dirname) {
50
+ const plugin = factory(api, options, dirname);
51
+ const program = plugin.visitor?.Program;
52
+ if (typeof program !== "function") {
53
+ return plugin;
54
+ }
55
+ const visitor = {
56
+ ...plugin.visitor,
57
+ Program(this : PluginPass, path : NodePath<types.Program>, state : PluginPass) : void {
58
+ const ownTraverse = path.traverse;
59
+ // An own property of this path object hides the method of the prototype during the visitor
60
+ path.traverse = function (this : NodePath, inner : Visitor<unknown>, innerState? : unknown) : void {
61
+ Reflect.apply(ownTraverse, this, [api.traverse.visitors.merge([skipRuntimeVisitor() as Visitor<unknown>, inner]), innerState]);
62
+ } as typeof path.traverse;
63
+ try {
64
+ Reflect.apply(program, this, [path, state]);
65
+ } finally {
66
+ delete (path as { traverse? : unknown }).traverse;
28
67
  }
29
68
  },
30
- },
69
+ } as Visitor<PluginPass>;
70
+ return { ...plugin, visitor };
31
71
  };
32
72
  }
@@ -0,0 +1,117 @@
1
+ import { types, type NodePath, type PluginObject, type PluginPass } from "@babel/core";
2
+ import { keyName } from "./name-coroutines.js";
3
+
4
+ /**
5
+ * `@babel/plugin-transform-async-to-generator` keeps `this` and `super` of an async arrow
6
+ * function in the nearest function or non-static class property. It does not stop at a static
7
+ * class property or a static block. Thus, in
8
+ *
9
+ * ```js
10
+ * class A { static load = async () => { await null; return this; }; }
11
+ * ```
12
+ *
13
+ * the transform gives `var _this = this` at the top of the module, and `A.load()` gives
14
+ * `undefined`. With `super`, the output is a SyntaxError. The plain async transform of Babel
15
+ * changes such code only when it also changes the class fields. This preset changes async
16
+ * functions in modern code, so it must change the class first.
17
+ *
18
+ * This plugin moves such an initializer or static block into a static private method, which has
19
+ * the same `this` and `super`:
20
+ *
21
+ * ```js
22
+ * class A { static load = this.#asyncContext1(); static #asyncContext1() { return { "load": async () => {...} }["load"]; } }
23
+ * ```
24
+ *
25
+ * The object property keeps the name of the function (`A.load.name` is "load").
26
+ */
27
+
28
+ /**
29
+ * This function gives `true` if `element` is or contains an async arrow function whose `this` is the `this` of the class element.
30
+ * It gives `false` for a path without a node, for example the value of `static x;`.
31
+ */
32
+ function hasAsyncArrowOfElement(element : NodePath) : boolean {
33
+ if (element.isArrowFunctionExpression() && element.node.async) {
34
+ return true;
35
+ }
36
+ let found = false;
37
+ element.traverse({
38
+ Function(path) {
39
+ if (!path.isArrowFunctionExpression()) {
40
+ // A function that is not an arrow function has its own this
41
+ path.skip();
42
+ return;
43
+ }
44
+ if (path.node.async) {
45
+ found = true;
46
+ // Stryker disable next-line CallExpression: the stop only ends the search early, and the result stays the same
47
+ path.stop();
48
+ }
49
+ },
50
+ Class(path) {
51
+ path.skip();
52
+ },
53
+ });
54
+ return found;
55
+ }
56
+
57
+ /** This function gives the name of a static class element for NamedEvaluation, or `undefined` for a computed key that is not a literal. */
58
+ function staticName(node : types.ClassProperty | types.ClassPrivateProperty | types.ClassAccessorProperty) : string | undefined {
59
+ // A private property has no computed field
60
+ return keyName(node.key, (node as { computed? : boolean }).computed === true);
61
+ }
62
+
63
+ /** This function gives a private name that the class does not use. */
64
+ function uniquePrivateName(body : types.ClassBody) : types.PrivateName {
65
+ const used = new Set<string>();
66
+ for (const member of body.body) {
67
+ if ("key" in member && types.isPrivateName(member.key)) {
68
+ used.add(member.key.id.name);
69
+ }
70
+ }
71
+ let index = 1;
72
+ while (used.has(`asyncContext${index}`)) {
73
+ index++;
74
+ }
75
+ return types.privateName(types.identifier(`asyncContext${index}`));
76
+ }
77
+
78
+ /** This function adds a static private method with `statements` to the class, and gives `this.#method()`. */
79
+ function addStaticMethod(body : NodePath<types.ClassBody>, statements : types.Statement[]) : types.CallExpression {
80
+ const name = uniquePrivateName(body.node);
81
+ body.pushContainer("body", types.classPrivateMethod("method", name, [], types.blockStatement(statements), true));
82
+ return types.callExpression(types.memberExpression(types.thisExpression(), types.cloneNode(name)), []);
83
+ }
84
+
85
+ /** The Babel plugin that moves static class members with async arrow functions into static private methods. */
86
+ export function staticMembersPlugin() : PluginObject<PluginPass> {
87
+ return {
88
+ name : "async-browser-context/static-members",
89
+ visitor : {
90
+ Program(programPath) {
91
+ programPath.traverse({
92
+ "ClassProperty|ClassPrivateProperty|ClassAccessorProperty"(path : NodePath<types.ClassProperty | types.ClassPrivateProperty | types.ClassAccessorProperty>) {
93
+ const node = path.node;
94
+ if (node.static !== true || !hasAsyncArrowOfElement(path.get("value") as NodePath)) {
95
+ return;
96
+ }
97
+ // A field without a value has no async arrow function
98
+ const value = node.value as types.Expression;
99
+ const name = staticName(node);
100
+ // An object property keeps the name of an anonymous function, as the static property did
101
+ const expression = name === undefined
102
+ ? value
103
+ : types.memberExpression(types.objectExpression([types.objectProperty(types.stringLiteral(name), value)]), types.stringLiteral(name), true);
104
+ node.value = addStaticMethod(path.parentPath as NodePath<types.ClassBody>, [types.returnStatement(expression)]);
105
+ },
106
+ StaticBlock(path) {
107
+ if (!hasAsyncArrowOfElement(path)) {
108
+ return;
109
+ }
110
+ const call = addStaticMethod(path.parentPath as NodePath<types.ClassBody>, path.node.body);
111
+ path.node.body = [types.expressionStatement(call)];
112
+ },
113
+ });
114
+ },
115
+ },
116
+ };
117
+ }
@@ -2,33 +2,115 @@
2
2
  * The async generators of transformed code. `@babel/plugin-transform-async-generator-functions`
3
3
  * changes each async generator into a sync generator and its helper `wrapAsyncGenerator`.
4
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`.
5
+ * Firefox. The preset replaces the helper with `asyncGenerator` of the runtime. It also takes
6
+ * the helpers `OverloadYield`, `awaitAsyncGenerator` and `asyncGeneratorDelegate` from this
7
+ * module. The driver in this module then continues each step with a native `await`.
8
8
  *
9
9
  * The protocol is the protocol of the Babel 8 helper: the body gives
10
10
  * `new OverloadYield(value, 0)` for an `await`, and `new OverloadYield(promise, 1)` for a
11
11
  * step of `yield*`. Each other value is a `yield`. Where the helper differs from a native async
12
12
  * generator, the driver does as the native generator. Thus `return()` at a `yield` awaits its
13
- * value first, and a request on a complete generator settles at once.
13
+ * value first, and a request on a complete generator settles at once. The delegate of this
14
+ * module also gives kind 2 for a step of `yield*` after `return()`.
14
15
  */
15
16
 
16
17
  /** The Promise of the time when the module loads, for the rejections of the methods. */
17
18
  const NativePromise : PromiseConstructor = Promise;
18
19
 
19
20
  /**
20
- * The value that the body gives for an `await` (kind 0) or for a step of `yield*` (kind 1).
21
- * The Babel helpers `awaitAsyncGenerator` and `asyncGeneratorDelegate` make it with `new`.
21
+ * The value that the body gives for an `await` (kind 0), for a step of `yield*` (kind 1), or
22
+ * for a step of `yield*` after `return()` (kind 2). The helpers `awaitAsyncGenerator` and
23
+ * `asyncGeneratorDelegate` make it with `new`.
22
24
  */
23
25
  export class OverloadYield {
24
26
  readonly v : unknown;
25
- readonly k : 0 | 1;
26
- constructor(value : unknown, kind : 0 | 1) {
27
+ readonly k : 0 | 1 | 2;
28
+ constructor(value : unknown, kind : 0 | 1 | 2) {
27
29
  this.v = value;
28
30
  this.k = kind;
29
31
  }
30
32
  }
31
33
 
34
+ /**
35
+ * The error of a step of `yield*` that was rejected. The driver gives it back to the delegate,
36
+ * and the delegate throws the error. Thus the error goes into the body at the `yield*`, also
37
+ * when the delegate has no `throw` method.
38
+ */
39
+ class DelegateRejection {
40
+ readonly error : unknown;
41
+ constructor(error : unknown) {
42
+ this.error = error;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * The helper `awaitAsyncGenerator` of Babel: the body gives its value for an `await`. The preset
48
+ * gives this function in place of the helper of Babel. Thus the marker is always the class of this
49
+ * module, also when `@babel/plugin-transform-runtime` gives the other helpers.
50
+ */
51
+ export function awaitAsyncGenerator(value : unknown) : OverloadYield {
52
+ return new OverloadYield(value, 0);
53
+ }
54
+
55
+ /**
56
+ * The helper `asyncGeneratorDelegate` of Babel 8: a sync iterator for `yield*` in an async
57
+ * generator. Each step of the inner async iterator becomes `new OverloadYield(promise, 1)`, or
58
+ * kind 2 after `return()`. The driver awaits the promise, and gives a copy of its result back to
59
+ * the iterator. After kind 2, the driver gives it back with `return()`. Thus a complete inner
60
+ * iterator ends the body, as with a native `yield*`.
61
+ */
62
+ export function asyncGeneratorDelegate(inner : AsyncIterator<unknown, unknown, unknown>) : Iterator<unknown, unknown, unknown> {
63
+ const iterator = inner as unknown as Record<ResumeKey, ((value : unknown) => unknown) | undefined>;
64
+ let waiting = false;
65
+ const pump = (key : ResumeKey, value : unknown) : IteratorResult<unknown, unknown> => {
66
+ waiting = true;
67
+ const promise = new NativePromise((resolve) => {
68
+ resolve(Reflect.apply(iterator[key] as (value : unknown) => unknown, inner, [value]));
69
+ });
70
+ return { done : false, value : new OverloadYield(promise, key === "return" ? 2 : 1) };
71
+ };
72
+ const delegate : Record<PropertyKey, unknown> = {
73
+ [Symbol.iterator]() { return this; },
74
+ next(value : unknown) : unknown {
75
+ if (!waiting) {
76
+ return pump("next", value);
77
+ }
78
+ waiting = false;
79
+ if (value instanceof DelegateRejection) {
80
+ throw value.error;
81
+ }
82
+ return value;
83
+ },
84
+ };
85
+ delegate["throw"] = (value : unknown) : unknown => {
86
+ if (typeof iterator.throw === "function") {
87
+ return pump("throw", value);
88
+ }
89
+ // Without a throw method, a native yield* closes the inner iterator and awaits its return()
90
+ // (AsyncIteratorClose). An error of return() goes into the body, else a TypeError.
91
+ waiting = true;
92
+ const closed = new NativePromise<never>((resolve) => {
93
+ resolve(typeof iterator.return === "function" ? Reflect.apply(iterator.return, inner, []) : undefined);
94
+ }).then((result : unknown) : never => {
95
+ if (typeof iterator.return === "function" && !isObject(result)) {
96
+ throw new TypeError("The result of return() of the iterator of yield* is not an object");
97
+ }
98
+ throw new TypeError("The iterator of yield* has no throw method");
99
+ });
100
+ return { done : false, value : new OverloadYield(closed, 1) };
101
+ };
102
+ if (typeof iterator.return === "function") {
103
+ delegate["return"] = (value : unknown) : unknown => {
104
+ if (waiting) {
105
+ waiting = false;
106
+ return value;
107
+ }
108
+ return pump("return", value);
109
+ };
110
+ }
111
+ return delegate as unknown as Iterator<unknown, unknown, unknown>;
112
+ }
113
+
32
114
  /**
33
115
  * A value that is not a thenable, in a box. The browser runtime reads the `then` property of an
34
116
  * awaited object one time, in the context of the body. When the object has no `then` method,
@@ -47,6 +129,11 @@ export function unbox(value : unknown) : unknown {
47
129
  return value instanceof PlainValue ? value.value : value;
48
130
  }
49
131
 
132
+ /** This function gives `true` for a value that can have properties: an object or a function. */
133
+ export function isObject(value : unknown) : value is object {
134
+ return (typeof value === "object" && value !== null) || typeof value === "function";
135
+ }
136
+
50
137
  /** The methods of a generator that a request of the consumer starts. */
51
138
  export type ResumeKey = "next" | "throw" | "return";
52
139
 
@@ -87,27 +174,31 @@ function request(target : unknown, key : ResumeKey, argument : unknown) : Promis
87
174
  }
88
175
 
89
176
  /**
90
- * This function gives %AsyncIteratorPrototype% of the engine, which gives `Symbol.asyncIterator`,
91
- * `Symbol.asyncDispose` and the async iterator helpers. If a compiler changed the async
92
- * generator below, the function gives `undefined`.
177
+ * This function gives %AsyncIteratorPrototype% of the engine from an async generator function.
178
+ * The prototype gives `Symbol.asyncIterator`, `Symbol.asyncDispose` and the async iterator
179
+ * helpers. If a compiler changed the async generator function, the function gives `undefined`.
180
+ *
181
+ * @internal
93
182
  */
94
- function asyncIteratorPrototype() : object | undefined {
183
+ export function asyncIteratorPrototypeOf(generatorFunction : Function) : object | undefined {
184
+ let prototype : Record<symbol, unknown> | null;
95
185
  try {
96
- const generatorFunction = async function* () {
97
- // The directive tells the Babel preset not to change this function (src/babel/skip-runtime.ts)
98
- // Stryker disable next-line all: the directive matters only when a bundler applies the preset to the runtime
99
- "async-browser-context runtime";
100
- };
101
- const prototype = Object.getPrototypeOf(Object.getPrototypeOf(generatorFunction.prototype) as object) as Record<symbol, unknown> | null;
102
- return prototype !== null && typeof prototype[Symbol.asyncIterator] === "function" ? prototype : undefined;
186
+ prototype = Object.getPrototypeOf(Object.getPrototypeOf(generatorFunction.prototype) as object) as Record<symbol, unknown> | null;
103
187
  } catch {
188
+ // A function without a prototype object, for example an arrow function
104
189
  return undefined;
105
190
  }
191
+ return prototype !== null && typeof prototype[Symbol.asyncIterator] === "function" ? prototype : undefined;
106
192
  }
107
193
 
108
- /** The prototype of the async generator objects of transformed code. Its methods are not enumerable, as native methods. */
109
- const AsyncGeneratorPrototype : object = (() => {
110
- const parent = asyncIteratorPrototype();
194
+ /**
195
+ * This function makes the prototype of the async generator objects of transformed code. Its
196
+ * methods are not enumerable, as native methods. Without `parent`, the prototype inherits from
197
+ * `Object.prototype` and gets its own `Symbol.asyncIterator` method.
198
+ *
199
+ * @internal
200
+ */
201
+ export function makeAsyncGeneratorPrototype(parent : object | undefined) : object {
111
202
  const prototype = Object.create(parent ?? Object.prototype) as object;
112
203
  const methods : Record<ResumeKey, (this : unknown, argument? : unknown) => Promise<IteratorResult<unknown, unknown>>> = {
113
204
  next(value) { return request(this, "next", value); },
@@ -122,7 +213,29 @@ const AsyncGeneratorPrototype : object = (() => {
122
213
  }
123
214
  Object.defineProperty(prototype, Symbol.toStringTag, { value : "AsyncGenerator", configurable : true });
124
215
  return prototype;
125
- })();
216
+ }
217
+
218
+ /**
219
+ * This function gives %AsyncIteratorPrototype% of the engine, or `undefined`. Another preset in
220
+ * the same Babel configuration, for example `next/babel` with its preset-env, can change the
221
+ * async generator below in the runtime itself. Its helper is then a module that loads at this
222
+ * time, and the call can throw. The catch keeps the runtime available, with a prototype
223
+ * without the parent of the engine.
224
+ */
225
+ function engineAsyncIteratorPrototype() : object | undefined {
226
+ try {
227
+ return asyncIteratorPrototypeOf(async function* () {
228
+ // The directive tells the Babel preset not to change this function (src/babel/skip-runtime.ts)
229
+ // Stryker disable next-line all: the directive matters only when a bundler applies the preset to the runtime
230
+ "async-browser-context runtime";
231
+ });
232
+ } catch {
233
+ return undefined;
234
+ }
235
+ }
236
+
237
+ /** The prototype of the async generator objects of transformed code. */
238
+ const AsyncGeneratorPrototype : object = makeAsyncGeneratorPrototype(engineAsyncIteratorPrototype());
126
239
 
127
240
  /**
128
241
  * This function makes an async generator object. The object queues the requests of the
@@ -137,8 +250,10 @@ export function createAsyncGenerator(
137
250
  ) : AsyncGenerator<unknown, unknown, unknown> {
138
251
  let first : Request | undefined;
139
252
  let last : Request | undefined;
140
- /** The state of the body: not started, suspended at a `yield`, or complete. While a step operates, the requests wait in the queue. */
141
- let state : "start" | "yield" | "done" = "start";
253
+ /** `true` after the first step of the body. While a step operates, the requests wait in the queue. */
254
+ let started = false;
255
+ /** `true` when the body is complete. */
256
+ let complete = false;
142
257
 
143
258
  /** This function starts the requests in the queue, one after the other, until the queue is empty. */
144
259
  const run = async (key : ResumeKey, argument : unknown) : Promise<void> => {
@@ -149,12 +264,10 @@ export function createAsyncGenerator(
149
264
  for (;;) {
150
265
  let failed = false;
151
266
  let settled : unknown;
152
- let done = false;
153
267
  try {
154
- if (state === "done" || (state === "start" && key !== "next")) {
268
+ if (complete || (!started && key !== "next")) {
155
269
  // The body does not operate: it is complete, or return() or throw() came before the start
156
- state = "done";
157
- done = true;
270
+ complete = true;
158
271
  if (key === "throw") {
159
272
  throw argument;
160
273
  }
@@ -163,6 +276,7 @@ export function createAsyncGenerator(
163
276
  settled = await argument;
164
277
  }
165
278
  } else {
279
+ started = true;
166
280
  if (key === "return") {
167
281
  // At a yield, return() awaits its value first. A rejection goes into the body at the yield.
168
282
  try {
@@ -174,43 +288,52 @@ export function createAsyncGenerator(
174
288
  resumed = true;
175
289
  }
176
290
  let result = step(key, argument, resumed);
291
+ // return() at a yield already awaited its value. If the body completes with that value, a native generator does not await it again.
292
+ if (key === "return" && result.done === true && result.value === argument) {
293
+ settled = argument;
294
+ complete = true;
295
+ result = { done : true, value : undefined };
296
+ }
177
297
  for (;;) {
298
+ if (complete) {
299
+ break;
300
+ }
178
301
  const yielded : unknown = result.value;
179
302
  const overloaded = yielded instanceof OverloadYield;
180
303
  let value : unknown;
181
304
  try {
182
305
  value = unbox(await prepare(overloaded ? yielded.v : yielded));
183
306
  } catch (error) {
184
- resumed = true;
185
- key = "throw";
186
- result = step("throw", error, true);
307
+ // The error goes into the body at the await or the yield. The delegate of a yield* throws it.
308
+ result = overloaded && yielded.k !== 0 ? step("next", new DelegateRejection(error), true) : step("throw", error, true);
187
309
  continue;
188
310
  }
189
311
  resumed = true;
190
312
  if (overloaded) {
191
- const nextKey : ResumeKey = key === "return" && yielded.k === 1 ? "return" : "next";
192
- if (yielded.k === 0 || Boolean((value as { done? : unknown }).done)) {
193
- key = nextKey;
194
- result = step(nextKey, value, true);
313
+ const resumeKey : ResumeKey = yielded.k === 2 ? "return" : "next";
314
+ if (yielded.k === 0 || !isObject(value)) {
315
+ // The value of an await. For a result of yield* that is not an object, the body throws a TypeError.
316
+ result = step(resumeKey, value, true);
195
317
  continue;
196
318
  }
197
- // A step of yield*: the body gives the result of the delegate back without a change.
198
- // Its value is not awaited, as with a native yield*.
199
- const passed = step(nextKey, value, true);
200
- if (passed !== value) {
201
- result = passed;
319
+ // A step of yield*. As a native yield*, the driver reads done and value one time, and the body gets a copy.
320
+ // The driver does not compare the result of the body with the copy, because the yield* of WebKit makes a new object.
321
+ const done = Boolean((value as { done? : unknown }).done);
322
+ const item = (value as { value? : unknown }).value;
323
+ result = step(resumeKey, { value : item, done }, true);
324
+ if (done) {
202
325
  continue;
203
326
  }
204
- value = passed.value;
327
+ // The body gives the result back. Its value is not awaited, as with a native yield*.
328
+ value = item;
205
329
  }
206
330
  settled = value;
207
- done = result.done === true;
331
+ complete = result.done === true;
208
332
  break;
209
333
  }
210
- state = done ? "done" : "yield";
211
334
  }
212
335
  } catch (error) {
213
- state = "done";
336
+ complete = true;
214
337
  failed = true;
215
338
  settled = error;
216
339
  }
@@ -220,7 +343,7 @@ export function createAsyncGenerator(
220
343
  if (failed) {
221
344
  current.reject(settled);
222
345
  } else {
223
- current.resolve({ value : settled, done });
346
+ current.resolve({ value : settled, done : complete });
224
347
  }
225
348
  if (first === undefined) {
226
349
  last = undefined;
@@ -63,6 +63,9 @@ export class AsyncLocalStorage<T> {
63
63
  * This method sets `store` for the rest of the current synchronous step, and for the
64
64
  * code that this step starts later. Prefer `run()`: `enterWith()` can also
65
65
  * change the store of the code that called the current function.
66
+ *
67
+ * Outside all steps, for example at the top level of a module, the store stays after the
68
+ * task as a default store, as on Node.js. No code sets the root context again.
66
69
  */
67
70
  enterWith(store : T) : void {
68
71
  this.#enabled = true;
@@ -8,9 +8,9 @@ export interface CallbackHook {
8
8
  /**
9
9
  * The library starts this method before the callback.
10
10
  *
11
- * @param callback - The function that the library starts. For the step
12
- * of an async function after an `await`, it is the body of the async
13
- * function, with the name of the async function.
11
+ * @param callback - The function that the library starts. For a step
12
+ * after an `await`, it is the body of the async function or the async
13
+ * generator. It has the name of that function.
14
14
  * @param source - The API that got the callback, for example
15
15
  * `"setTimeout"`, `"Promise.then"`, `"addEventListener:click"`,
16
16
  * `"onclick"` or `"await"`.