entropic-bond 1.51.13 → 1.52.1

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,P){typeof exports=="object"&&typeof module<"u"?P(exports):typeof define=="function"&&define.amd?define(["exports"],P):(a=typeof globalThis<"u"?globalThis:a||self,P(a["entropic-bond"]={}))})(this,function(a){"use strict";var f;class P{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}}let j;const Q=new Uint8Array(16);function Y(){if(!j&&(j=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!j))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return j(Q)}const p=[];for(let i=0;i<256;++i)p.push((i+256).toString(16).slice(1));function z(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]]}const V={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function J(i,e,t){if(V.randomUUID&&!e&&!i)return V.randomUUID();i=i||{};const r=i.random||(i.rng||Y)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){t=t||0;for(let s=0;s<16;++s)e[t+s]=r[s];return e}return z(r)}var H=Object.defineProperty,Z=Object.getOwnPropertyDescriptor,G=(i,e,t,r)=>{for(var s=r>1?void 0:r?Z(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&&H(e,t,s),s};const $=(f=class{static registerFactory(e,t,r){this._factoryMap[e]={factory:t,annotation:r}}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.keys(this._factoryMap)}static classesExtending(e){return Object.entries(this._factoryMap).filter(([,t])=>new t.factory instanceof e).map(([t])=>t)}static annotations(e){if(e instanceof f?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=J()){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 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[f.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=f.createInstance(t);return r.__documentReference=e.__documentReference,r}if(e.__className)return f.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 f)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];if(Array.isArray(r)){if(e.cachedProps&&!e.searchableArray)throw new Error(`${this.className}.${e.name} is an array but cached array props are only allowed in searchable array references`);return r.map(s=>(e.isPureReference||this.pushDocument(t,f.collectionPath(s,e),s),this.buildRefObject(s,f.collectionPath(s,e),e.cachedProps)))}else return e.isPureReference||this.pushDocument(t,f.collectionPath(r,e),r),this.buildRefObject(r,f.collectionPath(r,e),e.cachedProps)}buildRefObject(e,t,r){const s=r==null?void 0: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=f.createInstance(e);return t.__documentReference=e.__documentReference||{storedInCollection:t.className},t}static createInstance(e){if(typeof e=="string")return new(f.classFactory(e));try{return new(f.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,P){typeof exports=="object"&&typeof module<"u"?P(exports):typeof define=="function"&&define.amd?define(["exports"],P):(a=typeof globalThis<"u"?globalThis:a||self,P(a["entropic-bond"]={}))})(this,function(a){"use strict";var f;class P{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}}let j;const Q=new Uint8Array(16);function Y(){if(!j&&(j=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!j))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return j(Q)}const m=[];for(let i=0;i<256;++i)m.push((i+256).toString(16).slice(1));function z(i,e=0){return m[i[e+0]]+m[i[e+1]]+m[i[e+2]]+m[i[e+3]]+"-"+m[i[e+4]]+m[i[e+5]]+"-"+m[i[e+6]]+m[i[e+7]]+"-"+m[i[e+8]]+m[i[e+9]]+"-"+m[i[e+10]]+m[i[e+11]]+m[i[e+12]]+m[i[e+13]]+m[i[e+14]]+m[i[e+15]]}const V={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function J(i,e,t){if(V.randomUUID&&!e&&!i)return V.randomUUID();i=i||{};const r=i.random||(i.rng||Y)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){t=t||0;for(let s=0;s<16;++s)e[t+s]=r[s];return e}return z(r)}var H=Object.defineProperty,Z=Object.getOwnPropertyDescriptor,G=(i,e,t,r)=>{for(var s=r>1?void 0:r?Z(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&&H(e,t,s),s};const $=(f=class{static registerFactory(e,t,r){this._factoryMap[e]={factory:t,annotation:r}}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.keys(this._factoryMap)}static classesExtending(e){return Object.entries(this._factoryMap).filter(([,t])=>new t.factory instanceof e).map(([t])=>t)}static annotations(e){if(e instanceof f?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=J()){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 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[f.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=f.createInstance(t);return r.__documentReference=e.__documentReference,r}if(e.__className)return f.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 f)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];if(Array.isArray(r)){if(e.cachedProps&&!e.searchableArray)throw new Error(`${this.className}.${e.name} is an array but cached array props are only allowed in searchable array references`);return r.map(s=>(e.isPureReference||this.pushDocument(t,f.collectionPath(s,e),s),this.buildRefObject(s,f.collectionPath(s,e),e.cachedProps)))}else return e.isPureReference||this.pushDocument(t,f.collectionPath(r,e),r),this.buildRefObject(r,f.collectionPath(r,e),e.cachedProps)}buildRefObject(e,t,r){const s=r==null?void 0: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=f.createInstance(e);return t.__documentReference=e.__documentReference||{storedInCollection:t.className},t}static createInstance(e){if(typeof e=="string")return new(f.classFactory(e));try{return new(f.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 f.createInstance(e).getPropInfo(t)}static getSystemRegisteredReferencesWithCachedProps(){return f.registeredClasses().reduce((r,s)=>{const o=f.createInstance(s).getPersistentProperties().filter(u=>u.cachedProps);return o.length>0&&(r[s]=o),r},{})}},f._factoryMap={},f);G([C],$.prototype,"_id",2);let d=$;function C(i,e){return _()(i,e)}function K(i){return function(e,t){return _({storeInCollection:i,isReference:!0})(e,t)}}function X(i,e){return _({isReference:!0})(i,e)}function x(i,e){return function(t,r){return _({isReference:!0,cachedProps:i,storeInCollection:e})(t,r)}}function ee(i,e,t){return _({isReference:!0,isPureReference:!0,storeInCollection:t})(i,e)}function te(i,e){return function(t,r){return _({isReference:!0,isPureReference:!0,cachedProps:i,storeInCollection:e})(t,r)}}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 T(i,e){return t=>{d.registerFactory(i,t,e),t.prototype.__className=i}}function re(i){return e=>{d.registerFactory(i,e)}}function se(i,e){return _({searchableArray:!0})(i,e)}function ie(i,e){return _({validator:t=>t!=null})(i,e)}function ne(i=e=>e!=null){return function(e,t){return _({validator:i})(e,t)}}class oe extends d{constructor(){super(...arguments),this._onChange=new P}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 U=class U{constructor(e,t,r){if(r){if(!(t instanceof d))throw new Error(U.error.persistentNeedForSubCollection);this.collectionName=`${t.className}/${t.id}/${r}`}else this.collectionName=t instanceof d?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=d.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 B(this)}query(e={},t){if(t){const r=t instanceof d?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))}mapToInstance(e){return new Promise((t,r)=>{e().then(s=>t(s.map(n=>d.createInstance(n)))).catch(s=>r(s))})}preprocessQueryObject(e){var r;if(Object.values(e).length===0)return e;const t=((r=e.operations)==null?void 0:r.map(s=>{const n=s.value[0]??s.value;return R.isArrayOperator(s.operator)&&n instanceof d?{property:d.searchableArrayNameFor(s.property),operator:s.operator,value:Array.isArray(s.value)?s.value.map(o=>o.id):n.id,aggregate:s.aggregate}:{property:s.property,operator:s.operator,value:s.value instanceof d?{id:s.value.id}:s.value,aggregate:s.aggregate}}))??[];return{...e,operations:t}}};U.error={persistentNeedForSubCollection:"The document parameter for a sub-collection should be a Persistent instace",invalidQueryOrder:"Cannot add where calls after or calls"};let S=U;class B{constructor(e){this.queryObject={operations:[]},this.model=e}where(e,t,r,s){var n,o,u;if((o=(n=this.queryObject.operations)==null?void 0:n.at(-1))!=null&&o.aggregate&&!s)throw new Error(S.error.invalidQueryOrder);return(u=this.queryObject.operations)==null||u.push({property:e,operator:t,value:r,aggregate:s}),this}whereDeepProp(e,t,r,s){var l,c,h;if((c=(l=this.queryObject.operations)==null?void 0:l.at(-1))!=null&&c.aggregate&&!s)throw new Error(S.error.invalidQueryOrder);const n=e.split(".");let o={},u=n.length>1?o:r;return n.slice(1).forEach((O,A)=>{o[O]=A<n.length-2?{}:r,o=o[O]}),(h=this.queryObject.operations)==null||h.push({property:n[0],operator:t,value:u,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){var r;const t=e instanceof d?e.className:e;return(r=this.queryObject.operations)==null||r.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)}}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 E=b;class R{installCachedPropsUpdaters(e={}){R.onUpdate=e.onUpdate;const t=d.getSystemRegisteredReferencesWithCachedProps(),r={};Object.entries(t).forEach(([n,o])=>{o.forEach(u=>{const l=d.collectionPath(d.createInstance(n),u);r[l]||(r[l]=[]),r[l].push({prop:u,collectionPropOwner:n})})});const s=[];return Object.entries(r).forEach(([n,o])=>{const u=this.subscribeToDocumentChangeListerner(n,l=>R.onDocumentChange(l,o));if(u)s.push(u);else if(e.noThrowOnNonImplementedListener)throw new Error("The method documentChangeListerner has not been implemented in the concrete data source")}),s}subscribeToDocumentChangeListerner(e,t){}static toPropertyPathOperations(e){return e?e.map(t=>{if(R.isArrayOperator(t.operator)&&t.value[0]instanceof d)return{property:d.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 onDocumentChange(e,t){if(e.before)return t.map(async r=>{var u;const s=E.getModel(r.collectionPropOwner);let n=s.find();(u=r.prop.cachedProps)==null||u.forEach(l=>{const c=e.before[l],h=e.after[l];c!==h&&(n=n.orDeepProp(`${r.prop.name}.${l}`,"==",c))});const o=await n.get();return Promise.all([o.map(async l=>{var c;(c=r.prop.cachedProps)==null||c.forEach(async h=>{var q;const O=e.before[h],A=e.after[h];O!==A&&(l[`_${r.prop.name}`][`_${h}`]=A,await s.save(l),(q=this.onUpdate)==null||q.call(this,l,r.prop))})})])})}}class ae extends R{constructor(e){super(),this._jsonRawData={},this._lastMatchingDocs=[],this._lastLimit=0,this._cursor=0,this._simulateDelay=0,this._pendingPromises=[],this._listener={},e&&(this._jsonRawData=e)}setDataStore(e){return this._jsonRawData=e,this}simulateDelay(e){return this._simulateDelay=e,this}findById(e,t){var r,s;if((r=this._simulateError)!=null&&r.findById)throw new Error(this._simulateError.findById);return this.resolveWithDelay((s=this._jsonRawData[t])==null?void 0:s[e])}save(e){var t;if((t=this._simulateError)!=null&&t.store)throw new Error(this._simulateError.store);return Object.entries(e).forEach(([r,s])=>{this._jsonRawData[r]||(this._jsonRawData[r]={}),s==null||s.forEach(n=>{const o=this._jsonRawData[r][n.id];this._jsonRawData[r][n.id]=n,o&&this.notifyChange(r,d.createInstance(n),d.createInstance(o))})}),this.resolveWithDelay()}find(e,t){var s;if((s=this._simulateError)!=null&&s.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((n,[o,u])=>this.queryProcessor(n,o,u),Object.values(r)),this.resolveWithDelay(this._lastMatchingDocs.slice(0,e.limit))):this.resolveWithDelay(r)}delete(e,t){var r;if((r=this._simulateError)!=null&&r.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)}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)}subscribeToDocumentChangeListerner(e,t){return delete this._listener[e],this._listener[e]=t,{uninstall:()=>delete this._listener[e],nativeHandler:t,collectionPath:e}}notifyChange(e,t,r){const s=this._listener[e];s&&s({before:r,after:t,collectionPath:e})}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((u,l)=>n==="asc"?this.deepValue(u,o)>this.deepValue(l,o)?1:-1:this.deepValue(u,o)<this.deepValue(l,o)?1:-1)}[t](r)}retrieveQueryDocs(e,t){return t.reduce((r,s,n)=>{if(s.aggregate){const o=e.filter(u=>this.isQueryMatched(u,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={"==":(c,h)=>c===h,"!=":(c,h)=>c!==h,"<":(c,h)=>c<h,"<=":(c,h)=>c<=h,">":(c,h)=>c>h,">=":(c,h)=>c>=h,containsAny:(c,h)=>c==null?void 0:c.some(O=>h==null?void 0:h.includes(O)),contains:(c,h)=>c==null?void 0:c.includes(h)},{property:s,value:n,operator:o}=t,[u,l]=this.retrieveValuesToCompare(e,s,n);return r[o](u,l)}retrieveValuesToCompare(e,t,r){const s=e[t];if(s&&typeof r=="object"&&!Array.isArray(r)){const u=Object.keys(r)[0];var[n,o]=this.retrieveValuesToCompare(s,u,r==null?void 0:r[u])}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 w=class w{static registerCloudStorage(e,t){w._cloudStorageFactoryMap[e]=t}static createInstance(e){const t=w._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){w._defaultCloudStorage=e}static get defaultCloudStorage(){if(!w._defaultCloudStorage)throw new Error("You should define a default cloud storage provider prior to use it");return w._defaultCloudStorage}};w._cloudStorageFactoryMap={};let v=w;function W(i,e){return v.registerCloudStorage(i,e),t=>{t.prototype.__className=i}}var ce=Object.defineProperty,ue=Object.getOwnPropertyDescriptor,he=(i,e,t,r)=>{for(var s=r>1?void 0:r?ue(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&&ce(e,t,s),s};a.MockCloudStorage=class extends v{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=he([W("MockCloudStorage",()=>new a.MockCloudStorage)],a.MockCloudStorage);var le=Object.defineProperty,de=Object.getOwnPropertyDescriptor,D=(i,e,t,r)=>{for(var s=r>1?void 0:r?de(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&&le(e,t,s),s},L=(i=>(i[i.stored=0]="stored",i[i.pendingDataSet=1]="pendingDataSet",i[i.deleted=2]="deleted",i))(L||{});a.StoredFile=class extends d{constructor(){super(...arguments),this._onChange=new P}async save({data:e,fileName:t,progress:r,cloudStorageProvider:s}={}){const n=e||this._pendingData;n&&(this._reference&&await this.delete(),this.provider=s||v.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=v.createInstance(this._cloudStorageProviderName)}catch{this._provider=v.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([C],a.StoredFile.prototype,"_reference",2),D([C],a.StoredFile.prototype,"_url",2),D([C],a.StoredFile.prototype,"_cloudStorageProviderName",2),D([C],a.StoredFile.prototype,"_originalFileName",2),D([C],a.StoredFile.prototype,"_mimeType",2),a.StoredFile=D([T("StoredFile")],a.StoredFile);class F{}const m=class m extends F{constructor(){if(super(),this._onAuthStateChange=new P,!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 I=m;class fe extends F{constructor(){super(...arguments),this.pendingPromises=[],this._fakeRegisteredUsers={}}signUp(e){const{verificationLink:t,email:r,password:s,authProvider:n}=e,o=new Promise(async(u,l)=>{var c,h;n==="email"&&(r||l({code:"missingEmail",message:"missingEmail"}),s||l({code:"missingPassword",message:"missingPassword"})),s!=="fail"&&r!=="fail"?(this._loggedUser=this.userCredentials(e),this._fakeRegisteredUsers[this._loggedUser.id]=this._loggedUser,u(this._loggedUser),(c=this.notifyChange)==null||c.call(this,this._loggedUser)):(l({code:"userNotFound",message:t||"Test auth error"}),(h=this.notifyChange)==null||h.call(this,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=>{var r;this._loggedUser=void 0,t(),(r=this.notifyChange)==null||r.call(this,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 d?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?d.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 M=y;class pe{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 k{}const g=class g extends k{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 N=g;class me extends k{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 ge(i,e){return i?i.replace(/\${\s*(\w*)\s*}/g,function(t,r){return e[r]||""}):""}function _e(i){return i?i.replace(/([-_ ][\w])/g,e=>e.toUpperCase().replace("-","").replace("_","").replace(" ","")):""}function ye(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 Pe(i,e){return e.split(".").reduce((t,r)=>t[r],i)}a.Auth=I,a.AuthMock=fe,a.AuthService=F,a.CloudFunctions=M,a.CloudFunctionsMock=pe,a.CloudStorage=v,a.DataSource=R,a.EntropicComponent=oe,a.JsonDataSource=ae,a.Model=S,a.Observable=P,a.Persistent=d,a.Query=B,a.ServerAuth=N,a.ServerAuthMock=me,a.ServerAuthService=k,a.Store=E,a.StoredFileEvent=L,a.camelCase=_e,a.getDeepValue=Pe,a.persistent=C,a.persistentParser=_,a.persistentPureReference=ee,a.persistentPureReferenceWithCachedProps=te,a.persistentReference=X,a.persistentReferenceAt=K,a.persistentReferenceWithCachedProps=x,a.registerCloudStorage=W,a.registerLegacyClassName=re,a.registerPersistentClass=T,a.replaceValue=ge,a.required=ie,a.requiredWithValidator=ne,a.searchableArray=se,a.snakeCase=ye,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});
7
+ `)}}static propInfo(e,t){return f.createInstance(e).getPropInfo(t)}static getSystemRegisteredReferencesWithCachedProps(){return f.registeredClasses().reduce((r,s)=>{const o=f.createInstance(s).getPersistentProperties().filter(c=>c.cachedProps);return o.length>0&&(r[s]=o),r},{})}},f._factoryMap={},f);G([C],$.prototype,"_id",2);let l=$;function C(i,e){return _()(i,e)}function K(i){return function(e,t){return _({storeInCollection:i,isReference:!0})(e,t)}}function X(i,e){return _({isReference:!0})(i,e)}function x(i,e){return function(t,r){return _({isReference:!0,cachedProps:i,storeInCollection:e})(t,r)}}function ee(i,e,t){return function(r,s){const n={isReference:!0,cachedProps:e,storeInCollection:t,typeName:i instanceof l?i.className:new i().className};return _(n)(r,s)}}function te(i,e,t){return _({isReference:!0,isPureReference:!0,storeInCollection:t})(i,e)}function re(i,e){return function(t,r){return _({isReference:!0,isPureReference:!0,cachedProps:i,storeInCollection:e})(t,r)}}function se(i,e,t){return function(r,s){return _({isReference:!0,isPureReference:!0,cachedProps:e,storeInCollection:t,typeName:i instanceof l?i.className:new i().className})(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 T(i,e){return t=>{l.registerFactory(i,t,e),t.prototype.__className=i}}function ie(i){return e=>{l.registerFactory(i,e)}}function ne(i,e){return _({searchableArray:!0})(i,e)}function oe(i,e){return _({validator:t=>t!=null})(i,e)}function ae(i=e=>e!=null){return function(e,t){return _({validator:i})(e,t)}}class ce extends l{constructor(){super(...arguments),this._onChange=new P}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 U=class U{constructor(e,t,r){if(r){if(!(t instanceof l))throw new Error(U.error.persistentNeedForSubCollection);this.collectionName=`${t.className}/${t.id}/${r}`}else this.collectionName=t instanceof l?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=l.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 W(this)}query(e={},t){if(t){const r=t instanceof l?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))}mapToInstance(e){return new Promise((t,r)=>{e().then(s=>t(s.map(n=>l.createInstance(n)))).catch(s=>r(s))})}preprocessQueryObject(e){var r;if(Object.values(e).length===0)return e;const t=((r=e.operations)==null?void 0:r.map(s=>{const n=s.value[0]??s.value;return R.isArrayOperator(s.operator)&&n instanceof l?{property:l.searchableArrayNameFor(s.property),operator:s.operator,value:Array.isArray(s.value)?s.value.map(o=>o.id):n.id,aggregate:s.aggregate}:{property:s.property,operator:s.operator,value:s.value instanceof l?{id:s.value.id}:s.value,aggregate:s.aggregate}}))??[];return{...e,operations:t}}};U.error={persistentNeedForSubCollection:"The document parameter for a sub-collection should be a Persistent instace",invalidQueryOrder:"Cannot add where calls after or calls"};let S=U;class W{constructor(e){this.queryObject={operations:[]},this.model=e}where(e,t,r,s){var n,o,c;if((o=(n=this.queryObject.operations)==null?void 0:n.at(-1))!=null&&o.aggregate&&!s)throw new Error(S.error.invalidQueryOrder);return(c=this.queryObject.operations)==null||c.push({property:e,operator:t,value:r,aggregate:s}),this}whereDeepProp(e,t,r,s){var d,u,h;if((u=(d=this.queryObject.operations)==null?void 0:d.at(-1))!=null&&u.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((O,A)=>{o[O]=A<n.length-2?{}:r,o=o[O]}),(h=this.queryObject.operations)==null||h.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){var r;const t=e instanceof l?e.className:e;return(r=this.queryObject.operations)==null||r.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)}}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 E=b;class R{installCachedPropsUpdaters(e={}){R.onUpdate=e.onUpdate;const t=l.getSystemRegisteredReferencesWithCachedProps(),r={};Object.entries(t).forEach(([n,o])=>{o.forEach(c=>{if(!c.typeName)return;const d=l.collectionPath(l.createInstance(c.typeName),c);r[d]||(r[d]=[]),r[d].push({prop:c,collectionPropOwner:n})})});const s=[];return Object.entries(r).forEach(([n,o])=>{const c=this.subscribeToDocumentChangeListerner(n,d=>R.onDocumentChange(d,o));if(c)s.push(c);else if(e.noThrowOnNonImplementedListener)throw new Error("The method documentChangeListerner has not been implemented in the concrete data source")}),s}subscribeToDocumentChangeListerner(e,t){}static toPropertyPathOperations(e){return e?e.map(t=>{if(R.isArrayOperator(t.operator)&&t.value[0]instanceof l)return{property:l.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 onDocumentChange(e,t){if(e.before)return t.map(async r=>{var c;const s=E.getModel(r.collectionPropOwner);let n=s.find();(c=r.prop.cachedProps)==null||c.forEach(d=>{const u=e.before[d],h=e.after[d];u!==h&&(n=n.orDeepProp(`${r.prop.name}.${d}`,"==",u))});const o=await n.get();return Promise.all([o.map(async d=>{var u;(u=r.prop.cachedProps)==null||u.forEach(async h=>{var q;const O=e.before[h],A=e.after[h];O!==A&&(d[`_${r.prop.name}`][`_${h}`]=A,await s.save(d),(q=this.onUpdate)==null||q.call(this,d,r.prop))})})])})}}class ue extends R{constructor(e){super(),this._jsonRawData={},this._lastMatchingDocs=[],this._lastLimit=0,this._cursor=0,this._simulateDelay=0,this._pendingPromises=[],this._listener={},e&&(this._jsonRawData=e)}setDataStore(e){return this._jsonRawData=e,this}simulateDelay(e){return this._simulateDelay=e,this}findById(e,t){var r,s;if((r=this._simulateError)!=null&&r.findById)throw new Error(this._simulateError.findById);return this.resolveWithDelay((s=this._jsonRawData[t])==null?void 0:s[e])}save(e){var t;if((t=this._simulateError)!=null&&t.store)throw new Error(this._simulateError.store);return Object.entries(e).forEach(([r,s])=>{this._jsonRawData[r]||(this._jsonRawData[r]={}),s==null||s.forEach(n=>{const o=this._jsonRawData[r][n.id];this._jsonRawData[r][n.id]=n,o&&this.notifyChange(r,l.createInstance(n),l.createInstance(o))})}),this.resolveWithDelay()}find(e,t){var s;if((s=this._simulateError)!=null&&s.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((n,[o,c])=>this.queryProcessor(n,o,c),Object.values(r)),this.resolveWithDelay(this._lastMatchingDocs.slice(0,e.limit))):this.resolveWithDelay(r)}delete(e,t){var r;if((r=this._simulateError)!=null&&r.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)}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)}subscribeToDocumentChangeListerner(e,t){return delete this._listener[e],this._listener[e]=t,{uninstall:()=>delete this._listener[e],nativeHandler:t,collectionPath:e}}notifyChange(e,t,r){const s=this._listener[e];s&&s({before:r,after:t,collectionPath:e})}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,d)=>n==="asc"?this.deepValue(c,o)>this.deepValue(d,o)?1:-1:this.deepValue(c,o)<this.deepValue(d,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={"==":(u,h)=>u===h,"!=":(u,h)=>u!==h,"<":(u,h)=>u<h,"<=":(u,h)=>u<=h,">":(u,h)=>u>h,">=":(u,h)=>u>=h,containsAny:(u,h)=>u==null?void 0:u.some(O=>h==null?void 0:h.includes(O)),contains:(u,h)=>u==null?void 0:u.includes(h)},{property:s,value:n,operator:o}=t,[c,d]=this.retrieveValuesToCompare(e,s,n);return r[o](c,d)}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==null?void 0: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 w=class w{static registerCloudStorage(e,t){w._cloudStorageFactoryMap[e]=t}static createInstance(e){const t=w._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){w._defaultCloudStorage=e}static get defaultCloudStorage(){if(!w._defaultCloudStorage)throw new Error("You should define a default cloud storage provider prior to use it");return w._defaultCloudStorage}};w._cloudStorageFactoryMap={};let v=w;function B(i,e){return v.registerCloudStorage(i,e),t=>{t.prototype.__className=i}}var he=Object.defineProperty,le=Object.getOwnPropertyDescriptor,de=(i,e,t,r)=>{for(var s=r>1?void 0:r?le(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&&he(e,t,s),s};a.MockCloudStorage=class extends v{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=de([B("MockCloudStorage",()=>new a.MockCloudStorage)],a.MockCloudStorage);var fe=Object.defineProperty,me=Object.getOwnPropertyDescriptor,D=(i,e,t,r)=>{for(var s=r>1?void 0:r?me(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&&fe(e,t,s),s},L=(i=>(i[i.stored=0]="stored",i[i.pendingDataSet=1]="pendingDataSet",i[i.deleted=2]="deleted",i))(L||{});a.StoredFile=class extends l{constructor(){super(...arguments),this._onChange=new P}async save({data:e,fileName:t,progress:r,cloudStorageProvider:s}={}){const n=e||this._pendingData;n&&(this._reference&&await this.delete(),this.provider=s||v.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=v.createInstance(this._cloudStorageProviderName)}catch{this._provider=v.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([C],a.StoredFile.prototype,"_reference",2),D([C],a.StoredFile.prototype,"_url",2),D([C],a.StoredFile.prototype,"_cloudStorageProviderName",2),D([C],a.StoredFile.prototype,"_originalFileName",2),D([C],a.StoredFile.prototype,"_mimeType",2),a.StoredFile=D([T("StoredFile")],a.StoredFile);class F{}const p=class p extends F{constructor(){if(super(),this._onAuthStateChange=new P,!p._authService)throw new Error(p.error.shouldBeRegistered);p._authService.onAuthStateChange(e=>this.authStateChanged(e))}static useAuthService(e){p._authService!=e&&(p._authService=e,this._instance=void 0)}static get instance(){return this._instance||(this._instance=new this)}signUp(e){return p._authService.signUp(e)}login(e){return p._authService.login(e)}logout(){return p._authService.logout()}resetEmailPassword(e){return p._authService.resetEmailPassword(e)}resendVerificationEmail(e,t,r){return p._authService.resendVerificationEmail(e,t,r)}refreshToken(){return p._authService.refreshToken()}onAuthStateChange(e){return this._onAuthStateChange.subscribe(e)}removeAuthStateChange(e){this._onAuthStateChange.unsubscribe(e)}linkAdditionalProvider(e){return p._authService.linkAdditionalProvider(e)}unlinkProvider(e){return p._authService.unlinkProvider(e)}authStateChanged(e){this._onAuthStateChange.notify(e)}};p.error={shouldBeRegistered:"You should register an auth service before using Auth."},p._instance=void 0;let N=p;class pe extends F{constructor(){super(...arguments),this.pendingPromises=[],this._fakeRegisteredUsers={}}signUp(e){const{verificationLink:t,email:r,password:s,authProvider:n}=e,o=new Promise(async(c,d)=>{var u,h;n==="email"&&(r||d({code:"missingEmail",message:"missingEmail"}),s||d({code:"missingPassword",message:"missingPassword"})),s!=="fail"&&r!=="fail"?(this._loggedUser=this.userCredentials(e),this._fakeRegisteredUsers[this._loggedUser.id]=this._loggedUser,c(this._loggedUser),(u=this.notifyChange)==null||u.call(this,this._loggedUser)):(d({code:"userNotFound",message:t||"Test auth error"}),(h=this.notifyChange)==null||h.call(this,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=>{var r;this._loggedUser=void 0,t(),(r=this.notifyChange)==null||r.call(this,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 l?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?l.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 I=y;class ge{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 M{}const g=class g extends M{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 _e extends M{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 ye(i,e){return i?i.replace(/\${\s*(\w*)\s*}/g,function(t,r){return e[r]||""}):""}function Pe(i){return i?i.replace(/([-_ ][\w])/g,e=>e.toUpperCase().replace("-","").replace("_","").replace(" ","")):""}function ve(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 be(i,e){return e.split(".").reduce((t,r)=>t[r],i)}a.Auth=N,a.AuthMock=pe,a.AuthService=F,a.CloudFunctions=I,a.CloudFunctionsMock=ge,a.CloudStorage=v,a.DataSource=R,a.EntropicComponent=ce,a.JsonDataSource=ue,a.Model=S,a.Observable=P,a.Persistent=l,a.Query=W,a.ServerAuth=k,a.ServerAuthMock=_e,a.ServerAuthService=M,a.Store=E,a.StoredFileEvent=L,a.camelCase=Pe,a.getDeepValue=be,a.persistent=C,a.persistentParser=_,a.persistentPureReference=te,a.persistentPureReferenceWithCachedProps=re,a.persistentPureReferenceWithUpdatableCachedProps=se,a.persistentReference=X,a.persistentReferenceAt=K,a.persistentReferenceWithCachedProps=x,a.persistentReferenceWithUpdatableCachedProps=ee,a.registerCloudStorage=B,a.registerLegacyClassName=ie,a.registerPersistentClass=T,a.replaceValue=ye,a.required=oe,a.requiredWithValidator=ae,a.searchableArray=ne,a.snakeCase=ve,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})});
8
8
  //# sourceMappingURL=entropic-bond.umd.cjs.map