/
meta.ts
766 lines (643 loc) · 20.2 KB
/
meta.ts
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
import { symbol, toString } from '@ember/-internals/utils';
import { assert, deprecate } from '@ember/debug';
import { isDestroyed, isDestroying } from '@glimmer/destroyable';
import { DEBUG } from '@glimmer/env';
import { Revision, UpdatableTag } from '@glimmer/validator';
type ObjMap<T> = { [key: string]: T };
const objectPrototype = Object.prototype;
export interface MetaCounters {
peekCalls: number;
peekPrototypeWalks: number;
setCalls: number;
deleteCalls: number;
metaCalls: number;
metaInstantiated: number;
matchingListenersCalls: number;
observerEventsCalls: number;
addToListenersCalls: number;
removeFromListenersCalls: number;
removeAllListenersCalls: number;
listenersInherited: number;
listenersFlattened: number;
parentListenersUsed: number;
flattenedListenersCalls: number;
reopensAfterFlatten: number;
readableLazyChainsCalls: number;
writableLazyChainsCalls: number;
}
let counters: MetaCounters | undefined;
if (DEBUG) {
counters = {
peekCalls: 0,
peekPrototypeWalks: 0,
setCalls: 0,
deleteCalls: 0,
metaCalls: 0,
metaInstantiated: 0,
matchingListenersCalls: 0,
observerEventsCalls: 0,
addToListenersCalls: 0,
removeFromListenersCalls: 0,
removeAllListenersCalls: 0,
listenersInherited: 0,
listenersFlattened: 0,
parentListenersUsed: 0,
flattenedListenersCalls: 0,
reopensAfterFlatten: 0,
readableLazyChainsCalls: 0,
writableLazyChainsCalls: 0,
};
}
/**
@module ember
*/
export const UNDEFINED = symbol('undefined');
const enum ListenerKind {
ADD = 0,
ONCE = 1,
REMOVE = 2,
}
interface StringListener {
event: string;
target: null;
method: string;
kind: ListenerKind.ADD | ListenerKind.ONCE | ListenerKind.REMOVE;
sync: boolean;
}
interface FunctionListener {
event: string;
target: object | null;
method: Function;
kind: ListenerKind.ADD | ListenerKind.ONCE | ListenerKind.REMOVE;
sync: boolean;
}
type Listener = StringListener | FunctionListener;
let currentListenerVersion = 1;
export class Meta {
_descriptors: Map<string, any> | undefined;
_mixins: any | undefined;
_isInit: boolean;
_lazyChains: ObjMap<[UpdatableTag, unknown][]> | undefined;
_values: ObjMap<unknown> | undefined;
_revisions: ObjMap<Revision> | undefined;
source: object;
proto: object | undefined;
_parent: Meta | undefined | null;
_listeners: Listener[] | undefined;
_listenersVersion = 1;
_inheritedEnd = -1;
_flattenedVersion = 0;
// DEBUG
constructor(obj: object) {
if (DEBUG) {
counters!.metaInstantiated++;
}
this._parent = undefined;
this._descriptors = undefined;
this._mixins = undefined;
this._lazyChains = undefined;
this._values = undefined;
this._revisions = undefined;
// initial value for all flags right now is false
// see FLAGS const for detailed list of flags used
this._isInit = false;
// used only internally
this.source = obj;
this.proto = obj.constructor === undefined ? undefined : obj.constructor.prototype;
this._listeners = undefined;
}
get parent() {
let parent = this._parent;
if (parent === undefined) {
let proto = getPrototypeOf(this.source);
this._parent = parent = proto === null || proto === objectPrototype ? null : meta(proto);
}
return parent;
}
// These methods are here to prevent errors in legacy compat with some addons
// that used them as intimate API
setSourceDestroying() {
deprecate(
'setSourceDestroying is deprecated, use the destroy() API to destroy the object directly instead',
false,
{
id: 'meta-destruction-apis',
until: '3.25.0',
for: 'ember-source',
since: {
enabled: '3.21.0',
},
}
);
}
setSourceDestroyed() {
deprecate(
'setSourceDestroyed is deprecated, use the destroy() API to destroy the object directly instead',
false,
{
id: 'meta-destruction-apis',
until: '3.25.0',
for: 'ember-source',
since: {
enabled: '3.21.0',
},
}
);
}
isSourceDestroying() {
deprecate(
'isSourceDestroying is deprecated, use the isDestroying() API to check the object destruction state directly instead',
false,
{
id: 'meta-destruction-apis',
until: '3.25.0',
for: 'ember-source',
since: {
enabled: '3.21.0',
},
}
);
return isDestroying(this.source);
}
isSourceDestroyed() {
deprecate(
'isSourceDestroyed is deprecated, use the isDestroyed() API to check the object destruction state directly instead',
false,
{
id: 'meta-destruction-apis',
until: '3.25.0',
for: 'ember-source',
since: {
enabled: '3.21.0',
},
}
);
return isDestroyed(this.source);
}
setInitializing() {
this._isInit = true;
}
unsetInitializing() {
this._isInit = false;
}
isInitializing() {
return this._isInit;
}
isPrototypeMeta(obj: object) {
return this.proto === this.source && this.source === obj;
}
_getOrCreateOwnMap(key: string) {
return this[key] || (this[key] = Object.create(null));
}
_getOrCreateOwnSet(key: string) {
return this[key] || (this[key] = new Set());
}
_findInheritedMap(key: string, subkey: string): any | undefined {
let pointer: Meta | null = this;
while (pointer !== null) {
let map: Map<string, any> = pointer[key];
if (map !== undefined) {
let value = map.get(subkey);
if (value !== undefined) {
return value;
}
}
pointer = pointer.parent;
}
}
_hasInInheritedSet(key: string, value: any) {
let pointer: Meta | null = this;
while (pointer !== null) {
let set = pointer[key];
if (set !== undefined && set.has(value)) {
return true;
}
pointer = pointer.parent;
}
return false;
}
valueFor(key: string): unknown {
let values = this._values;
return values !== undefined ? values[key] : undefined;
}
setValueFor(key: string, value: unknown) {
let values = this._getOrCreateOwnMap('_values');
values[key] = value;
}
revisionFor(key: string): Revision | undefined {
let revisions = this._revisions;
return revisions !== undefined ? revisions[key] : undefined;
}
setRevisionFor(key: string, revision: Revision | undefined) {
let revisions = this._getOrCreateOwnMap('_revisions');
revisions[key] = revision;
}
writableLazyChainsFor(key: string): [UpdatableTag, unknown][] {
if (DEBUG) {
counters!.writableLazyChainsCalls++;
}
let lazyChains = this._getOrCreateOwnMap('_lazyChains');
let chains = lazyChains[key];
if (chains === undefined) {
chains = lazyChains[key] = [];
}
return chains;
}
readableLazyChainsFor(key: string): [UpdatableTag, unknown][] | undefined {
if (DEBUG) {
counters!.readableLazyChainsCalls++;
}
let lazyChains = this._lazyChains;
if (lazyChains !== undefined) {
return lazyChains[key];
}
return undefined;
}
addMixin(mixin: any) {
assert(
isDestroyed(this.source)
? `Cannot add mixins of \`${toString(mixin)}\` on \`${toString(
this.source
)}\` call addMixin after it has been destroyed.`
: '',
!isDestroyed(this.source)
);
let set = this._getOrCreateOwnSet('_mixins');
set.add(mixin);
}
hasMixin(mixin: any) {
return this._hasInInheritedSet('_mixins', mixin);
}
forEachMixins(fn: Function) {
let pointer: Meta | null = this;
let seen: Set<any> | undefined;
while (pointer !== null) {
let set = pointer._mixins;
if (set !== undefined) {
seen = seen === undefined ? new Set() : seen;
// TODO cleanup typing here
set.forEach((mixin: any) => {
if (!seen!.has(mixin)) {
seen!.add(mixin);
fn(mixin);
}
});
}
pointer = pointer.parent;
}
}
writeDescriptors(subkey: string, value: any) {
assert(
isDestroyed(this.source)
? `Cannot update descriptors for \`${subkey}\` on \`${toString(
this.source
)}\` after it has been destroyed.`
: '',
!isDestroyed(this.source)
);
let map = this._descriptors || (this._descriptors = new Map());
map.set(subkey, value);
}
peekDescriptors(subkey: string) {
let possibleDesc = this._findInheritedMap('_descriptors', subkey);
return possibleDesc === UNDEFINED ? undefined : possibleDesc;
}
removeDescriptors(subkey: string) {
this.writeDescriptors(subkey, UNDEFINED);
}
forEachDescriptors(fn: Function) {
let pointer: Meta | null = this;
let seen: Set<any> | undefined;
while (pointer !== null) {
let map = pointer._descriptors;
if (map !== undefined) {
seen = seen === undefined ? new Set() : seen;
map.forEach((value, key) => {
if (!seen!.has(key)) {
seen!.add(key);
if (value !== UNDEFINED) {
fn(key, value);
}
}
});
}
pointer = pointer.parent;
}
}
addToListeners(
eventName: string,
target: object | null,
method: Function | string,
once: boolean,
sync: boolean
) {
if (DEBUG) {
counters!.addToListenersCalls++;
}
this.pushListener(eventName, target, method, once ? ListenerKind.ONCE : ListenerKind.ADD, sync);
}
removeFromListeners(eventName: string, target: object | null, method: Function | string): void {
if (DEBUG) {
counters!.removeFromListenersCalls++;
}
this.pushListener(eventName, target, method, ListenerKind.REMOVE);
}
private pushListener(
event: string,
target: object | null,
method: Function | string,
kind: ListenerKind.ADD | ListenerKind.ONCE | ListenerKind.REMOVE,
sync = false
): void {
let listeners = this.writableListeners();
let i = indexOfListener(listeners, event, target, method!);
// remove if found listener was inherited
if (i !== -1 && i < this._inheritedEnd) {
listeners.splice(i, 1);
this._inheritedEnd--;
i = -1;
}
// if not found, push. Note that we must always push if a listener is not
// found, even in the case of a function listener remove, because we may be
// attempting to add or remove listeners _before_ flattening has occurred.
if (i === -1) {
assert(
'You cannot add function listeners to prototypes. Convert the listener to a string listener, or add it to the instance instead.',
!(this.isPrototypeMeta(this.source) && typeof method === 'function')
);
assert(
'You attempted to remove a function listener which did not exist on the instance, which means you may have attempted to remove it before it was added.',
!(
!this.isPrototypeMeta(this.source) &&
typeof method === 'function' &&
kind === ListenerKind.REMOVE
)
);
listeners.push({
event,
target,
method,
kind,
sync,
} as Listener);
} else {
let listener = listeners[i];
// If the listener is our own listener and we are trying to remove it, we
// want to splice it out entirely so we don't hold onto a reference.
if (kind === ListenerKind.REMOVE && listener.kind !== ListenerKind.REMOVE) {
listeners.splice(i, 1);
} else {
assert(
`You attempted to add an observer for the same method on '${
event.split(':')[0]
}' twice to ${target} as both sync and async. Observers must be either sync or async, they cannot be both. This is likely a mistake, you should either remove the code that added the observer a second time, or update it to always be sync or async. The method was ${method}.`,
!(
listener.kind === ListenerKind.ADD &&
kind === ListenerKind.ADD &&
listener.sync !== sync
)
);
// update own listener
listener.kind = kind;
listener.sync = sync;
}
}
}
private writableListeners(): Listener[] {
// Check if we need to invalidate and reflatten. We need to do this if we
// have already flattened (flattened version is the current version) and
// we are either writing to a prototype meta OR we have never inherited, and
// may have cached the parent's listeners.
if (
this._flattenedVersion === currentListenerVersion &&
(this.source === this.proto || this._inheritedEnd === -1)
) {
if (DEBUG) {
counters!.reopensAfterFlatten++;
}
currentListenerVersion++;
}
// Inherited end has not been set, then we have never created our own
// listeners, but may have cached the parent's
if (this._inheritedEnd === -1) {
this._inheritedEnd = 0;
this._listeners = [];
}
return this._listeners!;
}
/**
Flattening is based on a global revision counter. If the revision has
bumped it means that somewhere in a class inheritance chain something has
changed, so we need to reflatten everything. This can only happen if:
1. A meta has been flattened (listener has been called)
2. The meta is a prototype meta with children who have inherited its
listeners
3. A new listener is subsequently added to the meta (e.g. via `.reopen()`)
This is a very rare occurrence, so while the counter is global it shouldn't
be updated very often in practice.
*/
private flattenedListeners(): Listener[] | undefined {
if (DEBUG) {
counters!.flattenedListenersCalls++;
}
if (this._flattenedVersion < currentListenerVersion) {
if (DEBUG) {
counters!.listenersFlattened++;
}
let parent = this.parent;
if (parent !== null) {
// compute
let parentListeners = parent.flattenedListeners();
if (parentListeners !== undefined) {
if (this._listeners === undefined) {
// If this instance doesn't have any of its own listeners (writableListeners
// has never been called) then we don't need to do any flattening, return
// the parent's listeners instead.
if (DEBUG) {
counters!.parentListenersUsed++;
}
this._listeners = parentListeners;
} else {
let listeners = this._listeners;
if (this._inheritedEnd > 0) {
listeners.splice(0, this._inheritedEnd);
this._inheritedEnd = 0;
}
for (let i = 0; i < parentListeners.length; i++) {
let listener = parentListeners[i];
let index = indexOfListener(
listeners,
listener.event,
listener.target,
listener.method
);
if (index === -1) {
if (DEBUG) {
counters!.listenersInherited++;
}
listeners.unshift(listener);
this._inheritedEnd++;
}
}
}
}
}
this._flattenedVersion = currentListenerVersion;
}
return this._listeners;
}
matchingListeners(eventName: string): (string | boolean | object | null)[] | undefined {
let listeners = this.flattenedListeners();
let result;
if (DEBUG) {
counters!.matchingListenersCalls++;
}
if (listeners !== undefined) {
for (let index = 0; index < listeners.length; index++) {
let listener = listeners[index];
// REMOVE listeners are placeholders that tell us not to
// inherit, so they never match. Only ADD and ONCE can match.
if (
listener.event === eventName &&
(listener.kind === ListenerKind.ADD || listener.kind === ListenerKind.ONCE)
) {
if (result === undefined) {
// we create this array only after we've found a listener that
// matches to avoid allocations when no matches are found.
result = [] as any[];
}
result.push(listener.target!, listener.method, listener.kind === ListenerKind.ONCE);
}
}
}
return result;
}
observerEvents() {
let listeners = this.flattenedListeners();
let result;
if (DEBUG) {
counters!.observerEventsCalls++;
}
if (listeners !== undefined) {
for (let index = 0; index < listeners.length; index++) {
let listener = listeners[index];
// REMOVE listeners are placeholders that tell us not to
// inherit, so they never match. Only ADD and ONCE can match.
if (
(listener.kind === ListenerKind.ADD || listener.kind === ListenerKind.ONCE) &&
listener.event.indexOf(':change') !== -1
) {
if (result === undefined) {
// we create this array only after we've found a listener that
// matches to avoid allocations when no matches are found.
result = [] as any[];
}
result.push(listener);
}
}
}
return result;
}
}
const getPrototypeOf = Object.getPrototypeOf;
const metaStore = new WeakMap();
export function setMeta(obj: object, meta: Meta) {
assert('Cannot call `setMeta` on null', obj !== null);
assert('Cannot call `setMeta` on undefined', obj !== undefined);
assert(
`Cannot call \`setMeta\` on ${typeof obj}`,
typeof obj === 'object' || typeof obj === 'function'
);
if (DEBUG) {
counters!.setCalls++;
}
metaStore.set(obj, meta);
}
export function peekMeta(obj: object): Meta | null {
assert('Cannot call `peekMeta` on null', obj !== null);
assert('Cannot call `peekMeta` on undefined', obj !== undefined);
assert(
`Cannot call \`peekMeta\` on ${typeof obj}`,
typeof obj === 'object' || typeof obj === 'function'
);
if (DEBUG) {
counters!.peekCalls++;
}
let meta = metaStore.get(obj);
if (meta !== undefined) {
return meta;
}
let pointer = getPrototypeOf(obj);
while (pointer !== null) {
if (DEBUG) {
counters!.peekPrototypeWalks++;
}
meta = metaStore.get(pointer);
if (meta !== undefined) {
if (meta.proto !== pointer) {
// The meta was a prototype meta which was not marked as initializing.
// This can happen when a prototype chain was created manually via
// Object.create() and the source object does not have a constructor.
meta.proto = pointer;
}
return meta;
}
pointer = getPrototypeOf(pointer);
}
return null;
}
/**
Retrieves the meta hash for an object. If `writable` is true ensures the
hash is writable for this object as well.
The meta object contains information about computed property descriptors as
well as any watched properties and other information. You generally will
not access this information directly but instead work with higher level
methods that manipulate this hash indirectly.
@method meta
@for Ember
@private
@param {Object} obj The object to retrieve meta for
@param {Boolean} [writable=true] Pass `false` if you do not intend to modify
the meta hash, allowing the method to avoid making an unnecessary copy.
@return {Object} the meta hash for an object
*/
export const meta: {
(obj: object): Meta;
_counters?: MetaCounters;
} = function meta(obj: object) {
assert('Cannot call `meta` on null', obj !== null);
assert('Cannot call `meta` on undefined', obj !== undefined);
assert(
`Cannot call \`meta\` on ${typeof obj}`,
typeof obj === 'object' || typeof obj === 'function'
);
if (DEBUG) {
counters!.metaCalls++;
}
let maybeMeta = peekMeta(obj);
// remove this code, in-favor of explicit parent
if (maybeMeta !== null && maybeMeta.source === obj) {
return maybeMeta;
}
let newMeta = new Meta(obj);
setMeta(obj, newMeta);
return newMeta;
};
if (DEBUG) {
meta._counters = counters;
}
export { counters };
function indexOfListener(
listeners: Listener[],
event: string,
target: object | null,
method: Function | string | null
) {
for (let i = listeners.length - 1; i >= 0; i--) {
let listener = listeners[i];
if (listener.event === event && listener.target === target && listener.method === method) {
return i;
}
}
return -1;
}