entropic-bond 1.53.21 → 1.53.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.
@@ -1,8 +1,8 @@
1
- (function(a,v){typeof exports=="object"&&typeof module<"u"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(a=typeof globalThis<"u"?globalThis:a||self,v(a["entropic-bond"]={}))})(this,function(a){"use strict";var l;class v{constructor(){this.subscribers=new Set}subscribe(e){return this.subscribers.add(e),()=>this.unsubscribe(e)}unsubscribe(e){this.subscribers.delete(e)}notify(e){this.subscribers.forEach(t=>t(e))}get subscribersCount(){return this.subscribers.size}}const p=[];for(let i=0;i<256;++i)p.push((i+256).toString(16).slice(1));function B(i,e=0){return(p[i[e+0]]+p[i[e+1]]+p[i[e+2]]+p[i[e+3]]+"-"+p[i[e+4]]+p[i[e+5]]+"-"+p[i[e+6]]+p[i[e+7]]+"-"+p[i[e+8]]+p[i[e+9]]+"-"+p[i[e+10]]+p[i[e+11]]+p[i[e+12]]+p[i[e+13]]+p[i[e+14]]+p[i[e+15]]).toLowerCase()}let A;const W=new Uint8Array(16);function Q(){if(!A){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");A=crypto.getRandomValues.bind(crypto)}return A(W)}const N={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function q(i,e,t){i=i||{};const r=i.random??i.rng?.()??Q();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,B(r)}function Y(i,e,t){return N.randomUUID&&!i?N.randomUUID():q(i)}var z=Object.defineProperty,J=(i,e,t,r)=>{for(var s=void 0,n=i.length-1,o;n>=0;n--)(o=i[n])&&(s=o(e,t,s)||s);return s&&z(e,t,s),s};const M=(l=class{static registerFactory(e,t,r,s=!1){this._factoryMap[e]={factory:t,annotation:r,isLegacy:s}}static classFactory(e){if(!e)throw new Error("You should provide a class name.");if(!this._factoryMap[e])throw new Error(`You should register class ${e} prior to use.`);return this._factoryMap[e].factory}static registeredClasses(){return Object.entries(this._factoryMap).filter(([,e])=>!e.isLegacy).map(([e])=>e)}static registeredClassesAndLegacyNames(){return Object.keys(this._factoryMap)}static classesExtending(e){return Object.entries(this._factoryMap).filter(([,t])=>new t.factory instanceof e&&!t.isLegacy).map(([t])=>t)}static annotations(e){if(e instanceof l?e=e.className:typeof e=="string"||(e=new e().className),!this._factoryMap[e])throw new Error(`You should register class ${e} prior to use.`);return this._factoryMap[e].annotation}constructor(e=Y()){this._id=e}get className(){return this.__className}setId(e){this._id=e}get id(){return this._id}afterDeserialize(){}beforeSerialize(){}getPersistentProperties(){return this._persistentProperties?this._persistentProperties.map(e=>({...e,name:e.name.slice(1)})):[]}getPropInfo(e){const t=this.getPersistentProperties().find(r=>r.name===e);if(!t)throw new Error(`Property "${e}" has not been registered.`);return t}isRequired(e){const t=this.getPropInfo(e).validator;return t!=null}isPropValueValid(e){const t=this.getPropInfo(e);return t.validator?t.validator(this[t.name],t,this):!0}clone(e){const t=e.toObject();return delete t.id,this.fromObject(t)}fromObject(e){return this.fromObj(e),this.afterDeserialize(),this}fromObj(e){return this._persistentProperties?(this._persistentProperties.forEach(t=>{const r=this.removeUnderscore(t),s=e[r];s!=null&&(this[t.name]=this.fromDeepObject(s))}),this):this}toObject(){const e={},t=this.toObj(e);return this.pushDocument(e,this.className,t),{...t,__rootCollections:e}}toObj(e){if(!this._persistentProperties)return{};this.beforeSerialize();const t={};if(!this.className)throw new Error(`You should register \`${this.constructor.name||this.toString()||"this"}\` class prior to streaming it.`);return this._persistentProperties.forEach(r=>{const s=this[r.name],n=this.removeUnderscore(r);s!=null&&(r.isReference?t[n]=this.toReferenceObj(r,e):t[n]=this.toDeepObj(s,e),r.searchableArray&&(t[l.searchableArrayNameFor(n)]=s.map(o=>o.id)))}),t.__className=this.className,t}static searchableArrayNameFor(e){return`__${e}_searchable`}fromDeepObject(e){if(e==null)return e;if(Array.isArray(e))return e.map(t=>this.fromDeepObject(t));if(e.__documentReference){const t=e,r=l.createInstance(t);return r.__documentReference=e.__documentReference,r}if(e.__className)return l.createInstance(e);if(typeof e=="object"){const t={};return Object.entries(e).forEach(([r,s])=>t[r]=this.fromDeepObject(s)),t}return e}toDeepObj(e,t){if(e!=null){if(Array.isArray(e))return e.map(r=>this.toDeepObj(r,t));if(e.__documentReference)return e;if(e instanceof l)return e.toObj(t);if(typeof e=="object"){const r={};return Object.entries(e).forEach(([s,n])=>r[s]=this.toDeepObj(n,t)),r}return e}}static collectionPath(e,t){let r;return typeof t.storeInCollection=="function"?r=t.storeInCollection(e,t):r=t.storeInCollection??e.className,r}toReferenceObj(e,t){const r=this[e.name];return Array.isArray(r)?r.map(s=>(e.isPureReference||this.pushDocument(t,l.collectionPath(s,e),s),this.buildRefObject(s,l.collectionPath(s,e),e.cachedPropsConfig?.cachedProps))):(e.isPureReference||this.pushDocument(t,l.collectionPath(r,e),r),this.buildRefObject(r,l.collectionPath(r,e),e.cachedPropsConfig?.cachedProps))}buildRefObject(e,t,r){const s=r?.reduce((n,o)=>(e[o]!==void 0&&(n[o]=e[o]),n),{});return{id:e.id,__className:e.className||e.__className,__documentReference:{storedInCollection:t},...s}}pushDocument(e,t,r){if("__documentReference"in r&&r.__documentReference)return;e[t]||(e[t]=[]);const s=this.toDeepObj(r,e);e[t].push(s)}removeUnderscore(e){return e.name.slice(1)}static createReference(e){const t=l.createInstance(e);return t.__documentReference=e.__documentReference||{storedInCollection:t.className},t}static createInstance(e){if(typeof e=="string")return new(l.classFactory(e));try{return new(l.classFactory(e.__className))().fromObject(e)}catch(t){const r=Object.entries(e).filter(([s,n])=>n!=null&&typeof n!="function").map(([s,n])=>`${s}: ${n}`).join(`,
1
+ (function(a,v){typeof exports=="object"&&typeof module<"u"?v(exports):typeof define=="function"&&define.amd?define(["exports"],v):(a=typeof globalThis<"u"?globalThis:a||self,v(a["entropic-bond"]={}))})(this,function(a){"use strict";var d;class v{constructor(){this.subscribers=new Set}subscribe(e){return this.subscribers.add(e),()=>this.unsubscribe(e)}unsubscribe(e){this.subscribers.delete(e)}notify(e){this.subscribers.forEach(t=>t(e))}get subscribersCount(){return this.subscribers.size}}const p=[];for(let i=0;i<256;++i)p.push((i+256).toString(16).slice(1));function B(i,e=0){return(p[i[e+0]]+p[i[e+1]]+p[i[e+2]]+p[i[e+3]]+"-"+p[i[e+4]]+p[i[e+5]]+"-"+p[i[e+6]]+p[i[e+7]]+"-"+p[i[e+8]]+p[i[e+9]]+"-"+p[i[e+10]]+p[i[e+11]]+p[i[e+12]]+p[i[e+13]]+p[i[e+14]]+p[i[e+15]]).toLowerCase()}let E;const W=new Uint8Array(16);function Q(){if(!E){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");E=crypto.getRandomValues.bind(crypto)}return E(W)}const M={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function q(i,e,t){i=i||{};const r=i.random??i.rng?.()??Q();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,B(r)}function Y(i,e,t){return M.randomUUID&&!i?M.randomUUID():q(i)}var z=Object.defineProperty,J=(i,e,t,r)=>{for(var s=void 0,n=i.length-1,o;n>=0;n--)(o=i[n])&&(s=o(e,t,s)||s);return s&&z(e,t,s),s};const L=(d=class{static registerFactory(e,t,r,s=!1){this._factoryMap[e]={factory:t,annotation:r,isLegacy:s}}static classFactory(e){if(!e)throw new Error("You should provide a class name.");if(!this._factoryMap[e])throw new Error(`You should register class ${e} prior to use.`);return this._factoryMap[e].factory}static registeredClasses(){return Object.entries(this._factoryMap).filter(([,e])=>!e.isLegacy).map(([e])=>e)}static registeredClassesAndLegacyNames(){return Object.keys(this._factoryMap)}static classesExtending(e){return Object.entries(this._factoryMap).filter(([,t])=>new t.factory instanceof e&&!t.isLegacy).map(([t])=>t)}static annotations(e){if(e instanceof d?e=e.className:typeof e=="string"||(e=new e().className),!this._factoryMap[e])throw new Error(`You should register class ${e} prior to use.`);return this._factoryMap[e].annotation}constructor(e=Y()){this._id=e}get className(){return this.__className}setId(e){this._id=e}get id(){return this._id}afterDeserialize(){}beforeSerialize(){}getPersistentProperties(){return this._persistentProperties?this._persistentProperties.map(e=>({...e,name:e.name.slice(1)})):[]}getPropInfo(e){const t=this.getPersistentProperties().find(r=>r.name===e);if(!t)throw new Error(`Property "${e}" has not been registered.`);return t}isRequired(e){const t=this.getPropInfo(e).validator;return t!=null}isPropValueValid(e){const t=this.getPropInfo(e);return t.validator?t.validator(this[t.name],t,this):!0}clone(e){const t=e.toObject();return delete t.id,this.fromObject(t)}fromObject(e){return this.fromObj(e),this.afterDeserialize(),this}fromObj(e){return this._persistentProperties?(this._persistentProperties.forEach(t=>{const r=this.removeUnderscore(t),s=e[r];s!=null&&(this[t.name]=this.fromDeepObject(s))}),this):this}toObject(){const e={},t=this.toObj(e);return this.pushDocument(e,this.className,t),{...t,__rootCollections:e}}toObj(e){if(!this._persistentProperties)return{};this.beforeSerialize();const t={};if(!this.className)throw new Error(`You should register \`${this.constructor.name||this.toString()||"this"}\` class prior to streaming it.`);return this._persistentProperties.forEach(r=>{const s=this[r.name],n=this.removeUnderscore(r);s!=null&&(r.isReference?t[n]=this.toReferenceObj(r,e):t[n]=this.toDeepObj(s,e),r.searchableArray&&(t[d.searchableArrayNameFor(n)]=s.map(o=>o.id)))}),t.__className=this.className,t}static searchableArrayNameFor(e){return`__${e}_searchable`}fromDeepObject(e){if(e==null)return e;if(Array.isArray(e))return e.map(t=>this.fromDeepObject(t));if(e.__documentReference){const t=e,r=d.createInstance(t);return r.__documentReference=e.__documentReference,r}if(e.__className)return d.createInstance(e);if(typeof e=="object"){const t={};return Object.entries(e).forEach(([r,s])=>t[r]=this.fromDeepObject(s)),t}return e}toDeepObj(e,t){if(e!=null){if(Array.isArray(e))return e.map(r=>this.toDeepObj(r,t));if(e.__documentReference)return e;if(e instanceof d)return e.toObj(t);if(typeof e=="object"){const r={};return Object.entries(e).forEach(([s,n])=>r[s]=this.toDeepObj(n,t)),r}return e}}static collectionPath(e,t){let r;return typeof t.storeInCollection=="function"?r=t.storeInCollection(e,t):r=t.storeInCollection??e.className,r}toReferenceObj(e,t){const r=this[e.name];return Array.isArray(r)?r.map(s=>(e.isPureReference||this.pushDocument(t,d.collectionPath(s,e),s),this.buildRefObject(s,d.collectionPath(s,e),e.cachedPropsConfig?.cachedProps))):(e.isPureReference||this.pushDocument(t,d.collectionPath(r,e),r),this.buildRefObject(r,d.collectionPath(r,e),e.cachedPropsConfig?.cachedProps))}buildRefObject(e,t,r){const s=r?.reduce((n,o)=>(e[o]!==void 0&&(n[o]=e[o]),n),{});return{id:e.id,__className:e.className||e.__className,__documentReference:{storedInCollection:t},...s}}pushDocument(e,t,r){if("__documentReference"in r&&r.__documentReference)return;e[t]||(e[t]=[]);const s=this.toDeepObj(r,e);e[t].push(s)}removeUnderscore(e){return e.name.slice(1)}static createReference(e){const t=d.createInstance(e);return t.__documentReference=e.__documentReference||{storedInCollection:t.className},t}static createInstance(e){if(typeof e=="string")return new(d.classFactory(e));try{return new(d.classFactory(e.__className))().fromObject(e)}catch(t){const r=Object.entries(e).filter(([s,n])=>n!=null&&typeof n!="function").map(([s,n])=>`${s}: ${n}`).join(`,
2
2
  `);throw new Error(`${t}
3
3
  -----> Class name not found in object:
4
4
  {
5
5
  ${r}
6
6
  }
7
- `)}}static propInfo(e,t){return l.createInstance(e).getPropInfo(t)}static getSystemRegisteredReferencesWithCachedProps(){return l.registeredClassesAndLegacyNames().reduce((r,s)=>{const o=l.createInstance(s).getPersistentProperties().filter(c=>c.cachedPropsConfig?.cachedProps);return o.length>0&&(r[s]=o),r},{})}},l._factoryMap={},l);J([w],M.prototype,"_id");let u=M;function w(i,e){return _()(i,e)}function H(i){return function(e,t){return _({storeInCollection:i,isReference:!0})(e,t)}}function Z(i,e){return _({isReference:!0})(i,e)}function G(i,e,t){const r=Array.isArray(i)?{cachedProps:i}:i;return function(s,n){return _({isReference:!0,storeInCollection:e,typeName:t,cachedPropsConfig:r})(s,n)}}function K(i,e,t){return _({isReference:!0,isPureReference:!0,storeInCollection:t})(i,e)}function X(i,e,t){return function(r,s){const n=Array.isArray(i)?{cachedProps:i}:i;return _({isReference:!0,isPureReference:!0,storeInCollection:e,typeName:t,cachedPropsConfig:n})(r,s)}}function _(i){return function(e,t){Object.getOwnPropertyDescriptor(e,"_persistentProperties")||(e._persistentProperties?e._persistentProperties=[...e._persistentProperties]:e._persistentProperties=[]);const r=e._persistentProperties.find(s=>s.name===t);r?Object.assign(r,i):e._persistentProperties.push({name:t,...i})}}function L(i,e){return t=>{u.registerFactory(i,t,e),t.prototype.__className=i}}function x(i){return e=>{u.registerFactory(i,e,void 0,!0)}}function ee(i,e){return _({searchableArray:!0})(i,e)}function te(i,e){return _({validator:t=>t!=null})(i,e)}function re(i=e=>e!=null){return function(e,t){return _({validator:i})(e,t)}}class se extends u{constructor(){super(...arguments),this._onChange=new v}onChange(e){return this._onChange.subscribe(e)}removeOnChange(e){this._onChange.unsubscribe(e)}changeProp(e,t){const r="_"+String(e);return this[r]!==t?(this[r]=t,this._onChange.notify({[e]:t}),!0):!1}notify(e){this._onChange.notify(e)}pushAndNotify(e,t,r){const s="_"+String(e);if(!(r&&this[s].find(o=>!r(o,t))))return this[s].push(t),this.notify({[e]:this[e]}),t}removeAndNotify(e,t,r){const s="_"+String(e),n=this[s].length;if(this[s]=this[s].filter(o=>!r(o,t)),n!==this[s].length)return this.notify({[e]:this[e]}),t}}const j=class j{constructor(e,t,r){if(r){if(!(t instanceof u))throw new Error(j.error.persistentNeedForSubCollection);this.collectionName=`${t.className}/${t.id}/${r}`}else this.collectionName=t instanceof u?t.className:t;this._stream=e}findById(e,t){return new Promise((r,s)=>{this._stream.findById(e,this.collectionName).then(n=>{n?(t?t.fromObject(n):t=u.createInstance(n),r(t)):r(void 0)}).catch(n=>s(n))})}save(e){const t=e.toObject();return this.collectionName!==t.__className&&(t.__rootCollections[this.collectionName]=t.__rootCollections[t.__className],delete t.__rootCollections[t.__className]),new Promise((r,s)=>{this._stream.save(t.__rootCollections).then(()=>r()).catch(n=>s(n))})}delete(e){return new Promise((t,r)=>{this._stream.delete(e,this.collectionName).then(()=>t()).catch(s=>r(s))})}find(){return new V(this)}query(e={},t){if(t){const r=t instanceof u?t.className:t;e.operations||(e.operations=[]),e.operations.push({property:"__className",operator:"==",value:r})}return this.mapToInstance(()=>this._stream.find(this.preprocessQueryObject(e),this.collectionName))}count(e){return this._stream.count(e,this.collectionName)}next(e){return this.mapToInstance(()=>this._stream.next(e))}onDocumentChange(e,t){return this._stream.onDocumentChange(this.collectionName,e,r=>t(this.toPersistentChangeObject(r)))}onCollectionChange(e,t){return this._stream.onCollectionChange(this.preprocessQueryObject(e.getQueryObject()),this.collectionName,r=>t(r.map(s=>({after:s.after&&u.createInstance(s.after),before:s.before&&u.createInstance(s.before),type:s.type,params:s.params}))))}toPersistentChangeObject(e){return{...e,before:e.before&&u.createInstance(e.before),after:e.after&&u.createInstance(e.after)}}mapToInstance(e){return new Promise((t,r)=>{e().then(s=>t(s.map(n=>u.createInstance(n)))).catch(s=>r(s))})}preprocessQueryObject(e){if(Object.values(e).length===0)return e;const t=e.operations?.map(r=>{const s=r.value[0]??r.value;return R.isArrayOperator(r.operator)&&s instanceof u?{property:u.searchableArrayNameFor(r.property),operator:r.operator,value:Array.isArray(r.value)?r.value.map(n=>n.id):s.id,aggregate:r.aggregate}:{property:r.property,operator:r.operator,value:r.value instanceof u?{id:r.value.id}:r.value,aggregate:r.aggregate}})??[];return{...e,operations:t}}};j.error={persistentNeedForSubCollection:"The document parameter for a sub-collection should be a Persistent instace",invalidQueryOrder:"Cannot add where calls after or calls"};let S=j;class V{constructor(e){this.queryObject={operations:[]},this.model=e}where(e,t,r,s){if(this.queryObject.operations?.at(-1)?.aggregate&&!s)throw new Error(S.error.invalidQueryOrder);return this.queryObject.operations?.push({property:e,operator:t,value:r,aggregate:s}),this}whereDeepProp(e,t,r,s){if(this.queryObject.operations?.at(-1)?.aggregate&&!s)throw new Error(S.error.invalidQueryOrder);const n=e.split(".");let o={},c=n.length>1?o:r;return n.slice(1).forEach((h,d)=>{o[h]=d<n.length-2?{}:r,o=o[h]}),this.queryObject.operations?.push({property:n[0],operator:t,value:c,aggregate:s}),this}and(e,t,r){return this.where(e,t,r)}andDeepProp(e,t,r){return this.whereDeepProp(e,t,r)}or(e,t,r){return this.where(e,t,r,!0)}orDeepProp(e,t,r){return this.whereDeepProp(e,t,r,!0)}instanceOf(e){const t=e instanceof u?e.className:e;return this.queryObject.operations?.push({property:"__className",operator:"==",value:t}),this}get(e){return e&&(this.queryObject.limit=e),this.model.query(this.queryObject)}limit(e){return this.queryObject.limit=e,this}orderBy(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}orderByDeepProp(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}count(){return this.model.count(this.queryObject)}getQueryObject(){return this.queryObject}}const b=class b{constructor(){}static useDataSource(e){this._dataSource=e}static get dataSource(){return b._dataSource}static getModel(e){if(!b._dataSource)throw new Error(this.error.shouldBeRegistered);return new S(b._dataSource,e)}static getModelForSubCollection(e,t){if(!b._dataSource)throw new Error(this.error.shouldBeRegistered);return new S(b._dataSource,e,t)}static async populate(e){if(!e)return;const t=async r=>{const s=r;if(!s.__documentReference)return r;const o=await this.getModel(s.__documentReference.storedInCollection).findById(s.id,r);return o&&(o.__documentReference=void 0),o};return Array.isArray(e)?(await Promise.all(e.map(s=>t(s)))).filter(s=>s):t(e)}static isPopulated(e){return Array.isArray(e)?e.reduce((t,r)=>t&&r.__documentReference===void 0,!0):e.__documentReference===void 0}};b.error={shouldBeRegistered:"You should register a data source before using the data Store."};let O=b;class R{installCachedPropsUpdaters(e={}){R.onUpdate=e.onUpdate;const t=u.getSystemRegisteredReferencesWithCachedProps(),r={};Object.entries(t).forEach(([n,o])=>{o.forEach(c=>{const h=u.collectionPath(u.createInstance(n),c);r[h]||(r[h]=[]),r[h].push({prop:c,collectionPropOwner:n})})});const s=[];return Object.entries(r).forEach(([n,o])=>{const c=this.subscribeToDocumentChangeListener(n,h=>R.processDocumentChange(h,o));if(c)s.push(c);else if(e.noThrowOnNonImplementedListener)throw new Error("The method documentChangeListener has not been implemented in the concrete data source")}),s}subscribeToDocumentChangeListener(e,t){}static toPropertyPathOperations(e){return e?e.map(t=>{if(R.isArrayOperator(t.operator)&&t.value[0]instanceof u)return{property:u.searchableArrayNameFor(t.property),operator:t.operator,value:t.value.map(o=>o.id),aggregate:t.aggregate};const[r,s]=this.toPropertyPathValue(t.value);return{property:`${String(t.property)}${r?"."+r:""}`,operator:t.operator,value:s,aggregate:t.aggregate}}):[]}static isArrayOperator(e){return e==="containsAny"||e==="contains"}static toPropertyPathValue(e){if(typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e)[0],[r,s]=this.toPropertyPathValue(e[t]);return[`${t}${r?"."+r:""}`,s]}else return[void 0,e]}static async processDocumentChange(e,t){if(e.before)return t.map(async r=>{const s=O.getModel(r.collectionPropOwner);let n=s.find();r.prop.cachedPropsConfig?.cachedProps?.forEach(c=>{const h=e.before?.[c],d=e.after?.[c];h!==d&&(n=n.orDeepProp(`${r.prop.name}.${c}`,"==",h))});const o=await n.get();return Promise.all([o.map(async c=>{r.prop.cachedPropsConfig?.cachedProps?.forEach(async h=>{const d=e.before?.[h],f=e.after?.[h];d!==f&&(c[`_${r.prop.name}`][`_${h}`]=f,await s.save(c),this.onUpdate?.(c,r.prop))})})])})}}class ie extends R{constructor(e){super(),this._jsonRawData={},this._lastMatchingDocs=[],this._lastLimit=0,this._cursor=0,this._simulateDelay=0,this._pendingPromises=[],this._documentListeners={},this._collectionListeners={},this._serverCollectionListeners={},e&&(this._jsonRawData=e)}setDataStore(e){return this._jsonRawData=e,this}simulateDelay(e){return this._simulateDelay=e,this}findById(e,t){if(this._simulateError?.findById)throw new Error(this._simulateError.findById);return this.resolveWithDelay(this._jsonRawData[t]?.[e])}save(e){if(this._simulateError?.store)throw new Error(this._simulateError.store);return Object.entries(e).forEach(([t,r])=>{this._jsonRawData[t]||(this._jsonRawData[t]={}),r?.forEach(s=>{const n=this._jsonRawData[t][s.id];this._jsonRawData[t][s.id]=s,n&&this.notifyChange(t,s,n)})}),this.resolveWithDelay()}find(e,t){if(this._simulateError?.find)throw new Error(this._simulateError.find);const r=Object.values(this._jsonRawData[t]||{});return e?(this._lastLimit=e.limit||0,this._cursor=0,this._lastMatchingDocs=Object.entries(e).reduce((s,[n,o])=>this.queryProcessor(s,n,o),Object.values(r)),this.resolveWithDelay(this._lastMatchingDocs.slice(0,e.limit))):this.resolveWithDelay(r)}delete(e,t){if(this._simulateError?.delete)throw new Error(this._simulateError.delete);return delete this._jsonRawData[t][e],this.resolveWithDelay()}next(e){return e&&(this._lastLimit=e),this.incCursor(this._lastLimit),this.resolveWithDelay(this._lastMatchingDocs.slice(this._cursor,this._cursor+this._lastLimit))}count(e,t){return this.resolveWithDelay(Object.keys(this._jsonRawData[t]??{}).length)}onCollectionChange(e,t,r){return this._collectionListeners[t]=s=>{if(!s.after)return;const n=this.retrieveQueryDocs([s.after],e.operations);n.length>0&&r(n.map(o=>({before:void 0,after:o,type:s.type,params:s.params})))},()=>delete this._serverCollectionListeners[t]}onDocumentChange(e,t,r){return this._documentListeners[e]=s=>{s.after&&s.after.id===t&&r(s)},()=>delete this._serverCollectionListeners[e]}get rawData(){return this._jsonRawData}wait(){return Promise.all([...this._pendingPromises])}incCursor(e){this._cursor+=e,this._cursor>this._lastMatchingDocs.length&&(this._cursor=this._lastMatchingDocs.length)}simulateError(e){return e===void 0?(this._simulateError=void 0,this):(typeof e=="string"?this._simulateError={store:e,find:e,findById:e,delete:e}:this._simulateError=e,this)}subscribeToDocumentChangeListener(e,t){return delete this._serverCollectionListeners[e],this._serverCollectionListeners[e]=t,{uninstall:()=>delete this._serverCollectionListeners[e],nativeHandler:t,collectionPath:e}}notifyChange(e,t,r){const s={before:r,after:t,collectionPath:e,params:{},type:r?"update":"create"};this._serverCollectionListeners[e]?.(s),this._documentListeners[e]?.(s),this._collectionListeners[e]?.(s)}decCursor(e){return this._cursor-=e,this._cursor<0?(this._cursor=0,!0):!1}queryProcessor(e,t,r){return{limit:n=>e,operations:n=>this.retrieveQueryDocs(e,n),sort:({order:n,propertyName:o})=>e.sort((c,h)=>n==="asc"?this.deepValue(c,o)>this.deepValue(h,o)?1:-1:this.deepValue(c,o)<this.deepValue(h,o)?1:-1)}[t](r)}retrieveQueryDocs(e,t){return t.reduce((r,s,n)=>{if(s.aggregate){const o=e.filter(c=>this.isQueryMatched(c,s));return n===0?o:r.concat(o)}else return r.filter(o=>this.isQueryMatched(o,s))},e)}deepValue(e,t){return t.split(".").reduce((s,n)=>s[n],e)}isQueryMatched(e,t){const r={"==":(d,f)=>d===f,"!=":(d,f)=>d!==f,"<":(d,f)=>d<f,"<=":(d,f)=>d<=f,">":(d,f)=>d>f,">=":(d,f)=>d>=f,containsAny:(d,f)=>d?.some(ge=>f?.includes(ge)),contains:(d,f)=>d?.includes(f)},{property:s,value:n,operator:o}=t,[c,h]=this.retrieveValuesToCompare(e,s,n);return r[o](c,h)}retrieveValuesToCompare(e,t,r){const s=e[t];if(s&&typeof r=="object"&&!Array.isArray(r)){const c=Object.keys(r)[0];var[n,o]=this.retrieveValuesToCompare(s,c,r?.[c])}return[n||s,o||r]}resolveWithDelay(e){if(this._simulateDelay<=0)return Promise.resolve(e);const t=new Promise(r=>{setTimeout(()=>r(e),this._simulateDelay)});return this._pendingPromises.push(t),t.finally(()=>this._pendingPromises=this._pendingPromises.filter(r=>r===t)),t}}const C=class C{static registerCloudStorage(e,t){C._cloudStorageFactoryMap[e]=t}static createInstance(e){const t=C._cloudStorageFactoryMap[e];if(!t)throw new Error(`You should register the ${e} cloud storage provider prior to use it`);return t()}get className(){return this.__className}static useCloudStorage(e){C._defaultCloudStorage=e}static get defaultCloudStorage(){if(!C._defaultCloudStorage)throw new Error("You should define a default cloud storage provider prior to use it");return C._defaultCloudStorage}};C._cloudStorageFactoryMap={};let P=C;function $(i,e){return P.registerCloudStorage(i,e),t=>{t.prototype.__className=i}}var ne=Object.getOwnPropertyDescriptor,oe=(i,e,t,r)=>{for(var s=r>1?void 0:r?ne(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(s=o(s)||s);return s};a.MockCloudStorage=class extends P{constructor(e=""){super(),this._simulateDelay=0,this._pendingPromises=[],this.mockFileSystem={},this._pathToMockFiles=e}simulateDelay(e){return this._simulateDelay=e,this}resolveWithDelay(e){if(this._simulateDelay<=0)return Promise.resolve(e);const t=new Promise(r=>{setTimeout(()=>r(e),this._simulateDelay)});return this._pendingPromises.push(t),t.finally(()=>this._pendingPromises=this._pendingPromises.filter(r=>r===t)),t}save(e,t){const r=e;this._onProgress&&this._onProgress(0,100),this.mockFileSystem[e]=JSON.stringify(t),this._onProgress&&this._onProgress(100,100);const s=t instanceof File?t.name:r;return this.resolveWithDelay(s)}uploadControl(){return{resume:()=>{},pause:()=>{},cancel:()=>{},onProgress:e=>this._onProgress=e}}getUrl(e){return Promise.resolve(this._pathToMockFiles+e)}delete(e){return delete this.mockFileSystem[e],this.resolveWithDelay()}},a.MockCloudStorage=oe([$("MockCloudStorage",()=>new a.MockCloudStorage)],a.MockCloudStorage);var ae=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,D=(i,e,t,r)=>{for(var s=r>1?void 0:r?ce(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(s=(r?o(e,t,s):o(s))||s);return r&&s&&ae(e,t,s),s},T=(i=>(i[i.stored=0]="stored",i[i.pendingDataSet=1]="pendingDataSet",i[i.deleted=2]="deleted",i))(T||{});a.StoredFile=class extends u{constructor(){super(...arguments),this._onChange=new v}async save({data:e,fileName:t,progress:r,cloudStorageProvider:s}={}){const n=e||this._pendingData;n&&(this._reference&&await this.delete(),this.provider=s||P.defaultCloudStorage,this._originalFileName=t||(n instanceof File?n.name:void 0),this._reference=await this.provider.save(this.id,n,r),this._url=await this.provider.getUrl(this._reference),this._pendingData=void 0,this._onChange.notify({event:0,storedFile:this}))}uploadControl(){return this.provider.uploadControl()}async delete(){if(!this._reference)throw new Error("Cannot delete a not stored file");await this.provider.delete(this._reference),this._reference=void 0,this._url=void 0,this._onChange.notify({event:2,storedFile:this})}set provider(e){this._provider=e,this._cloudStorageProviderName=e.className}get provider(){if(!this._provider)try{this._provider=P.createInstance(this._cloudStorageProviderName)}catch{this._provider=P.defaultCloudStorage}return this._provider}get url(){return this._url}get mimeType(){return this._mimeType}setDataToStore(e){return this._pendingData=e,this._originalFileName=e instanceof File?e.name:void 0,this._mimeType=e instanceof Blob?e.type:void 0,this._onChange.notify({event:1,pendingData:e,storedFile:this}),this}get originalFileName(){return this._originalFileName}onChange(e){return this._onChange.subscribe(e)}},D([w],a.StoredFile.prototype,"_reference",2),D([w],a.StoredFile.prototype,"_url",2),D([w],a.StoredFile.prototype,"_cloudStorageProviderName",2),D([w],a.StoredFile.prototype,"_originalFileName",2),D([w],a.StoredFile.prototype,"_mimeType",2),a.StoredFile=D([L("StoredFile")],a.StoredFile);class E{}const m=class m extends E{constructor(){if(super(),this._onAuthStateChange=new v,!m._authService)throw new Error(m.error.shouldBeRegistered);m._authService.onAuthStateChange(e=>this.authStateChanged(e))}static useAuthService(e){m._authService!=e&&(m._authService=e,this._instance=void 0)}static get instance(){return this._instance||(this._instance=new this)}signUp(e){return m._authService.signUp(e)}login(e){return m._authService.login(e)}logout(){return m._authService.logout()}resetEmailPassword(e){return m._authService.resetEmailPassword(e)}resendVerificationEmail(e,t,r){return m._authService.resendVerificationEmail(e,t,r)}refreshToken(){return m._authService.refreshToken()}onAuthStateChange(e){return this._onAuthStateChange.subscribe(e)}removeAuthStateChange(e){this._onAuthStateChange.unsubscribe(e)}linkAdditionalProvider(e){return m._authService.linkAdditionalProvider(e)}unlinkProvider(e){return m._authService.unlinkProvider(e)}authStateChanged(e){this._onAuthStateChange.notify(e)}};m.error={shouldBeRegistered:"You should register an auth service before using Auth."},m._instance=void 0;let U=m;class ue extends E{constructor(){super(...arguments),this.pendingPromises=[],this._fakeRegisteredUsers={}}signUp(e){const{verificationLink:t,email:r,password:s,authProvider:n}=e,o=new Promise(async(c,h)=>{n==="email"&&(r||h({code:"missingEmail",message:"missingEmail"}),s||h({code:"missingPassword",message:"missingPassword"})),s!=="fail"&&r!=="fail"?(this._loggedUser=this.userCredentials(e),this._fakeRegisteredUsers[this._loggedUser.id]=this._loggedUser,c(this._loggedUser),this.notifyChange?.(this._loggedUser)):(h({code:"userNotFound",message:t||"Test auth error"}),this.notifyChange?.(void 0))});return this.pendingPromises.push(o),o}login(e){const t=Object.values(this._fakeRegisteredUsers).find(r=>r.email===e.email);return e.authProvider==="email"&&!t&&e.email&&(e.email="fail"),this.signUp(e)}onAuthStateChange(e){this.notifyChange=e,this.notifyChange(this._loggedUser)}async logout(){const e=new Promise(t=>{this._loggedUser=void 0,t(),this.notifyChange?.(void 0)});return this.pendingPromises.push(e),e}resetEmailPassword(e){return Object.values(this._fakeRegisteredUsers).find(r=>r.email===e)?Promise.resolve():Promise.reject({code:"userNotFound",message:"Test auth error"})}resendVerificationEmail(e,t,r){return Object.values(this._fakeRegisteredUsers).find(n=>n.email===e)?Promise.resolve():Promise.reject({code:"userNotFound",message:"Test auth error"})}refreshToken(){return Promise.resolve()}linkAdditionalProvider(e){throw new Error("Not implemented.")}unlinkProvider(e){throw new Error("Not implemented.")}async flush(){await Promise.all(this.pendingPromises),this.pendingPromises=[]}fakeRegisteredUser(e){if(this._fakeRegisteredUsers[e.id])throw new Error(`User with id ${e.id} already exists in fake user list`);return this._fakeRegisteredUsers[e.id]=e,this}get fakeRegisteredUsers(){return this._fakeRegisteredUsers}userCredentials(e){const t=Object.values(this._fakeRegisteredUsers).find(r=>r.email===e.email);return t?{...t}:{id:e.authProvider||`testUID${e.email?"-"+e.email:""}`,email:e.email||"testEmail",name:e.authProvider||`testName${e.email?" "+e.email:""}`,phoneNumber:"testPhone",customData:{role:"test"},lastLogin:0,creationDate:0}}}const y=class y{constructor(){}static useCloudFunctionsService(e){this._cloudFunctionsService!=e&&(this._cloudFunctionsService=e)}static get instance(){if(!this._cloudFunctionsService)throw new Error(y.error.shouldBeRegistered);return y._instance||(y._instance=new y)}getRawFunction(e){return y._cloudFunctionsService.retrieveFunction(e)}getFunction(e){const t=y._cloudFunctionsService.callFunction,r=this.getRawFunction(e);return async s=>{const n=await t(r,this.processParam(s));return this.processResult(n)}}processParam(e){if(e!=null)return e instanceof u?e.toObject():Array.isArray(e)?e.map(t=>this.processParam(t)):typeof e=="object"?Object.entries(e).reduce((t,[r,s])=>(t[r]=this.processParam(s),t),{}):e}processResult(e){if(e!=null)return e.__className?u.createInstance(e):Array.isArray(e)?e.map(t=>this.processResult(t)):typeof e=="object"?Object.entries(e).reduce((t,[r,s])=>(t[r]=this.processResult(s),t),{}):e}};y.error={shouldBeRegistered:"You should register a cloud functions service with useCloudFunctionsService static method before using CloudFunctions."};let F=y;class he{constructor(e){this._registeredFunctions=e}retrieveFunction(e){const t=this._registeredFunctions[e];if(!t)throw new Error(`Cloud function ${e} is not registered.`);return t}callFunction(e,t){return e(t)}}class I{}const g=class g extends I{constructor(){super()}static useServerAuthService(e){g._authService!=e&&(g._authService=e,this._instance=void 0)}static get instance(){if(!g._authService)throw new Error(g.error.shouldBeRegistered);return this._instance||(this._instance=new g)}getUser(e){return g._authService.getUser(e)}updateUser(e,t){return g._authService.updateUser(e,t)}setCustomCredentials(e,t){return g._authService.setCustomCredentials(e,t)}deleteUser(e){return g._authService.deleteUser(e)}};g.error={shouldBeRegistered:"You should register a Server Auth service before using the Server Auth."},g._instance=void 0;let k=g;class le extends I{constructor(e){super(),this._userCredentials=e}getUser(e){return this._userCredentials[e]||Promise.resolve(void 0),Promise.resolve(this._userCredentials[e])}setCustomCredentials(e,t){const r=this._userCredentials[e];if(!r)throw new Error(`User ${e} not found in the auth system`);return r.customData={...t},Promise.resolve()}updateUser(e,t){return this._userCredentials[e]={...this._userCredentials,...t,id:e},Promise.resolve(this._userCredentials[e])}deleteUser(e){return delete this._userCredentials[e],Promise.resolve()}get userCredentials(){return this._userCredentials}}function de(i,e){return i?i.replace(/\${\s*(\w*)\s*}/g,function(t,r){return e[r]||""}):""}function fe(i){return i?i.replace(/([-_ ][\w])/g,e=>e.toUpperCase().replace("-","").replace("_","").replace(" ","")):""}function pe(i,e="-"){if(!i)return"";const t=i.slice(1).replace(/( |[A-Z])/g,r=>r===" "?"-":e+r[0].toLowerCase());return i[0].toLocaleLowerCase()+t.replace(/--/g,"-")}function me(i,e){return e.split(".").reduce((t,r)=>t[r],i)}a.Auth=U,a.AuthMock=ue,a.AuthService=E,a.CloudFunctions=F,a.CloudFunctionsMock=he,a.CloudStorage=P,a.DataSource=R,a.EntropicComponent=se,a.JsonDataSource=ie,a.Model=S,a.Observable=v,a.Persistent=u,a.Query=V,a.ServerAuth=k,a.ServerAuthMock=le,a.ServerAuthService=I,a.Store=O,a.StoredFileEvent=T,a.camelCase=fe,a.getDeepValue=me,a.persistent=w,a.persistentParser=_,a.persistentPureReference=K,a.persistentPureReferenceWithCachedProps=X,a.persistentReference=Z,a.persistentReferenceAt=H,a.persistentReferenceWithCachedProps=G,a.registerCloudStorage=$,a.registerLegacyClassName=x,a.registerPersistentClass=L,a.replaceValue=de,a.required=te,a.requiredWithValidator=re,a.searchableArray=ee,a.snakeCase=pe,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});
7
+ `)}}static propInfo(e,t){return d.createInstance(e).getPropInfo(t)}static getSystemRegisteredReferencesWithCachedProps(){return d.registeredClassesAndLegacyNames().reduce((r,s)=>{const o=d.createInstance(s).getPersistentProperties().filter(c=>c.cachedPropsConfig?.cachedProps);return o.length>0&&(r[s]=o),r},{})}},d._factoryMap={},d);J([w],L.prototype,"_id");let h=L;function w(i,e){return _()(i,e)}function H(i){return function(e,t){return _({storeInCollection:i,isReference:!0})(e,t)}}function Z(i,e){return _({isReference:!0})(i,e)}function G(i,e,t){const r=Array.isArray(i)?{cachedProps:i}:i;return function(s,n){return _({isReference:!0,storeInCollection:e,typeName:t,cachedPropsConfig:r})(s,n)}}function K(i,e,t){return _({isReference:!0,isPureReference:!0,storeInCollection:t})(i,e)}function X(i,e,t){return function(r,s){const n=Array.isArray(i)?{cachedProps:i}:i;return _({isReference:!0,isPureReference:!0,storeInCollection:e,typeName:t,cachedPropsConfig:n})(r,s)}}function _(i){return function(e,t){Object.getOwnPropertyDescriptor(e,"_persistentProperties")||(e._persistentProperties?e._persistentProperties=[...e._persistentProperties]:e._persistentProperties=[]);const r=e._persistentProperties.find(s=>s.name===t);r?Object.assign(r,i):e._persistentProperties.push({name:t,...i})}}function N(i,e){return t=>{h.registerFactory(i,t,e),t.prototype.__className=i}}function x(i){return e=>{h.registerFactory(i,e,void 0,!0)}}function ee(i,e){return _({searchableArray:!0})(i,e)}function te(i,e){return _({validator:t=>t!=null})(i,e)}function re(i=e=>e!=null){return function(e,t){return _({validator:i})(e,t)}}class se extends h{constructor(){super(...arguments),this._onChange=new v}onChange(e){return this._onChange.subscribe(e)}removeOnChange(e){this._onChange.unsubscribe(e)}changeProp(e,t){const r="_"+String(e);return this[r]!==t?(this[r]=t,this._onChange.notify({[e]:t}),!0):!1}notify(e){this._onChange.notify(e)}pushAndNotify(e,t,r){const s="_"+String(e);if(!(r&&this[s].find(o=>!r(o,t))))return this[s].push(t),this.notify({[e]:this[e]}),t}removeAndNotify(e,t,r){const s="_"+String(e),n=this[s].length;if(this[s]=this[s].filter(o=>!r(o,t)),n!==this[s].length)return this.notify({[e]:this[e]}),t}}const j=class j{constructor(e,t,r){if(r){if(!(t instanceof h))throw new Error(j.error.persistentNeedForSubCollection);this.collectionName=`${t.className}/${t.id}/${r}`}else this.collectionName=t instanceof h?t.className:t;this._stream=e}findById(e,t){return new Promise((r,s)=>{this._stream.findById(e,this.collectionName).then(n=>{n?(t?t.fromObject(n):t=h.createInstance(n),r(t)):r(void 0)}).catch(n=>s(n))})}save(e){const t=e.toObject();return this.collectionName!==t.__className&&(t.__rootCollections[this.collectionName]=t.__rootCollections[t.__className],delete t.__rootCollections[t.__className]),new Promise((r,s)=>{this._stream.save(t.__rootCollections).then(()=>r()).catch(n=>s(n))})}delete(e){return new Promise((t,r)=>{this._stream.delete(e,this.collectionName).then(()=>t()).catch(s=>r(s))})}find(){return new V(this)}query(e={},t){if(t){const r=t instanceof h?t.className:t;e.operations||(e.operations=[]),e.operations.push({property:"__className",operator:"==",value:r})}return this.mapToInstance(()=>this._stream.find(this.preprocessQueryObject(e),this.collectionName))}count(e){return this._stream.count(e,this.collectionName)}next(e){return this.mapToInstance(()=>this._stream.next(e))}onDocumentChange(e,t){return this._stream.onDocumentChange(this.collectionName,e,r=>t(this.toPersistentChangeObject(r)))}onCollectionChange(e,t){return this._stream.onCollectionChange(this.preprocessQueryObject(e.getQueryObject()),this.collectionName,r=>t(r.map(s=>({after:s.after&&h.createInstance(s.after),before:s.before&&h.createInstance(s.before),type:s.type,params:s.params}))))}toPersistentChangeObject(e){return{...e,before:e.before&&h.createInstance(e.before),after:e.after&&h.createInstance(e.after)}}mapToInstance(e){return new Promise((t,r)=>{e().then(s=>t(s.map(n=>h.createInstance(n)))).catch(s=>r(s))})}preprocessQueryObject(e){if(Object.values(e).length===0)return e;const t=e.operations?.map(r=>{const s=r.value[0]??r.value;return R.isArrayOperator(r.operator)&&s instanceof h?{property:h.searchableArrayNameFor(r.property),operator:r.operator,value:Array.isArray(r.value)?r.value.map(n=>n.id):s.id,aggregate:r.aggregate}:{property:r.property,operator:r.operator,value:r.value instanceof h?{id:r.value.id}:r.value,aggregate:r.aggregate}})??[];return{...e,operations:t}}};j.error={persistentNeedForSubCollection:"The document parameter for a sub-collection should be a Persistent instace",invalidQueryOrder:"Cannot add where calls after or calls"};let S=j;class V{constructor(e){this.queryObject={operations:[]},this.model=e}where(e,t,r,s){if(this.queryObject.operations?.at(-1)?.aggregate&&!s)throw new Error(S.error.invalidQueryOrder);return this.queryObject.operations?.push({property:e,operator:t,value:r,aggregate:s}),this}whereDeepProp(e,t,r,s){if(this.queryObject.operations?.at(-1)?.aggregate&&!s)throw new Error(S.error.invalidQueryOrder);const n=e.split(".");let o={},c=n.length>1?o:r;return n.slice(1).forEach((u,l)=>{o[u]=l<n.length-2?{}:r,o=o[u]}),this.queryObject.operations?.push({property:n[0],operator:t,value:c,aggregate:s}),this}and(e,t,r){return this.where(e,t,r)}andDeepProp(e,t,r){return this.whereDeepProp(e,t,r)}or(e,t,r){return this.where(e,t,r,!0)}orDeepProp(e,t,r){return this.whereDeepProp(e,t,r,!0)}instanceOf(e){const t=e instanceof h?e.className:e;return this.queryObject.operations?.push({property:"__className",operator:"==",value:t}),this}get(e){return e&&(this.queryObject.limit=e),this.model.query(this.queryObject)}limit(e){return this.queryObject.limit=e,this}orderBy(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}orderByDeepProp(e,t="asc"){return this.queryObject.sort={propertyName:e,order:t},this}count(){return this.model.count(this.queryObject)}getQueryObject(){return this.queryObject}}const b=class b{constructor(){}static useDataSource(e){this._dataSource=e}static get dataSource(){return b._dataSource}static getModel(e){if(!b._dataSource)throw new Error(this.error.shouldBeRegistered);return new S(b._dataSource,e)}static getModelForSubCollection(e,t){if(!b._dataSource)throw new Error(this.error.shouldBeRegistered);return new S(b._dataSource,e,t)}static async populate(e){if(!e)return;const t=async r=>{const s=r;if(!s.__documentReference)return r;const o=await this.getModel(s.__documentReference.storedInCollection).findById(s.id,r);return o&&(o.__documentReference=void 0),o};return Array.isArray(e)?(await Promise.all(e.map(s=>t(s)))).filter(s=>s):t(e)}static isPopulated(e){return Array.isArray(e)?e.reduce((t,r)=>t&&r.__documentReference===void 0,!0):e.__documentReference===void 0}};b.error={shouldBeRegistered:"You should register a data source before using the data Store."};let D=b;class R{installCachedPropsUpdaters(e={}){R.onUpdate=e.onUpdate;const t=h.getSystemRegisteredReferencesWithCachedProps(),r={};Object.entries(t).forEach(([n,o])=>{o.forEach(c=>{const u=h.collectionPath(h.createInstance(n),c);r[u]||(r[u]=[]),r[u].push({prop:c,collectionPropOwner:n})})});const s=[];return Object.entries(r).forEach(([n,o])=>{const c=this.subscribeToDocumentChangeListener(n,u=>R.processDocumentChange(u,o));if(c)s.push(c);else if(e.noThrowOnNonImplementedListener)throw new Error("The method documentChangeListener has not been implemented in the concrete data source")}),s}subscribeToDocumentChangeListener(e,t){}static toPropertyPathOperations(e){return e?e.map(t=>{if(R.isArrayOperator(t.operator)&&t.value[0]instanceof h)return{property:h.searchableArrayNameFor(t.property),operator:t.operator,value:t.value.map(o=>o.id),aggregate:t.aggregate};const[r,s]=this.toPropertyPathValue(t.value);return{property:`${String(t.property)}${r?"."+r:""}`,operator:t.operator,value:s,aggregate:t.aggregate}}):[]}static isArrayOperator(e){return e==="containsAny"||e==="contains"}static toPropertyPathValue(e){if(typeof e=="object"&&!Array.isArray(e)){const t=Object.keys(e)[0],[r,s]=this.toPropertyPathValue(e[t]);return[`${t}${r?"."+r:""}`,s]}else return[void 0,e]}static async processDocumentChange(e,t){if(e.before)return t.map(async r=>{const s=D.getModel(r.collectionPropOwner);let n=s.find();r.prop.cachedPropsConfig?.cachedProps?.forEach(c=>{const u=e.before?.[c],l=e.after?.[c];u!==l&&(n=n.orDeepProp(`${r.prop.name}.${c}`,"==",u))});const o=await n.get();return Promise.all([o.map(async c=>{r.prop.cachedPropsConfig?.cachedProps?.forEach(async u=>{const l=e.before?.[u],f=e.after?.[u];l!==f&&(c[`_${r.prop.name}`][`_${u}`]=f,await s.save(c),this.onUpdate?.(c,r.prop))})})])})}}class ie extends R{constructor(e){super(),this._jsonRawData={},this._lastMatchingDocs=[],this._lastLimit=0,this._cursor=0,this._simulateDelay=0,this._pendingPromises=[],this._documentListeners={},this._collectionListeners={},this._serverCollectionListeners={},e&&(this._jsonRawData=e)}setDataStore(e){return this._jsonRawData=e,this}simulateDelay(e){return this._simulateDelay=e,this}findById(e,t){if(this._simulateError?.findById)throw new Error(this._simulateError.findById);return this.resolveWithDelay(this._jsonRawData[t]?.[e])}save(e){if(this._simulateError?.store)throw new Error(this._simulateError.store);return Object.entries(e).forEach(([t,r])=>{this._jsonRawData[t]||(this._jsonRawData[t]={}),r?.forEach(s=>{const n=this._jsonRawData[t][s.id];this._jsonRawData[t][s.id]=s,this.notifyChange(t,s,n)})}),this.resolveWithDelay()}find(e,t){if(this._simulateError?.find)throw new Error(this._simulateError.find);const r=Object.values(this._jsonRawData[t]||{});return e?(this._lastLimit=e.limit||0,this._cursor=0,this._lastMatchingDocs=Object.entries(e).reduce((s,[n,o])=>this.queryProcessor(s,n,o),Object.values(r)),this.resolveWithDelay(this._lastMatchingDocs.slice(0,e.limit))):this.resolveWithDelay(r)}delete(e,t){if(this._simulateError?.delete)throw new Error(this._simulateError.delete);return delete this._jsonRawData[t][e],this.resolveWithDelay()}next(e){return e&&(this._lastLimit=e),this.incCursor(this._lastLimit),this.resolveWithDelay(this._lastMatchingDocs.slice(this._cursor,this._cursor+this._lastLimit))}count(e,t){return this.resolveWithDelay(Object.keys(this._jsonRawData[t]??{}).length)}onCollectionChange(e,t,r){let s=this._collectionListeners[t];s||(this._collectionListeners[t]={},s=this._collectionListeners[t]);const n=c=>{if(!c.after)return;const u=this.retrieveQueryDocs([c.after],e.operations);u.length>0&&r(u.map(l=>({before:void 0,after:l,type:c.type,params:c.params})))},o=Math.random().toString(36).substring(2,9);return s[o]=n,()=>delete s[o]}onDocumentChange(e,t,r){let s=this._documentListeners[e];s||(this._documentListeners[e]={},s=this._documentListeners[e]);const n=c=>{c.after&&c.after.id===t&&r(c)},o=Math.random().toString(36).substring(2,9);return s[o]=n,()=>delete s[o]}get rawData(){return this._jsonRawData}wait(){return Promise.all([...this._pendingPromises])}incCursor(e){this._cursor+=e,this._cursor>this._lastMatchingDocs.length&&(this._cursor=this._lastMatchingDocs.length)}simulateError(e){return e===void 0?(this._simulateError=void 0,this):(typeof e=="string"?this._simulateError={store:e,find:e,findById:e,delete:e}:this._simulateError=e,this)}subscribeToDocumentChangeListener(e,t){return delete this._serverCollectionListeners[e],this._serverCollectionListeners[e]=t,{uninstall:()=>delete this._serverCollectionListeners[e],nativeHandler:t,collectionPath:e}}notifyChange(e,t,r){const s={before:r,after:t,collectionPath:e,params:{},type:r?"update":"create"};this._serverCollectionListeners[e]?.(s),Object.values(this._documentListeners[e]??{}).forEach(n=>n(s)),Object.values(this._collectionListeners[e]??{}).forEach(n=>n(s))}decCursor(e){return this._cursor-=e,this._cursor<0?(this._cursor=0,!0):!1}queryProcessor(e,t,r){return{limit:n=>e,operations:n=>this.retrieveQueryDocs(e,n),sort:({order:n,propertyName:o})=>e.sort((c,u)=>n==="asc"?this.deepValue(c,o)>this.deepValue(u,o)?1:-1:this.deepValue(c,o)<this.deepValue(u,o)?1:-1)}[t](r)}retrieveQueryDocs(e,t){return t.reduce((r,s,n)=>{if(s.aggregate){const o=e.filter(c=>this.isQueryMatched(c,s));return n===0?o:r.concat(o)}else return r.filter(o=>this.isQueryMatched(o,s))},e)}deepValue(e,t){return t.split(".").reduce((s,n)=>s[n],e)}isQueryMatched(e,t){const r={"==":(l,f)=>l===f,"!=":(l,f)=>l!==f,"<":(l,f)=>l<f,"<=":(l,f)=>l<=f,">":(l,f)=>l>f,">=":(l,f)=>l>=f,containsAny:(l,f)=>l?.some(ge=>f?.includes(ge)),contains:(l,f)=>l?.includes(f)},{property:s,value:n,operator:o}=t,[c,u]=this.retrieveValuesToCompare(e,s,n);return r[o](c,u)}retrieveValuesToCompare(e,t,r){const s=e[t];if(s&&typeof r=="object"&&!Array.isArray(r)){const c=Object.keys(r)[0];var[n,o]=this.retrieveValuesToCompare(s,c,r?.[c])}return[n||s,o||r]}resolveWithDelay(e){if(this._simulateDelay<=0)return Promise.resolve(e);const t=new Promise(r=>{setTimeout(()=>r(e),this._simulateDelay)});return this._pendingPromises.push(t),t.finally(()=>this._pendingPromises=this._pendingPromises.filter(r=>r===t)),t}}const C=class C{static registerCloudStorage(e,t){C._cloudStorageFactoryMap[e]=t}static createInstance(e){const t=C._cloudStorageFactoryMap[e];if(!t)throw new Error(`You should register the ${e} cloud storage provider prior to use it`);return t()}get className(){return this.__className}static useCloudStorage(e){C._defaultCloudStorage=e}static get defaultCloudStorage(){if(!C._defaultCloudStorage)throw new Error("You should define a default cloud storage provider prior to use it");return C._defaultCloudStorage}};C._cloudStorageFactoryMap={};let P=C;function $(i,e){return P.registerCloudStorage(i,e),t=>{t.prototype.__className=i}}var ne=Object.getOwnPropertyDescriptor,oe=(i,e,t,r)=>{for(var s=r>1?void 0:r?ne(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(s=o(s)||s);return s};a.MockCloudStorage=class extends P{constructor(e=""){super(),this._simulateDelay=0,this._pendingPromises=[],this.mockFileSystem={},this._pathToMockFiles=e}simulateDelay(e){return this._simulateDelay=e,this}resolveWithDelay(e){if(this._simulateDelay<=0)return Promise.resolve(e);const t=new Promise(r=>{setTimeout(()=>r(e),this._simulateDelay)});return this._pendingPromises.push(t),t.finally(()=>this._pendingPromises=this._pendingPromises.filter(r=>r===t)),t}save(e,t){const r=e;this._onProgress&&this._onProgress(0,100),this.mockFileSystem[e]=JSON.stringify(t),this._onProgress&&this._onProgress(100,100);const s=t instanceof File?t.name:r;return this.resolveWithDelay(s)}uploadControl(){return{resume:()=>{},pause:()=>{},cancel:()=>{},onProgress:e=>this._onProgress=e}}getUrl(e){return Promise.resolve(this._pathToMockFiles+e)}delete(e){return delete this.mockFileSystem[e],this.resolveWithDelay()}},a.MockCloudStorage=oe([$("MockCloudStorage",()=>new a.MockCloudStorage)],a.MockCloudStorage);var ae=Object.defineProperty,ce=Object.getOwnPropertyDescriptor,O=(i,e,t,r)=>{for(var s=r>1?void 0:r?ce(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(s=(r?o(e,t,s):o(s))||s);return r&&s&&ae(e,t,s),s},T=(i=>(i[i.stored=0]="stored",i[i.pendingDataSet=1]="pendingDataSet",i[i.deleted=2]="deleted",i))(T||{});a.StoredFile=class extends h{constructor(){super(...arguments),this._onChange=new v}async save({data:e,fileName:t,progress:r,cloudStorageProvider:s}={}){const n=e||this._pendingData;n&&(this._reference&&await this.delete(),this.provider=s||P.defaultCloudStorage,this._originalFileName=t||(n instanceof File?n.name:void 0),this._reference=await this.provider.save(this.id,n,r),this._url=await this.provider.getUrl(this._reference),this._pendingData=void 0,this._onChange.notify({event:0,storedFile:this}))}uploadControl(){return this.provider.uploadControl()}async delete(){if(!this._reference)throw new Error("Cannot delete a not stored file");await this.provider.delete(this._reference),this._reference=void 0,this._url=void 0,this._onChange.notify({event:2,storedFile:this})}set provider(e){this._provider=e,this._cloudStorageProviderName=e.className}get provider(){if(!this._provider)try{this._provider=P.createInstance(this._cloudStorageProviderName)}catch{this._provider=P.defaultCloudStorage}return this._provider}get url(){return this._url}get mimeType(){return this._mimeType}setDataToStore(e){return this._pendingData=e,this._originalFileName=e instanceof File?e.name:void 0,this._mimeType=e instanceof Blob?e.type:void 0,this._onChange.notify({event:1,pendingData:e,storedFile:this}),this}get originalFileName(){return this._originalFileName}onChange(e){return this._onChange.subscribe(e)}},O([w],a.StoredFile.prototype,"_reference",2),O([w],a.StoredFile.prototype,"_url",2),O([w],a.StoredFile.prototype,"_cloudStorageProviderName",2),O([w],a.StoredFile.prototype,"_originalFileName",2),O([w],a.StoredFile.prototype,"_mimeType",2),a.StoredFile=O([N("StoredFile")],a.StoredFile);class A{}const m=class m extends A{constructor(){if(super(),this._onAuthStateChange=new v,!m._authService)throw new Error(m.error.shouldBeRegistered);m._authService.onAuthStateChange(e=>this.authStateChanged(e))}static useAuthService(e){m._authService!=e&&(m._authService=e,this._instance=void 0)}static get instance(){return this._instance||(this._instance=new this)}signUp(e){return m._authService.signUp(e)}login(e){return m._authService.login(e)}logout(){return m._authService.logout()}resetEmailPassword(e){return m._authService.resetEmailPassword(e)}resendVerificationEmail(e,t,r){return m._authService.resendVerificationEmail(e,t,r)}refreshToken(){return m._authService.refreshToken()}onAuthStateChange(e){return this._onAuthStateChange.subscribe(e)}removeAuthStateChange(e){this._onAuthStateChange.unsubscribe(e)}linkAdditionalProvider(e){return m._authService.linkAdditionalProvider(e)}unlinkProvider(e){return m._authService.unlinkProvider(e)}authStateChanged(e){this._onAuthStateChange.notify(e)}};m.error={shouldBeRegistered:"You should register an auth service before using Auth."},m._instance=void 0;let U=m;class ue extends A{constructor(){super(...arguments),this.pendingPromises=[],this._fakeRegisteredUsers={}}signUp(e){const{verificationLink:t,email:r,password:s,authProvider:n}=e,o=new Promise(async(c,u)=>{n==="email"&&(r||u({code:"missingEmail",message:"missingEmail"}),s||u({code:"missingPassword",message:"missingPassword"})),s!=="fail"&&r!=="fail"?(this._loggedUser=this.userCredentials(e),this._fakeRegisteredUsers[this._loggedUser.id]=this._loggedUser,c(this._loggedUser),this.notifyChange?.(this._loggedUser)):(u({code:"userNotFound",message:t||"Test auth error"}),this.notifyChange?.(void 0))});return this.pendingPromises.push(o),o}login(e){const t=Object.values(this._fakeRegisteredUsers).find(r=>r.email===e.email);return e.authProvider==="email"&&!t&&e.email&&(e.email="fail"),this.signUp(e)}onAuthStateChange(e){this.notifyChange=e,this.notifyChange(this._loggedUser)}async logout(){const e=new Promise(t=>{this._loggedUser=void 0,t(),this.notifyChange?.(void 0)});return this.pendingPromises.push(e),e}resetEmailPassword(e){return Object.values(this._fakeRegisteredUsers).find(r=>r.email===e)?Promise.resolve():Promise.reject({code:"userNotFound",message:"Test auth error"})}resendVerificationEmail(e,t,r){return Object.values(this._fakeRegisteredUsers).find(n=>n.email===e)?Promise.resolve():Promise.reject({code:"userNotFound",message:"Test auth error"})}refreshToken(){return Promise.resolve()}linkAdditionalProvider(e){throw new Error("Not implemented.")}unlinkProvider(e){throw new Error("Not implemented.")}async flush(){await Promise.all(this.pendingPromises),this.pendingPromises=[]}fakeRegisteredUser(e){if(this._fakeRegisteredUsers[e.id])throw new Error(`User with id ${e.id} already exists in fake user list`);return this._fakeRegisteredUsers[e.id]=e,this}get fakeRegisteredUsers(){return this._fakeRegisteredUsers}userCredentials(e){const t=Object.values(this._fakeRegisteredUsers).find(r=>r.email===e.email);return t?{...t}:{id:e.authProvider||`testUID${e.email?"-"+e.email:""}`,email:e.email||"testEmail",name:e.authProvider||`testName${e.email?" "+e.email:""}`,phoneNumber:"testPhone",customData:{role:"test"},lastLogin:0,creationDate:0}}}const y=class y{constructor(){}static useCloudFunctionsService(e){this._cloudFunctionsService!=e&&(this._cloudFunctionsService=e)}static get instance(){if(!this._cloudFunctionsService)throw new Error(y.error.shouldBeRegistered);return y._instance||(y._instance=new y)}getRawFunction(e){return y._cloudFunctionsService.retrieveFunction(e)}getFunction(e){const t=y._cloudFunctionsService.callFunction,r=this.getRawFunction(e);return async s=>{const n=await t(r,this.processParam(s));return this.processResult(n)}}processParam(e){if(e!=null)return e instanceof h?e.toObject():Array.isArray(e)?e.map(t=>this.processParam(t)):typeof e=="object"?Object.entries(e).reduce((t,[r,s])=>(t[r]=this.processParam(s),t),{}):e}processResult(e){if(e!=null)return e.__className?h.createInstance(e):Array.isArray(e)?e.map(t=>this.processResult(t)):typeof e=="object"?Object.entries(e).reduce((t,[r,s])=>(t[r]=this.processResult(s),t),{}):e}};y.error={shouldBeRegistered:"You should register a cloud functions service with useCloudFunctionsService static method before using CloudFunctions."};let F=y;class he{constructor(e){this._registeredFunctions=e}retrieveFunction(e){const t=this._registeredFunctions[e];if(!t)throw new Error(`Cloud function ${e} is not registered.`);return t}callFunction(e,t){return e(t)}}class I{}const g=class g extends I{constructor(){super()}static useServerAuthService(e){g._authService!=e&&(g._authService=e,this._instance=void 0)}static get instance(){if(!g._authService)throw new Error(g.error.shouldBeRegistered);return this._instance||(this._instance=new g)}getUser(e){return g._authService.getUser(e)}updateUser(e,t){return g._authService.updateUser(e,t)}setCustomCredentials(e,t){return g._authService.setCustomCredentials(e,t)}deleteUser(e){return g._authService.deleteUser(e)}};g.error={shouldBeRegistered:"You should register a Server Auth service before using the Server Auth."},g._instance=void 0;let k=g;class le extends I{constructor(e){super(),this._userCredentials=e}getUser(e){return this._userCredentials[e]||Promise.resolve(void 0),Promise.resolve(this._userCredentials[e])}setCustomCredentials(e,t){const r=this._userCredentials[e];if(!r)throw new Error(`User ${e} not found in the auth system`);return r.customData={...t},Promise.resolve()}updateUser(e,t){return this._userCredentials[e]={...this._userCredentials,...t,id:e},Promise.resolve(this._userCredentials[e])}deleteUser(e){return delete this._userCredentials[e],Promise.resolve()}get userCredentials(){return this._userCredentials}}function de(i,e){return i?i.replace(/\${\s*(\w*)\s*}/g,function(t,r){return e[r]||""}):""}function fe(i){return i?i.replace(/([-_ ][\w])/g,e=>e.toUpperCase().replace("-","").replace("_","").replace(" ","")):""}function pe(i,e="-"){if(!i)return"";const t=i.slice(1).replace(/( |[A-Z])/g,r=>r===" "?"-":e+r[0].toLowerCase());return i[0].toLocaleLowerCase()+t.replace(/--/g,"-")}function me(i,e){return e.split(".").reduce((t,r)=>t[r],i)}a.Auth=U,a.AuthMock=ue,a.AuthService=A,a.CloudFunctions=F,a.CloudFunctionsMock=he,a.CloudStorage=P,a.DataSource=R,a.EntropicComponent=se,a.JsonDataSource=ie,a.Model=S,a.Observable=v,a.Persistent=h,a.Query=V,a.ServerAuth=k,a.ServerAuthMock=le,a.ServerAuthService=I,a.Store=D,a.StoredFileEvent=T,a.camelCase=fe,a.getDeepValue=me,a.persistent=w,a.persistentParser=_,a.persistentPureReference=K,a.persistentPureReferenceWithCachedProps=X,a.persistentReference=Z,a.persistentReferenceAt=H,a.persistentReferenceWithCachedProps=G,a.registerCloudStorage=$,a.registerLegacyClassName=x,a.registerPersistentClass=N,a.replaceValue=de,a.required=te,a.requiredWithValidator=re,a.searchableArray=ee,a.snakeCase=pe,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});
8
8
  //# sourceMappingURL=entropic-bond.umd.cjs.map