wraplet 1.0.0-beta.21 → 1.0.0-beta.22
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.
- package/dist/DependencyManager/DDM.d.ts +3 -0
- package/dist/ambient.d.ts +4 -97
- package/dist/errors.d.ts +0 -2
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/utils/utils.d.ts +1 -0
- package/package.json +27 -33
- package/dist/Storage/AbstractNongranularKeyValueStorage.d.ts +0 -30
- package/dist/Storage/ElementAttributeStorage.d.ts +0 -13
- package/dist/Storage/ElementOptionsMerger.d.ts +0 -1
- package/dist/Storage/ElementStorage.d.ts +0 -11
- package/dist/Storage/NongranularStorageOptions.d.ts +0 -5
- package/dist/Storage/StorageWrapper.d.ts +0 -21
- package/dist/Storage/types/KeyValueStorage.d.ts +0 -13
- package/dist/Storage/types/KeyValueStorageReadonly.d.ts +0 -6
- package/dist/Storage/types/StorageValidators.d.ts +0 -2
- package/dist/Wraplet/statusActions.d.ts +0 -7
- package/dist/Wraplet/utils.d.ts +0 -1
- package/dist/storage.cjs +0 -2
- package/dist/storage.cjs.map +0 -1
- package/dist/storage.d.ts +0 -9
- package/dist/storage.js +0 -2
- package/dist/storage.js.map +0 -1
|
@@ -13,6 +13,9 @@ export declare class DDM<N extends Node = Node, M extends WrapletDependencyMap =
|
|
|
13
13
|
[DependencyManagerSymbol]: true;
|
|
14
14
|
private logger;
|
|
15
15
|
private dependenciesAreInstantiated;
|
|
16
|
+
private initializePromise;
|
|
17
|
+
private destroyPromise;
|
|
18
|
+
private syncPromise;
|
|
16
19
|
status: DDMStatus;
|
|
17
20
|
private readonly mapTree;
|
|
18
21
|
private directDependencies;
|
package/dist/ambient.d.ts
CHANGED
|
@@ -3,6 +3,9 @@ class DDM<N extends Node = Node, M extends WrapletDependencyMap = {}> implements
|
|
|
3
3
|
[DependencyManagerSymbol]: true;
|
|
4
4
|
private logger;
|
|
5
5
|
private dependenciesAreInstantiated;
|
|
6
|
+
private initializePromise;
|
|
7
|
+
private destroyPromise;
|
|
8
|
+
private syncPromise;
|
|
6
9
|
status: DDMStatus;
|
|
7
10
|
private readonly mapTree;
|
|
8
11
|
private directDependencies;
|
|
@@ -222,96 +225,6 @@ const WrapletSetReadonlySymbol: unique symbol;
|
|
|
222
225
|
interface WrapletSetReadonly<T extends Wraplet = Wraplet> extends BaseSet<T>, ReadonlySet<T> {
|
|
223
226
|
[WrapletSetReadonlySymbol]: true;
|
|
224
227
|
}
|
|
225
|
-
type ValidatorsFor<D extends Record<string, unknown>, IS_PARTIAL extends boolean> = IS_PARTIAL extends true ? Partial<StorageValidators<D>> : StorageValidators<D>;
|
|
226
|
-
abstract class AbstractNongranularKeyValueStorage<D extends Record<string, unknown>, IS_PARTIAL extends boolean = false, V extends ValidatorsFor<D, IS_PARTIAL> = ValidatorsFor<D, IS_PARTIAL>> implements KeyValueStorage<D> {
|
|
227
|
-
private isPartial;
|
|
228
|
-
protected defaults: D;
|
|
229
|
-
protected validators: V;
|
|
230
|
-
[KeyValueStorageSymbol]: true;
|
|
231
|
-
private data;
|
|
232
|
-
private options;
|
|
233
|
-
protected constructor(isPartial: IS_PARTIAL, defaults: D, validators: V, options?: Partial<NongranularStorageOptions<D>>);
|
|
234
|
-
has(key: keyof D): Promise<boolean>;
|
|
235
|
-
get<T extends keyof D>(key: T): Promise<D[T]>;
|
|
236
|
-
getMultiple<T extends keyof D>(keys: T[]): Promise<Pick<D, T>>;
|
|
237
|
-
getAll(): Promise<D>;
|
|
238
|
-
set<T extends keyof D>(key: T, value: D[T]): Promise<void>;
|
|
239
|
-
setMultiple(data: Partial<D>): Promise<void>;
|
|
240
|
-
setAll(data: D): Promise<void>;
|
|
241
|
-
delete(key: keyof D): Promise<void>;
|
|
242
|
-
deleteMultiple(keys: (keyof D)[]): Promise<void>;
|
|
243
|
-
deleteAll(): Promise<void>;
|
|
244
|
-
refresh(): Promise<void>;
|
|
245
|
-
private fetchFreshData;
|
|
246
|
-
private validateData;
|
|
247
|
-
private validateValidators;
|
|
248
|
-
protected abstract getValue(): Promise<string>;
|
|
249
|
-
protected abstract setValue(value: D): Promise<void>;
|
|
250
|
-
protected abstract deleteAllValues(): Promise<void>;
|
|
251
|
-
}
|
|
252
|
-
type ElementStorageOptions<D extends Record<string, unknown>> = NongranularStorageOptions<D>;
|
|
253
|
-
class ElementAttributeStorage<D extends Record<string, unknown>, IS_PARTIAL extends boolean = false, V extends ValidatorsFor<D, IS_PARTIAL> = ValidatorsFor<D, IS_PARTIAL>> extends AbstractNongranularKeyValueStorage<D, IS_PARTIAL, V> {
|
|
254
|
-
private element;
|
|
255
|
-
private attribute;
|
|
256
|
-
protected defaults: D;
|
|
257
|
-
protected validators: V;
|
|
258
|
-
constructor(isPartial: IS_PARTIAL, element: Element, attribute: string, defaults: D, validators: V, options?: Partial<ElementStorageOptions<D>>);
|
|
259
|
-
protected getValue(): Promise<string>;
|
|
260
|
-
protected setValue(value: D): Promise<void>;
|
|
261
|
-
protected deleteAllValues(): Promise<void>;
|
|
262
|
-
}
|
|
263
|
-
type ElementOptionsMerger<D extends Record<string, unknown>> = (defaults: D, elementOptions: Partial<D>) => D;
|
|
264
|
-
class ElementStorage<D extends Record<string, unknown>, E extends Element = HTMLScriptElement, IS_PARTIAL extends boolean = false, V extends ValidatorsFor<D, IS_PARTIAL> = ValidatorsFor<D, IS_PARTIAL>> extends AbstractNongranularKeyValueStorage<D, IS_PARTIAL, V> {
|
|
265
|
-
private element;
|
|
266
|
-
protected defaults: D;
|
|
267
|
-
protected validators: V;
|
|
268
|
-
constructor(isPartial: IS_PARTIAL, element: E, defaults: D, validators: V, options?: Partial<NongranularStorageOptions<D>>);
|
|
269
|
-
protected getValue(): Promise<string>;
|
|
270
|
-
protected setValue(value: D): Promise<void>;
|
|
271
|
-
protected deleteAllValues(): Promise<void>;
|
|
272
|
-
}
|
|
273
|
-
type NongranularStorageOptions<D extends Record<string, unknown>> = {
|
|
274
|
-
keepFresh: boolean;
|
|
275
|
-
elementOptionsMerger: ElementOptionsMerger<D>;
|
|
276
|
-
};
|
|
277
|
-
class StorageWrapper<D extends Record<string, unknown>> implements KeyValueStorage<D> {
|
|
278
|
-
private storage;
|
|
279
|
-
private defaults;
|
|
280
|
-
private validators;
|
|
281
|
-
[KeyValueStorageSymbol]: true;
|
|
282
|
-
constructor(storage: KeyValueStorage<Partial<D>>, defaults: D, validators: StorageValidators<D>);
|
|
283
|
-
has(key: keyof D): Promise<boolean>;
|
|
284
|
-
get<T extends keyof D>(key: T): Promise<D[T]>;
|
|
285
|
-
getMultiple<T extends keyof D>(keys: T[]): Promise<Pick<D, T>>;
|
|
286
|
-
getAll(): Promise<D>;
|
|
287
|
-
set<T extends keyof D>(key: T, value: D[T]): Promise<void>;
|
|
288
|
-
setMultiple(data: Partial<D>): Promise<void>;
|
|
289
|
-
setAll(data: D): Promise<void>;
|
|
290
|
-
delete(key: keyof D): Promise<void>;
|
|
291
|
-
deleteMultiple(keys: (keyof D)[]): Promise<void>;
|
|
292
|
-
deleteAll(): Promise<void>;
|
|
293
|
-
private validateGetValue;
|
|
294
|
-
private validateSetValue;
|
|
295
|
-
}
|
|
296
|
-
const KeyValueStorageSymbol: unique symbol;
|
|
297
|
-
interface KeyValueStorage<D extends Record<string, unknown>> extends KeyValueStorageReadonly<D> {
|
|
298
|
-
[KeyValueStorageSymbol]: true;
|
|
299
|
-
set: <T extends keyof D>(key: T, value: D[T]) => Promise<void>;
|
|
300
|
-
setMultiple: (data: Partial<D>) => Promise<void>;
|
|
301
|
-
setAll: (data: D) => Promise<void>;
|
|
302
|
-
delete: (key: keyof D) => Promise<void>;
|
|
303
|
-
deleteMultiple: (keys: (keyof D)[]) => Promise<void>;
|
|
304
|
-
deleteAll: () => Promise<void>;
|
|
305
|
-
}
|
|
306
|
-
function isKeyValueStorage<D extends Record<string, unknown>>(object: unknown): object is KeyValueStorage<D>;
|
|
307
|
-
type KeyValueStorageReadonly<D extends Record<string, unknown>> = {
|
|
308
|
-
get: <T extends keyof D>(key: T) => Promise<D[T]>;
|
|
309
|
-
getMultiple: <T extends keyof D>(keys: T[]) => Promise<Pick<D, T>>;
|
|
310
|
-
getAll: () => Promise<D>;
|
|
311
|
-
has: (key: keyof D) => Promise<boolean>;
|
|
312
|
-
};
|
|
313
|
-
type StorageValidators<T extends Record<string, unknown>> = Record<keyof T, StorageValidator>;
|
|
314
|
-
type StorageValidator = (value: unknown) => boolean;
|
|
315
228
|
abstract class AbstractDependentWraplet<N extends Node = Node, M extends WrapletDependencyMap = {}> extends AbstractWraplet<N> implements Wraplet {
|
|
316
229
|
protected dm: DependencyManager<N, M>;
|
|
317
230
|
constructor(dm: DependencyManager<N, M>);
|
|
@@ -448,10 +361,6 @@ type OuterInitializeCallbackArgs = {
|
|
|
448
361
|
};
|
|
449
362
|
function createOuterInitializeCallback(args: OuterInitializeCallbackArgs, initializeLogic?: WrapletApiFactoryBasicCallback): () => Promise<void>;
|
|
450
363
|
const createWrapletApi: (args: WrapletApiFactoryArgs) => WrapletApi & WrapletApiDebug;
|
|
451
|
-
function initializationStarted(status: StatusWritable): boolean;
|
|
452
|
-
function initializationCompleted(status: StatusWritable, destroyMethod: () => Promise<void>): Promise<void>;
|
|
453
|
-
function destructionStarted(status: StatusWritable): boolean;
|
|
454
|
-
function destructionCompleted(status: StatusWritable, wraplet: Wraplet, destroyListeners: DestroyListener[]): Promise<void>;
|
|
455
364
|
type DependencyInstance<M extends WrapletDependencyMap, K extends keyof M = keyof M> = InstantiableReturnType<M[K]["Class"]>;
|
|
456
365
|
interface Status {
|
|
457
366
|
readonly isInitialized: boolean;
|
|
@@ -519,7 +428,6 @@ type MultipleDependencyKeys<M extends WrapletDependencyMap> = Extract<keyof {
|
|
|
519
428
|
[K in keyof M as M[K]["multiple"] extends true ? K : never]: true;
|
|
520
429
|
}, string>;
|
|
521
430
|
function isWrapletDependencyMap(object: unknown): object is WrapletDependencyMapWithDefaults;
|
|
522
|
-
const isOverridden: (instance: object, methodName: string, stopAt?: Function) => boolean;
|
|
523
431
|
class MissingRequiredDependencyError extends Error {
|
|
524
432
|
}
|
|
525
433
|
class MapError extends Error {
|
|
@@ -528,8 +436,6 @@ class RequiredDependencyDestroyedError extends Error {
|
|
|
528
436
|
}
|
|
529
437
|
class DependenciesAreNotAvailableError extends Error {
|
|
530
438
|
}
|
|
531
|
-
class StorageValidationError extends Error {
|
|
532
|
-
}
|
|
533
439
|
class TooManyChildrenFoundError extends Error {
|
|
534
440
|
}
|
|
535
441
|
class InternalLogicError extends Error {
|
|
@@ -555,3 +461,4 @@ type InstantiableReturnType<T> = T extends {
|
|
|
555
461
|
type Nullable<T> = {
|
|
556
462
|
[K in keyof T]: T[K] | null;
|
|
557
463
|
};
|
|
464
|
+
const RESOLVE: Promise<void>;
|
package/dist/errors.d.ts
CHANGED
|
@@ -6,8 +6,6 @@ export declare class RequiredDependencyDestroyedError extends Error {
|
|
|
6
6
|
}
|
|
7
7
|
export declare class DependenciesAreNotAvailableError extends Error {
|
|
8
8
|
}
|
|
9
|
-
export declare class StorageValidationError extends Error {
|
|
10
|
-
}
|
|
11
9
|
export declare class TooManyChildrenFoundError extends Error {
|
|
12
10
|
}
|
|
13
11
|
export declare class InternalLogicError extends Error {
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{AbstractDependentWraplet:()=>Y,AbstractWraplet:()=>U,DDM:()=>j,DNTM:()=>V,DefaultWrapletSet:()=>z,DefaultWrapletSetReadonly:()=>B,DependenciesAreNotAvailableError:()=>r,InternalLogicError:()=>d,LifecycleAsyncErrors:()=>p,LifecycleError:()=>l,MapError:()=>i,MissingRequiredDependencyError:()=>n,RequiredDependencyDestroyedError:()=>s,StorageValidationError:()=>a,TooManyChildrenFoundError:()=>o,UnsupportedNodeTypeError:()=>c,WrapletSymbol:()=>u,createOuterDestroyCallback:()=>_,createOuterInitializeCallback:()=>R,createWrapletApi:()=>F,destroyWrapletsRecursively:()=>S,destructionCompleted:()=>N,destructionStarted:()=>$,getWrapletsFromNode:()=>W,initializationCompleted:()=>q,initializationStarted:()=>T,isWraplet:()=>y});class n extends Error{}class i extends Error{}class s extends Error{}class r extends Error{}class a extends Error{}class o extends Error{}class d extends Error{}class c extends Error{}class l extends Error{}class p extends Error{errors=[]}const h=(e,t)=>"object"==typeof e&&null!==e&&!0===e[t],u=Symbol("Wraplet");function y(e){return h(e,u)}function f(e){return"object"==typeof e&&null!==e&&Object.getPrototypeOf(e)===Object.prototype}function w(e){for(const t of Object.keys(e))if(!["selector","Class","multiple","required","destructible","injector","args"].includes(t))return!1;return!!["string","function","undefined"].includes(typeof e.selector)&&"function"==typeof e.Class&&"boolean"==typeof e.required&&"boolean"==typeof e.multiple}function D(e){if(!f(e))return!1;for(const t in e){if(!f(e[t]))return!1;if(!w(e[t]))return!1}return!0}const g=Symbol("WrapletSet");function m(e){return h(e,g)}class b extends Set{find(e){const t=[];for(const n of this)e(n)&&t.push(n);return t}findOne(e){for(const t of this)if(e(t))return t;return null}getOrdered(e){return Array.from(this).sort((t,n)=>e(t)-e(n))}}const E=Symbol("WrapletSetReadonly");class z extends b{[E]=!0;[g]=!0}function I(e,t,n=!0){const i=new p(e);for(const e of t)"rejected"===e.status&&i.errors.push(e.reason);if(0===i.errors.length)return null;if(n)throw i;return i}function v(e){return"function"==typeof e.querySelectorAll}function W(e){const t=e.wraplets;return m(t)?t:null}async function M(e,t){t(e);const n=e.childNodes;for(const e of n)await M(e,t)}async function S(e){const t=[];await M(e,e=>{const n=W(e);if(n)for(const e of[...n])e.wraplet.status.isGettingDestroyed||e.wraplet.status.isDestroyed||t.push(e)}),I("Some wraplets threw exceptions during destruction",await Promise.allSettled(t.map(e=>e.wraplet.destroy())))}const L=Symbol("DependencyManager");class A{static#e=new A;constructor(){}dumpError(e){console.dir(e,{depth:null})}static getGlobalLogger(){return this.#e}}function C(e){return{args:[],destructible:!0,injector:{callback:e=>e},...e}}const G=Symbol("MapTreeBuilder");class O{parent;[G]=!0;map;children={};constructor(e){this.parent=e}getParent(){if(!this.parent)throw new Error("Parent not found.");return this.parent}createChild(e){const t=new O(this);return this.children[e]=t,t}setMap(e){this.map=function(e){const t={};for(const n of Object.keys(e)){const i=e[n];t[n]=C(i)}return t}(e)}getMap(){if(!this.map)throw new Error("Map is not set.");return this.map}}class j{node;[L]=!0;logger;dependenciesAreInstantiated=!1;status={isDestroyed:!1,isGettingDestroyed:!1,isGettingSynced:!1,isInitialized:!1,isGettingInitialized:!1};mapTree;directDependencies={};wrappedDependencies={};instantiatedDependencyListeners;initializedDependencyListeners;destroyedDependencyListeners;constructor(e,t,n={}){if(this.node=e,!(e instanceof Node))throw new Error("The node provided to the DDM is not a valid node.");if(D(t))this.mapTree=new O,this.mapTree.setMap(t);else{if("object"!=typeof(s=t)||null===s||!(G in s))throw new i("The map provided to the DDM is not a valid map.");this.mapTree=t}var s;const r=Object.assign(this.defaultOptions(),n);this.logger=r.logger,this.instantiatedDependencyListeners=r.dependencyInstantiatedListeners,this.initializedDependencyListeners=r.dependencyInitializedListeners,this.destroyedDependencyListeners=r.dependencyDestroyedListeners}async initializeDependencies(){if(this.status.isInitialized)throw new l("Dependencies are already initialized.");this.status.isGettingInitialized=!0,await this.initializeDeps(),this.status.isInitialized=!0,this.status.isGettingInitialized=!1,this.status.isGettingDestroyed&&await this.destroyDependencies()}async initializeDeps(){const e=await Promise.allSettled(Object.entries(this.directDependencies).map(async([e,t])=>{if(!t)return;const n=m(t)?Array.from(t):[t],i=await Promise.allSettled(n.map(async t=>{if(t.wraplet.status.isInitialized||t.wraplet.status.isGettingInitialized)return;await t.wraplet.initialize();const n=await Promise.allSettled((this.initializedDependencyListeners.get(e)||[]).map(e=>e(t)));I(`Errors in the DDM's dependency "${e}" initialize listeners.`,n)}));I(`Error at "${e}" dependency's initialization.`,i)})),t=I("Error at DDM's initialization.",e,!1);if(t)throw this.logger.dumpError(t),t}async syncDependencies(){this.status.isGettingSynced=!0,this.instantiateDeps(!0),await this.initializeDeps(),await this.destroyDeps(!0),this.status.isGettingSynced=!1}get map(){return this.mapTree.getMap()}instantiateDeps(e=!1){const t=this.directDependencies;if(v(this.node))for(const n in this.map){const i=this.map[n],s=i.multiple;if(this.validateMapItem(n,i),s){t[n]||(t[n]=new z);const e=t[n],s=this.instantiateMultipleDependencies(i,this.node,n);for(const t of s)e.add(t);continue}const r=this.instantiateSingleWrapletDependency(i,this.node,n);r!==t[n]&&(e&&r&&t[n]&&t[n].wraplet.destroy(),t[n]=r)}else{for(const e in this.map){const t=this.map[e];this.validateMapItemForNonParent(e,t)}this.dependenciesAreInstantiated=!0}}instantiateDependencies(){if(this.dependenciesAreInstantiated)throw new l("Dependencies are already instantiated.");this.wrappedDependencies=this.wrapDependencies(this.directDependencies),this.instantiateDeps(),this.dependenciesAreInstantiated=!0}findExistingWraplet(e,t){if(void 0===this.directDependencies||!this.directDependencies[e])return null;const n=this.directDependencies[e];if(this.map[e].multiple){if(!m(n))throw new d("Internal logic error. Expected a WrapletSet.");const e=t.wraplets;if(!e)return null;const i=n.find(t=>e.has(t));if(i.length>1)throw new d("Internal logic error. Multiple instances wrapping the same element found in the DDM.");return i[0]}if(!y(n))throw new d("Internal logic error. Expected a Wraplet.");return t.wraplets&&t.wraplets.has(n)?n:null}instantiateSingleWrapletDependency(e,t,n){if(!e.selector)return this.directDependencies[n]||null;if(!this.dependenciesAreInstantiated&&this.directDependencies[n])throw new i("It's not possible to provide a single-type dependency manually and use selector at the same time.");const s=e.selector,r=this.findChildrenElements(s,t);if(this.validateElements(n,r,e),0===r.length)return null;if(r.length>1)throw new o(`${this.constructor.name}: More than one element was found for the "${n}" dependency. Selector used: "${s}".`);const a=r[0];return this.instantiateWrapletItem(n,e,a)}instantiateWrapletItem(e,t,n){const i=this.findExistingWraplet(e,n);if(i)return i;let s=null;try{const i=new t.Class(t.injector.callback(n,this.mapTree.createChild(e),t.injector.data),...t.args);if(!y(i))throw new Error("Created dependency is not a Wraplet instance.");s=i}catch(n){if(n instanceof c&&!t.required)return console.warn(`${n.message} Skipping instantiation of the "${e}" dependency.`),null;throw n}this.prepareIndividualWraplet(e,s);for(const t of this.instantiatedDependencyListeners.get(e)||[])t(s);return s}instantiateMultipleDependencies(e,t,n){const i=e.selector;if(!i)return new z;const s=this.findChildrenElements(i,t);this.validateElements(n,s,e);const r=new z;for(const t of s){let i=this.findExistingWraplet(n,t);i||(i=this.instantiateWrapletItem(n,e,t)),i&&r.add(i)}return r}addDependencyInstantiatedListener(e,t){const n=this.instantiatedDependencyListeners.get(e)||[];n.push(t),this.instantiatedDependencyListeners.set(e,n)}addDependencyInitializedListener(e,t){const n=this.initializedDependencyListeners.get(e)||[];n.push(t),this.initializedDependencyListeners.set(e,n)}addDependencyDestroyedListener(e,t){const n=this.destroyedDependencyListeners.get(e)||[];n.push(t),this.destroyedDependencyListeners.set(e,n)}setExistingInstance(e,t){if(this.map[e].multiple)throw new i("This method can only be used to set a single-value dependency.");if(!y(t))throw new i("Provided instance is not a valid dependency.");this.prepareIndividualWraplet(e,t),this.directDependencies[e]=t}addExistingInstance(e,t){if(!this.map[e].multiple)throw new i("This method can only be used to set a multi-value dependency.");this.prepareIndividualWraplet(e,t);const n=this.directDependencies&&this.directDependencies[e]?this.directDependencies[e]:new z;n.add(t),this.directDependencies[e]=n}prepareIndividualWraplet(e,t){t.wraplet.addDestroyListener(this.createDependencyDestroyListener(e))}createDependencyDestroyListener(e){return async t=>{this.removeDependency(t,e);const n=await Promise.allSettled((this.destroyedDependencyListeners.get(e)||[]).map(e=>e(t))),i=this.validateRequiredDependencyAfterRemoval(e);i&&n.push({status:"rejected",reason:i}),I(`Errors in the destruction callbacks of the "${e} dependency."`,n)}}validateRequiredDependencyAfterRemoval(e){return this.map[e].required&&!this.status.isGettingDestroyed&&null===this.directDependencies[e]?new s(`Required dependency "${e}" has been destroyed.`):null}async destroyDependencies(){if(this.status.isDestroyed)throw new l("Dependencies are already destroyed.");if(this.status.isGettingDestroyed=!0,!this.status.isGettingInitialized){if(!this.status.isInitialized)return this.status.isDestroyed=!0,void(this.status.isGettingDestroyed=!1);await this.destroyDeps(),this.status.isInitialized=!1,this.status.isDestroyed=!0,this.status.isGettingDestroyed=!1}}findChildrenElements(e,t){return"string"==typeof e?((e,t)=>Array.from(t.querySelectorAll(e)))(e,t):e(t)}get dependencies(){if(!this.dependenciesAreInstantiated)throw new r("Wraplet is not yet fully initialized.");return this.wrappedDependencies}removeDependency(e,t){m(this.directDependencies[t])?this.directDependencies[t].delete(e):this.directDependencies[t]===e&&(this.directDependencies[t]=null)}validateMapItem(e,t){const n=t.selector,s=t.required;if(!n&&s&&(!this.directDependencies[e]||m(this.directDependencies[e])&&0===this.directDependencies[e].size))throw new i(`${this.constructor.name}: Dependency "${e}" cannot at the same be required, have no selector, and be not provided otherwise.`)}validateMapItemForNonParent(e,t){if(t.required)throw new i(`Dependency "${e}" error: If the node provided cannot have children, there should be no required dependencies.`)}validateElements(e,t,i){if(0===t.length&&i.required)throw new n(`${this.constructor.name}: Couldn't find a node for the wraplet "${e}". Selector used: "${i.selector}".`)}wrapDependencies(e){return new Proxy(e,{get:(e,t)=>{if("symbol"==typeof t)throw new Error("Symbol access is not supported for dependencies.");if(!(t in e))throw new Error(`Dependency '${t}' has not been found.`);return e[t]},set:()=>{throw new Error("Dependencies cannot be set directly. Use the 'setExistingInstance' or 'addExistingInstance' methods instead.")}})}defaultOptions(){return{dependencyInstantiatedListeners:new Map,dependencyInitializedListeners:new Map,dependencyDestroyedListeners:new Map,logger:A.getGlobalLogger()}}async destroyDeps(e=!1){const t=await Promise.allSettled(Object.entries(this.directDependencies).map(async([t,n])=>{if(!n||!this.map[t].destructible)return;let i=[];if(m(n))for(const e of n)i.push(e);else i.push(n);if(e){if(!this.map[t].selector)return;i=await async function(e,t){const n=new z(e);return await M(t,e=>{const t=W(e);if(t)for(const e of t)n.delete(e)}),Array.from(n)}(i,this.node)}I(`Errors during destruction of the "${t}" dependency.`,await Promise.allSettled(i.map(async e=>{if(!e.wraplet.status.isDestroyed&&!e.wraplet.status.isGettingDestroyed)return e.wraplet.destroy()})))})),n=I("Errors during the dependencies destruction.",t,!1);if(n)throw this.logger.dumpError(n),n}static createInjector(e,t){return{data:t||{},callback:(t,n,i)=>{let s=n;if(r=e,Number.isInteger(r))for(let t=0;t<e;t++)s=s.getParent();else{if(!D(e))throw new Error("Invalid map argument.");s.setMap(e)}var r;return new j(t,s,i)}}}}const k=(e,t,n)=>{let i=Object.getPrototypeOf(e);const s=n?n.prototype:Object.getPrototypeOf(i);for(;i&&i!==s;){if(Object.prototype.hasOwnProperty.call(i,t))return!0;i=Object.getPrototypeOf(i)}return!1};class x{node;listeners=new Map;constructor(e){this.node=e}addListener(e,t,n){this.node.addEventListener(e,t,n);const i=this.listeners.get(this.node)||[];i.push({callback:t,event:e,options:n}),this.listeners.set(this.node,i)}addListenerTo(e,t,n,i,s=!0){if(!v(this.node))throw new Error("Target node is not a parent node. Cannot add listener to its child.");const r=[];if("string"==typeof e?r.push(...Array.from(this.node.querySelectorAll(e))):r.push(...e(this.node)),s&&0===r.length)throw new Error("No nodes found");for(const e of r){e.addEventListener(t,n,i);const s=this.listeners.get(e)||[];s.push({event:t,callback:n,options:i}),this.listeners.set(e,s)}}destroy(){for(const e of this.listeners){const t=e[0],n=e[1];for(const e of n)t.removeEventListener(e.event,e.callback,e.options)}this.listeners.clear()}}const P=Symbol("WrapletApi");function T(e){return!(e.isInitialized||e.isGettingInitialized||e.isDestroyed||e.isGettingDestroyed||(e.isGettingInitialized=!0,0))}async function q(e,t){e.isInitialized=!0,e.isGettingInitialized=!1,e.isGettingDestroyed&&await t()}function $(e){if(e.isDestroyed)return!1;if(e.isGettingDestroyed=!0,e.isGettingInitialized)return!1;if(!e.isInitialized)throw new l("Wraplet cannot be destroyed before it is initialized.");return!0}async function N(e,t,n){e.isGettingDestroyed=!1,e.isInitialized=!1,e.isDestroyed=!0;for(const e of[...n].reverse())await e(t);n.length=0}function _(e,t){return async function(){const n=e.status;$(n)&&(t&&await t(),await N(n,e.wraplet,e.destroyListeners))}}function R(e,t){return async function(){const n=e.status;T(n)&&(t&&await t(),await q(n,e.destroyCallback))}}const F=e=>{!function(e){if(!y(e.wraplet))throw new Error("Correct wraplet instance has to be provided.");if(e.node&&!(e.node instanceof Node))throw new Error("Correct node has to be provided.");if(e.initializeCallback&&"function"!=typeof e.initializeCallback)throw new Error("initializeCallback has to be a function.");if(e.destroyCallback&&"function"!=typeof e.destroyCallback)throw new Error("destroyCallback has to be a function.")}(e);const t={...e},n={isGettingInitialized:!1,isDestroyed:!1,isInitialized:!1,isGettingDestroyed:!1},i={},s=[],r=_({status:n,wraplet:t.wraplet,destroyListeners:s},async()=>{t.destroyCallback&&await t.destroyCallback(),t.node&&function(e,t){const n=W(t);n&&n.delete(e)}(t.wraplet,t.node)}).bind(i),a=R({status:n,destroyCallback:r,wraplet:t.wraplet},async()=>{t.initializeCallback&&await t.initializeCallback()}).bind(i);var o,d;return t.node&&(o=t.wraplet,(d=t.node).wraplets||(d.wraplets=new z),d.wraplets.add(o)),Object.assign(i,{[P]:!0,__destroyListeners:s,status:n,addDestroyListener:e=>{s.push(e)},initialize:a,destroy:r})};class U{node;[u]=!0;wraplet;_nodeManager;constructor(e){if(this.node=e,!(e instanceof Node))throw new Error("AbstractWraplet requires a Node instance.");const t=this.supportedNodeTypes();if(null!==t&&!t.find(t=>e instanceof t))throw new c(`Node type ${e.constructor.name} is not supported by the ${this.constructor.name} wraplet.`);this.wraplet=this.createWrapletApi()}createWrapletApi(){const e=k(this,"onInitialize",U)?this.onInitialize.bind(this):void 0,t=k(this,"onDestroy",U)?this.onDestroy.bind(this):void 0;return this.buildWrapletApi(e,t)}buildWrapletApi(e,t){return F({node:this.node,wraplet:this,initializeCallback:e,destroyCallback:async()=>{t&&await t(),this._nodeManager&&this._nodeManager.destroy()}})}get nodeManager(){return this._nodeManager||(this._nodeManager=new x(this.node)),this._nodeManager}supportedNodeTypes(){return null}supportedNodeTypesGuard(e){return e}async onInitialize(){throw new Error("Method has to be implemented by subclass.")}async onDestroy(){throw new Error("Method has to be implemented by subclass.")}static createWraplets(e,t,n=[]){if(this===U)throw new Error("You cannot instantiate an abstract class.");const i=[];let s;"function"==typeof t?s=t(e):(e instanceof Element&&e.hasAttribute(t)&&i.push(new this(e,...n)),s=e.querySelectorAll(`[${t}]`));for(const e of s)i.push(new this(e,...n));return i}static async createAndInitializeWraplets(e,t,n=[]){const i=this.createWraplets(e,t,n);for(const e of i)await e.wraplet.initialize();return i}}class Y extends U{dm;constructor(e){if(!h(e,L))throw new Error("AbstractDependentWraplet requires an instance implementing the DependencyManager interface.");super(e.node),this.dm=e,e.instantiateDependencies()}createWrapletApi(){return this.buildWrapletApi(async()=>{await this.dm.initializeDependencies(),await this.onInitialize.bind(this)()},async()=>{await this.onDestroy.bind(this)(),await this.dm.destroyDependencies()})}async onDestroy(){}async onInitialize(){}get d(){return this.dm.dependencies}static createDependencyManager(e,t){return new j(e,t)}static createWraplets(){throw new Error("This method is not supported for AbstractDependentWraplet.")}static createAndInitializeWraplets(){throw new Error("This method is not supported for AbstractDependentWraplet.")}static createDependentWraplets(e,t,n,i=[]){if(this===Y)throw new Error("You cannot instantiate an abstract class.");const s=this,r=[];let a;if("function"==typeof t)a=t(e);else{if(e instanceof Element&&e.hasAttribute(t)){const t=s.createDependencyManager(e,n);r.push(new this(t,...i))}a=e.querySelectorAll(`[${t}]`)}for(const e of a){const t=s.createDependencyManager(e,n);r.push(new this(t,...i))}return r}static async createAndInitializeDependentWraplets(e,t,n,i=[]){const s=this.createDependentWraplets(e,t,n,i);for(const e of s)await e.wraplet.initialize();return s}}class B extends b{[E]=!0}class V{initializers=[];addNodeInitializer(e){this.initializers.push(e)}async initializeNode(e,t){I("There were errors during the node's initialization.",await Promise.allSettled(this.initializers.map(n=>n(e,t))))}async destroyNode(e){await S(e)}}var H=exports;for(var J in t)H[J]=t[J];t.__esModule&&Object.defineProperty(H,"__esModule",{value:!0});
|
|
1
|
+
var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{AbstractDependentWraplet:()=>N,AbstractWraplet:()=>$,DDM:()=>k,DNTM:()=>R,DefaultWrapletSet:()=>z,DefaultWrapletSetReadonly:()=>_,DependenciesAreNotAvailableError:()=>r,InternalLogicError:()=>o,LifecycleAsyncErrors:()=>c,LifecycleError:()=>l,MapError:()=>i,MissingRequiredDependencyError:()=>n,RequiredDependencyDestroyedError:()=>s,TooManyChildrenFoundError:()=>a,UnsupportedNodeTypeError:()=>d,WrapletSymbol:()=>h,createOuterDestroyCallback:()=>j,createOuterInitializeCallback:()=>q,createWrapletApi:()=>O,destroyWrapletsRecursively:()=>M,getWrapletsFromNode:()=>v,isWraplet:()=>u});class n extends Error{}class i extends Error{}class s extends Error{}class r extends Error{}class a extends Error{}class o extends Error{}class d extends Error{}class l extends Error{}class c extends Error{errors=[]}const p=(e,t)=>"object"==typeof e&&null!==e&&!0===e[t],h=Symbol("Wraplet");function u(e){return p(e,h)}function y(e){return"object"==typeof e&&null!==e&&Object.getPrototypeOf(e)===Object.prototype}function f(e){for(const t of Object.keys(e))if(!["selector","Class","multiple","required","destructible","injector","args"].includes(t))return!1;return!!["string","function","undefined"].includes(typeof e.selector)&&"function"==typeof e.Class&&"boolean"==typeof e.required&&"boolean"==typeof e.multiple}function w(e){if(!y(e))return!1;for(const t in e){if(!y(e[t]))return!1;if(!f(e[t]))return!1}return!0}const D=Symbol("WrapletSet");function m(e){return p(e,D)}class g extends Set{find(e){const t=[];for(const n of this)e(n)&&t.push(n);return t}findOne(e){for(const t of this)if(e(t))return t;return null}getOrdered(e){return Array.from(this).sort((t,n)=>e(t)-e(n))}}const b=Symbol("WrapletSetReadonly");class z extends g{[b]=!0;[D]=!0}function E(e,t,n=!0){const i=new c(e);for(const e of t)"rejected"===e.status&&i.errors.push(e.reason);if(0===i.errors.length)return null;if(n)throw i;return i}function I(e){return"function"==typeof e.querySelectorAll}function v(e){const t=e.wraplets;return m(t)?t:null}async function W(e,t){t(e);const n=e.childNodes;for(const e of n)await W(e,t)}async function M(e){const t=[];await W(e,e=>{const n=v(e);if(n)for(const e of[...n])e.wraplet.status.isGettingDestroyed||e.wraplet.status.isDestroyed||t.push(e)}),E("Some wraplets threw exceptions during destruction",await Promise.allSettled(t.map(e=>e.wraplet.destroy())))}const L=Symbol("DependencyManager");class S{static#e=new S;constructor(){}dumpError(e){console.dir(e,{depth:null})}static getGlobalLogger(){return this.#e}}function A(e){return{args:[],destructible:!0,injector:{callback:e=>e},...e}}const P=Symbol("MapTreeBuilder");class C{parent;[P]=!0;map;children={};constructor(e){this.parent=e}getParent(){if(!this.parent)throw new Error("Parent not found.");return this.parent}createChild(e){const t=new C(this);return this.children[e]=t,t}setMap(e){this.map=function(e){const t={};for(const n of Object.keys(e)){const i=e[n];t[n]=A(i)}return t}(e)}getMap(){if(!this.map)throw new Error("Map is not set.");return this.map}}const G=Promise.resolve();class k{node;[L]=!0;logger;dependenciesAreInstantiated=!1;initializePromise=null;destroyPromise=null;syncPromise=null;status={isDestroyed:!1,isGettingDestroyed:!1,isGettingSynced:!1,isInitialized:!1,isGettingInitialized:!1};mapTree;directDependencies={};wrappedDependencies={};instantiatedDependencyListeners;initializedDependencyListeners;destroyedDependencyListeners;constructor(e,t,n={}){if(this.node=e,!(e instanceof Node))throw new Error("The node provided to the DDM is not a valid node.");if(w(t))this.mapTree=new C,this.mapTree.setMap(t);else{if("object"!=typeof(s=t)||null===s||!(P in s))throw new i("The map provided to the DDM is not a valid map.");this.mapTree=t}var s;const r=Object.assign(this.defaultOptions(),n);this.logger=r.logger,this.instantiatedDependencyListeners=r.dependencyInstantiatedListeners,this.initializedDependencyListeners=r.dependencyInitializedListeners,this.destroyedDependencyListeners=r.dependencyDestroyedListeners}initializeDependencies(){return this.status.isInitialized?G:(this.initializePromise||(this.initializePromise=(async()=>{try{this.status.isGettingInitialized=!0,await this.initializeDeps(),this.status.isInitialized=!0}finally{this.initializePromise=null,this.status.isGettingInitialized=!1}})()),this.initializePromise)}async initializeDeps(){const e=await Promise.allSettled(Object.entries(this.directDependencies).map(async([e,t])=>{if(!t)return;const n=m(t)?Array.from(t):[t],i=await Promise.allSettled(n.map(async t=>{if(t.wraplet.status.isInitialized||t.wraplet.status.isGettingInitialized)return;await t.wraplet.initialize();const n=await Promise.allSettled((this.initializedDependencyListeners.get(e)||[]).map(e=>e(t)));E(`Errors in the DDM's dependency "${e}" initialize listeners.`,n)}));E(`Error at "${e}" dependency's initialization.`,i)})),t=E("Error at DDM's initialization.",e,!1);if(t)throw this.logger.dumpError(t),t}syncDependencies(){return this.syncPromise||(this.syncPromise=(async()=>{try{this.status.isGettingSynced=!0,this.instantiateDeps(!0),await this.initializeDeps(),await this.destroyDeps(!0)}finally{this.syncPromise=null,this.status.isGettingSynced=!1}})()),this.syncPromise}get map(){return this.mapTree.getMap()}instantiateDeps(e=!1){const t=this.directDependencies;if(I(this.node))for(const n in this.map){const i=this.map[n],s=i.multiple;if(this.validateMapItem(n,i),s){t[n]||(t[n]=new z);const e=t[n],s=this.instantiateMultipleDependencies(i,this.node,n);for(const t of s)e.add(t);continue}const r=this.instantiateSingleWrapletDependency(i,this.node,n);r!==t[n]&&(e&&r&&t[n]&&t[n].wraplet.destroy(),t[n]=r)}else{for(const e in this.map){const t=this.map[e];this.validateMapItemForNonParent(e,t)}this.dependenciesAreInstantiated=!0}}instantiateDependencies(){if(this.dependenciesAreInstantiated)throw new l("Dependencies are already instantiated.");this.wrappedDependencies=this.wrapDependencies(this.directDependencies),this.instantiateDeps(),this.dependenciesAreInstantiated=!0}findExistingWraplet(e,t){if(void 0===this.directDependencies||!this.directDependencies[e])return null;const n=this.directDependencies[e];if(this.map[e].multiple){if(!m(n))throw new o("Internal logic error. Expected a WrapletSet.");const e=t.wraplets;if(!e)return null;const i=n.find(t=>e.has(t));if(i.length>1)throw new o("Internal logic error. Multiple instances wrapping the same element found in the DDM.");return i[0]}if(!u(n))throw new o("Internal logic error. Expected a Wraplet.");return t.wraplets&&t.wraplets.has(n)?n:null}instantiateSingleWrapletDependency(e,t,n){if(!e.selector)return this.directDependencies[n]||null;if(!this.dependenciesAreInstantiated&&this.directDependencies[n])throw new i("It's not possible to provide a single-type dependency manually and use selector at the same time.");const s=e.selector,r=this.findChildrenElements(s,t);if(this.validateElements(n,r,e),0===r.length)return null;if(r.length>1)throw new a(`${this.constructor.name}: More than one element was found for the "${n}" dependency. Selector used: "${s}".`);const o=r[0];return this.instantiateWrapletItem(n,e,o)}instantiateWrapletItem(e,t,n){const i=this.findExistingWraplet(e,n);if(i)return i;let s;try{const i=new t.Class(t.injector.callback(n,this.mapTree.createChild(e),t.injector.data),...t.args);if(!u(i))throw new Error("Created dependency is not a Wraplet instance.");s=i}catch(n){if(n instanceof d&&!t.required)return console.warn(`${n.message} Skipping instantiation of the "${e}" dependency.`),null;throw n}this.prepareIndividualWraplet(e,s);for(const t of this.instantiatedDependencyListeners.get(e)||[])t(s);return s}instantiateMultipleDependencies(e,t,n){const i=e.selector;if(!i)return new z;const s=this.findChildrenElements(i,t);this.validateElements(n,s,e);const r=new z;for(const t of s){let i=this.findExistingWraplet(n,t);i||(i=this.instantiateWrapletItem(n,e,t)),i&&r.add(i)}return r}addDependencyInstantiatedListener(e,t){const n=this.instantiatedDependencyListeners.get(e)||[];n.push(t),this.instantiatedDependencyListeners.set(e,n)}addDependencyInitializedListener(e,t){const n=this.initializedDependencyListeners.get(e)||[];n.push(t),this.initializedDependencyListeners.set(e,n)}addDependencyDestroyedListener(e,t){const n=this.destroyedDependencyListeners.get(e)||[];n.push(t),this.destroyedDependencyListeners.set(e,n)}setExistingInstance(e,t){if(this.map[e].multiple)throw new i("This method can only be used to set a single-value dependency.");if(!u(t))throw new i("Provided instance is not a valid dependency.");this.prepareIndividualWraplet(e,t),this.directDependencies[e]=t}addExistingInstance(e,t){if(!this.map[e].multiple)throw new i("This method can only be used to set a multi-value dependency.");this.prepareIndividualWraplet(e,t);const n=this.directDependencies&&this.directDependencies[e]?this.directDependencies[e]:new z;n.add(t),this.directDependencies[e]=n}prepareIndividualWraplet(e,t){t.wraplet.addDestroyListener(this.createDependencyDestroyListener(e))}createDependencyDestroyListener(e){return async t=>{this.removeDependency(t,e);const n=await Promise.allSettled((this.destroyedDependencyListeners.get(e)||[]).map(e=>e(t))),i=this.validateRequiredDependencyAfterRemoval(e);i&&n.push({status:"rejected",reason:i}),E(`Errors in the destruction callbacks of the "${e} dependency."`,n)}}validateRequiredDependencyAfterRemoval(e){return this.map[e].required&&!this.status.isGettingDestroyed&&null===this.directDependencies[e]?new s(`Required dependency "${e}" has been destroyed.`):null}destroyDependencies(){return this.status.isDestroyed?G:(this.destroyPromise||(this.destroyPromise=(async()=>{try{if(this.status.isGettingDestroyed=!0,this.initializePromise&&await this.initializePromise,!this.status.isInitialized)return this.status.isDestroyed=!0,void(this.status.isGettingDestroyed=!1);await this.destroyDeps(),this.status.isInitialized=!1,this.status.isDestroyed=!0}finally{this.destroyPromise=null,this.status.isGettingDestroyed=!1}})()),this.destroyPromise)}findChildrenElements(e,t){return"string"==typeof e?((e,t)=>Array.from(t.querySelectorAll(e)))(e,t):e(t)}get dependencies(){if(!this.dependenciesAreInstantiated)throw new r("Wraplet is not yet fully initialized.");return this.wrappedDependencies}removeDependency(e,t){m(this.directDependencies[t])?this.directDependencies[t].delete(e):this.directDependencies[t]===e&&(this.directDependencies[t]=null)}validateMapItem(e,t){const n=t.selector,s=t.required;if(!n&&s&&(!this.directDependencies[e]||m(this.directDependencies[e])&&0===this.directDependencies[e].size))throw new i(`${this.constructor.name}: Dependency "${e}" cannot at the same be required, have no selector, and be not provided otherwise.`)}validateMapItemForNonParent(e,t){if(t.required)throw new i(`Dependency "${e}" error: If the node provided cannot have children, there should be no required dependencies.`)}validateElements(e,t,i){if(0===t.length&&i.required)throw new n(`${this.constructor.name}: Couldn't find a node for the wraplet "${e}". Selector used: "${i.selector}".`)}wrapDependencies(e){return new Proxy(e,{get:(e,t)=>{if("symbol"==typeof t)throw new Error("Symbol access is not supported for dependencies.");if(!(t in e))throw new Error(`Dependency '${t}' has not been found.`);return e[t]},set:()=>{throw new Error("Dependencies cannot be set directly. Use the 'setExistingInstance' or 'addExistingInstance' methods instead.")}})}defaultOptions(){return{dependencyInstantiatedListeners:new Map,dependencyInitializedListeners:new Map,dependencyDestroyedListeners:new Map,logger:S.getGlobalLogger()}}async destroyDeps(e=!1){const t=await Promise.allSettled(Object.entries(this.directDependencies).map(async([t,n])=>{if(!n||!this.map[t].destructible)return;let i=[];if(m(n))for(const e of n)i.push(e);else i.push(n);if(e){if(!this.map[t].selector)return;i=await async function(e,t){const n=new z(e);return await W(t,e=>{const t=v(e);if(t)for(const e of t)n.delete(e)}),Array.from(n)}(i,this.node)}E(`Errors during destruction of the "${t}" dependency.`,await Promise.allSettled(i.map(async e=>{if(!e.wraplet.status.isDestroyed&&!e.wraplet.status.isGettingDestroyed)return e.wraplet.destroy()})))})),n=E("Errors during the dependencies destruction.",t,!1);if(n)throw this.logger.dumpError(n),n}static createInjector(e,t){return{data:t||{},callback:(t,n,i)=>{let s=n;if(r=e,Number.isInteger(r))for(let t=0;t<e;t++)s=s.getParent();else{if(!w(e))throw new Error("Invalid map argument.");s.setMap(e)}var r;return new k(t,s,i)}}}}class x{node;listeners=new Map;constructor(e){this.node=e}addListener(e,t,n){this.node.addEventListener(e,t,n);const i=this.listeners.get(this.node)||[];i.push({callback:t,event:e,options:n}),this.listeners.set(this.node,i)}addListenerTo(e,t,n,i,s=!0){if(!I(this.node))throw new Error("Target node is not a parent node. Cannot add listener to its child.");const r=[];if("string"==typeof e?r.push(...Array.from(this.node.querySelectorAll(e))):r.push(...e(this.node)),s&&0===r.length)throw new Error("No nodes found");for(const e of r){e.addEventListener(t,n,i);const s=this.listeners.get(e)||[];s.push({event:t,callback:n,options:i}),this.listeners.set(e,s)}}destroy(){for(const e of this.listeners){const t=e[0],n=e[1];for(const e of n)t.removeEventListener(e.event,e.callback,e.options)}this.listeners.clear()}}const T=Symbol("WrapletApi");function j(e,t){let n=null;return function(){return n||(n=(async()=>{const n=e.status;if(!n.isDestroyed&&(n.isGettingDestroyed=!0,!n.isGettingInitialized)){if(!n.isInitialized)throw new l("Wraplet cannot be destroyed before it is initialized.");t&&await t(),n.isGettingDestroyed=!1,n.isInitialized=!1,n.isDestroyed=!0;for(const t of[...e.destroyListeners].reverse())await t(e.wraplet);e.destroyListeners.length=0}})().finally(()=>{n=null}),n)}}function q(e,t){let n=null;return function(){return n||(n=(async()=>{const n=e.status;if(n.isDestroyed||n.isGettingDestroyed)throw new l("Wraplet cannot be initialized when destroyed or in the process of being destroyed");n.isInitialized||n.isGettingInitialized||(n.isGettingInitialized=!0,t&&await t(),n.isInitialized=!0,n.isGettingInitialized=!1,n.isGettingDestroyed&&await e.destroyCallback())})().finally(()=>{n=null}),n)}}const O=e=>{!function(e){if(!u(e.wraplet))throw new Error("Correct wraplet instance has to be provided.");if(e.node&&!(e.node instanceof Node))throw new Error("Correct node has to be provided.");if(e.initializeCallback&&"function"!=typeof e.initializeCallback)throw new Error("initializeCallback has to be a function.");if(e.destroyCallback&&"function"!=typeof e.destroyCallback)throw new Error("destroyCallback has to be a function.")}(e);const t={...e},n={isGettingInitialized:!1,isDestroyed:!1,isInitialized:!1,isGettingDestroyed:!1},i={},s=[],r=j({status:n,wraplet:t.wraplet,destroyListeners:s},async()=>{t.destroyCallback&&await t.destroyCallback(),t.node&&function(e,t){const n=v(t);n&&n.delete(e)}(t.wraplet,t.node)}).bind(i),a=q({status:n,destroyCallback:r,wraplet:t.wraplet},async()=>{t.initializeCallback&&await t.initializeCallback()}).bind(i);var o,d;return t.node&&(o=t.wraplet,(d=t.node).wraplets||(d.wraplets=new z),d.wraplets.add(o)),Object.assign(i,{[T]:!0,__destroyListeners:s,status:n,addDestroyListener:e=>{s.push(e)},initialize:a,destroy:r})};class ${node;[h]=!0;wraplet;_nodeManager;constructor(e){if(this.node=e,!(e instanceof Node))throw new Error("AbstractWraplet requires a Node instance.");const t=this.supportedNodeTypes();if(null!==t&&!t.find(t=>e instanceof t))throw new d(`Node type ${e.constructor.name} is not supported by the ${this.constructor.name} wraplet.`);this.wraplet=this.createWrapletApi()}createWrapletApi(){return this.buildWrapletApi(this.onInitialize.bind(this),this.onDestroy.bind(this))}buildWrapletApi(e,t){return O({node:this.node,wraplet:this,initializeCallback:e,destroyCallback:async()=>{t&&await t(),this._nodeManager&&this._nodeManager.destroy()}})}get nodeManager(){return this._nodeManager||(this._nodeManager=new x(this.node)),this._nodeManager}supportedNodeTypes(){return null}supportedNodeTypesGuard(e){return e}onInitialize(){return G}onDestroy(){return G}static createWraplets(e,t,n=[]){if(this===$)throw new Error("You cannot instantiate an abstract class.");const i=[];let s;"function"==typeof t?s=t(e):(e instanceof Element&&e.hasAttribute(t)&&i.push(new this(e,...n)),s=e.querySelectorAll(`[${t}]`));for(const e of s)i.push(new this(e,...n));return i}static async createAndInitializeWraplets(e,t,n=[]){const i=this.createWraplets(e,t,n);for(const e of i)await e.wraplet.initialize();return i}}class N extends ${dm;constructor(e){if(!p(e,L))throw new Error("AbstractDependentWraplet requires an instance implementing the DependencyManager interface.");super(e.node),this.dm=e,e.instantiateDependencies()}createWrapletApi(){return this.buildWrapletApi(async()=>{await this.dm.initializeDependencies(),await this.onInitialize.bind(this)()},async()=>{await this.onDestroy.bind(this)(),await this.dm.destroyDependencies()})}onDestroy(){return G}onInitialize(){return G}get d(){return this.dm.dependencies}static createDependencyManager(e,t){return new k(e,t)}static createWraplets(){throw new Error("This method is not supported for AbstractDependentWraplet.")}static createAndInitializeWraplets(){throw new Error("This method is not supported for AbstractDependentWraplet.")}static createDependentWraplets(e,t,n,i=[]){if(this===N)throw new Error("You cannot instantiate an abstract class.");const s=this,r=[];let a;if("function"==typeof t)a=t(e);else{if(e instanceof Element&&e.hasAttribute(t)){const t=s.createDependencyManager(e,n);r.push(new this(t,...i))}a=e.querySelectorAll(`[${t}]`)}for(const e of a){const t=s.createDependencyManager(e,n);r.push(new this(t,...i))}return r}static async createAndInitializeDependentWraplets(e,t,n,i=[]){const s=this.createDependentWraplets(e,t,n,i);for(const e of s)await e.wraplet.initialize();return s}}class _ extends g{[b]=!0}class R{initializers=[];addNodeInitializer(e){this.initializers.push(e)}async initializeNode(e,t){E("There were errors during the node's initialization.",await Promise.allSettled(this.initializers.map(n=>n(e,t))))}async destroyNode(e){await M(e)}}var F=exports;for(var U in t)F[U]=t[U];t.__esModule&&Object.defineProperty(F,"__esModule",{value:!0});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|