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
@@ -1,5 +1,6 @@
1
- import { createAsyncGenerator, PlainValue, unbox } from "./async-generator.js";
2
- import { applyWithHooks, store, type Frame } from "./store.js";
1
+ import { createAsyncGenerator, isObject, PlainValue, unbox } from "./async-generator.js";
2
+ import { copyNameAndLength } from "./function-name.js";
3
+ import { applyQuietly, applyWithHooks, store, type Frame } from "./store.js";
3
4
 
4
5
  /**
5
6
  * The code from the Babel preset uses these runtime functions. Do not use them
@@ -14,26 +15,20 @@ import { applyWithHooks, store, type Frame } from "./store.js";
14
15
 
15
16
  /**
16
17
  * This function gives the generator function to the callback hooks, with the name of the
17
- * async function. The preset gives the name, because the generator function
18
+ * async function or the async generator. The preset gives the name, because the generator function
18
19
  * of Babel has no name. The function sets the name only when a hook operates.
19
20
  */
20
21
  function namedForHooks(generatorFunction : Function, name : string | undefined) : Function {
21
- if (name !== undefined && generatorFunction.name !== name) {
22
+ if (name === undefined) {
23
+ return generatorFunction;
24
+ }
25
+ // Stryker disable next-line ConditionalExpression: the check only prevents a second change to the same name
26
+ if (generatorFunction.name !== name) {
22
27
  Object.defineProperty(generatorFunction, "name", { value : name, configurable : true });
23
28
  }
24
29
  return generatorFunction;
25
30
  }
26
31
 
27
- /**
28
- * This function gives an async function that operates `generatorFunction`. The preset gives
29
- * this function to `@babel/plugin-transform-async-to-generator` as its
30
- * `method` option, and adds `name`, the name of the async function, if it has one.
31
- */
32
- /** This function gives `true` for a value that can have a `then` property: an object or a function. */
33
- function isObject(value : unknown) : value is object {
34
- return (typeof value === "object" && value !== null) || typeof value === "function";
35
- }
36
-
37
32
  /**
38
33
  * This function gives the value that a driver awaits or gives as its result, in place of `value`. It
39
34
  * operates in the context of the body, as `await` reads the `then` property there:
@@ -80,15 +75,20 @@ function awaitable(value : unknown, NativePromise : PromiseConstructor, box : bo
80
75
  * This function gives an async function that operates `generatorFunction`. The preset gives
81
76
  * this function to `@babel/plugin-transform-async-to-generator` as its
82
77
  * `method` option, and adds `name`, the name of the async function, if it has one.
78
+ *
79
+ * The first step of the body operates in the step of the caller. Thus an `enterWith()` of that
80
+ * step stays for the caller, as on Node.js.
83
81
  */
84
82
  export function coroutine<T, A extends unknown[], R>(
85
83
  generatorFunction : (this : T, ...args : A) => Generator<unknown, R, unknown>,
86
84
  name? : string,
87
85
  ) : (this : T, ...args : A) => Promise<R> {
88
86
  const NativePromise = store.intrinsics.Promise;
89
- return function asyncFunction(this : T, ...args : A) : Promise<R> {
87
+ const asyncFunction = function asyncFunction(this : T, ...args : A) : Promise<R> {
90
88
  // The context of the call. The body can change it with AsyncLocalStorage.enterWith.
91
89
  let frame : Frame = store.current;
90
+ // An async function that a hook starts does not start the hooks (store.ts, applyQuietly)
91
+ const quiet = store.inHook === true;
92
92
  let generator : Generator<unknown, R, unknown>;
93
93
  const next = (value : unknown) : IteratorResult<unknown, R> => generator.next(value);
94
94
  const throwInto = (error : unknown) : IteratorResult<unknown, R> => generator.throw(error);
@@ -105,9 +105,11 @@ export function coroutine<T, A extends unknown[], R>(
105
105
  store.current = frame;
106
106
  try {
107
107
  const hooks = resumed ? store.hooks : undefined;
108
- const result = hooks === undefined
109
- ? resume(argument)
110
- : applyWithHooks(hooks, namedForHooks(generatorFunction, name), "await", resume, undefined, [argument]);
108
+ const result = quiet
109
+ ? applyQuietly(resume, undefined, [argument])
110
+ : hooks === undefined
111
+ ? resume(argument)
112
+ : applyWithHooks(hooks, namedForHooks(generatorFunction, name), "await", resume, undefined, [argument]);
111
113
  // The result object is new for each step, so the change is not visible to other code
112
114
  (result as { value : unknown }).value = awaitable(result.value, NativePromise, result.done !== true);
113
115
  return result;
@@ -143,22 +145,29 @@ export function coroutine<T, A extends unknown[], R>(
143
145
  };
144
146
  return drive();
145
147
  };
148
+ // Where Babel gives no named wrapper, for example in a class field, the function keeps the name and the length of the source
149
+ copyNameAndLength(asyncFunction, name, generatorFunction.length);
150
+ return asyncFunction;
146
151
  }
147
152
 
148
153
  /**
149
154
  * This function gives a function that makes an async generator object, which operates
150
155
  * `generatorFunction`. The preset gives this function in place of the helper
151
- * `wrapAsyncGenerator` of `@babel/plugin-transform-async-generator-functions`.
156
+ * `wrapAsyncGenerator` of `@babel/plugin-transform-async-generator-functions`. It adds `name`,
157
+ * the name of the async generator, if it has one.
152
158
  *
153
159
  * Each step of the body operates in the context of the call that made the generator
154
160
  * (rule C5). The driver continues each step with a native `await` (`async-generator.ts`).
155
161
  */
156
162
  export function asyncGenerator<T, A extends unknown[]>(
157
163
  generatorFunction : (this : T, ...args : A) => Generator<unknown, unknown, unknown>,
164
+ name? : string,
158
165
  ) : (this : T, ...args : A) => AsyncGenerator<unknown, unknown, unknown> {
159
166
  const NativePromise = store.intrinsics.Promise;
160
- return function makeAsyncGenerator(this : T, ...args : A) : AsyncGenerator<unknown, unknown, unknown> {
167
+ const makeAsyncGenerator = function makeAsyncGenerator(this : T, ...args : A) : AsyncGenerator<unknown, unknown, unknown> {
161
168
  let frame : Frame = store.current;
169
+ // An async generator that a hook makes does not start the hooks (store.ts, applyQuietly)
170
+ const quiet = store.inHook === true;
162
171
  const generator = Reflect.apply(generatorFunction, this, args);
163
172
  const methods : Record<ResumeMethod, (argument : unknown) => IteratorResult<unknown, unknown>> = {
164
173
  next : (argument) => generator.next(argument),
@@ -170,10 +179,13 @@ export function asyncGenerator<T, A extends unknown[]>(
170
179
  const previous = store.current;
171
180
  store.current = frame;
172
181
  try {
182
+ if (quiet) {
183
+ return applyQuietly(methods[key], undefined, [argument]);
184
+ }
173
185
  const hooks = resumed ? store.hooks : undefined;
174
186
  return hooks === undefined
175
187
  ? methods[key](argument)
176
- : applyWithHooks(hooks, generatorFunction, "await", methods[key], undefined, [argument]);
188
+ : applyWithHooks(hooks, namedForHooks(generatorFunction, name), "await", methods[key], undefined, [argument]);
177
189
  } finally {
178
190
  frame = store.current;
179
191
  store.current = previous;
@@ -191,6 +203,8 @@ export function asyncGenerator<T, A extends unknown[]>(
191
203
  };
192
204
  return createAsyncGenerator(step, NativePromise, undefined, prepare);
193
205
  };
206
+ copyNameAndLength(makeAsyncGenerator, name, generatorFunction.length);
207
+ return makeAsyncGenerator;
194
208
  }
195
209
 
196
210
  type AnyIterator = Iterator<unknown, unknown, unknown> | AsyncIterator<unknown, unknown, unknown>;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * This function gives the function of the runtime the `name` and the `length` of the source
3
+ * function, as the native function has them. Without a name, the name is the empty string, as
4
+ * for a native anonymous function. The preset gives the name, if the source has one. Where Babel
5
+ * gives no named wrapper, for example in a class field, the function of the runtime is the
6
+ * function that the program sees. The browser runtime and the Node.js runtime both use it.
7
+ */
8
+ export function copyNameAndLength(fn : Function, name : string | undefined, length : number) : void {
9
+ Object.defineProperty(fn, "name", { value : name ?? "", configurable : true });
10
+ Object.defineProperty(fn, "length", { value : length, configurable : true });
11
+ }
package/src/core/hooks.ts CHANGED
@@ -3,6 +3,25 @@ import { store, type HookEntry } from "./store.js";
3
3
 
4
4
  export type { CallbackHook } from "./callback-hook.js";
5
5
 
6
+ let warned = false;
7
+
8
+ /**
9
+ * Version 0.1 of the library has no callback hooks. If a copy of version 0.1 installed some
10
+ * patches first, the callbacks of those patches do not start the hooks. The function tells
11
+ * this one time on the console. The patches of version 0.2 start the hooks, and the patch of
12
+ * `Function.prototype.toString` has no callbacks.
13
+ */
14
+ function warnAboutOldPatches() : void {
15
+ if (warned) {
16
+ return;
17
+ }
18
+ const without = [...(store.oldCopyPatches ?? [])].filter((name) => name !== "Function.prototype.toString");
19
+ if (without.length > 0) {
20
+ warned = true;
21
+ console.warn(`async-browser-context: an older copy of the library installed these patches, and their callbacks do not start the callback hooks: ${without.join(", ")}`);
22
+ }
23
+ }
24
+
6
25
  /**
7
26
  * This function adds a hook. The library starts its methods before and after each
8
27
  * callback that it starts. These callbacks are the callbacks of the patched
@@ -12,18 +31,16 @@ export type { CallbackHook } from "./callback-hook.js";
12
31
  * A tool can use the hook to measure the time of each callback, with the
13
32
  * name of the callback and the values of its context. An error in a hook goes
14
33
  * to `reportError()`, and the callback operates as usual. A callback that
15
- * starts synchronously in a hook does not start the hook methods.
34
+ * starts synchronously in a hook does not start the hook methods. A callback
35
+ * that a hook schedules does not start them either, also later.
16
36
  */
17
37
  export function addCallbackHook(hook : CallbackHook) : () => void {
18
38
  assertCallbackHook(hook);
39
+ warnAboutOldPatches();
19
40
  const entry : HookEntry = { hook };
20
41
  store.hooks = [...(store.hooks ?? []), entry];
21
- let removed = false;
42
+ // A second removal finds no entry, and the list stays the same
22
43
  return function removeCallbackHook() : void {
23
- if (removed) {
24
- return;
25
- }
26
- removed = true;
27
44
  const remaining = (store.hooks ?? []).filter((other) => other !== entry);
28
45
  store.hooks = remaining.length === 0 ? undefined : remaining;
29
46
  };
@@ -28,7 +28,8 @@ export class Snapshot {
28
28
  /**
29
29
  * This method records the current context and gives a wrapper of `fn`. The
30
30
  * wrapper starts `fn` in the recorded context, with the `this` value and the arguments of
31
- * each call.
31
+ * each call. The name of the wrapper is "wrapped" and the name of `fn`, and its length is
32
+ * the length of `fn`.
32
33
  */
33
34
  static wrap<T, A extends unknown[], R>(fn : (this : T, ...args : A) => R) : (this : T, ...args : A) => R {
34
35
  if (typeof fn !== "function") {
@@ -39,13 +40,17 @@ export class Snapshot {
39
40
  const previous = store.current;
40
41
  store.current = frame;
41
42
  try {
42
- return fn.apply(this, args);
43
+ return Reflect.apply(fn, this, args);
43
44
  } finally {
44
45
  store.current = previous;
45
46
  }
46
47
  };
47
- Object.defineProperty(wrapped, "name", { value : fn.name, configurable : true });
48
+ // As CopyNameAndLength with the prefix "wrapped" in the TC39 draft
49
+ const name : unknown = fn.name;
50
+ Object.defineProperty(wrapped, "name", { value : `wrapped ${typeof name === "string" ? name : ""}`, configurable : true });
48
51
  Object.defineProperty(wrapped, "length", { value : fn.length, configurable : true });
49
52
  return wrapped;
50
53
  }
51
54
  }
55
+
56
+ Object.defineProperty(Snapshot.prototype, Symbol.toStringTag, { value : "AsyncContext.Snapshot", configurable : true });
package/src/core/store.ts CHANGED
@@ -19,8 +19,10 @@ export interface Frame {
19
19
  /** The native functions that the runtime uses. The store records them before a patch replaces them. */
20
20
  export interface Intrinsics {
21
21
  readonly Promise : PromiseConstructor;
22
+ /** The patch of version 0.3 does not use it. An older copy of the library that shares the store can use it. */
22
23
  readonly promiseThen : typeof Promise.prototype.then;
23
24
  readonly promiseResolve : <T>(value : T) => Promise<Awaited<T>>;
25
+ /** The patch of version 0.3 does not use it. An older copy of the library that shares the store can use it. */
24
26
  readonly functionToString : () => string;
25
27
  }
26
28
 
@@ -42,6 +44,18 @@ export interface ContextStore {
42
44
  hooks? : readonly HookEntry[] | undefined;
43
45
  /** `true` while a hook operates. Callbacks that start in a hook do not start the hook methods. */
44
46
  inHook? : boolean | undefined;
47
+ /**
48
+ * The patches that a copy of version 0.1 installed before a newer copy loaded. Version 0.1
49
+ * has no callback hooks, so the callbacks of these patches do not start the hooks. Only a
50
+ * store that a copy of version 0.1 made has this property.
51
+ */
52
+ oldCopyPatches? : ReadonlySet<string> | undefined;
53
+ /**
54
+ * The frame that stays current between tasks: the root frame, or the frame of a top-level
55
+ * `enterWith()` (a default store). The event patch handles it as the root frame (rule C13).
56
+ * The store of an older copy of the library does not have this property.
57
+ */
58
+ idle? : Frame | undefined;
45
59
  }
46
60
 
47
61
  /** The methods of a callback hook. The public type is `CallbackHook` in `hooks.ts`. */
@@ -75,22 +89,54 @@ function createStore() : ContextStore {
75
89
  // Own properties from the start: each callback reads `hooks`, and the read of an own property is faster
76
90
  hooks : undefined,
77
91
  inHook : false,
92
+ idle : root,
78
93
  };
79
94
  }
80
95
 
81
- function getOrCreateStore() : ContextStore {
82
- const holder = globalThis as unknown as Record<symbol, ContextStore | undefined>;
83
- const existing = holder[STORE_KEY];
96
+ /**
97
+ * This function gives the store of the global object `holder`. If `holder` has no store, the
98
+ * function makes one, and adds it as a property that code cannot change or remove.
99
+ *
100
+ * @internal
101
+ */
102
+ export function getOrCreateStore(holder : object) : ContextStore {
103
+ const existing = (holder as Record<symbol, ContextStore | undefined>)[STORE_KEY];
84
104
  if (existing !== undefined) {
105
+ // The stores of version 0.2 and later have the own property hooks from the start. Version 0.1 has no hooks.
106
+ if (!Object.prototype.hasOwnProperty.call(existing, "hooks") && existing.oldCopyPatches === undefined) {
107
+ existing.oldCopyPatches = new Set(existing.patches);
108
+ }
85
109
  return existing;
86
110
  }
87
111
  const created = createStore();
88
- Object.defineProperty(globalThis, STORE_KEY, { value : created, writable : false, enumerable : false, configurable : false });
112
+ Object.defineProperty(holder, STORE_KEY, { value : created, writable : false, enumerable : false, configurable : false });
89
113
  return created;
90
114
  }
91
115
 
92
116
  /** The store of this global object. */
93
- export const store : ContextStore = getOrCreateStore();
117
+ export const store : ContextStore = getOrCreateStore(globalThis);
118
+
119
+ /** `true` while a record of the idle frame waits in the microtask queue. */
120
+ let idleRecordQueued = false;
121
+
122
+ /**
123
+ * This function records `store.idle` in the next microtask. `enterWith()` starts it, because a
124
+ * top-level `enterWith()` changes the frame that stays current between tasks. A microtask
125
+ * operates when the stack is empty, after each wrapper set its previous frame again. The callback
126
+ * goes to the native `then`, so no wrapper sets a frame for it.
127
+ */
128
+ export function recordIdleFrame() : void {
129
+ // Stryker disable next-line ConditionalExpression,BlockStatement: a second record in the same turn records the same frame, so the flag only prevents more microtasks
130
+ if (idleRecordQueued) {
131
+ return;
132
+ }
133
+ // Stryker disable next-line BooleanLiteral: a second record in the same turn records the same frame, so the flag only prevents more microtasks
134
+ idleRecordQueued = true;
135
+ Reflect.apply(store.intrinsics.promiseThen, store.intrinsics.promiseResolve(undefined), [() : void => {
136
+ idleRecordQueued = false;
137
+ store.idle = store.current;
138
+ }]);
139
+ }
94
140
 
95
141
  /** This function makes `frame` the current frame. It gives the frame that was current before. */
96
142
  export function enter(frame : Frame) : Frame {
@@ -115,7 +161,8 @@ class ValueFrame implements Frame {
115
161
  /**
116
162
  * The result of the last search for another variable from this frame. A
117
163
  * frame does not change, so the result stays correct. The cached value
118
- * comes from a parent frame, so the cache keeps no other object in memory.
164
+ * comes from a parent frame. The cache also keeps the last variable of a
165
+ * search, so a frame can keep one more variable in memory.
119
166
  */
120
167
  #cachedVariable : object | undefined = undefined;
121
168
  #cachedValue : unknown = undefined;
@@ -145,6 +192,16 @@ class ValueFrame implements Frame {
145
192
  return value;
146
193
  }
147
194
 
195
+ /**
196
+ * This method makes a frame that sets `variable`. When `parent` sets the same variable,
197
+ * the new frame replaces it: the new frame has the parent of `parent`. A search gives the
198
+ * same values. Many uses of enterWith() in one context thus do not make a long chain.
199
+ */
200
+ static create(parent : Frame, variable : object, value : unknown) : ValueFrame {
201
+ const base = #variable in parent && parent.#variable === variable ? parent.parent : parent;
202
+ return new ValueFrame(base, variable, value);
203
+ }
204
+
148
205
  static #search(start : Frame | null, variable : object) : unknown {
149
206
  for (let frame = start; frame !== null; frame = frame.parent) {
150
207
  if (#variable in frame && frame.#variable === variable) {
@@ -157,7 +214,7 @@ class ValueFrame implements Frame {
157
214
 
158
215
  /** This function makes a new frame that has `parent` as its parent and sets `variable` to `value`. */
159
216
  export function createFrame(parent : Frame, variable : object, value : unknown) : Frame {
160
- return new ValueFrame(parent, variable, value);
217
+ return ValueFrame.create(parent, variable, value);
161
218
  }
162
219
 
163
220
  /** This function gives the value of `variable` in `frame`, or `NOT_FOUND` if no frame sets it. */
@@ -167,12 +224,16 @@ export function findValue(frame : Frame, variable : object) : unknown {
167
224
 
168
225
  /** This function gives the error of a hook to the host. A hook error does not stop the callback. */
169
226
  function reportHookError(error : unknown) : void {
170
- const report = (globalThis as { reportError? : unknown }).reportError;
171
- if (typeof report === "function") {
172
- (report as (error : unknown) => void)(error);
173
- return;
227
+ try {
228
+ const report = (globalThis as { reportError? : unknown }).reportError;
229
+ if (typeof report === "function") {
230
+ Reflect.apply(report, globalThis, [error]);
231
+ return;
232
+ }
233
+ console.error(error);
234
+ } catch {
235
+ // The report itself failed. The callback must operate, so the error stops here.
174
236
  }
175
- console.error(error);
176
237
  }
177
238
 
178
239
  /**
@@ -187,12 +248,12 @@ function callHooks(hooks : readonly HookEntry[], phase : "before" | "after", cal
187
248
  const count = hooks.length;
188
249
  for (let step = 0; step < count; step++) {
189
250
  const { hook } = hooks[phase === "before" ? step : count - 1 - step] as HookEntry;
190
- const method = hook[phase];
191
- if (typeof method !== "function") {
192
- continue;
193
- }
194
251
  try {
195
- method.call(hook, callback, source);
252
+ // A getter of the method can also throw
253
+ const method = hook[phase];
254
+ if (typeof method === "function") {
255
+ Reflect.apply(method, hook, [callback, source]);
256
+ }
196
257
  } catch (error) {
197
258
  reportHookError(error);
198
259
  }
@@ -218,16 +279,32 @@ export function applyWithHooks<T, A extends unknown[], R>(
218
279
  args : A,
219
280
  ) : R {
220
281
  if (store.inHook === true) {
221
- return fn.apply(thisValue, args);
282
+ return Reflect.apply(fn, thisValue, args);
222
283
  }
223
284
  callHooks(hooks, "before", callback, source);
224
285
  try {
225
- return fn.apply(thisValue, args);
286
+ return Reflect.apply(fn, thisValue, args);
226
287
  } finally {
227
288
  callHooks(hooks, "after", callback, source);
228
289
  }
229
290
  }
230
291
 
292
+ /**
293
+ * This function starts `fn` as a callback that a hook registered: the hooks do not operate for
294
+ * it. `store.inHook` stays `true` while it operates. Thus the callbacks and the async functions
295
+ * that it starts or registers do not start the hooks either. A hook cannot start itself without
296
+ * end, also through a chain of callbacks.
297
+ */
298
+ export function applyQuietly<T, A extends unknown[], R>(fn : (this : T, ...args : A) => R, thisValue : T, args : A) : R {
299
+ const previous = store.inHook;
300
+ store.inHook = true;
301
+ try {
302
+ return Reflect.apply(fn, thisValue, args);
303
+ } finally {
304
+ store.inHook = previous;
305
+ }
306
+ }
307
+
231
308
  /*
232
309
  * Each wrapper has the name `asyncBrowserContextWrapper`. Profilers, stack
233
310
  * traces and the Long Animation Frames API show the static name of a
@@ -242,13 +319,18 @@ export function applyWithHooks<T, A extends unknown[], R>(
242
319
  * `fn`, for the callback hooks.
243
320
  */
244
321
  export function bindToFrame<T, A extends unknown[], R>(frame : Frame, fn : (this : T, ...args : A) => R, source : string) : (this : T, ...args : A) => R {
322
+ // A callback that a hook registers does not start the hooks, so a hook cannot start itself without end
323
+ const quiet = store.inHook === true;
245
324
  return function asyncBrowserContextWrapper(this : T, ...args : A) : R {
246
325
  const previous = store.current;
247
326
  store.current = frame;
248
327
  try {
328
+ if (quiet) {
329
+ return applyQuietly(fn, this, args);
330
+ }
249
331
  const hooks = store.hooks;
250
332
  if (hooks === undefined) {
251
- return fn.apply(this, args);
333
+ return Reflect.apply(fn, this, args);
252
334
  }
253
335
  return applyWithHooks(hooks, fn, source, fn, this, args);
254
336
  } finally {
@@ -263,13 +345,17 @@ export function bindToFrame<T, A extends unknown[], R>(frame : Frame, fn : (this
263
345
  * `bindToFrame` on the hot path.
264
346
  */
265
347
  export function bindOneArgument<T, A, R>(frame : Frame, fn : (this : T, argument : A) => R, source : string) : (this : T, argument : A) => R {
348
+ const quiet = store.inHook === true;
266
349
  return function asyncBrowserContextWrapper(this : T, argument : A) : R {
267
350
  const previous = store.current;
268
351
  store.current = frame;
269
352
  try {
353
+ if (quiet) {
354
+ return applyQuietly(fn, this, [argument]);
355
+ }
270
356
  const hooks = store.hooks;
271
357
  if (hooks === undefined) {
272
- return fn.call(this, argument);
358
+ return Reflect.apply(fn, this, [argument]);
273
359
  }
274
360
  return applyWithHooks(hooks, fn, source, fn, this, [argument]);
275
361
  } finally {
@@ -1,4 +1,4 @@
1
- import { createFrame, findValue, NOT_FOUND, store } from "./store.js";
1
+ import { createFrame, findValue, NOT_FOUND, recordIdleFrame, store } from "./store.js";
2
2
 
3
3
  /** The options of a `Variable`. */
4
4
  export interface VariableOptions<T> {
@@ -50,7 +50,8 @@ export class Variable<T> {
50
50
 
51
51
  /**
52
52
  * This method starts `fn` with `args` in a new context in which `get()`
53
- * gives `value`. After `fn` ends, also with an error, the previous context is
53
+ * gives `value`. As in the TC39 draft, `fn` gets `undefined` as its `this`
54
+ * value. After `fn` ends, also with an error, the previous context is
54
55
  * current again. The method gives the result of `fn`.
55
56
  */
56
57
  run<R, A extends unknown[]>(value : T, fn : (...args : A) => R, ...args : A) : R {
@@ -64,6 +65,8 @@ export class Variable<T> {
64
65
  }
65
66
  }
66
67
 
68
+ Object.defineProperty(Variable.prototype, Symbol.toStringTag, { value : "AsyncContext.Variable", configurable : true });
69
+
67
70
  /**
68
71
  * This function makes a new current frame in which `variable` has `value`.
69
72
  * The frame stays current until the code that controls the current step sets
@@ -73,4 +76,5 @@ export class Variable<T> {
73
76
  */
74
77
  export function enterValue<T>(variable : Variable<T>, value : T) : void {
75
78
  store.current = createFrame(store.current, variable, value);
79
+ recordIdleFrame();
76
80
  }
package/src/node/index.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * @packageDocumentation
9
9
  */
10
- import { AsyncLocalStorage as NodeAsyncLocalStorage } from "node:async_hooks";
10
+ import { AsyncLocalStorage as NodeAsyncLocalStorage, AsyncResource } from "node:async_hooks";
11
11
  import { assertCallbackHook, type CallbackHook } from "../core/callback-hook.js";
12
12
  import type { VariableOptions } from "../core/variable.js";
13
13
  import { createCompatibleStorage } from "./compatible-storage.js";
@@ -16,16 +16,27 @@ export type { AsyncLocalStorageOptions } from "../core/async-local-storage.js";
16
16
  export type { CallbackHook } from "../core/callback-hook.js";
17
17
  export type { VariableOptions } from "../core/variable.js";
18
18
 
19
- /** The value of a `Variable` in one context. The box tells "a value is set" apart from `undefined`. */
20
- interface Box<T> {
21
- readonly value : T;
19
+ /**
20
+ * One value of one variable in a context, and the values of the parent context. The chain
21
+ * tells "a value is set" apart from `undefined`.
22
+ */
23
+ interface Entry {
24
+ readonly variable : object;
25
+ readonly value : unknown;
26
+ readonly parent : Entry | undefined;
22
27
  }
23
28
 
29
+ /**
30
+ * One native storage for all variables. Its store is the chain of the values of the current
31
+ * context. On Node.js 22, each native storage that operated stays in a global list of
32
+ * async_hooks, and each new async resource examines the list. One storage keeps that list short.
33
+ */
34
+ const values = new NodeAsyncLocalStorage<Entry>();
35
+
24
36
  /** The `AsyncContext.Variable` of the TC39 proposal, on the native `AsyncLocalStorage`. */
25
37
  export class Variable<T> {
26
38
  readonly #name : string;
27
39
  readonly #defaultValue : T | undefined;
28
- readonly #storage : NodeAsyncLocalStorage<Box<T>> = new NodeAsyncLocalStorage<Box<T>>();
29
40
 
30
41
  constructor(options : VariableOptions<T> = {}) {
31
42
  this.#name = options.name === undefined ? "" : String(options.name);
@@ -39,23 +50,41 @@ export class Variable<T> {
39
50
 
40
51
  /** This method gives the value of this variable in the current context, or the default value. */
41
52
  get() : T | undefined {
42
- const box = this.#storage.getStore();
43
- return box === undefined ? this.#defaultValue : box.value;
53
+ for (let entry = values.getStore(); entry !== undefined; entry = entry.parent) {
54
+ if (entry.variable === this) {
55
+ return entry.value as T;
56
+ }
57
+ }
58
+ return this.#defaultValue;
44
59
  }
45
60
 
46
- /** This method starts `fn` with `args` in a new context in which `get()` gives `value`. */
61
+ /**
62
+ * This method starts `fn` with `args` in a new context in which `get()` gives `value`. As
63
+ * in the TC39 draft, `fn` gets `undefined` as its `this` value.
64
+ */
47
65
  run<R, A extends unknown[]>(value : T, fn : (...args : A) => R, ...args : A) : R {
48
- return this.#storage.run({ value }, fn, ...args);
66
+ const current = values.getStore();
67
+ // A value of the same variable in the current context gets replaced, so the chain stays short
68
+ const parent = current !== undefined && current.variable === this ? current.parent : current;
69
+ return values.run({ variable : this, value, parent }, () => fn(...args));
49
70
  }
50
71
  }
51
72
 
52
- /** The `AsyncContext.Snapshot` of the TC39 proposal, on the native `AsyncLocalStorage.snapshot()`. */
73
+ Object.defineProperty(Variable.prototype, Symbol.toStringTag, { value : "AsyncContext.Variable", configurable : true });
74
+
75
+ /** The type of the async resources of the snapshots, for async_hooks. */
76
+ const SNAPSHOT_TYPE = "AsyncContext.Snapshot";
77
+
78
+ /**
79
+ * The `AsyncContext.Snapshot` of the TC39 proposal. An `AsyncResource` records the context, as
80
+ * `AsyncLocalStorage.snapshot()` does, at a much lower cost (src/node/runtime.ts).
81
+ */
53
82
  export class Snapshot {
54
- readonly #run : <R, A extends unknown[]>(fn : (...args : A) => R, ...args : A) => R = NodeAsyncLocalStorage.snapshot();
83
+ readonly #context = new AsyncResource(SNAPSHOT_TYPE);
55
84
 
56
- /** This method starts `fn` with `args` in the recorded context. */
85
+ /** This method starts `fn` with `args` in the recorded context. `fn` gets `undefined` as its `this` value. */
57
86
  run<R, A extends unknown[]>(fn : (...args : A) => R, ...args : A) : R {
58
- return this.#run(fn, ...args);
87
+ return this.#context.runInAsyncScope(fn, undefined, ...args);
59
88
  }
60
89
 
61
90
  /** This method records the current context. It gives a wrapper of `fn` that operates in that context. */
@@ -63,25 +92,39 @@ export class Snapshot {
63
92
  if (typeof fn !== "function") {
64
93
  throw new TypeError("Snapshot.wrap: the argument is not a function");
65
94
  }
66
- const run = NodeAsyncLocalStorage.snapshot();
95
+ const context = new AsyncResource(SNAPSHOT_TYPE);
67
96
  const wrapped = function (this : T, ...args : A) : R {
68
- return run(() => fn.apply(this, args));
97
+ return context.runInAsyncScope(fn, this, ...args);
69
98
  };
70
- Object.defineProperty(wrapped, "name", { value : fn.name, configurable : true });
99
+ // As CopyNameAndLength with the prefix "wrapped" in the TC39 draft
100
+ const name : unknown = fn.name;
101
+ Object.defineProperty(wrapped, "name", { value : `wrapped ${typeof name === "string" ? name : ""}`, configurable : true });
71
102
  Object.defineProperty(wrapped, "length", { value : fn.length, configurable : true });
72
103
  return wrapped;
73
104
  }
74
105
  }
75
106
 
76
- /** This function gives `true` if the native class supports the `defaultValue` option (Node.js 24 and later). */
107
+ Object.defineProperty(Snapshot.prototype, Symbol.toStringTag, { value : "AsyncContext.Snapshot", configurable : true });
108
+
109
+ /**
110
+ * This function gives `true` if the native class supports the `defaultValue` option (Node.js 24
111
+ * and later), and `exit()` then gives `undefined` as in the browser class. Without
112
+ * AsyncContextFrame (`--no-async-context-frame`), `exit()` gives the default value, so the
113
+ * compatible class is used. The probe disables itself, so it does not stay in the list of
114
+ * async_hooks.
115
+ */
77
116
  function supportsOptions() : boolean {
78
117
  const probe = new NodeAsyncLocalStorage<number>({ defaultValue : 1 } as never);
79
- return probe.getStore() === 1;
118
+ try {
119
+ return probe.getStore() === 1 && probe.run(2, () => probe.exit(() => probe.getStore())) === undefined;
120
+ } finally {
121
+ probe.disable();
122
+ }
80
123
  }
81
124
 
82
125
  /**
83
126
  * The native `AsyncLocalStorage` of Node.js. On a Node.js version without the
84
- * `defaultValue` and `name` options, a subclass adds them.
127
+ * `defaultValue` and `name` options, a compatible class adds them (compatible-storage.ts).
85
128
  */
86
129
  export const AsyncLocalStorage : typeof NodeAsyncLocalStorage = supportsOptions()
87
130
  ? NodeAsyncLocalStorage