-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy patheventEmitter.ts
More file actions
430 lines (361 loc) · 13.5 KB
/
Copy patheventEmitter.ts
File metadata and controls
430 lines (361 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/* eslint-disable no-restricted-syntax */
import { v4 as uuidv4 } from 'uuid'
import { ErrorRef, IEventEmitterRegistryController, Statuses } from '../../interfaces/eventEmitter'
import wait from '../../utils/wait'
const LIMIT_ON_THE_NUMBER_OF_ERRORS = 100
// Cache to ensure referential stability. When a nested object is accessed multiple times,
// it should return the same Proxy instance, preventing infinite re-render loops in React
// caused by unstable references in selectors.
const proxyCache = new WeakMap<any, any>()
function createDeepProxy(target: any, topLevelKey: string, updatedKeys: Set<string>): any {
if (!isPlainObjectOrArray(target)) {
return target
}
const cachedProxy = proxyCache.get(target)
if (cachedProxy) return cachedProxy
const proxy = new Proxy(target, {
get(obj, prop) {
const value = Reflect.get(obj, prop)
if (isPlainObjectOrArray(value)) {
return createDeepProxy(value, topLevelKey, updatedKeys)
}
return value
},
set(obj, prop, value, receiver) {
const currentValue = Reflect.get(obj, prop)
if (currentValue !== value) {
Reflect.set(obj, prop, value, receiver)
updatedKeys.add(topLevelKey)
}
return true
}
})
proxyCache.set(target, proxy)
return proxy
}
function isPlainObjectOrArray(value: any): boolean {
if (value === null || typeof value !== 'object') return false
const proto = Object.getPrototypeOf(value)
// Only return true for {} and []
return proto === Object.prototype || proto === Array.prototype || proto === null
}
export default class EventEmitter {
id: string
#registry: IEventEmitterRegistryController | null = null
#callbacksWithId: {
id: string | null
cb: (forceEmit?: boolean) => void
}[] = []
#callbacks: ((forceEmit?: boolean) => void)[] = []
#errorCallbacksWithId: {
id: string | null
cb: (error: ErrorRef) => void
}[] = []
#errorCallbacks: ((error: ErrorRef) => void)[] = []
#errors: ErrorRef[] = []
statuses: Statuses<string> = {}
#updatedKeys: Set<string> = new Set()
#lastState: { [key: string]: any } = {}
#hasEmittedUpdate: boolean = false
/**
*
* @param registry - EventEmitterRegistryController instance to be used by this controller. Controllers
* added to the registry will have their updates and errors propagated to the front-end.
* @param registerImmediately - Most of the time we want to register the controller in the registry
* immediately upon construction. However, there are some dynamic controllers (like SignAccountOpController)
* that should be registered only after a condition is met (e.g. when the request is open)
*/
constructor(registry?: IEventEmitterRegistryController, registerImmediately: boolean = true) {
this.id = uuidv4()
if (registry) {
this.#registry = registry
if (registerImmediately) {
this.registerInRegistry()
}
}
}
get name(): string {
return this.constructor.name
}
get onUpdateIds() {
return this.#callbacksWithId.map((item) => item.id)
}
get onErrorIds() {
return this.#errorCallbacksWithId.map((item) => item.id)
}
// called emittedErrors and not just errors because some of the other controllers
// that extend this one have errors defined already
get emittedErrors() {
return this.#errors
}
getUpdatedKeys(): string[] {
if (!this.#hasEmittedUpdate) {
this.#updatedKeys.clear()
return []
}
const keys = new Set(this.#updatedKeys)
for (const key of Object.keys(this)) {
if (key.startsWith('_') || key.startsWith('#')) continue
const val = (this as any)[key]
if (val instanceof Set || val instanceof Map) {
keys.add(key)
}
}
const getterKeys = this.#getGettersKeys()
for (const key of getterKeys) {
keys.add(key)
}
this.#updatedKeys.clear()
return Array.from(keys)
}
#getGettersKeys(): string[] {
const proto = Object.getPrototypeOf(this)
const descriptors = Object.getOwnPropertyDescriptors(proto)
return Object.keys(descriptors).filter((key) => {
if (key.startsWith('#') || key.startsWith('_') || key === 'toJSON') return false
return typeof descriptors[key]?.get === 'function'
})
}
protected trackUpdates() {
for (const key of Object.keys(this)) {
if (key === 'updatedKeys' || key.startsWith('_') || key.startsWith('#')) continue
const currentValue = (this as any)[key]
if (typeof currentValue === 'function') continue
if (currentValue !== this.#lastState[key]) {
this.#updatedKeys.add(key)
// Wrap objects/arrays in a proxy and reassign back to `this` so direct mutations are caught
if (isPlainObjectOrArray(currentValue)) {
const proxiedValue = createDeepProxy(currentValue, key, this.#updatedKeys)
;(this as any)[key] = proxiedValue
this.#lastState[key] = proxiedValue
} else {
this.#lastState[key] = currentValue
}
}
}
}
/**
* Emits an update immediately, bypassing both background batching
* (where updates on the same tick are debounced and batched for performance)
* and React batching (where rapid state updates are merged).
*
* This ensures the state change is applied instantly at the React application level.
* It is especially useful when multiple status flags change in quick succession.
*
* For example, if a flow updates a status from INITIAL -> LOADING -> SUCCESS -> INITIAL,
* normal batching may skip intermediate states and only emit the first and last ones.
*/
async forceEmitUpdate() {
this.trackUpdates()
// Bypassing background batching on the same tick
await wait(1)
// Passing `true` to the cb will bypass React batching
// eslint-disable-next-line no-restricted-syntax
for (const i of this.#callbacksWithId) i.cb(true)
// eslint-disable-next-line no-restricted-syntax
for (const cb of this.#callbacks) cb(true)
this.#hasEmittedUpdate = true
}
protected emitUpdate() {
this.trackUpdates()
// eslint-disable-next-line no-restricted-syntax
for (const i of this.#callbacksWithId) i.cb()
// eslint-disable-next-line no-restricted-syntax
for (const cb of this.#callbacks) cb()
this.#hasEmittedUpdate = true
}
/**
* Propagates updates from a child controller to its parent in a parent -> child setup,
* ensuring child state updates reach the application without being lost due to batching.
*
* Used when a parent controller (e.g. swapAndBridgeController) subscribes to child updates:
*
* this.#signAccountOpController.onUpdate((forceEmit) => {
* this.propagateUpdate(forceEmit)
* })
*
* Child controllers may update their status very quickly
* (e.g. INITIAL -> LOADING -> SUCCESS -> INITIAL).
* If the parent propagates these updates via `forceEmitUpdate()`,
* the update is scheduled in a new tick and intermediate states may be lost.
*
* `propagateUpdate` forwards the update in the same tick while preserving the
* `forceEmit` behavior, ensuring all states are correctly propagated.
*
* Notes:
* - If `forceEmit` is falsy, this behaves the same as calling `emitUpdate()`.
* For consistency and clarity, parent -> child setups should always use
* `propagateUpdate()` instead of mixing `emitUpdate()` and `propagateUpdate()`.
*
* - For all direct controller updates (i.e. when there is no child controller involved
* and the controller updates its own state), use `emitUpdate()` or `forceEmitUpdate()`.
*/
protected propagateUpdate(forceEmit?: boolean) {
this.trackUpdates()
// eslint-disable-next-line no-restricted-syntax
for (const i of this.#callbacksWithId) i.cb(forceEmit)
// eslint-disable-next-line no-restricted-syntax
for (const cb of this.#callbacks) cb(forceEmit)
this.#hasEmittedUpdate = true
}
protected emitError(error: ErrorRef) {
this.#errors.push(error)
this.#trimErrorsIfNeeded()
console.log(
`[Еmitted error in controller ${this.constructor.name}] ${error.message}`,
this.#errors
)
// eslint-disable-next-line no-restricted-syntax
for (const i of this.#errorCallbacksWithId) i.cb(error)
// eslint-disable-next-line no-restricted-syntax
for (const cb of this.#errorCallbacks) cb(error)
}
protected async withStatus(
callName: string,
fn: Function,
allowConcurrentActions = false,
// Silence this error in prod to avoid displaying wired error messages.
// The only benefit of displaying it is for devs to see when an action is dispatched twice.
// TODO: If this happens on PROD, ideally we should get an error report somehow somewhere.
errorLevel: ErrorRef['level'] = process.env.APP_ENV === 'production' &&
process.env.IS_TESTING !== 'true'
? 'silent'
: 'minor'
) {
const someStatusIsLoading = Object.values(this.statuses).some((status) => status !== 'INITIAL')
if (!this.statuses[callName]) {
console.error(`${callName} is not defined in "statuses".`)
}
// By default, concurrent actions are disallowed to maintain consistency, particularly within sub-controllers where
// simultaneous actions can lead to unintended side effects. The 'allowConcurrentActions' flag is provided to enable
// concurrent execution at the main controller level. This is useful when multiple actions need to modify the state
// of different sub-controllers simultaneously.
if (
(someStatusIsLoading && !allowConcurrentActions) ||
!['INITIAL', 'SUCCESS'].includes(this.statuses[callName] as any)
) {
this.emitError({
level: errorLevel,
message: `Please wait for the completion of the previous action before initiating another one.', ${callName}`,
error: new Error(
'Another function is already being handled by withStatus refrain from invoking a second function.'
)
})
return
}
if (this.statuses[callName] === 'SUCCESS') {
await wait(2) // to let the INITIAL status be fired from the prev session
}
this.statuses[callName] = 'LOADING'
await this.forceEmitUpdate()
try {
await fn()
this.statuses[callName] = 'SUCCESS'
await this.forceEmitUpdate()
} catch (error: any) {
this.statuses[callName] = 'ERROR'
if ('message' in error && 'level' in error && 'error' in error) {
this.emitError(error)
// Sometimes we don't want to show an error message to the user. For example, if the user cancels a request
// we don't want to go through the SUCCESS state, but we also don't want to show an error message.
} else if (error?.message) {
this.emitError({
message: error?.message || 'An unexpected error occurred',
level: 'major',
error
})
}
await this.forceEmitUpdate()
}
this.statuses[callName] = 'INITIAL'
await this.forceEmitUpdate()
}
// Prevents memory leaks and storing huge amount of errors
#trimErrorsIfNeeded() {
if (this.#errors.length > LIMIT_ON_THE_NUMBER_OF_ERRORS) {
const excessErrors = this.#errors.length - LIMIT_ON_THE_NUMBER_OF_ERRORS
this.#errors = this.#errors.slice(excessErrors)
}
}
// returns an unsub function
onUpdate(cb: (forceUpdate?: boolean) => void, id?: string): () => void {
if (id) {
this.#callbacksWithId.push({ id, cb })
} else {
this.#callbacks.push(cb)
}
return () => {
if (id) {
this.#callbacksWithId = this.#callbacksWithId.filter(
(callbackItem) => callbackItem.id !== id
)
} else {
this.#callbacks.splice(this.#callbacks.indexOf(cb), 1)
}
}
}
// returns an unsub function for error events
onError(cb: (error: ErrorRef) => void, id?: string): () => void {
if (id) {
this.#errorCallbacksWithId.push({ id, cb })
} else {
this.#errorCallbacks.push(cb)
}
return () => {
if (id) {
this.#errorCallbacksWithId = this.#errorCallbacksWithId.filter(
(callbackItem) => callbackItem.id !== id
)
} else {
this.#errorCallbacks.splice(this.#errorCallbacks.indexOf(cb), 1)
}
}
}
/**
* Destroys the controller, unregistering it from the EventEmitterRegistry and
* clearing all callbacks and errors.
*/
destroy() {
this.unregisterFromRegistry()
this.#callbacks = []
this.#callbacksWithId = []
this.#errorCallbacks = []
this.#errorCallbacksWithId = []
this.#errors = []
}
/**
* Registers the controller into the EventEmitterRegistry (if set)
* to propagate its updates and errors to the front-end.
*/
registerInRegistry() {
if (!this.#registry) {
this.emitError({
level: 'silent',
message: `EventEmitter: Trying to register a controller while the registry is not set. Controller: ${this.name}`,
error: new Error(
'EventEmitter: Trying to register a controller while the registry is not set.'
)
})
return
}
this.#registry.set(this.id, this)
}
/**
* Unregisters the controller from the EventEmitterRegistry (if set).
* Used when controllers are destroyed or by dynamic controllers.
*/
unregisterFromRegistry() {
if (!this.#registry) return
this.#registry?.delete(this.id)
}
isInRegistry(): boolean {
return !!this.#registry?.has(this.id)
}
toJSON() {
return {
...this,
name: this.name,
emittedErrors: this.emittedErrors // includes the getter in the stringified instance
}
}
}