entropic-bond 1.59.2 → 1.59.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/entropic-bond.js +110 -115
- package/lib/entropic-bond.js.map +1 -1
- package/lib/entropic-bond.umd.cjs +2 -2
- package/lib/entropic-bond.umd.cjs.map +1 -1
- package/package.json +8 -8
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`entropic-bond`]={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=class{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}},n=[];for(let e=0;e<256;++e)
|
|
2
|
-
`);throw Error(`${e}\n-----> Class name not found in object:\n{\n\t ${n} \n}\n`)}}static propInfo(t,n){return e.createInstance(t).getPropInfo(n)}static propType(t){if(t.typeName)return Array.isArray(t.typeName)?`undefined[]`:t.typeName??`undefined`;let n=e.createInstance(t.ownerClassName())[t.name];if(Array.isArray(n)){if(n.length===0)return`undefined[]`;let t=n[0];return t instanceof e?t.className+`[]`:typeof t+`[]`}else if(n instanceof e)return n.className;else return typeof n}static getSystemRegisteredReferencesWithCachedProps(){return e.registeredClasses().reduce((t,n)=>{let r=e.createInstance(n).getPersistentProperties().filter(e=>e.cachedProps);return r.length>0&&(t[n]=r),t},{})}static{this._factoryMap={}}};u([f],d.prototype,`_id`,void 0);function f(e,t){return v()(e,t)}function p(e){return function(t,n){return v({storeInCollection:e,isReference:!0})(t,n)}}function m(e,t){return v({isReference:!0})(e,t)}function h(e,t,n,r){return function(i,a){return v({isReference:!0,storeInCollection:n,typeName:t,cachedProps:e,ownerCollection:r??i.className})(i,a)}}function g(e,t,n){return v({isReference:!0,isPureReference:!0,storeInCollection:n})(e,t)}function _(e,t,n,r){return function(i,a){return v({isReference:!0,isPureReference:!0,storeInCollection:n,ownerCollection:r,typeName:t,cachedProps:e})(i,a)}}function v(e){return function(t,n){Object.getOwnPropertyDescriptor(t,`_persistentProperties`)||(t._persistentProperties?t._persistentProperties=[...t._persistentProperties]:t._persistentProperties=[]);let r=t._persistentProperties.find(e=>e.name===n);r?Object.assign(r,e):t._persistentProperties.push({name:n,ownerClassName:()=>t.className,...e})}}function y(e,t){return n=>{d.registerFactory(e,n,t),n.prototype.__className=e}}function b(e){return t=>{d.registerFactory(e,t,void 0,!0)}}function x(e,t){return v({searchableArray:!0})(e,t)}function S(e,t){return v({validator:e=>e!=null})(e,t)}function C(e=e=>e!=null){return function(t,n){return v({validator:e})(t,n)}}function w(e){let t;return t=typeof e==`function`?new e().className:e,function(e,n){return v({typeName:t})(e,n)}}var T=class extends d{constructor(...e){super(...e),this._onChange=new t}onChange(e){return this._onChange.subscribe(e)}removeOnChange(e){this._onChange.unsubscribe(e)}changeProp(e,t){let n=`_`+String(e);return this[n]===t?!1:(this[n]=t,this._onChange.notify({[e]:t}),!0)}notify(e){this._onChange.notify(e)}pushAndNotify(e,t,n){let r=`_`+String(e);if(!(n&&this[r].find(e=>!n(e,t))))return this[r].push(t),this.notify({[e]:this[e]}),t}removeAndNotify(e,t,n){let r=`_`+String(e),i=this[r].length;if(this[r]=this[r].filter(e=>!n(e,t)),i!==this[r].length)return this.notify({[e]:this[e]}),t}},E=class e{static{this.error={persistentNeedForSubCollection:`The document parameter for a sub-collection should be a Persistent instace`,invalidQueryOrder:`Cannot add where calls after or calls`}}constructor(t,n,r){if(r){if(!(n instanceof d))throw Error(e.error.persistentNeedForSubCollection);this.collectionName=`${n.className}/${n.id}/${r}`}else this.collectionName=n instanceof d?n.className:n;this._stream=t}findById(e,t){return new Promise((n,r)=>{this._stream.findById(e,this.collectionName).then(e=>{e?(t?t.fromObject(e):t=d.createInstance(e),n(t)):n(void 0)}).catch(e=>r(e))})}save(e){let t=e.toObject();return this.collectionName!==t.__className&&(t.__rootCollections[this.collectionName]=t.__rootCollections[t.__className],delete t.__rootCollections[t.__className]),new Promise((e,n)=>{this._stream.save(t.__rootCollections).then(()=>e()).catch(e=>n(e))})}delete(e){return new Promise((t,n)=>{this._stream.delete(e,this.collectionName).then(()=>t()).catch(e=>n(e))})}find(){return new D(this)}query(e={},t){if(t){let n=t instanceof d?t.className:t;e.operations||=[],e.operations.push({property:`__className`,operator:`==`,value:n})}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,e=>t(A.toPersistentDocumentChange(e)))}onCollectionChange(e,t){return this._stream.onCollectionChange(this.preprocessQueryObject(e.getQueryObject()),this.collectionName,e=>t(e.map(e=>A.toPersistentDocumentChange(e))))}onCollectionTemplateChange(e,t){return this._stream.onDocumentTemplateChange(e,e=>t(A.toPersistentDocumentChange(e)))}mapToInstance(e){return new Promise((t,n)=>{e().then(e=>t(e.map(e=>d.createInstance(e)))).catch(e=>n(e))})}preprocessQueryObject(e){if(Object.values(e).length===0)return e;let t=e.operations?.map(e=>{let t=e.value[0]??e.value;return A.isArrayOperator(e.operator)&&t instanceof d?{property:d.searchableArrayNameFor(e.property),operator:e.operator,value:Array.isArray(e.value)?e.value.map(e=>e.id):t.id,aggregate:e.aggregate}:{property:e.property,operator:e.operator,value:e.value instanceof d?{id:e.value.id}:e.value,aggregate:e.aggregate}})??[];return{...e,operations:t}}},D=class{constructor(e){this.queryObject={operations:[]},this.model=e}where(e,t,n,r){if(this.queryObject.operations?.at(-1)?.aggregate&&!r)throw Error(E.error.invalidQueryOrder);return this.queryObject.operations?.push({property:e,operator:t,value:n,aggregate:r}),this}whereDeepProp(e,t,n,r){if(this.queryObject.operations?.at(-1)?.aggregate&&!r)throw Error(E.error.invalidQueryOrder);let i=e.split(`.`),a={},o=i.length>1?a:n;return i.slice(1).forEach((e,t)=>{a[e]=t<i.length-2?{}:n,a=a[e]}),this.queryObject.operations?.push({property:i[0],operator:t,value:o,aggregate:r}),this}and(e,t,n){return this.where(e,t,n)}andDeepProp(e,t,n){return this.whereDeepProp(e,t,n)}or(e,t,n){return this.where(e,t,n,!0)}orDeepProp(e,t,n){return this.whereDeepProp(e,t,n,!0)}instanceOf(e){let t=e instanceof d?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}getQueryModel(){return this.model}},O=class e{constructor(){}static{this.error={shouldBeRegistered:`You should register a data source before using the data Store.`}}static useDataSource(e){this._dataSource=e}static get dataSource(){return e._dataSource}static getModel(t){if(!e._dataSource)throw Error(this.error.shouldBeRegistered);return new E(e._dataSource,t)}static getModelForSubCollection(t,n){if(!e._dataSource)throw Error(this.error.shouldBeRegistered);return new E(e._dataSource,t,n)}static async populate(e){if(!e)return;let t=async e=>{let t=e;if(!t.__documentReference)return e;let n=await this.getModel(t.__documentReference.storedInCollection).findById(t.id,e);return n&&(n.__documentReference=void 0),n};return Array.isArray(e)?(await Promise.all(e.map(e=>t(e)))).filter(e=>e):t(e)}static isPopulated(e){return Array.isArray(e)?e.reduce((e,t)=>e&&t.__documentReference===void 0,!0):e.__documentReference===void 0}},k=class e{constructor(e){this._resolveCollectionPaths=()=>{throw Error(`The method collectionsMatchingTemplate has not been implemented in the concrete data source`)},this._disabledChangeListeners=new Set,this._collectionsToWatch={},e&&(this._beforeUpdateDocument=e.beforeUpdateDocument,this._afterUpdateDocument=e.afterUpdateDocument,this._afterDocumentChange=e.afterDocumentChange,this._beforeDocumentChange=e.beforeDocumentChange,this._beforeQueryOwnerCollection=e.beforeQueryOwnerCollection),this.installUpdaters()}installUpdaters(){let e=d.getSystemRegisteredReferencesWithCachedProps();this._collectionsToWatch={},Object.entries(e).forEach(([e,t])=>{t.forEach(t=>{t.typeName&&(Array.isArray(t.typeName)?t.typeName:[t?.typeName??e]).map(e=>d.collectionPath(d.createInstance(e),t)).forEach(e=>{this._collectionsToWatch[e]||(this._collectionsToWatch[e]=[]),this._collectionsToWatch[e].find(e=>e.name===t.name&&e.ownerClassName()===t.ownerClassName())||this._collectionsToWatch[e].push(t)})})})}set beforeDocumentChange(e){this._beforeDocumentChange=e}set afterDocumentChange(e){this._afterDocumentChange=e}set beforeUpdateDocument(e){this._beforeUpdateDocument=e}set afterUpdateDocument(e){this._afterUpdateDocument=e}set beforeQueryOwnerCollection(e){this._beforeQueryOwnerCollection=e}set resolveCollectionPaths(e){this._resolveCollectionPaths=e}get collectionsToWatch(){return this._collectionsToWatch}updateProps(e,t){let n=this._collectionsToWatch[e];return n?this.onDocumentChange(t,n):Promise.resolve()}async onDocumentChange(t,n){let r=A.toPersistentDocumentChange(t);this._beforeDocumentChange?.(r,n);let i={};t.type!==`update`||!r.before||r.after?.id&&this._disabledChangeListeners.has(r.after?.id)||(await Promise.all(n.map(async t=>{let n=e.ownerCollectionPath(d.createInstance(t.ownerClassName()),t,r.params),a=await this._resolveCollectionPaths(n);await Promise.all(a.map(async e=>{let n=O.getModel(e),a=n.find(),o=!1;t.cachedProps?.forEach(e=>{r.before[e]!==r.after[e]&&(o=!0)}),o&&(a=t.searchableArray?a.where(t.name,`contains`,r.before):a.where(t.name,`==`,r.before)),a=this._beforeQueryOwnerCollection?.(a)??a;let s=await a.get();return i[e]={totalDocumentsToUpdate:s.length,updatedDocuments:[],documentsToUpdate:s.map(e=>e.name??e.id)},Promise.all([s.map(async a=>{let o=!1;if(t.cachedProps?.forEach(e=>{r.before[e]!==r.after[e]&&(o=!0)}),o){if(t.searchableArray){let e=a[t.name].findIndex(e=>e.id===r.before.id);a[t.name][e]=r.after}else a[`_${t.name}`]=r.after;this._beforeUpdateDocument?.(a,t,r.after),this.disableChangeListener(a),await n.save(a),this.enableChangeListener(a),i[e]?.updatedDocuments.push(a.id),this._afterUpdateDocument?.(a,t,r.after)}else return Promise.resolve()})])}))})),this._afterDocumentChange?.(i,n))}disableChangeListener(e){this._disabledChangeListeners.add(e.id)}enableChangeListener(e){this._disabledChangeListeners.delete(e.id)}static ownerCollectionPath(e,t,n){let r;return r=typeof t.ownerCollection==`function`?t.ownerCollection(e,t,n):t.ownerCollection??e.className,r}},A=class e{constructor(){this._cachedPropsUpdater=void 0}installCachedPropsUpdater(e){return this._cachedPropsUpdater=new k(e),this._cachedPropsUpdater.resolveCollectionPaths=this.resolveCollectionPaths.bind(this),this._cachedPropsUpdater}get cachedPropsUpdater(){return this._cachedPropsUpdater}static toPropertyPathOperations(t){return t?t.map(t=>{if(e.isArrayOperator(t.operator)&&t.value[0]instanceof d)return{property:d.searchableArrayNameFor(t.property),operator:t.operator,value:t.value.map(e=>e.id),aggregate:t.aggregate};let[n,r]=this.toPropertyPathValue(t.value);return{property:`${String(t.property)}${n?`.`+n:``}`,operator:t.operator,value:r,aggregate:t.aggregate}}):[]}static isArrayOperator(e){return e===`containsAny`||e===`contains`}static toPersistentDocumentChange(e){return{...e,before:e.before&&d.createInstance(e.before),after:e.after&&d.createInstance(e.after)}}static toPropertyPathValue(e){if(typeof e==`object`&&!Array.isArray(e)){let t=Object.keys(e)[0],[n,r]=this.toPropertyPathValue(e[t]);return[`${t}${n?`.`+n:``}`,r]}else return[void 0,e]}static isStringMatchingTemplate(e,t){let n=e.split(`/`),r=t.split(`/`);if(r.length>n.length)return!1;for(let e=0;e<r.length;e++){let t=n[e],i=r[e];if(!(t.startsWith(`{`)&&t.endsWith(`}`)||t.startsWith("${")&&t.endsWith(`}`))&&t!==i)return!1}for(let e=r.length;e<n.length;e++){let t=n[e];if(!(t.startsWith(`{`)&&t.endsWith(`}`)||t.startsWith("${")&&t.endsWith(`}`)))return!1}return!0}static extractTemplateParams(e,t){let n=t.split(`/`),r=e.split(`/`),i={};if(r.length>n.length)return i;for(let e=0;e<r.length;e++){let t=n[e],a=r[e];if(t.startsWith(`{`)&&t.endsWith(`}`))i[t.slice(1,-1)]=a;else if(t.startsWith("${")&&t.endsWith(`}`))i[t.slice(2,-1)]=a;else if(t!==a)return{}}for(let e=r.length;e<n.length;e++){let t=n[e];if(!(t.startsWith(`{`)&&t.endsWith(`}`)||t.startsWith("${")&&t.endsWith(`}`)))return{}}return i}},j=class extends A{constructor(e){super(),this._jsonRawData={},this._lastMatchingDocs=[],this._lastLimit=0,this._cursor=0,this._simulateDelay=0,this._pendingPromises=[],this._documentListeners={},this._collectionListeners={},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 Error(this._simulateError.findById);return this.resolveWithDelay(this._jsonRawData[t]?.[e])}save(e){if(this._simulateError?.store)throw Error(this._simulateError.store);return Object.entries(e).forEach(([e,t])=>{this._jsonRawData[e]||(this._jsonRawData[e]={}),t?.forEach(t=>{let n=this._jsonRawData[e][t.id];this._jsonRawData[e][t.id]=t,this.notifyChange(e,t,n)})}),this.resolveWithDelay()}find(e,t){if(this._simulateError?.find)throw Error(this._simulateError.find);let n=Object.values(this._jsonRawData[t]||{});return e?(this._lastLimit=e.limit||0,this._cursor=0,this._lastMatchingDocs=Object.entries(e).reduce((e,[t,n])=>this.queryProcessor(e,t,n),Object.values(n)),this.resolveWithDelay(this._lastMatchingDocs.slice(0,e.limit))):this.resolveWithDelay(n)}delete(e,t){if(this._simulateError?.delete)throw 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,n){let r=this._collectionListeners[t];r||=(this._collectionListeners[t]={},this._collectionListeners[t]);let i=t=>{if(!t.after)return;let r=[t.after];t.before&&r.push(t.before);let i=this.retrieveQueryDocs(r,e.operations).filter((e,t,n)=>t===n.findIndex(t=>t.id===e.id));i.length>0&&n(i.map(e=>({before:t.before,after:e,type:t.type,params:t.params})))},a=Math.random().toString(36).substring(2,9);return r[a]=i,()=>delete r[a]}onDocumentChange(e,t,n){let r=this._documentListeners[e];r||=(this._documentListeners[e]={},this._documentListeners[e]);let i=e=>{e.after&&e.after.id===t&&n(e)},a=Math.random().toString(36).substring(2,9);return r[a]=i,()=>delete r[a]}onDocumentTemplateChange(e,t){let n=this.collectionsMatchingTemplate(e),r=[];return n.forEach(n=>{let i=this._documentListeners[n];i||=(this._documentListeners[n]={},this._documentListeners[n]);let a=r=>{r.params=A.extractTemplateParams(n,e),t(r)},o=Math.random().toString(36).substring(2,9);i[o]=a,r.push(()=>delete i[o])}),()=>r.forEach(e=>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)}notifyChange(e,t,n){let r={before:n,after:t,collectionPath:e,params:{},type:n?`update`:`create`};Object.values(this._documentListeners[e]??{}).forEach(e=>e(r)),Object.values(this._collectionListeners[e]??{}).forEach(e=>e(r))}decCursor(e){return this._cursor-=e,this._cursor<0?(this._cursor=0,!0):!1}queryProcessor(e,t,n){return{limit:t=>e,operations:t=>this.retrieveQueryDocs(e,t),sort:({order:t,propertyName:n})=>e.sort((e,r)=>t===`asc`?this.deepValue(e,n)>this.deepValue(r,n)?1:-1:this.deepValue(e,n)<this.deepValue(r,n)?1:-1)}[t](n)}retrieveQueryDocs(e,t){return t.reduce((t,n,r)=>{if(n.aggregate){let i=e.filter(e=>this.isQueryMatched(e,n));return r===0?i:t.concat(i)}else return t.filter(e=>this.isQueryMatched(e,n))},e)}deepValue(e,t){return t.split(`.`).reduce((e,t)=>e[t],e)}isQueryMatched(e,t){let n={"==":(e,t)=>e===t,"!=":(e,t)=>e!==t,"<":(e,t)=>e<t,"<=":(e,t)=>e<=t,">":(e,t)=>e>t,">=":(e,t)=>e>=t,containsAny:(e,t)=>e?.some(e=>t?.includes(e)),contains:(e,t)=>e?.includes(t)},{property:r,value:i,operator:a}=t,[o,s]=this.retrieveValuesToCompare(e,r,i);return n[a](o,s)}retrieveValuesToCompare(e,t,n){let r=e[t];if(r&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n)[0];var[i,a]=this.retrieveValuesToCompare(r,e,n?.[e])}return[i||r,a||n]}resolveWithDelay(e){if(this._simulateDelay<=0)return Promise.resolve(e);let t=new Promise(t=>{setTimeout(()=>t(e),this._simulateDelay)});return this._pendingPromises.push(t),t.finally(()=>this._pendingPromises=this._pendingPromises.filter(e=>e===t)),t}resolveCollectionPaths(e){return Promise.resolve(this.collectionsMatchingTemplate(e))}collectionsMatchingTemplate(e){return Object.keys(this._jsonRawData).filter(t=>A.isStringMatchingTemplate(e,t))}},M=class e{static registerCloudStorage(t,n){e._cloudStorageFactoryMap[t]=n}static createInstance(t){let n=e._cloudStorageFactoryMap[t];if(!n)throw Error(`You should register the ${t} cloud storage provider prior to use it`);return n()}get className(){return this.__className}static useCloudStorage(t){e._defaultCloudStorage=t}static get defaultCloudStorage(){if(!e._defaultCloudStorage)throw Error(`You should define a default cloud storage provider prior to use it`);return e._defaultCloudStorage}static{this._cloudStorageFactoryMap={}}};function N(e,t){return M.registerCloudStorage(e,t),t=>{t.prototype.__className=e}}var P=class extends M{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);let t=new Promise(t=>{setTimeout(()=>t(e),this._simulateDelay)});return this._pendingPromises.push(t),t.finally(()=>this._pendingPromises=this._pendingPromises.filter(e=>e===t)),t}save(e,t){let n=e;this._onProgress&&this._onProgress(0,100),this.mockFileSystem[e]=JSON.stringify(t),this._onProgress&&this._onProgress(100,100);let r=t instanceof File?t.name:n;return this.resolveWithDelay(r)}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()}};P=u([N(`MockCloudStorage`,()=>new P)],P);var F=function(e){return e[e.stored=0]=`stored`,e[e.pendingDataSet=1]=`pendingDataSet`,e[e.deleted=2]=`deleted`,e}({}),I=class extends d{constructor(...e){super(...e),this._onChange=new t}async save({data:e,fileName:t,progress:n,cloudStorageProvider:r}={}){let i=e||this._pendingData;i&&(this._reference&&await this.delete(),this.provider=r||M.defaultCloudStorage,this._originalFileName=t||(i instanceof File?i.name:void 0),this._reference=await this.provider.save(this.id,i,n),this._url=await this.provider.getUrl(this._reference),this._pendingData=void 0,this._onChange.notify({event:F.stored,storedFile:this}))}uploadControl(){return this.provider.uploadControl()}async delete(){if(!this._reference)throw 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:F.deleted,storedFile:this})}set provider(e){this._provider=e,this._cloudStorageProviderName=e.className}get provider(){if(!this._provider)try{this._provider=M.createInstance(this._cloudStorageProviderName)}catch{this._provider=M.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:F.pendingDataSet,pendingData:e,storedFile:this}),this}get originalFileName(){return this._originalFileName}onChange(e){return this._onChange.subscribe(e)}};u([f],I.prototype,`_reference`,void 0),u([f],I.prototype,`_url`,void 0),u([f],I.prototype,`_cloudStorageProviderName`,void 0),u([f],I.prototype,`_originalFileName`,void 0),u([f],I.prototype,`_mimeType`,void 0),I=u([y(`StoredFile`)],I);var L=class{},R=class e extends L{static{this.error={shouldBeRegistered:`You should register an auth service before using Auth.`}}constructor(){if(super(),this._onAuthStateChange=new t,!e._authService)throw Error(e.error.shouldBeRegistered);e._authService.onAuthStateChange(e=>this.authStateChanged(e))}static useAuthService(t){e._authService!=t&&(e._authService=t,this._instance=void 0)}static get instance(){return this._instance||=new this}signUp(t){return e._authService.signUp(t)}login(t){return e._authService.login(t)}logout(){return e._authService.logout()}resetEmailPassword(t){return e._authService.resetEmailPassword(t)}resendVerificationEmail(t,n,r){return e._authService.resendVerificationEmail(t,n,r)}refreshToken(){return e._authService.refreshToken()}onAuthStateChange(e){return this._onAuthStateChange.subscribe(e)}removeAuthStateChange(e){this._onAuthStateChange.unsubscribe(e)}linkAdditionalProvider(t){return e._authService.linkAdditionalProvider(t)}unlinkProvider(t){return e._authService.unlinkProvider(t)}authStateChanged(e){this._onAuthStateChange.notify(e)}static{this._instance=void 0}},z=class extends L{constructor(...e){super(...e),this.pendingPromises=[],this._fakeRegisteredUsers={}}signUp(e){let{verificationLink:t,email:n,password:r,authProvider:i}=e,a=new Promise(async(a,o)=>{i===`email`&&(n||o({code:`missingEmail`,message:`missingEmail`}),r||o({code:`missingPassword`,message:`missingPassword`})),r!==`fail`&&n!==`fail`?(this._loggedUser=this.userCredentials(e),this._fakeRegisteredUsers[this._loggedUser.id]=this._loggedUser,a(this._loggedUser),this.notifyChange?.(this._loggedUser)):(o({code:`userNotFound`,message:t||`Test auth error`}),this.notifyChange?.(void 0))});return this.pendingPromises.push(a),a}login(e){let t=Object.values(this._fakeRegisteredUsers).find(t=>t.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(){let e=new Promise(e=>{this._loggedUser=void 0,e(),this.notifyChange?.(void 0)});return this.pendingPromises.push(e),e}resetEmailPassword(e){return Object.values(this._fakeRegisteredUsers).find(t=>t.email===e)?Promise.resolve():Promise.reject({code:`userNotFound`,message:`Test auth error`})}resendVerificationEmail(e,t,n){return Object.values(this._fakeRegisteredUsers).find(t=>t.email===e)?Promise.resolve():Promise.reject({code:`userNotFound`,message:`Test auth error`})}refreshToken(){return Promise.resolve()}linkAdditionalProvider(e){throw Error(`Not implemented.`)}unlinkProvider(e){throw Error(`Not implemented.`)}async flush(){await Promise.all(this.pendingPromises),this.pendingPromises=[]}fakeRegisteredUser(e){if(this._fakeRegisteredUsers[e.id])throw 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){let t=Object.values(this._fakeRegisteredUsers).find(t=>t.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}}},B=class e{constructor(){}static{this.error={shouldBeRegistered:`You should register a cloud functions service with useCloudFunctionsService static method before using CloudFunctions.`}}static useCloudFunctionsService(e){this._cloudFunctionsService!=e&&(this._cloudFunctionsService=e)}static get instance(){if(!this._cloudFunctionsService)throw Error(e.error.shouldBeRegistered);return e._instance||=new e}getRawFunction(t){return e._cloudFunctionsService.retrieveFunction(t)}getFunction(t){let n=e._cloudFunctionsService.callFunction,r=this.getRawFunction(t);return async e=>{let t=await n(r,this.processParam(e));return this.processResult(t)}}processParam(e){if(e!=null)return e instanceof d?e.toObject():Array.isArray(e)?e.map(e=>this.processParam(e)):typeof e==`object`?Object.entries(e).reduce((e,[t,n])=>(e[t]=this.processParam(n),e),{}):e}processResult(e){if(e!=null)return e.__className?d.createInstance(e):Array.isArray(e)?e.map(e=>this.processResult(e)):typeof e==`object`?Object.entries(e).reduce((e,[t,n])=>(e[t]=this.processResult(n),e),{}):e}},V=class{constructor(e){this._registeredFunctions=e}retrieveFunction(e){let t=this._registeredFunctions[e];if(!t)throw Error(`Cloud function ${e} is not registered.`);return t}callFunction(e,t){return e(t)}},H=class{},U=class e extends H{static{this.error={shouldBeRegistered:`You should register a Server Auth service before using the Server Auth.`}}constructor(){super()}static useServerAuthService(t){e._authService!=t&&(e._authService=t,this._instance=void 0)}static get instance(){if(!e._authService)throw Error(e.error.shouldBeRegistered);return this._instance||=new e}getUser(t){return e._authService.getUser(t)}updateUser(t,n){return e._authService.updateUser(t,n)}setCustomCredentials(t,n){return e._authService.setCustomCredentials(t,n)}deleteUser(t){return e._authService.deleteUser(t)}static{this._instance=void 0}},W=class extends H{constructor(e){super(),this._userCredentials=e}getUser(e){return this._userCredentials[e]||Promise.resolve(void 0),Promise.resolve(this._userCredentials[e])}setCustomCredentials(e,t){let n=this._userCredentials[e];if(!n)throw Error(`User ${e} not found in the auth system`);return n.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 G(e,t){return e?e.replace(/\${\s*(\w*)\s*}/g,function(e,n){return t[n]||``}):``}function K(e){return e?e.replace(/([-_ ][\w])/g,e=>e.toUpperCase().replace(`-`,``).replace(`_`,``).replace(` `,``)):``}function q(e,t=`-`){if(!e)return``;let n=e.slice(1).replace(/( |[A-Z])/g,e=>e===` `?`-`:t+e[0].toLowerCase());return e[0].toLocaleLowerCase()+n.replace(/--/g,`-`)}function J(e,t){return t.split(`.`).reduce((e,t)=>e[t],e)}e.Auth=R,e.AuthMock=z,e.AuthService=L,e.CloudFunctions=B,e.CloudFunctionsMock=V,e.CloudStorage=M,e.DataSource=A,e.EntropicComponent=T,e.JsonDataSource=j,Object.defineProperty(e,`MockCloudStorage`,{enumerable:!0,get:function(){return P}}),e.Model=E,e.Observable=t,e.Persistent=d,e.Query=D,e.ServerAuth=U,e.ServerAuthMock=W,e.ServerAuthService=H,e.Store=O,Object.defineProperty(e,`StoredFile`,{enumerable:!0,get:function(){return I}}),e.StoredFileEvent=F,e.camelCase=K,e.getDeepValue=J,e.persistent=f,e.persistentParser=v,e.persistentPureReference=g,e.persistentPureReferenceWithCachedProps=_,e.persistentReference=m,e.persistentReferenceAt=p,e.persistentReferenceWithCachedProps=h,e.registerCloudStorage=N,e.registerLegacyClassName=b,e.registerPersistentClass=y,e.replaceValue=G,e.required=S,e.requiredWithValidator=C,e.searchableArray=x,e.snakeCase=q,e.typeName=w});
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`entropic-bond`]={}))})(this,function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=class{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}},n=new Uint8Array(16);function r(){return crypto.getRandomValues(n)}var i=[];for(let e=0;e<256;++e)i.push((e+256).toString(16).slice(1));function a(e,t=0){return(i[e[t+0]]+i[e[t+1]]+i[e[t+2]]+i[e[t+3]]+`-`+i[e[t+4]]+i[e[t+5]]+`-`+i[e[t+6]]+i[e[t+7]]+`-`+i[e[t+8]]+i[e[t+9]]+`-`+i[e[t+10]]+i[e[t+11]]+i[e[t+12]]+i[e[t+13]]+i[e[t+14]]+i[e[t+15]]).toLowerCase()}function o(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():s(e,t,n)}function s(e,t,n){e||={};let i=e.random??e.rng?.()??r();if(i.length<16)throw Error(`Random bytes length must be >= 16`);if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=i[e];return t}return a(i)}function c(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var l=class e{static registerFactory(e,t,n,r=!1){this._factoryMap[e]={factory:t,annotation:n,isLegacy:r}}static classFactory(e){if(!e)throw Error(`You should provide a class name.`);if(!this._factoryMap[e])throw 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(([e])=>e)}static isInstanceOf(t,n){let r=e.classFactory(n);return t instanceof e?t instanceof r:e.createInstance(t)instanceof r}static annotations(t){if(t instanceof e?t=t.className:typeof t==`string`||(t=new t().className),!this._factoryMap[t])throw Error(`You should register class ${t} prior to use.`);return this._factoryMap[t].annotation}constructor(e=o()){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){let t=this.getPersistentProperties().find(t=>t.name===e);if(!t)throw Error(`Property "${e}" has not been registered.`);return t}isRequired(e){return this.getPropInfo(e).validator!=null}isPropValueValid(e){let t=this.getPropInfo(e);return t.validator?t.validator(this[t.name],t,this):!0}clone(e){let 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=>{let n=e[this.removeUnderscore(t)];n!=null&&(this[t.name]=this.fromDeepObject(n))}),this}toObject(){let e={},t=this.toObj(e);return this.pushDocument(e,this.className,t),{...t,__rootCollections:e}}toObj(t){if(!this._persistentProperties)return{};this.beforeSerialize();let n={};if(!this.className)throw Error(`You should register \`${this.constructor.name||this.toString()||`this`}\` class prior to streaming it.`);return this._persistentProperties.forEach(r=>{let i=this[r.name],a=this.removeUnderscore(r);i!=null&&(r.isReference?n[a]=this.toReferenceObj(r,t):n[a]=this.toDeepObj(i,t),r.searchableArray&&(n[e.searchableArrayNameFor(a)]=i.map(e=>e.id)))}),n.__className=this.className,n}static searchableArrayNameFor(e){return`__${e}_searchable`}fromDeepObject(t){if(t==null)return t;if(Array.isArray(t))return t.map(e=>this.fromDeepObject(e));if(t.__documentReference){let n=t,r=e.createInstance(n);return r.__documentReference=t.__documentReference,r}if(t.__className)return e.createInstance(t);if(typeof t==`object`){let e={};return Object.entries(t).forEach(([t,n])=>e[t]=this.fromDeepObject(n)),e}return t}toDeepObj(t,n){if(t!=null){if(Array.isArray(t))return t.map(e=>this.toDeepObj(e,n));if(t.__documentReference)return t;if(t instanceof e)return t.toObj(n);if(typeof t==`object`){let e={};return Object.entries(t).forEach(([t,r])=>e[t]=this.toDeepObj(r,n)),e}return t}}static collectionPath(e,t,n){let r;return r=typeof t.storeInCollection==`function`?t.storeInCollection(e,t,n):t.storeInCollection??e.className,r}toReferenceObj(t,n){let r=this[t.name];return Array.isArray(r)?r.map(r=>(t.isPureReference||this.pushDocument(n,e.collectionPath(r,t),r),this.buildRefObject(r,e.collectionPath(r,t),t.cachedProps))):(t.isPureReference||this.pushDocument(n,e.collectionPath(r,t),r),this.buildRefObject(r,e.collectionPath(r,t),t.cachedProps))}buildRefObject(e,t,n){let r=n?.reduce((t,n)=>(e[n]!==void 0&&(t[n]=e[n]),t),{});return{id:e.id,__className:e.className||e.__className,__documentReference:{storedInCollection:t},...r}}pushDocument(e,t,n){if(`__documentReference`in n&&n.__documentReference)return;e[t]||(e[t]=[]);let r=this.toDeepObj(n,e);e[t].push(r)}removeUnderscore(e){return e.name.slice(1)}static createReference(t){let n=e.createInstance(t);return n.__documentReference=t.__documentReference||{storedInCollection:n.className},n}static createInstance(t){if(typeof t==`string`)return new(e.classFactory(t));try{return new(e.classFactory(t.__className))().fromObject(t)}catch(e){let n=Object.entries(t).filter(([e,t])=>t!=null&&typeof t!=`function`).map(([e,t])=>`${e}: ${t}`).join(`,
|
|
2
|
+
`);throw Error(`${e}\n-----> Class name not found in object:\n{\n\t ${n} \n}\n`)}}static propInfo(t,n){return e.createInstance(t).getPropInfo(n)}static propType(t){if(t.typeName)return Array.isArray(t.typeName)?`undefined[]`:t.typeName??`undefined`;let n=e.createInstance(t.ownerClassName())[t.name];if(Array.isArray(n)){if(n.length===0)return`undefined[]`;let t=n[0];return t instanceof e?t.className+`[]`:typeof t+`[]`}else if(n instanceof e)return n.className;else return typeof n}static getSystemRegisteredReferencesWithCachedProps(){return e.registeredClasses().reduce((t,n)=>{let r=e.createInstance(n).getPersistentProperties().filter(e=>e.cachedProps);return r.length>0&&(t[n]=r),t},{})}static{this._factoryMap={}}};c([u],l.prototype,`_id`,void 0);function u(e,t){return g()(e,t)}function d(e){return function(t,n){return g({storeInCollection:e,isReference:!0})(t,n)}}function f(e,t){return g({isReference:!0})(e,t)}function p(e,t,n,r){return function(i,a){return g({isReference:!0,storeInCollection:n,typeName:t,cachedProps:e,ownerCollection:r??i.className})(i,a)}}function m(e,t,n){return g({isReference:!0,isPureReference:!0,storeInCollection:n})(e,t)}function h(e,t,n,r){return function(i,a){return g({isReference:!0,isPureReference:!0,storeInCollection:n,ownerCollection:r,typeName:t,cachedProps:e})(i,a)}}function g(e){return function(t,n){Object.getOwnPropertyDescriptor(t,`_persistentProperties`)||(t._persistentProperties?t._persistentProperties=[...t._persistentProperties]:t._persistentProperties=[]);let r=t._persistentProperties.find(e=>e.name===n);r?Object.assign(r,e):t._persistentProperties.push({name:n,ownerClassName:()=>t.className,...e})}}function _(e,t){return n=>{l.registerFactory(e,n,t),n.prototype.__className=e}}function v(e){return t=>{l.registerFactory(e,t,void 0,!0)}}function y(e,t){return g({searchableArray:!0})(e,t)}function b(e,t){return g({validator:e=>e!=null})(e,t)}function x(e=e=>e!=null){return function(t,n){return g({validator:e})(t,n)}}function S(e){let t;return t=typeof e==`function`?new e().className:e,function(e,n){return g({typeName:t})(e,n)}}var C=class extends l{constructor(...e){super(...e),this._onChange=new t}onChange(e){return this._onChange.subscribe(e)}removeOnChange(e){this._onChange.unsubscribe(e)}changeProp(e,t){let n=`_`+String(e);return this[n]===t?!1:(this[n]=t,this._onChange.notify({[e]:t}),!0)}notify(e){this._onChange.notify(e)}pushAndNotify(e,t,n){let r=`_`+String(e);if(!(n&&this[r].find(e=>!n(e,t))))return this[r].push(t),this.notify({[e]:this[e]}),t}removeAndNotify(e,t,n){let r=`_`+String(e),i=this[r].length;if(this[r]=this[r].filter(e=>!n(e,t)),i!==this[r].length)return this.notify({[e]:this[e]}),t}},w=class e{static{this.error={persistentNeedForSubCollection:`The document parameter for a sub-collection should be a Persistent instace`,invalidQueryOrder:`Cannot add where calls after or calls`}}constructor(t,n,r){if(r){if(!(n instanceof l))throw Error(e.error.persistentNeedForSubCollection);this.collectionName=`${n.className}/${n.id}/${r}`}else this.collectionName=n instanceof l?n.className:n;this._stream=t}findById(e,t){return new Promise((n,r)=>{this._stream.findById(e,this.collectionName).then(e=>{e?(t?t.fromObject(e):t=l.createInstance(e),n(t)):n(void 0)}).catch(e=>r(e))})}save(e){let t=e.toObject();return this.collectionName!==t.__className&&(t.__rootCollections[this.collectionName]=t.__rootCollections[t.__className],delete t.__rootCollections[t.__className]),new Promise((e,n)=>{this._stream.save(t.__rootCollections).then(()=>e()).catch(e=>n(e))})}delete(e){return new Promise((t,n)=>{this._stream.delete(e,this.collectionName).then(()=>t()).catch(e=>n(e))})}find(){return new T(this)}query(e={},t){if(t){let n=t instanceof l?t.className:t;e.operations||=[],e.operations.push({property:`__className`,operator:`==`,value:n})}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,e=>t(O.toPersistentDocumentChange(e)))}onCollectionChange(e,t){return this._stream.onCollectionChange(this.preprocessQueryObject(e.getQueryObject()),this.collectionName,e=>t(e.map(e=>O.toPersistentDocumentChange(e))))}onCollectionTemplateChange(e,t){return this._stream.onDocumentTemplateChange(e,e=>t(O.toPersistentDocumentChange(e)))}mapToInstance(e){return new Promise((t,n)=>{e().then(e=>t(e.map(e=>l.createInstance(e)))).catch(e=>n(e))})}preprocessQueryObject(e){if(Object.values(e).length===0)return e;let t=e.operations?.map(e=>{let t=e.value[0]??e.value;return O.isArrayOperator(e.operator)&&t instanceof l?{property:l.searchableArrayNameFor(e.property),operator:e.operator,value:Array.isArray(e.value)?e.value.map(e=>e.id):t.id,aggregate:e.aggregate}:{property:e.property,operator:e.operator,value:e.value instanceof l?{id:e.value.id}:e.value,aggregate:e.aggregate}})??[];return{...e,operations:t}}},T=class{constructor(e){this.queryObject={operations:[]},this.model=e}where(e,t,n,r){if(this.queryObject.operations?.at(-1)?.aggregate&&!r)throw Error(w.error.invalidQueryOrder);return this.queryObject.operations?.push({property:e,operator:t,value:n,aggregate:r}),this}whereDeepProp(e,t,n,r){if(this.queryObject.operations?.at(-1)?.aggregate&&!r)throw Error(w.error.invalidQueryOrder);let i=e.split(`.`),a={},o=i.length>1?a:n;return i.slice(1).forEach((e,t)=>{a[e]=t<i.length-2?{}:n,a=a[e]}),this.queryObject.operations?.push({property:i[0],operator:t,value:o,aggregate:r}),this}and(e,t,n){return this.where(e,t,n)}andDeepProp(e,t,n){return this.whereDeepProp(e,t,n)}or(e,t,n){return this.where(e,t,n,!0)}orDeepProp(e,t,n){return this.whereDeepProp(e,t,n,!0)}instanceOf(e){let t=e instanceof l?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}getQueryModel(){return this.model}},E=class e{constructor(){}static{this.error={shouldBeRegistered:`You should register a data source before using the data Store.`}}static useDataSource(e){this._dataSource=e}static get dataSource(){return e._dataSource}static getModel(t){if(!e._dataSource)throw Error(this.error.shouldBeRegistered);return new w(e._dataSource,t)}static getModelForSubCollection(t,n){if(!e._dataSource)throw Error(this.error.shouldBeRegistered);return new w(e._dataSource,t,n)}static async populate(e){if(!e)return;let t=async e=>{let t=e;if(!t.__documentReference)return e;let n=await this.getModel(t.__documentReference.storedInCollection).findById(t.id,e);return n&&(n.__documentReference=void 0),n};return Array.isArray(e)?(await Promise.all(e.map(e=>t(e)))).filter(e=>e):t(e)}static isPopulated(e){return Array.isArray(e)?e.reduce((e,t)=>e&&t.__documentReference===void 0,!0):e.__documentReference===void 0}},D=class e{constructor(e){this._resolveCollectionPaths=()=>{throw Error(`The method collectionsMatchingTemplate has not been implemented in the concrete data source`)},this._disabledChangeListeners=new Set,this._collectionsToWatch={},e&&(this._beforeUpdateDocument=e.beforeUpdateDocument,this._afterUpdateDocument=e.afterUpdateDocument,this._afterDocumentChange=e.afterDocumentChange,this._beforeDocumentChange=e.beforeDocumentChange,this._beforeQueryOwnerCollection=e.beforeQueryOwnerCollection),this.installUpdaters()}installUpdaters(){let e=l.getSystemRegisteredReferencesWithCachedProps();this._collectionsToWatch={},Object.entries(e).forEach(([e,t])=>{t.forEach(t=>{t.typeName&&(Array.isArray(t.typeName)?t.typeName:[t?.typeName??e]).map(e=>l.collectionPath(l.createInstance(e),t)).forEach(e=>{this._collectionsToWatch[e]||(this._collectionsToWatch[e]=[]),this._collectionsToWatch[e].find(e=>e.name===t.name&&e.ownerClassName()===t.ownerClassName())||this._collectionsToWatch[e].push(t)})})})}set beforeDocumentChange(e){this._beforeDocumentChange=e}set afterDocumentChange(e){this._afterDocumentChange=e}set beforeUpdateDocument(e){this._beforeUpdateDocument=e}set afterUpdateDocument(e){this._afterUpdateDocument=e}set beforeQueryOwnerCollection(e){this._beforeQueryOwnerCollection=e}set resolveCollectionPaths(e){this._resolveCollectionPaths=e}get collectionsToWatch(){return this._collectionsToWatch}updateProps(e,t){let n=this._collectionsToWatch[e];return n?this.onDocumentChange(t,n):Promise.resolve()}async onDocumentChange(t,n){let r=O.toPersistentDocumentChange(t);this._beforeDocumentChange?.(r,n);let i={};t.type!==`update`||!r.before||r.after?.id&&this._disabledChangeListeners.has(r.after?.id)||(await Promise.all(n.map(async t=>{let n=e.ownerCollectionPath(l.createInstance(t.ownerClassName()),t,r.params),a=await this._resolveCollectionPaths(n);await Promise.all(a.map(async e=>{let n=E.getModel(e),a=n.find(),o=!1;t.cachedProps?.forEach(e=>{r.before[e]!==r.after[e]&&(o=!0)}),o&&(a=t.searchableArray?a.where(t.name,`contains`,r.before):a.where(t.name,`==`,r.before)),a=this._beforeQueryOwnerCollection?.(a)??a;let s=await a.get();return i[e]={totalDocumentsToUpdate:s.length,updatedDocuments:[],documentsToUpdate:s.map(e=>e.name??e.id)},Promise.all([s.map(async a=>{let o=!1;if(t.cachedProps?.forEach(e=>{r.before[e]!==r.after[e]&&(o=!0)}),o){if(t.searchableArray){let e=a[t.name].findIndex(e=>e.id===r.before.id);a[t.name][e]=r.after}else a[`_${t.name}`]=r.after;this._beforeUpdateDocument?.(a,t,r.after),this.disableChangeListener(a),await n.save(a),this.enableChangeListener(a),i[e]?.updatedDocuments.push(a.id),this._afterUpdateDocument?.(a,t,r.after)}else return Promise.resolve()})])}))})),this._afterDocumentChange?.(i,n))}disableChangeListener(e){this._disabledChangeListeners.add(e.id)}enableChangeListener(e){this._disabledChangeListeners.delete(e.id)}static ownerCollectionPath(e,t,n){let r;return r=typeof t.ownerCollection==`function`?t.ownerCollection(e,t,n):t.ownerCollection??e.className,r}},O=class e{constructor(){this._cachedPropsUpdater=void 0}installCachedPropsUpdater(e){return this._cachedPropsUpdater=new D(e),this._cachedPropsUpdater.resolveCollectionPaths=this.resolveCollectionPaths.bind(this),this._cachedPropsUpdater}get cachedPropsUpdater(){return this._cachedPropsUpdater}static toPropertyPathOperations(t){return t?t.map(t=>{if(e.isArrayOperator(t.operator)&&t.value[0]instanceof l)return{property:l.searchableArrayNameFor(t.property),operator:t.operator,value:t.value.map(e=>e.id),aggregate:t.aggregate};let[n,r]=this.toPropertyPathValue(t.value);return{property:`${String(t.property)}${n?`.`+n:``}`,operator:t.operator,value:r,aggregate:t.aggregate}}):[]}static isArrayOperator(e){return e===`containsAny`||e===`contains`}static toPersistentDocumentChange(e){return{...e,before:e.before&&l.createInstance(e.before),after:e.after&&l.createInstance(e.after)}}static toPropertyPathValue(e){if(typeof e==`object`&&!Array.isArray(e)){let t=Object.keys(e)[0],[n,r]=this.toPropertyPathValue(e[t]);return[`${t}${n?`.`+n:``}`,r]}else return[void 0,e]}static isStringMatchingTemplate(e,t){let n=e.split(`/`),r=t.split(`/`);if(r.length>n.length)return!1;for(let e=0;e<r.length;e++){let t=n[e],i=r[e];if(!(t.startsWith(`{`)&&t.endsWith(`}`)||t.startsWith("${")&&t.endsWith(`}`))&&t!==i)return!1}for(let e=r.length;e<n.length;e++){let t=n[e];if(!(t.startsWith(`{`)&&t.endsWith(`}`)||t.startsWith("${")&&t.endsWith(`}`)))return!1}return!0}static extractTemplateParams(e,t){let n=t.split(`/`),r=e.split(`/`),i={};if(r.length>n.length)return i;for(let e=0;e<r.length;e++){let t=n[e],a=r[e];if(t.startsWith(`{`)&&t.endsWith(`}`))i[t.slice(1,-1)]=a;else if(t.startsWith("${")&&t.endsWith(`}`))i[t.slice(2,-1)]=a;else if(t!==a)return{}}for(let e=r.length;e<n.length;e++){let t=n[e];if(!(t.startsWith(`{`)&&t.endsWith(`}`)||t.startsWith("${")&&t.endsWith(`}`)))return{}}return i}},k=class extends O{constructor(e){super(),this._jsonRawData={},this._lastMatchingDocs=[],this._lastLimit=0,this._cursor=0,this._simulateDelay=0,this._pendingPromises=[],this._documentListeners={},this._collectionListeners={},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 Error(this._simulateError.findById);return this.resolveWithDelay(this._jsonRawData[t]?.[e])}save(e){if(this._simulateError?.store)throw Error(this._simulateError.store);return Object.entries(e).forEach(([e,t])=>{this._jsonRawData[e]||(this._jsonRawData[e]={}),t?.forEach(t=>{let n=this._jsonRawData[e][t.id];this._jsonRawData[e][t.id]=t,this.notifyChange(e,t,n)})}),this.resolveWithDelay()}find(e,t){if(this._simulateError?.find)throw Error(this._simulateError.find);let n=Object.values(this._jsonRawData[t]||{});return e?(this._lastLimit=e.limit||0,this._cursor=0,this._lastMatchingDocs=Object.entries(e).reduce((e,[t,n])=>this.queryProcessor(e,t,n),Object.values(n)),this.resolveWithDelay(this._lastMatchingDocs.slice(0,e.limit))):this.resolveWithDelay(n)}delete(e,t){if(this._simulateError?.delete)throw 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,n){let r=this._collectionListeners[t];r||=(this._collectionListeners[t]={},this._collectionListeners[t]);let i=t=>{if(!t.after)return;let r=[t.after];t.before&&r.push(t.before);let i=this.retrieveQueryDocs(r,e.operations).filter((e,t,n)=>t===n.findIndex(t=>t.id===e.id));i.length>0&&n(i.map(e=>({before:t.before,after:e,type:t.type,params:t.params})))},a=Math.random().toString(36).substring(2,9);return r[a]=i,()=>delete r[a]}onDocumentChange(e,t,n){let r=this._documentListeners[e];r||=(this._documentListeners[e]={},this._documentListeners[e]);let i=e=>{e.after&&e.after.id===t&&n(e)},a=Math.random().toString(36).substring(2,9);return r[a]=i,()=>delete r[a]}onDocumentTemplateChange(e,t){let n=this.collectionsMatchingTemplate(e),r=[];return n.forEach(n=>{let i=this._documentListeners[n];i||=(this._documentListeners[n]={},this._documentListeners[n]);let a=r=>{r.params=O.extractTemplateParams(n,e),t(r)},o=Math.random().toString(36).substring(2,9);i[o]=a,r.push(()=>delete i[o])}),()=>r.forEach(e=>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)}notifyChange(e,t,n){let r={before:n,after:t,collectionPath:e,params:{},type:n?`update`:`create`};Object.values(this._documentListeners[e]??{}).forEach(e=>e(r)),Object.values(this._collectionListeners[e]??{}).forEach(e=>e(r))}decCursor(e){return this._cursor-=e,this._cursor<0?(this._cursor=0,!0):!1}queryProcessor(e,t,n){return{limit:t=>e,operations:t=>this.retrieveQueryDocs(e,t),sort:({order:t,propertyName:n})=>e.sort((e,r)=>t===`asc`?this.deepValue(e,n)>this.deepValue(r,n)?1:-1:this.deepValue(e,n)<this.deepValue(r,n)?1:-1)}[t](n)}retrieveQueryDocs(e,t){return t.reduce((t,n,r)=>{if(n.aggregate){let i=e.filter(e=>this.isQueryMatched(e,n));return r===0?i:t.concat(i)}else return t.filter(e=>this.isQueryMatched(e,n))},e)}deepValue(e,t){return t.split(`.`).reduce((e,t)=>e[t],e)}isQueryMatched(e,t){let n={"==":(e,t)=>e===t,"!=":(e,t)=>e!==t,"<":(e,t)=>e<t,"<=":(e,t)=>e<=t,">":(e,t)=>e>t,">=":(e,t)=>e>=t,containsAny:(e,t)=>e?.some(e=>t?.includes(e)),contains:(e,t)=>e?.includes(t)},{property:r,value:i,operator:a}=t,[o,s]=this.retrieveValuesToCompare(e,r,i);return n[a](o,s)}retrieveValuesToCompare(e,t,n){let r=e[t];if(r&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n)[0];var[i,a]=this.retrieveValuesToCompare(r,e,n?.[e])}return[i||r,a||n]}resolveWithDelay(e){if(this._simulateDelay<=0)return Promise.resolve(e);let t=new Promise(t=>{setTimeout(()=>t(e),this._simulateDelay)});return this._pendingPromises.push(t),t.finally(()=>this._pendingPromises=this._pendingPromises.filter(e=>e===t)),t}resolveCollectionPaths(e){return Promise.resolve(this.collectionsMatchingTemplate(e))}collectionsMatchingTemplate(e){return Object.keys(this._jsonRawData).filter(t=>O.isStringMatchingTemplate(e,t))}},A=class e{static registerCloudStorage(t,n){e._cloudStorageFactoryMap[t]=n}static createInstance(t){let n=e._cloudStorageFactoryMap[t];if(!n)throw Error(`You should register the ${t} cloud storage provider prior to use it`);return n()}get className(){return this.__className}static useCloudStorage(t){e._defaultCloudStorage=t}static get defaultCloudStorage(){if(!e._defaultCloudStorage)throw Error(`You should define a default cloud storage provider prior to use it`);return e._defaultCloudStorage}static{this._cloudStorageFactoryMap={}}};function j(e,t){return A.registerCloudStorage(e,t),t=>{t.prototype.__className=e}}var M=class extends A{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);let t=new Promise(t=>{setTimeout(()=>t(e),this._simulateDelay)});return this._pendingPromises.push(t),t.finally(()=>this._pendingPromises=this._pendingPromises.filter(e=>e===t)),t}save(e,t){let n=e;this._onProgress&&this._onProgress(0,100),this.mockFileSystem[e]=JSON.stringify(t),this._onProgress&&this._onProgress(100,100);let r=t instanceof File?t.name:n;return this.resolveWithDelay(r)}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()}};M=c([j(`MockCloudStorage`,()=>new M)],M);var N=function(e){return e[e.stored=0]=`stored`,e[e.pendingDataSet=1]=`pendingDataSet`,e[e.deleted=2]=`deleted`,e}({}),P=class extends l{constructor(...e){super(...e),this._onChange=new t}async save({data:e,fileName:t,progress:n,cloudStorageProvider:r}={}){let i=e||this._pendingData;i&&(this._reference&&await this.delete(),this.provider=r||A.defaultCloudStorage,this._originalFileName=t||(i instanceof File?i.name:void 0),this._reference=await this.provider.save(this.id,i,n),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 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=A.createInstance(this._cloudStorageProviderName)}catch{this._provider=A.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)}};c([u],P.prototype,`_reference`,void 0),c([u],P.prototype,`_url`,void 0),c([u],P.prototype,`_cloudStorageProviderName`,void 0),c([u],P.prototype,`_originalFileName`,void 0),c([u],P.prototype,`_mimeType`,void 0),P=c([_(`StoredFile`)],P);var F=class{},I=class e extends F{static{this.error={shouldBeRegistered:`You should register an auth service before using Auth.`}}constructor(){if(super(),this._onAuthStateChange=new t,!e._authService)throw Error(e.error.shouldBeRegistered);e._authService.onAuthStateChange(e=>this.authStateChanged(e))}static useAuthService(t){e._authService!=t&&(e._authService=t,this._instance=void 0)}static get instance(){return this._instance||=new this}signUp(t){return e._authService.signUp(t)}login(t){return e._authService.login(t)}logout(){return e._authService.logout()}resetEmailPassword(t){return e._authService.resetEmailPassword(t)}resendVerificationEmail(t,n,r){return e._authService.resendVerificationEmail(t,n,r)}refreshToken(){return e._authService.refreshToken()}onAuthStateChange(e){return this._onAuthStateChange.subscribe(e)}removeAuthStateChange(e){this._onAuthStateChange.unsubscribe(e)}linkAdditionalProvider(t){return e._authService.linkAdditionalProvider(t)}unlinkProvider(t){return e._authService.unlinkProvider(t)}authStateChanged(e){this._onAuthStateChange.notify(e)}static{this._instance=void 0}},L=class extends F{constructor(...e){super(...e),this.pendingPromises=[],this._fakeRegisteredUsers={}}signUp(e){let{verificationLink:t,email:n,password:r,authProvider:i}=e,a=new Promise(async(a,o)=>{i===`email`&&(n||o({code:`missingEmail`,message:`missingEmail`}),r||o({code:`missingPassword`,message:`missingPassword`})),r!==`fail`&&n!==`fail`?(this._loggedUser=this.userCredentials(e),this._fakeRegisteredUsers[this._loggedUser.id]=this._loggedUser,a(this._loggedUser),this.notifyChange?.(this._loggedUser)):(o({code:`userNotFound`,message:t||`Test auth error`}),this.notifyChange?.(void 0))});return this.pendingPromises.push(a),a}login(e){let t=Object.values(this._fakeRegisteredUsers).find(t=>t.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(){let e=new Promise(e=>{this._loggedUser=void 0,e(),this.notifyChange?.(void 0)});return this.pendingPromises.push(e),e}resetEmailPassword(e){return Object.values(this._fakeRegisteredUsers).find(t=>t.email===e)?Promise.resolve():Promise.reject({code:`userNotFound`,message:`Test auth error`})}resendVerificationEmail(e,t,n){return Object.values(this._fakeRegisteredUsers).find(t=>t.email===e)?Promise.resolve():Promise.reject({code:`userNotFound`,message:`Test auth error`})}refreshToken(){return Promise.resolve()}linkAdditionalProvider(e){throw Error(`Not implemented.`)}unlinkProvider(e){throw Error(`Not implemented.`)}async flush(){await Promise.all(this.pendingPromises),this.pendingPromises=[]}fakeRegisteredUser(e){if(this._fakeRegisteredUsers[e.id])throw 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){let t=Object.values(this._fakeRegisteredUsers).find(t=>t.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}}},R=class e{constructor(){}static{this.error={shouldBeRegistered:`You should register a cloud functions service with useCloudFunctionsService static method before using CloudFunctions.`}}static useCloudFunctionsService(e){this._cloudFunctionsService!=e&&(this._cloudFunctionsService=e)}static get instance(){if(!this._cloudFunctionsService)throw Error(e.error.shouldBeRegistered);return e._instance||=new e}getRawFunction(t){return e._cloudFunctionsService.retrieveFunction(t)}getFunction(t){let n=e._cloudFunctionsService.callFunction,r=this.getRawFunction(t);return async e=>{let t=await n(r,this.processParam(e));return this.processResult(t)}}processParam(e){if(e!=null)return e instanceof l?e.toObject():Array.isArray(e)?e.map(e=>this.processParam(e)):typeof e==`object`?Object.entries(e).reduce((e,[t,n])=>(e[t]=this.processParam(n),e),{}):e}processResult(e){if(e!=null)return e.__className?l.createInstance(e):Array.isArray(e)?e.map(e=>this.processResult(e)):typeof e==`object`?Object.entries(e).reduce((e,[t,n])=>(e[t]=this.processResult(n),e),{}):e}},z=class{constructor(e){this._registeredFunctions=e}retrieveFunction(e){let t=this._registeredFunctions[e];if(!t)throw Error(`Cloud function ${e} is not registered.`);return t}callFunction(e,t){return e(t)}},B=class{},V=class e extends B{static{this.error={shouldBeRegistered:`You should register a Server Auth service before using the Server Auth.`}}constructor(){super()}static useServerAuthService(t){e._authService!=t&&(e._authService=t,this._instance=void 0)}static get instance(){if(!e._authService)throw Error(e.error.shouldBeRegistered);return this._instance||=new e}getUser(t){return e._authService.getUser(t)}updateUser(t,n){return e._authService.updateUser(t,n)}setCustomCredentials(t,n){return e._authService.setCustomCredentials(t,n)}deleteUser(t){return e._authService.deleteUser(t)}static{this._instance=void 0}},H=class extends B{constructor(e){super(),this._userCredentials=e}getUser(e){return this._userCredentials[e]||Promise.resolve(void 0),Promise.resolve(this._userCredentials[e])}setCustomCredentials(e,t){let n=this._userCredentials[e];if(!n)throw Error(`User ${e} not found in the auth system`);return n.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 U(e,t){return e?e.replace(/\${\s*(\w*)\s*}/g,function(e,n){return t[n]||``}):``}function W(e){return e?e.replace(/([-_ ][\w])/g,e=>e.toUpperCase().replace(`-`,``).replace(`_`,``).replace(` `,``)):``}function G(e,t=`-`){if(!e)return``;let n=e.slice(1).replace(/( |[A-Z])/g,e=>e===` `?`-`:t+e[0].toLowerCase());return e[0].toLocaleLowerCase()+n.replace(/--/g,`-`)}function K(e,t){return t.split(`.`).reduce((e,t)=>e[t],e)}e.Auth=I,e.AuthMock=L,e.AuthService=F,e.CloudFunctions=R,e.CloudFunctionsMock=z,e.CloudStorage=A,e.DataSource=O,e.EntropicComponent=C,e.JsonDataSource=k,Object.defineProperty(e,"MockCloudStorage",{enumerable:!0,get:function(){return M}}),e.Model=w,e.Observable=t,e.Persistent=l,e.Query=T,e.ServerAuth=V,e.ServerAuthMock=H,e.ServerAuthService=B,e.Store=E,Object.defineProperty(e,"StoredFile",{enumerable:!0,get:function(){return P}}),e.StoredFileEvent=N,e.camelCase=W,e.getDeepValue=K,e.persistent=u,e.persistentParser=g,e.persistentPureReference=m,e.persistentPureReferenceWithCachedProps=h,e.persistentReference=f,e.persistentReferenceAt=d,e.persistentReferenceWithCachedProps=p,e.registerCloudStorage=j,e.registerLegacyClassName=v,e.registerPersistentClass=_,e.replaceValue=U,e.required=b,e.requiredWithValidator=x,e.searchableArray=y,e.snakeCase=G,e.typeName=S});
|
|
3
3
|
//# sourceMappingURL=entropic-bond.umd.cjs.map
|