mutts 1.0.8 → 1.0.10

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 (195) hide show
  1. package/README.md +77 -35
  2. package/dist/browser.cjs +2144 -5355
  3. package/dist/browser.cjs.map +1 -1
  4. package/dist/browser.d.ts +2 -1655
  5. package/dist/browser.dev.cjs +110 -0
  6. package/dist/browser.dev.cjs.map +1 -0
  7. package/dist/browser.dev.d.ts +2 -0
  8. package/dist/browser.dev.esm.js +5 -0
  9. package/dist/browser.dev.esm.js.map +1 -0
  10. package/dist/browser.esm.js +20 -107
  11. package/dist/browser.esm.js.map +1 -1
  12. package/dist/chunks/{async-browser-CA0jPWIi.cjs → async-browser-BU_IfxYD.cjs} +19 -107
  13. package/dist/chunks/async-browser-BU_IfxYD.cjs.map +1 -0
  14. package/dist/chunks/{async-core-UqHzvJ-S.cjs → async-core-CRLKP3l-.cjs} +8 -4
  15. package/dist/chunks/async-core-CRLKP3l-.cjs.map +1 -0
  16. package/dist/chunks/{async-node-BYHuGTni.cjs → async-node-3PrbVAbB.cjs} +7 -12
  17. package/dist/chunks/async-node-3PrbVAbB.cjs.map +1 -0
  18. package/dist/chunks/index-CaaQQlPJ.esm.js +3174 -0
  19. package/dist/chunks/index-CaaQQlPJ.esm.js.map +1 -0
  20. package/dist/chunks/node-nKJBk8iJ.esm.js +96 -0
  21. package/dist/chunks/node-nKJBk8iJ.esm.js.map +1 -0
  22. package/dist/chunks/proxy-Dtg-bJ3T.cjs +3763 -0
  23. package/dist/chunks/proxy-Dtg-bJ3T.cjs.map +1 -0
  24. package/dist/chunks/proxy-r7lARftl.esm.js +3701 -0
  25. package/dist/chunks/proxy-r7lARftl.esm.js.map +1 -0
  26. package/dist/debug.cjs +980 -0
  27. package/dist/debug.cjs.map +1 -0
  28. package/dist/debug.d.ts +208 -0
  29. package/dist/debug.esm.js +950 -0
  30. package/dist/debug.esm.js.map +1 -0
  31. package/dist/devtools/manifest.json +1 -1
  32. package/dist/devtools/panel.html +1 -1
  33. package/dist/devtools/panel.js +107 -94
  34. package/dist/devtools/panel.js.map +1 -1
  35. package/dist/index.d.ts +1447 -13
  36. package/dist/mutts.umd.js +7167 -1
  37. package/dist/mutts.umd.js.map +1 -1
  38. package/dist/mutts.umd.min.js +1 -1
  39. package/dist/mutts.umd.min.js.map +1 -1
  40. package/dist/node.cjs +70 -66
  41. package/dist/node.cjs.map +1 -1
  42. package/dist/node.d.ts +2 -1
  43. package/dist/node.dev.cjs +110 -0
  44. package/dist/node.dev.cjs.map +1 -0
  45. package/dist/node.dev.d.ts +2 -0
  46. package/dist/node.dev.esm.js +6 -0
  47. package/dist/node.dev.esm.js.map +1 -0
  48. package/dist/node.esm.js +4 -103
  49. package/dist/node.esm.js.map +1 -1
  50. package/dist/{reactive/types.d.ts → types-W5vD6m2n.d.ts} +186 -93
  51. package/docs/ai/api-reference.md +12 -19
  52. package/docs/ai/manual.md +521 -17
  53. package/docs/events.md +57 -2
  54. package/docs/flavored.md +210 -0
  55. package/docs/reactive/advanced.md +314 -5
  56. package/docs/reactive/attend.md +142 -0
  57. package/docs/reactive/collections.md +76 -39
  58. package/docs/reactive/core.md +100 -14
  59. package/docs/reactive/debugging.md +123 -18
  60. package/docs/reactive/error-handling.md +121 -0
  61. package/docs/reactive/resource.md +125 -0
  62. package/docs/reactive/scan.md +247 -1
  63. package/docs/reactive.md +4 -1
  64. package/docs/std-decorators.md +102 -51
  65. package/docs/utils.md +70 -0
  66. package/docs/zone.md +3 -7
  67. package/package.json +64 -30
  68. package/dist/async/browser.d.ts +0 -2
  69. package/dist/async/browser.d.ts.map +0 -1
  70. package/dist/async/index.d.ts +0 -18
  71. package/dist/async/index.d.ts.map +0 -1
  72. package/dist/async/node.d.ts +0 -2
  73. package/dist/async/node.d.ts.map +0 -1
  74. package/dist/chunks/async-browser-CA0jPWIi.cjs.map +0 -1
  75. package/dist/chunks/async-core-UqHzvJ-S.cjs.map +0 -1
  76. package/dist/chunks/async-node-BYHuGTni.cjs.map +0 -1
  77. package/dist/chunks/index-DhaOVusv.esm.js +0 -6411
  78. package/dist/chunks/index-DhaOVusv.esm.js.map +0 -1
  79. package/dist/decorator.d.ts +0 -106
  80. package/dist/decorator.d.ts.map +0 -1
  81. package/dist/destroyable.d.ts +0 -87
  82. package/dist/destroyable.d.ts.map +0 -1
  83. package/dist/entry-browser.d.ts +0 -3
  84. package/dist/entry-browser.d.ts.map +0 -1
  85. package/dist/entry-node.d.ts +0 -3
  86. package/dist/entry-node.d.ts.map +0 -1
  87. package/dist/eventful.d.ts +0 -18
  88. package/dist/eventful.d.ts.map +0 -1
  89. package/dist/index.d.ts.map +0 -1
  90. package/dist/indexable.d.ts +0 -243
  91. package/dist/indexable.d.ts.map +0 -1
  92. package/dist/introspection.d.ts +0 -27
  93. package/dist/introspection.d.ts.map +0 -1
  94. package/dist/iterableWeak.d.ts +0 -53
  95. package/dist/iterableWeak.d.ts.map +0 -1
  96. package/dist/mixins.d.ts +0 -25
  97. package/dist/mixins.d.ts.map +0 -1
  98. package/dist/promiseChain.d.ts +0 -20
  99. package/dist/promiseChain.d.ts.map +0 -1
  100. package/dist/reactive/array.d.ts +0 -49
  101. package/dist/reactive/array.d.ts.map +0 -1
  102. package/dist/reactive/buffer.d.ts +0 -44
  103. package/dist/reactive/buffer.d.ts.map +0 -1
  104. package/dist/reactive/change.d.ts +0 -29
  105. package/dist/reactive/change.d.ts.map +0 -1
  106. package/dist/reactive/debug.d.ts +0 -111
  107. package/dist/reactive/debug.d.ts.map +0 -1
  108. package/dist/reactive/deep-touch.d.ts +0 -28
  109. package/dist/reactive/deep-touch.d.ts.map +0 -1
  110. package/dist/reactive/deep-watch-state.d.ts +0 -25
  111. package/dist/reactive/deep-watch-state.d.ts.map +0 -1
  112. package/dist/reactive/deep-watch.d.ts +0 -19
  113. package/dist/reactive/deep-watch.d.ts.map +0 -1
  114. package/dist/reactive/effect-context.d.ts +0 -7
  115. package/dist/reactive/effect-context.d.ts.map +0 -1
  116. package/dist/reactive/effects.d.ts +0 -151
  117. package/dist/reactive/effects.d.ts.map +0 -1
  118. package/dist/reactive/index.d.ts +0 -20
  119. package/dist/reactive/index.d.ts.map +0 -1
  120. package/dist/reactive/interface.d.ts +0 -64
  121. package/dist/reactive/interface.d.ts.map +0 -1
  122. package/dist/reactive/map.d.ts +0 -30
  123. package/dist/reactive/map.d.ts.map +0 -1
  124. package/dist/reactive/memoize.d.ts +0 -5
  125. package/dist/reactive/memoize.d.ts.map +0 -1
  126. package/dist/reactive/non-reactive-state.d.ts +0 -9
  127. package/dist/reactive/non-reactive-state.d.ts.map +0 -1
  128. package/dist/reactive/non-reactive.d.ts +0 -11
  129. package/dist/reactive/non-reactive.d.ts.map +0 -1
  130. package/dist/reactive/project.d.ts +0 -41
  131. package/dist/reactive/project.d.ts.map +0 -1
  132. package/dist/reactive/proxy-state.d.ts +0 -8
  133. package/dist/reactive/proxy-state.d.ts.map +0 -1
  134. package/dist/reactive/proxy.d.ts +0 -23
  135. package/dist/reactive/proxy.d.ts.map +0 -1
  136. package/dist/reactive/record.d.ts +0 -116
  137. package/dist/reactive/record.d.ts.map +0 -1
  138. package/dist/reactive/register.d.ts +0 -64
  139. package/dist/reactive/register.d.ts.map +0 -1
  140. package/dist/reactive/registry.d.ts +0 -20
  141. package/dist/reactive/registry.d.ts.map +0 -1
  142. package/dist/reactive/set.d.ts +0 -28
  143. package/dist/reactive/set.d.ts.map +0 -1
  144. package/dist/reactive/tracking.d.ts +0 -7
  145. package/dist/reactive/tracking.d.ts.map +0 -1
  146. package/dist/reactive/types.d.ts.map +0 -1
  147. package/dist/std-decorators.d.ts +0 -50
  148. package/dist/std-decorators.d.ts.map +0 -1
  149. package/dist/utils.d.ts +0 -49
  150. package/dist/utils.d.ts.map +0 -1
  151. package/dist/zone.d.ts +0 -40
  152. package/dist/zone.d.ts.map +0 -1
  153. package/docs/reactive/project.md +0 -93
  154. package/src/async/browser.ts +0 -319
  155. package/src/async/index.ts +0 -23
  156. package/src/async/node.ts +0 -104
  157. package/src/decorator.ts +0 -272
  158. package/src/destroyable.ts +0 -199
  159. package/src/entry-browser.ts +0 -5
  160. package/src/entry-node.ts +0 -5
  161. package/src/eventful.ts +0 -77
  162. package/src/index.d.ts +0 -12
  163. package/src/index.ts +0 -64
  164. package/src/indexable.ts +0 -526
  165. package/src/introspection.ts +0 -59
  166. package/src/iterableWeak.ts +0 -233
  167. package/src/mixins.ts +0 -123
  168. package/src/promiseChain.ts +0 -110
  169. package/src/reactive/array.ts +0 -507
  170. package/src/reactive/buffer.ts +0 -168
  171. package/src/reactive/change.ts +0 -138
  172. package/src/reactive/debug.ts +0 -517
  173. package/src/reactive/deep-touch.ts +0 -268
  174. package/src/reactive/deep-watch-state.ts +0 -82
  175. package/src/reactive/deep-watch.ts +0 -168
  176. package/src/reactive/effect-context.ts +0 -18
  177. package/src/reactive/effects.ts +0 -1382
  178. package/src/reactive/index.ts +0 -75
  179. package/src/reactive/interface.ts +0 -210
  180. package/src/reactive/map.ts +0 -158
  181. package/src/reactive/memoize.ts +0 -163
  182. package/src/reactive/non-reactive-state.ts +0 -49
  183. package/src/reactive/non-reactive.ts +0 -43
  184. package/src/reactive/project.ts +0 -453
  185. package/src/reactive/proxy-state.ts +0 -27
  186. package/src/reactive/proxy.ts +0 -264
  187. package/src/reactive/record.ts +0 -196
  188. package/src/reactive/register.ts +0 -419
  189. package/src/reactive/registry.ts +0 -59
  190. package/src/reactive/set.ts +0 -130
  191. package/src/reactive/tracking.ts +0 -44
  192. package/src/reactive/types.ts +0 -440
  193. package/src/std-decorators.ts +0 -217
  194. package/src/utils.ts +0 -301
  195. package/src/zone.ts +0 -138
@@ -1,93 +0,0 @@
1
- # Reactive Register Memoization Notes
2
-
3
- ## Background
4
-
5
- - Register entries are stored in a reactive `Map`. Updating an entry via `Map.set` marks the entire value as changed.
6
- - Memoized computations that read through `map.get(key)` re-execute fully when the entry changes, even if only a nested property is touched.
7
- - The goal for rendering lists in a JSX/HTML engine is to avoid rebuilding DOM nodes; only the affected properties should update.
8
-
9
- ## Evolution: From `organized` to `project`
10
-
11
- ### Initial State
12
-
13
- - `memoize` caches results but invalidates on `Map.set`, so large effects still re-run.
14
- - `organized` (designed for `Record` sources) creates per-key effects so downstream work reruns only for the touched key; this matches the desired behaviour.
15
- - **Gap:** `organized` operates on plain objects: key enumeration relies on property iteration and `FoolProof.get/set`. Registers and other keyed collections (`Map`, `Register`, custom stores) need the same per-entry orchestration without converting to records.
16
-
17
- ### Completed Evolution: `project` Implementation
18
-
19
- We implemented `project` as a generalized transformation helper that works across arrays, records, and maps:
20
-
21
- **Key Design Decisions:**
22
- - **Unified API:** Single `project` function with runtime dispatch to `project.array`, `project.record`, or `project.map` based on source type.
23
- - **Access Pattern:** Callback receives a `ProjectAccess` object with `get()`, `set()`, `key`, `source`, and `value` (computed property) - similar to `organized` but returning a value instead of an effect.
24
- - **Automatic Target Creation:** The function always creates its own reactive target container (array, record, or map) - no `baseTarget` parameter needed.
25
- - **Per-Key Effects:** Each source key/index gets its own reactive effect that recomputes only when that specific entry changes, enabling granular updates for rendering pipelines.
26
-
27
- **Current API:**
28
- ```typescript
29
- project.array(source: readonly T[], apply: (access, target) => U): ProjectResult<U[]>
30
- project.record(source: Record<K, T>, apply: (access, target) => U): ProjectResult<Record<K, U>>
31
- project.map(source: Map<K, T>, apply: (access, target) => U): ProjectResult<Map<K, U>>
32
- ```
33
-
34
- **Current Behavior:**
35
- - Eager computation: all entries are computed immediately when keys are present.
36
- - One-way transformation: callback only handles "get" (read) operations; no write-back support.
37
- - Mutable results: returned arrays/records/maps are fully mutable.
38
- - `ProjectAccess.old` exposes the previously computed result for each entry, enabling incremental updates and state preservation.
39
-
40
- ## Future Evolutions
41
-
42
- ### Bidirectional Transformation (Set Callback)
43
-
44
- **Goal:** Support writing back to the source through the projected object.
45
-
46
- **Implementation:**
47
- - Add optional second callback parameter: `set: (access, newValue, target) => void | boolean`
48
- - When `set` is provided, mutations to the projected object trigger the set callback.
49
- - The callback receives the same `ProjectAccess` object plus the new value, allowing it to update the source.
50
- - If `set` returns `false` or throws, the mutation is rejected.
51
-
52
- **API Impact:**
53
- ```typescript
54
- project.array(
55
- source: readonly T[],
56
- apply: (access, target) => U,
57
- set?: (access, newValue: U, target) => void | boolean
58
- ): ProjectResult<U[]>
59
- ```
60
-
61
- ### Readonly Results When No Set Callback
62
-
63
- **Goal:** Make projected objects readonly when no write-back is supported.
64
-
65
- **Implementation:**
66
- - When `set` callback is not provided, wrap the result in a readonly proxy or use read-only array/record types.
67
- - Prevents accidental mutations that would have no effect on the source.
68
- - Type system should reflect readonly nature in return types.
69
-
70
- **API Impact:**
71
- - Return type becomes `ProjectResult<readonly U[]>` or similar when `set` is omitted.
72
- - Arrays use `ReactiveReadOnlyArray` (already exists in `mapped.ts`).
73
- - Records and maps need readonly wrappers or proxy-based protection.
74
-
75
- ## Implementation Notes for AI Agents
76
-
77
- **Current State:**
78
- - `project` is fully functional for arrays, records, maps, and registers with eager, one-way transformation.
79
- - Tests cover per-key reactivity, key addition/removal, automatic helper selection, and `access.old` value propagation.
80
- - The implementation follows the same per-key effect pattern as `organized` but returns computed values.
81
-
82
- **Future Work:**
83
- - Lazy computing requires careful effect lifecycle management to avoid memory leaks.
84
- - Bidirectional support needs to handle edge cases (concurrent reads/writes, validation).
85
- - Readonly enforcement should align with existing `ReactiveReadOnlyArray` patterns where possible.
86
- - Consider whether these features should be opt-in via options object or separate function variants.
87
-
88
- **Related Files:**
89
- - `src/reactive/project.ts` - Main implementation
90
- - `src/reactive/mapped.ts` - Reference for `ReactiveReadOnlyArray` pattern
91
- - `src/reactive/record.ts` - Reference for `organized` pattern (different use case)
92
- - `tests/reactive/project.test.ts` - Test coverage
93
-
@@ -1,319 +0,0 @@
1
- import { Hook, Restorer, asyncHooks } from '.'
2
-
3
- const hooks = new Set<Hook>()
4
- const promiseContexts = new WeakMap<Promise<any>, Set<Restorer>>()
5
-
6
- asyncHooks.addHook = function (hook: Hook) {
7
- hooks.add(hook)
8
- return () => {
9
- hooks.delete(hook)
10
- }
11
- }
12
-
13
- // [HACK]: Sanitization
14
- // If a Promise is created inside the zone, it carries the "Sticky" zone context.
15
- // If returned to the outer scope, that context leaks. We wrap it in a new Promise
16
- // created here (in the outer scope) to break the chain and sanitize the return value.
17
- // See BROWSER_ASYNC_POLYFILL.md for full details.
18
- asyncHooks.sanitizePromise = (res: any) => {
19
- if (res && typeof (res as any).then === 'function') {
20
- return new Promise((resolve, reject) => {
21
- setTimeout(() => {
22
- (res as any).then(resolve, reject)
23
- }, 0)
24
- })
25
- }
26
- return res
27
- }
28
-
29
- function captureRestorers() {
30
- const restorers = new Set<Restorer>()
31
- for (const hook of hooks) {
32
- const restorer = hook()
33
- if (restorer) restorers.add(restorer)
34
- }
35
- return restorers
36
- }
37
-
38
- function wrap<Args extends any[], R>(fn: ((...args: Args) => R) | null | undefined, capturedRestorers?: Set<Restorer>) {
39
- if (typeof fn !== 'function') return fn
40
- const restorers = capturedRestorers || captureRestorers()
41
- return function (this: any, ...args: Args) {
42
- const undoers: (() => void)[] = []
43
- for (const restore of restorers) undoers.push(restore())
44
- try {
45
- return fn.apply(this, args)
46
- } finally {
47
- if (originals.queueMicrotask) {
48
- // Double microtask ensures we run after the first await resumption microtask
49
- originals.queueMicrotask.call(globalThis, () => {
50
- originals.queueMicrotask.call(globalThis, () => {
51
- originals.queueMicrotask.call(globalThis, () => {
52
- for (let i = undoers.length - 1; i >= 0; i--) undoers[i]()
53
- })
54
- })
55
- })
56
- } else {
57
- for (let i = undoers.length - 1; i >= 0; i--) undoers[i]()
58
- }
59
- }
60
- }
61
- }
62
-
63
- const targetWrappers = new WeakMap<any, Map<string, WeakMap<Function, Function>>>()
64
-
65
- function patchEventTarget(proto: any) {
66
- if (!proto || !proto.addEventListener || !proto.removeEventListener) return
67
- const nativeAdd = proto.addEventListener
68
- const nativeRemove = proto.removeEventListener
69
-
70
- proto.addEventListener = function (this: any, type: string, listener: any, options: any) {
71
- if (typeof listener !== 'function') {
72
- return nativeAdd.call(this, type, listener, options)
73
- }
74
-
75
- let types = targetWrappers.get(this)
76
- if (!types) {
77
- types = new Map()
78
- targetWrappers.set(this, types)
79
- }
80
- let listeners = types.get(type)
81
- if (!listeners) {
82
- listeners = new WeakMap()
83
- types.set(type, listeners)
84
- }
85
-
86
- let wrapped = listeners.get(listener)
87
- if (!wrapped) {
88
- wrapped = wrap(listener)
89
- listeners.set(listener, wrapped)
90
- }
91
-
92
- return nativeAdd.call(this, type, wrapped, options)
93
- }
94
-
95
- proto.removeEventListener = function (this: any, type: string, listener: any, options: any) {
96
- if (typeof listener !== 'function') {
97
- return nativeRemove.call(this, type, listener, options)
98
- }
99
-
100
- const types = targetWrappers.get(this)
101
- if (types) {
102
- const listeners = types.get(type)
103
- if (listeners) {
104
- const wrapped = listeners.get(listener)
105
- if (wrapped) {
106
- return nativeRemove.call(this, type, wrapped, options)
107
- }
108
- }
109
- }
110
-
111
- return nativeRemove.call(this, type, listener, options)
112
- }
113
- }
114
-
115
- function patchOnProperties(proto: any) {
116
- if (!proto) return
117
- for (const prop of Object.getOwnPropertyNames(proto)) {
118
- if (prop.startsWith('on')) {
119
- const desc = Object.getOwnPropertyDescriptor(proto, prop)
120
- if (desc && desc.set && desc.configurable) {
121
- const nativeSet = desc.set
122
- Object.defineProperty(proto, prop, {
123
- ...desc,
124
- set: function (this: any, fn: any) {
125
- nativeSet.call(this, wrap(fn))
126
- }
127
- })
128
- }
129
- }
130
- }
131
- }
132
-
133
- if (typeof EventTarget !== 'undefined') {
134
- patchEventTarget(EventTarget.prototype)
135
- }
136
-
137
- const prototypesToPatch = [
138
- typeof EventTarget !== 'undefined' && EventTarget.prototype,
139
- typeof HTMLElement !== 'undefined' && HTMLElement.prototype,
140
- typeof Window !== 'undefined' && Window.prototype,
141
- typeof Document !== 'undefined' && Document.prototype,
142
- typeof MessagePort !== 'undefined' && MessagePort.prototype,
143
- typeof XMLHttpRequest !== 'undefined' && XMLHttpRequest.prototype,
144
- typeof IDBRequest !== 'undefined' && IDBRequest.prototype,
145
- typeof IDBTransaction !== 'undefined' && IDBTransaction.prototype,
146
- typeof IDBDatabase !== 'undefined' && IDBDatabase.prototype,
147
- typeof FileReader !== 'undefined' && FileReader.prototype,
148
- typeof AbortSignal !== 'undefined' && AbortSignal.prototype,
149
- ]
150
-
151
- for (const proto of prototypesToPatch) {
152
- if (proto) {
153
- patchOnProperties(proto)
154
- }
155
- }
156
-
157
- const GLOBAL_ORIGINALS = Symbol.for('mutts.originals');
158
- const GLOBAL_PROMISE = Symbol.for('mutts.OriginalPromise');
159
-
160
- let originals: any;
161
- let OriginalPromise: any;
162
-
163
- if ((globalThis as any)[GLOBAL_ORIGINALS]) {
164
- originals = (globalThis as any)[GLOBAL_ORIGINALS];
165
- OriginalPromise = (globalThis as any)[GLOBAL_PROMISE];
166
- } else {
167
- OriginalPromise = globalThis.Promise;
168
- originals = {
169
- then: OriginalPromise.prototype.then,
170
- catch: OriginalPromise.prototype.catch,
171
- finally: OriginalPromise.prototype.finally,
172
- resolve: OriginalPromise.resolve,
173
- reject: OriginalPromise.reject,
174
- all: OriginalPromise.all,
175
- allSettled: (OriginalPromise as any).allSettled,
176
- race: OriginalPromise.race,
177
- any: (OriginalPromise as any).any,
178
- setTimeout: globalThis.setTimeout,
179
- setInterval: globalThis.setInterval,
180
- setImmediate: (globalThis as any).setImmediate,
181
- requestAnimationFrame: (globalThis as any).requestAnimationFrame,
182
- queueMicrotask: globalThis.queueMicrotask,
183
- };
184
- (globalThis as any)[GLOBAL_ORIGINALS] = originals;
185
- (globalThis as any)[GLOBAL_PROMISE] = OriginalPromise;
186
- }
187
-
188
- // Ensure modern statics are captured even if originals was cached from an older version
189
- if (!originals.allSettled) originals.allSettled = (OriginalPromise as any).allSettled
190
- if (!originals.any) originals.any = (OriginalPromise as any).any
191
- if (!originals.race) originals.race = OriginalPromise.race
192
-
193
- function patchedThen(this: any, onFulfilled: any, onRejected: any) {
194
- const context = promiseContexts.get(this) || captureRestorers()
195
- const nextPromise = originals.then.call(this, wrap(onFulfilled, context), wrap(onRejected, context))
196
- if (context.size > 0) promiseContexts.set(nextPromise, context)
197
- return nextPromise
198
- }
199
-
200
- function patchedCatch(this: any, onRejected: any) {
201
- const context = promiseContexts.get(this) || captureRestorers()
202
- const nextPromise = originals.catch.call(this, wrap(onRejected, context))
203
- if (context.size > 0) promiseContexts.set(nextPromise, context)
204
- return nextPromise
205
- }
206
-
207
- function patchedFinally(this: any, onFinally: any) {
208
- const context = promiseContexts.get(this) || captureRestorers()
209
- const nextPromise = originals.finally.call(this, wrap(onFinally, context))
210
- if (context.size > 0) promiseContexts.set(nextPromise, context)
211
- return nextPromise
212
- }
213
-
214
- function PatchedPromise<T>(this: any, executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) {
215
- if (typeof executor === 'function') {
216
- const p = new OriginalPromise((resolve, reject) => {
217
- const wrappedResolve = wrap(resolve)
218
- const wrappedReject = wrap(reject)
219
- executor(wrappedResolve, wrappedReject)
220
- })
221
- const context = captureRestorers()
222
- promiseContexts.set(p, context) // Always set, even if empty (Sticky Root)
223
- return p
224
- }
225
- return new OriginalPromise(executor)
226
- }
227
-
228
- // Copy statics
229
- Object.assign(PatchedPromise, (OriginalPromise as any))
230
-
231
- // Inherit prototype for instanceof checks
232
- PatchedPromise.prototype = OriginalPromise.prototype
233
-
234
- PatchedPromise.resolve = function<T>(value?: T | PromiseLike<T>): Promise<T> {
235
- const p = originals.resolve.call(OriginalPromise, value) as Promise<T>
236
- const context = captureRestorers()
237
- // Ensure we don't overwrite if it already has context (e.g. from constructor)
238
- if (context.size > 0 && !promiseContexts.has(p)) promiseContexts.set(p, context)
239
- return p
240
- } as any
241
-
242
- PatchedPromise.reject = function<T = never>(reason?: any): Promise<T> {
243
- const p = originals.reject.call(OriginalPromise, reason) as Promise<T>
244
- const context = captureRestorers()
245
- if (context.size > 0) promiseContexts.set(p, context)
246
- return p
247
- } as any
248
-
249
- PatchedPromise.all = function<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]> {
250
- const p = originals.all.call(OriginalPromise, values) as Promise<Awaited<T>[]>
251
- const context = captureRestorers()
252
- if (context.size > 0) promiseContexts.set(p, context)
253
- return p
254
- } as any
255
-
256
- PatchedPromise.allSettled = function<T>(values: Iterable<T | PromiseLike<T>>): Promise<PromiseSettledResult<Awaited<T>>[]> {
257
- const p = (originals.allSettled as any).call(OriginalPromise, values)
258
- const context = captureRestorers()
259
- if (context.size > 0) promiseContexts.set(p, context)
260
- return p
261
- } as any
262
-
263
- PatchedPromise.race = function<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>> {
264
- const p = originals.race.call(OriginalPromise, values) as Promise<Awaited<T>>
265
- const context = captureRestorers()
266
- if (context.size > 0) promiseContexts.set(p, context)
267
- return p
268
- } as any
269
-
270
- PatchedPromise.any = function<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>> {
271
- const p = (originals.any as any).call(OriginalPromise, values)
272
- const context = captureRestorers()
273
- if (context.size > 0) promiseContexts.set(p, context)
274
- return p
275
- } as any
276
-
277
- // Only apply patches if not already applied (or re-apply safely)
278
- // Note: OriginalPromise.prototype might be shared if we used the global one.
279
- // We must ensure we don't patch it twice if it's the SAME object.
280
- if (OriginalPromise.prototype.then !== patchedThen) {
281
- OriginalPromise.prototype.then = patchedThen as any
282
- OriginalPromise.prototype.catch = patchedCatch as any
283
- OriginalPromise.prototype.finally = patchedFinally as any
284
- }
285
-
286
- try {
287
- Object.defineProperty(OriginalPromise, Symbol.species, {
288
- get: () => PatchedPromise,
289
- configurable: true
290
- })
291
- } catch (e) {}
292
-
293
- ;(globalThis as any).Promise = PatchedPromise
294
-
295
- globalThis.setTimeout = ((callback: Function, ...args: any[]) => {
296
- return originals.setTimeout.call(globalThis, wrap(callback as any), ...args)
297
- }) as any
298
-
299
- globalThis.setInterval = ((callback: Function, ...args: any[]) => {
300
- return originals.setInterval.call(globalThis, wrap(callback as any), ...args)
301
- }) as any
302
-
303
- if (originals.setImmediate) {
304
- ;(globalThis as any).setImmediate = ((callback: Function, ...args: any[]) => {
305
- return originals.setImmediate.call(globalThis, wrap(callback as any), ...args)
306
- }) as any
307
- }
308
-
309
- if (originals.requestAnimationFrame) {
310
- globalThis.requestAnimationFrame = (callback: FrameRequestCallback) => {
311
- return originals.requestAnimationFrame.call(globalThis, wrap(callback))
312
- }
313
- }
314
-
315
- if (originals.queueMicrotask) {
316
- globalThis.queueMicrotask = (callback: VoidFunction): void => {
317
- originals.queueMicrotask.call(globalThis, wrap(callback))
318
- }
319
- }
@@ -1,23 +0,0 @@
1
- export type Restorer = () => () => void
2
- export type Hook = () => Restorer
3
-
4
- export const asyncHooks = {
5
- addHook(_hook: Hook): () => void {
6
- throw 'One must import the library from the server or the client side'
7
- },
8
- /**
9
- * [Hack] Sanitize a promise (or value) to prevent context leaks.
10
- * Default: Identity function.
11
- * Browser: Uses Macrotask wrapping to break microtask chains.
12
- */
13
- sanitizePromise(p: any): any {
14
- return p
15
- }
16
- }
17
-
18
- /**
19
- * Register a hook that will be called whenever an asynchronous operation is initiated.
20
- * The hook should return a restorer function which will be called just before the async callback runs.
21
- * That restorer should in turn return an undoer function which will be called just after the async callback finishes.
22
- */
23
- export const asyncHook = (hook: Hook) => asyncHooks.addHook(hook)
package/src/async/node.ts DELETED
@@ -1,104 +0,0 @@
1
- import { createHook } from 'node:async_hooks'
2
- import { Hook, Restorer, asyncHooks } from '.'
3
-
4
- // 1. Generic async_hooks implementation for Hooks
5
- // This maintains support for 'asyncHooks.addHook' for generic use cases.
6
-
7
- const hooks = new Set<Hook>()
8
- asyncHooks.addHook = function (hook: Hook) {
9
- hooks.add(hook)
10
- return () => {
11
- hooks.delete(hook)
12
- }
13
- }
14
-
15
- const contexts = new Map<number, Restorer[]>()
16
- const activeUndoers = new Map<number, (() => void)[]>()
17
-
18
- // Helper to capture current hooks state
19
- function captureRestorers() {
20
- if (hooks.size === 0) return []
21
- const restorers: Restorer[] = []
22
- for (const h of hooks) {
23
- const r = h()
24
- if (r) restorers.push(r)
25
- }
26
- return restorers
27
- }
28
-
29
- // Manual Wrap function to handle Promise callbacks
30
- function wrap<Args extends any[], R>(fn: ((...args: Args) => R) | null | undefined) {
31
- if (typeof fn !== 'function') return fn
32
- const restorers = captureRestorers()
33
- if (restorers.length === 0) return fn
34
-
35
- return function (this: any, ...args: Args) {
36
- const undoers: (() => void)[] = []
37
- for (const restore of restorers) {
38
- const u = restore()
39
- if (u) undoers.push(u)
40
- }
41
- try {
42
- return fn.apply(this, args)
43
- } finally {
44
- for (let i = undoers.length - 1; i >= 0; i--) undoers[i]()
45
- }
46
- }
47
- }
48
-
49
- const hook = createHook({
50
- init(asyncId, type, triggerId, resource) {
51
- // Used for native resources like Timers
52
- const restorers = captureRestorers()
53
- if (restorers.length > 0) contexts.set(asyncId, restorers)
54
- },
55
- before(asyncId) {
56
- const restorers = contexts.get(asyncId)
57
- if (!restorers) return
58
- const undoers: (() => void)[] = []
59
- for (const restore of restorers) {
60
- const u = restore()
61
- if (u) undoers.push(u)
62
- }
63
- if (undoers.length > 0) activeUndoers.set(asyncId, undoers)
64
- },
65
- after(asyncId) {
66
- const undoers = activeUndoers.get(asyncId)
67
- if (!undoers) return
68
- for (let i = undoers.length - 1; i >= 0; i--) undoers[i]()
69
- activeUndoers.delete(asyncId)
70
- },
71
- destroy(asyncId) {
72
- contexts.delete(asyncId)
73
- activeUndoers.delete(asyncId)
74
- },
75
- })
76
- hook.enable()
77
-
78
- // 2. Shadow Promise Implementation
79
- // Ensures V8 await resumptions are visible as .then callbacks, wrapping them to restore context.
80
-
81
- const OriginalPromise = globalThis.Promise
82
- const originalMethods = {
83
- then: OriginalPromise.prototype.then,
84
- catch: OriginalPromise.prototype.catch,
85
- finally: OriginalPromise.prototype.finally,
86
- resolve: OriginalPromise.resolve,
87
- reject: OriginalPromise.reject,
88
- all: OriginalPromise.all,
89
- }
90
-
91
-
92
-
93
- // Patch prototype
94
- OriginalPromise.prototype.then = function(onFulfilled, onRejected) {
95
- return originalMethods.then.call(this, wrap(onFulfilled), wrap(onRejected))
96
- } as any
97
- OriginalPromise.prototype.catch = function(onRejected) {
98
- return originalMethods.catch.call(this, wrap(onRejected))
99
- } as any
100
- OriginalPromise.prototype.finally = function(onFinally) {
101
- return originalMethods.finally.call(this, wrap(onFinally))
102
- } as any
103
-
104
-