async-browser-context 0.2.4 → 0.3.1

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 +94 -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 +4 -3
  86. package/dist/patches/handler-interfaces.d.ts.map +1 -1
  87. package/dist/patches/handler-interfaces.js +7 -5
  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 +52 -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 +7 -5
  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
@@ -1,29 +1,39 @@
1
1
  import type { PluginItem, PresetAPI, PresetObject } from "@babel/core";
2
2
  import asyncGeneratorFunctions from "@babel/plugin-transform-async-generator-functions";
3
3
  import asyncToGenerator from "@babel/plugin-transform-async-to-generator";
4
+ import explicitResourceManagement from "@babel/plugin-transform-explicit-resource-management";
4
5
  import { asyncGeneratorHelpersPlugin } from "./async-generator-helpers.js";
6
+ import { asyncGeneratorResources } from "./async-generator-resources.js";
5
7
  import { bindGeneratorsPlugin } from "./bind-generators.js";
6
8
  import { nameCoroutinesPlugin } from "./name-coroutines.js";
7
- import { skipRuntimePlugin } from "./skip-runtime.js";
9
+ import { skipRuntimePlugin, withRuntimeSkipped, type PluginFactory } from "./skip-runtime.js";
10
+ import { staticMembersPlugin } from "./static-members.js";
8
11
 
9
12
  export { METADATA_KEY } from "./bind-generators.js";
10
13
 
11
14
  /** The options of the preset. */
12
15
  export interface PresetOptions {
13
16
  /**
14
- * The module that exports the runtime functions `coroutine` and
15
- * `bindGenerator`. The default is `async-browser-context/runtime`.
17
+ * The module that exports the six names of the runtime: `coroutine`,
18
+ * `bindGenerator`, `asyncGenerator`, `OverloadYield`, `awaitAsyncGenerator`
19
+ * and `asyncGeneratorDelegate`. The default is `async-browser-context/runtime`.
16
20
  */
17
21
  readonly runtime? : string | undefined;
18
22
  /**
19
- * Give the name of each async function to `coroutine`, for the callback
20
- * hooks. The default is `true`. With `false`, the hooks get no name for the
21
- * steps after an `await`. The code is then smaller by 0.1 to 1.6 percent
22
- * of its gzip size (`pnpm bench:size`).
23
+ * Give the name of each async function and each async generator to the
24
+ * runtime, for the callback hooks. The default is `true`. With `false`, the
25
+ * hooks get no name for the steps after an `await`. The code is then smaller
26
+ * by 0.1 to 1.8 percent of its gzip size (`pnpm bench:size`).
23
27
  */
24
28
  readonly names? : boolean | undefined;
25
29
  }
26
30
 
31
+ /** The plugin of Babel for async generators, without a change of the functions of the runtime (skip-runtime.ts). */
32
+ const asyncGeneratorFunctionsOutsideRuntime = withRuntimeSkipped(asyncGeneratorFunctions as unknown as PluginFactory);
33
+
34
+ /** The plugin of `using` declarations for async generators, before the plugin of Babel for async generators (async-generator-resources.ts). */
35
+ const asyncGeneratorResourcesPlugin = asyncGeneratorResources(explicitResourceManagement as unknown as PluginFactory);
36
+
27
37
  /** The default runtime module. */
28
38
  export const DEFAULT_RUNTIME = "async-browser-context/runtime";
29
39
 
@@ -37,13 +47,21 @@ export const DEFAULT_RUNTIME = "async-browser-context/runtime";
37
47
  * 2. A plugin of this library binds each sync generator to the context of
38
48
  * its creation.
39
49
  * 3. A plugin of this library gives the name of each async function to
40
- * `coroutine`, for the callback hooks. The option `names: false` removes
41
- * this step.
42
- * 4. A plugin of this library gives the async generators to `asyncGenerator`
43
- * of the runtime, in place of the Babel helper.
44
- * 5. `@babel/plugin-transform-async-generator-functions` changes async
45
- * generators and `for await` loops.
46
- * 6. `@babel/plugin-transform-async-to-generator` changes each async function
50
+ * `coroutine`, and of each async generator to `asyncGenerator`, for the
51
+ * callback hooks. The option `names: false` removes this step.
52
+ * 4. A plugin of this library moves the static class members with async arrow
53
+ * functions into static private methods. Thus `this` and `super` stay
54
+ * correct (static-members.ts).
55
+ * 5. A plugin of this library gives the async generators to the helpers of the
56
+ * runtime, in place of the Babel helpers.
57
+ * 6. `@babel/plugin-transform-explicit-resource-management` changes `using` and
58
+ * `await using` declarations, with Babel 7.23.9 and later.
59
+ * 7. A plugin of this library starts the plugin of step 6 on each async
60
+ * generator, before step 8 changes it (async-generator-resources.ts).
61
+ * 8. `@babel/plugin-transform-async-generator-functions` changes async
62
+ * generators and `for await` loops. Its own traversal also skips the
63
+ * functions of the runtime (skip-runtime.ts).
64
+ * 9. `@babel/plugin-transform-async-to-generator` changes each async function
47
65
  * into a generator that the `coroutine` function of the runtime operates.
48
66
  *
49
67
  * The preset operates with Babel 7.22 and later and with Babel 8. Put it last
@@ -52,15 +70,29 @@ export const DEFAULT_RUNTIME = "async-browser-context/runtime";
52
70
  export default function asyncBrowserContextPreset(api : PresetAPI, options : PresetOptions = {}) : PresetObject {
53
71
  api.assertVersion("^7.22.0 || ^8.0.0");
54
72
  const runtime = options.runtime ?? DEFAULT_RUNTIME;
73
+ // Stryker disable next-line ObjectLiteral: the plugin also finds the local names that the preset gives, for example _coroutine, without the runtime
55
74
  const names : PluginItem[] = options.names === false ? [] : [[nameCoroutinesPlugin, { runtime }]];
75
+ // The async transform keeps an `await using` declaration, which is a SyntaxError in a generator
76
+ const resources : PluginItem[] = supportsResourceManagement(api.version) ? [explicitResourceManagement, asyncGeneratorResourcesPlugin] : [];
56
77
  return {
57
78
  plugins : [
58
79
  skipRuntimePlugin,
59
80
  [bindGeneratorsPlugin, { runtime }],
60
81
  ...names,
82
+ staticMembersPlugin,
61
83
  [asyncGeneratorHelpersPlugin, { runtime }],
62
- asyncGeneratorFunctions,
84
+ ...resources,
85
+ asyncGeneratorFunctionsOutsideRuntime,
63
86
  [asyncToGenerator, { module : runtime, method : "coroutine" }],
64
87
  ],
65
88
  };
66
89
  }
90
+
91
+ /** This function gives `true` for a version of Babel that the plugin of explicit resource management accepts: 7.23.9 or later. */
92
+ export function supportsResourceManagement(version : string | undefined) : boolean {
93
+ if (typeof version !== "string") {
94
+ return false;
95
+ }
96
+ const [major = 0, minor = 0, patch = 0] = version.split(/[.+-]/).map(Number);
97
+ return major > 7 || (major === 7 && (minor > 23 || (minor === 23 && patch >= 9)));
98
+ }
@@ -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
+ }