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
@@ -2,22 +2,35 @@
2
2
  * The runtime of transformed code on Node.js. On Node.js, the native
3
3
  * `AsyncLocalStorage` keeps the context through promises, so `coroutine` is
4
4
  * a plain driver of the generator. `bindGenerator` keeps the context of the
5
- * generator creation (rule C5), with `AsyncLocalStorage.snapshot()`.
5
+ * generator creation (rule C5), with an `AsyncResource`.
6
+ *
7
+ * An `AsyncResource` records the context as `AsyncLocalStorage.snapshot()` does,
8
+ * but at a much lower cost. `snapshot()` is `AsyncResource.bind()`, which also
9
+ * defines properties on a new function (approximately 3 µs against 30 ns on
10
+ * Node.js 24). The drivers record the context again after each step.
6
11
  *
7
12
  * @packageDocumentation
8
13
  */
9
- import { AsyncLocalStorage } from "node:async_hooks";
14
+ import { AsyncResource } from "node:async_hooks";
10
15
  import { createAsyncGenerator, type ResumeKey } from "../core/async-generator.js";
16
+ import { copyNameAndLength } from "../core/function-name.js";
17
+
18
+ export { asyncGeneratorDelegate, awaitAsyncGenerator, OverloadYield } from "../core/async-generator.js";
11
19
 
12
- export { OverloadYield } from "../core/async-generator.js";
20
+ /** The type of the async resources of the generators, for async_hooks. */
21
+ const RESOURCE_TYPE = "async-browser-context:generator";
13
22
 
14
23
  /**
15
24
  * This function gives an async function that operates `generatorFunction`. The function is
16
25
  * a native async function: each `await` of the source becomes one native `await`, with
17
- * the same microtask turns. An error of the parameters rejects the promise.
26
+ * the same microtask turns. An error of the parameters rejects the promise. The function has the
27
+ * name and the length of the source, as in the browser runtime.
18
28
  */
19
- export function coroutine<T, A extends unknown[], R>(generatorFunction : (this : T, ...args : A) => Generator<unknown, R, unknown>) : (this : T, ...args : A) => Promise<R> {
20
- return async function asyncFunction(this : T, ...args : A) : Promise<R> {
29
+ export function coroutine<T, A extends unknown[], R>(
30
+ generatorFunction : (this : T, ...args : A) => Generator<unknown, R, unknown>,
31
+ name? : string,
32
+ ) : (this : T, ...args : A) => Promise<R> {
33
+ const asyncFunction = async function asyncFunction(this : T, ...args : A) : Promise<R> {
21
34
  // The directive tells the Babel preset not to change this function (src/babel/skip-runtime.ts)
22
35
  "async-browser-context runtime";
23
36
  const generator = generatorFunction.apply(this, args);
@@ -34,30 +47,35 @@ export function coroutine<T, A extends unknown[], R>(generatorFunction : (this :
34
47
  }
35
48
  return result.value;
36
49
  };
50
+ copyNameAndLength(asyncFunction, name, generatorFunction.length);
51
+ return asyncFunction;
37
52
  }
38
53
 
39
54
  /**
40
55
  * This function gives a function that makes an async generator object, which operates
41
56
  * `generatorFunction`. The preset gives it in place of the helper `wrapAsyncGenerator` of
42
- * Babel. The driver starts in a snapshot of the context of the creation (rule C5). The
43
- * native `AsyncLocalStorage` keeps that context through the `await` of the driver.
57
+ * Babel. The driver starts in the context of the creation (rule C5). The native
58
+ * `AsyncLocalStorage` keeps that context through the `await` of the driver.
44
59
  */
45
60
  export function asyncGenerator<T, A extends unknown[]>(
46
61
  generatorFunction : (this : T, ...args : A) => Generator<unknown, unknown, unknown>,
62
+ name? : string,
47
63
  ) : (this : T, ...args : A) => AsyncGenerator<unknown, unknown, unknown> {
48
- return function makeAsyncGenerator(this : T, ...args : A) : AsyncGenerator<unknown, unknown, unknown> {
49
- let snapshot = AsyncLocalStorage.snapshot();
64
+ const makeAsyncGenerator = function makeAsyncGenerator(this : T, ...args : A) : AsyncGenerator<unknown, unknown, unknown> {
65
+ let context = new AsyncResource(RESOURCE_TYPE);
50
66
  const generator = generatorFunction.apply(this, args);
51
67
  const step = (key : ResumeKey, argument : unknown) : IteratorResult<unknown, unknown> => {
52
68
  try {
53
69
  return generator[key](argument);
54
70
  } finally {
55
71
  // The body can change its context with enterWith before it stops
56
- snapshot = AsyncLocalStorage.snapshot();
72
+ context = new AsyncResource(RESOURCE_TYPE);
57
73
  }
58
74
  };
59
- return createAsyncGenerator(step, Promise, (start) => snapshot(start));
75
+ return createAsyncGenerator(step, Promise, (start) => context.runInAsyncScope(start));
60
76
  };
77
+ copyNameAndLength(makeAsyncGenerator, name, generatorFunction.length);
78
+ return makeAsyncGenerator;
61
79
  }
62
80
 
63
81
  type AnyIterator = Iterator<unknown, unknown, unknown> | AsyncIterator<unknown, unknown, unknown>;
@@ -65,14 +83,14 @@ type ResumeMethod = "next" | "throw" | "return";
65
83
 
66
84
  /** This function binds a generator object to the current context (rule C5). */
67
85
  export function bindGenerator<I extends AnyIterator>(generator : I) : I {
68
- let run = AsyncLocalStorage.snapshot();
86
+ let context = new AsyncResource(RESOURCE_TYPE);
69
87
  const target = generator as unknown as Record<ResumeMethod, (argument? : unknown) => unknown>;
70
- const resume = (method : ResumeMethod, argument : unknown) : unknown => run(() => {
88
+ const resume = (method : ResumeMethod, argument : unknown) : unknown => context.runInAsyncScope(() => {
71
89
  try {
72
90
  return target[method](argument);
73
91
  } finally {
74
92
  // The body can change its context with enterWith before it stops
75
- run = AsyncLocalStorage.snapshot();
93
+ context = new AsyncResource(RESOURCE_TYPE);
76
94
  }
77
95
  });
78
96
  const methods = {
@@ -10,6 +10,51 @@ export interface ContextStorage {
10
10
  /** The type of the context manager class. */
11
11
  export type AsyncContextManagerClass = new () => ContextManager;
12
12
 
13
+ type Listener = (...args : unknown[]) => unknown;
14
+
15
+ /** The guard of one emitter against nested adds: `true` while a patched add method operates. */
16
+ interface AddGuard {
17
+ adding : boolean;
18
+ }
19
+ type Method = (this : unknown, ...args : unknown[]) => unknown;
20
+
21
+ /** The methods of a Node.js EventEmitter that add a listener. */
22
+ const ADD_LISTENER_METHODS = ["addListener", "on", "once", "prependListener", "prependOnceListener"] as const;
23
+
24
+ /** The emitters and event targets that bind() patched. A second bind() keeps the first context, as the context managers of OpenTelemetry do. */
25
+ const boundTargets = new WeakSet<object>();
26
+
27
+ /** The bound listeners of one emitter or event target, for each event name. */
28
+ type ListenersByEvent = Record<PropertyKey, WeakMap<object, Listener> | undefined>;
29
+
30
+ /**
31
+ * The bound listeners of each emitter or event target, so that a remove method finds the bound listener.
32
+ * The event names are property keys, as in the EventEmitter of Node.js. Thus `1` and `"1"` are the same
33
+ * event name, as for the event target, which changes the type to a string.
34
+ */
35
+ const boundListeners = new WeakMap<object, ListenersByEvent>();
36
+
37
+ function listenersOf(target : object, event : unknown) : WeakMap<object, Listener> {
38
+ let byEvent = boundListeners.get(target);
39
+ if (byEvent === undefined) {
40
+ // The object has no prototype, thus the event name "constructor" gives no inherited value
41
+ byEvent = Object.create(null) as ListenersByEvent;
42
+ boundListeners.set(target, byEvent);
43
+ }
44
+ let listeners = byEvent[event as PropertyKey];
45
+ if (listeners === undefined) {
46
+ listeners = new WeakMap();
47
+ byEvent[event as PropertyKey] = listeners;
48
+ }
49
+ return listeners;
50
+ }
51
+
52
+ /** This function gives the bound listener of `listener`, or `undefined` if the add methods did not bind it. */
53
+ function boundListenerOf(target : object, event : unknown, listener : unknown) : Listener | undefined {
54
+ // For a key that is not an object, WeakMap.get() gives undefined
55
+ return boundListeners.get(target)?.[event as PropertyKey]?.get(listener as object);
56
+ }
57
+
13
58
  /**
14
59
  * This function makes the context manager class for one `AsyncLocalStorage`
15
60
  * class: the class of the browser runtime, or the native class of Node.js.
@@ -24,21 +69,42 @@ export function defineContextManager(createStorage : () => ContextStorage) : Asy
24
69
  return this.#storage.getStore() ?? ROOT_CONTEXT;
25
70
  }
26
71
 
27
- /** This method starts `fn` with `context` as the active context, also after each `await` in `fn`. */
72
+ /**
73
+ * This method starts `fn` with `context` as the active context, also after each `await` in `fn`.
74
+ * With `thisArg` `null` or `undefined`, `fn` gets `undefined` as its `this` value, as in OpenTelemetry.
75
+ */
28
76
  with<A extends unknown[], F extends (...args : A) => ReturnType<F>>(context : Context, fn : F, thisArg? : ThisParameterType<F>, ...args : A) : ReturnType<F> {
29
- return this.#storage.run(context, () => fn.apply(thisArg, args));
77
+ return this.#storage.run(context, () => Reflect.apply(fn, thisArg ?? undefined, args) as ReturnType<F>);
30
78
  }
31
79
 
32
- /** This method gives a function that starts `target` with `context` as the active context. Other values stay as they are. */
33
- bind<T>(context : Context, target : T) : T {
34
- if (typeof target !== "function") return target;
35
- const fn = target as unknown as (...args : unknown[]) => unknown;
36
- const run = (call : () => unknown) : unknown => this.with(context, call);
37
- const bound = function (this : unknown, ...args : unknown[]) : unknown {
38
- return run(() => fn.apply(this, args));
39
- };
40
- Object.defineProperty(bound, "length", { value : fn.length, configurable : true });
41
- return bound as T;
80
+ /**
81
+ * This method binds `target` to `context`, as the context managers of OpenTelemetry do:
82
+ *
83
+ * - A function gives a wrapper that starts it with `context` as the active context.
84
+ * - An event target (`addEventListener`) or a Node.js event emitter (`on`) gets a patch of
85
+ * its methods. Each listener that the program adds later operates with `context`, and the
86
+ * remove methods find the bound listener. A second `bind()` of the same object keeps the
87
+ * first context.
88
+ * - Other values stay as they are.
89
+ *
90
+ * Without a context, the method uses the active context.
91
+ */
92
+ bind<T>(context : Context | undefined, target : T) : T {
93
+ const bound = context ?? this.active();
94
+ if (typeof target === "function") {
95
+ return this.#bindFunction(bound, target as unknown as Listener) as T;
96
+ }
97
+ if (typeof target === "object" && target !== null && !boundTargets.has(target)) {
98
+ const methods = target as unknown as Record<string, unknown>;
99
+ if (typeof methods["addEventListener"] === "function") {
100
+ boundTargets.add(target);
101
+ this.#bindEventTarget(bound, target);
102
+ } else if (typeof methods["on"] === "function" || typeof methods["addListener"] === "function") {
103
+ boundTargets.add(target);
104
+ this.#bindEmitter(bound, target);
105
+ }
106
+ }
107
+ return target;
42
108
  }
43
109
 
44
110
  /** The manager is active when it exists. The method is for the `ContextManager` interface. */
@@ -46,10 +112,119 @@ export function defineContextManager(createStorage : () => ContextStorage) : Asy
46
112
  return this;
47
113
  }
48
114
 
49
- /** After this method, `active()` gives the root context until the next `with()`. */
115
+ /**
116
+ * After this method, `active()` gives the root context in the current code. With the
117
+ * browser runtime and with Node.js 22, it also gives the root context in all other code
118
+ * until the next `with()`. With Node.js 24 and its AsyncContextFrame, the native class
119
+ * changes only the current context, also for the callbacks that this context registered.
120
+ */
50
121
  disable() : this {
51
122
  this.#storage.disable();
52
123
  return this;
53
124
  }
125
+
126
+ /** With `guard`, the listener of an emitter clears the guard against nested adds while it operates (`#bindEmitter`). */
127
+ #bindFunction(context : Context, fn : Listener, guard? : AddGuard) : Listener {
128
+ const run = (call : () => unknown) : unknown => this.with(context, call);
129
+ const wrapper = function (this : unknown, ...args : unknown[]) : unknown {
130
+ if (guard === undefined) {
131
+ return run(() => Reflect.apply(fn, this, args));
132
+ }
133
+ // A listener of "newListener" can add listeners during an add: they also get the context
134
+ const outer = guard.adding;
135
+ guard.adding = false;
136
+ try {
137
+ return run(() => Reflect.apply(fn, this, args));
138
+ } finally {
139
+ guard.adding = outer;
140
+ }
141
+ };
142
+ Object.defineProperty(wrapper, "length", { value : fn.length, configurable : true });
143
+ return wrapper;
144
+ }
145
+
146
+ /** This method patches the methods of a Node.js event emitter, as `AsyncLocalStorageContextManager` of OpenTelemetry does. */
147
+ #bindEmitter(context : Context, emitter : object) : void {
148
+ const methods = emitter as Record<string, unknown>;
149
+ // `once` of Node.js adds its own wrapper with `this.on`. That inner add must not wrap again,
150
+ // else `removeListener` does not find the listener. OpenTelemetry has the same guard.
151
+ const guard : AddGuard = { adding : false };
152
+ for (const name of ADD_LISTENER_METHODS) {
153
+ const original = methods[name];
154
+ if (typeof original !== "function") {
155
+ continue;
156
+ }
157
+ const manager = this;
158
+ methods[name] = function (this : unknown, event : unknown, listener : unknown) : unknown {
159
+ if (guard.adding || typeof listener !== "function") {
160
+ return Reflect.apply(original as Method, this, arguments);
161
+ }
162
+ const listeners = listenersOf(emitter, event);
163
+ let wrapper = listeners.get(listener);
164
+ if (wrapper === undefined) {
165
+ wrapper = manager.#bindFunction(context, listener as Listener, guard);
166
+ listeners.set(listener, wrapper);
167
+ }
168
+ guard.adding = true;
169
+ try {
170
+ return Reflect.apply(original as Method, this, [event, wrapper]);
171
+ } finally {
172
+ guard.adding = false;
173
+ }
174
+ };
175
+ }
176
+ for (const name of ["removeListener", "off"] as const) {
177
+ const original = methods[name];
178
+ if (typeof original !== "function") {
179
+ continue;
180
+ }
181
+ methods[name] = function (this : unknown, event : unknown, listener : unknown) : unknown {
182
+ return Reflect.apply(original as Method, this, [event, boundListenerOf(emitter, event, listener) ?? listener]);
183
+ };
184
+ }
185
+ const removeAll = methods["removeAllListeners"];
186
+ if (typeof removeAll === "function") {
187
+ methods["removeAllListeners"] = function (this : unknown, event? : unknown) : unknown {
188
+ if (arguments.length === 0) {
189
+ boundListeners.delete(emitter);
190
+ } else {
191
+ delete boundListeners.get(emitter)?.[event as PropertyKey];
192
+ }
193
+ return Reflect.apply(removeAll as Method, this, arguments);
194
+ };
195
+ }
196
+ }
197
+
198
+ /** This method patches the methods of an event target, as `ZoneContextManager` of OpenTelemetry does. */
199
+ #bindEventTarget(context : Context, target : object) : void {
200
+ const methods = target as Record<string, unknown>;
201
+ const add = methods["addEventListener"] as Method;
202
+ const remove = methods["removeEventListener"];
203
+ const manager = this;
204
+ methods["addEventListener"] = function (this : unknown, type : unknown, listener : unknown) : unknown {
205
+ if (typeof listener !== "function") {
206
+ return Reflect.apply(add, this, arguments);
207
+ }
208
+ const listeners = listenersOf(target, type);
209
+ let wrapper = listeners.get(listener);
210
+ if (wrapper === undefined) {
211
+ wrapper = manager.#bindFunction(context, listener as Listener);
212
+ listeners.set(listener, wrapper);
213
+ }
214
+ const args = Array.prototype.slice.call(arguments) as unknown[];
215
+ args[1] = wrapper;
216
+ return Reflect.apply(add, this, args);
217
+ };
218
+ if (typeof remove === "function") {
219
+ methods["removeEventListener"] = function (this : unknown, type : unknown, listener : unknown) : unknown {
220
+ const wrapper = boundListenerOf(target, type, listener);
221
+ const args = Array.prototype.slice.call(arguments) as unknown[];
222
+ if (wrapper !== undefined) {
223
+ args[1] = wrapper;
224
+ }
225
+ return Reflect.apply(remove as Method, this, args);
226
+ };
227
+ }
228
+ }
54
229
  };
55
230
  }
@@ -1,4 +1,4 @@
1
- import { bindToFrame, store } from "../core/store.js";
1
+ import { bindToFrame, store, type Frame } from "../core/store.js";
2
2
  import { claim, globalPrototype, ownDataValue, replaceFunction, wrapFunctionArguments } from "./patch.js";
3
3
 
4
4
  type Method = (this : unknown, ...args : unknown[]) => unknown;
@@ -24,40 +24,91 @@ const PROTOTYPE_METHODS : readonly (readonly [string, readonly string[]])[] = [
24
24
  /** The static methods that get callbacks and use them later. */
25
25
  const STATIC_METHODS : readonly (readonly [string, readonly string[]])[] = [
26
26
  ["Notification", ["requestPermission"]],
27
- ["Array", ["fromAsync"]],
28
27
  ];
29
28
 
30
- /** `source` is the name of the method, for the callback hooks. */
29
+ /** `source` is the name of the method, for the callback hooks. The replacement is a method, as the native function. */
31
30
  function wrapArguments(source : string) : (original : Method) => Method {
32
- return (original) => function (this : unknown, ...args : unknown[]) : unknown {
33
- return original.apply(this, wrapFunctionArguments(args, source));
34
- };
31
+ return (original) => ({
32
+ method(this : unknown, ...args : unknown[]) : unknown {
33
+ return Reflect.apply(original, this, wrapFunctionArguments(args, source));
34
+ },
35
+ }).method;
35
36
  }
36
37
 
37
- /** `startViewTransition()` gets a callback, or an object with an `update` callback. */
38
- function wrapViewTransition(original : Method) : Method {
39
- const source = "Document.startViewTransition";
40
- return function (this : unknown, ...args : unknown[]) : unknown {
41
- const [first] = args;
42
- if (typeof first === "object" && first !== null && typeof (first as { update? : unknown }).update === "function") {
43
- const options = first as { update : Method };
44
- args[0] = { ...options, update : bindToFrame(store.current, options.update, source) };
45
- return original.apply(this, args);
46
- }
47
- return original.apply(this, wrapFunctionArguments(args, source));
48
- };
38
+ /**
39
+ * `Array.fromAsync(items, mapFn, thisArg)` uses only `mapFn` later. `items` and `thisArg` can
40
+ * also be functions, and they must not change.
41
+ */
42
+ function wrapFromAsync(original : Method) : Method {
43
+ return {
44
+ fromAsync(this : unknown) : unknown {
45
+ const mapFn : unknown = arguments[1];
46
+ if (typeof mapFn !== "function") {
47
+ return Reflect.apply(original, this, arguments);
48
+ }
49
+ const args = Array.prototype.slice.call(arguments) as unknown[];
50
+ args[1] = bindToFrame(store.current, mapFn as Method, "Array.fromAsync");
51
+ return Reflect.apply(original, this, args);
52
+ },
53
+ }.fromAsync;
54
+ }
55
+
56
+ /**
57
+ * This function gives a view of the dictionary `options` in which each key of `keys` gives a
58
+ * wrapper of its callback. The other members come from `options` with their getters and their
59
+ * prototype chain. The target of the Proxy is an empty object, so a frozen object also
60
+ * operates. The browser reads the members of a dictionary with [[Get]] only.
61
+ */
62
+ function withCallback(options : object, keys : readonly string[], frame : Frame, source : string) : object {
63
+ const wrappers = new Map<PropertyKey, Method>();
64
+ return new Proxy({}, {
65
+ get(_target, property) : unknown {
66
+ const value : unknown = Reflect.get(options, property, options);
67
+ if (typeof property !== "string" || !keys.includes(property) || typeof value !== "function") {
68
+ return value;
69
+ }
70
+ let wrapper = wrappers.get(property);
71
+ if (wrapper === undefined) {
72
+ wrapper = bindToFrame(frame, value as Method, source);
73
+ wrappers.set(property, wrapper);
74
+ }
75
+ return wrapper;
76
+ },
77
+ // For an engine that examines a member with the `in` operator first, as the streams of WebKit do
78
+ has(_target, property) : boolean {
79
+ return Reflect.has(options, property);
80
+ },
81
+ });
82
+ }
83
+
84
+ /** `startViewTransition()` gets a callback, or an object with an `update` callback. `source` names the class. */
85
+ function wrapViewTransition(source : string) : (original : Method) => Method {
86
+ return (original) => ({
87
+ startViewTransition(this : unknown) : unknown {
88
+ const first : unknown = arguments[0];
89
+ if (typeof first === "object" && first !== null) {
90
+ const args = Array.prototype.slice.call(arguments) as unknown[];
91
+ args[0] = withCallback(first, ["update"], store.current, source);
92
+ return Reflect.apply(original, this, args);
93
+ }
94
+ return Reflect.apply(original, this, wrapFunctionArguments(Array.prototype.slice.call(arguments) as unknown[], source));
95
+ },
96
+ }).startViewTransition;
49
97
  }
50
98
 
51
- /** `NavigateEvent.intercept()` gets an object with a `handler` callback. */
99
+ /** `NavigateEvent.intercept()` gets an object with a `handler` and a `precommitHandler` callback. */
52
100
  function wrapIntercept(original : Method) : Method {
53
- return function (this : unknown, ...args : unknown[]) : unknown {
54
- const [first] = args;
55
- if (typeof first === "object" && first !== null && typeof (first as { handler? : unknown }).handler === "function") {
56
- const options = first as { handler : Method };
57
- args[0] = { ...options, handler : bindToFrame(store.current, options.handler, "NavigateEvent.intercept") };
58
- }
59
- return original.apply(this, args);
60
- };
101
+ return {
102
+ intercept(this : unknown) : unknown {
103
+ const first : unknown = arguments[0];
104
+ if (typeof first === "object" && first !== null) {
105
+ const args = Array.prototype.slice.call(arguments) as unknown[];
106
+ args[0] = withCallback(first, ["handler", "precommitHandler"], store.current, "NavigateEvent.intercept");
107
+ return Reflect.apply(original, this, args);
108
+ }
109
+ return Reflect.apply(original, this, arguments);
110
+ },
111
+ }.intercept;
61
112
  }
62
113
 
63
114
  /** This function patches the callback APIs that are not events, timers or observers. */
@@ -83,9 +134,15 @@ export function installCallbackPatches() : void {
83
134
  replaceFunction<Method>(constructor, method, wrapArguments(`${constructorName}.${method}`));
84
135
  }
85
136
  }
86
- const documentPrototype = globalPrototype("Document");
87
- if (documentPrototype !== undefined) {
88
- replaceFunction<Method>(documentPrototype, "startViewTransition", wrapViewTransition);
137
+ const array = ownDataValue(globalThis, "Array");
138
+ if (typeof array === "function") {
139
+ replaceFunction<Method>(array, "fromAsync", wrapFromAsync);
140
+ }
141
+ for (const owner of ["Document", "Element"]) {
142
+ const prototype = globalPrototype(owner);
143
+ if (prototype !== undefined) {
144
+ replaceFunction<Method>(prototype, "startViewTransition", wrapViewTransition(`${owner}.startViewTransition`));
145
+ }
89
146
  }
90
147
  const navigateEventPrototype = globalPrototype("NavigateEvent");
91
148
  if (navigateEventPrototype !== undefined) {