assign-gingerly 0.0.37 → 0.0.39

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.
@@ -0,0 +1,683 @@
1
+ /**
2
+ * assignFeatures - Dependency injection for custom element features
3
+ *
4
+ * Allows custom element authors to declare supported feature slots via
5
+ * `static supportedFeatures`, then have implementations injected via
6
+ * `customElementRegistry.assignFeatures(Ctor, features)`.
7
+ *
8
+ * Features are lazily instantiated on first property access via getter-only
9
+ * properties installed on the class prototype.
10
+ */
11
+
12
+ import { parseWithAttrs } from './parseWithAttrs.js';
13
+
14
+ /**
15
+ * Context passed to feature spawn constructors
16
+ */
17
+ export interface FeatureSpawnContext {
18
+ /** The feature key (e.g., 'photoTaker') */
19
+ key: string;
20
+ /** The SupportedFeatureConfig from static supportedFeatures */
21
+ optIn: SupportedFeatureConfig;
22
+ /** The FeatureConfig from assignFeatures */
23
+ injection: FeatureConfig;
24
+ /** The features registry reference */
25
+ featuresRegistry: FeaturesRegistry;
26
+ /** Shared context from the host element (via getSharedContext callback) */
27
+ shared?: any;
28
+ }
29
+
30
+ export interface SupportedFeatureConfig {
31
+ /**
32
+ * Optional fallback class (or async spawner) to use if no implementation is injected.
33
+ */
34
+ fallbackSpawn?:
35
+ | { new(hostElement: any, ctx: FeatureSpawnContext, initVals?: any): any }
36
+ | (() => Promise<{ new(hostElement: any, ctx: FeatureSpawnContext, initVals?: any): any }>);
37
+
38
+ /**
39
+ * Optional runtime shape validation for the spawned instance.
40
+ * Return true if the instance is valid, false to throw.
41
+ */
42
+ validateShape?: (spawnedInstance: any) => boolean;
43
+
44
+ /**
45
+ * Optional callback to provide shared context (e.g., ElementInternals, private state)
46
+ * to the feature at construction time.
47
+ *
48
+ * Defined in the class body, this callback has access to #private fields
49
+ * because static methods/properties of a class can access private fields
50
+ * of instances of that class.
51
+ *
52
+ * The returned object is passed to the feature constructor as `ctx.shared`.
53
+ *
54
+ * @param instance - The host element instance
55
+ * @returns An object containing shared data for the feature
56
+ *
57
+ * @example
58
+ * static supportedFeatures = {
59
+ * ariaManager: {
60
+ * fallbackSpawn: AriaManagerImpl,
61
+ * getSharedContext(instance) {
62
+ * return { internals: instance.#internals };
63
+ * }
64
+ * }
65
+ * }
66
+ */
67
+ getSharedContext?: (instance: any) => any;
68
+ }
69
+
70
+ /**
71
+ * Class-level configuration for the features system.
72
+ * Declared as `static featuresConfig` on the class.
73
+ *
74
+ * @example
75
+ * class ClubMember extends HTMLElement {
76
+ * static supportedFeatures = { photoTaker: { fallbackSpawn: PhotoTakerImpl } }
77
+ * static featuresConfig = { lifecycleKeys: true }
78
+ * }
79
+ */
80
+ export interface FeaturesClassConfig {
81
+ /**
82
+ * Lifecycle method configuration.
83
+ *
84
+ * If set to `true`, installs a method named 'whenFeatureReady' on the prototype.
85
+ * If set to an object, allows customizing the method name.
86
+ *
87
+ * The installed method accepts a feature key and returns a Promise that resolves
88
+ * with the feature instance once it's ready (useful for async spawners).
89
+ * For synchronous spawners, the Promise resolves immediately.
90
+ *
91
+ * Suggested default name: 'whenFeatureReady'
92
+ *
93
+ * @example
94
+ * static featuresConfig = { lifecycleKeys: true }
95
+ * // await el.whenFeatureReady('photoTaker')
96
+ *
97
+ * @example
98
+ * static featuresConfig = { lifecycleKeys: { whenFeatureReady: 'awaitFeature' } }
99
+ * // await el.awaitFeature('photoTaker')
100
+ */
101
+ lifecycleKeys?: true | {
102
+ /** Method name for awaiting feature readiness. Defaults to 'whenFeatureReady'. */
103
+ whenFeatureReady?: string;
104
+ };
105
+ }
106
+
107
+ export interface FeatureConfig {
108
+ /**
109
+ * The class to instantiate for this feature, or an async function that
110
+ * resolves to such a class (for lazy-loading).
111
+ *
112
+ * Synchronous: Constructor receives the host element as its first argument,
113
+ * a FeatureSpawnContext as second, and optional initVals as third.
114
+ *
115
+ * Asynchronous: A function (arrow or async) that returns a Promise resolving
116
+ * to a constructor. The getter returns a placeholder object immediately and
117
+ * instantiates the real class once the Promise resolves.
118
+ */
119
+ spawn?:
120
+ | { new(hostElement: any, ctx: FeatureSpawnContext, initVals?: any): any }
121
+ | (() => Promise<{ new(hostElement: any, ctx: FeatureSpawnContext, initVals?: any): any }>);
122
+
123
+ /**
124
+ * Attribute patterns for parsing element attributes into initVals.
125
+ * Attributes are the "base layer" — programmatic values override them.
126
+ * Always unprefixed for features (no enh- prefix).
127
+ */
128
+ withAttrs?: any; // AttrPatterns<any> — imported type from types
129
+
130
+ /**
131
+ * Reserved field for custom configuration data.
132
+ * Not interpreted by the library — available to the feature class
133
+ * via ctx.injection.customData in the constructor.
134
+ */
135
+ customData?: any;
136
+ }
137
+
138
+ export type SupportedFeaturesMap = Record<string, SupportedFeatureConfig>;
139
+ export type FeatureConfigsMap = Record<string, FeatureConfig>;
140
+
141
+ /**
142
+ * WeakMap storing per-instance feature caches.
143
+ * Outer key: the instance (element or other object).
144
+ * Inner map: feature key -> spawned instance.
145
+ */
146
+ const featureStorage = new WeakMap<object, Map<string, any>>();
147
+
148
+ /**
149
+ * The features registry: maps a constructor to its accumulated feature injections.
150
+ */
151
+ export class FeaturesRegistry {
152
+ #registry = new Map<Function, Map<string, FeatureConfig>>();
153
+
154
+ has(ctr: Function): boolean {
155
+ return this.#registry.has(ctr);
156
+ }
157
+
158
+ get(ctr: Function): Map<string, FeatureConfig> | undefined {
159
+ return this.#registry.get(ctr);
160
+ }
161
+
162
+ set(ctr: Function, key: string, injection: FeatureConfig): void {
163
+ let features = this.#registry.get(ctr);
164
+ if (!features) {
165
+ features = new Map();
166
+ this.#registry.set(ctr, features);
167
+ }
168
+ features.set(key, injection);
169
+ }
170
+
171
+ hasKey(ctr: Function, key: string): boolean {
172
+ const features = this.#registry.get(ctr);
173
+ return features ? features.has(key) : false;
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Sentinel symbol to mark stored values as raw initVals (not yet spawned).
179
+ */
180
+ const RAW_INIT_VALS = Symbol('rawInitVals');
181
+
182
+ /**
183
+ * Sentinel symbol to mark stored values as error state from failed async spawn.
184
+ */
185
+ const FEATURE_ERROR = Symbol('featureError');
186
+
187
+ /**
188
+ * WeakMap storing pending Promises for async feature resolution.
189
+ * Outer key: the instance. Inner map: feature key -> { promise, resolve, reject }.
190
+ */
191
+ const pendingFeatures = new WeakMap<object, Map<string, { promise: Promise<any>, resolve: Function, reject: Function }>>();
192
+
193
+ /**
194
+ * Resolves the whenFeatureReady method name from lifecycleKeys config.
195
+ * Returns undefined if lifecycleKeys is not set.
196
+ */
197
+ function resolveWhenFeatureReadyName(lifecycleKeys: true | { whenFeatureReady?: string } | undefined): string | undefined {
198
+ if (lifecycleKeys === undefined) return undefined;
199
+ if (lifecycleKeys === true) return 'whenFeatureReady';
200
+ return lifecycleKeys.whenFeatureReady || 'whenFeatureReady';
201
+ }
202
+
203
+ /**
204
+ * Installs the whenFeatureReady method on the constructor prototype if not already present.
205
+ */
206
+ function installWhenFeatureReadyMethod(ctr: Function, methodName: string): void {
207
+ // Only install once per class
208
+ if (Object.getOwnPropertyDescriptor(ctr.prototype, methodName)) return;
209
+
210
+ Object.defineProperty(ctr.prototype, methodName, {
211
+ value: function (this: any, featureKey: string): Promise<any> {
212
+ // Trigger the getter (starts async resolution if needed, or returns sync instance)
213
+ const current = this[featureKey];
214
+
215
+ // Check if there's a pending async resolution for this instance + key
216
+ const pending = pendingFeatures.get(this)?.get(featureKey);
217
+ if (pending) {
218
+ return pending.promise;
219
+ }
220
+
221
+ // No pending — feature is already resolved (sync or async already completed)
222
+ return Promise.resolve(current);
223
+ },
224
+ writable: true,
225
+ enumerable: false,
226
+ configurable: true
227
+ });
228
+ }
229
+
230
+ /**
231
+ * Determines if a function is an async spawner (returns a Promise<Constructor>)
232
+ * rather than a synchronous constructor.
233
+ *
234
+ * Heuristic:
235
+ * - AsyncFunction (async () => ...) → async spawner
236
+ * - Arrow function (no .prototype) → async spawner (assumed to return Promise<Constructor>)
237
+ * - Class or function declaration (has .prototype) → synchronous constructor
238
+ */
239
+ function isAsyncSpawn(fn: any): boolean {
240
+ if (typeof fn !== 'function') return false;
241
+ // Explicit async function
242
+ if (fn.constructor.name === 'AsyncFunction') return true;
243
+ // Arrow function or non-constructor function (no .prototype)
244
+ if (fn.prototype === undefined) return true;
245
+ return false;
246
+ }
247
+
248
+ /**
249
+ * Installs a getter/setter pair on the constructor's prototype for the given feature key.
250
+ *
251
+ * - The setter stores raw values (pre-upgrade or early assignment) into the WeakMap
252
+ * tagged with a sentinel so the getter knows they are initVals, not spawned instances.
253
+ * - The getter spawns the feature instance on first access, using any stored raw value
254
+ * as initVals, then caches the spawned instance.
255
+ *
256
+ * If an own-property with the same key exists on the instance (e.g., set before
257
+ * the element upgraded), it is captured as initVals and deleted so the prototype
258
+ * getter/setter is no longer shadowed.
259
+ */
260
+ function installFeatureGetter(
261
+ ctr: Function,
262
+ key: string,
263
+ featuresRegistry: FeaturesRegistry
264
+ ): void {
265
+ Object.defineProperty(ctr.prototype, key, {
266
+ get: function (this: any) {
267
+ // Get or create the per-instance storage
268
+ let storage = featureStorage.get(this);
269
+ if (!storage) {
270
+ storage = new Map();
271
+ featureStorage.set(this, storage);
272
+ }
273
+
274
+ const stored = storage.get(key);
275
+
276
+ // Check for error state from failed async spawn
277
+ if (stored && typeof stored === 'object' && FEATURE_ERROR in stored) {
278
+ throw stored[FEATURE_ERROR];
279
+ }
280
+
281
+ // If already spawned (not a raw sentinel, not undefined), return it
282
+ if (stored !== undefined && !(stored && typeof stored === 'object' && RAW_INIT_VALS in stored)) {
283
+ return stored;
284
+ }
285
+
286
+ // Determine initVals: from setter-stored raw value, or from own-property shadow
287
+ let initVals: any = undefined;
288
+ if (stored && typeof stored === 'object' && RAW_INIT_VALS in stored) {
289
+ initVals = stored[RAW_INIT_VALS];
290
+ storage.delete(key);
291
+ } else if (Object.hasOwn(this, key)) {
292
+ initVals = this[key];
293
+ delete this[key]; // Unshadow the prototype accessor
294
+ }
295
+
296
+ // Resolve the registry — use scoped registry if available, fall back to global
297
+ const registry = (this.customElementRegistry || customElements) as any;
298
+ const fr: FeaturesRegistry = registry.featuresRegistry;
299
+
300
+ if (!fr || !fr.has(ctr)) {
301
+ throw new Error(`assignFeatures: featuresRegistry missing entry for constructor`);
302
+ }
303
+
304
+ const features = fr.get(ctr)!;
305
+ const injection = features.get(key);
306
+
307
+ if (!injection) {
308
+ throw new Error(`assignFeatures: no injection found for feature "${key}"`);
309
+ }
310
+
311
+ // Resolve spawn: injection.spawn takes priority, then fallbackSpawn
312
+ const supportedFeatures = (ctr as any).supportedFeatures;
313
+ const optIn: SupportedFeatureConfig | undefined = supportedFeatures?.[key];
314
+
315
+ if (!optIn) {
316
+ throw new Error(`assignFeatures: "${key}" not in static supportedFeatures`);
317
+ }
318
+
319
+ const SpawnClass = injection.spawn || optIn.fallbackSpawn;
320
+
321
+ if (!SpawnClass) {
322
+ throw new Error(
323
+ `assignFeatures: no spawn implementation found for feature "${key}". ` +
324
+ `Provide spawn in assignFeatures() or fallbackSpawn in supportedFeatures.`
325
+ );
326
+ }
327
+
328
+ // Build the spawn context
329
+ const shared = optIn.getSharedContext?.(this);
330
+ const ctx: FeatureSpawnContext = {
331
+ key,
332
+ optIn,
333
+ injection,
334
+ featuresRegistry: fr,
335
+ shared
336
+ };
337
+
338
+ // Parse attributes if withAttrs is configured
339
+ let attrInitVals: any = undefined;
340
+ if (injection.withAttrs && this instanceof Element) {
341
+ try {
342
+ attrInitVals = parseWithAttrs(
343
+ this as Element,
344
+ injection.withAttrs,
345
+ true // always unprefixed for features
346
+ );
347
+ } catch (e) {
348
+ console.error('Error parsing feature attributes:', e);
349
+ throw e;
350
+ }
351
+ }
352
+
353
+ // Merge: attributes are base layer, programmatic initVals override
354
+ if (attrInitVals) {
355
+ initVals = initVals
356
+ ? { ...attrInitVals, ...initVals }
357
+ : attrInitVals;
358
+ }
359
+
360
+ if (isAsyncSpawn(SpawnClass)) {
361
+ // Async path: SpawnClass is a function that returns Promise<Constructor>
362
+ const placeholder = initVals && typeof initVals === 'object' ? initVals : {};
363
+ storage.set(key, placeholder);
364
+
365
+ // Capture host element reference for the async callback
366
+ const hostElement = this;
367
+
368
+ // Create a pending Promise for whenFeatureReady consumers
369
+ let pendingMap = pendingFeatures.get(hostElement);
370
+ if (!pendingMap) {
371
+ pendingMap = new Map();
372
+ pendingFeatures.set(hostElement, pendingMap);
373
+ }
374
+ let resolvePending: Function;
375
+ let rejectPending: Function;
376
+ const promise = new Promise<any>((resolve, reject) => {
377
+ resolvePending = resolve;
378
+ rejectPending = reject;
379
+ });
380
+ pendingMap.set(key, { promise, resolve: resolvePending!, reject: rejectPending! });
381
+
382
+ // Kick off async resolution
383
+ (SpawnClass as () => Promise<any>)().then((ResolvedClass: any) => {
384
+ // Mutate injection so future getter calls see the resolved constructor
385
+ (injection as any).spawn = ResolvedClass;
386
+
387
+ // Get the current placeholder (may have accumulated properties via assignGingerly)
388
+ const currentStorage = featureStorage.get(hostElement);
389
+ const currentPlaceholder = currentStorage?.get(key);
390
+
391
+ // Don't upgrade if an error was stored or if already upgraded
392
+ if (!currentPlaceholder || (typeof currentPlaceholder === 'object' && FEATURE_ERROR in currentPlaceholder)) {
393
+ return;
394
+ }
395
+
396
+ // Parse attributes at resolution time (element should be in DOM by now)
397
+ let asyncAttrInitVals: any = undefined;
398
+ if (injection.withAttrs && hostElement instanceof Element) {
399
+ try {
400
+ asyncAttrInitVals = parseWithAttrs(
401
+ hostElement as Element,
402
+ injection.withAttrs,
403
+ true // always unprefixed for features
404
+ );
405
+ } catch (e) {
406
+ // Non-fatal: log and continue with placeholder as initVals
407
+ console.error('Error parsing feature attributes during async resolution:', e);
408
+ }
409
+ }
410
+
411
+ // Merge: attributes are base, placeholder (programmatic) overrides
412
+ const asyncInitVals = asyncAttrInitVals
413
+ ? { ...asyncAttrInitVals, ...currentPlaceholder }
414
+ : currentPlaceholder;
415
+
416
+ // Instantiate the real class with merged initVals
417
+ const realCtx: FeatureSpawnContext = {
418
+ key,
419
+ optIn,
420
+ injection,
421
+ featuresRegistry: fr,
422
+ shared: optIn.getSharedContext?.(hostElement)
423
+ };
424
+ const instance = new ResolvedClass(hostElement, realCtx, asyncInitVals);
425
+
426
+ // Validate shape if configured
427
+ if (optIn.validateShape) {
428
+ if (!optIn.validateShape(instance)) {
429
+ const error: any = new Error(
430
+ `assignFeatures: spawned instance for "${key}" failed shape validation`
431
+ );
432
+ error.placeholder = currentPlaceholder;
433
+ currentStorage!.set(key, { [FEATURE_ERROR]: error });
434
+ rejectPending!(error);
435
+ pendingMap!.delete(key);
436
+ return;
437
+ }
438
+ }
439
+
440
+ // Replace placeholder with real instance
441
+ currentStorage!.set(key, instance);
442
+
443
+ // Resolve the pending Promise and clean up
444
+ resolvePending!(instance);
445
+ pendingMap!.delete(key);
446
+ }).catch((err: any) => {
447
+ // Store error state — getter will throw on next access
448
+ const currentStorage = featureStorage.get(hostElement);
449
+ const currentPlaceholder = currentStorage?.get(key);
450
+ const error: any = new Error(
451
+ `assignFeatures: async spawn for "${key}" failed: ${err.message}`
452
+ );
453
+ error.placeholder = currentPlaceholder;
454
+ error.cause = err;
455
+ currentStorage?.set(key, { [FEATURE_ERROR]: error });
456
+
457
+ // Reject the pending Promise and clean up
458
+ rejectPending!(error);
459
+ pendingMap!.delete(key);
460
+ });
461
+
462
+ return placeholder;
463
+ } else {
464
+ // Synchronous path: SpawnClass is a constructor
465
+ const instance = new (SpawnClass as any)(this, ctx, initVals);
466
+
467
+ // Validate shape if configured
468
+ if (optIn.validateShape) {
469
+ if (!optIn.validateShape(instance)) {
470
+ throw new Error(
471
+ `assignFeatures: spawned instance for "${key}" failed shape validation`
472
+ );
473
+ }
474
+ }
475
+
476
+ storage.set(key, instance);
477
+ return instance;
478
+ }
479
+ },
480
+ enumerable: true,
481
+ configurable: false
482
+ });
483
+ }
484
+
485
+ /**
486
+ * Core assignFeatures implementation.
487
+ * Validates inputs, registers injections, and installs lazy getters.
488
+ *
489
+ * Important: Call assignFeatures BEFORE customElements.define(), or at minimum
490
+ * before any instances of the element are created. The lazy getters must be on
491
+ * the prototype before instances exist to properly capture pre-set properties.
492
+ *
493
+ * @param ctr - The constructor (class) to assign features to
494
+ * @param features - Map of feature keys to their injection configs
495
+ * @param featuresRegistry - The registry to store injections in
496
+ */
497
+ export function assignFeatures(
498
+ ctr: Function,
499
+ features: FeatureConfigsMap,
500
+ featuresRegistry: FeaturesRegistry
501
+ ): void {
502
+ // Validate that the constructor has static supportedFeatures
503
+ const supportedFeatures: SupportedFeaturesMap | undefined = (ctr as any).supportedFeatures;
504
+
505
+ if (!supportedFeatures) {
506
+ throw new Error(
507
+ `assignFeatures: ${ctr.name || 'constructor'} does not define static supportedFeatures`
508
+ );
509
+ }
510
+
511
+ for (const key of Object.keys(features)) {
512
+ // 1. Confirm the key is opted-in via supportedFeatures
513
+ if (!(key in supportedFeatures)) {
514
+ throw new Error(
515
+ `assignFeatures: "${key}" is not declared in ${ctr.name || 'constructor'}.supportedFeatures`
516
+ );
517
+ }
518
+
519
+ // 2. Check that the prototype doesn't already have this property defined
520
+ const existingDescriptor = Object.getOwnPropertyDescriptor(ctr.prototype, key);
521
+ if (existingDescriptor) {
522
+ throw new Error(
523
+ `assignFeatures: "${key}" already exists on ${ctr.name || 'constructor'}.prototype`
524
+ );
525
+ }
526
+
527
+ // 3. Check that this key hasn't already been registered for this constructor
528
+ if (featuresRegistry.hasKey(ctr, key)) {
529
+ throw new Error(
530
+ `assignFeatures: "${key}" has already been assigned for ${ctr.name || 'constructor'}`
531
+ );
532
+ }
533
+
534
+ // 4. Register the injection
535
+ featuresRegistry.set(ctr, key, features[key]);
536
+
537
+ // 5. Install the lazy getter on the prototype
538
+ installFeatureGetter(ctr, key, featuresRegistry);
539
+ }
540
+
541
+ // 6. Install whenFeatureReady method if featuresConfig.lifecycleKeys is configured
542
+ const featuresConfig: FeaturesClassConfig | undefined = (ctr as any).featuresConfig;
543
+ if (featuresConfig?.lifecycleKeys) {
544
+ const methodName = resolveWhenFeatureReadyName(featuresConfig.lifecycleKeys);
545
+ if (methodName) {
546
+ installWhenFeatureReadyMethod(ctr, methodName);
547
+ }
548
+ }
549
+ }
550
+
551
+ /**
552
+ * Captures own-properties that shadow feature getters and stores them as initVals.
553
+ * Call this in the custom element constructor to handle pre-upgrade property values.
554
+ *
555
+ * When an element exists in the DOM before `define()` is called, properties may have
556
+ * been set on it directly. After upgrade, these own-properties shadow the prototype
557
+ * getters installed by `assignFeatures`. This helper captures those values and deletes
558
+ * the own-properties so the getters can function properly.
559
+ *
560
+ * @param instance - The custom element instance (typically `this` in the constructor)
561
+ *
562
+ * @example
563
+ * class ClubMember extends HTMLElement {
564
+ * static supportedFeatures = { photoTaker: { fallbackSpawn: PhotoTakerImpl } }
565
+ * constructor() {
566
+ * super();
567
+ * captureFeatureInitVals(this);
568
+ * }
569
+ * }
570
+ */
571
+ export function captureFeatureInitVals(instance: any): void {
572
+ const ctr = instance.constructor;
573
+ const supportedFeatures = ctr.supportedFeatures;
574
+ if (!supportedFeatures) return;
575
+
576
+ for (const key of Object.keys(supportedFeatures)) {
577
+ if (Object.hasOwn(instance, key)) {
578
+ const value = instance[key];
579
+ delete instance[key];
580
+
581
+ // Store in the WeakMap so the getter can pick it up
582
+ let storage = featureStorage.get(instance);
583
+ if (!storage) {
584
+ storage = new Map();
585
+ featureStorage.set(instance, storage);
586
+ }
587
+ storage.set(key, { [RAW_INIT_VALS]: value });
588
+ }
589
+ }
590
+ }
591
+
592
+ // =============================================================================
593
+ // PropertyBag — base class for nested feature containers
594
+ // =============================================================================
595
+
596
+ /**
597
+ * PropertyBag is a base class for creating nested feature containers.
598
+ *
599
+ * Subclass it to group related features under a single namespace property.
600
+ * PropertyBag carries the `customElementRegistry` reference from the host element
601
+ * so that nested features can resolve their registries correctly.
602
+ *
603
+ * PropertyBag must be subclassed — direct instantiation throws an error.
604
+ * Subclasses must define `static supportedFeatures` to declare their feature slots.
605
+ *
606
+ * @example
607
+ * class ClubMemberBehaviors extends PropertyBag {
608
+ * static supportedFeatures = {
609
+ * commandBehavior: { fallbackSpawn: CommandFeatureImpl },
610
+ * ariaBehavior: { fallbackSpawn: AriaFeatureImpl }
611
+ * }
612
+ * }
613
+ *
614
+ * class ClubMember extends HTMLElement {
615
+ * static supportedFeatures = {
616
+ * behaviors: { fallbackSpawn: ClubMemberBehaviors }
617
+ * }
618
+ * }
619
+ *
620
+ * customElements.assignFeatures(ClubMember, { behaviors: { spawn: ClubMemberBehaviors } });
621
+ * customElements.assignFeatures(ClubMemberBehaviors, {
622
+ * commandBehavior: { spawn: CommandFeatureImpl }
623
+ * });
624
+ */
625
+ export class PropertyBag {
626
+ /** Registry reference carried from the host element */
627
+ customElementRegistry: any;
628
+
629
+ constructor(hostElement: any, ctx?: FeatureSpawnContext, initVals?: any) {
630
+ if (this.constructor === PropertyBag) {
631
+ throw new Error(
632
+ 'PropertyBag must be subclassed. Define static supportedFeatures on your subclass.'
633
+ );
634
+ }
635
+
636
+ // Carry the registry reference from the host element
637
+ this.customElementRegistry = hostElement.customElementRegistry ||
638
+ (typeof customElements !== 'undefined' ? customElements : undefined);
639
+
640
+ // Apply any initVals
641
+ if (initVals && typeof initVals === 'object') {
642
+ Object.assign(this, initVals);
643
+ }
644
+ }
645
+ }
646
+
647
+ // =============================================================================
648
+ // Self-installing: adds featuresRegistry and assignFeatures to CustomElementRegistry
649
+ // This code runs as a side effect when this module is imported.
650
+ // =============================================================================
651
+
652
+ declare global {
653
+ interface CustomElementRegistry {
654
+ featuresRegistry: FeaturesRegistry;
655
+ assignFeatures(ctr: Function, features: FeatureConfigsMap): void;
656
+ }
657
+ }
658
+
659
+ if (typeof CustomElementRegistry !== 'undefined') {
660
+ Object.defineProperty(CustomElementRegistry.prototype, 'featuresRegistry', {
661
+ get: function () {
662
+ const registry = new FeaturesRegistry();
663
+ Object.defineProperty(this, 'featuresRegistry', {
664
+ value: registry,
665
+ writable: true,
666
+ enumerable: false,
667
+ configurable: true,
668
+ });
669
+ return registry;
670
+ },
671
+ enumerable: false,
672
+ configurable: true,
673
+ });
674
+
675
+ Object.defineProperty(CustomElementRegistry.prototype, 'assignFeatures', {
676
+ value: function (ctr: Function, features: FeatureConfigsMap): void {
677
+ assignFeatures(ctr, features, this.featuresRegistry);
678
+ },
679
+ writable: true,
680
+ enumerable: false,
681
+ configurable: true,
682
+ });
683
+ }