async-browser-context 0.2.3 → 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 +102 -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 +51 -13
  36. package/dist/core/async-generator.d.ts.map +1 -1
  37. package/dist/core/async-generator.js +255 -58
  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 +106 -44
  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 +273 -62
  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 +104 -43
  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, OverloadYield } 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,56 +15,107 @@ 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
 
32
+ /**
33
+ * This function gives the value that a driver awaits or gives as its result, in place of `value`. It
34
+ * operates in the context of the body, as `await` reads the `then` property there:
35
+ *
36
+ * - A primitive value and a native promise stay the same. `await` does not read a `then`
37
+ * property of them.
38
+ * - For another object, the function reads `then` one time. A `then` method gets the current
39
+ * frame for its later call. Thus the method operates in the context of the body, as with
40
+ * the native `AsyncLocalStorage`. With `box`, an object without a `then` method goes into a
41
+ * box, so that the engine does not read `then` a second time.
42
+ * - When the read throws, the function gives a rejected promise: the error goes into the body.
43
+ */
44
+ function awaitable(value : unknown, NativePromise : PromiseConstructor, box : boolean) : unknown {
45
+ if (!isObject(value)) {
46
+ return value;
47
+ }
48
+ let then : unknown;
49
+ try {
50
+ if (value instanceof NativePromise && value.constructor === NativePromise) {
51
+ return value;
52
+ }
53
+ then = (value as { then? : unknown }).then;
54
+ } catch (error) {
55
+ return new NativePromise((_resolve, reject) => reject(error));
56
+ }
57
+ if (typeof then !== "function") {
58
+ return box ? new PlainValue(value) : value;
59
+ }
60
+ const frame = store.current;
61
+ return {
62
+ then(this : unknown, resolve : unknown, reject : unknown) : unknown {
63
+ const previous = store.current;
64
+ store.current = frame;
65
+ try {
66
+ return Reflect.apply(then, value, [resolve, reject]);
67
+ } finally {
68
+ store.current = previous;
69
+ }
70
+ },
71
+ };
72
+ }
73
+
27
74
  /**
28
75
  * This function gives an async function that operates `generatorFunction`. The preset gives
29
76
  * this function to `@babel/plugin-transform-async-to-generator` as its
30
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.
31
81
  */
32
82
  export function coroutine<T, A extends unknown[], R>(
33
83
  generatorFunction : (this : T, ...args : A) => Generator<unknown, R, unknown>,
34
84
  name? : string,
35
85
  ) : (this : T, ...args : A) => Promise<R> {
36
- const { promiseResolve } = store.intrinsics;
37
- return function asyncFunction(this : T, ...args : A) : Promise<R> {
86
+ const NativePromise = store.intrinsics.Promise;
87
+ const asyncFunction = function asyncFunction(this : T, ...args : A) : Promise<R> {
38
88
  // The context of the call. The body can change it with AsyncLocalStorage.enterWith.
39
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;
40
92
  let generator : Generator<unknown, R, unknown>;
41
93
  const next = (value : unknown) : IteratorResult<unknown, R> => generator.next(value);
42
94
  const throwInto = (error : unknown) : IteratorResult<unknown, R> => generator.throw(error);
43
95
 
44
96
  /**
45
- * This function does one step of the body in the context of the async function, and sets
46
- * the previous context again. `resumed` is `true` for a step after an `await`. Only these
47
- * steps start the hook methods. The function gives the value to await.
97
+ * This function does one step of the body in the context of the async function. `resumed`
98
+ * is `true` for a step after an `await`. Only these steps start the hook methods. After a
99
+ * resumed step, the function sets the previous context again. The first step operates in
100
+ * the code of the caller, so an `enterWith` of that step stays for the caller, as on
101
+ * Node.js. The function gives the value to await, or the result of the function.
48
102
  */
49
103
  const step = (resume : (argument : unknown) => IteratorResult<unknown, R>, argument : unknown, resumed : boolean) : IteratorResult<unknown, R> => {
50
104
  const previous = store.current;
51
105
  store.current = frame;
52
106
  try {
53
107
  const hooks = resumed ? store.hooks : undefined;
54
- const result = hooks === undefined
55
- ? resume(argument)
56
- : applyWithHooks(hooks, namedForHooks(generatorFunction, name), "await", resume, undefined, [argument]);
57
- const value : unknown = result.value;
58
- if (!result.done && ((typeof value === "object" && value !== null) || typeof value === "function")) {
59
- // Promise.resolve reads the "then" property of an object. Do it in the context of the body, as await does.
60
- // The result object is new for each step, so the change is not visible to other code.
61
- (result as { value : unknown }).value = promiseResolve(value);
62
- }
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]);
113
+ // The result object is new for each step, so the change is not visible to other code
114
+ (result as { value : unknown }).value = awaitable(result.value, NativePromise, result.done !== true);
63
115
  return result;
64
116
  } finally {
65
117
  frame = store.current;
66
- store.current = previous;
118
+ store.current = resumed ? previous : frame;
67
119
  }
68
120
  };
69
121
 
@@ -74,14 +126,15 @@ export function coroutine<T, A extends unknown[], R>(
74
126
  */
75
127
  const drive = async () : Promise<R> => {
76
128
  // The directive tells the Babel preset not to change this function (src/babel/skip-runtime.ts)
129
+ // Stryker disable next-line all: the directive matters only when a bundler applies the preset to the runtime
77
130
  "async-browser-context runtime";
78
131
  // In the driver, an error of the parameters rejects the promise, as with a native async function
79
- generator = generatorFunction.apply(this, args);
132
+ generator = Reflect.apply(generatorFunction, this, args);
80
133
  let result = step(next, undefined, false);
81
134
  while (result.done !== true) {
82
135
  let value : unknown;
83
136
  try {
84
- value = await result.value;
137
+ value = unbox(await result.value);
85
138
  } catch (error) {
86
139
  result = step(throwInto, error, true);
87
140
  continue;
@@ -92,58 +145,66 @@ export function coroutine<T, A extends unknown[], R>(
92
145
  };
93
146
  return drive();
94
147
  };
95
- }
96
-
97
- /** This function gives `true` for a value that can have a `then` property: an object or a function. */
98
- function isObject(value : unknown) : value is object {
99
- return (typeof value === "object" && value !== null) || typeof value === "function";
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;
100
151
  }
101
152
 
102
153
  /**
103
154
  * This function gives a function that makes an async generator object, which operates
104
155
  * `generatorFunction`. The preset gives this function in place of the helper
105
- * `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.
106
158
  *
107
159
  * Each step of the body operates in the context of the call that made the generator
108
160
  * (rule C5). The driver continues each step with a native `await` (`async-generator.ts`).
109
161
  */
110
162
  export function asyncGenerator<T, A extends unknown[]>(
111
163
  generatorFunction : (this : T, ...args : A) => Generator<unknown, unknown, unknown>,
164
+ name? : string,
112
165
  ) : (this : T, ...args : A) => AsyncGenerator<unknown, unknown, unknown> {
113
- const { Promise : NativePromise, promiseResolve } = store.intrinsics;
114
- return function makeAsyncGenerator(this : T, ...args : A) : AsyncGenerator<unknown, unknown, unknown> {
166
+ const NativePromise = store.intrinsics.Promise;
167
+ const makeAsyncGenerator = function makeAsyncGenerator(this : T, ...args : A) : AsyncGenerator<unknown, unknown, unknown> {
115
168
  let frame : Frame = store.current;
116
- const generator = generatorFunction.apply(this, args);
169
+ // An async generator that a hook makes does not start the hooks (store.ts, applyQuietly)
170
+ const quiet = store.inHook === true;
171
+ const generator = Reflect.apply(generatorFunction, this, args);
117
172
  const methods : Record<ResumeMethod, (argument : unknown) => IteratorResult<unknown, unknown>> = {
118
173
  next : (argument) => generator.next(argument),
119
174
  throw : (argument) => generator.throw(argument),
120
175
  return : (argument) => generator.return(argument),
121
176
  };
177
+ /** One step of the body in the context of the generator. The result stays the same: `yield*` gives the result of the delegate back. */
122
178
  const step = (key : ResumeMethod, argument : unknown, resumed : boolean) : IteratorResult<unknown, unknown> => {
123
179
  const previous = store.current;
124
180
  store.current = frame;
125
181
  try {
182
+ if (quiet) {
183
+ return applyQuietly(methods[key], undefined, [argument]);
184
+ }
126
185
  const hooks = resumed ? store.hooks : undefined;
127
- const result = hooks === undefined
186
+ return hooks === undefined
128
187
  ? methods[key](argument)
129
- : applyWithHooks(hooks, generatorFunction, "await", methods[key], undefined, [argument]);
130
- // Read the "then" property of an awaited or yielded object in the context of the body, as await and yield do
131
- const value : unknown = result.value;
132
- if (value instanceof OverloadYield) {
133
- if (isObject(value.v)) {
134
- value.v = promiseResolve(value.v);
135
- }
136
- } else if (isObject(value)) {
137
- (result as { value : unknown }).value = promiseResolve(value);
138
- }
139
- return result;
188
+ : applyWithHooks(hooks, namedForHooks(generatorFunction, name), "await", methods[key], undefined, [argument]);
140
189
  } finally {
141
190
  frame = store.current;
142
191
  store.current = previous;
143
192
  }
144
193
  };
145
- return createAsyncGenerator(step, NativePromise);
194
+ /** The value to await, in the context of the generator: `await` and `yield` read the `then` property of an object there. */
195
+ const prepare = (value : unknown) : unknown => {
196
+ const previous = store.current;
197
+ store.current = frame;
198
+ try {
199
+ return awaitable(value, NativePromise, true);
200
+ } finally {
201
+ store.current = previous;
202
+ }
203
+ };
204
+ return createAsyncGenerator(step, NativePromise, undefined, prepare);
146
205
  };
206
+ copyNameAndLength(makeAsyncGenerator, name, generatorFunction.length);
207
+ return makeAsyncGenerator;
147
208
  }
148
209
 
149
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
  }