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,4 +1,4 @@
1
- import { applyWithHooks, store, type Frame } from "../core/store.js";
1
+ import { applyQuietly, applyWithHooks, store, type Frame } from "../core/store.js";
2
2
  import { HANDLER_INTERFACES } from "./handler-interfaces.js";
3
3
  import { claim, globalPrototype, ownDataValue, rememberOriginal, replaceFunction } from "./patch.js";
4
4
 
@@ -20,28 +20,85 @@ type RemoveEventListener = typeof EventTarget.prototype.removeEventListener;
20
20
  type Handler = (this : unknown, ...args : unknown[]) => unknown;
21
21
 
22
22
  interface Registration {
23
- readonly frame : Frame;
24
23
  readonly wrapper : EventListener;
24
+ /** The DOM removes the listener when this signal aborts. */
25
+ readonly signal : AbortSignal | undefined;
26
+ /** `true` after a `once` listener operated, or after the abort of the signal. */
27
+ gone : boolean;
28
+ /** This function removes the abort listener of the registration from its signal. */
29
+ stopWatching : (() => void) | undefined;
30
+ }
31
+
32
+ /**
33
+ * The registrations of one type and capture flag of a target. The map of the listeners is weak.
34
+ * On Node.js, the native addEventListener with a signal adds an abort listener to the signal
35
+ * through the patched method, and keeps that listener only weakly. A strong map of a signal that
36
+ * lives long kept that listener, its target and the context in memory.
37
+ */
38
+ interface TypeEntry {
39
+ readonly listeners : WeakMap<Listener, Registration>;
40
+ /** The number of registrations in `listeners`. At 0, the target drops the entry, so many types do not fill the memory. */
41
+ size : number;
25
42
  }
26
43
 
27
44
  /** The registrations of each target: type and capture flag, then listener. */
28
- const registrations = new WeakMap<object, Map<string, Map<Listener, Registration>>>();
45
+ const registrations = new WeakMap<object, Map<string, TypeEntry>>();
46
+
47
+ /** This function removes the entry of a type when it has no registration. */
48
+ function dropIfEmpty(byKey : Map<string, TypeEntry>, key : string, entry : TypeEntry) : void {
49
+ if (entry.size <= 0 && byKey.get(key) === entry) {
50
+ byKey.delete(key);
51
+ }
52
+ }
53
+
54
+ /** This function removes `registration`, if it is the registration of `listener`, and the entry of its type when it is empty. */
55
+ function forget(byKey : Map<string, TypeEntry>, key : string, entry : TypeEntry, listener : Listener, registration : Registration) : void {
56
+ if (entry.listeners.get(listener) !== registration) {
57
+ return;
58
+ }
59
+ entry.listeners.delete(listener);
60
+ entry.size--;
61
+ dropIfEmpty(byKey, key, entry);
62
+ }
63
+
64
+ /** The options of an `addEventListener()` or `removeEventListener()` call, as the DOM reads them (WebIDL). */
65
+ interface ListenerOptions {
66
+ readonly capture : boolean;
67
+ readonly once : boolean;
68
+ readonly signal : AbortSignal | undefined;
69
+ }
70
+
71
+ function readOptions(options : unknown) : ListenerOptions {
72
+ if ((typeof options === "object" && options !== null) || typeof options === "function") {
73
+ const dictionary = options as { capture? : unknown; once? : unknown; signal? : unknown };
74
+ const signal = dictionary.signal;
75
+ return {
76
+ capture : Boolean(dictionary.capture),
77
+ once : Boolean(dictionary.once),
78
+ signal : signal === undefined || signal === null ? undefined : signal as AbortSignal,
79
+ };
80
+ }
81
+ // undefined and null give the default options. Another value is the capture flag.
82
+ return { capture : Boolean(options), once : false, signal : undefined };
83
+ }
29
84
 
30
- function keyOf(type : string, options : boolean | EventListenerOptions | undefined) : string {
31
- const capture = typeof options === "boolean" ? options : options?.capture === true;
32
- return `${type}\u0000${capture ? "1" : "0"}`;
85
+ function keyOf(type : unknown, capture : boolean) : string {
86
+ return `${String(type)}\u0000${capture ? "1" : "0"}`;
33
87
  }
34
88
 
35
89
  /** This function gives the frame for a listener call: the current frame, or the registration frame in the root context. */
36
90
  function frameForCall(registered : Frame) : Frame {
37
91
  const current = store.current;
38
- return current === store.root ? registered : current;
92
+ // After a top-level enterWith(), the default store stays current between tasks, as the root frame does
93
+ return current === store.root || current === store.idle ? registered : current;
39
94
  }
40
95
 
41
96
  /** `source` is `addEventListener:` and the event type, for the callback hooks. */
42
- function createWrapper(listener : Listener, frame : Frame, onFirstCall : (() => void) | undefined, source : string) : EventListener {
97
+ function createWrapper(listener : Listener, frame : Frame, onCall : (() => void) | undefined, source : string) : EventListener {
98
+ // A listener that a hook registers does not start the hooks
99
+ const quiet = store.inHook === true;
43
100
  return function asyncBrowserContextWrapper(this : unknown, event : Event) : unknown {
44
- onFirstCall?.();
101
+ onCall?.();
45
102
  const previous = store.current;
46
103
  store.current = frameForCall(frame);
47
104
  try {
@@ -54,9 +111,12 @@ function createWrapper(listener : Listener, frame : Frame, onFirstCall : (() =>
54
111
  fn = listener.handleEvent as Handler;
55
112
  thisValue = listener;
56
113
  }
114
+ if (quiet) {
115
+ return applyQuietly(fn, thisValue, [event]);
116
+ }
57
117
  const hooks = store.hooks;
58
118
  if (hooks === undefined || typeof fn !== "function") {
59
- return fn.call(thisValue, event);
119
+ return Reflect.apply(fn, thisValue, [event]);
60
120
  }
61
121
  return applyWithHooks(hooks, fn, source, fn, thisValue, [event]);
62
122
  } finally {
@@ -65,91 +125,170 @@ function createWrapper(listener : Listener, frame : Frame, onFirstCall : (() =>
65
125
  };
66
126
  }
67
127
 
128
+ /** A weak reference, or a strong one where the engine has no WeakRef. */
129
+ function weak<T extends object>(value : T) : { deref() : T | undefined } {
130
+ return typeof WeakRef === "function" ? new WeakRef(value) : { deref : () => value };
131
+ }
132
+
133
+ /** The place of a registration: the map of its target, its key, and the entry of its type. */
134
+ interface Place {
135
+ readonly byKey : Map<string, TypeEntry>;
136
+ readonly key : string;
137
+ readonly entry : TypeEntry;
138
+ }
139
+
140
+ /**
141
+ * This function removes `registration` when its signal aborts, as the DOM removes the listener.
142
+ * The abort listener keeps only weak references. Thus a signal that lives long does not keep the
143
+ * target, the listener or the context in memory.
144
+ */
145
+ function watchSignal(
146
+ signal : AbortSignal,
147
+ place : Place,
148
+ listener : Listener,
149
+ registration : Registration,
150
+ nativeAdd : AddEventListener,
151
+ nativeRemove : RemoveEventListener,
152
+ ) : void {
153
+ const byKeyRef = weak(place.byKey);
154
+ const entryRef = weak(place.entry);
155
+ const key = place.key;
156
+ const listenerRef = weak(listener);
157
+ const registrationRef = weak(registration);
158
+ const onAbort = () : void => {
159
+ const current = registrationRef.deref();
160
+ const registered = listenerRef.deref();
161
+ if (current === undefined || registered === undefined) {
162
+ return;
163
+ }
164
+ current.gone = true;
165
+ const byKey = byKeyRef.deref();
166
+ const entry = entryRef.deref();
167
+ if (byKey !== undefined && entry !== undefined) {
168
+ forget(byKey, key, entry, registered, current);
169
+ }
170
+ };
171
+ Reflect.apply(nativeAdd, signal, ["abort", onAbort, { once : true }]);
172
+ registration.stopWatching = () : void => {
173
+ Reflect.apply(nativeRemove, signal, ["abort", onAbort]);
174
+ };
175
+ }
176
+
177
+ /** This function gives the arguments of a call, with `wrapper` in place of the listener. The number of arguments stays the same. */
178
+ function withListener(args : IArguments, wrapper : EventListener) : unknown[] {
179
+ const copy = Array.prototype.slice.call(args) as unknown[];
180
+ copy[1] = wrapper;
181
+ return copy;
182
+ }
183
+
68
184
  function installListenerPatch() : void {
69
185
  const prototype = globalPrototype("EventTarget");
70
186
  if (prototype === undefined) {
71
187
  return;
72
188
  }
73
- replaceFunction<AddEventListener>(prototype, "addEventListener", (nativeAdd) => function addEventListener(
74
- this : EventTarget | null | undefined,
75
- type : string,
76
- listener : Listener | null,
77
- options? : boolean | AddEventListenerOptions,
78
- ) : void {
79
- const target = this ?? (globalThis as unknown as EventTarget);
80
- if (listener === null || (typeof listener !== "function" && typeof listener !== "object")) {
81
- nativeAdd.call(target, type, listener, options);
82
- return;
83
- }
84
- const key = keyOf(String(type), options);
85
- let byKey = registrations.get(target);
86
- if (byKey === undefined) {
87
- byKey = new Map();
88
- registrations.set(target, byKey);
89
- }
90
- let byListener = byKey.get(key);
91
- if (byListener === undefined) {
92
- byListener = new Map();
93
- byKey.set(key, byListener);
94
- }
95
- let registration = byListener.get(listener);
96
- if (registration === undefined) {
97
- const listeners = byListener;
98
- const forget = () : void => {
99
- if (listeners.get(listener) === registration) {
100
- listeners.delete(listener);
189
+ const nativeRemove = (prototype as { removeEventListener : RemoveEventListener }).removeEventListener;
190
+ // Method syntax: a native method has no prototype property and is not a constructor
191
+ replaceFunction<AddEventListener>(prototype, "addEventListener", (nativeAdd) => ({
192
+ addEventListener(this : EventTarget | null | undefined, type : string, listener : Listener | null, options? : boolean | AddEventListenerOptions) : void {
193
+ const target = this ?? (globalThis as unknown as EventTarget);
194
+ if (arguments.length < 2 || listener === null || (typeof listener !== "function" && typeof listener !== "object")) {
195
+ // The DOM gives its own error, or ignores a null listener
196
+ Reflect.apply(nativeAdd, target, arguments);
197
+ return;
198
+ }
199
+ const { capture, once, signal } = readOptions(options);
200
+ const key = keyOf(type, capture);
201
+ let byKey = registrations.get(target);
202
+ if (byKey === undefined) {
203
+ byKey = new Map();
204
+ registrations.set(target, byKey);
205
+ }
206
+ let entry = byKey.get(key);
207
+ if (entry === undefined) {
208
+ entry = { listeners : new WeakMap(), size : 0 };
209
+ byKey.set(key, entry);
210
+ }
211
+ const place : Place = { byKey, key, entry };
212
+ const existing = entry.listeners.get(listener);
213
+ if (existing !== undefined && !existing.gone && existing.signal?.aborted !== true) {
214
+ // The DOM ignores a second registration of the same listener, so the first context stays
215
+ Reflect.apply(nativeAdd, target, withListener(arguments, existing.wrapper));
216
+ return;
217
+ }
218
+ if (existing !== undefined) {
219
+ // The DOM removed the old registration: a once listener operated, or its signal aborted
220
+ existing.stopWatching?.();
221
+ entry.listeners.delete(listener);
222
+ entry.size--;
223
+ }
224
+ const registration : Registration = { wrapper : undefined as unknown as EventListener, signal, gone : false, stopWatching : undefined };
225
+ const onCall = once
226
+ ? () : void => {
227
+ registration.gone = true;
228
+ registration.stopWatching?.();
229
+ forget(place.byKey, place.key, place.entry, listener, registration);
101
230
  }
102
- };
103
- const once = typeof options === "object" && options.once === true;
104
- registration = { frame : store.current, wrapper : createWrapper(listener, store.current, once ? forget : undefined, `addEventListener:${String(type)}`) };
105
- listeners.set(listener, registration);
106
- const signal = typeof options === "object" ? options.signal : undefined;
231
+ : undefined;
232
+ (registration as { wrapper : EventListener }).wrapper = createWrapper(listener, store.current, onCall, `addEventListener:${String(type)}`);
233
+ try {
234
+ // The native method examines the options, and throws for an incorrect signal
235
+ Reflect.apply(nativeAdd, target, withListener(arguments, registration.wrapper));
236
+ } catch (error) {
237
+ dropIfEmpty(byKey, key, entry);
238
+ throw error;
239
+ }
240
+ if (signal?.aborted === true) {
241
+ // The DOM does not add a listener with an aborted signal
242
+ dropIfEmpty(byKey, key, entry);
243
+ return;
244
+ }
245
+ entry.listeners.set(listener, registration);
246
+ entry.size++;
107
247
  if (signal !== undefined) {
108
- if (signal.aborted) {
109
- forget();
110
- } else {
111
- nativeAdd.call(signal, "abort", forget, { once : true });
112
- }
248
+ watchSignal(signal, place, listener, registration, nativeAdd, nativeRemove);
113
249
  }
114
- }
115
- // The DOM ignores a second registration of the same wrapper, as it does for the same listener
116
- nativeAdd.call(target, type, registration.wrapper, options);
117
- } as AddEventListener);
250
+ },
251
+ }).addEventListener as AddEventListener);
118
252
 
119
- replaceFunction<RemoveEventListener>(prototype, "removeEventListener", (nativeRemove) => function removeEventListener(
120
- this : EventTarget | null | undefined,
121
- type : string,
122
- listener : Listener | null,
123
- options? : boolean | EventListenerOptions,
124
- ) : void {
125
- const target = this ?? (globalThis as unknown as EventTarget);
126
- if (listener !== null && (typeof listener === "function" || typeof listener === "object")) {
127
- const byListener = registrations.get(target)?.get(keyOf(String(type), options));
128
- const registration = byListener?.get(listener);
129
- if (registration !== undefined) {
130
- byListener?.delete(listener);
131
- nativeRemove.call(target, type, registration.wrapper, options);
132
- return;
253
+ replaceFunction<RemoveEventListener>(prototype, "removeEventListener", (native) => ({
254
+ removeEventListener(this : EventTarget | null | undefined, type : string, listener : Listener | null, options? : boolean | EventListenerOptions) : void {
255
+ const target = this ?? (globalThis as unknown as EventTarget);
256
+ if (arguments.length >= 2 && listener !== null && (typeof listener === "function" || typeof listener === "object")) {
257
+ const key = keyOf(type, readOptions(options).capture);
258
+ const byKey = registrations.get(target);
259
+ const entry = byKey?.get(key);
260
+ const registration = entry?.listeners.get(listener);
261
+ if (registration !== undefined && byKey !== undefined && entry !== undefined) {
262
+ registration.stopWatching?.();
263
+ forget(byKey, key, entry, listener, registration);
264
+ Reflect.apply(native, target, withListener(arguments, registration.wrapper));
265
+ return;
266
+ }
133
267
  }
134
- }
135
- nativeRemove.call(target, type, listener, options);
136
- } as RemoveEventListener);
268
+ Reflect.apply(native, target, arguments);
269
+ },
270
+ }).removeEventListener as RemoveEventListener);
137
271
  }
138
272
 
139
- /** The handler and its wrapper of each `on...` property of each target. */
140
- const handlers = new WeakMap<object, Map<string, { readonly handler : Handler; readonly wrapper : Handler }>>();
273
+ /** The handler of each wrapper of an `on...` property. The getter gives the handler in place of its wrapper. */
274
+ const handlerOfWrapper = new WeakMap<object, Handler>();
141
275
 
142
276
  /** `source` is the name of the `on...` property, for the callback hooks. */
143
277
  function createHandlerWrapper(handler : Handler, frame : Frame, source : string) : Handler {
144
- return function asyncBrowserContextWrapper(this : unknown, ...args : unknown[]) : unknown {
278
+ const quiet = store.inHook === true;
279
+ return function asyncBrowserContextWrapper(this : unknown) : unknown {
145
280
  const previous = store.current;
146
281
  store.current = frameForCall(frame);
147
282
  try {
283
+ if (quiet) {
284
+ return applyQuietly(handler, this, Array.prototype.slice.call(arguments) as unknown[]);
285
+ }
148
286
  const hooks = store.hooks;
149
287
  if (hooks === undefined) {
150
- return handler.apply(this, args);
288
+ // The arguments object gives the arguments without a new array
289
+ return Reflect.apply(handler, this, arguments);
151
290
  }
152
- return applyWithHooks(hooks, handler, source, handler, this, args);
291
+ return applyWithHooks(hooks, handler, source, handler, this, Array.prototype.slice.call(arguments) as unknown[]);
153
292
  } finally {
154
293
  store.current = previous;
155
294
  }
@@ -171,25 +310,19 @@ function patchHandlerProperties(owner : object) : void {
171
310
  const accessors = {
172
311
  get [name]() : unknown {
173
312
  const target = (this as object | undefined) ?? globalThis;
174
- const value : unknown = nativeGet.call(target);
175
- const entry = handlers.get(target)?.get(name);
176
- return entry !== undefined && entry.wrapper === value ? entry.handler : value;
313
+ const value : unknown = Reflect.apply(nativeGet, target, []);
314
+ // One map for all targets: the handlers of body and window give the same wrapper
315
+ return typeof value === "function" ? handlerOfWrapper.get(value) ?? value : value;
177
316
  },
178
317
  set [name](value : unknown) {
179
318
  const target = (this as object | undefined) ?? globalThis;
180
- let byName = handlers.get(target);
181
319
  if (typeof value !== "function") {
182
- byName?.delete(name);
183
- nativeSet.call(target, value);
320
+ Reflect.apply(nativeSet, target, [value]);
184
321
  return;
185
322
  }
186
- if (byName === undefined) {
187
- byName = new Map();
188
- handlers.set(target, byName);
189
- }
190
323
  const wrapper = createHandlerWrapper(value as Handler, store.current, name);
191
- byName.set(name, { handler : value as Handler, wrapper });
192
- nativeSet.call(target, wrapper);
324
+ handlerOfWrapper.set(wrapper, value as Handler);
325
+ Reflect.apply(nativeSet, target, [wrapper]);
193
326
  },
194
327
  };
195
328
  const replacement = Object.getOwnPropertyDescriptor(accessors, name);
@@ -227,28 +360,41 @@ function installHandlerPropertyPatch() : void {
227
360
  patchHandlerProperties(globalThis);
228
361
  }
229
362
 
230
- type LegacyListenerMethod = (this : unknown, callback : ((this : MediaQueryList, event : MediaQueryListEvent) => unknown) | null) => void;
363
+ type LegacyListenerMethod = (this : unknown, callback : Listener | null) => void;
231
364
 
232
- /** `MediaQueryList.addListener()` and `removeListener()` do not use the JavaScript `addEventListener()`. */
365
+ /**
366
+ * `MediaQueryList.addListener()` and `removeListener()` do not use the JavaScript `addEventListener()`.
367
+ * The patch gives each listener, also an object with `handleEvent`, to the patched methods of
368
+ * `EventTarget.prototype`, as the DOM does with the native methods.
369
+ */
233
370
  function installMediaQueryListPatch() : void {
234
371
  const prototype = globalPrototype("MediaQueryList");
235
- if (prototype === undefined) {
372
+ const eventTarget = globalPrototype("EventTarget") as { addEventListener : AddEventListener; removeEventListener : RemoveEventListener } | undefined;
373
+ if (prototype === undefined || eventTarget === undefined) {
236
374
  return;
237
375
  }
238
- replaceFunction<LegacyListenerMethod>(prototype, "addListener", (native) => function addListener(this : unknown, callback) : void {
239
- if (typeof callback === "function") {
240
- (this as MediaQueryList).addEventListener("change", callback);
241
- return;
242
- }
243
- native.call(this, callback);
244
- });
245
- replaceFunction<LegacyListenerMethod>(prototype, "removeListener", (native) => function removeListener(this : unknown, callback) : void {
246
- if (typeof callback === "function") {
247
- (this as MediaQueryList).removeEventListener("change", callback);
248
- return;
249
- }
250
- native.call(this, callback);
251
- });
376
+ const patchedAdd = eventTarget.addEventListener;
377
+ const patchedRemove = eventTarget.removeEventListener;
378
+ // The native method throws a TypeError for an object that is not a MediaQueryList
379
+ const isQueryList = (value : unknown) : boolean => typeof value === "object" && value !== null && Object.prototype.isPrototypeOf.call(prototype, value);
380
+ replaceFunction<LegacyListenerMethod>(prototype, "addListener", (native) => ({
381
+ addListener(this : unknown, callback : Listener | null) : void {
382
+ if (isQueryList(this) && (typeof callback === "function" || (typeof callback === "object" && callback !== null))) {
383
+ Reflect.apply(patchedAdd, this, ["change", callback]);
384
+ return;
385
+ }
386
+ Reflect.apply(native, this, arguments);
387
+ },
388
+ }).addListener);
389
+ replaceFunction<LegacyListenerMethod>(prototype, "removeListener", (native) => ({
390
+ removeListener(this : unknown, callback : Listener | null) : void {
391
+ if (isQueryList(this) && (typeof callback === "function" || (typeof callback === "object" && callback !== null))) {
392
+ Reflect.apply(patchedRemove, this, ["change", callback]);
393
+ return;
394
+ }
395
+ Reflect.apply(native, this, arguments);
396
+ },
397
+ }).removeListener);
252
398
  }
253
399
 
254
400
  /** This function installs the event patch (rule C13). */
@@ -2,8 +2,9 @@
2
2
  * The global interfaces whose prototype has its own `on...` properties. The
3
3
  * event patch reads only these globals. For each global that code reads for
4
4
  * the first time, the browser makes the interface object, and a page has
5
- * approximately 1,000 interfaces. Thus, a read of all globals costs 10 to 20
6
- * ms when the page loads, and this list costs 3 to 7 ms.
5
+ * approximately 1,000 interfaces. With a read of all globals (version 0.1),
6
+ * the patches took 16 to 22 ms when the page loaded. With this list, they
7
+ * take 7 to 8 ms (the medians in CHANGELOG.md, version 0.2.0).
7
8
  *
8
9
  * The list is the union of Chromium 156, Firefox 157 and WebKit 27.2 in a
9
10
  * secure context. It also has some interfaces of Safari, of mobile browsers
@@ -13,22 +13,26 @@ type Then = typeof Promise.prototype.then;
13
13
  *
14
14
  * `await` in native code does not use `then`. The Babel preset changes each
15
15
  * `await` so that the coroutine sets the context (rule C3).
16
+ *
17
+ * The patch starts the `then` that it replaces, as the other patches do. Thus a
18
+ * patch of `then` that another tool installed before stays in effect.
16
19
  */
17
20
  export function installPromisePatch() : void {
18
21
  if (!claim("Promise.prototype.then")) {
19
22
  return;
20
23
  }
21
- const nativeThen = store.intrinsics.promiseThen;
22
- replaceFunction<Then>(Promise.prototype, "then", () => function then<T, R1 = T, R2 = never>(
23
- this : Promise<T>,
24
- onFulfilled? : ((value : T) => R1 | PromiseLike<R1>) | null,
25
- onRejected? : ((reason : unknown) => R2 | PromiseLike<R2>) | null,
26
- ) : Promise<R1 | R2> {
27
- const frame = store.current;
28
- return nativeThen.call(
29
- this,
30
- typeof onFulfilled === "function" ? bindOneArgument(frame, onFulfilled, "Promise.then") : onFulfilled,
31
- typeof onRejected === "function" ? bindOneArgument(frame, onRejected, "Promise.then") : onRejected,
32
- ) as Promise<R1 | R2>;
33
- } as Then);
24
+ // Method syntax: a native method has no prototype property and is not a constructor
25
+ replaceFunction<Then>(Promise.prototype, "then", (original) => ({
26
+ then<T, R1 = T, R2 = never>(
27
+ this : Promise<T>,
28
+ onFulfilled? : ((value : T) => R1 | PromiseLike<R1>) | null,
29
+ onRejected? : ((reason : unknown) => R2 | PromiseLike<R2>) | null,
30
+ ) : Promise<R1 | R2> {
31
+ const frame = store.current;
32
+ return Reflect.apply(original, this, [
33
+ typeof onFulfilled === "function" ? bindOneArgument(frame, onFulfilled, "Promise.then") : onFulfilled,
34
+ typeof onRejected === "function" ? bindOneArgument(frame, onRejected, "Promise.then") : onRejected,
35
+ ]) as Promise<R1 | R2>;
36
+ },
37
+ }).then as Then);
34
38
  }
@@ -1,4 +1,4 @@
1
- import { applyWithHooks, store, type Frame } from "../core/store.js";
1
+ import { applyQuietly, applyWithHooks, store, type Frame } from "../core/store.js";
2
2
  import { claim, ownDataValue, rememberOriginal } from "./patch.js";
3
3
 
4
4
  /**
@@ -15,35 +15,55 @@ const STREAMS : readonly (readonly [string, readonly string[]])[] = [
15
15
  type Method = (this : unknown, ...args : unknown[]) => unknown;
16
16
 
17
17
  /**
18
- * This function gives an object that inherits from `underlying` and has a wrapper for each
19
- * method. The other properties, for example `type`, come from `underlying`.
20
- * Each method gets `underlying` as its `this` value, as the specification
21
- * tells.
18
+ * This function gives a view of `underlying` in which each method of `methods` is a wrapper.
19
+ * The view is a Proxy, so the other properties, for example `type`, come from `underlying`
20
+ * with their getters and private fields. The target of the Proxy is an empty object, so a
21
+ * frozen object also operates. The specification reads the members with [[Get]]. But the
22
+ * streams of WebKit first examine each member with the `in` operator, thus the `has` trap
23
+ * gives the answer of `underlying`. Each method gets `underlying` as its `this` value, as the
24
+ * specification tells.
22
25
  */
23
26
  function wrapUnderlying(underlying : object, methods : readonly string[], frame : Frame, name : string) : object {
24
- const wrapped = Object.create(underlying) as Record<string, unknown>;
25
- const properties = underlying as Record<string, unknown>;
26
- for (const method of methods) {
27
- const original = properties[method];
28
- if (typeof original !== "function") {
29
- continue;
27
+ // A method that a hook registers does not start the hooks
28
+ const quiet = store.inHook === true;
29
+ const wrappers = new Map<string, Method>();
30
+ const wrapperOf = (method : string, original : Method) : Method => {
31
+ let wrapper = wrappers.get(method);
32
+ if (wrapper !== undefined) {
33
+ return wrapper;
30
34
  }
31
35
  const source = `${name}.${method}`;
32
- wrapped[method] = function asyncBrowserContextWrapper(...args : unknown[]) : unknown {
36
+ wrapper = function asyncBrowserContextWrapper() : unknown {
33
37
  const previous = store.current;
34
38
  store.current = frame;
35
39
  try {
40
+ if (quiet) {
41
+ return applyQuietly(original, underlying, Array.prototype.slice.call(arguments) as unknown[]);
42
+ }
36
43
  const hooks = store.hooks;
37
44
  if (hooks === undefined) {
38
- return (original as Method).apply(underlying, args);
45
+ return Reflect.apply(original, underlying, arguments);
39
46
  }
40
- return applyWithHooks(hooks, original as Method, source, original as Method, underlying, args);
47
+ return applyWithHooks(hooks, original, source, original, underlying, Array.prototype.slice.call(arguments) as unknown[]);
41
48
  } finally {
42
49
  store.current = previous;
43
50
  }
44
51
  };
45
- }
46
- return wrapped;
52
+ wrappers.set(method, wrapper);
53
+ return wrapper;
54
+ };
55
+ return new Proxy({}, {
56
+ get(_target, property) : unknown {
57
+ const value : unknown = Reflect.get(underlying, property, underlying);
58
+ if (typeof property === "string" && typeof value === "function" && methods.includes(property)) {
59
+ return wrapperOf(property, value as Method);
60
+ }
61
+ return value;
62
+ },
63
+ has(_target, property) : boolean {
64
+ return Reflect.has(underlying, property);
65
+ },
66
+ });
47
67
  }
48
68
 
49
69
  /** This function patches the stream constructors. */
@@ -25,12 +25,24 @@ const PROTOTYPE_SCHEDULERS : readonly (readonly [string, string])[] = [
25
25
  ];
26
26
  // Stryker restore all
27
27
 
28
- /** `source` is the name of the scheduler, for the callback hooks. */
28
+ /**
29
+ * `source` is the name of the scheduler, for the callback hooks. The replacement is a method,
30
+ * so it has no prototype property and is not a constructor, as the native function. It gives
31
+ * the native function the same number of arguments, so `setTimeout()` without arguments
32
+ * throws as the native function does.
33
+ */
29
34
  function wrapFirstArgument(source : string) : (original : Scheduler) => Scheduler {
30
- return (original) => function (this : unknown, callback : unknown, ...rest : unknown[]) : unknown {
31
- const wrapped = typeof callback === "function" ? bindToFrame(store.current, callback as (...args : unknown[]) => unknown, source) : callback;
32
- return original.call(this, wrapped, ...rest);
33
- };
35
+ return (original) => ({
36
+ scheduler(this : unknown, callback : unknown) : unknown {
37
+ if (typeof callback !== "function") {
38
+ // A string callback of setTimeout, or no callback: the native function decides
39
+ return Reflect.apply(original, this, arguments);
40
+ }
41
+ const args = Array.prototype.slice.call(arguments) as unknown[];
42
+ args[0] = bindToFrame(store.current, callback as (...values : unknown[]) => unknown, source);
43
+ return Reflect.apply(original, this, args);
44
+ },
45
+ }).scheduler;
34
46
  }
35
47
 
36
48
  /**
@@ -7,15 +7,21 @@ type ToString = (this : unknown) => string;
7
7
  * This function patches `Function.prototype.toString`. For a patched function, the patch gives
8
8
  * the source text of the original function. Some libraries examine this text
9
9
  * to find native functions, and a changed text can stop them.
10
+ *
11
+ * The patch starts the `toString` that it replaces, as the other patches do. Thus a patch of
12
+ * `toString` that another tool installed before, for example to show the source of its own
13
+ * wrappers, stays in effect.
10
14
  */
11
15
  export function installToStringPatch() : void {
12
16
  if (!claim("Function.prototype.toString")) {
13
17
  return;
14
18
  }
15
- const nativeToString = store.intrinsics.functionToString;
16
- replaceFunction<ToString>(Function.prototype, "toString", () => function toString(this : unknown) : string {
17
- // WeakMap.get gives undefined for a primitive. The native function then throws its TypeError.
18
- const original = store.originals.get(this as object);
19
- return nativeToString.call(original ?? this);
20
- });
19
+ // Method syntax: a native method has no prototype property and is not a constructor
20
+ replaceFunction<ToString>(Function.prototype, "toString", (replaced) => ({
21
+ toString(this : unknown) : string {
22
+ // WeakMap.get gives undefined for a primitive. The native function then throws its TypeError.
23
+ const original = store.originals.get(this as object);
24
+ return Reflect.apply(replaced, original ?? this, []);
25
+ },
26
+ }).toString);
21
27
  }