-
-
Notifications
You must be signed in to change notification settings - Fork 202
Expand file tree
/
Copy pathBase.mjs
More file actions
1279 lines (1130 loc) · 46.1 KB
/
Base.mjs
File metadata and controls
1279 lines (1130 loc) · 46.1 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
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {buffer, debounce, intercept, resolveCallback, throttle} from '../util/Function.mjs';
import Compare from '../core/Compare.mjs';
import Util from '../core/Util.mjs';
import Config from './Config.mjs';
import {isDescriptor, mergeFrom} from './ConfigSymbols.mjs';
import IdGenerator from './IdGenerator.mjs';
import EffectManager from './EffectManager.mjs';
const configSymbol = Symbol.for('configSymbol'),
forceAssignConfigs = Symbol('forceAssignConfigs'),
isInstance = Symbol('isInstance');
/**
* The base class for (almost) all classes inside the Neo namespace
* Exceptions are e.g. core.IdGenerator, vdom.VNode
* @class Neo.core.Base
*/
class Base {
/**
* You can define methods which should get delayed.
* Types are buffer, debounce & throttle.
* @example
* delayable: {
* fireChangeEvent: {
* type : 'debounce',
* timer: 300
* }
* }
* @member {Object} delayable={}
* @protected
* @static
*/
static delayable = {}
/**
* Flag which will get set to true once manager.Instance got created
* @member {Boolean} instanceManagerAvailable=false
* @static
*/
static instanceManagerAvailable = false
/**
* Regex to grab the MethodName from an error
* which is a second generation function
* @member {RegExp} methodNameRegex
* @static
*/
static methodNameRegex = /\n.*\n\s+at\s+.*\.(\w+)\s+.*/
/**
* True automatically applies the core.Observable mixin
* @member {Boolean} observable=false
* @static
*/
static observable = false
/**
* Keep the overwritten methods
* @member {Object} overwrittenMethods={}
* @protected
* @static
*/
static overwrittenMethods = {}
/**
* Defines the default configuration properties for the class. These configurations are
* merged throughout the class hierarchy and can be overridden at the instance level.
*
* There are two main types of configs:
*
* 1. **Reactive Configs:** Property names ending with a trailing underscore (e.g., `myConfig_`).
* The framework automatically generates a public getter and setter, removing the underscore
* from the property name (e.g., `this.myConfig`). This system enables powerful, optional
* lifecycle hooks that are called automatically if they are implemented on the class:
* - `beforeGetMyConfig(value)`: Executed before the getter returns. Can be used to dynamically modify the returned value.
* - `beforeSetMyConfig(newValue, oldValue)`: Executed before a new value is set. Can be used for validation or transformation. Returning `undefined` from this hook will cancel the update.
* - `afterSetMyConfig(newValue, oldValue)`: Executed after a new value has been successfully set. Ideal for triggering side effects.
*
* **The `undefined` Sentinel Value:**
* In Neo.mjs, `undefined` is used as a strict, immutable sentinel value representing "initial instantiation".
* When an `afterSet` hook runs for the very first time during component creation, its `oldValue` will ALWAYS be `undefined`.
* This allows developers to easily skip logic that should not run during setup using a simple `if (oldValue !== undefined)`.
* Because of this architecture, **you should never set a config to `undefined` later in its lifecycle.**
* If you need to clear or reset a config's state, explicitly set it to `null`.
*
* 2. **Non-Reactive (Prototype-based) Configs:** Property names without a trailing underscore.
* These are applied directly to the class's **prototype** during the `Neo.setupClass`
* process. This is highly memory-efficient as the value is shared across all instances.
* It also allows for powerful, application-wide modifications of default behaviors
* by using the `Neo.overwrites` mechanism, which modifies these prototype values at
* load time.
*
* **vs. Class Fields:**
* Use a non-reactive config when you want the property to be eligible for the `Neo.overwrites`
* mechanism. This allows external code (like themes or application-level overrides) to change
* the default value for the class, which then propagates to all subclasses and instances
* globally. Use standard class fields for internal state that should not be globally reconfigured.
*
* @returns {Object} config
*/
static config = {
/**
* The class name which will get mapped into the Neo or app namespace
* @member {String} className='Neo.core.Base'
* @protected
*/
className: 'Neo.core.Base',
/**
* The class shortcut-name to use for e.g. creating child components inside a JSON-format
* @member {String} ntype='base'
* @protected
*/
ntype: 'base',
/**
* While it is recommended to change the static delayable configs on class level,
* you can change it on instance level too. If not null, we will do a deep merge.
* @member {Object} delayable=null
*/
delayable: null,
/**
* The unique component id
* @member {String|null} id_=null
* @reactive
*/
id_: null,
/**
* An array of remote method names that should be intercepted.
* Names used here must be present inside the `remote_` config.
* If a remote call for one of these methods arrives, `onInterceptRemotes()` will be called.
* @member {String[]|null} interceptRemotes=null
* @protected
*/
interceptRemotes: null,
/**
* Neo.create() will change this flag to true after the onConstructed() chain is done.
* @member {Boolean} isConstructed=false
* @protected
*/
isConstructed: false,
/**
* This config will be set to `true` as the very first action within the `destroy()` method.
* Effects can observe this config to clean themselves up.
* @member {Boolean} isDestroying_=false
* @protected
* @reactive
*/
isDestroying_: false,
/**
* The config will get set to `true` once the Promise of `async initAsync()` is resolved.
* You can use `afterSetIsReady()` to get notified once the ready state is reached.
* For observable classes, this will also fire a `ready` event.
* @member {Boolean} isReady_=false
* @reactive
*/
isReady_: false,
/**
* Add mixins as an array of classNames, imported modules or a mixed version
* @member {String[]|Neo.core.Base[]|null} mixins=null
*/
mixins: null,
/**
* You can create a new instance by passing an imported class (JS module default export)
* @member {Class} module=null
* @protected
*/
module: null,
/**
* Remote method access for other threads. Example use case:
* remote: {app: ['myRemoteMethod']}
*
* ONLY supported for singletons.
*
* @member {Object|null} remote_={[isDescriptor]: true, merge: 'deepArrays', value: null}
* @protected
* @reactive
*/
remote_: {
[isDescriptor]: true,
merge : 'deepArrays',
value : null
}
}
/**
* Internal cache for all async reject functions (timeouts, remote calls, promises).
* @member {Map<Number|Symbol, Function>} #asyncRejects=new Map()
* @private
*/
#asyncRejects = new Map()
/**
* A private field to store the Config controller instances.
* @member {Object} #configs={}
* @private
*/
#configs = {}
/**
* Internal cache for all config subscription cleanup functions.
* @member {Function[]} #configSubscriptionCleanups=[]
* @private
*/
#configSubscriptionCleanups = []
/**
* A promise that resolves when the instance is fully initialized (after initAsync() completes).
* @member {Promise<void>|null} #readyPromise
* @private
*/
#readyPromise = null
/**
* A resolver function for the ready promise.
* @member {Function|null} #readyResolver
* @private
*/
#readyResolver = null
/**
* A promise that resolves when the remote methods are registered.
* @member {Promise<void>|null} #remotesReadyPromise
* @private
*/
#remotesReadyPromise = null
/**
* A resolver function for the remotesReady promise.
* @member {Function|null} #remotesReadyResolver
* @private
*/
#remotesReadyResolver = null
/**
* The main initializer for all Neo.mjs classes, invoked by `Neo.create()`.
* NOTE: This is not the native `constructor()`, which is called without arguments by `Neo.create()` first.
*
* This method orchestrates the entire instance initialization process, including
* the setup of the powerful and flexible config system.
*
* The `config` parameter is a single object that can contain different types of properties,
* which are processed in a specific order to ensure consistency and predictability:
*
* 1. **Public Class Fields & Other Properties:** Any key in the `config` object that is NOT
* defined in the class's `static config` hierarchy is considered a public field or a
* dynamic property. These are assigned directly to the instance (`this.myField = value`)
* at the very beginning. This is crucial so that subsequent config hooks (like `afterSet*`)
* can access their latest values.
*
* 2. **Reactive Configs:** A property is considered reactive if it is defined with a trailing
* underscore (e.g., `myValue_`) in the `static config` of **any class in the inheritance
* chain**. Subclasses can provide new default values for these configs without the
* underscore, and they will still be reactive. Their values are applied via generated
* setters, triggering `beforeSet*` and `afterSet*` hooks, and they are wrapped in a
* `Neo.core.Config` instance to enable subscription-based reactivity.
*
* 3. **Non-Reactive Configs:** Properties defined in `static config` without a trailing
* underscore in their entire inheritance chain. Their default values are applied directly
* to the class **prototype**, making them shared across all instances and allowing for
* run-time modifications (prototypal inheritance). When a new value is passed to this
* method, it creates an instance-specific property that shadows the prototype value.
*
* This method also initializes the observable mixin (if applicable) and schedules asynchronous
* logic like `initAsync()` (which handles remote method access) to run after the synchronous
* construction chain is complete.
*
* @param {Object} config={} The initial configuration object for the instance.
*/
construct(config={}) {
let me = this;
Object.defineProperties(me, {
[configSymbol]: {
configurable: true,
enumerable : false,
value : {},
writable : true
},
[isInstance]: {
enumerable: false,
value : true
}
});
me.id = config.id || me.constructor.config.id || IdGenerator.getId(this.getIdKey());
delete config.id;
// Assign class field values prior to configs
config = me.setFields(config);
me.initConfig(config);
Object.defineProperty(me, 'configsApplied', {
enumerable: false,
value : true
});
me.applyDelayable();
/*
* We do not want to force devs to check for the `isDestroyed` flag in every possible class extension.
* So, we are intercepting the top-most `destroy()` call to check for the flag there.
* Rationale: `destroy()` must only get called once.
*/
intercept(me, 'destroy', me.#preDestroyHook, me);
// Storing a resolver to execute inside `afterSetIsReady`.
me.#readyPromise = new Promise(resolve => {
me.#readyResolver = resolve
});
me.#remotesReadyPromise = new Promise(resolve => {
me.#remotesReadyResolver = resolve
});
// Triggers async logic after the construction chain is done.
Promise.resolve().then(async () => {
await me.initAsync();
me.isReady = true
})
}
/**
* Triggered after the id config got changed.
* You can dynamically change instance ids if needed. They need to stay unique at any given point.
* Use case: e.g. component based lists, where you want to re-use item instances.
* @param {String|null} value
* @param {String|null} oldValue
* @protected
*/
afterSetId(value, oldValue) {
let me = this,
hasManager = Base.instanceManagerAvailable === true;
if (oldValue) {
if (hasManager) {
Neo.manager.Instance.unregister(oldValue)
} else if (Neo.idMap) {
delete Neo.idMap[oldValue]
}
}
if (value) {
if (hasManager) {
Neo.manager.Instance.register(me)
} else {
Neo.idMap ??= {};
Neo.idMap[value] = me
}
}
}
/**
* Triggered after the isReady config gets changed.
* Resolves the ready() promise and fires the ready event for observable classes.
* @param {Boolean} value
* @param {Boolean} oldValue
* @protected
*/
afterSetIsReady(value, oldValue) {
if (value) {
let me = this;
me.#readyResolver?.();
// We can only fire the event in case the Observable mixin is included.
me.getStaticConfig('observable') && me.fire('ready')
}
}
/**
* Adjusts all methods inside static delayable
*/
applyDelayable() {
let me = this,
ctorDelayable = me.constructor.delayable,
delayable = me.delayable ? Neo.merge({}, me.delayable, ctorDelayable) : ctorDelayable;
Object.entries(delayable).forEach(([key, value]) => {
if (value) {
let map = {
buffer() {me[key] = new buffer(me[key], me, value.timer)},
debounce() {me[key] = new debounce(me[key], me, value.timer)},
throttle() {me[key] = new throttle(me[key], me, value.timer)}
};
map[value.type]?.()
}
})
}
/**
* This static method is called by `Neo.setupClass()` during the class creation process.
* It allows for modifying a class's default prototype-based configs from outside the
* class hierarchy, which is a powerful way to avoid boilerplate code.
*
* It looks for a matching entry in the global `Neo.overwrites` object based on the
* class's `className`. If found, it merges the properties from the overwrite object
* into the class's static `config`. This provides a powerful mechanism for theming
* or applying application-wide customizations to framework or library classes without
* needing to extend them.
*
* @example
* // Imagine you have hundreds of buttons in your app, and you want all of them
* // to have `labelPosition: 'top'` instead of the default `'left'`.
* // Instead of configuring each instance, you can define an overwrite.
*
* // inside an Overwrites.mjs file loaded by your app:
* Neo.overwrites = {
* Neo: {
* button: {
* Base: {
* labelPosition: 'top'
* }
* }
* }
* };
*
* // Now, every `Neo.button.Base` (and any class that extends it) will have this
* // new default value on its prototype.
*
* @param {Object} cfg The static `config` object of the class being processed.
* @protected
* @static
*/
static applyOverwrites(cfg) {
let overwrites = Neo.ns(cfg.className, false, Neo.overwrites),
cls, item;
if (overwrites) {
// Apply all methods
for (item in overwrites) {
if (Neo.isFunction(overwrites[item])) {
// Already existing ones
cls = this.prototype;
if (cls[item]) {
// Add to overwrittenMethods
cls.constructor.overwrittenMethods[item] = cls[item]
}
}
}
// Apply configs to prototype
Object.assign(cfg, overwrites)
}
}
/**
* Convenience method for beforeSet functions which test if a given value is inside a static array
* @param {String|Number} value
* @param {String|Number} oldValue
* @param {String} name config name
* @param {Array|String} [staticName=name + 's'] name of the static config array
* @returns {String|Number} value or oldValue
*/
beforeSetEnumValue(value, oldValue, name, staticName = name + 's') {
let values = Array.isArray(staticName) ? staticName : this.getStaticConfig(staticName);
if (!values.includes(value)) {
console.error(`Supported values for ${name} are:`, ...values, this);
return oldValue
}
return value
}
/**
* @param {String} fn The name of a function to find in the passed scope object.
* @param {Object} originName The name of the method inside the originScope.
* @param {Object} scope The scope to find the function in if it is specified as a string.
* @param {Object} originScope=this The scope where the function is located.
*/
bindCallback(fn, originName, scope=this, originScope=this) {
if (fn && Neo.isString(fn)) {
const handler = resolveCallback(fn, scope);
originScope[originName] = handler.fn.bind(handler.scope)
}
}
/**
* From within an overwrite, a method can call a parent method, by using callOverwritten.
*
* @example
* afterSetHeight(value, oldValue) {
* // do the standard
* this.callOverwritten(...arguments);
* // do you own stuff
* }
*
* We create an error to get the caller.name and then run that method on the constructor.
* This is based on the following error structure, e.g. afterSetHeight.
*
* Error
* at Base.callOverwritten (Base.mjs:176:21)
* at Base.afterSetHeight (Overrides.mjs:19:26)
*
* @param args
*/
callOverwritten(...args) {
let stack = new Error().stack,
methodName = stack.match(Base.methodNameRegex)[1];
this.__proto__.constructor.overwrittenMethods[methodName].call(this, ...args)
}
/**
* Unregisters this instance from Neo.manager.Instance
* and removes all object entries from this instance
*/
destroy() {
let me = this;
me.#asyncRejects.forEach((reject, id) => {
if (Neo.isNumber(id)) {
clearTimeout(id)
}
reject(Neo.isDestroyed)
});
me.#asyncRejects.clear();
me.#configSubscriptionCleanups.forEach(cleanup => {
cleanup()
});
if (Base.instanceManagerAvailable === true) {
Neo.manager.Instance.unregister(me)
} else if (Neo.idMap) {
delete Neo.idMap[me.id]
}
Object.keys(me).forEach(key => {
if (Object.getOwnPropertyDescriptor(me, key).writable) {
// We must not delete the custom destroy() interceptor
if (key !== 'destroy' && key !== '_id') {
delete me[key]
}
}
});
// We do want to prevent delayed event calls after an observable instance got destroyed.
if (Neo.isFunction(me.fire)) {
me.fire = Neo.emptyFn
}
me.isDestroyed = true
}
/**
* A public method to access the underlying Config controller.
* This enables advanced interactions like subscriptions.
* @param {String} key The name of the config property (e.g., 'items').
* @returns {Config|undefined} The Config instance, or undefined if not found.
*/
getConfig(key) {
let me = this;
if (!me.#configs[key] && me.isConfig(key)) {
me.#configs[key] = new Config(me.constructor.configDescriptors?.[key])
}
return me.#configs[key]
}
/**
* Used inside createId() as the default value passed to the IdGenerator.
* Override this method as needed.
* @returns {String}
*/
getIdKey() {
return this.ntype
}
/**
* Returns the value of a static config key or the staticConfig object itself in case no value is set
* @param {String} key The key of a staticConfig defined inside static getStaticConfig
* @returns {*}
*/
getStaticConfig(key) {
return this.constructor[key]
}
/**
* Check if a given ntype exists inside the proto chain, including the top level class
* @param {String} ntype
* @returns {Boolean}
*/
hasNtype(ntype) {
return this.constructor.ntypeChain.includes(ntype)
}
/**
* Gets triggered after onConstructed() is done
*/
init() {}
/**
* You can use this method in subclasses to perform asynchronous initialization logic.
* Make sure to use the parent call `await super.initAsync()` at the beginning of their implementations,
* or the registration of remote methods will get delayed.
*
* A common use case is requiring conditional or optional dynamic imports or fetching initial data.
*
* Once the promise returned by this method is fulfilled, the `isReady` config will be set to `true`.
* @returns {Promise<void>} A promise that resolves when the asynchronous initialization is complete.
*/
async initAsync() {
let me = this;
if (me.remote) {
await me.initRemote()
}
me.#remotesReadyResolver()
}
/**
* Applies all class configs to this instance
* @param {Object} config
* @param {Boolean} [preventOriginalConfig] True prevents the instance from getting an originalConfig property
* @protected
*/
initConfig(config, preventOriginalConfig) {
let me = this;
me.isConfiguring = true;
Object.assign(me[configSymbol], me.mergeConfig(config, preventOriginalConfig));
delete me[configSymbol].id;
me.processConfigs();
me.isConfiguring = false
}
/**
* Does get triggered with a delay to ensure that Neo.workerId & Neo.worker.Manager are defined
* Remote method access via promises
* @protected
*/
async initRemote() {
let me = this,
{className, remote} = me,
{currentWorker} = Neo;
if (!Neo.config.isMiddleware && !Neo.config.unitTestMode) {
// SetupClass applies `singleton` to the instance prototype if configured.
// Main thread addons are also treated as singletons for remote method access.
if (me.singleton === true || me.isMainThreadAddon === true) {
// Singleton Routing (Namespace-Driven)
if (Neo.workerId !== 'main' && currentWorker.isSharedWorker) {
if (remote.main) {
currentWorker.remotesToRegister.push({className, methods: remote.main})
}
if (!currentWorker.isConnected) {
await new Promise(resolve => {
currentWorker.on('connected', () => resolve(), me, {once: true})
})
}
} else if (Neo.workerId === 'service') {
if (remote.app) {
currentWorker.remotesToRegister.push({className, methods: remote.app})
}
}
await Base.promiseRemotes(className, remote)
} else {
// Instance-to-Instance Routing (ID-Driven)
// Unlike Singletons which broadcast their existence globally via 'registerRemote',
// instances dynamically build a `me.remote` object containing pre-bound proxy functions.
// This establishes a localized IPC channel for cross-thread architecture (e.g. data.Pipeline).
let remoteObj = {};
Object.entries(remote).forEach(([worker, methods]) => {
remoteObj[worker] = {};
methods.forEach(method => {
remoteObj[worker][method] = (data, buffer) => {
let origin = Neo.workerId === 'main' ? Neo.worker.Manager : Neo.currentWorker,
opts = {
action : 'remoteMethod',
data,
destination : worker,
remoteClassName: className,
remoteMethod : method
};
// The destination ID is resolved at execution time. This accommodates
// the "Handshake" pattern where `me.remoteId` is populated asynchronously
// after the target instance is created in the remote thread.
if (me.remoteId) {
opts.remoteId = me.remoteId
} else if (data?.remoteId) {
opts.remoteId = data.remoteId
}
if (worker === 'main' && data?.windowId) {
opts.destination = data.windowId
}
if (origin.isSharedWorker) {
origin.assignPort(data, opts)
}
return origin.promiseMessage(opts.destination, opts, buffer)
}
})
});
me.remote = remoteObj
}
}
}
/**
* @param {String} key
* @returns {Boolean}
*/
isConfig(key) {
let me = this;
// If a `core.Config` controller is already created, return true (fastest possible check).
// If not, a config is considered "reactive" if it has a generated property setter
// AND it is present as a defined config in the merged static config hierarchy.
// Neo.setupClass() removes the underscore from the static config keys.
return me.#configs[key] || (Neo.hasPropertySetter(me, key) && (key in me.constructor.config))
}
/**
* Override this method to change the order configs are applied to this instance.
* @param {Object} config
* @param {Boolean} [preventOriginalConfig] True prevents the instance from getting an originalConfig property
* @returns {Object} config
* @protected
*/
mergeConfig(config, preventOriginalConfig) {
let me = this,
ctor = me.constructor,
configDescriptors, staticConfig;
if (!ctor.config) {
throw new Error('Neo.applyClassConfig has not been run on ' + me.className)
}
if (!preventOriginalConfig) {
me.originalConfig = Neo.clone(config, true, true)
}
configDescriptors = ctor.configDescriptors;
staticConfig = ctor.config;
if (configDescriptors) {
Object.entries(config).forEach(([key, instanceValue]) => {
const descriptor = configDescriptors[key];
if (descriptor?.merge) {
config[key] = Neo.mergeConfig(staticConfig[key], instanceValue, descriptor.merge)
}
})
}
return {...staticConfig, ...config}
}
/**
* Subscribes *this* instance (the subscriber) to changes of a specific config property on another instance (the publisher).
* Ensures automatic cleanup when *this* instance (the subscriber) is destroyed.
*
* @param {String|Neo.core.Base} publisher - The ID of the publisher instance or the instance reference itself.
* @param {String} configName - The name of the config property on the publisher to subscribe to (e.g., 'myConfig').
* @param {Function} fn - The callback function to execute when the config changes.
* @returns {Function} A cleanup function to manually unsubscribe if needed before this instance's destruction.
*
* @example
* // Subscribing to a config on another instance
* this.observeConfig(someOtherInstance, 'myConfig', (newValue, oldValue) => {
* console.log('myConfig changed:', newValue);
* });
*
* // Discouraged: Self-observation. Use afterSet<ConfigName>() hooks instead.
* this.observeConfig(this, 'myOwnConfig', (newValue, oldValue) => {
* console.log('myOwnConfig changed:', newValue);
* });
*/
observeConfig(publisher, configName, fn) {
let publisherInstance = publisher;
if (Neo.isString(publisher)) {
publisherInstance = Neo.get(publisher);
if (!publisherInstance) {
console.warn(`Publisher instance with ID '${publisher}' not found. Cannot subscribe.`);
return Neo.emptyFn
}
}
if (!(publisherInstance instanceof Neo.core.Base)) {
console.warn(`Invalid publisher provided. Must be a Neo.core.Base instance or its ID.`);
return Neo.emptyFn
}
const configController = publisherInstance.getConfig(configName);
if (!configController) {
console.warn(`Config '${configName}' not found on publisher instance ${publisherInstance.id}. Cannot subscribe.`);
return Neo.emptyFn
}
const cleanup = configController.subscribe({id: this.id, fn});
this.#configSubscriptionCleanups.push(cleanup);
return cleanup
}
/**
*
*/
onAfterConstructed() {
let me = this;
me.isConstructed = true;
// We can only fire the event in case the Observable mixin is included.
me.getStaticConfig('observable') && me.fire('constructed', me)
}
/**
* Gets triggered after all constructors are done
*/
onConstructed() {}
/**
* Placeholder method for intercepting remote calls.
* Subclasses can override this method to implement custom interception logic.
* @param {Object} msg The remote message object.
*/
onInterceptRemotes(msg) {
// No-op in base class
}
/**
* Helper method to replace string-based values containing "@config:" with the matching config value
* of this instance.
* @param {Object|Object[]} items
*/
parseItemConfigs(items) {
let me = this,
ns, nsArray, nsKey, symbolNs;
if (items) {
if (!Array.isArray(items)) {
if (Neo.isObject(items)) {
Object.keys(items).forEach(key => {
let item = items[key];
if (item) {
if (item[mergeFrom]) {
if (me[item[mergeFrom]]) {
items[key] = Neo.mergeConfig(me[item[mergeFrom]], item, 'deep');
item = items[key];
delete item[mergeFrom]
}
}
me.parseItemConfigs([item])
}
});
return
}
items = [items]
}
items.forEach((item, index) => {
if (item) {
if (item[mergeFrom]) {
if (me[item[mergeFrom]]) {
items[index] = Neo.mergeConfig(me[item[mergeFrom]], item, 'deep');
item = items[index];
delete item[mergeFrom]
}
}
Object.entries(item).forEach(([key, value]) => {
if (Array.isArray(value)) {
me.parseItemConfigs(value);
} else if (Neo.isObject(value) && key === 'items') {
me.parseItemConfigs(value)
} else if (typeof value === 'string' && value.startsWith('@config:')) {
nsArray = value.substring(8).trim().split('.');
nsKey = nsArray.pop();
ns = Neo.ns(nsArray, false, me);
if (ns[nsKey] === undefined) {
console.error('The used @config does not exist:', nsKey, nsArray.join('.'))
} else {
symbolNs = Neo.ns(nsArray, false, me[configSymbol]);
// The config might not be processed yet, especially for configs
// not ending with an underscore, so we need to check the configSymbol first.
if (symbolNs && Object.hasOwn(symbolNs, nsKey)) {
item[key] = symbolNs[nsKey]
} else {
item[key] = ns[nsKey]
}
}
}
})
}
})
}
}
/**
* Intercepts destroy() calls to ensure they will only get called once
* @returns {Boolean}
* @private
*/
#preDestroyHook() {
this.isDestroying = true;
return !this.isDestroyed
}
/**
* When using set(), configs without a trailing underscore can already be assigned,
* so the hasOwnProperty() check will return true
* @param {Boolean} [forceAssign=false]
* @protected
*/
processConfigs(forceAssign=false) {
let me = this,
keys = Object.keys(me[configSymbol]);
me[forceAssignConfigs] = forceAssign;
// We do not want to iterate over the keys, since 1 config can remove more than 1 key (beforeSetX, afterSetX)
if (keys.length > 0) {
// The hasOwnProperty check is intended for configs without a trailing underscore
// => they could already have been assigned inside an afterSet-method
if (forceAssign || !me.hasOwnProperty(keys[0])) {
me[keys[0]] = me[configSymbol][keys[0]]
}
// there is a delete-call inside the config getter as well (Neo.mjs => autoGenerateGetSet())
// we need to keep this one for configs, which do not use getters (no trailing underscore)
delete me[configSymbol][keys[0]];
me.processConfigs(forceAssign)
}
}
/**
* Returns a promise that resolves when the instance is fully initialized (after initAsync).
* Use case: alternative way to subscribe to the ready state, especially for classes which are not observable.
* @example: await ChromaManager.ready();
* @returns {Promise<void>}
*/
ready() {
return this.#readyPromise
}
/**
* Returns a promise that resolves when the remote methods are registered.
* @returns {Promise<void>}
*/
remotesReady() {
return this.#remotesReadyPromise
}
/**
* Sends remote method registration messages to other threads (workers or main-threads).
* This method is crucial for enabling cross-worker communication and remote method invocation
* for singleton instances. It ensures that methods defined in the `remote` config
* are properly registered in the target realm.
* @param {String} className - The class name of the instance sending the remote messages.
* @param {Object} remote - The remote config object, specifying target threads and methods.
* @protected
* @static
*/
static async promiseRemotes(className, remote) {
let origin, promises = [];
Object.entries(remote).forEach(([worker, methods]) => {
if (Neo.workerId !== worker) {
origin = Neo.workerId === 'main' ? Neo.worker.Manager : Neo.currentWorker;
if (origin.hasWorker(worker)) {
promises.push(origin.promiseMessage(worker, {action: 'registerRemote', className, methods}))
}
}
});
await Promise.all(promises)
}
/**
* Serializes a config object/array to be JSON-compatible.
* Use this method when a config might contain references to Neo classes (constructors)
* which need to be converted to their className strings for serialization.
* @param {Array|Object} config
* @returns {Array|Object}
*/
serializeConfig(config) {
let me = this,
type = Neo.typeOf(config);
if (type === 'Array') {
return config.map(item => me.serializeConfig(item))
}
if (type === 'NeoInstance') {
return {
className: config.className,
id : config.id