prostgles-client 1.5.158 → 1.5.161
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.no-sync.js +1 -1
- package/dist/prostgles.d.ts.map +1 -1
- package/dist/prostgles.js +38 -2
- package/lib/prostgles.ts +49 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(this||window,(()=>(()=>{var e={133:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncedTable=t.debug=void 0;const i=n(792),s="DEBUG_SYNCEDTABLE",r="undefined"!=typeof window;t.debug=function(...e){r&&window[s]&&window[s](...e)};const o={array:"array",localStorage:"localStorage",object:"object"};class a{constructor({name:e,filter:n,onChange:s,onReady:a,db:c,skipFirstTrigger:d=!1,select:h="*",storageType:u="object",patchText:f=!1,patchJSON:m=!1,onError:g}){if(this.throttle=100,this.batch_size=50,this.skipFirstTrigger=!1,this.columns=[],this._multiSubscriptions=[],this._singleSubscriptions=[],this.items=[],this.itemsObj={},this.isSynced=!1,this.updatePatches=async e=>{var t,n;let s=e.map((e=>e.current)),r=[],o=[];if(this.columns&&this.columns.length&&(null===(t=this.tableHandler)||void 0===t?void 0:t.updateBatch)&&(this.patchText||this.patchJSON)){const t=this.columns.filter((e=>"text"===e.data_type));if(this.patchText&&t.length){s=[];const n=[this.synced_field,...this.id_fields];await Promise.all(e.slice(0).map((async(e,a)=>{const{current:l,initial:c}={...e};let d;c&&(t.map((e=>{!n.includes(e.name)&&e.name in l&&(null!=d||(d={...l}),d[e.name]=(0,i.getTextPatch)(c[e.name],l[e.name]))})),d&&this.wal&&(o.push(d),r.push([this.wal.getIdObj(d),this.wal.getDeltaObj(d)]))),d||s.push(l)})))}}if(r.length)try{await(null===(n=this.tableHandler)||void 0===n?void 0:n.updateBatch(r))}catch(e){console.log("failed to patch update",e),s=s.concat(o)}return s.filter((e=>e))},this._notifySubscribers=(e=[])=>{if(!this.isSynced)return;let t=[],n=[],i=[];if(e.map((({idObj:e,newItem:s,delta:r})=>{this.singleSubscriptions.filter((t=>this.matchesIdObj(t.idObj,e))).map((async e=>{try{await e.notify(s,r)}catch(e){console.error("SyncedTable failed to notify: ",e)}})),this.matchesFilter(s)&&(t.push(s),n.push(r),i.push(e))})),this.onChange||this.multiSubscriptions.length){let e=[],i=[];if(this.getItems().map((s=>{e.push({...s});const r=t.findIndex((e=>this.matchesIdObj(s,e)));i.push(n[r])})),this.onChange)try{this.onChange(e,i)}catch(e){console.error("SyncedTable failed to notify onChange: ",e)}this.multiSubscriptions.map((async t=>{try{await t.notify(e,i)}catch(e){console.error("SyncedTable failed to notify: ",e)}}))}},this.unsubscribe=e=>(this.singleSubscriptions=this.singleSubscriptions.filter((t=>t._onChange!==e)),this.multiSubscriptions=this.multiSubscriptions.filter((t=>t._onChange!==e)),(0,t.debug)("unsubscribe",this),"ok"),this.unsync=()=>{this.dbSync&&this.dbSync.unsync&&this.dbSync.unsync()},this.destroy=()=>{this.unsync(),this.multiSubscriptions=[],this.singleSubscriptions=[],this.itemsObj={},this.items=[],this.onChange=void 0},this.delete=async(e,t=!1)=>{var n;const i=this.getIdObj(e);return this.setItem(i,void 0,!0,!0),!t&&(null===(n=this.tableHandler)||void 0===n?void 0:n.delete)&&await this.tableHandler.delete(i),this._notifySubscribers(),!0},this.checkItemCols=e=>{if(this.columns&&this.columns.length){const t=Object.keys({...e}).filter((e=>!this.columns.find((t=>t.name===e))));if(t.length)throw"Unexpected columns in sync item update: "+t.join(", ")}},this.upsert=async(e,t=!1)=>{var n,s;if(!(e&&e.length||t))throw"No data provided for upsert";let r,o=[],a=[];await Promise.all(e.map((async(e,n)=>{var s;let c={...e.idObj},d={...e.delta};Object.keys(d).map((e=>{void 0===d[e]&&(d[e]=null)})),t||this.checkItemCols({...e.delta,...e.idObj});let h=this.getItem(c),u=h.index,f=h.data;!t&&!(0,i.isEmpty)(d)||(0,i.isEmpty)(f)||(d=this.getDelta(f||{},d)),t||(d[this.synced_field]=Date.now());let m={...f,...d,...c};f&&!t&&(null===(s=e.opts)||void 0===s?void 0:s.deepMerge)&&(m=l({...f,...c},{...d})),r=f?f[this.synced_field]<m[this.synced_field]?"updated":"unchanged":"inserted",this.setItem(m,u);let g={idObj:c,delta:d,oldItem:f,newItem:m,status:r,from_server:t};return t||a.push({initial:f,current:{...m}}),g.delta&&!(0,i.isEmpty)(g.delta)&&o.push(g),!0}))).catch((e=>{console.error("SyncedTable failed upsert: ",e)})),null===(n=this.notifyWal)||void 0===n||n.addData(o.map((e=>({initial:e.oldItem,current:e.newItem})))),!t&&a.length&&(null===(s=this.wal)||void 0===s||s.addData(a))},this.setItems=e=>{if(this.storageType===o.localStorage){if(!r)throw"Cannot access window object. Choose another storage method (array OR object)";window.localStorage.setItem(this.name,JSON.stringify(e))}else this.storageType===o.array?this.items=e:this.itemsObj=e.reduce(((e,t)=>({...e,[this.getIdStr(t)]:{...t}})),{})},this.getItems=()=>{let e=[];if(this.storageType===o.localStorage){if(!r)throw"Cannot access window object. Choose another storage method (array OR object)";let t=window.localStorage.getItem(this.name);if(t)try{e=JSON.parse(t)}catch(e){console.error(e)}}else e=this.storageType===o.array?this.items.map((e=>({...e}))):Object.values({...this.itemsObj});if(!this.id_fields||!this.synced_field)throw"id_fields AND/OR synced_field missing";{const t=[this.synced_field,...this.id_fields.sort()];e=e.filter((e=>!this.filter||!(0,i.getKeys)(this.filter).find((t=>e[t]!==this.filter[t])))).sort(((e,n)=>t.map((t=>e[t]<n[t]?-1:e[t]>n[t]?1:0)).find((e=>e))))}return e.map((e=>({...e})))},this.getBatch=({from_synced:e,to_synced:t,offset:n,limit:i}={offset:0,limit:void 0})=>{let s=this.getItems().map((e=>({...e}))).filter((n=>(!Number.isFinite(e)||+n[this.synced_field]>=+e)&&(!Number.isFinite(t)||+n[this.synced_field]<=+t)));return(n||i)&&(s=s.splice(null!=n?n:0,i||s.length)),s},this.name=e,this.filter=n,this.select=h,this.onChange=s,!o[u])throw"Invalid storage type. Expecting one of: "+Object.keys(o).join(", ");if(r||u!==o.localStorage||(console.warn("Could not set storageType to localStorage: window object missing\nStorage changed to object"),u="object"),this.storageType=u,this.patchText=f,this.patchJSON=m,!c)throw"db missing";this.db=c;const{id_fields:p,synced_field:y,throttle:b=100,batch_size:S=50}=c[this.name]._syncInfo;if(!p||!y)throw"id_fields/synced_field missing";this.id_fields=p,this.synced_field=y,this.batch_size=S,this.throttle=b,this.skipFirstTrigger=d,this.multiSubscriptions=[],this.singleSubscriptions=[],this.onError=g||function(e){console.error("Sync internal error: ",e)};const _={id_fields:p,synced_field:y,throttle:b};c[this.name]._sync(n,{select:h},{onSyncRequest:e=>{let t={c_lr:void 0,c_fr:void 0,c_count:0},n=this.getBatch(e);return n.length&&(t={c_fr:this.getRowSyncObj(n[0]),c_lr:this.getRowSyncObj(n[n.length-1]),c_count:n.length}),t},onPullRequest:async e=>this.getBatch(e),onUpdates:async e=>{var t;if("err"in e&&e.err)null===(t=this.onError)||void 0===t||t.call(this,e.err);else if("isSynced"in e&&e.isSynced&&!this.isSynced){this.isSynced=e.isSynced;let t=this.getItems().map((e=>({...e})));this.setItems([]);const n=t.map((e=>({idObj:this.getIdObj(e),delta:{...e}})));await this.upsert(n,!0)}else if("data"in e){let t=e.data.map((e=>({idObj:this.getIdObj(e),delta:e})));await this.upsert(t,!0)}else console.error("Unexpected onUpdates");return!0}}).then((e=>{function t(){return"Data may be lost. Are you sure?"}this.dbSync=e,this.wal=new i.WAL({..._,batch_size:S,onSendStart:()=>{r&&(window.onbeforeunload=t)},onSend:async(e,t)=>(await this.updatePatches(t)).length?this.dbSync.syncData(e):[],onSendEnd:()=>{r&&(window.onbeforeunload=null)}}),this.notifyWal=new i.WAL({..._,batch_size:1/0,throttle:5,onSend:async(e,t)=>{this._notifySubscribers(t.map((e=>{var t;return{delta:this.getDelta(null!==(t=e.initial)&&void 0!==t?t:{},e.current),idObj:this.getIdObj(e.current),newItem:e.current}})))}}),a()})),c[this.name].getColumns&&c[this.name].getColumns().then((e=>{this.columns=e})),this.onChange&&!this.skipFirstTrigger&&setTimeout(this.onChange,0),(0,t.debug)(this)}set multiSubscriptions(e){(0,t.debug)(e,this._multiSubscriptions),this._multiSubscriptions=e.slice(0)}get multiSubscriptions(){return this._multiSubscriptions}set singleSubscriptions(e){(0,t.debug)(e,this._singleSubscriptions),this._singleSubscriptions=e.slice(0)}get singleSubscriptions(){return this._singleSubscriptions}static create(e){return new Promise(((t,n)=>{try{const n=new a({...e,onReady:()=>{setTimeout((()=>{t(n)}),0)}})}catch(e){n(e)}}))}sync(e,t=!0){const n={$unsync:()=>this.unsubscribe(e),getItems:()=>this.getItems(),$upsert:e=>{if(e){const t=e=>({idObj:this.getIdObj(e),delta:e});Array.isArray(e)?this.upsert(e.map((e=>t(e)))):this.upsert([t(e)])}}},i={_onChange:e,handlesOnData:t,handles:n,notify:(n,i)=>{let s=[...n],r=[...i];return t&&(s=s.map(((n,i)=>{const s=(n,i)=>({...n,...this.makeSingleSyncHandles(i,e),$get:()=>s(this.getItem(i).data,i),$find:e=>s(this.getItem(e).data,e),$update:(e,t)=>this.upsert([{idObj:i,delta:e,opts:t}]).then((e=>!0)),$delete:async()=>this.delete(i),$cloneMultiSync:e=>this.sync(e,t)}),r=this.getIdObj(n);return s(n,r)}))),e(s,r)}};return this.multiSubscriptions.push(i),this.skipFirstTrigger||setTimeout((()=>{let e=this.getItems();i.notify(e,e)}),0),Object.freeze({...n})}makeSingleSyncHandles(e,n){if(!e||!n)throw"syncOne(idObj, onChange) -> MISSING idObj or onChange";const i={$get:()=>this.getItem(e).data,$find:e=>this.getItem(e).data,$unsync:()=>this.unsubscribe(n),$delete:()=>this.delete(e),$update:(n,i)=>{this.singleSubscriptions.length||this.multiSubscriptions.length||(console.warn("No sync listeners"),(0,t.debug)("nosync",this._singleSubscriptions,this._multiSubscriptions)),this.upsert([{idObj:e,delta:n,opts:i}])},$cloneSync:t=>this.syncOne(e,t),$cloneMultiSync:e=>this.sync(e,!0)};return i}syncOne(e,t,n=!0){const i=this.makeSingleSyncHandles(e,t),s={_onChange:t,idObj:e,handlesOnData:n,handles:i,notify:(e,s)=>{let r={...e};return n&&(r.$get=i.$get,r.$find=i.$find,r.$update=i.$update,r.$delete=i.$delete,r.$unsync=i.$unsync,r.$cloneSync=i.$cloneSync),t(r,s)}};return this.singleSubscriptions.push(s),setTimeout((()=>{let e=i.$get();e&&s.notify(e,e)}),0),Object.freeze({...i})}getIdStr(e){return this.id_fields.sort().map((t=>`${e[t]||""}`)).join(".")}getIdObj(e){let t={};return this.id_fields.sort().map((n=>{t[n]=e[n]})),t}getRowSyncObj(e){let t={};return[this.synced_field,...this.id_fields].sort().map((n=>{t[n]=e[n]})),t}matchesFilter(e){return Boolean(e&&(!this.filter||(0,i.isEmpty)(this.filter)||!Object.keys(this.filter).find((t=>this.filter[t]!==e[t]))))}matchesIdObj(e,t){return Boolean(e&&t&&!this.id_fields.sort().find((n=>e[n]!==t[n])))}getDelta(e,t){return(0,i.isEmpty)(e)?{...t}:Object.keys({...e,...t}).filter((e=>!this.id_fields.includes(e))).reduce(((n,i)=>{let s={};if(i in t&&t[i]!==e[i]){let n={[i]:t[i]};t[i]&&e[i]&&"object"==typeof e[i]?JSON.stringify(t[i])!==JSON.stringify(e[i])&&(s=n):s=n}return{...n,...s}}),{})}deleteAll(){this.getItems().map((e=>this.delete(e)))}get tableHandler(){const e=this.db[this.name];if(e.update&&e.updateBatch)return e}getItem(e){let t;return this.storageType===o.localStorage?t=this.getItems().find((t=>this.matchesIdObj(t,e))):this.storageType===o.array?t=this.items.find((t=>this.matchesIdObj(t,e))):(this.itemsObj=this.itemsObj||{},t={...this.itemsObj}[this.getIdStr(e)]),{data:t?{...t}:t,index:-1}}setItem(e,t,n=!1,i=!1){if(this.storageType===o.localStorage){let s=this.getItems();i?s=s.filter((t=>!this.matchesIdObj(t,e))):void 0!==t&&s[t]?s[t]=n?{...e}:{...s[t],...e}:s.push(e),r&&window.localStorage.setItem(this.name,JSON.stringify(s))}else if(this.storageType===o.array)i?this.items=this.items.filter((t=>!this.matchesIdObj(t,e))):void 0===t||this.items[t]?void 0!==t&&(this.items[t]=n?{...e}:{...this.items[t],...e}):this.items.push(e);else if(this.itemsObj=this.itemsObj||{},i)delete this.itemsObj[this.getIdStr(e)];else{let t=this.itemsObj[this.getIdStr(e)]||{};this.itemsObj[this.getIdStr(e)]=n?{...e}:{...t,...e}}}}function l(e,t){let n=Object.assign({},e);return(0,i.isObject)(e)&&(0,i.isObject)(t)&&Object.keys(t).forEach((s=>{(0,i.isObject)(t[s])?s in e?n[s]=l(e[s],t[s]):Object.assign(n,{[s]:t[s]}):Object.assign(n,{[s]:t[s]})})),n}t.SyncedTable=a,t.default=l},274:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prostgles=t.debug=void 0;const i=n(792),s="DEBUG_SYNCEDTABLE",r="undefined"!=typeof window;t.debug=function(...e){r&&window[s]&&window[s](...e)},t.prostgles=function(e,n){const{socket:s,onReady:r,onDisconnect:o,onReconnect:a,onSchemaChange:l=!0}=e;if((0,t.debug)("prostgles",{initOpts:e}),l){let e;"function"==typeof l&&(e=l),s.removeAllListeners(i.CHANNELS.SCHEMA_CHANGED),e&&s.on(i.CHANNELS.SCHEMA_CHANGED,e)}const c=i.CHANNELS._preffix;let d={},h={},u={};const f=[];let m,g=!1,p={},y=!1;function b(e,n){return(0,t.debug)("_unsubscribe",{channelName:e,handler:n}),new Promise(((t,i)=>{d[e]?(d[e].handlers=d[e].handlers.filter((e=>e!==n)),d[e].handlers.length||(s.emit(e+"unsubscribe",{},((e,t)=>{e&&console.error(e)})),s.removeListener(e,d[e].onCall),delete d[e]),t(!0)):t(!0)}))}function S({tableName:e,command:t,param1:n,param2:i},r){return new Promise(((o,a)=>{s.emit(c,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{if(e)console.error(e),a(e);else if(t){const{id_fields:e,synced_field:n,channelName:i}=t;s.emit(i,{onSyncRequest:r({})},(e=>{console.log(e)})),o({id_fields:e,synced_field:n,channelName:i})}}))}))}function _({tableName:e,command:t,param1:n,param2:i}){return new Promise(((r,o)=>{s.emit(c,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{e?(console.error(e),o(e)):t&&r(t.channelName)}))}))}async function O(e,t,n,i){const r=new Promise(((s,r)=>{const o={dbo:e,params:t,onChange:n,_onError:i,returnHandlers:e=>{s(e)}};f.push(o)})),o=async()=>{if(!g)return;const e=f.shift();if(e){const t=await async function(e,{tableName:t,command:n,param1:i,param2:r},o,a){function l(n){let s={unsubscribe:function(){return b(n,o)},filter:{...i}};return e[t].update&&(s={...s,update:function(n,s){return e[t].update(i,n,s)}}),e[t].delete&&(s={...s,delete:function(n){return e[t].delete(i,n)}}),Object.freeze(s)}g=!0;const c=Object.keys(d).find((e=>{let s=d[e];return s.tableName===t&&s.command===n&&JSON.stringify(s.param1||{})===JSON.stringify(i||{})&&JSON.stringify(s.param2||{})===JSON.stringify(r||{})}));if(c)return d[c].handlers.push(o),setTimeout((()=>{o&&(null==d?void 0:d[c].lastData)&&o(null==d?void 0:d[c].lastData)}),10),g=!1,l(c);const h=await _({tableName:t,command:n,param1:i,param2:r});let u=function(e,t){d[h]?e.data?(d[h].lastData=e.data,d[h].handlers.map((t=>{t(e.data)}))):e.err?d[h].errorHandlers.map((t=>{t(e.err)})):console.error("INTERNAL ERROR: Unexpected data format from subscription: ",e):console.warn("Orphaned subscription: ",h)},f=a||function(e){console.error(`Uncaught error within running subscription \n ${h}`,e)};return s.on(h,u),d[h]={lastData:void 0,tableName:t,command:n,param1:i,param2:r,onCall:u,handlers:[o],errorHandlers:[f],destroy:()=>{d[h]&&(Object.values(d[h]).map((e=>{e&&e.handlers&&e.handlers.map((e=>b(h,e)))})),delete d[h])}},g=!1,l(h)}(e.dbo,e.params,e.onChange,e._onError);e.returnHandlers(t)}f.length&&o()};return o(),r}return new Promise(((e,l)=>{o&&s.on("disconnect",o),s.on(i.CHANNELS.SCHEMA,(({schema:o,methods:f,tableSchema:g,auth:b,rawSQL:j,joinTables:w=[],err:v})=>{if(v)throw l(v),v;(0,t.debug)("destroySyncs",{subscriptions:d,syncedTables:h}),Object.values(d).map((e=>e.destroy())),d={},u={},Object.values(h).map((e=>{e&&e.destroy&&e.destroy()})),h={},y&&a&&a(s),y=!0;let N=JSON.parse(JSON.stringify(o)),C=JSON.parse(JSON.stringify(f)),T={},E={};if(b){if(b.pathGuard){const e=e=>{var t,n;(null==e?void 0:e.shouldReload)&&"undefined"!=typeof window&&(null===(n=null===(t=null===window||void 0===window?void 0:window.location)||void 0===t?void 0:t.reload)||void 0===n||n.call(t))};s.emit(i.CHANNELS.AUTHGUARD,JSON.stringify(window.location),((t,n)=>{e(n)})),s.removeAllListeners(i.CHANNELS.AUTHGUARD),s.on(i.CHANNELS.AUTHGUARD,(t=>{e(t)}))}E={...b},[i.CHANNELS.LOGIN,i.CHANNELS.LOGOUT,i.CHANNELS.REGISTER].map((e=>{b[e]&&(E[e]=function(t){return new Promise(((n,i)=>{s.emit(c+e,t,((e,t)=>{e?i(e):n(t)}))}))})}))}C.map((e=>{T[e]=function(...t){return new Promise(((n,r)=>{s.emit(i.CHANNELS.METHOD,{method:e,params:t},((e,t)=>{e?r(e):n(t)}))}))}})),T=Object.freeze(T),j&&(N.sql=function(e,t,n){return new Promise(((r,o)=>{s.emit(i.CHANNELS.SQL,{query:e,params:t,options:n},((e,t)=>{if(e)o(e);else if(n&&"noticeSubscription"===n.returnType&&t&&Object.keys(t).sort().join()===["socketChannel","socketUnsubChannel"].sort().join()&&!Object.values(t).find((e=>"string"!=typeof e))){const e=t,n=t=>(((e,t)=>{m=m||{config:t,listeners:[]},m.listeners.length||(s.removeAllListeners(t.socketChannel),s.on(t.socketChannel,(e=>{m&&m.listeners&&m.listeners.length?m.listeners.map((t=>{t(e)})):s.emit(t.socketUnsubChannel,{})}))),m.listeners.push(e)})(t,e),{...e,removeListener:()=>(e=>{m&&(m.listeners=m.listeners.filter((t=>t!==e)),!m.listeners.length&&m.config&&m.config.socketUnsubChannel&&s&&s.emit(m.config.socketUnsubChannel,{}))})(t)}),i={...e,addListener:n};r(i)}else if(n&&n.returnType&&"statement"===n.returnType||!t||Object.keys(t).sort().join()!==["socketChannel","socketUnsubChannel","notifChannel"].sort().join()||Object.values(t).find((e=>"string"!=typeof e)))r(t);else{const e=e=>(((e,t)=>{p=p||{},p[t.notifChannel]?p[t.notifChannel].listeners.push(e):(p[t.notifChannel]={config:t,listeners:[e]},s.removeAllListeners(t.socketChannel),s.on(t.socketChannel,(e=>{p[t.notifChannel]&&p[t.notifChannel].listeners&&p[t.notifChannel].listeners.length?p[t.notifChannel].listeners.map((t=>{t(e)})):s.emit(p[t.notifChannel].config.socketUnsubChannel,{})})))})(e,t),{...t,removeListener:()=>((e,t)=>{p&&p[t.notifChannel]&&(p[t.notifChannel].listeners=p[t.notifChannel].listeners.filter((t=>t!==e)),!p[t.notifChannel].listeners.length&&p[t.notifChannel].config&&p[t.notifChannel].config.socketUnsubChannel&&s&&(s.emit(p[t.notifChannel].config.socketUnsubChannel,{}),delete p[t.notifChannel]))})(e,t)}),n={...t,addListener:e};r(n)}}))}))});const I=e=>"[object Object]"===Object.prototype.toString.call(e),P=(e,t,n,i)=>{if(!I(e)||!I(t)||"function"!=typeof n||i&&"function"!=typeof i)throw"Expecting: ( basicFilter<object>, options<object>, onChange<function> , onError?<function>) but got something else"},A=["subscribe","subscribeOne"];Object.keys(N).forEach((e=>{Object.keys(N[e]).sort(((e,t)=>A.includes(e)-A.includes(t))).forEach((i=>{if(["find","findOne"].includes(i)&&(N[e].getJoinedTables=function(){return(w||[]).filter((t=>Array.isArray(t)&&t.includes(e))).flat().filter((t=>t!==e))}),"sync"===i){if(N[e]._syncInfo={...N[e][i]},n){N[e].getSync=(t,i={})=>n.create({name:e,filter:t,db:N,...i});const t=async(t={},i={},s)=>{const r=`${e}.${JSON.stringify(t)}.${JSON.stringify(i)}`;return h[r]||(h[r]=await n.create({...i,name:e,filter:t,db:N,onError:s})),h[r]};N[e].sync=async(e,n={handlesOnData:!0,select:"*"},i,s)=>{P(e,n,i,s);const r=await t(e,n,s);return await r.sync(i,n.handlesOnData)},N[e].syncOne=async(e,n={handlesOnData:!0},i,s)=>{P(e,n,i,s);const r=await t(e,n,s);return await r.syncOne(e,i,n.handlesOnData)}}N[e]._sync=function(n,r,o){return async function({tableName:e,command:n,param1:i,param2:r},o){const{onPullRequest:a,onSyncRequest:l,onUpdates:c}=o;function d(e){return Object.freeze({unsync:function(){!function(e,n){(0,t.debug)("_unsync",{channelName:e,triggers:n}),new Promise(((t,i)=>{u[e]&&(u[e].triggers=u[e].triggers.filter((e=>e.onPullRequest!==n.onPullRequest&&e.onSyncRequest!==n.onSyncRequest&&e.onUpdates!==n.onUpdates)),u[e].triggers.length||(s.emit(e+"unsync",{},((e,n)=>{e?i(e):t(n)})),s.removeListener(e,u[e].onCall),delete u[e]))}))}(e,o)},syncData:function(t,n,i){s.emit(e,{onSyncRequest:{...l({}),...{data:t}||{},...{deleted:n}||{}}},i?e=>{i(e)}:null)}})}const h=Object.keys(u).find((t=>{let s=u[t];return s.tableName===e&&s.command===n&&JSON.stringify(s.param1||{})===JSON.stringify(i||{})&&JSON.stringify(s.param2||{})===JSON.stringify(r||{})}));if(h)return u[h].triggers.push(o),d(h);{const f=await S({tableName:e,command:n,param1:i,param2:r},l),{channelName:m,synced_field:g,id_fields:p}=f;function y(t,n){t&&u[m]&&u[m].triggers.map((({onUpdates:i,onSyncRequest:s,onPullRequest:r})=>{t.data?Promise.resolve(i(t)).then((()=>{n&&n({ok:!0})})).catch((t=>{n?n({err:t}):console.error(e+" onUpdates error",t)})):t.onSyncRequest?Promise.resolve(s(t.onSyncRequest)).then((e=>n({onSyncRequest:e}))).catch((t=>{n?n({err:t}):console.error(e+" onSyncRequest error",t)})):t.onPullRequest?Promise.resolve(r(t.onPullRequest)).then((e=>{n({data:e})})).catch((t=>{n?n({err:t}):console.error(e+" onPullRequest error",t)})):console.log("unexpected response")}))}return u[m]={tableName:e,command:n,param1:i,param2:r,triggers:[o],syncInfo:f,onCall:y},s.on(m,y),d(m)}}({tableName:e,command:i,param1:n,param2:r},o)}}else if(A.includes(i)){N[e][i]=function(t,n,s,r){return P(t,n,s,r),O(N,{tableName:e,command:i,param1:t,param2:n},s,r)};const t="subscribeOne";i!==t&&A.includes(t)||(N[e][t]=function(t,n,s,r){return P(t,n,s,r),O(N,{tableName:e,command:i,param1:t,param2:n},(e=>{s(e[0])}),r)})}else N[e][i]=function(t,n,r){return new Promise(((o,a)=>{s.emit(c,{tableName:e,command:i,param1:t,param2:n,param3:r},((e,t)=>{e?a(e):o(t)}))}))}}))})),d&&Object.keys(d).length&&Object.keys(d).map((async e=>{try{let t=d[e];await _(t),s.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting old subscriptions",e)}})),u&&Object.keys(u).length&&Object.keys(u).filter((e=>u[e].triggers&&u[e].triggers.length)).map((async e=>{try{let t=u[e];await S(t,t.triggers[0].onSyncRequest),s.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting olf subscriptions",e)}})),w.flat().map((e=>{function t(t=!0,n,i,s){return{[t?"$leftJoin":"$innerJoin"]:e,filter:n,select:i,...s}}N.innerJoin=N.innerJoin||{},N.leftJoin=N.leftJoin||{},N.innerJoinOne=N.innerJoinOne||{},N.leftJoinOne=N.leftJoinOne||{},N.leftJoin[e]=(e,n,i={})=>t(!0,e,n,i),N.innerJoin[e]=(e,n,i={})=>t(!1,e,n,i),N.leftJoinOne[e]=(e,n,i={})=>t(!0,e,n,{...i,limit:1}),N.innerJoinOne[e]=(e,n,i={})=>t(!1,e,n,{...i,limit:1})})),(async()=>{try{await r(N,T,g,E)}catch(e){console.error("Prostgles: Error within onReady: \n",e),l(e)}e(N)})()}))}))}},792:function(e){var t;this||window,t=()=>(()=>{"use strict";var e={444:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EXISTS_KEYS=t.GeomFilter_Funcs=t.GeomFilterKeys=t.ArrayFilterOperands=t.TextFilter_FullTextSearchFilterKeys=t.TextFilterFTSKeys=t.TextFilterKeys=t.CompareInFilterKeys=t.CompareFilterKeys=void 0,t.CompareFilterKeys=["=","$eq","<>",">",">=","<=","$eq","$ne","$gt","$gte","$lte"],t.CompareInFilterKeys=["$in","$nin"],t.TextFilterKeys=["$ilike","$like"],t.TextFilterFTSKeys=["@@","@>","<@","$contains","$containedBy"],t.TextFilter_FullTextSearchFilterKeys=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"],t.ArrayFilterOperands=[...t.TextFilterFTSKeys,"&&","$overlaps"],t.GeomFilterKeys=["~","~=","@","|&>","|>>",">>","=","<<|","<<","&>","&<|","&<","&&&","&&"];const n=["ST_MakeEnvelope","ST_MakePolygon"];t.GeomFilter_Funcs=n.concat(n.map((e=>e.toLowerCase()))),t.EXISTS_KEYS=["$exists","$notExists","$existsJoined","$notExistsJoined"]},590:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.getKeys=t.isObject=t.isDefined=t.get=t.WAL=t.unpatchText=t.stableStringify=t.isEmpty=t.getTextPatch=t.asName=t.RULE_METHODS=t.CHANNELS=t.TS_PG_Types=t._PG_postgis=t._PG_date=t._PG_bool=t._PG_json=t._PG_numbers=t._PG_strings=void 0,t._PG_strings=["bpchar","char","varchar","text","citext","uuid","bytea","inet","time","timetz","interval","name"],t._PG_numbers=["int2","int4","int8","float4","float8","numeric","money","oid"],t._PG_json=["json","jsonb"],t._PG_bool=["bool"],t._PG_date=["date","timestamp","timestamptz"],t._PG_postgis=["geometry","geography"],t.TS_PG_Types={string:t._PG_strings,number:t._PG_numbers,boolean:t._PG_bool,Date:t._PG_date,"Array<number>":t._PG_numbers.map((e=>`_${e}`)),"Array<boolean>":t._PG_bool.map((e=>`_${e}`)),"Array<string>":t._PG_strings.map((e=>`_${e}`)),"Array<Object>":t._PG_json.map((e=>`_${e}`)),"Array<Date>":t._PG_date.map((e=>`_${e}`)),any:[]};const r="_psqlWS_.";t.CHANNELS={SCHEMA_CHANGED:r+"schema-changed",SCHEMA:r+"schema",DEFAULT:r,SQL:"_psqlWS_.sql",METHOD:"_psqlWS_.method",NOTICE_EV:"_psqlWS_.notice",LISTEN_EV:"_psqlWS_.listen",REGISTER:"_psqlWS_.register",LOGIN:"_psqlWS_.login",LOGOUT:"_psqlWS_.logout",AUTHGUARD:"_psqlWS_.authguard",_preffix:r},t.RULE_METHODS={getColumns:["getColumns"],getInfo:["getInfo"],insert:["insert","upsert"],update:["update","upsert","updateBatch"],select:["findOne","find","count","size"],delete:["delete","remove"],sync:["sync","unsync"],subscribe:["unsubscribe","subscribe","subscribeOne"]};var o=n(128);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return o.asName}}),Object.defineProperty(t,"getTextPatch",{enumerable:!0,get:function(){return o.getTextPatch}}),Object.defineProperty(t,"isEmpty",{enumerable:!0,get:function(){return o.isEmpty}}),Object.defineProperty(t,"stableStringify",{enumerable:!0,get:function(){return o.stableStringify}}),Object.defineProperty(t,"unpatchText",{enumerable:!0,get:function(){return o.unpatchText}}),Object.defineProperty(t,"WAL",{enumerable:!0,get:function(){return o.WAL}}),Object.defineProperty(t,"get",{enumerable:!0,get:function(){return o.get}}),Object.defineProperty(t,"isDefined",{enumerable:!0,get:function(){return o.isDefined}}),Object.defineProperty(t,"isObject",{enumerable:!0,get:function(){return o.isObject}}),Object.defineProperty(t,"getKeys",{enumerable:!0,get:function(){return o.getKeys}}),s(n(444),t)},899:(e,t)=>{function n(e,t){var n=e[0],i=e[1],l=e[2],c=e[3];n=s(n,i,l,c,t[0],7,-680876936),c=s(c,n,i,l,t[1],12,-389564586),l=s(l,c,n,i,t[2],17,606105819),i=s(i,l,c,n,t[3],22,-1044525330),n=s(n,i,l,c,t[4],7,-176418897),c=s(c,n,i,l,t[5],12,1200080426),l=s(l,c,n,i,t[6],17,-1473231341),i=s(i,l,c,n,t[7],22,-45705983),n=s(n,i,l,c,t[8],7,1770035416),c=s(c,n,i,l,t[9],12,-1958414417),l=s(l,c,n,i,t[10],17,-42063),i=s(i,l,c,n,t[11],22,-1990404162),n=s(n,i,l,c,t[12],7,1804603682),c=s(c,n,i,l,t[13],12,-40341101),l=s(l,c,n,i,t[14],17,-1502002290),n=r(n,i=s(i,l,c,n,t[15],22,1236535329),l,c,t[1],5,-165796510),c=r(c,n,i,l,t[6],9,-1069501632),l=r(l,c,n,i,t[11],14,643717713),i=r(i,l,c,n,t[0],20,-373897302),n=r(n,i,l,c,t[5],5,-701558691),c=r(c,n,i,l,t[10],9,38016083),l=r(l,c,n,i,t[15],14,-660478335),i=r(i,l,c,n,t[4],20,-405537848),n=r(n,i,l,c,t[9],5,568446438),c=r(c,n,i,l,t[14],9,-1019803690),l=r(l,c,n,i,t[3],14,-187363961),i=r(i,l,c,n,t[8],20,1163531501),n=r(n,i,l,c,t[13],5,-1444681467),c=r(c,n,i,l,t[2],9,-51403784),l=r(l,c,n,i,t[7],14,1735328473),n=o(n,i=r(i,l,c,n,t[12],20,-1926607734),l,c,t[5],4,-378558),c=o(c,n,i,l,t[8],11,-2022574463),l=o(l,c,n,i,t[11],16,1839030562),i=o(i,l,c,n,t[14],23,-35309556),n=o(n,i,l,c,t[1],4,-1530992060),c=o(c,n,i,l,t[4],11,1272893353),l=o(l,c,n,i,t[7],16,-155497632),i=o(i,l,c,n,t[10],23,-1094730640),n=o(n,i,l,c,t[13],4,681279174),c=o(c,n,i,l,t[0],11,-358537222),l=o(l,c,n,i,t[3],16,-722521979),i=o(i,l,c,n,t[6],23,76029189),n=o(n,i,l,c,t[9],4,-640364487),c=o(c,n,i,l,t[12],11,-421815835),l=o(l,c,n,i,t[15],16,530742520),n=a(n,i=o(i,l,c,n,t[2],23,-995338651),l,c,t[0],6,-198630844),c=a(c,n,i,l,t[7],10,1126891415),l=a(l,c,n,i,t[14],15,-1416354905),i=a(i,l,c,n,t[5],21,-57434055),n=a(n,i,l,c,t[12],6,1700485571),c=a(c,n,i,l,t[3],10,-1894986606),l=a(l,c,n,i,t[10],15,-1051523),i=a(i,l,c,n,t[1],21,-2054922799),n=a(n,i,l,c,t[8],6,1873313359),c=a(c,n,i,l,t[15],10,-30611744),l=a(l,c,n,i,t[6],15,-1560198380),i=a(i,l,c,n,t[13],21,1309151649),n=a(n,i,l,c,t[4],6,-145523070),c=a(c,n,i,l,t[11],10,-1120210379),l=a(l,c,n,i,t[2],15,718787259),i=a(i,l,c,n,t[9],21,-343485551),e[0]=u(n,e[0]),e[1]=u(i,e[1]),e[2]=u(l,e[2]),e[3]=u(c,e[3])}function i(e,t,n,i,s,r){return t=u(u(t,e),u(i,r)),u(t<<s|t>>>32-s,n)}function s(e,t,n,s,r,o,a){return i(t&n|~t&s,e,t,r,o,a)}function r(e,t,n,s,r,o,a){return i(t&s|n&~s,e,t,r,o,a)}function o(e,t,n,s,r,o,a){return i(t^n^s,e,t,r,o,a)}function a(e,t,n,s,r,o,a){return i(n^(t|~s),e,t,r,o,a)}function l(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}Object.defineProperty(t,"__esModule",{value:!0}),t.md5=t.md5cycle=void 0,t.md5cycle=n;var c="0123456789abcdef".split("");function d(e){for(var t="",n=0;n<4;n++)t+=c[e>>8*n+4&15]+c[e>>8*n&15];return t}function h(e){return function(e){for(var t=0;t<e.length;t++)e[t]=d(e[t]);return e.join("")}(function(e){var t,i=e.length,s=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=e.length;t+=64)n(s,l(e.substring(t-64,t)));e=e.substring(t-64);var r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t<e.length;t++)r[t>>2]|=e.charCodeAt(t)<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(n(s,r),t=0;t<16;t++)r[t]=0;return r[14]=8*i,n(s,r),s}(e))}function u(e,t){return e+t&4294967295}t.md5=h,h("hello")},128:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getKeys=t.isDefined=t.isObject=t.get=t.isEmpty=t.WAL=t.unpatchText=t.getTextPatch=t.stableStringify=t.asName=void 0;const i=n(899);function s(e){for(var t in e)return!1;return!0}t.asName=function(e){if(null==e||!e.toString||!e.toString())throw"Expecting a non empty string";return`"${e.toString().replace(/"/g,'""')}"`},t.stableStringify=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var n,i="boolean"==typeof t.cycles&&t.cycles,s=t.cmp&&(n=t.cmp,function(e){return function(t,i){var s={key:t,value:e[t]},r={key:i,value:e[i]};return n(s,r)}}),r=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var n,o;if(Array.isArray(t)){for(o="[",n=0;n<t.length;n++)n&&(o+=","),o+=e(t[n])||"null";return o+"]"}if(null===t)return"null";if(-1!==r.indexOf(t)){if(i)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var a=r.push(t)-1,l=Object.keys(t).sort(s&&s(t));for(o="",n=0;n<l.length;n++){var c=l[n],d=e(t[c]);d&&(o&&(o+=","),o+=JSON.stringify(c)+":"+d)}return r.splice(a,1),"{"+o+"}"}}(e)},t.getTextPatch=function(e,t){if(!(e&&t&&e.trim().length&&t.trim().length))return t;if(e===t)return{from:0,to:0,text:"",md5:(0,i.md5)(t)};function n(n=1){let i=n<1?-1:0,s=!1;for(;!s&&Math.abs(i)<=t.length;){const r=n<1?[i]:[0,i];e.slice(...r)!==t.slice(...r)?s=!0:i+=1*Math.sign(n)}return i}let s=n()-1,r=e.length+n(-1)+1,o=t.length+n(-1)+1;return{from:s,to:r,text:t.slice(s,o),md5:(0,i.md5)(t)}},t.unpatchText=function(e,t){if(!t||"string"==typeof t)return t;const{from:n,to:s,text:r,md5:o}=t;if(null===r||null===e)return r;let a=e.slice(0,n)+r+e.slice(s);if(o&&(0,i.md5)(a)!==o)throw"Patch text error: Could not match md5 hash: (original/result) \n"+e+"\n"+a;return a},t.WAL=class{constructor(e){if(this.changed={},this.sending={},this.sentHistory={},this.callbacks=[],this.sort=(e,t)=>{const{orderBy:n}=this.options;return n&&e&&t&&n.map((n=>{if(!(n.fieldName in e)||!(n.fieldName in t))throw"Replication error: \n some orderBy fields missing from data";let i=n.asc?e[n.fieldName]:t[n.fieldName],s=n.asc?t[n.fieldName]:e[n.fieldName],r=+i-+s,o=i<s?-1:i==s?0:1;return"number"===n.tsDataType&&Number.isFinite(r)?r:o})).find((e=>e))||0},this.isInHistory=e=>{if(!e)throw"Provide item";const t=e[this.options.synced_field];if(!Number.isFinite(+t))throw"Provided item Synced field value is missing/invalid ";const n=this.sentHistory[this.getIdStr(e)],i=n?.[this.options.synced_field];if(n){if(!Number.isFinite(+i))throw"Provided historic item Synced field value is missing/invalid";if(+i==+t)return!0}return!1},this.addData=e=>{s(this.changed)&&this.options.onSendStart&&this.options.onSendStart(),e.map((e=>{var t;const{initial:n,current:i}={...e};if(!i)throw"Expecting { current: object, initial?: object }";const s=this.getIdStr(i);this.changed??(this.changed={}),(t=this.changed)[s]??(t[s]={initial:n,current:i}),this.changed[s].current={...this.changed[s].current,...i}})),this.sendItems()},this.isOnSending=!1,this.isSendingTimeout=void 0,this.willDeleteHistory=void 0,this.sendItems=async()=>{const{DEBUG_MODE:e,onSend:t,onSendEnd:n,batch_size:i,throttle:r,historyAgeSeconds:o=2}=this.options;if(this.isSendingTimeout||this.sending&&!s(this.sending))return;if(!this.changed||s(this.changed))return;let a,l=[],c=[],d={};Object.keys(this.changed).sort(((e,t)=>this.sort(this.changed[e].current,this.changed[t].current))).slice(0,i).map((e=>{let t={...this.changed[e]};this.sending[e]={...t},c.push({...t}),d[e]={...t.current},delete this.changed[e]})),l=c.map((e=>e.current)),e&&console.log(this.options.id," SENDING lr->",l[l.length-1]),this.isSendingTimeout||(this.isSendingTimeout=setTimeout((()=>{this.isSendingTimeout=void 0,s(this.changed)||this.sendItems()}),r)),this.isOnSending=!0;try{await t(l,c),o&&(this.sentHistory={...this.sentHistory,...d},this.willDeleteHistory||(this.willDeleteHistory=setTimeout((()=>{this.willDeleteHistory=void 0,this.sentHistory={}}),1e3*o)))}catch(e){a=e,console.error("WAL onSend failed:",e,l,c)}if(this.isOnSending=!1,this.callbacks.length){const e=Object.keys(this.sending);this.callbacks.forEach(((t,n)=>{t.idStrs=t.idStrs.filter((t=>e.includes(t))),t.idStrs.length||t.cb(a)})),this.callbacks=this.callbacks.filter((e=>e.idStrs.length))}this.sending={},e&&console.log(this.options.id," SENT lr->",l[l.length-1]),s(this.changed)?n&&n(l,c,a):this.sendItems()},this.options={...e},!this.options.orderBy){const{synced_field:t,id_fields:n}=e;this.options.orderBy=[t,...n.sort()].map((e=>({fieldName:e,tsDataType:e===t?"number":"string",asc:!0})))}}isSending(){const e=this.isOnSending||!(s(this.sending)&&s(this.changed));return this.options.DEBUG_MODE&&console.log(this.options.id," CHECKING isSending ->",e),e}getIdStr(e){return this.options.id_fields.sort().map((t=>`${e[t]||""}`)).join(".")}getIdObj(e){let t={};return this.options.id_fields.sort().map((n=>{t[n]=e[n]})),t}getDeltaObj(e){let t={};return Object.keys(e).map((n=>{this.options.id_fields.includes(n)||(t[n]=e[n])})),t}},t.isEmpty=s,t.get=function(e,t){let n=t,i=e;return e?("string"==typeof n&&(n=n.split(".")),n.reduce(((e,t)=>e&&e[t]?e[t]:void 0),i)):e},t.isObject=function(e){return Boolean(e&&"object"==typeof e&&!Array.isArray(e))},t.isDefined=function(e){return null!=e},t.getKeys=function(e){return Object.keys(e)}}},t={};return function n(i){var s=t[i];if(void 0!==s)return s.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}(590)})(),e.exports=t()}},t={};function n(i){var s=t[i];if(void 0!==s)return s.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}var i={};return(()=>{"use strict";var e=i;Object.defineProperty(e,"__esModule",{value:!0}),e.prostgles=void 0;const t=n(274),s=n(133);e.prostgles=function(e){return(0,t.prostgles)(e,s.SyncedTable)}})(),i})()));
|
|
1
|
+
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(this||window,(()=>(()=>{var e={133:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SyncedTable=t.debug=void 0;const i=n(792),s="DEBUG_SYNCEDTABLE",r="undefined"!=typeof window;t.debug=function(...e){r&&window[s]&&window[s](...e)};const o={array:"array",localStorage:"localStorage",object:"object"};class a{constructor({name:e,filter:n,onChange:s,onReady:a,db:c,skipFirstTrigger:u=!1,select:h="*",storageType:d="object",patchText:f=!1,patchJSON:m=!1,onError:g}){if(this.throttle=100,this.batch_size=50,this.skipFirstTrigger=!1,this.columns=[],this._multiSubscriptions=[],this._singleSubscriptions=[],this.items=[],this.itemsObj={},this.isSynced=!1,this.updatePatches=async e=>{var t,n;let s=e.map((e=>e.current)),r=[],o=[];if(this.columns&&this.columns.length&&(null===(t=this.tableHandler)||void 0===t?void 0:t.updateBatch)&&(this.patchText||this.patchJSON)){const t=this.columns.filter((e=>"text"===e.data_type));if(this.patchText&&t.length){s=[];const n=[this.synced_field,...this.id_fields];await Promise.all(e.slice(0).map((async(e,a)=>{const{current:l,initial:c}={...e};let u;c&&(t.map((e=>{!n.includes(e.name)&&e.name in l&&(null!=u||(u={...l}),u[e.name]=(0,i.getTextPatch)(c[e.name],l[e.name]))})),u&&this.wal&&(o.push(u),r.push([this.wal.getIdObj(u),this.wal.getDeltaObj(u)]))),u||s.push(l)})))}}if(r.length)try{await(null===(n=this.tableHandler)||void 0===n?void 0:n.updateBatch(r))}catch(e){console.log("failed to patch update",e),s=s.concat(o)}return s.filter((e=>e))},this._notifySubscribers=(e=[])=>{if(!this.isSynced)return;let t=[],n=[],i=[];if(e.map((({idObj:e,newItem:s,delta:r})=>{this.singleSubscriptions.filter((t=>this.matchesIdObj(t.idObj,e))).map((async e=>{try{await e.notify(s,r)}catch(e){console.error("SyncedTable failed to notify: ",e)}})),this.matchesFilter(s)&&(t.push(s),n.push(r),i.push(e))})),this.onChange||this.multiSubscriptions.length){let e=[],i=[];if(this.getItems().map((s=>{e.push({...s});const r=t.findIndex((e=>this.matchesIdObj(s,e)));i.push(n[r])})),this.onChange)try{this.onChange(e,i)}catch(e){console.error("SyncedTable failed to notify onChange: ",e)}this.multiSubscriptions.map((async t=>{try{await t.notify(e,i)}catch(e){console.error("SyncedTable failed to notify: ",e)}}))}},this.unsubscribe=e=>(this.singleSubscriptions=this.singleSubscriptions.filter((t=>t._onChange!==e)),this.multiSubscriptions=this.multiSubscriptions.filter((t=>t._onChange!==e)),(0,t.debug)("unsubscribe",this),"ok"),this.unsync=()=>{this.dbSync&&this.dbSync.unsync&&this.dbSync.unsync()},this.destroy=()=>{this.unsync(),this.multiSubscriptions=[],this.singleSubscriptions=[],this.itemsObj={},this.items=[],this.onChange=void 0},this.delete=async(e,t=!1)=>{var n;const i=this.getIdObj(e);return this.setItem(i,void 0,!0,!0),!t&&(null===(n=this.tableHandler)||void 0===n?void 0:n.delete)&&await this.tableHandler.delete(i),this._notifySubscribers(),!0},this.checkItemCols=e=>{if(this.columns&&this.columns.length){const t=Object.keys({...e}).filter((e=>!this.columns.find((t=>t.name===e))));if(t.length)throw"Unexpected columns in sync item update: "+t.join(", ")}},this.upsert=async(e,t=!1)=>{var n,s;if(!(e&&e.length||t))throw"No data provided for upsert";let r,o=[],a=[];await Promise.all(e.map((async(e,n)=>{var s;let c={...e.idObj},u={...e.delta};Object.keys(u).map((e=>{void 0===u[e]&&(u[e]=null)})),t||this.checkItemCols({...e.delta,...e.idObj});let h=this.getItem(c),d=h.index,f=h.data;!t&&!(0,i.isEmpty)(u)||(0,i.isEmpty)(f)||(u=this.getDelta(f||{},u)),t||(u[this.synced_field]=Date.now());let m={...f,...u,...c};f&&!t&&(null===(s=e.opts)||void 0===s?void 0:s.deepMerge)&&(m=l({...f,...c},{...u})),r=f?f[this.synced_field]<m[this.synced_field]?"updated":"unchanged":"inserted",this.setItem(m,d);let g={idObj:c,delta:u,oldItem:f,newItem:m,status:r,from_server:t};return t||a.push({initial:f,current:{...m}}),g.delta&&!(0,i.isEmpty)(g.delta)&&o.push(g),!0}))).catch((e=>{console.error("SyncedTable failed upsert: ",e)})),null===(n=this.notifyWal)||void 0===n||n.addData(o.map((e=>({initial:e.oldItem,current:e.newItem})))),!t&&a.length&&(null===(s=this.wal)||void 0===s||s.addData(a))},this.setItems=e=>{if(this.storageType===o.localStorage){if(!r)throw"Cannot access window object. Choose another storage method (array OR object)";window.localStorage.setItem(this.name,JSON.stringify(e))}else this.storageType===o.array?this.items=e:this.itemsObj=e.reduce(((e,t)=>({...e,[this.getIdStr(t)]:{...t}})),{})},this.getItems=()=>{let e=[];if(this.storageType===o.localStorage){if(!r)throw"Cannot access window object. Choose another storage method (array OR object)";let t=window.localStorage.getItem(this.name);if(t)try{e=JSON.parse(t)}catch(e){console.error(e)}}else e=this.storageType===o.array?this.items.map((e=>({...e}))):Object.values({...this.itemsObj});if(!this.id_fields||!this.synced_field)throw"id_fields AND/OR synced_field missing";{const t=[this.synced_field,...this.id_fields.sort()];e=e.filter((e=>!this.filter||!(0,i.getKeys)(this.filter).find((t=>e[t]!==this.filter[t])))).sort(((e,n)=>t.map((t=>e[t]<n[t]?-1:e[t]>n[t]?1:0)).find((e=>e))))}return e.map((e=>({...e})))},this.getBatch=({from_synced:e,to_synced:t,offset:n,limit:i}={offset:0,limit:void 0})=>{let s=this.getItems().map((e=>({...e}))).filter((n=>(!Number.isFinite(e)||+n[this.synced_field]>=+e)&&(!Number.isFinite(t)||+n[this.synced_field]<=+t)));return(n||i)&&(s=s.splice(null!=n?n:0,i||s.length)),s},this.name=e,this.filter=n,this.select=h,this.onChange=s,!o[d])throw"Invalid storage type. Expecting one of: "+Object.keys(o).join(", ");if(r||d!==o.localStorage||(console.warn("Could not set storageType to localStorage: window object missing\nStorage changed to object"),d="object"),this.storageType=d,this.patchText=f,this.patchJSON=m,!c)throw"db missing";this.db=c;const{id_fields:p,synced_field:y,throttle:b=100,batch_size:S=50}=c[this.name]._syncInfo;if(!p||!y)throw"id_fields/synced_field missing";this.id_fields=p,this.synced_field=y,this.batch_size=S,this.throttle=b,this.skipFirstTrigger=u,this.multiSubscriptions=[],this.singleSubscriptions=[],this.onError=g||function(e){console.error("Sync internal error: ",e)};const _={id_fields:p,synced_field:y,throttle:b};c[this.name]._sync(n,{select:h},{onSyncRequest:e=>{let t={c_lr:void 0,c_fr:void 0,c_count:0},n=this.getBatch(e);return n.length&&(t={c_fr:this.getRowSyncObj(n[0]),c_lr:this.getRowSyncObj(n[n.length-1]),c_count:n.length}),t},onPullRequest:async e=>this.getBatch(e),onUpdates:async e=>{var t;if("err"in e&&e.err)null===(t=this.onError)||void 0===t||t.call(this,e.err);else if("isSynced"in e&&e.isSynced&&!this.isSynced){this.isSynced=e.isSynced;let t=this.getItems().map((e=>({...e})));this.setItems([]);const n=t.map((e=>({idObj:this.getIdObj(e),delta:{...e}})));await this.upsert(n,!0)}else if("data"in e){let t=e.data.map((e=>({idObj:this.getIdObj(e),delta:e})));await this.upsert(t,!0)}else console.error("Unexpected onUpdates");return!0}}).then((e=>{function t(){return"Data may be lost. Are you sure?"}this.dbSync=e,this.wal=new i.WAL({..._,batch_size:S,onSendStart:()=>{r&&(window.onbeforeunload=t)},onSend:async(e,t)=>(await this.updatePatches(t)).length?this.dbSync.syncData(e):[],onSendEnd:()=>{r&&(window.onbeforeunload=null)}}),this.notifyWal=new i.WAL({..._,batch_size:1/0,throttle:5,onSend:async(e,t)=>{this._notifySubscribers(t.map((e=>{var t;return{delta:this.getDelta(null!==(t=e.initial)&&void 0!==t?t:{},e.current),idObj:this.getIdObj(e.current),newItem:e.current}})))}}),a()})),c[this.name].getColumns&&c[this.name].getColumns().then((e=>{this.columns=e})),this.onChange&&!this.skipFirstTrigger&&setTimeout(this.onChange,0),(0,t.debug)(this)}set multiSubscriptions(e){(0,t.debug)(e,this._multiSubscriptions),this._multiSubscriptions=e.slice(0)}get multiSubscriptions(){return this._multiSubscriptions}set singleSubscriptions(e){(0,t.debug)(e,this._singleSubscriptions),this._singleSubscriptions=e.slice(0)}get singleSubscriptions(){return this._singleSubscriptions}static create(e){return new Promise(((t,n)=>{try{const n=new a({...e,onReady:()=>{setTimeout((()=>{t(n)}),0)}})}catch(e){n(e)}}))}sync(e,t=!0){const n={$unsync:()=>this.unsubscribe(e),getItems:()=>this.getItems(),$upsert:e=>{if(e){const t=e=>({idObj:this.getIdObj(e),delta:e});Array.isArray(e)?this.upsert(e.map((e=>t(e)))):this.upsert([t(e)])}}},i={_onChange:e,handlesOnData:t,handles:n,notify:(n,i)=>{let s=[...n],r=[...i];return t&&(s=s.map(((n,i)=>{const s=(n,i)=>({...n,...this.makeSingleSyncHandles(i,e),$get:()=>s(this.getItem(i).data,i),$find:e=>s(this.getItem(e).data,e),$update:(e,t)=>this.upsert([{idObj:i,delta:e,opts:t}]).then((e=>!0)),$delete:async()=>this.delete(i),$cloneMultiSync:e=>this.sync(e,t)}),r=this.getIdObj(n);return s(n,r)}))),e(s,r)}};return this.multiSubscriptions.push(i),this.skipFirstTrigger||setTimeout((()=>{let e=this.getItems();i.notify(e,e)}),0),Object.freeze({...n})}makeSingleSyncHandles(e,n){if(!e||!n)throw"syncOne(idObj, onChange) -> MISSING idObj or onChange";const i={$get:()=>this.getItem(e).data,$find:e=>this.getItem(e).data,$unsync:()=>this.unsubscribe(n),$delete:()=>this.delete(e),$update:(n,i)=>{this.singleSubscriptions.length||this.multiSubscriptions.length||(console.warn("No sync listeners"),(0,t.debug)("nosync",this._singleSubscriptions,this._multiSubscriptions)),this.upsert([{idObj:e,delta:n,opts:i}])},$cloneSync:t=>this.syncOne(e,t),$cloneMultiSync:e=>this.sync(e,!0)};return i}syncOne(e,t,n=!0){const i=this.makeSingleSyncHandles(e,t),s={_onChange:t,idObj:e,handlesOnData:n,handles:i,notify:(e,s)=>{let r={...e};return n&&(r.$get=i.$get,r.$find=i.$find,r.$update=i.$update,r.$delete=i.$delete,r.$unsync=i.$unsync,r.$cloneSync=i.$cloneSync),t(r,s)}};return this.singleSubscriptions.push(s),setTimeout((()=>{let e=i.$get();e&&s.notify(e,e)}),0),Object.freeze({...i})}getIdStr(e){return this.id_fields.sort().map((t=>`${e[t]||""}`)).join(".")}getIdObj(e){let t={};return this.id_fields.sort().map((n=>{t[n]=e[n]})),t}getRowSyncObj(e){let t={};return[this.synced_field,...this.id_fields].sort().map((n=>{t[n]=e[n]})),t}matchesFilter(e){return Boolean(e&&(!this.filter||(0,i.isEmpty)(this.filter)||!Object.keys(this.filter).find((t=>this.filter[t]!==e[t]))))}matchesIdObj(e,t){return Boolean(e&&t&&!this.id_fields.sort().find((n=>e[n]!==t[n])))}getDelta(e,t){return(0,i.isEmpty)(e)?{...t}:Object.keys({...e,...t}).filter((e=>!this.id_fields.includes(e))).reduce(((n,i)=>{let s={};if(i in t&&t[i]!==e[i]){let n={[i]:t[i]};t[i]&&e[i]&&"object"==typeof e[i]?JSON.stringify(t[i])!==JSON.stringify(e[i])&&(s=n):s=n}return{...n,...s}}),{})}deleteAll(){this.getItems().map((e=>this.delete(e)))}get tableHandler(){const e=this.db[this.name];if(e.update&&e.updateBatch)return e}getItem(e){let t;return this.storageType===o.localStorage?t=this.getItems().find((t=>this.matchesIdObj(t,e))):this.storageType===o.array?t=this.items.find((t=>this.matchesIdObj(t,e))):(this.itemsObj=this.itemsObj||{},t={...this.itemsObj}[this.getIdStr(e)]),{data:t?{...t}:t,index:-1}}setItem(e,t,n=!1,i=!1){if(this.storageType===o.localStorage){let s=this.getItems();i?s=s.filter((t=>!this.matchesIdObj(t,e))):void 0!==t&&s[t]?s[t]=n?{...e}:{...s[t],...e}:s.push(e),r&&window.localStorage.setItem(this.name,JSON.stringify(s))}else if(this.storageType===o.array)i?this.items=this.items.filter((t=>!this.matchesIdObj(t,e))):void 0===t||this.items[t]?void 0!==t&&(this.items[t]=n?{...e}:{...this.items[t],...e}):this.items.push(e);else if(this.itemsObj=this.itemsObj||{},i)delete this.itemsObj[this.getIdStr(e)];else{let t=this.itemsObj[this.getIdStr(e)]||{};this.itemsObj[this.getIdStr(e)]=n?{...e}:{...t,...e}}}}function l(e,t){let n=Object.assign({},e);return(0,i.isObject)(e)&&(0,i.isObject)(t)&&Object.keys(t).forEach((s=>{(0,i.isObject)(t[s])?s in e?n[s]=l(e[s],t[s]):Object.assign(n,{[s]:t[s]}):Object.assign(n,{[s]:t[s]})})),n}t.SyncedTable=a,t.default=l},274:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prostgles=t.debug=void 0;const i=n(792),s="DEBUG_SYNCEDTABLE",r="undefined"!=typeof window;t.debug=function(...e){r&&window[s]&&window[s](...e)},t.prostgles=function(e,n){const{socket:s,onReady:r,onDisconnect:a,onReconnect:l,onSchemaChange:c=!0}=e;if((0,t.debug)("prostgles",{initOpts:e}),c){let e;"function"==typeof c&&(e=c),s.removeAllListeners(i.CHANNELS.SCHEMA_CHANGED),e&&s.on(i.CHANNELS.SCHEMA_CHANGED,e)}const u=i.CHANNELS._preffix;let h,d={},f={},m={},g=!1,p={},y=!1;function b(e,n){return(0,t.debug)("_unsubscribe",{channelName:e,handler:n}),new Promise(((t,i)=>{d[e]?(d[e].handlers=d[e].handlers.filter((e=>e!==n)),d[e].handlers.length||(s.emit(e+"unsubscribe",{},((e,t)=>{e&&console.error(e)})),s.removeListener(e,d[e].onCall),delete d[e]),t(!0)):t(!0)}))}function S({tableName:e,command:t,param1:n,param2:i},r){return new Promise(((o,a)=>{s.emit(u,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{if(e)console.error(e),a(e);else if(t){const{id_fields:e,synced_field:n,channelName:i}=t;s.emit(i,{onSyncRequest:r({})},(e=>{console.log(e)})),o({id_fields:e,synced_field:n,channelName:i})}}))}))}function _({tableName:e,command:t,param1:n,param2:i}){return new Promise(((r,o)=>{s.emit(u,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{e?(console.error(e),o(e)):t&&r(t.channelName)}))}))}const O=new o((async function({tableName:e,command:n,param1:i,param2:r},o){const{onPullRequest:a,onSyncRequest:l,onUpdates:c}=o;function u(e){return Object.freeze({unsync:function(){!function(e,n){(0,t.debug)("_unsync",{channelName:e,triggers:n}),new Promise(((t,i)=>{m[e]&&(m[e].triggers=m[e].triggers.filter((e=>e.onPullRequest!==n.onPullRequest&&e.onSyncRequest!==n.onSyncRequest&&e.onUpdates!==n.onUpdates)),m[e].triggers.length||(s.emit(e+"unsync",{},((e,n)=>{e?i(e):t(n)})),s.removeListener(e,m[e].onCall),delete m[e]))}))}(e,o)},syncData:function(t,n,i){s.emit(e,{onSyncRequest:{...l({}),...{data:t}||{},...{deleted:n}||{}}},i?e=>{i(e)}:null)}})}const h=Object.keys(m).find((t=>{let s=m[t];return s.tableName===e&&s.command===n&&JSON.stringify(s.param1||{})===JSON.stringify(i||{})&&JSON.stringify(s.param2||{})===JSON.stringify(r||{})}));if(h)return m[h].triggers.push(o),u(h);{const d=await S({tableName:e,command:n,param1:i,param2:r},l),{channelName:f,synced_field:g,id_fields:p}=d;function y(t,n){t&&m[f]&&m[f].triggers.map((({onUpdates:i,onSyncRequest:s,onPullRequest:r})=>{t.data?Promise.resolve(i(t)).then((()=>{n&&n({ok:!0})})).catch((t=>{n?n({err:t}):console.error(e+" onUpdates error",t)})):t.onSyncRequest?Promise.resolve(s(t.onSyncRequest)).then((e=>n({onSyncRequest:e}))).catch((t=>{n?n({err:t}):console.error(e+" onSyncRequest error",t)})):t.onPullRequest?Promise.resolve(r(t.onPullRequest)).then((e=>{n({data:e})})).catch((t=>{n?n({err:t}):console.error(e+" onPullRequest error",t)})):console.log("unexpected response")}))}return m[f]={tableName:e,command:n,param1:i,param2:r,triggers:[o],syncInfo:d,onCall:y},s.on(f,y),u(f)}})),j=new o((async function(e,{tableName:t,command:n,param1:i,param2:r},o,a){function l(n){let s={unsubscribe:function(){return b(n,o)},filter:{...i}};return e[t].update&&(s={...s,update:function(n,s){return e[t].update(i,n,s)}}),e[t].delete&&(s={...s,delete:function(n){return e[t].delete(i,n)}}),Object.freeze(s)}g=!0;const c=Object.keys(d).find((e=>{let s=d[e];return s.tableName===t&&s.command===n&&JSON.stringify(s.param1||{})===JSON.stringify(i||{})&&JSON.stringify(s.param2||{})===JSON.stringify(r||{})}));if(c)return d[c].handlers.push(o),setTimeout((()=>{o&&(null==d?void 0:d[c].lastData)&&o(null==d?void 0:d[c].lastData)}),10),g=!1,l(c);const u=await _({tableName:t,command:n,param1:i,param2:r});let h=function(e,t){d[u]?e.data?(d[u].lastData=e.data,d[u].handlers.map((t=>{t(e.data)}))):e.err?d[u].errorHandlers.map((t=>{t(e.err)})):console.error("INTERNAL ERROR: Unexpected data format from subscription: ",e):console.warn("Orphaned subscription: ",u)},f=a||function(e){console.error(`Uncaught error within running subscription \n ${u}`,e)};return s.on(u,h),d[u]={lastData:void 0,tableName:t,command:n,param1:i,param2:r,onCall:h,handlers:[o],errorHandlers:[f],destroy:()=>{d[u]&&(Object.values(d[u]).map((e=>{e&&e.handlers&&e.handlers.map((e=>b(u,e)))})),delete d[u])}},g=!1,l(u)}));async function w(e,t,n,i){return j.run([e,t,n,i])}return new Promise(((e,o)=>{a&&s.on("disconnect",a),s.on(i.CHANNELS.SCHEMA,(({schema:a,methods:c,tableSchema:g,auth:b,rawSQL:j,joinTables:v=[],err:N})=>{if(N)throw o(N),N;(0,t.debug)("destroySyncs",{subscriptions:d,syncedTables:f}),Object.values(d).map((e=>e.destroy())),d={},m={},Object.values(f).map((e=>{e&&e.destroy&&e.destroy()})),f={},y&&l&&l(s),y=!0;let C=JSON.parse(JSON.stringify(a)),T=JSON.parse(JSON.stringify(c)),E={},I={};if(b){if(b.pathGuard){const e=e=>{var t,n;(null==e?void 0:e.shouldReload)&&"undefined"!=typeof window&&(null===(n=null===(t=null===window||void 0===window?void 0:window.location)||void 0===t?void 0:t.reload)||void 0===n||n.call(t))};s.emit(i.CHANNELS.AUTHGUARD,JSON.stringify(window.location),((t,n)=>{e(n)})),s.removeAllListeners(i.CHANNELS.AUTHGUARD),s.on(i.CHANNELS.AUTHGUARD,(t=>{e(t)}))}I={...b},[i.CHANNELS.LOGIN,i.CHANNELS.LOGOUT,i.CHANNELS.REGISTER].map((e=>{b[e]&&(I[e]=function(t){return new Promise(((n,i)=>{s.emit(u+e,t,((e,t)=>{e?i(e):n(t)}))}))})}))}T.map((e=>{E[e]=function(...t){return new Promise(((n,r)=>{s.emit(i.CHANNELS.METHOD,{method:e,params:t},((e,t)=>{e?r(e):n(t)}))}))}})),E=Object.freeze(E),j&&(C.sql=function(e,t,n){return new Promise(((r,o)=>{s.emit(i.CHANNELS.SQL,{query:e,params:t,options:n},((e,t)=>{if(e)o(e);else if(n&&"noticeSubscription"===n.returnType&&t&&Object.keys(t).sort().join()===["socketChannel","socketUnsubChannel"].sort().join()&&!Object.values(t).find((e=>"string"!=typeof e))){const e=t,n=t=>(((e,t)=>{h=h||{config:t,listeners:[]},h.listeners.length||(s.removeAllListeners(t.socketChannel),s.on(t.socketChannel,(e=>{h&&h.listeners&&h.listeners.length?h.listeners.map((t=>{t(e)})):s.emit(t.socketUnsubChannel,{})}))),h.listeners.push(e)})(t,e),{...e,removeListener:()=>(e=>{h&&(h.listeners=h.listeners.filter((t=>t!==e)),!h.listeners.length&&h.config&&h.config.socketUnsubChannel&&s&&s.emit(h.config.socketUnsubChannel,{}))})(t)}),i={...e,addListener:n};r(i)}else if(n&&n.returnType&&"statement"===n.returnType||!t||Object.keys(t).sort().join()!==["socketChannel","socketUnsubChannel","notifChannel"].sort().join()||Object.values(t).find((e=>"string"!=typeof e)))r(t);else{const e=e=>(((e,t)=>{p=p||{},p[t.notifChannel]?p[t.notifChannel].listeners.push(e):(p[t.notifChannel]={config:t,listeners:[e]},s.removeAllListeners(t.socketChannel),s.on(t.socketChannel,(e=>{p[t.notifChannel]&&p[t.notifChannel].listeners&&p[t.notifChannel].listeners.length?p[t.notifChannel].listeners.map((t=>{t(e)})):s.emit(p[t.notifChannel].config.socketUnsubChannel,{})})))})(e,t),{...t,removeListener:()=>((e,t)=>{p&&p[t.notifChannel]&&(p[t.notifChannel].listeners=p[t.notifChannel].listeners.filter((t=>t!==e)),!p[t.notifChannel].listeners.length&&p[t.notifChannel].config&&p[t.notifChannel].config.socketUnsubChannel&&s&&(s.emit(p[t.notifChannel].config.socketUnsubChannel,{}),delete p[t.notifChannel]))})(e,t)}),n={...t,addListener:e};r(n)}}))}))});const P=e=>"[object Object]"===Object.prototype.toString.call(e),A=(e,t,n,i)=>{if(!P(e)||!P(t)||"function"!=typeof n||i&&"function"!=typeof i)throw"Expecting: ( basicFilter<object>, options<object>, onChange<function> , onError?<function>) but got something else"},x=["subscribe","subscribeOne"];Object.keys(C).forEach((e=>{Object.keys(C[e]).sort(((e,t)=>x.includes(e)-x.includes(t))).forEach((t=>{if(["find","findOne"].includes(t)&&(C[e].getJoinedTables=function(){return(v||[]).filter((t=>Array.isArray(t)&&t.includes(e))).flat().filter((t=>t!==e))}),"sync"===t){if(C[e]._syncInfo={...C[e][t]},n){C[e].getSync=(t,i={})=>n.create({name:e,filter:t,db:C,...i});const t=async(t={},i={},s)=>{const r=`${e}.${JSON.stringify(t)}.${JSON.stringify(i)}`;return f[r]||(f[r]=await n.create({...i,name:e,filter:t,db:C,onError:s})),f[r]};C[e].sync=async(e,n={handlesOnData:!0,select:"*"},i,s)=>{A(e,n,i,s);const r=await t(e,n,s);return await r.sync(i,n.handlesOnData)},C[e].syncOne=async(e,n={handlesOnData:!0},i,s)=>{A(e,n,i,s);const r=await t(e,n,s);return await r.syncOne(e,i,n.handlesOnData)}}C[e]._sync=function(n,i,s){return async function(e,t){return O.run([e,t])}({tableName:e,command:t,param1:n,param2:i},s)}}else if(x.includes(t)){C[e][t]=function(n,i,s,r){return A(n,i,s,r),w(C,{tableName:e,command:t,param1:n,param2:i},s,r)};const n="subscribeOne";t!==n&&x.includes(n)||(C[e][n]=function(n,i,s,r){return A(n,i,s,r),w(C,{tableName:e,command:t,param1:n,param2:i},(e=>{s(e[0])}),r)})}else C[e][t]=function(n,i,r){return new Promise(((o,a)=>{s.emit(u,{tableName:e,command:t,param1:n,param2:i,param3:r},((e,t)=>{e?a(e):o(t)}))}))}}))})),d&&Object.keys(d).length&&Object.keys(d).map((async e=>{try{let t=d[e];await _(t),s.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting old subscriptions",e)}})),m&&Object.keys(m).length&&Object.keys(m).filter((e=>m[e].triggers&&m[e].triggers.length)).map((async e=>{try{let t=m[e];await S(t,t.triggers[0].onSyncRequest),s.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting olf subscriptions",e)}})),v.flat().map((e=>{function t(t=!0,n,i,s){return{[t?"$leftJoin":"$innerJoin"]:e,filter:n,select:i,...s}}C.innerJoin=C.innerJoin||{},C.leftJoin=C.leftJoin||{},C.innerJoinOne=C.innerJoinOne||{},C.leftJoinOne=C.leftJoinOne||{},C.leftJoin[e]=(e,n,i={})=>t(!0,e,n,i),C.innerJoin[e]=(e,n,i={})=>t(!1,e,n,i),C.leftJoinOne[e]=(e,n,i={})=>t(!0,e,n,{...i,limit:1}),C.innerJoinOne[e]=(e,n,i={})=>t(!1,e,n,{...i,limit:1})})),(async()=>{try{await r(C,E,g,I)}catch(e){console.error("Prostgles: Error within onReady: \n",e),o(e)}e(C)})()}))}))};class o{constructor(e){this.queue=[],this.isRunning=!1,this.func=e}async run(e){const t=new Promise(((t,n)=>{const i={arguments:e,onResult:t};this.queue.push(i)})),n=async()=>{if(this.isRunning)return;this.isRunning=!0;const e=this.queue.shift();if(e){const t=await this.func(...e.arguments);e.onResult(t)}this.isRunning=!1,this.queue.length&&n()};return n(),t}}},792:function(e){var t;this||window,t=()=>(()=>{"use strict";var e={444:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EXISTS_KEYS=t.GeomFilter_Funcs=t.GeomFilterKeys=t.ArrayFilterOperands=t.TextFilter_FullTextSearchFilterKeys=t.TextFilterFTSKeys=t.TextFilterKeys=t.CompareInFilterKeys=t.CompareFilterKeys=void 0,t.CompareFilterKeys=["=","$eq","<>",">",">=","<=","$eq","$ne","$gt","$gte","$lte"],t.CompareInFilterKeys=["$in","$nin"],t.TextFilterKeys=["$ilike","$like"],t.TextFilterFTSKeys=["@@","@>","<@","$contains","$containedBy"],t.TextFilter_FullTextSearchFilterKeys=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"],t.ArrayFilterOperands=[...t.TextFilterFTSKeys,"&&","$overlaps"],t.GeomFilterKeys=["~","~=","@","|&>","|>>",">>","=","<<|","<<","&>","&<|","&<","&&&","&&"];const n=["ST_MakeEnvelope","ST_MakePolygon"];t.GeomFilter_Funcs=n.concat(n.map((e=>e.toLowerCase()))),t.EXISTS_KEYS=["$exists","$notExists","$existsJoined","$notExistsJoined"]},590:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.getKeys=t.isObject=t.isDefined=t.get=t.WAL=t.unpatchText=t.stableStringify=t.isEmpty=t.getTextPatch=t.asName=t.RULE_METHODS=t.CHANNELS=t.TS_PG_Types=t._PG_postgis=t._PG_date=t._PG_bool=t._PG_json=t._PG_numbers=t._PG_strings=void 0,t._PG_strings=["bpchar","char","varchar","text","citext","uuid","bytea","inet","time","timetz","interval","name"],t._PG_numbers=["int2","int4","int8","float4","float8","numeric","money","oid"],t._PG_json=["json","jsonb"],t._PG_bool=["bool"],t._PG_date=["date","timestamp","timestamptz"],t._PG_postgis=["geometry","geography"],t.TS_PG_Types={string:t._PG_strings,number:t._PG_numbers,boolean:t._PG_bool,Date:t._PG_date,"Array<number>":t._PG_numbers.map((e=>`_${e}`)),"Array<boolean>":t._PG_bool.map((e=>`_${e}`)),"Array<string>":t._PG_strings.map((e=>`_${e}`)),"Array<Object>":t._PG_json.map((e=>`_${e}`)),"Array<Date>":t._PG_date.map((e=>`_${e}`)),any:[]};const r="_psqlWS_.";t.CHANNELS={SCHEMA_CHANGED:r+"schema-changed",SCHEMA:r+"schema",DEFAULT:r,SQL:"_psqlWS_.sql",METHOD:"_psqlWS_.method",NOTICE_EV:"_psqlWS_.notice",LISTEN_EV:"_psqlWS_.listen",REGISTER:"_psqlWS_.register",LOGIN:"_psqlWS_.login",LOGOUT:"_psqlWS_.logout",AUTHGUARD:"_psqlWS_.authguard",_preffix:r},t.RULE_METHODS={getColumns:["getColumns"],getInfo:["getInfo"],insert:["insert","upsert"],update:["update","upsert","updateBatch"],select:["findOne","find","count","size"],delete:["delete","remove"],sync:["sync","unsync"],subscribe:["unsubscribe","subscribe","subscribeOne"]};var o=n(128);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return o.asName}}),Object.defineProperty(t,"getTextPatch",{enumerable:!0,get:function(){return o.getTextPatch}}),Object.defineProperty(t,"isEmpty",{enumerable:!0,get:function(){return o.isEmpty}}),Object.defineProperty(t,"stableStringify",{enumerable:!0,get:function(){return o.stableStringify}}),Object.defineProperty(t,"unpatchText",{enumerable:!0,get:function(){return o.unpatchText}}),Object.defineProperty(t,"WAL",{enumerable:!0,get:function(){return o.WAL}}),Object.defineProperty(t,"get",{enumerable:!0,get:function(){return o.get}}),Object.defineProperty(t,"isDefined",{enumerable:!0,get:function(){return o.isDefined}}),Object.defineProperty(t,"isObject",{enumerable:!0,get:function(){return o.isObject}}),Object.defineProperty(t,"getKeys",{enumerable:!0,get:function(){return o.getKeys}}),s(n(444),t)},899:(e,t)=>{function n(e,t){var n=e[0],i=e[1],l=e[2],c=e[3];n=s(n,i,l,c,t[0],7,-680876936),c=s(c,n,i,l,t[1],12,-389564586),l=s(l,c,n,i,t[2],17,606105819),i=s(i,l,c,n,t[3],22,-1044525330),n=s(n,i,l,c,t[4],7,-176418897),c=s(c,n,i,l,t[5],12,1200080426),l=s(l,c,n,i,t[6],17,-1473231341),i=s(i,l,c,n,t[7],22,-45705983),n=s(n,i,l,c,t[8],7,1770035416),c=s(c,n,i,l,t[9],12,-1958414417),l=s(l,c,n,i,t[10],17,-42063),i=s(i,l,c,n,t[11],22,-1990404162),n=s(n,i,l,c,t[12],7,1804603682),c=s(c,n,i,l,t[13],12,-40341101),l=s(l,c,n,i,t[14],17,-1502002290),n=r(n,i=s(i,l,c,n,t[15],22,1236535329),l,c,t[1],5,-165796510),c=r(c,n,i,l,t[6],9,-1069501632),l=r(l,c,n,i,t[11],14,643717713),i=r(i,l,c,n,t[0],20,-373897302),n=r(n,i,l,c,t[5],5,-701558691),c=r(c,n,i,l,t[10],9,38016083),l=r(l,c,n,i,t[15],14,-660478335),i=r(i,l,c,n,t[4],20,-405537848),n=r(n,i,l,c,t[9],5,568446438),c=r(c,n,i,l,t[14],9,-1019803690),l=r(l,c,n,i,t[3],14,-187363961),i=r(i,l,c,n,t[8],20,1163531501),n=r(n,i,l,c,t[13],5,-1444681467),c=r(c,n,i,l,t[2],9,-51403784),l=r(l,c,n,i,t[7],14,1735328473),n=o(n,i=r(i,l,c,n,t[12],20,-1926607734),l,c,t[5],4,-378558),c=o(c,n,i,l,t[8],11,-2022574463),l=o(l,c,n,i,t[11],16,1839030562),i=o(i,l,c,n,t[14],23,-35309556),n=o(n,i,l,c,t[1],4,-1530992060),c=o(c,n,i,l,t[4],11,1272893353),l=o(l,c,n,i,t[7],16,-155497632),i=o(i,l,c,n,t[10],23,-1094730640),n=o(n,i,l,c,t[13],4,681279174),c=o(c,n,i,l,t[0],11,-358537222),l=o(l,c,n,i,t[3],16,-722521979),i=o(i,l,c,n,t[6],23,76029189),n=o(n,i,l,c,t[9],4,-640364487),c=o(c,n,i,l,t[12],11,-421815835),l=o(l,c,n,i,t[15],16,530742520),n=a(n,i=o(i,l,c,n,t[2],23,-995338651),l,c,t[0],6,-198630844),c=a(c,n,i,l,t[7],10,1126891415),l=a(l,c,n,i,t[14],15,-1416354905),i=a(i,l,c,n,t[5],21,-57434055),n=a(n,i,l,c,t[12],6,1700485571),c=a(c,n,i,l,t[3],10,-1894986606),l=a(l,c,n,i,t[10],15,-1051523),i=a(i,l,c,n,t[1],21,-2054922799),n=a(n,i,l,c,t[8],6,1873313359),c=a(c,n,i,l,t[15],10,-30611744),l=a(l,c,n,i,t[6],15,-1560198380),i=a(i,l,c,n,t[13],21,1309151649),n=a(n,i,l,c,t[4],6,-145523070),c=a(c,n,i,l,t[11],10,-1120210379),l=a(l,c,n,i,t[2],15,718787259),i=a(i,l,c,n,t[9],21,-343485551),e[0]=d(n,e[0]),e[1]=d(i,e[1]),e[2]=d(l,e[2]),e[3]=d(c,e[3])}function i(e,t,n,i,s,r){return t=d(d(t,e),d(i,r)),d(t<<s|t>>>32-s,n)}function s(e,t,n,s,r,o,a){return i(t&n|~t&s,e,t,r,o,a)}function r(e,t,n,s,r,o,a){return i(t&s|n&~s,e,t,r,o,a)}function o(e,t,n,s,r,o,a){return i(t^n^s,e,t,r,o,a)}function a(e,t,n,s,r,o,a){return i(n^(t|~s),e,t,r,o,a)}function l(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}Object.defineProperty(t,"__esModule",{value:!0}),t.md5=t.md5cycle=void 0,t.md5cycle=n;var c="0123456789abcdef".split("");function u(e){for(var t="",n=0;n<4;n++)t+=c[e>>8*n+4&15]+c[e>>8*n&15];return t}function h(e){return function(e){for(var t=0;t<e.length;t++)e[t]=u(e[t]);return e.join("")}(function(e){var t,i=e.length,s=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=e.length;t+=64)n(s,l(e.substring(t-64,t)));e=e.substring(t-64);var r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t<e.length;t++)r[t>>2]|=e.charCodeAt(t)<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(n(s,r),t=0;t<16;t++)r[t]=0;return r[14]=8*i,n(s,r),s}(e))}function d(e,t){return e+t&4294967295}t.md5=h,h("hello")},128:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getKeys=t.isDefined=t.isObject=t.get=t.isEmpty=t.WAL=t.unpatchText=t.getTextPatch=t.stableStringify=t.asName=void 0;const i=n(899);function s(e){for(var t in e)return!1;return!0}t.asName=function(e){if(null==e||!e.toString||!e.toString())throw"Expecting a non empty string";return`"${e.toString().replace(/"/g,'""')}"`},t.stableStringify=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var n,i="boolean"==typeof t.cycles&&t.cycles,s=t.cmp&&(n=t.cmp,function(e){return function(t,i){var s={key:t,value:e[t]},r={key:i,value:e[i]};return n(s,r)}}),r=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var n,o;if(Array.isArray(t)){for(o="[",n=0;n<t.length;n++)n&&(o+=","),o+=e(t[n])||"null";return o+"]"}if(null===t)return"null";if(-1!==r.indexOf(t)){if(i)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var a=r.push(t)-1,l=Object.keys(t).sort(s&&s(t));for(o="",n=0;n<l.length;n++){var c=l[n],u=e(t[c]);u&&(o&&(o+=","),o+=JSON.stringify(c)+":"+u)}return r.splice(a,1),"{"+o+"}"}}(e)},t.getTextPatch=function(e,t){if(!(e&&t&&e.trim().length&&t.trim().length))return t;if(e===t)return{from:0,to:0,text:"",md5:(0,i.md5)(t)};function n(n=1){let i=n<1?-1:0,s=!1;for(;!s&&Math.abs(i)<=t.length;){const r=n<1?[i]:[0,i];e.slice(...r)!==t.slice(...r)?s=!0:i+=1*Math.sign(n)}return i}let s=n()-1,r=e.length+n(-1)+1,o=t.length+n(-1)+1;return{from:s,to:r,text:t.slice(s,o),md5:(0,i.md5)(t)}},t.unpatchText=function(e,t){if(!t||"string"==typeof t)return t;const{from:n,to:s,text:r,md5:o}=t;if(null===r||null===e)return r;let a=e.slice(0,n)+r+e.slice(s);if(o&&(0,i.md5)(a)!==o)throw"Patch text error: Could not match md5 hash: (original/result) \n"+e+"\n"+a;return a},t.WAL=class{constructor(e){if(this.changed={},this.sending={},this.sentHistory={},this.callbacks=[],this.sort=(e,t)=>{const{orderBy:n}=this.options;return n&&e&&t&&n.map((n=>{if(!(n.fieldName in e)||!(n.fieldName in t))throw"Replication error: \n some orderBy fields missing from data";let i=n.asc?e[n.fieldName]:t[n.fieldName],s=n.asc?t[n.fieldName]:e[n.fieldName],r=+i-+s,o=i<s?-1:i==s?0:1;return"number"===n.tsDataType&&Number.isFinite(r)?r:o})).find((e=>e))||0},this.isInHistory=e=>{if(!e)throw"Provide item";const t=e[this.options.synced_field];if(!Number.isFinite(+t))throw"Provided item Synced field value is missing/invalid ";const n=this.sentHistory[this.getIdStr(e)],i=n?.[this.options.synced_field];if(n){if(!Number.isFinite(+i))throw"Provided historic item Synced field value is missing/invalid";if(+i==+t)return!0}return!1},this.addData=e=>{s(this.changed)&&this.options.onSendStart&&this.options.onSendStart(),e.map((e=>{var t;const{initial:n,current:i}={...e};if(!i)throw"Expecting { current: object, initial?: object }";const s=this.getIdStr(i);this.changed??(this.changed={}),(t=this.changed)[s]??(t[s]={initial:n,current:i}),this.changed[s].current={...this.changed[s].current,...i}})),this.sendItems()},this.isOnSending=!1,this.isSendingTimeout=void 0,this.willDeleteHistory=void 0,this.sendItems=async()=>{const{DEBUG_MODE:e,onSend:t,onSendEnd:n,batch_size:i,throttle:r,historyAgeSeconds:o=2}=this.options;if(this.isSendingTimeout||this.sending&&!s(this.sending))return;if(!this.changed||s(this.changed))return;let a,l=[],c=[],u={};Object.keys(this.changed).sort(((e,t)=>this.sort(this.changed[e].current,this.changed[t].current))).slice(0,i).map((e=>{let t={...this.changed[e]};this.sending[e]={...t},c.push({...t}),u[e]={...t.current},delete this.changed[e]})),l=c.map((e=>e.current)),e&&console.log(this.options.id," SENDING lr->",l[l.length-1]),this.isSendingTimeout||(this.isSendingTimeout=setTimeout((()=>{this.isSendingTimeout=void 0,s(this.changed)||this.sendItems()}),r)),this.isOnSending=!0;try{await t(l,c),o&&(this.sentHistory={...this.sentHistory,...u},this.willDeleteHistory||(this.willDeleteHistory=setTimeout((()=>{this.willDeleteHistory=void 0,this.sentHistory={}}),1e3*o)))}catch(e){a=e,console.error("WAL onSend failed:",e,l,c)}if(this.isOnSending=!1,this.callbacks.length){const e=Object.keys(this.sending);this.callbacks.forEach(((t,n)=>{t.idStrs=t.idStrs.filter((t=>e.includes(t))),t.idStrs.length||t.cb(a)})),this.callbacks=this.callbacks.filter((e=>e.idStrs.length))}this.sending={},e&&console.log(this.options.id," SENT lr->",l[l.length-1]),s(this.changed)?n&&n(l,c,a):this.sendItems()},this.options={...e},!this.options.orderBy){const{synced_field:t,id_fields:n}=e;this.options.orderBy=[t,...n.sort()].map((e=>({fieldName:e,tsDataType:e===t?"number":"string",asc:!0})))}}isSending(){const e=this.isOnSending||!(s(this.sending)&&s(this.changed));return this.options.DEBUG_MODE&&console.log(this.options.id," CHECKING isSending ->",e),e}getIdStr(e){return this.options.id_fields.sort().map((t=>`${e[t]||""}`)).join(".")}getIdObj(e){let t={};return this.options.id_fields.sort().map((n=>{t[n]=e[n]})),t}getDeltaObj(e){let t={};return Object.keys(e).map((n=>{this.options.id_fields.includes(n)||(t[n]=e[n])})),t}},t.isEmpty=s,t.get=function(e,t){let n=t,i=e;return e?("string"==typeof n&&(n=n.split(".")),n.reduce(((e,t)=>e&&e[t]?e[t]:void 0),i)):e},t.isObject=function(e){return Boolean(e&&"object"==typeof e&&!Array.isArray(e))},t.isDefined=function(e){return null!=e},t.getKeys=function(e){return Object.keys(e)}}},t={};return function n(i){var s=t[i];if(void 0!==s)return s.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}(590)})(),e.exports=t()}},t={};function n(i){var s=t[i];if(void 0!==s)return s.exports;var r=t[i]={exports:{}};return e[i].call(r.exports,r,r.exports,n),r.exports}var i={};return(()=>{"use strict";var e=i;Object.defineProperty(e,"__esModule",{value:!0}),e.prostgles=void 0;const t=n(274),s=n(133);e.prostgles=function(e){return(0,t.prostgles)(e,s.SyncedTable)}})(),i})()));
|
package/dist/index.no-sync.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var r in n)("object"==typeof exports?exports:e)[r]=n[r]}}(this||window,(()=>{return e={274:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prostgles=t.debug=void 0;const r=n(792),i="DEBUG_SYNCEDTABLE",s="undefined"!=typeof window;t.debug=function(...e){s&&window[i]&&window[i](...e)},t.prostgles=function(e,n){const{socket:i,onReady:s,onDisconnect:o,onReconnect:a,onSchemaChange:l=!0}=e;if((0,t.debug)("prostgles",{initOpts:e}),l){let e;"function"==typeof l&&(e=l),i.removeAllListeners(r.CHANNELS.SCHEMA_CHANGED),e&&i.on(r.CHANNELS.SCHEMA_CHANGED,e)}const c=r.CHANNELS._preffix;let u={},d={},f={};const m=[];let h,p=!1,g={},y=!1;function b(e,n){return(0,t.debug)("_unsubscribe",{channelName:e,handler:n}),new Promise(((t,r)=>{u[e]?(u[e].handlers=u[e].handlers.filter((e=>e!==n)),u[e].handlers.length||(i.emit(e+"unsubscribe",{},((e,t)=>{e&&console.error(e)})),i.removeListener(e,u[e].onCall),delete u[e]),t(!0)):t(!0)}))}function _({tableName:e,command:t,param1:n,param2:r},s){return new Promise(((o,a)=>{i.emit(c,{tableName:e,command:t,param1:n,param2:r},((e,t)=>{if(e)console.error(e),a(e);else if(t){const{id_fields:e,synced_field:n,channelName:r}=t;i.emit(r,{onSyncRequest:s({})},(e=>{console.log(e)})),o({id_fields:e,synced_field:n,channelName:r})}}))}))}function S({tableName:e,command:t,param1:n,param2:r}){return new Promise(((s,o)=>{i.emit(c,{tableName:e,command:t,param1:n,param2:r},((e,t)=>{e?(console.error(e),o(e)):t&&s(t.channelName)}))}))}async function O(e,t,n,r){const s=new Promise(((i,s)=>{const o={dbo:e,params:t,onChange:n,_onError:r,returnHandlers:e=>{i(e)}};m.push(o)})),o=async()=>{if(!p)return;const e=m.shift();if(e){const t=await async function(e,{tableName:t,command:n,param1:r,param2:s},o,a){function l(n){let i={unsubscribe:function(){return b(n,o)},filter:{...r}};return e[t].update&&(i={...i,update:function(n,i){return e[t].update(r,n,i)}}),e[t].delete&&(i={...i,delete:function(n){return e[t].delete(r,n)}}),Object.freeze(i)}p=!0;const c=Object.keys(u).find((e=>{let i=u[e];return i.tableName===t&&i.command===n&&JSON.stringify(i.param1||{})===JSON.stringify(r||{})&&JSON.stringify(i.param2||{})===JSON.stringify(s||{})}));if(c)return u[c].handlers.push(o),setTimeout((()=>{o&&(null==u?void 0:u[c].lastData)&&o(null==u?void 0:u[c].lastData)}),10),p=!1,l(c);const d=await S({tableName:t,command:n,param1:r,param2:s});let f=function(e,t){u[d]?e.data?(u[d].lastData=e.data,u[d].handlers.map((t=>{t(e.data)}))):e.err?u[d].errorHandlers.map((t=>{t(e.err)})):console.error("INTERNAL ERROR: Unexpected data format from subscription: ",e):console.warn("Orphaned subscription: ",d)},m=a||function(e){console.error(`Uncaught error within running subscription \n ${d}`,e)};return i.on(d,f),u[d]={lastData:void 0,tableName:t,command:n,param1:r,param2:s,onCall:f,handlers:[o],errorHandlers:[m],destroy:()=>{u[d]&&(Object.values(u[d]).map((e=>{e&&e.handlers&&e.handlers.map((e=>b(d,e)))})),delete u[d])}},p=!1,l(d)}(e.dbo,e.params,e.onChange,e._onError);e.returnHandlers(t)}m.length&&o()};return o(),s}return new Promise(((e,l)=>{o&&i.on("disconnect",o),i.on(r.CHANNELS.SCHEMA,(({schema:o,methods:m,tableSchema:p,auth:b,rawSQL:N,joinTables:v=[],err:C})=>{if(C)throw l(C),C;(0,t.debug)("destroySyncs",{subscriptions:u,syncedTables:d}),Object.values(u).map((e=>e.destroy())),u={},f={},Object.values(d).map((e=>{e&&e.destroy&&e.destroy()})),d={},y&&a&&a(i),y=!0;let j=JSON.parse(JSON.stringify(o)),E=JSON.parse(JSON.stringify(m)),P={},w={};if(b){if(b.pathGuard){const e=e=>{var t,n;(null==e?void 0:e.shouldReload)&&"undefined"!=typeof window&&(null===(n=null===(t=null===window||void 0===window?void 0:window.location)||void 0===t?void 0:t.reload)||void 0===n||n.call(t))};i.emit(r.CHANNELS.AUTHGUARD,JSON.stringify(window.location),((t,n)=>{e(n)})),i.removeAllListeners(r.CHANNELS.AUTHGUARD),i.on(r.CHANNELS.AUTHGUARD,(t=>{e(t)}))}w={...b},[r.CHANNELS.LOGIN,r.CHANNELS.LOGOUT,r.CHANNELS.REGISTER].map((e=>{b[e]&&(w[e]=function(t){return new Promise(((n,r)=>{i.emit(c+e,t,((e,t)=>{e?r(e):n(t)}))}))})}))}E.map((e=>{P[e]=function(...t){return new Promise(((n,s)=>{i.emit(r.CHANNELS.METHOD,{method:e,params:t},((e,t)=>{e?s(e):n(t)}))}))}})),P=Object.freeze(P),N&&(j.sql=function(e,t,n){return new Promise(((s,o)=>{i.emit(r.CHANNELS.SQL,{query:e,params:t,options:n},((e,t)=>{if(e)o(e);else if(n&&"noticeSubscription"===n.returnType&&t&&Object.keys(t).sort().join()===["socketChannel","socketUnsubChannel"].sort().join()&&!Object.values(t).find((e=>"string"!=typeof e))){const e=t,n=t=>(((e,t)=>{h=h||{config:t,listeners:[]},h.listeners.length||(i.removeAllListeners(t.socketChannel),i.on(t.socketChannel,(e=>{h&&h.listeners&&h.listeners.length?h.listeners.map((t=>{t(e)})):i.emit(t.socketUnsubChannel,{})}))),h.listeners.push(e)})(t,e),{...e,removeListener:()=>(e=>{h&&(h.listeners=h.listeners.filter((t=>t!==e)),!h.listeners.length&&h.config&&h.config.socketUnsubChannel&&i&&i.emit(h.config.socketUnsubChannel,{}))})(t)}),r={...e,addListener:n};s(r)}else if(n&&n.returnType&&"statement"===n.returnType||!t||Object.keys(t).sort().join()!==["socketChannel","socketUnsubChannel","notifChannel"].sort().join()||Object.values(t).find((e=>"string"!=typeof e)))s(t);else{const e=e=>(((e,t)=>{g=g||{},g[t.notifChannel]?g[t.notifChannel].listeners.push(e):(g[t.notifChannel]={config:t,listeners:[e]},i.removeAllListeners(t.socketChannel),i.on(t.socketChannel,(e=>{g[t.notifChannel]&&g[t.notifChannel].listeners&&g[t.notifChannel].listeners.length?g[t.notifChannel].listeners.map((t=>{t(e)})):i.emit(g[t.notifChannel].config.socketUnsubChannel,{})})))})(e,t),{...t,removeListener:()=>((e,t)=>{g&&g[t.notifChannel]&&(g[t.notifChannel].listeners=g[t.notifChannel].listeners.filter((t=>t!==e)),!g[t.notifChannel].listeners.length&&g[t.notifChannel].config&&g[t.notifChannel].config.socketUnsubChannel&&i&&(i.emit(g[t.notifChannel].config.socketUnsubChannel,{}),delete g[t.notifChannel]))})(e,t)}),n={...t,addListener:e};s(n)}}))}))});const T=e=>"[object Object]"===Object.prototype.toString.call(e),A=(e,t,n,r)=>{if(!T(e)||!T(t)||"function"!=typeof n||r&&"function"!=typeof r)throw"Expecting: ( basicFilter<object>, options<object>, onChange<function> , onError?<function>) but got something else"},x=["subscribe","subscribeOne"];Object.keys(j).forEach((e=>{Object.keys(j[e]).sort(((e,t)=>x.includes(e)-x.includes(t))).forEach((r=>{if(["find","findOne"].includes(r)&&(j[e].getJoinedTables=function(){return(v||[]).filter((t=>Array.isArray(t)&&t.includes(e))).flat().filter((t=>t!==e))}),"sync"===r){if(j[e]._syncInfo={...j[e][r]},n){j[e].getSync=(t,r={})=>n.create({name:e,filter:t,db:j,...r});const t=async(t={},r={},i)=>{const s=`${e}.${JSON.stringify(t)}.${JSON.stringify(r)}`;return d[s]||(d[s]=await n.create({...r,name:e,filter:t,db:j,onError:i})),d[s]};j[e].sync=async(e,n={handlesOnData:!0,select:"*"},r,i)=>{A(e,n,r,i);const s=await t(e,n,i);return await s.sync(r,n.handlesOnData)},j[e].syncOne=async(e,n={handlesOnData:!0},r,i)=>{A(e,n,r,i);const s=await t(e,n,i);return await s.syncOne(e,r,n.handlesOnData)}}j[e]._sync=function(n,s,o){return async function({tableName:e,command:n,param1:r,param2:s},o){const{onPullRequest:a,onSyncRequest:l,onUpdates:c}=o;function u(e){return Object.freeze({unsync:function(){!function(e,n){(0,t.debug)("_unsync",{channelName:e,triggers:n}),new Promise(((t,r)=>{f[e]&&(f[e].triggers=f[e].triggers.filter((e=>e.onPullRequest!==n.onPullRequest&&e.onSyncRequest!==n.onSyncRequest&&e.onUpdates!==n.onUpdates)),f[e].triggers.length||(i.emit(e+"unsync",{},((e,n)=>{e?r(e):t(n)})),i.removeListener(e,f[e].onCall),delete f[e]))}))}(e,o)},syncData:function(t,n,r){i.emit(e,{onSyncRequest:{...l({}),...{data:t}||{},...{deleted:n}||{}}},r?e=>{r(e)}:null)}})}const d=Object.keys(f).find((t=>{let i=f[t];return i.tableName===e&&i.command===n&&JSON.stringify(i.param1||{})===JSON.stringify(r||{})&&JSON.stringify(i.param2||{})===JSON.stringify(s||{})}));if(d)return f[d].triggers.push(o),u(d);{const m=await _({tableName:e,command:n,param1:r,param2:s},l),{channelName:h,synced_field:p,id_fields:g}=m;function y(t,n){t&&f[h]&&f[h].triggers.map((({onUpdates:r,onSyncRequest:i,onPullRequest:s})=>{t.data?Promise.resolve(r(t)).then((()=>{n&&n({ok:!0})})).catch((t=>{n?n({err:t}):console.error(e+" onUpdates error",t)})):t.onSyncRequest?Promise.resolve(i(t.onSyncRequest)).then((e=>n({onSyncRequest:e}))).catch((t=>{n?n({err:t}):console.error(e+" onSyncRequest error",t)})):t.onPullRequest?Promise.resolve(s(t.onPullRequest)).then((e=>{n({data:e})})).catch((t=>{n?n({err:t}):console.error(e+" onPullRequest error",t)})):console.log("unexpected response")}))}return f[h]={tableName:e,command:n,param1:r,param2:s,triggers:[o],syncInfo:m,onCall:y},i.on(h,y),u(h)}}({tableName:e,command:r,param1:n,param2:s},o)}}else if(x.includes(r)){j[e][r]=function(t,n,i,s){return A(t,n,i,s),O(j,{tableName:e,command:r,param1:t,param2:n},i,s)};const t="subscribeOne";r!==t&&x.includes(t)||(j[e][t]=function(t,n,i,s){return A(t,n,i,s),O(j,{tableName:e,command:r,param1:t,param2:n},(e=>{i(e[0])}),s)})}else j[e][r]=function(t,n,s){return new Promise(((o,a)=>{i.emit(c,{tableName:e,command:r,param1:t,param2:n,param3:s},((e,t)=>{e?a(e):o(t)}))}))}}))})),u&&Object.keys(u).length&&Object.keys(u).map((async e=>{try{let t=u[e];await S(t),i.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting old subscriptions",e)}})),f&&Object.keys(f).length&&Object.keys(f).filter((e=>f[e].triggers&&f[e].triggers.length)).map((async e=>{try{let t=f[e];await _(t,t.triggers[0].onSyncRequest),i.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting olf subscriptions",e)}})),v.flat().map((e=>{function t(t=!0,n,r,i){return{[t?"$leftJoin":"$innerJoin"]:e,filter:n,select:r,...i}}j.innerJoin=j.innerJoin||{},j.leftJoin=j.leftJoin||{},j.innerJoinOne=j.innerJoinOne||{},j.leftJoinOne=j.leftJoinOne||{},j.leftJoin[e]=(e,n,r={})=>t(!0,e,n,r),j.innerJoin[e]=(e,n,r={})=>t(!1,e,n,r),j.leftJoinOne[e]=(e,n,r={})=>t(!0,e,n,{...r,limit:1}),j.innerJoinOne[e]=(e,n,r={})=>t(!1,e,n,{...r,limit:1})})),(async()=>{try{await s(j,P,p,w)}catch(e){console.error("Prostgles: Error within onReady: \n",e),l(e)}e(j)})()}))}))}},792:function(e){var t;this||window,t=()=>(()=>{"use strict";var e={444:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EXISTS_KEYS=t.GeomFilter_Funcs=t.GeomFilterKeys=t.ArrayFilterOperands=t.TextFilter_FullTextSearchFilterKeys=t.TextFilterFTSKeys=t.TextFilterKeys=t.CompareInFilterKeys=t.CompareFilterKeys=void 0,t.CompareFilterKeys=["=","$eq","<>",">",">=","<=","$eq","$ne","$gt","$gte","$lte"],t.CompareInFilterKeys=["$in","$nin"],t.TextFilterKeys=["$ilike","$like"],t.TextFilterFTSKeys=["@@","@>","<@","$contains","$containedBy"],t.TextFilter_FullTextSearchFilterKeys=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"],t.ArrayFilterOperands=[...t.TextFilterFTSKeys,"&&","$overlaps"],t.GeomFilterKeys=["~","~=","@","|&>","|>>",">>","=","<<|","<<","&>","&<|","&<","&&&","&&"];const n=["ST_MakeEnvelope","ST_MakePolygon"];t.GeomFilter_Funcs=n.concat(n.map((e=>e.toLowerCase()))),t.EXISTS_KEYS=["$exists","$notExists","$existsJoined","$notExistsJoined"]},590:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||r(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.getKeys=t.isObject=t.isDefined=t.get=t.WAL=t.unpatchText=t.stableStringify=t.isEmpty=t.getTextPatch=t.asName=t.RULE_METHODS=t.CHANNELS=t.TS_PG_Types=t._PG_postgis=t._PG_date=t._PG_bool=t._PG_json=t._PG_numbers=t._PG_strings=void 0,t._PG_strings=["bpchar","char","varchar","text","citext","uuid","bytea","inet","time","timetz","interval","name"],t._PG_numbers=["int2","int4","int8","float4","float8","numeric","money","oid"],t._PG_json=["json","jsonb"],t._PG_bool=["bool"],t._PG_date=["date","timestamp","timestamptz"],t._PG_postgis=["geometry","geography"],t.TS_PG_Types={string:t._PG_strings,number:t._PG_numbers,boolean:t._PG_bool,Date:t._PG_date,"Array<number>":t._PG_numbers.map((e=>`_${e}`)),"Array<boolean>":t._PG_bool.map((e=>`_${e}`)),"Array<string>":t._PG_strings.map((e=>`_${e}`)),"Array<Object>":t._PG_json.map((e=>`_${e}`)),"Array<Date>":t._PG_date.map((e=>`_${e}`)),any:[]};const s="_psqlWS_.";t.CHANNELS={SCHEMA_CHANGED:s+"schema-changed",SCHEMA:s+"schema",DEFAULT:s,SQL:"_psqlWS_.sql",METHOD:"_psqlWS_.method",NOTICE_EV:"_psqlWS_.notice",LISTEN_EV:"_psqlWS_.listen",REGISTER:"_psqlWS_.register",LOGIN:"_psqlWS_.login",LOGOUT:"_psqlWS_.logout",AUTHGUARD:"_psqlWS_.authguard",_preffix:s},t.RULE_METHODS={getColumns:["getColumns"],getInfo:["getInfo"],insert:["insert","upsert"],update:["update","upsert","updateBatch"],select:["findOne","find","count","size"],delete:["delete","remove"],sync:["sync","unsync"],subscribe:["unsubscribe","subscribe","subscribeOne"]};var o=n(128);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return o.asName}}),Object.defineProperty(t,"getTextPatch",{enumerable:!0,get:function(){return o.getTextPatch}}),Object.defineProperty(t,"isEmpty",{enumerable:!0,get:function(){return o.isEmpty}}),Object.defineProperty(t,"stableStringify",{enumerable:!0,get:function(){return o.stableStringify}}),Object.defineProperty(t,"unpatchText",{enumerable:!0,get:function(){return o.unpatchText}}),Object.defineProperty(t,"WAL",{enumerable:!0,get:function(){return o.WAL}}),Object.defineProperty(t,"get",{enumerable:!0,get:function(){return o.get}}),Object.defineProperty(t,"isDefined",{enumerable:!0,get:function(){return o.isDefined}}),Object.defineProperty(t,"isObject",{enumerable:!0,get:function(){return o.isObject}}),Object.defineProperty(t,"getKeys",{enumerable:!0,get:function(){return o.getKeys}}),i(n(444),t)},899:(e,t)=>{function n(e,t){var n=e[0],r=e[1],l=e[2],c=e[3];n=i(n,r,l,c,t[0],7,-680876936),c=i(c,n,r,l,t[1],12,-389564586),l=i(l,c,n,r,t[2],17,606105819),r=i(r,l,c,n,t[3],22,-1044525330),n=i(n,r,l,c,t[4],7,-176418897),c=i(c,n,r,l,t[5],12,1200080426),l=i(l,c,n,r,t[6],17,-1473231341),r=i(r,l,c,n,t[7],22,-45705983),n=i(n,r,l,c,t[8],7,1770035416),c=i(c,n,r,l,t[9],12,-1958414417),l=i(l,c,n,r,t[10],17,-42063),r=i(r,l,c,n,t[11],22,-1990404162),n=i(n,r,l,c,t[12],7,1804603682),c=i(c,n,r,l,t[13],12,-40341101),l=i(l,c,n,r,t[14],17,-1502002290),n=s(n,r=i(r,l,c,n,t[15],22,1236535329),l,c,t[1],5,-165796510),c=s(c,n,r,l,t[6],9,-1069501632),l=s(l,c,n,r,t[11],14,643717713),r=s(r,l,c,n,t[0],20,-373897302),n=s(n,r,l,c,t[5],5,-701558691),c=s(c,n,r,l,t[10],9,38016083),l=s(l,c,n,r,t[15],14,-660478335),r=s(r,l,c,n,t[4],20,-405537848),n=s(n,r,l,c,t[9],5,568446438),c=s(c,n,r,l,t[14],9,-1019803690),l=s(l,c,n,r,t[3],14,-187363961),r=s(r,l,c,n,t[8],20,1163531501),n=s(n,r,l,c,t[13],5,-1444681467),c=s(c,n,r,l,t[2],9,-51403784),l=s(l,c,n,r,t[7],14,1735328473),n=o(n,r=s(r,l,c,n,t[12],20,-1926607734),l,c,t[5],4,-378558),c=o(c,n,r,l,t[8],11,-2022574463),l=o(l,c,n,r,t[11],16,1839030562),r=o(r,l,c,n,t[14],23,-35309556),n=o(n,r,l,c,t[1],4,-1530992060),c=o(c,n,r,l,t[4],11,1272893353),l=o(l,c,n,r,t[7],16,-155497632),r=o(r,l,c,n,t[10],23,-1094730640),n=o(n,r,l,c,t[13],4,681279174),c=o(c,n,r,l,t[0],11,-358537222),l=o(l,c,n,r,t[3],16,-722521979),r=o(r,l,c,n,t[6],23,76029189),n=o(n,r,l,c,t[9],4,-640364487),c=o(c,n,r,l,t[12],11,-421815835),l=o(l,c,n,r,t[15],16,530742520),n=a(n,r=o(r,l,c,n,t[2],23,-995338651),l,c,t[0],6,-198630844),c=a(c,n,r,l,t[7],10,1126891415),l=a(l,c,n,r,t[14],15,-1416354905),r=a(r,l,c,n,t[5],21,-57434055),n=a(n,r,l,c,t[12],6,1700485571),c=a(c,n,r,l,t[3],10,-1894986606),l=a(l,c,n,r,t[10],15,-1051523),r=a(r,l,c,n,t[1],21,-2054922799),n=a(n,r,l,c,t[8],6,1873313359),c=a(c,n,r,l,t[15],10,-30611744),l=a(l,c,n,r,t[6],15,-1560198380),r=a(r,l,c,n,t[13],21,1309151649),n=a(n,r,l,c,t[4],6,-145523070),c=a(c,n,r,l,t[11],10,-1120210379),l=a(l,c,n,r,t[2],15,718787259),r=a(r,l,c,n,t[9],21,-343485551),e[0]=f(n,e[0]),e[1]=f(r,e[1]),e[2]=f(l,e[2]),e[3]=f(c,e[3])}function r(e,t,n,r,i,s){return t=f(f(t,e),f(r,s)),f(t<<i|t>>>32-i,n)}function i(e,t,n,i,s,o,a){return r(t&n|~t&i,e,t,s,o,a)}function s(e,t,n,i,s,o,a){return r(t&i|n&~i,e,t,s,o,a)}function o(e,t,n,i,s,o,a){return r(t^n^i,e,t,s,o,a)}function a(e,t,n,i,s,o,a){return r(n^(t|~i),e,t,s,o,a)}function l(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}Object.defineProperty(t,"__esModule",{value:!0}),t.md5=t.md5cycle=void 0,t.md5cycle=n;var c="0123456789abcdef".split("");function u(e){for(var t="",n=0;n<4;n++)t+=c[e>>8*n+4&15]+c[e>>8*n&15];return t}function d(e){return function(e){for(var t=0;t<e.length;t++)e[t]=u(e[t]);return e.join("")}(function(e){var t,r=e.length,i=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=e.length;t+=64)n(i,l(e.substring(t-64,t)));e=e.substring(t-64);var s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t<e.length;t++)s[t>>2]|=e.charCodeAt(t)<<(t%4<<3);if(s[t>>2]|=128<<(t%4<<3),t>55)for(n(i,s),t=0;t<16;t++)s[t]=0;return s[14]=8*r,n(i,s),i}(e))}function f(e,t){return e+t&4294967295}t.md5=d,d("hello")},128:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getKeys=t.isDefined=t.isObject=t.get=t.isEmpty=t.WAL=t.unpatchText=t.getTextPatch=t.stableStringify=t.asName=void 0;const r=n(899);function i(e){for(var t in e)return!1;return!0}t.asName=function(e){if(null==e||!e.toString||!e.toString())throw"Expecting a non empty string";return`"${e.toString().replace(/"/g,'""')}"`},t.stableStringify=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var n,r="boolean"==typeof t.cycles&&t.cycles,i=t.cmp&&(n=t.cmp,function(e){return function(t,r){var i={key:t,value:e[t]},s={key:r,value:e[r]};return n(i,s)}}),s=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var n,o;if(Array.isArray(t)){for(o="[",n=0;n<t.length;n++)n&&(o+=","),o+=e(t[n])||"null";return o+"]"}if(null===t)return"null";if(-1!==s.indexOf(t)){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var a=s.push(t)-1,l=Object.keys(t).sort(i&&i(t));for(o="",n=0;n<l.length;n++){var c=l[n],u=e(t[c]);u&&(o&&(o+=","),o+=JSON.stringify(c)+":"+u)}return s.splice(a,1),"{"+o+"}"}}(e)},t.getTextPatch=function(e,t){if(!(e&&t&&e.trim().length&&t.trim().length))return t;if(e===t)return{from:0,to:0,text:"",md5:(0,r.md5)(t)};function n(n=1){let r=n<1?-1:0,i=!1;for(;!i&&Math.abs(r)<=t.length;){const s=n<1?[r]:[0,r];e.slice(...s)!==t.slice(...s)?i=!0:r+=1*Math.sign(n)}return r}let i=n()-1,s=e.length+n(-1)+1,o=t.length+n(-1)+1;return{from:i,to:s,text:t.slice(i,o),md5:(0,r.md5)(t)}},t.unpatchText=function(e,t){if(!t||"string"==typeof t)return t;const{from:n,to:i,text:s,md5:o}=t;if(null===s||null===e)return s;let a=e.slice(0,n)+s+e.slice(i);if(o&&(0,r.md5)(a)!==o)throw"Patch text error: Could not match md5 hash: (original/result) \n"+e+"\n"+a;return a},t.WAL=class{constructor(e){if(this.changed={},this.sending={},this.sentHistory={},this.callbacks=[],this.sort=(e,t)=>{const{orderBy:n}=this.options;return n&&e&&t&&n.map((n=>{if(!(n.fieldName in e)||!(n.fieldName in t))throw"Replication error: \n some orderBy fields missing from data";let r=n.asc?e[n.fieldName]:t[n.fieldName],i=n.asc?t[n.fieldName]:e[n.fieldName],s=+r-+i,o=r<i?-1:r==i?0:1;return"number"===n.tsDataType&&Number.isFinite(s)?s:o})).find((e=>e))||0},this.isInHistory=e=>{if(!e)throw"Provide item";const t=e[this.options.synced_field];if(!Number.isFinite(+t))throw"Provided item Synced field value is missing/invalid ";const n=this.sentHistory[this.getIdStr(e)],r=n?.[this.options.synced_field];if(n){if(!Number.isFinite(+r))throw"Provided historic item Synced field value is missing/invalid";if(+r==+t)return!0}return!1},this.addData=e=>{i(this.changed)&&this.options.onSendStart&&this.options.onSendStart(),e.map((e=>{var t;const{initial:n,current:r}={...e};if(!r)throw"Expecting { current: object, initial?: object }";const i=this.getIdStr(r);this.changed??(this.changed={}),(t=this.changed)[i]??(t[i]={initial:n,current:r}),this.changed[i].current={...this.changed[i].current,...r}})),this.sendItems()},this.isOnSending=!1,this.isSendingTimeout=void 0,this.willDeleteHistory=void 0,this.sendItems=async()=>{const{DEBUG_MODE:e,onSend:t,onSendEnd:n,batch_size:r,throttle:s,historyAgeSeconds:o=2}=this.options;if(this.isSendingTimeout||this.sending&&!i(this.sending))return;if(!this.changed||i(this.changed))return;let a,l=[],c=[],u={};Object.keys(this.changed).sort(((e,t)=>this.sort(this.changed[e].current,this.changed[t].current))).slice(0,r).map((e=>{let t={...this.changed[e]};this.sending[e]={...t},c.push({...t}),u[e]={...t.current},delete this.changed[e]})),l=c.map((e=>e.current)),e&&console.log(this.options.id," SENDING lr->",l[l.length-1]),this.isSendingTimeout||(this.isSendingTimeout=setTimeout((()=>{this.isSendingTimeout=void 0,i(this.changed)||this.sendItems()}),s)),this.isOnSending=!0;try{await t(l,c),o&&(this.sentHistory={...this.sentHistory,...u},this.willDeleteHistory||(this.willDeleteHistory=setTimeout((()=>{this.willDeleteHistory=void 0,this.sentHistory={}}),1e3*o)))}catch(e){a=e,console.error("WAL onSend failed:",e,l,c)}if(this.isOnSending=!1,this.callbacks.length){const e=Object.keys(this.sending);this.callbacks.forEach(((t,n)=>{t.idStrs=t.idStrs.filter((t=>e.includes(t))),t.idStrs.length||t.cb(a)})),this.callbacks=this.callbacks.filter((e=>e.idStrs.length))}this.sending={},e&&console.log(this.options.id," SENT lr->",l[l.length-1]),i(this.changed)?n&&n(l,c,a):this.sendItems()},this.options={...e},!this.options.orderBy){const{synced_field:t,id_fields:n}=e;this.options.orderBy=[t,...n.sort()].map((e=>({fieldName:e,tsDataType:e===t?"number":"string",asc:!0})))}}isSending(){const e=this.isOnSending||!(i(this.sending)&&i(this.changed));return this.options.DEBUG_MODE&&console.log(this.options.id," CHECKING isSending ->",e),e}getIdStr(e){return this.options.id_fields.sort().map((t=>`${e[t]||""}`)).join(".")}getIdObj(e){let t={};return this.options.id_fields.sort().map((n=>{t[n]=e[n]})),t}getDeltaObj(e){let t={};return Object.keys(e).map((n=>{this.options.id_fields.includes(n)||(t[n]=e[n])})),t}},t.isEmpty=i,t.get=function(e,t){let n=t,r=e;return e?("string"==typeof n&&(n=n.split(".")),n.reduce(((e,t)=>e&&e[t]?e[t]:void 0),r)):e},t.isObject=function(e){return Boolean(e&&"object"==typeof e&&!Array.isArray(e))},t.isDefined=function(e){return null!=e},t.getKeys=function(e){return Object.keys(e)}}},t={};return function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={exports:{}};return e[r].call(s.exports,s,s.exports,n),s.exports}(590)})(),e.exports=t()}},t={},function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={exports:{}};return e[r].call(s.exports,s,s.exports,n),s.exports}(274);var e,t}));
|
|
1
|
+
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var n=t();for(var i in n)("object"==typeof exports?exports:e)[i]=n[i]}}(this||window,(()=>{return e={274:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prostgles=t.debug=void 0;const i=n(792),r="DEBUG_SYNCEDTABLE",s="undefined"!=typeof window;t.debug=function(...e){s&&window[r]&&window[r](...e)},t.prostgles=function(e,n){const{socket:r,onReady:s,onDisconnect:a,onReconnect:c,onSchemaChange:l=!0}=e;if((0,t.debug)("prostgles",{initOpts:e}),l){let e;"function"==typeof l&&(e=l),r.removeAllListeners(i.CHANNELS.SCHEMA_CHANGED),e&&r.on(i.CHANNELS.SCHEMA_CHANGED,e)}const u=i.CHANNELS._preffix;let d,f={},m={},h={},p=!1,g={},y=!1;function b(e,n){return(0,t.debug)("_unsubscribe",{channelName:e,handler:n}),new Promise(((t,i)=>{f[e]?(f[e].handlers=f[e].handlers.filter((e=>e!==n)),f[e].handlers.length||(r.emit(e+"unsubscribe",{},((e,t)=>{e&&console.error(e)})),r.removeListener(e,f[e].onCall),delete f[e]),t(!0)):t(!0)}))}function _({tableName:e,command:t,param1:n,param2:i},s){return new Promise(((o,a)=>{r.emit(u,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{if(e)console.error(e),a(e);else if(t){const{id_fields:e,synced_field:n,channelName:i}=t;r.emit(i,{onSyncRequest:s({})},(e=>{console.log(e)})),o({id_fields:e,synced_field:n,channelName:i})}}))}))}function S({tableName:e,command:t,param1:n,param2:i}){return new Promise(((s,o)=>{r.emit(u,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{e?(console.error(e),o(e)):t&&s(t.channelName)}))}))}const O=new o((async function({tableName:e,command:n,param1:i,param2:s},o){const{onPullRequest:a,onSyncRequest:c,onUpdates:l}=o;function u(e){return Object.freeze({unsync:function(){!function(e,n){(0,t.debug)("_unsync",{channelName:e,triggers:n}),new Promise(((t,i)=>{h[e]&&(h[e].triggers=h[e].triggers.filter((e=>e.onPullRequest!==n.onPullRequest&&e.onSyncRequest!==n.onSyncRequest&&e.onUpdates!==n.onUpdates)),h[e].triggers.length||(r.emit(e+"unsync",{},((e,n)=>{e?i(e):t(n)})),r.removeListener(e,h[e].onCall),delete h[e]))}))}(e,o)},syncData:function(t,n,i){r.emit(e,{onSyncRequest:{...c({}),...{data:t}||{},...{deleted:n}||{}}},i?e=>{i(e)}:null)}})}const d=Object.keys(h).find((t=>{let r=h[t];return r.tableName===e&&r.command===n&&JSON.stringify(r.param1||{})===JSON.stringify(i||{})&&JSON.stringify(r.param2||{})===JSON.stringify(s||{})}));if(d)return h[d].triggers.push(o),u(d);{const f=await _({tableName:e,command:n,param1:i,param2:s},c),{channelName:m,synced_field:p,id_fields:g}=f;function y(t,n){t&&h[m]&&h[m].triggers.map((({onUpdates:i,onSyncRequest:r,onPullRequest:s})=>{t.data?Promise.resolve(i(t)).then((()=>{n&&n({ok:!0})})).catch((t=>{n?n({err:t}):console.error(e+" onUpdates error",t)})):t.onSyncRequest?Promise.resolve(r(t.onSyncRequest)).then((e=>n({onSyncRequest:e}))).catch((t=>{n?n({err:t}):console.error(e+" onSyncRequest error",t)})):t.onPullRequest?Promise.resolve(s(t.onPullRequest)).then((e=>{n({data:e})})).catch((t=>{n?n({err:t}):console.error(e+" onPullRequest error",t)})):console.log("unexpected response")}))}return h[m]={tableName:e,command:n,param1:i,param2:s,triggers:[o],syncInfo:f,onCall:y},r.on(m,y),u(m)}})),N=new o((async function(e,{tableName:t,command:n,param1:i,param2:s},o,a){function c(n){let r={unsubscribe:function(){return b(n,o)},filter:{...i}};return e[t].update&&(r={...r,update:function(n,r){return e[t].update(i,n,r)}}),e[t].delete&&(r={...r,delete:function(n){return e[t].delete(i,n)}}),Object.freeze(r)}p=!0;const l=Object.keys(f).find((e=>{let r=f[e];return r.tableName===t&&r.command===n&&JSON.stringify(r.param1||{})===JSON.stringify(i||{})&&JSON.stringify(r.param2||{})===JSON.stringify(s||{})}));if(l)return f[l].handlers.push(o),setTimeout((()=>{o&&(null==f?void 0:f[l].lastData)&&o(null==f?void 0:f[l].lastData)}),10),p=!1,c(l);const u=await S({tableName:t,command:n,param1:i,param2:s});let d=function(e,t){f[u]?e.data?(f[u].lastData=e.data,f[u].handlers.map((t=>{t(e.data)}))):e.err?f[u].errorHandlers.map((t=>{t(e.err)})):console.error("INTERNAL ERROR: Unexpected data format from subscription: ",e):console.warn("Orphaned subscription: ",u)},m=a||function(e){console.error(`Uncaught error within running subscription \n ${u}`,e)};return r.on(u,d),f[u]={lastData:void 0,tableName:t,command:n,param1:i,param2:s,onCall:d,handlers:[o],errorHandlers:[m],destroy:()=>{f[u]&&(Object.values(f[u]).map((e=>{e&&e.handlers&&e.handlers.map((e=>b(u,e)))})),delete f[u])}},p=!1,c(u)}));async function v(e,t,n,i){return N.run([e,t,n,i])}return new Promise(((e,o)=>{a&&r.on("disconnect",a),r.on(i.CHANNELS.SCHEMA,(({schema:a,methods:l,tableSchema:p,auth:b,rawSQL:N,joinTables:C=[],err:j})=>{if(j)throw o(j),j;(0,t.debug)("destroySyncs",{subscriptions:f,syncedTables:m}),Object.values(f).map((e=>e.destroy())),f={},h={},Object.values(m).map((e=>{e&&e.destroy&&e.destroy()})),m={},y&&c&&c(r),y=!0;let E=JSON.parse(JSON.stringify(a)),P=JSON.parse(JSON.stringify(l)),w={},T={};if(b){if(b.pathGuard){const e=e=>{var t,n;(null==e?void 0:e.shouldReload)&&"undefined"!=typeof window&&(null===(n=null===(t=null===window||void 0===window?void 0:window.location)||void 0===t?void 0:t.reload)||void 0===n||n.call(t))};r.emit(i.CHANNELS.AUTHGUARD,JSON.stringify(window.location),((t,n)=>{e(n)})),r.removeAllListeners(i.CHANNELS.AUTHGUARD),r.on(i.CHANNELS.AUTHGUARD,(t=>{e(t)}))}T={...b},[i.CHANNELS.LOGIN,i.CHANNELS.LOGOUT,i.CHANNELS.REGISTER].map((e=>{b[e]&&(T[e]=function(t){return new Promise(((n,i)=>{r.emit(u+e,t,((e,t)=>{e?i(e):n(t)}))}))})}))}P.map((e=>{w[e]=function(...t){return new Promise(((n,s)=>{r.emit(i.CHANNELS.METHOD,{method:e,params:t},((e,t)=>{e?s(e):n(t)}))}))}})),w=Object.freeze(w),N&&(E.sql=function(e,t,n){return new Promise(((s,o)=>{r.emit(i.CHANNELS.SQL,{query:e,params:t,options:n},((e,t)=>{if(e)o(e);else if(n&&"noticeSubscription"===n.returnType&&t&&Object.keys(t).sort().join()===["socketChannel","socketUnsubChannel"].sort().join()&&!Object.values(t).find((e=>"string"!=typeof e))){const e=t,n=t=>(((e,t)=>{d=d||{config:t,listeners:[]},d.listeners.length||(r.removeAllListeners(t.socketChannel),r.on(t.socketChannel,(e=>{d&&d.listeners&&d.listeners.length?d.listeners.map((t=>{t(e)})):r.emit(t.socketUnsubChannel,{})}))),d.listeners.push(e)})(t,e),{...e,removeListener:()=>(e=>{d&&(d.listeners=d.listeners.filter((t=>t!==e)),!d.listeners.length&&d.config&&d.config.socketUnsubChannel&&r&&r.emit(d.config.socketUnsubChannel,{}))})(t)}),i={...e,addListener:n};s(i)}else if(n&&n.returnType&&"statement"===n.returnType||!t||Object.keys(t).sort().join()!==["socketChannel","socketUnsubChannel","notifChannel"].sort().join()||Object.values(t).find((e=>"string"!=typeof e)))s(t);else{const e=e=>(((e,t)=>{g=g||{},g[t.notifChannel]?g[t.notifChannel].listeners.push(e):(g[t.notifChannel]={config:t,listeners:[e]},r.removeAllListeners(t.socketChannel),r.on(t.socketChannel,(e=>{g[t.notifChannel]&&g[t.notifChannel].listeners&&g[t.notifChannel].listeners.length?g[t.notifChannel].listeners.map((t=>{t(e)})):r.emit(g[t.notifChannel].config.socketUnsubChannel,{})})))})(e,t),{...t,removeListener:()=>((e,t)=>{g&&g[t.notifChannel]&&(g[t.notifChannel].listeners=g[t.notifChannel].listeners.filter((t=>t!==e)),!g[t.notifChannel].listeners.length&&g[t.notifChannel].config&&g[t.notifChannel].config.socketUnsubChannel&&r&&(r.emit(g[t.notifChannel].config.socketUnsubChannel,{}),delete g[t.notifChannel]))})(e,t)}),n={...t,addListener:e};s(n)}}))}))});const A=e=>"[object Object]"===Object.prototype.toString.call(e),x=(e,t,n,i)=>{if(!A(e)||!A(t)||"function"!=typeof n||i&&"function"!=typeof i)throw"Expecting: ( basicFilter<object>, options<object>, onChange<function> , onError?<function>) but got something else"},G=["subscribe","subscribeOne"];Object.keys(E).forEach((e=>{Object.keys(E[e]).sort(((e,t)=>G.includes(e)-G.includes(t))).forEach((t=>{if(["find","findOne"].includes(t)&&(E[e].getJoinedTables=function(){return(C||[]).filter((t=>Array.isArray(t)&&t.includes(e))).flat().filter((t=>t!==e))}),"sync"===t){if(E[e]._syncInfo={...E[e][t]},n){E[e].getSync=(t,i={})=>n.create({name:e,filter:t,db:E,...i});const t=async(t={},i={},r)=>{const s=`${e}.${JSON.stringify(t)}.${JSON.stringify(i)}`;return m[s]||(m[s]=await n.create({...i,name:e,filter:t,db:E,onError:r})),m[s]};E[e].sync=async(e,n={handlesOnData:!0,select:"*"},i,r)=>{x(e,n,i,r);const s=await t(e,n,r);return await s.sync(i,n.handlesOnData)},E[e].syncOne=async(e,n={handlesOnData:!0},i,r)=>{x(e,n,i,r);const s=await t(e,n,r);return await s.syncOne(e,i,n.handlesOnData)}}E[e]._sync=function(n,i,r){return async function(e,t){return O.run([e,t])}({tableName:e,command:t,param1:n,param2:i},r)}}else if(G.includes(t)){E[e][t]=function(n,i,r,s){return x(n,i,r,s),v(E,{tableName:e,command:t,param1:n,param2:i},r,s)};const n="subscribeOne";t!==n&&G.includes(n)||(E[e][n]=function(n,i,r,s){return x(n,i,r,s),v(E,{tableName:e,command:t,param1:n,param2:i},(e=>{r(e[0])}),s)})}else E[e][t]=function(n,i,s){return new Promise(((o,a)=>{r.emit(u,{tableName:e,command:t,param1:n,param2:i,param3:s},((e,t)=>{e?a(e):o(t)}))}))}}))})),f&&Object.keys(f).length&&Object.keys(f).map((async e=>{try{let t=f[e];await S(t),r.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting old subscriptions",e)}})),h&&Object.keys(h).length&&Object.keys(h).filter((e=>h[e].triggers&&h[e].triggers.length)).map((async e=>{try{let t=h[e];await _(t,t.triggers[0].onSyncRequest),r.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting olf subscriptions",e)}})),C.flat().map((e=>{function t(t=!0,n,i,r){return{[t?"$leftJoin":"$innerJoin"]:e,filter:n,select:i,...r}}E.innerJoin=E.innerJoin||{},E.leftJoin=E.leftJoin||{},E.innerJoinOne=E.innerJoinOne||{},E.leftJoinOne=E.leftJoinOne||{},E.leftJoin[e]=(e,n,i={})=>t(!0,e,n,i),E.innerJoin[e]=(e,n,i={})=>t(!1,e,n,i),E.leftJoinOne[e]=(e,n,i={})=>t(!0,e,n,{...i,limit:1}),E.innerJoinOne[e]=(e,n,i={})=>t(!1,e,n,{...i,limit:1})})),(async()=>{try{await s(E,w,p,T)}catch(e){console.error("Prostgles: Error within onReady: \n",e),o(e)}e(E)})()}))}))};class o{constructor(e){this.queue=[],this.isRunning=!1,this.func=e}async run(e){const t=new Promise(((t,n)=>{const i={arguments:e,onResult:t};this.queue.push(i)})),n=async()=>{if(this.isRunning)return;this.isRunning=!0;const e=this.queue.shift();if(e){const t=await this.func(...e.arguments);e.onResult(t)}this.isRunning=!1,this.queue.length&&n()};return n(),t}}},792:function(e){var t;this||window,t=()=>(()=>{"use strict";var e={444:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EXISTS_KEYS=t.GeomFilter_Funcs=t.GeomFilterKeys=t.ArrayFilterOperands=t.TextFilter_FullTextSearchFilterKeys=t.TextFilterFTSKeys=t.TextFilterKeys=t.CompareInFilterKeys=t.CompareFilterKeys=void 0,t.CompareFilterKeys=["=","$eq","<>",">",">=","<=","$eq","$ne","$gt","$gte","$lte"],t.CompareInFilterKeys=["$in","$nin"],t.TextFilterKeys=["$ilike","$like"],t.TextFilterFTSKeys=["@@","@>","<@","$contains","$containedBy"],t.TextFilter_FullTextSearchFilterKeys=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"],t.ArrayFilterOperands=[...t.TextFilterFTSKeys,"&&","$overlaps"],t.GeomFilterKeys=["~","~=","@","|&>","|>>",">>","=","<<|","<<","&>","&<|","&<","&&&","&&"];const n=["ST_MakeEnvelope","ST_MakePolygon"];t.GeomFilter_Funcs=n.concat(n.map((e=>e.toLowerCase()))),t.EXISTS_KEYS=["$exists","$notExists","$existsJoined","$notExistsJoined"]},590:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),r=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0}),t.getKeys=t.isObject=t.isDefined=t.get=t.WAL=t.unpatchText=t.stableStringify=t.isEmpty=t.getTextPatch=t.asName=t.RULE_METHODS=t.CHANNELS=t.TS_PG_Types=t._PG_postgis=t._PG_date=t._PG_bool=t._PG_json=t._PG_numbers=t._PG_strings=void 0,t._PG_strings=["bpchar","char","varchar","text","citext","uuid","bytea","inet","time","timetz","interval","name"],t._PG_numbers=["int2","int4","int8","float4","float8","numeric","money","oid"],t._PG_json=["json","jsonb"],t._PG_bool=["bool"],t._PG_date=["date","timestamp","timestamptz"],t._PG_postgis=["geometry","geography"],t.TS_PG_Types={string:t._PG_strings,number:t._PG_numbers,boolean:t._PG_bool,Date:t._PG_date,"Array<number>":t._PG_numbers.map((e=>`_${e}`)),"Array<boolean>":t._PG_bool.map((e=>`_${e}`)),"Array<string>":t._PG_strings.map((e=>`_${e}`)),"Array<Object>":t._PG_json.map((e=>`_${e}`)),"Array<Date>":t._PG_date.map((e=>`_${e}`)),any:[]};const s="_psqlWS_.";t.CHANNELS={SCHEMA_CHANGED:s+"schema-changed",SCHEMA:s+"schema",DEFAULT:s,SQL:"_psqlWS_.sql",METHOD:"_psqlWS_.method",NOTICE_EV:"_psqlWS_.notice",LISTEN_EV:"_psqlWS_.listen",REGISTER:"_psqlWS_.register",LOGIN:"_psqlWS_.login",LOGOUT:"_psqlWS_.logout",AUTHGUARD:"_psqlWS_.authguard",_preffix:s},t.RULE_METHODS={getColumns:["getColumns"],getInfo:["getInfo"],insert:["insert","upsert"],update:["update","upsert","updateBatch"],select:["findOne","find","count","size"],delete:["delete","remove"],sync:["sync","unsync"],subscribe:["unsubscribe","subscribe","subscribeOne"]};var o=n(128);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return o.asName}}),Object.defineProperty(t,"getTextPatch",{enumerable:!0,get:function(){return o.getTextPatch}}),Object.defineProperty(t,"isEmpty",{enumerable:!0,get:function(){return o.isEmpty}}),Object.defineProperty(t,"stableStringify",{enumerable:!0,get:function(){return o.stableStringify}}),Object.defineProperty(t,"unpatchText",{enumerable:!0,get:function(){return o.unpatchText}}),Object.defineProperty(t,"WAL",{enumerable:!0,get:function(){return o.WAL}}),Object.defineProperty(t,"get",{enumerable:!0,get:function(){return o.get}}),Object.defineProperty(t,"isDefined",{enumerable:!0,get:function(){return o.isDefined}}),Object.defineProperty(t,"isObject",{enumerable:!0,get:function(){return o.isObject}}),Object.defineProperty(t,"getKeys",{enumerable:!0,get:function(){return o.getKeys}}),r(n(444),t)},899:(e,t)=>{function n(e,t){var n=e[0],i=e[1],c=e[2],l=e[3];n=r(n,i,c,l,t[0],7,-680876936),l=r(l,n,i,c,t[1],12,-389564586),c=r(c,l,n,i,t[2],17,606105819),i=r(i,c,l,n,t[3],22,-1044525330),n=r(n,i,c,l,t[4],7,-176418897),l=r(l,n,i,c,t[5],12,1200080426),c=r(c,l,n,i,t[6],17,-1473231341),i=r(i,c,l,n,t[7],22,-45705983),n=r(n,i,c,l,t[8],7,1770035416),l=r(l,n,i,c,t[9],12,-1958414417),c=r(c,l,n,i,t[10],17,-42063),i=r(i,c,l,n,t[11],22,-1990404162),n=r(n,i,c,l,t[12],7,1804603682),l=r(l,n,i,c,t[13],12,-40341101),c=r(c,l,n,i,t[14],17,-1502002290),n=s(n,i=r(i,c,l,n,t[15],22,1236535329),c,l,t[1],5,-165796510),l=s(l,n,i,c,t[6],9,-1069501632),c=s(c,l,n,i,t[11],14,643717713),i=s(i,c,l,n,t[0],20,-373897302),n=s(n,i,c,l,t[5],5,-701558691),l=s(l,n,i,c,t[10],9,38016083),c=s(c,l,n,i,t[15],14,-660478335),i=s(i,c,l,n,t[4],20,-405537848),n=s(n,i,c,l,t[9],5,568446438),l=s(l,n,i,c,t[14],9,-1019803690),c=s(c,l,n,i,t[3],14,-187363961),i=s(i,c,l,n,t[8],20,1163531501),n=s(n,i,c,l,t[13],5,-1444681467),l=s(l,n,i,c,t[2],9,-51403784),c=s(c,l,n,i,t[7],14,1735328473),n=o(n,i=s(i,c,l,n,t[12],20,-1926607734),c,l,t[5],4,-378558),l=o(l,n,i,c,t[8],11,-2022574463),c=o(c,l,n,i,t[11],16,1839030562),i=o(i,c,l,n,t[14],23,-35309556),n=o(n,i,c,l,t[1],4,-1530992060),l=o(l,n,i,c,t[4],11,1272893353),c=o(c,l,n,i,t[7],16,-155497632),i=o(i,c,l,n,t[10],23,-1094730640),n=o(n,i,c,l,t[13],4,681279174),l=o(l,n,i,c,t[0],11,-358537222),c=o(c,l,n,i,t[3],16,-722521979),i=o(i,c,l,n,t[6],23,76029189),n=o(n,i,c,l,t[9],4,-640364487),l=o(l,n,i,c,t[12],11,-421815835),c=o(c,l,n,i,t[15],16,530742520),n=a(n,i=o(i,c,l,n,t[2],23,-995338651),c,l,t[0],6,-198630844),l=a(l,n,i,c,t[7],10,1126891415),c=a(c,l,n,i,t[14],15,-1416354905),i=a(i,c,l,n,t[5],21,-57434055),n=a(n,i,c,l,t[12],6,1700485571),l=a(l,n,i,c,t[3],10,-1894986606),c=a(c,l,n,i,t[10],15,-1051523),i=a(i,c,l,n,t[1],21,-2054922799),n=a(n,i,c,l,t[8],6,1873313359),l=a(l,n,i,c,t[15],10,-30611744),c=a(c,l,n,i,t[6],15,-1560198380),i=a(i,c,l,n,t[13],21,1309151649),n=a(n,i,c,l,t[4],6,-145523070),l=a(l,n,i,c,t[11],10,-1120210379),c=a(c,l,n,i,t[2],15,718787259),i=a(i,c,l,n,t[9],21,-343485551),e[0]=f(n,e[0]),e[1]=f(i,e[1]),e[2]=f(c,e[2]),e[3]=f(l,e[3])}function i(e,t,n,i,r,s){return t=f(f(t,e),f(i,s)),f(t<<r|t>>>32-r,n)}function r(e,t,n,r,s,o,a){return i(t&n|~t&r,e,t,s,o,a)}function s(e,t,n,r,s,o,a){return i(t&r|n&~r,e,t,s,o,a)}function o(e,t,n,r,s,o,a){return i(t^n^r,e,t,s,o,a)}function a(e,t,n,r,s,o,a){return i(n^(t|~r),e,t,s,o,a)}function c(e){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}Object.defineProperty(t,"__esModule",{value:!0}),t.md5=t.md5cycle=void 0,t.md5cycle=n;var l="0123456789abcdef".split("");function u(e){for(var t="",n=0;n<4;n++)t+=l[e>>8*n+4&15]+l[e>>8*n&15];return t}function d(e){return function(e){for(var t=0;t<e.length;t++)e[t]=u(e[t]);return e.join("")}(function(e){var t,i=e.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=e.length;t+=64)n(r,c(e.substring(t-64,t)));e=e.substring(t-64);var s=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t<e.length;t++)s[t>>2]|=e.charCodeAt(t)<<(t%4<<3);if(s[t>>2]|=128<<(t%4<<3),t>55)for(n(r,s),t=0;t<16;t++)s[t]=0;return s[14]=8*i,n(r,s),r}(e))}function f(e,t){return e+t&4294967295}t.md5=d,d("hello")},128:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getKeys=t.isDefined=t.isObject=t.get=t.isEmpty=t.WAL=t.unpatchText=t.getTextPatch=t.stableStringify=t.asName=void 0;const i=n(899);function r(e){for(var t in e)return!1;return!0}t.asName=function(e){if(null==e||!e.toString||!e.toString())throw"Expecting a non empty string";return`"${e.toString().replace(/"/g,'""')}"`},t.stableStringify=function(e,t){t||(t={}),"function"==typeof t&&(t={cmp:t});var n,i="boolean"==typeof t.cycles&&t.cycles,r=t.cmp&&(n=t.cmp,function(e){return function(t,i){var r={key:t,value:e[t]},s={key:i,value:e[i]};return n(r,s)}}),s=[];return function e(t){if(t&&t.toJSON&&"function"==typeof t.toJSON&&(t=t.toJSON()),void 0!==t){if("number"==typeof t)return isFinite(t)?""+t:"null";if("object"!=typeof t)return JSON.stringify(t);var n,o;if(Array.isArray(t)){for(o="[",n=0;n<t.length;n++)n&&(o+=","),o+=e(t[n])||"null";return o+"]"}if(null===t)return"null";if(-1!==s.indexOf(t)){if(i)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var a=s.push(t)-1,c=Object.keys(t).sort(r&&r(t));for(o="",n=0;n<c.length;n++){var l=c[n],u=e(t[l]);u&&(o&&(o+=","),o+=JSON.stringify(l)+":"+u)}return s.splice(a,1),"{"+o+"}"}}(e)},t.getTextPatch=function(e,t){if(!(e&&t&&e.trim().length&&t.trim().length))return t;if(e===t)return{from:0,to:0,text:"",md5:(0,i.md5)(t)};function n(n=1){let i=n<1?-1:0,r=!1;for(;!r&&Math.abs(i)<=t.length;){const s=n<1?[i]:[0,i];e.slice(...s)!==t.slice(...s)?r=!0:i+=1*Math.sign(n)}return i}let r=n()-1,s=e.length+n(-1)+1,o=t.length+n(-1)+1;return{from:r,to:s,text:t.slice(r,o),md5:(0,i.md5)(t)}},t.unpatchText=function(e,t){if(!t||"string"==typeof t)return t;const{from:n,to:r,text:s,md5:o}=t;if(null===s||null===e)return s;let a=e.slice(0,n)+s+e.slice(r);if(o&&(0,i.md5)(a)!==o)throw"Patch text error: Could not match md5 hash: (original/result) \n"+e+"\n"+a;return a},t.WAL=class{constructor(e){if(this.changed={},this.sending={},this.sentHistory={},this.callbacks=[],this.sort=(e,t)=>{const{orderBy:n}=this.options;return n&&e&&t&&n.map((n=>{if(!(n.fieldName in e)||!(n.fieldName in t))throw"Replication error: \n some orderBy fields missing from data";let i=n.asc?e[n.fieldName]:t[n.fieldName],r=n.asc?t[n.fieldName]:e[n.fieldName],s=+i-+r,o=i<r?-1:i==r?0:1;return"number"===n.tsDataType&&Number.isFinite(s)?s:o})).find((e=>e))||0},this.isInHistory=e=>{if(!e)throw"Provide item";const t=e[this.options.synced_field];if(!Number.isFinite(+t))throw"Provided item Synced field value is missing/invalid ";const n=this.sentHistory[this.getIdStr(e)],i=n?.[this.options.synced_field];if(n){if(!Number.isFinite(+i))throw"Provided historic item Synced field value is missing/invalid";if(+i==+t)return!0}return!1},this.addData=e=>{r(this.changed)&&this.options.onSendStart&&this.options.onSendStart(),e.map((e=>{var t;const{initial:n,current:i}={...e};if(!i)throw"Expecting { current: object, initial?: object }";const r=this.getIdStr(i);this.changed??(this.changed={}),(t=this.changed)[r]??(t[r]={initial:n,current:i}),this.changed[r].current={...this.changed[r].current,...i}})),this.sendItems()},this.isOnSending=!1,this.isSendingTimeout=void 0,this.willDeleteHistory=void 0,this.sendItems=async()=>{const{DEBUG_MODE:e,onSend:t,onSendEnd:n,batch_size:i,throttle:s,historyAgeSeconds:o=2}=this.options;if(this.isSendingTimeout||this.sending&&!r(this.sending))return;if(!this.changed||r(this.changed))return;let a,c=[],l=[],u={};Object.keys(this.changed).sort(((e,t)=>this.sort(this.changed[e].current,this.changed[t].current))).slice(0,i).map((e=>{let t={...this.changed[e]};this.sending[e]={...t},l.push({...t}),u[e]={...t.current},delete this.changed[e]})),c=l.map((e=>e.current)),e&&console.log(this.options.id," SENDING lr->",c[c.length-1]),this.isSendingTimeout||(this.isSendingTimeout=setTimeout((()=>{this.isSendingTimeout=void 0,r(this.changed)||this.sendItems()}),s)),this.isOnSending=!0;try{await t(c,l),o&&(this.sentHistory={...this.sentHistory,...u},this.willDeleteHistory||(this.willDeleteHistory=setTimeout((()=>{this.willDeleteHistory=void 0,this.sentHistory={}}),1e3*o)))}catch(e){a=e,console.error("WAL onSend failed:",e,c,l)}if(this.isOnSending=!1,this.callbacks.length){const e=Object.keys(this.sending);this.callbacks.forEach(((t,n)=>{t.idStrs=t.idStrs.filter((t=>e.includes(t))),t.idStrs.length||t.cb(a)})),this.callbacks=this.callbacks.filter((e=>e.idStrs.length))}this.sending={},e&&console.log(this.options.id," SENT lr->",c[c.length-1]),r(this.changed)?n&&n(c,l,a):this.sendItems()},this.options={...e},!this.options.orderBy){const{synced_field:t,id_fields:n}=e;this.options.orderBy=[t,...n.sort()].map((e=>({fieldName:e,tsDataType:e===t?"number":"string",asc:!0})))}}isSending(){const e=this.isOnSending||!(r(this.sending)&&r(this.changed));return this.options.DEBUG_MODE&&console.log(this.options.id," CHECKING isSending ->",e),e}getIdStr(e){return this.options.id_fields.sort().map((t=>`${e[t]||""}`)).join(".")}getIdObj(e){let t={};return this.options.id_fields.sort().map((n=>{t[n]=e[n]})),t}getDeltaObj(e){let t={};return Object.keys(e).map((n=>{this.options.id_fields.includes(n)||(t[n]=e[n])})),t}},t.isEmpty=r,t.get=function(e,t){let n=t,i=e;return e?("string"==typeof n&&(n=n.split(".")),n.reduce(((e,t)=>e&&e[t]?e[t]:void 0),i)):e},t.isObject=function(e){return Boolean(e&&"object"==typeof e&&!Array.isArray(e))},t.isDefined=function(e){return null!=e},t.getKeys=function(e){return Object.keys(e)}}},t={};return function n(i){var r=t[i];if(void 0!==r)return r.exports;var s=t[i]={exports:{}};return e[i].call(s.exports,s,s.exports,n),s.exports}(590)})(),e.exports=t()}},t={},function n(i){var r=t[i];if(void 0!==r)return r.exports;var s=t[i]={exports:{}};return e[i].call(s.exports,s,s.exports,n),s.exports}(274);var e,t}));
|
package/dist/prostgles.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prostgles.d.ts","sourceRoot":"","sources":["../lib/prostgles.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,WAAW,EACjD,cAAc,EACE,SAAS,EACzB,UAAU,EAAqC,aAAa,EACjC,aAAa,EAA+D,SAAS,EACnH,MAAM,iBAAiB,CAAC;AAGzB,OAAO,KAAK,EAAe,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAMhE,eAAO,MAAM,KAAK,EAAE,GAInB,CAAC;AAEF,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,CAAC;AAEpC,oBAAY,kBAAkB,CAAC,CAAC,GAAG,SAAS,IAAI,YAAY,CAAC,CAAC,CAAC,GAAG;IAC9D,eAAe,EAAE,MAAM,MAAM,EAAE,CAAC;IAChC,SAAS,CAAC,EAAE,GAAG,CAAC;IAChB,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,GAAG,CAAC;CACf,CAAA;AACD,oBAAY,uBAAuB,GAAG,iBAAiB,GAAG;IACtD,eAAe,EAAE,MAAM,MAAM,EAAE,CAAC;IAChC,SAAS,CAAC,EAAE,GAAG,CAAC;IAChB,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,GAAG,CAAC;CACf,CAAA;AAED,oBAAY,eAAe,CAAC,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI;KACnG,GAAG,IAAI,MAAM,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;CAClE,GAAG,WAAW,GAAG;IACd,GAAG,CAAC,EAAE,UAAU,CAAC;CACpB,CAAC;AAUF,oBAAY,oBAAoB,GAAG;IAC/B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAC;CACjD,GAAG;IACF,SAAS,EAAE,cAAc,CAAC;IAC1B,QAAQ,EAAE,cAAc,CAAC;IACzB,YAAY,EAAE,cAAc,CAAC;IAC7B,WAAW,EAAE,cAAc,CAAC;CAC7B,GAAG;IAEF;;;;;OAKG;IACH,GAAG,CAAC,EAAE,UAAU,CAAC;CACpB,CAAC;AAEF,oBAAY,IAAI,GAAG;IACf,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IACzC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IACtC,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IACvC,IAAI,CAAC,EAAE,GAAG,CAAC;CACd,CAAA;AAED,oBAAY,WAAW,GAAG;IACtB,MAAM,EAAE,GAAG,CAAC;IAEZ;;OAEG;IACH,cAAc,CAAC,EAAE,KAAK,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC;IACtC,OAAO,EAAE,CAAC,GAAG,EAAE,eAAe,EAAE,OAAO,EAAE,aAAa,GAAG,SAAS,EAAE,WAAW,EAAE,aAAa,EAAE,GAAG,SAAS,EAAE,IAAI,CAAC,EAAE,IAAI,KAAK,GAAG,CAAC;IAClI,WAAW,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,GAAG,CAAC;IACnC,YAAY,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,GAAG,CAAC;CACvC,CAAA;AAsBD,oBAAY,eAAe,GAAG;IAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAA;CAAE,CAAA;AAQnE,oBAAY,QAAQ,GAAG;IACnB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAA;CACtB,CAAA;AASD,wBAAgB,SAAS,CAAC,QAAQ,EAAE,WAAW,EAAE,WAAW,EAAE,GAAG,
|
|
1
|
+
{"version":3,"file":"prostgles.d.ts","sourceRoot":"","sources":["../lib/prostgles.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,WAAW,EACjD,cAAc,EACE,SAAS,EACzB,UAAU,EAAqC,aAAa,EACjC,aAAa,EAA+D,SAAS,EACnH,MAAM,iBAAiB,CAAC;AAGzB,OAAO,KAAK,EAAe,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAMhE,eAAO,MAAM,KAAK,EAAE,GAInB,CAAC;AAEF,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,CAAC;AAEpC,oBAAY,kBAAkB,CAAC,CAAC,GAAG,SAAS,IAAI,YAAY,CAAC,CAAC,CAAC,GAAG;IAC9D,eAAe,EAAE,MAAM,MAAM,EAAE,CAAC;IAChC,SAAS,CAAC,EAAE,GAAG,CAAC;IAChB,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,GAAG,CAAC;CACf,CAAA;AACD,oBAAY,uBAAuB,GAAG,iBAAiB,GAAG;IACtD,eAAe,EAAE,MAAM,MAAM,EAAE,CAAC;IAChC,SAAS,CAAC,EAAE,GAAG,CAAC;IAChB,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,GAAG,CAAC;CACf,CAAA;AAED,oBAAY,eAAe,CAAC,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI;KACnG,GAAG,IAAI,MAAM,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;CAClE,GAAG,WAAW,GAAG;IACd,GAAG,CAAC,EAAE,UAAU,CAAC;CACpB,CAAC;AAUF,oBAAY,oBAAoB,GAAG;IAC/B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,uBAAuB,CAAC,CAAC;CACjD,GAAG;IACF,SAAS,EAAE,cAAc,CAAC;IAC1B,QAAQ,EAAE,cAAc,CAAC;IACzB,YAAY,EAAE,cAAc,CAAC;IAC7B,WAAW,EAAE,cAAc,CAAC;CAC7B,GAAG;IAEF;;;;;OAKG;IACH,GAAG,CAAC,EAAE,UAAU,CAAC;CACpB,CAAC;AAEF,oBAAY,IAAI,GAAG;IACf,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IACzC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IACtC,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IACvC,IAAI,CAAC,EAAE,GAAG,CAAC;CACd,CAAA;AAED,oBAAY,WAAW,GAAG;IACtB,MAAM,EAAE,GAAG,CAAC;IAEZ;;OAEG;IACH,cAAc,CAAC,EAAE,KAAK,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC;IACtC,OAAO,EAAE,CAAC,GAAG,EAAE,eAAe,EAAE,OAAO,EAAE,aAAa,GAAG,SAAS,EAAE,WAAW,EAAE,aAAa,EAAE,GAAG,SAAS,EAAE,IAAI,CAAC,EAAE,IAAI,KAAK,GAAG,CAAC;IAClI,WAAW,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,GAAG,CAAC;IACnC,YAAY,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,GAAG,CAAC;CACvC,CAAA;AAsBD,oBAAY,eAAe,GAAG;IAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAA;CAAE,CAAA;AAQnE,oBAAY,QAAQ,GAAG;IACnB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAA;CACtB,CAAA;AASD,wBAAgB,SAAS,CAAC,QAAQ,EAAE,WAAW,EAAE,WAAW,EAAE,GAAG,oBAiuBhE"}
|
package/dist/prostgles.js
CHANGED
|
@@ -195,7 +195,11 @@ function prostgles(initOpts, syncedTable) {
|
|
|
195
195
|
});
|
|
196
196
|
});
|
|
197
197
|
}
|
|
198
|
-
|
|
198
|
+
const addSyncQueuer = new FunctionQueuer(_addSync);
|
|
199
|
+
async function addSync(params, triggers) {
|
|
200
|
+
return addSyncQueuer.run([params, triggers]);
|
|
201
|
+
}
|
|
202
|
+
async function _addSync({ tableName, command, param1, param2 }, triggers) {
|
|
199
203
|
const { onPullRequest, onSyncRequest, onUpdates } = triggers;
|
|
200
204
|
function makeHandler(channelName) {
|
|
201
205
|
let unsync = function () {
|
|
@@ -313,7 +317,9 @@ function prostgles(initOpts, syncedTable) {
|
|
|
313
317
|
/**
|
|
314
318
|
* Can be used concurrently
|
|
315
319
|
*/
|
|
320
|
+
const addSubQueuer = new FunctionQueuer(_addSub);
|
|
316
321
|
async function addSub(dbo, params, onChange, _onError) {
|
|
322
|
+
return addSubQueuer.run([dbo, params, onChange, _onError]);
|
|
317
323
|
const result = new Promise((resolve, reject) => {
|
|
318
324
|
const item = { dbo, params, onChange, _onError, returnHandlers: (subHandlers) => {
|
|
319
325
|
resolve(subHandlers);
|
|
@@ -321,7 +327,7 @@ function prostgles(initOpts, syncedTable) {
|
|
|
321
327
|
addSubQueue.push(item);
|
|
322
328
|
});
|
|
323
329
|
const startQueueJob = async () => {
|
|
324
|
-
if (
|
|
330
|
+
if (isAddingSub) {
|
|
325
331
|
return;
|
|
326
332
|
}
|
|
327
333
|
const addingSub = addSubQueue.shift();
|
|
@@ -696,3 +702,33 @@ function prostgles(initOpts, syncedTable) {
|
|
|
696
702
|
}
|
|
697
703
|
exports.prostgles = prostgles;
|
|
698
704
|
;
|
|
705
|
+
class FunctionQueuer {
|
|
706
|
+
constructor(func) {
|
|
707
|
+
this.queue = [];
|
|
708
|
+
this.isRunning = false;
|
|
709
|
+
this.func = func;
|
|
710
|
+
}
|
|
711
|
+
async run(args) {
|
|
712
|
+
const result = new Promise((resolve, reject) => {
|
|
713
|
+
const item = { arguments: args, onResult: resolve };
|
|
714
|
+
this.queue.push(item);
|
|
715
|
+
});
|
|
716
|
+
const startQueueJob = async () => {
|
|
717
|
+
if (this.isRunning) {
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
this.isRunning = true;
|
|
721
|
+
const item = this.queue.shift();
|
|
722
|
+
if (item) {
|
|
723
|
+
const result = await this.func(...item.arguments);
|
|
724
|
+
item.onResult(result);
|
|
725
|
+
}
|
|
726
|
+
this.isRunning = false;
|
|
727
|
+
if (this.queue.length) {
|
|
728
|
+
startQueueJob();
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
startQueueJob();
|
|
732
|
+
return result;
|
|
733
|
+
}
|
|
734
|
+
}
|
package/lib/prostgles.ts
CHANGED
|
@@ -331,7 +331,11 @@ export function prostgles(initOpts: InitOptions, syncedTable: any){
|
|
|
331
331
|
});
|
|
332
332
|
}
|
|
333
333
|
|
|
334
|
-
|
|
334
|
+
const addSyncQueuer = new FunctionQueuer(_addSync);
|
|
335
|
+
async function addSync(params: CoreParams, triggers: ClientSyncHandles): Promise<any> {
|
|
336
|
+
return addSyncQueuer.run([params, triggers])
|
|
337
|
+
}
|
|
338
|
+
async function _addSync({ tableName, command, param1, param2 }: CoreParams, triggers: ClientSyncHandles): Promise<any> {
|
|
335
339
|
const { onPullRequest, onSyncRequest, onUpdates } = triggers;
|
|
336
340
|
|
|
337
341
|
function makeHandler(channelName: string){
|
|
@@ -453,10 +457,14 @@ export function prostgles(initOpts: InitOptions, syncedTable: any){
|
|
|
453
457
|
}
|
|
454
458
|
|
|
455
459
|
}
|
|
460
|
+
|
|
456
461
|
/**
|
|
457
462
|
* Can be used concurrently
|
|
458
463
|
*/
|
|
464
|
+
const addSubQueuer = new FunctionQueuer(_addSub);
|
|
465
|
+
|
|
459
466
|
async function addSub<T>(dbo: any, params: CoreParams, onChange: Function, _onError: Function): Promise<SubscriptionHandler<T>> {
|
|
467
|
+
return addSubQueuer.run([dbo, params, onChange, _onError]);
|
|
460
468
|
const result = new Promise<SubscriptionHandler<T>>((resolve, reject) => {
|
|
461
469
|
const item = { dbo, params, onChange, _onError, returnHandlers: (subHandlers: SubscriptionHandler<T>) => {
|
|
462
470
|
resolve(subHandlers)
|
|
@@ -465,7 +473,7 @@ export function prostgles(initOpts: InitOptions, syncedTable: any){
|
|
|
465
473
|
});
|
|
466
474
|
|
|
467
475
|
const startQueueJob = async () => {
|
|
468
|
-
if(
|
|
476
|
+
if(isAddingSub) {
|
|
469
477
|
return;
|
|
470
478
|
}
|
|
471
479
|
const addingSub = addSubQueue.shift();
|
|
@@ -482,6 +490,7 @@ export function prostgles(initOpts: InitOptions, syncedTable: any){
|
|
|
482
490
|
|
|
483
491
|
return result;
|
|
484
492
|
}
|
|
493
|
+
|
|
485
494
|
/**
|
|
486
495
|
* Do NOT use concurrently
|
|
487
496
|
*/
|
|
@@ -864,3 +873,41 @@ export function prostgles(initOpts: InitOptions, syncedTable: any){
|
|
|
864
873
|
|
|
865
874
|
})
|
|
866
875
|
};
|
|
876
|
+
|
|
877
|
+
type Func = (...args: any[]) => any;
|
|
878
|
+
class FunctionQueuer<F extends Func> {
|
|
879
|
+
private queue: { arguments: Parameters<F>; onResult: (result: ReturnType<F>) => void }[] = [];
|
|
880
|
+
private func: F;
|
|
881
|
+
constructor(func: F){
|
|
882
|
+
this.func = func;
|
|
883
|
+
}
|
|
884
|
+
private isRunning = false;
|
|
885
|
+
async run(args: Parameters<F>): Promise<ReturnType<F>> {
|
|
886
|
+
|
|
887
|
+
const result = new Promise<ReturnType<F>>((resolve, reject) => {
|
|
888
|
+
const item = { arguments: args, onResult: resolve }
|
|
889
|
+
this.queue.push(item);
|
|
890
|
+
});
|
|
891
|
+
|
|
892
|
+
const startQueueJob = async () => {
|
|
893
|
+
if(this.isRunning) {
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
this.isRunning = true;
|
|
897
|
+
const item = this.queue.shift();
|
|
898
|
+
if(item){
|
|
899
|
+
const result = await this.func(...item.arguments);
|
|
900
|
+
item.onResult(result);
|
|
901
|
+
}
|
|
902
|
+
this.isRunning = false;
|
|
903
|
+
if(this.queue.length){
|
|
904
|
+
startQueueJob();
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
startQueueJob();
|
|
909
|
+
|
|
910
|
+
return result;
|
|
911
|
+
|
|
912
|
+
}
|
|
913
|
+
}
|