prostgles-client 4.0.5 → 4.0.7
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/SyncedTable.js +1 -1
- package/dist/index.js +1 -1
- package/dist/index.no-sync.js +1 -1
- package/dist/prostgles.d.ts +5 -29
- package/dist/prostgles.d.ts.map +1 -1
- package/dist/prostgles.js +33 -23
- package/lib/SyncedTable.ts +4 -4
- package/lib/prostgles.ts +73 -66
- package/package.json +2 -2
- package/tsconfig.json +3 -1
package/dist/SyncedTable.js
CHANGED
|
@@ -762,7 +762,7 @@ class SyncedTable {
|
|
|
762
762
|
}
|
|
763
763
|
get tableHandler() {
|
|
764
764
|
const tblHandler = this.db[this.name];
|
|
765
|
-
if (tblHandler.update && tblHandler.updateBatch) {
|
|
765
|
+
if ((tblHandler === null || tblHandler === void 0 ? void 0 : tblHandler.update) && tblHandler.updateBatch) {
|
|
766
766
|
return tblHandler;
|
|
767
767
|
}
|
|
768
768
|
return undefined;
|
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.quickClone=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{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}constructor({name:e,filter:n,onChange:s,onReady:a,db:u,skipFirstTrigger:d=!1,select:h="*",storageType:p="object",patchText:m=!1,patchJSON:f=!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 d=this.getItem(c),h=d.index,p=d.data;!t&&!(0,i.isEmpty)(u)||(0,i.isEmpty)(p)||(u=this.getDelta(p||{},u)),t||(u[this.synced_field]=Date.now());let m={...p,...u,...c};p&&!t&&(null===(s=e.opts)||void 0===s?void 0:s.deepMerge)&&(m=l({...p,...c},{...u})),r=p?p[this.synced_field]<m[this.synced_field]?"updated":"unchanged":"inserted",this.setItem(m,h);let f={idObj:c,delta:u,oldItem:p,newItem:m,status:r,from_server:t};return t||a.push({initial:p,current:{...m}}),f.delta&&!(0,i.isEmpty)(f.delta)&&o.push(f),!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=>{const t=c(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(t))}else this.storageType===o.array?this.items=t:this.itemsObj=t.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 c(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[p])throw"Invalid storage type. Expecting one of: "+Object.keys(o).join(", ");if(r||p!==o.localStorage||(console.warn("Could not set storageType to localStorage: window object missing\nStorage changed to object"),p="object"),this.storageType=p,this.patchText=m,this.patchJSON=f,!u)throw"db missing";this.db=u;const{id_fields:y,synced_field:b,throttle:O=100,batch_size:S=50}=u[this.name]._syncInfo;if(!y||!b)throw"id_fields/synced_field missing";this.id_fields=y,this.synced_field=b,this.batch_size=S,this.throttle=O,this.skipFirstTrigger=d,this.multiSubscriptions=[],this.singleSubscriptions=[],this.onError=g||function(e){console.error("Sync internal error: ",e)};const _={id_fields:y,synced_field:b,throttle:O};u[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()})),u[this.name].getColumns&&u[this.name].getColumns().then((e=>{this.columns=e})),this.onChange&&!this.skipFirstTrigger&&setTimeout(this.onChange,0),(0,t.debug)(this)}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:c(t),index:-1}}setItem(e,t,n=!1,i=!1){const s=c(e);if(this.storageType===o.localStorage){let e=this.getItems();i?e=e.filter((e=>!this.matchesIdObj(e,s))):void 0!==t&&e[t]?e[t]=n?{...s}:{...e[t],...s}:e.push(s),r&&window.localStorage.setItem(this.name,JSON.stringify(e))}else if(this.storageType===o.array)i?this.items=this.items.filter((e=>!this.matchesIdObj(e,s))):void 0===t||this.items[t]?void 0!==t&&(this.items[t]=n?{...s}:{...this.items[t],...s}):this.items.push(s);else if(this.itemsObj=this.itemsObj||{},i)delete this.itemsObj[this.getIdStr(s)];else{let e=this.itemsObj[this.getIdStr(s)]||{};this.itemsObj[this.getIdStr(s)]=n?{...s}:{...e,...s}}}}function l(e,t){const n=e?c(e):e,s=t?c(t):t;let r=Object.assign({},n);return(0,i.isObject)(n)&&(0,i.isObject)(s)&&Object.keys(s).forEach((e=>{(0,i.isObject)(s[e])?e in n?r[e]=l(n[e],s[e]):Object.assign(r,{[e]:s[e]}):Object.assign(r,{[e]:s[e]})})),r}function c(e){if(r&&"structuredClone"in window&&"function"==typeof window.structuredClone)return window.structuredClone(e);if(Array.isArray(e))return e.slice(0).map((e=>c(e)));if((0,i.isObject)(e)){let t={};return(0,i.getKeys)(e).map((n=>{t[n]=c(e[n])})),t}return e}t.SyncedTable=a,t.default=l,t.quickClone=c},274:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prostgles=t.asName=t.debug=void 0;const i=n(792);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return i.asName}});const 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:a,onDisconnect:l,onReconnect:c,onSchemaChange:u=!0,onReload:d}=e;if((0,t.debug)("prostgles",{initOpts:e}),u){let e;"function"==typeof u&&(e=u),s.removeAllListeners(i.CHANNELS.SCHEMA_CHANGED),e&&s.on(i.CHANNELS.SCHEMA_CHANGED,e)}const h=i.CHANNELS._preffix;let p,m={},f={},g={},y={},b=!1;function O(e,n,i){return(0,t.debug)("_unsubscribe",{channelName:e,handler:i}),new Promise(((t,r)=>{m[e]?(m[e].handlers=m[e].handlers.filter((e=>e!==i)),m[e].handlers.length||(s.emit(n,{},((e,t)=>{e&&console.error(e)})),s.removeListener(e,m[e].onCall),delete m[e]),t(!0)):t(!0)}))}function S({tableName:e,command:t,param1:n,param2:i},r){return new Promise(((o,a)=>{s.emit(h,{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(h,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{e?(console.error(e),o(e)):t&&r(t)}))}))}const v=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)=>{g[e]&&(g[e].triggers=g[e].triggers.filter((e=>e.onPullRequest!==n.onPullRequest&&e.onSyncRequest!==n.onSyncRequest&&e.onUpdates!==n.onUpdates)),g[e].triggers.length||(s.emit(e+"unsync",{},((e,n)=>{e?i(e):t(n)})),s.removeListener(e,g[e].onCall),delete g[e]))}))}(e,o)},syncData:function(t,n,i){s.emit(e,{onSyncRequest:{...l({}),...{data:t}||{},...{deleted:n}||{}}},i?e=>{i(e)}:null)}})}const d=Object.keys(g).find((t=>{let s=g[t];return s.tableName===e&&s.command===n&&JSON.stringify(s.param1||{})===JSON.stringify(i||{})&&JSON.stringify(s.param2||{})===JSON.stringify(r||{})}));if(d)return g[d].triggers.push(o),u(d);{const h=await S({tableName:e,command:n,param1:i,param2:r},l),{channelName:p,synced_field:m,id_fields:f}=h;function y(t,n){t&&g[p]&&g[p].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 g[p]={tableName:e,command:n,param1:i,param2:r,triggers:[o],syncInfo:h,onCall:y},s.on(p,y),u(p)}}),(([{tableName:e}])=>e)),j=new o((async function(e,{tableName:t,command:n,param1:i,param2:r},o,a){function l(n,s){let r={unsubscribe:function(){return O(n,s,o)},filter:{...i}};return e[t].update&&(r={...r,update:function(n,s){return e[t].update(i,n,s)}}),e[t].delete&&(r={...r,delete:function(n){return e[t].delete(i,n)}}),Object.freeze(r)}const c=Object.keys(m).find((e=>{let s=m[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 m[c].handlers.push(o),m[c].errorHandlers.push(a),setTimeout((()=>{o&&(null==m?void 0:m[c].lastData)&&o(null==m?void 0:m[c].lastData)}),10),l(c,m[c].unsubChannel);const{channelName:u,channelNameReady:d,channelNameUnsubscribe:h}=await _({tableName:t,command:n,param1:i,param2:r}),p=function(e,t){m[u]?e.data?(m[u].lastData=e.data,m[u].handlers.forEach((t=>{t(e.data)}))):e.err?m[u].errorHandlers.forEach((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,p),m[u]={lastData:void 0,tableName:t,command:n,param1:i,param2:r,onCall:p,unsubChannel:h,handlers:[o],errorHandlers:[f],destroy:()=>{m[u]&&(Object.values(m[u]).map((e=>{e&&e.handlers&&e.handlers.map((e=>O(u,h,e)))})),delete m[u])}},s.emit(d,{now:Date.now()}),l(u,h)}),(([e,{tableName:t}])=>t));async function w(e,t,n,i){return j.run([e,t,n,i])}return new Promise(((e,o)=>{s.removeAllListeners(i.CHANNELS.CONNECTION),s.on(i.CHANNELS.CONNECTION,(e=>(o(e),"ok"))),l&&s.on("disconnect",l),s.on(i.CHANNELS.SCHEMA,(({schema:l,methods:u,tableSchema:O,auth:j,rawSQL:N,joinTables:T=[],err:x})=>{if((0,t.debug)("destroySyncs",{subscriptions:m,syncedTables:f}),Object.values(m).map((e=>e.destroy())),m={},g={},Object.values(f).map((e=>{e&&e.destroy&&e.destroy()})),f={},b&&c&&(c(s,x),x))return void console.error(x);if(x)throw o(x),x;b=!0;let E=JSON.parse(JSON.stringify(l)),C=JSON.parse(JSON.stringify(u)),P={},I={};if(j){if(j.pathGuard&&r){const e=e=>{var t,n;(null==e?void 0:e.shouldReload)&&(d?d():"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={...j},[i.CHANNELS.LOGIN,i.CHANNELS.LOGOUT,i.CHANNELS.REGISTER].map((e=>{j[e]&&(I[e]=function(t){return new Promise(((n,i)=>{s.emit(h+e,t,((e,t)=>{e?i(e):n(t)}))}))})}))}C.map((e=>{const t="string"==typeof e,n=function(...e){return new Promise(((t,n)=>{s.emit(i.CHANNELS.METHOD,{method:r,params:e},((e,i)=>{e?n(e):t(i)}))}))},r=t?e:e.name;P[r]=t?n:{...e,run:n}})),P=Object.freeze(P),N&&(E.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)=>{p=p||{config:t,listeners:[]},p.listeners.length||(s.removeAllListeners(t.socketChannel),s.on(t.socketChannel,(e=>{p&&p.listeners&&p.listeners.length?p.listeners.map((t=>{t(e)})):s.emit(t.socketUnsubChannel,{})}))),p.listeners.push(e)})(t,e),{...e,removeListener:()=>(e=>{p&&(p.listeners=p.listeners.filter((t=>t!==e)),!p.listeners.length&&p.config&&p.config.socketUnsubChannel&&s&&s.emit(p.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)=>{y=y||{},y[t.notifChannel]?y[t.notifChannel].listeners.push(e):(y[t.notifChannel]={config:t,listeners:[e]},s.removeAllListeners(t.socketChannel),s.on(t.socketChannel,(e=>{y[t.notifChannel]&&y[t.notifChannel].listeners&&y[t.notifChannel].listeners.length?y[t.notifChannel].listeners.map((t=>{t(e)})):s.emit(y[t.notifChannel].config.socketUnsubChannel,{})})))})(e,t),{...t,removeListener:()=>((e,t)=>{y&&y[t.notifChannel]&&(y[t.notifChannel].listeners=y[t.notifChannel].listeners.filter((t=>t!==e)),!y[t.notifChannel].listeners.length&&y[t.notifChannel].config&&y[t.notifChannel].config.socketUnsubChannel&&s&&(s.emit(y[t.notifChannel].config.socketUnsubChannel,{}),delete y[t.notifChannel]))})(e,t)}),n={...t,addListener:e};r(n)}}))}))});const k=e=>"[object Object]"===Object.prototype.toString.call(e),A=(e,t,n,i)=>{if(!k(e)||!k(t)||"function"!=typeof n||i&&"function"!=typeof i)throw"Expecting: ( basicFilter<object>, options<object>, onChange<function> , onError?<function>) but got something else"},D=["subscribe","subscribeOne"];Object.keys(E).forEach((e=>{Object.keys(E[e]).sort(((e,t)=>D.includes(e)-D.includes(t))).forEach((t=>{if(["find","findOne"].includes(t)&&(E[e].getJoinedTables=function(){return(T||[]).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={},s)=>{const r=`${e}.${JSON.stringify(t)}.${JSON.stringify(i)}`;return f[r]||(f[r]=await n.create({...i,name:e,filter:t,db:E,onError:s})),f[r]};E[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)},E[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)}}E[e]._sync=function(n,i,s){return async function(e,t){return v.run([e,t])}({tableName:e,command:t,param1:n,param2:i},s)}}else if(D.includes(t)){const n=function(n,i,s,r){return A(n,i,s,r),w(E,{tableName:e,command:t,param1:n,param2:i},s,r)};E[e][t]=n;const i="subscribeOne";E[e][t+"Hook"]=function(e,s,r){return{start:o=>n(e,s,t!==i?o:e=>{o(e[0])},r),args:[e,s,r]}},t!==i&&D.includes(i)||(E[e][i]=function(n,i,s,r){return A(n,i,s,r),w(E,{tableName:e,command:t,param1:n,param2:i},(e=>{s(e[0])}),r)})}else E[e][t]=function(n,i,r){return new Promise(((o,a)=>{s.emit(h,{tableName:e,command:t,param1:n,param2:i,param3:r},((e,t)=>{e?a(e):o(t)}))}))}}))})),m&&Object.keys(m).length&&Object.keys(m).map((async e=>{try{let t=m[e];await _(t),s.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting old subscriptions",e)}})),g&&Object.keys(g).length&&Object.keys(g).filter((e=>g[e].triggers&&g[e].triggers.length)).map((async e=>{try{let t=g[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)}})),T.flat().map((e=>{function t(t=!0,n,i,s){return{[t?"$leftJoin":"$innerJoin"]:e,filter:n,select:i,...s}}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 a(E,P,O,I,b)}catch(e){console.error("Prostgles: Error within onReady: \n",e),o(e)}e(E)})()}))}))};class o{constructor(e,t){this.queue=[],this.isRunning=!1,this.func=e,this.groupBy=t}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=async e=>{if(e){const t=await this.func(...e.arguments);e.onResult(t)}};if(this.groupBy){const t=[],n=[];this.queue.forEach((async(e,i)=>{const s=this.groupBy(e.arguments);t.includes(s)||(t.push(s),n.push({index:i,item:e}))})),n.slice(0).reverse().forEach((e=>{this.queue.splice(e.index,1)})),await Promise.all(n.map((t=>e(t.item))))}else{const t=this.queue.shift();await e(t)}this.isRunning=!1,this.queue.length&&n()};return n(),t}}},792:function(e){var t;this||window,t=()=>(()=>{"use strict";var e={31:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CONTENT_TYPE_TO_EXT=void 0,t.CONTENT_TYPE_TO_EXT={"text/html":["html","htm","shtml"],"text/css":["css"],"text/csv":["csv"],"text/tsv":["tsv"],"text/xml":["xml"],"text/mathml":["mml"],"text/plain":["txt"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/x-component":["htc"],"image/gif":["gif"],"image/jpeg":["jpeg","jpg"],"image/png":["png"],"image/tiff":["tif","tiff"],"image/vnd.wap.wbmp":["wbmp"],"image/x-icon":["ico"],"image/x-jng":["jng"],"image/x-ms-bmp":["bmp"],"image/svg+xml":["svg"],"image/webp":["webp"],"application/sql":["sql"],"application/x-javascript":["js"],"application/atom+xml":["atom"],"application/rss+xml":["rss"],"application/java-archive":["jar","war","ear"],"application/mac-binhex40":["hqx"],"application/msword":["doc","docx"],"application/pdf":["pdf"],"application/postscript":["ps","eps","ai"],"application/rtf":["rtf"],"application/vnd.ms-excel":["xls","xlsx"],"application/vnd.ms-powerpoint":["ppt","pptx"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/x-7z-compressed":["7z"],"application/x-cocoa":["cco"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-makeself":["run"],"application/x-perl":["pl","pm"],"application/x-pilot":["prc","pdb"],"application/x-rar-compressed":["rar"],"application/x-redhat-package-manager":["rpm"],"application/x-sea":["sea"],"application/x-shockwave-flash":["swf"],"application/x-stuffit":["sit"],"application/x-tcl":["tcl","tk"],"application/x-x509-ca-cert":["der","pem","crt"],"application/x-xpinstall":["xpi"],"application/xhtml+xml":["xhtml"],"application/zip":["zip"],"application/octet-stream":["bin","exe","dll","deb","dmg","eot","iso","img","msi","msp","msm"],"audio/midi":["mid","midi","kar"],"audio/mpeg":["mp3"],"audio/ogg":["ogg"],"audio/x-realaudio":["ra"],"video/3gpp":["3gpp","3gp"],"video/mpeg":["mpeg","mpg"],"video/quicktime":["mov"],"video/x-flv":["flv"],"video/x-mng":["mng"],"video/x-ms-asf":["asx","asf"],"video/x-ms-wmv":["wmv"],"video/x-msvideo":["avi"],"video/mp4":["m4v","mp4"],"video/webm":["webm"]}},444:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.COMPLEX_FILTER_KEY=t.EXISTS_KEYS=t.GeomFilter_Funcs=t.GeomFilterKeys=t.ArrayFilterOperands=t.TextFilter_FullTextSearchFilterKeys=t.TextFilterFTSKeys=t.TextFilterKeys=t.JsonbFilterKeys=t.JsonbOperands=t.CompareInFilterKeys=t.CompareFilterKeys=void 0;const i=n(128);t.CompareFilterKeys=["=","$eq","<>",">","<",">=","<=","$eq","$ne","$gt","$gte","$lte"],t.CompareInFilterKeys=["$in","$nin"],t.JsonbOperands={"@>":{Operator:"@>","Right Operand Type":"jsonb",Description:"Does the left JSON value contain the right JSON path/value entries at the top level?",Example:'\'{"a":1, "b":2}\'::jsonb @> \'{"b":2}\'::jsonb'},"<@":{Operator:"<@","Right Operand Type":"jsonb",Description:"Are the left JSON path/value entries contained at the top level within the right JSON value?",Example:'\'{"b":2}\'::jsonb <@ \'{"a":1, "b":2}\'::jsonb'},"?":{Operator:"?","Right Operand Type":"text",Description:"Does the string exist as a top-level key within the JSON value?",Example:"'{\"a\":1, \"b\":2}'::jsonb ? 'b'"},"?|":{Operator:"?|","Right Operand Type":"text[]",Description:"Do any of these array strings exist as top-level keys?",Example:"'{\"a\":1, \"b\":2, \"c\":3}'::jsonb ?| array['b', 'c']"},"?&":{Operator:"?&","Right Operand Type":"text[]",Description:"Do all of these array strings exist as top-level keys?",Example:"'[\"a\", \"b\"]'::jsonb ?& array['a', 'b']"},"||":{Operator:"||","Right Operand Type":"jsonb",Description:"Concatenate two jsonb values into a new jsonb value",Example:'\'["a", "b"]\'::jsonb || \'["c", "d"]\'::jsonb'},"-":{Operator:"-","Right Operand Type":"integer",Description:"Delete the array element with specified index (Negative integers count from the end). Throws an error if top level container is not an array.",Example:'\'["a", "b"]\'::jsonb - 1'},"#-":{Operator:"#-","Right Operand Type":"text[]",Description:"Delete the field or element with specified path (for JSON arrays, negative integers count from the end)",Example:"'[\"a\", {\"b\":1}]'::jsonb #- '{1,b}'"},"@?":{Operator:"@?","Right Operand Type":"jsonpath",Description:"Does JSON path return any item for the specified JSON value?",Example:"'{\"a\":[1,2,3,4,5]}'::jsonb @? '$.a[*] ? (@ > 2)'"},"@@":{Operator:"@@","Right Operand Type":"jsonpath",Description:"Returns the result of JSON path predicate check for the specified JSON value. Only the first item of the result is taken into account. If the result is not Boolean, then null is returned.",Example:"'{\"a\":[1,2,3,4,5]}'::jsonb @@ '$.a[*] > 2'"}},t.JsonbFilterKeys=(0,i.getKeys)(t.JsonbOperands),t.TextFilterKeys=["$ilike","$like","$nilike","$nlike"],t.TextFilterFTSKeys=["@@","@>","<@","$contains","$containedBy"],t.TextFilter_FullTextSearchFilterKeys=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"],t.ArrayFilterOperands=["@>","<@","=","$eq","$contains","$containedBy","&&","$overlaps"],t.GeomFilterKeys=["~","~=","@","|&>","|>>",">>","=","<<|","<<","&>","&<|","&<","&&&","&&"],t.GeomFilter_Funcs=["ST_MakeEnvelope","st_makeenvelope","ST_MakePolygon","st_makepolygon"],t.EXISTS_KEYS=["$exists","$notExists","$existsJoined","$notExistsJoined"],t.COMPLEX_FILTER_KEY="$filter"},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.CONTENT_TYPE_TO_EXT=t.getKeys=t.isObject=t.isDefined=t.get=t.WAL=t.unpatchText=t.stableStringify=t.isEmpty=t.getTextPatch=t.omitKeys=t.pickKeys=t.asName=t.RULE_METHODS=t.CHANNELS=t.JOIN_PARAMS=t.JOIN_KEYS=t.TS_PG_Types=t._PG_geometric=t._PG_postgis=t._PG_interval=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","time","timetz","interval","name","cidr","inet","macaddr","macaddr8","int4range","int8range","numrange","tsvector"],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_interval=["interval"],t._PG_postgis=["geometry","geography"],t._PG_geometric=["point","line","lseg","box","path","polygon","circle"];const r={string:[...t._PG_strings,...t._PG_date,...t._PG_geometric,...t._PG_postgis,"lseg"],number:t._PG_numbers,boolean:t._PG_bool,any:[...t._PG_json,...t._PG_interval]};t.TS_PG_Types={...r,"number[]":r.number.map((e=>`_${e}`)),"boolean[]":r.boolean.map((e=>`_${e}`)),"string[]":r.string.map((e=>`_${e}`)),"any[]":r.any.map((e=>`_${e}`))},t.JOIN_KEYS=["$innerJoin","$leftJoin"],t.JOIN_PARAMS=["select","filter","$path","$condition","offset","limit","orderBy"];const o="_psqlWS_.";t.CHANNELS={SCHEMA_CHANGED:o+"schema-changed",SCHEMA:o+"schema",DEFAULT:o,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",CONNECTION:"_psqlWS_.connection",_preffix:o},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 a=n(128);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return a.asName}}),Object.defineProperty(t,"pickKeys",{enumerable:!0,get:function(){return a.pickKeys}}),Object.defineProperty(t,"omitKeys",{enumerable:!0,get:function(){return a.omitKeys}}),Object.defineProperty(t,"getTextPatch",{enumerable:!0,get:function(){return a.getTextPatch}}),Object.defineProperty(t,"isEmpty",{enumerable:!0,get:function(){return a.isEmpty}}),Object.defineProperty(t,"stableStringify",{enumerable:!0,get:function(){return a.stableStringify}}),Object.defineProperty(t,"unpatchText",{enumerable:!0,get:function(){return a.unpatchText}}),Object.defineProperty(t,"WAL",{enumerable:!0,get:function(){return a.WAL}}),Object.defineProperty(t,"get",{enumerable:!0,get:function(){return a.get}}),Object.defineProperty(t,"isDefined",{enumerable:!0,get:function(){return a.isDefined}}),Object.defineProperty(t,"isObject",{enumerable:!0,get:function(){return a.isObject}}),Object.defineProperty(t,"getKeys",{enumerable:!0,get:function(){return a.getKeys}}),s(n(444),t);var l=n(31);Object.defineProperty(t,"CONTENT_TYPE_TO_EXT",{enumerable:!0,get:function(){return l.CONTENT_TYPE_TO_EXT}}),s(n(929),t)},929:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getJSONBSchemaAsJSONSchema=t.DATA_TYPES=t.PrimitiveArrayTypes=t.PrimitiveTypes=void 0;const i=n(128);t.PrimitiveTypes=["boolean","number","integer","string","Date","time","timestamp","any"],t.PrimitiveArrayTypes=t.PrimitiveTypes.map((e=>`${e}[]`)),t.DATA_TYPES=[...t.PrimitiveTypes,...t.PrimitiveArrayTypes];const s=(e,t)=>{const{type:n,arrayOf:r,arrayOfType:o,description:a,nullable:l,oneOf:c,oneOfType:u,title:d,record:h,...p}="string"==typeof e?{type:e}:e;let m={};const f={...(p.enum||p.allowedValues?.length)&&{enum:p.allowedValues?.slice(0)??p.enum.slice(0)},...!!a&&{description:a},...!!d&&{title:d}};if(p.enum?.length&&(f.type=typeof p.enum[0]),"string"==typeof n||r||o){if(n&&"string"!=typeof n)throw"Not expected";m=r||o||n?.endsWith("[]")?{type:"array",items:r||o?s(r||{type:o}):n?.startsWith("any")?{type:void 0}:{type:n?.slice(0,-2),...p.allowedValues&&{enum:p.allowedValues.slice(0)}}}:{type:n}}else(0,i.isObject)(n)?m={type:"object",required:(0,i.getKeys)(n).filter((e=>{const t=n[e];return"string"==typeof t||!t.optional})),properties:(0,i.getKeys)(n).reduce(((e,t)=>({...e,[t]:s(n[t])})),{})}:c||u?m={oneOf:(c||u.map((e=>({type:e})))).map((e=>s(e)))}:h&&(m={type:"object",...h.values&&!h.keysEnum&&{additionalProperties:s(h.values)},...h.keysEnum&&{properties:h.keysEnum.reduce(((e,t)=>({...e,[t]:h.values?s(h.values):{type:{}}})),{})}});if(l){const e={type:"null"};m.oneOf?m.oneOf.push(e):m.enum&&!m.enum.includes(null)?m.enum.push(null):m={oneOf:[m,e]}}return{...t?{$id:t?.id,$schema:"https://json-schema.org/draft/2020-12/schema"}:void 0,...f,...m}};t.getJSONBSchemaAsJSONSchema=function(e,t,n){return s(n,{id:`${e}.${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]=h(n,e[0]),e[1]=h(i,e[1]),e[2]=h(l,e[2]),e[3]=h(c,e[3])}function i(e,t,n,i,s,r){return t=h(h(t,e),h(i,r)),h(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 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,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 h(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.find=t.filter=t.omitKeys=t.pickKeys=t.asName=void 0;const i=n(899);function s(e,t=[],n=!1){let i=t;if(!i.length)return{};if(e&&i.length){let t={};return i.forEach((i=>{n&&void 0===e[i]||(t[i]=e[i])})),t}return e}function r(e,t){return e.filter((e=>Object.entries(t).every((([t,n])=>e[t]===n))))}function o(e){for(var t in e)return!1;return!0}function a(e){return Object.keys(e)}t.asName=function(e){if(null==e||!e.toString||!e.toString())throw"Expecting a non empty string";return`"${e.toString().replace(/"/g,'""')}"`},t.pickKeys=s,t.omitKeys=function(e,t){return s(e,a(e).filter((e=>!t.includes(e))))},t.filter=r,t.find=function(e,t){return r(e,t)[0]},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=>{o(this.changed)&&this.options.onSendStart&&this.options.onSendStart(),e.map((e=>{var t;const{initial:n,current:i,delta:s}={...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,delta:s}),this.changed[r].current={...this.changed[r].current,...i},this.changed[r].delta={...this.changed[r].delta,...s}})),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:r=2}=this.options;if(this.isSendingTimeout||this.sending&&!o(this.sending))return;if(!this.changed||o(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=>{let t={};return Object.keys(e.current).map((n=>{const i=e.initial?.[n],s=e.current[n];var r,o;![this.options.synced_field,...this.options.id_fields].includes(n)&&((r=i)===(o=s)||(["number","string","boolean"].includes(typeof r)?r===o:JSON.stringify(r)===JSON.stringify(o)))||(t[n]=s)})),t})),e&&console.log(this.options.id," SENDING lr->",l[l.length-1]),this.isSendingTimeout||(this.isSendingTimeout=setTimeout((()=>{this.isSendingTimeout=void 0,o(this.changed)||this.sendItems()}),s)),this.isOnSending=!0;try{await t(l,c),r&&(this.sentHistory={...this.sentHistory,...u},this.willDeleteHistory||(this.willDeleteHistory=setTimeout((()=>{this.willDeleteHistory=void 0,this.sentHistory={}}),1e3*r)))}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]),o(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||!(o(this.sending)&&o(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=o,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=a}},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.quickClone=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{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}constructor({name:e,filter:n,onChange:s,onReady:a,db:d,skipFirstTrigger:u=!1,select:h="*",storageType:p="object",patchText:m=!1,patchJSON:f=!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 u=this.getItem(c),h=u.index,p=u.data;!t&&!(0,i.isEmpty)(d)||(0,i.isEmpty)(p)||(d=this.getDelta(p||{},d)),t||(d[this.synced_field]=Date.now());let m={...p,...d,...c};p&&!t&&(null===(s=e.opts)||void 0===s?void 0:s.deepMerge)&&(m=l({...p,...c},{...d})),r=p?p[this.synced_field]<m[this.synced_field]?"updated":"unchanged":"inserted",this.setItem(m,h);let f={idObj:c,delta:d,oldItem:p,newItem:m,status:r,from_server:t};return t||a.push({initial:p,current:{...m}}),f.delta&&!(0,i.isEmpty)(f.delta)&&o.push(f),!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=>{const t=c(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(t))}else this.storageType===o.array?this.items=t:this.itemsObj=t.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 c(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[p])throw"Invalid storage type. Expecting one of: "+Object.keys(o).join(", ");if(r||p!==o.localStorage||(console.warn("Could not set storageType to localStorage: window object missing\nStorage changed to object"),p="object"),this.storageType=p,this.patchText=m,this.patchJSON=f,!d)throw"db missing";this.db=d;const{id_fields:y,synced_field:b,throttle:O=100,batch_size:S=50}=d[this.name]._syncInfo;if(!y||!b)throw"id_fields/synced_field missing";this.id_fields=y,this.synced_field=b,this.batch_size=S,this.throttle=O,this.skipFirstTrigger=u,this.multiSubscriptions=[],this.singleSubscriptions=[],this.onError=g||function(e){console.error("Sync internal error: ",e)};const _={id_fields:y,synced_field:b,throttle:O};d[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()})),d[this.name].getColumns&&d[this.name].getColumns().then((e=>{this.columns=e})),this.onChange&&!this.skipFirstTrigger&&setTimeout(this.onChange,0),(0,t.debug)(this)}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((null==e?void 0: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:c(t),index:-1}}setItem(e,t,n=!1,i=!1){const s=c(e);if(this.storageType===o.localStorage){let e=this.getItems();i?e=e.filter((e=>!this.matchesIdObj(e,s))):void 0!==t&&e[t]?e[t]=n?{...s}:{...e[t],...s}:e.push(s),r&&window.localStorage.setItem(this.name,JSON.stringify(e))}else if(this.storageType===o.array)i?this.items=this.items.filter((e=>!this.matchesIdObj(e,s))):void 0===t||this.items[t]?void 0!==t&&(this.items[t]=n?{...s}:{...this.items[t],...s}):this.items.push(s);else if(this.itemsObj=this.itemsObj||{},i)delete this.itemsObj[this.getIdStr(s)];else{let e=this.itemsObj[this.getIdStr(s)]||{};this.itemsObj[this.getIdStr(s)]=n?{...s}:{...e,...s}}}}function l(e,t){const n=e?c(e):e,s=t?c(t):t;let r=Object.assign({},n);return(0,i.isObject)(n)&&(0,i.isObject)(s)&&Object.keys(s).forEach((e=>{(0,i.isObject)(s[e])?e in n?r[e]=l(n[e],s[e]):Object.assign(r,{[e]:s[e]}):Object.assign(r,{[e]:s[e]})})),r}function c(e){if(r&&"structuredClone"in window&&"function"==typeof window.structuredClone)return window.structuredClone(e);if(Array.isArray(e))return e.slice(0).map((e=>c(e)));if((0,i.isObject)(e)){let t={};return(0,i.getKeys)(e).map((n=>{t[n]=c(e[n])})),t}return e}t.SyncedTable=a,t.default=l,t.quickClone=c},274:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.prostgles=t.asName=t.debug=void 0;const i=n(792);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return i.asName}});const 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:a,onDisconnect:l,onReconnect:c,onSchemaChange:d=!0,onReload:u}=e;if((0,t.debug)("prostgles",{initOpts:e}),d){let e;"function"==typeof d&&(e=d),s.removeAllListeners(i.CHANNELS.SCHEMA_CHANGED),e&&s.on(i.CHANNELS.SCHEMA_CHANGED,e)}const h=i.CHANNELS._preffix;let p,m={},f={},g={},y={},b=!1;function O(e,n,i){return(0,t.debug)("_unsubscribe",{channelName:e,handler:i}),new Promise(((t,r)=>{m[e]?(m[e].handlers=m[e].handlers.filter((e=>e!==i)),m[e].handlers.length||(s.emit(n,{},((e,t)=>{e&&console.error(e)})),s.removeListener(e,m[e].onCall),delete m[e]),t(!0)):t(!0)}))}function S({tableName:e,command:t,param1:n,param2:i},r){return new Promise(((o,a)=>{s.emit(h,{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(h,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{e?(console.error(e),o(e)):t&&r(t)}))}))}const v=new o((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)=>{g[e]&&(g[e].triggers=g[e].triggers.filter((e=>e.onPullRequest!==n.onPullRequest&&e.onSyncRequest!==n.onSyncRequest&&e.onUpdates!==n.onUpdates)),g[e].triggers.length||(s.emit(e+"unsync",{},((e,n)=>{e?i(e):t(n)})),s.removeListener(e,g[e].onCall),delete g[e]))}))}(e,o)},syncData:function(t,n,i){s.emit(e,{onSyncRequest:{...l({}),...{data:t}||{},...{deleted:n}||{}}},i?e=>{i(e)}:null)}})}const u=Object.keys(g).find((t=>{let s=g[t];return s&&s.tableName===e&&s.command===n&&JSON.stringify(s.param1||{})===JSON.stringify(i||{})&&JSON.stringify(s.param2||{})===JSON.stringify(r||{})}));if(u)return g[u].triggers.push(o),d(u);{const h=await S({tableName:e,command:n,param1:i,param2:r},l),{channelName:p,synced_field:m,id_fields:f}=h;function y(t,n){t&&g[p]&&g[p].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 g[p]={tableName:e,command:n,param1:i,param2:r,triggers:[o],syncInfo:h,onCall:y},s.on(p,y),d(p)}}),(([{tableName:e}])=>e)),j=new o((async function(e,{tableName:t,command:n,param1:i,param2:r},o,a){function l(n,s){let r={unsubscribe:function(){return O(n,s,o)},filter:{...i}};return e[t].update&&(r={...r,update:function(n,s){return e[t].update(i,n,s)}}),e[t].delete&&(r={...r,delete:function(n){return e[t].delete(i,n)}}),Object.freeze(r)}const c=Object.entries(m).find((([e])=>{let s=m[e];return s&&s.tableName===t&&s.command===n&&JSON.stringify(s.param1||{})===JSON.stringify(i||{})&&JSON.stringify(s.param2||{})===JSON.stringify(r||{})}));if(c){const e=c[0];return c[1].handlers.push(o),c[1].errorHandlers.push(a),setTimeout((()=>{var t,n;o&&(null===(t=null==m?void 0:m[e])||void 0===t?void 0:t.lastData)&&o(null===(n=null==m?void 0:m[e])||void 0===n?void 0:n.lastData)}),10),l(e,c[1].unsubChannel)}const{channelName:d,channelNameReady:u,channelNameUnsubscribe:h}=await _({tableName:t,command:n,param1:i,param2:r}),p=function(e,t){const n=m[d];n?e.data?(n.lastData=e.data,n.handlers.forEach((t=>{t(e.data)}))):e.err?n.errorHandlers.forEach((t=>{t(e.err)})):console.error("INTERNAL ERROR: Unexpected data format from subscription: ",e):console.warn("Orphaned subscription: ",d)},f=a||function(e){console.error(`Uncaught error within running subscription \n ${d}`,e)};return s.on(d,p),m[d]={lastData:void 0,tableName:t,command:n,param1:i,param2:r,onCall:p,unsubChannel:h,handlers:[o],errorHandlers:[f],destroy:()=>{m[d]&&(Object.values(m[d]).map((e=>{e&&e.handlers&&e.handlers.map((e=>O(d,h,e)))})),delete m[d])}},s.emit(u,{now:Date.now()}),l(d,h)}),(([e,{tableName:t}])=>t));async function w(e,t,n,i){return j.run([e,t,n,i])}return new Promise(((e,o)=>{s.removeAllListeners(i.CHANNELS.CONNECTION),s.on(i.CHANNELS.CONNECTION,(e=>(o(e),"ok"))),l&&s.on("disconnect",l),s.on(i.CHANNELS.SCHEMA,(({schema:l,methods:d,tableSchema:O,auth:j,rawSQL:N,joinTables:T=[],err:x})=>{if((0,t.debug)("destroySyncs",{subscriptions:m,syncedTables:f}),Object.values(m).map((e=>e.destroy())),m={},g={},Object.values(f).map((e=>{e&&e.destroy&&e.destroy()})),f={},b&&c&&(c(s,x),x))return void console.error(x);if(x)throw o(x),x;b=!0;let E=JSON.parse(JSON.stringify(l)),C=JSON.parse(JSON.stringify(d)),P={},I={};if(j){if(j.pathGuard&&r){const e=e=>{var t,n;(null==e?void 0:e.shouldReload)&&(u?u():"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={...j},[i.CHANNELS.LOGIN,i.CHANNELS.LOGOUT,i.CHANNELS.REGISTER].map((e=>{j[e]&&(I[e]=function(t){return new Promise(((n,i)=>{s.emit(h+e,t,((e,t)=>{e?i(e):n(t)}))}))})}))}C.map((e=>{const t="string"==typeof e,n=function(...e){return new Promise(((t,n)=>{s.emit(i.CHANNELS.METHOD,{method:r,params:e},((e,i)=>{e?n(e):t(i)}))}))},r=t?e:e.name;P[r]=t?n:{...e,run:n}})),P=Object.freeze(P),N&&(E.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)=>{p=p||{config:t,listeners:[]},p.listeners.length||(s.removeAllListeners(t.socketChannel),s.on(t.socketChannel,(e=>{p&&p.listeners&&p.listeners.length?p.listeners.map((t=>{t(e)})):s.emit(t.socketUnsubChannel,{})}))),p.listeners.push(e)})(t,e),{...e,removeListener:()=>(e=>{p&&(p.listeners=p.listeners.filter((t=>t!==e)),!p.listeners.length&&p.config&&p.config.socketUnsubChannel&&s&&s.emit(p.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)=>{var n;y=y||{},y[t.notifChannel]?null===(n=y[t.notifChannel])||void 0===n||n.listeners.push(e):(y[t.notifChannel]={config:t,listeners:[e]},s.removeAllListeners(t.socketChannel),s.on(t.socketChannel,(e=>{var n,i;(null===(n=y[t.notifChannel])||void 0===n?void 0:n.listeners.length)?y[t.notifChannel].listeners.map((t=>{t(e)})):s.emit(null===(i=y[t.notifChannel])||void 0===i?void 0:i.config.socketUnsubChannel,{})})))})(e,t),{...t,removeListener:()=>((e,t)=>{const n=y[t.notifChannel];n&&(n.listeners=n.listeners.filter((t=>t!==e)),!n.listeners.length&&n.config&&n.config.socketUnsubChannel&&s&&(s.emit(n.config.socketUnsubChannel,{}),delete y[t.notifChannel]))})(e,t)}),n={...t,addListener:e};r(n)}}))}))});const k=e=>"[object Object]"===Object.prototype.toString.call(e),A=(e,t,n,i)=>{if(!k(e)||!k(t)||"function"!=typeof n||i&&"function"!=typeof i)throw"Expecting: ( basicFilter<object>, options<object>, onChange<function> , onError?<function>) but got something else"},D=["subscribe","subscribeOne"];(0,i.getKeys)(E).forEach((e=>{Object.keys(E[e]).sort(((e,t)=>D.includes(e)-D.includes(t))).forEach((t=>{if(["find","findOne"].includes(t)&&(E[e].getJoinedTables=function(){return(T||[]).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={},s)=>{const r=`${e}.${JSON.stringify(t)}.${JSON.stringify(i)}`;return f[r]||(f[r]=await n.create({...i,name:e,filter:t,db:E,onError:s})),f[r]};E[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)},E[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)}}E[e]._sync=function(n,i,s){return async function(e,t){return v.run([e,t])}({tableName:e,command:t,param1:n,param2:i},s)}}else if(D.includes(t)){const n=function(n,i,s,r){return A(n,i,s,r),w(E,{tableName:e,command:t,param1:n,param2:i},s,r)};E[e][t]=n;const i="subscribeOne";E[e][t+"Hook"]=function(e,s,r){return{start:o=>n(e,s,t!==i?o:e=>{o(e[0])},r),args:[e,s,r]}},t!==i&&D.includes(i)||(E[e][i]=function(n,i,s,r){return A(n,i,s,r),w(E,{tableName:e,command:t,param1:n,param2:i},(e=>{s(e[0])}),r)})}else E[e][t]=function(n,i,r){return new Promise(((o,a)=>{s.emit(h,{tableName:e,command:t,param1:n,param2:i,param3:r},((e,t)=>{e?a(e):o(t)}))}))}}))})),m&&Object.keys(m).length&&Object.keys(m).map((async e=>{try{let t=m[e];await _(t),s.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting old subscriptions",e)}})),g&&Object.keys(g).length&&(0,i.getKeys)(g).filter((e=>{var t;return null===(t=g[e])||void 0===t?void 0:t.triggers.length})).map((async e=>{try{let t=g[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)}})),T.flat().map((e=>{function t(t=!0,n,i,s){return{[t?"$leftJoin":"$innerJoin"]:e,filter:n,select:i,...s}}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 a(E,P,O,I,b)}catch(e){console.error("Prostgles: Error within onReady: \n",e),o(e)}e(E)})()}))}))};class o{constructor(e,t){this.queue=[],this.isRunning=!1,this.func=e,this.groupBy=t}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=async e=>{if(e){const t=await this.func(...e.arguments);e.onResult(t)}};if(this.groupBy){const t=[],n=[];this.queue.forEach((async(e,i)=>{const s=this.groupBy(e.arguments);t.includes(s)||(t.push(s),n.push({index:i,item:e}))})),n.slice(0).reverse().forEach((e=>{this.queue.splice(e.index,1)})),await Promise.all(n.map((t=>e(t.item))))}else{const t=this.queue.shift();await e(t)}this.isRunning=!1,this.queue.length&&n()};return n(),t}}},792:function(e){var t;this||window,t=()=>(()=>{"use strict";var e={31:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CONTENT_TYPE_TO_EXT=void 0,t.CONTENT_TYPE_TO_EXT={"text/html":["html","htm","shtml"],"text/css":["css"],"text/csv":["csv"],"text/tsv":["tsv"],"text/xml":["xml"],"text/mathml":["mml"],"text/plain":["txt"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/x-component":["htc"],"image/gif":["gif"],"image/jpeg":["jpeg","jpg"],"image/png":["png"],"image/tiff":["tif","tiff"],"image/vnd.wap.wbmp":["wbmp"],"image/x-icon":["ico"],"image/x-jng":["jng"],"image/x-ms-bmp":["bmp"],"image/svg+xml":["svg"],"image/webp":["webp"],"application/sql":["sql"],"application/x-javascript":["js"],"application/atom+xml":["atom"],"application/rss+xml":["rss"],"application/java-archive":["jar","war","ear"],"application/mac-binhex40":["hqx"],"application/msword":["doc","docx"],"application/pdf":["pdf"],"application/postscript":["ps","eps","ai"],"application/rtf":["rtf"],"application/vnd.ms-excel":["xls","xlsx"],"application/vnd.ms-powerpoint":["ppt","pptx"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/x-7z-compressed":["7z"],"application/x-cocoa":["cco"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-makeself":["run"],"application/x-perl":["pl","pm"],"application/x-pilot":["prc","pdb"],"application/x-rar-compressed":["rar"],"application/x-redhat-package-manager":["rpm"],"application/x-sea":["sea"],"application/x-shockwave-flash":["swf"],"application/x-stuffit":["sit"],"application/x-tcl":["tcl","tk"],"application/x-x509-ca-cert":["der","pem","crt"],"application/x-xpinstall":["xpi"],"application/xhtml+xml":["xhtml"],"application/zip":["zip"],"application/octet-stream":["bin","exe","dll","deb","dmg","eot","iso","img","msi","msp","msm"],"audio/midi":["mid","midi","kar"],"audio/mpeg":["mp3"],"audio/ogg":["ogg"],"audio/x-realaudio":["ra"],"video/3gpp":["3gpp","3gp"],"video/mpeg":["mpeg","mpg"],"video/quicktime":["mov"],"video/x-flv":["flv"],"video/x-mng":["mng"],"video/x-ms-asf":["asx","asf"],"video/x-ms-wmv":["wmv"],"video/x-msvideo":["avi"],"video/mp4":["m4v","mp4"],"video/webm":["webm"]}},444:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.COMPLEX_FILTER_KEY=t.EXISTS_KEYS=t.GeomFilter_Funcs=t.GeomFilterKeys=t.ArrayFilterOperands=t.TextFilter_FullTextSearchFilterKeys=t.TextFilterFTSKeys=t.TextFilterKeys=t.JsonbFilterKeys=t.JsonbOperands=t.CompareInFilterKeys=t.CompareFilterKeys=void 0;const i=n(128);t.CompareFilterKeys=["=","$eq","<>",">","<",">=","<=","$eq","$ne","$gt","$gte","$lte"],t.CompareInFilterKeys=["$in","$nin"],t.JsonbOperands={"@>":{Operator:"@>","Right Operand Type":"jsonb",Description:"Does the left JSON value contain the right JSON path/value entries at the top level?",Example:'\'{"a":1, "b":2}\'::jsonb @> \'{"b":2}\'::jsonb'},"<@":{Operator:"<@","Right Operand Type":"jsonb",Description:"Are the left JSON path/value entries contained at the top level within the right JSON value?",Example:'\'{"b":2}\'::jsonb <@ \'{"a":1, "b":2}\'::jsonb'},"?":{Operator:"?","Right Operand Type":"text",Description:"Does the string exist as a top-level key within the JSON value?",Example:"'{\"a\":1, \"b\":2}'::jsonb ? 'b'"},"?|":{Operator:"?|","Right Operand Type":"text[]",Description:"Do any of these array strings exist as top-level keys?",Example:"'{\"a\":1, \"b\":2, \"c\":3}'::jsonb ?| array['b', 'c']"},"?&":{Operator:"?&","Right Operand Type":"text[]",Description:"Do all of these array strings exist as top-level keys?",Example:"'[\"a\", \"b\"]'::jsonb ?& array['a', 'b']"},"||":{Operator:"||","Right Operand Type":"jsonb",Description:"Concatenate two jsonb values into a new jsonb value",Example:'\'["a", "b"]\'::jsonb || \'["c", "d"]\'::jsonb'},"-":{Operator:"-","Right Operand Type":"integer",Description:"Delete the array element with specified index (Negative integers count from the end). Throws an error if top level container is not an array.",Example:'\'["a", "b"]\'::jsonb - 1'},"#-":{Operator:"#-","Right Operand Type":"text[]",Description:"Delete the field or element with specified path (for JSON arrays, negative integers count from the end)",Example:"'[\"a\", {\"b\":1}]'::jsonb #- '{1,b}'"},"@?":{Operator:"@?","Right Operand Type":"jsonpath",Description:"Does JSON path return any item for the specified JSON value?",Example:"'{\"a\":[1,2,3,4,5]}'::jsonb @? '$.a[*] ? (@ > 2)'"},"@@":{Operator:"@@","Right Operand Type":"jsonpath",Description:"Returns the result of JSON path predicate check for the specified JSON value. Only the first item of the result is taken into account. If the result is not Boolean, then null is returned.",Example:"'{\"a\":[1,2,3,4,5]}'::jsonb @@ '$.a[*] > 2'"}},t.JsonbFilterKeys=(0,i.getKeys)(t.JsonbOperands),t.TextFilterKeys=["$ilike","$like","$nilike","$nlike"],t.TextFilterFTSKeys=["@@","@>","<@","$contains","$containedBy"],t.TextFilter_FullTextSearchFilterKeys=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"],t.ArrayFilterOperands=["@>","<@","=","$eq","$contains","$containedBy","&&","$overlaps"],t.GeomFilterKeys=["~","~=","@","|&>","|>>",">>","=","<<|","<<","&>","&<|","&<","&&&","&&"],t.GeomFilter_Funcs=["ST_MakeEnvelope","st_makeenvelope","ST_MakePolygon","st_makepolygon"],t.EXISTS_KEYS=["$exists","$notExists","$existsJoined","$notExistsJoined"],t.COMPLEX_FILTER_KEY="$filter"},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.CONTENT_TYPE_TO_EXT=t.getKeys=t.isObject=t.isDefined=t.get=t.WAL=t.unpatchText=t.stableStringify=t.isEmpty=t.getTextPatch=t.omitKeys=t.pickKeys=t.asName=t.RULE_METHODS=t.CHANNELS=t.JOIN_PARAMS=t.JOIN_KEYS=t.TS_PG_Types=t._PG_geometric=t._PG_postgis=t._PG_interval=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","time","timetz","interval","name","cidr","inet","macaddr","macaddr8","int4range","int8range","numrange","tsvector"],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_interval=["interval"],t._PG_postgis=["geometry","geography"],t._PG_geometric=["point","line","lseg","box","path","polygon","circle"];const r={string:[...t._PG_strings,...t._PG_date,...t._PG_geometric,...t._PG_postgis,"lseg"],number:t._PG_numbers,boolean:t._PG_bool,any:[...t._PG_json,...t._PG_interval]};t.TS_PG_Types={...r,"number[]":r.number.map((e=>`_${e}`)),"boolean[]":r.boolean.map((e=>`_${e}`)),"string[]":r.string.map((e=>`_${e}`)),"any[]":r.any.map((e=>`_${e}`))},t.JOIN_KEYS=["$innerJoin","$leftJoin"],t.JOIN_PARAMS=["select","filter","$path","$condition","offset","limit","orderBy"];const o="_psqlWS_.";t.CHANNELS={SCHEMA_CHANGED:o+"schema-changed",SCHEMA:o+"schema",DEFAULT:o,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",CONNECTION:"_psqlWS_.connection",_preffix:o},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 a=n(128);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return a.asName}}),Object.defineProperty(t,"pickKeys",{enumerable:!0,get:function(){return a.pickKeys}}),Object.defineProperty(t,"omitKeys",{enumerable:!0,get:function(){return a.omitKeys}}),Object.defineProperty(t,"getTextPatch",{enumerable:!0,get:function(){return a.getTextPatch}}),Object.defineProperty(t,"isEmpty",{enumerable:!0,get:function(){return a.isEmpty}}),Object.defineProperty(t,"stableStringify",{enumerable:!0,get:function(){return a.stableStringify}}),Object.defineProperty(t,"unpatchText",{enumerable:!0,get:function(){return a.unpatchText}}),Object.defineProperty(t,"WAL",{enumerable:!0,get:function(){return a.WAL}}),Object.defineProperty(t,"get",{enumerable:!0,get:function(){return a.get}}),Object.defineProperty(t,"isDefined",{enumerable:!0,get:function(){return a.isDefined}}),Object.defineProperty(t,"isObject",{enumerable:!0,get:function(){return a.isObject}}),Object.defineProperty(t,"getKeys",{enumerable:!0,get:function(){return a.getKeys}}),s(n(444),t);var l=n(31);Object.defineProperty(t,"CONTENT_TYPE_TO_EXT",{enumerable:!0,get:function(){return l.CONTENT_TYPE_TO_EXT}}),s(n(929),t)},929:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getJSONBSchemaAsJSONSchema=t.DATA_TYPES=t.PrimitiveArrayTypes=t.PrimitiveTypes=void 0;const i=n(128);t.PrimitiveTypes=["boolean","number","integer","string","Date","time","timestamp","any"],t.PrimitiveArrayTypes=t.PrimitiveTypes.map((e=>`${e}[]`)),t.DATA_TYPES=[...t.PrimitiveTypes,...t.PrimitiveArrayTypes];const s=(e,t)=>{const{type:n,arrayOf:r,arrayOfType:o,description:a,nullable:l,oneOf:c,oneOfType:d,title:u,record:h,...p}="string"==typeof e?{type:e}:e;let m={};const f={...(p.enum||p.allowedValues?.length)&&{enum:p.allowedValues?.slice(0)??p.enum.slice(0)},...!!a&&{description:a},...!!u&&{title:u}};if(p.enum?.length&&(f.type=typeof p.enum[0]),"string"==typeof n||r||o){if(n&&"string"!=typeof n)throw"Not expected";m=r||o||n?.endsWith("[]")?{type:"array",items:r||o?s(r||{type:o}):n?.startsWith("any")?{type:void 0}:{type:n?.slice(0,-2),...p.allowedValues&&{enum:p.allowedValues.slice(0)}}}:{type:n}}else(0,i.isObject)(n)?m={type:"object",required:(0,i.getKeys)(n).filter((e=>{const t=n[e];return"string"==typeof t||!t.optional})),properties:(0,i.getKeys)(n).reduce(((e,t)=>({...e,[t]:s(n[t])})),{})}:c||d?m={oneOf:(c||d.map((e=>({type:e})))).map((e=>s(e)))}:h&&(m={type:"object",...h.values&&!h.keysEnum&&{additionalProperties:s(h.values)},...h.keysEnum&&{properties:h.keysEnum.reduce(((e,t)=>({...e,[t]:h.values?s(h.values):{type:{}}})),{})}});if(l){const e={type:"null"};m.oneOf?m.oneOf.push(e):m.enum&&!m.enum.includes(null)?m.enum.push(null):m={oneOf:[m,e]}}return{...t?{$id:t?.id,$schema:"https://json-schema.org/draft/2020-12/schema"}:void 0,...f,...m}};t.getJSONBSchemaAsJSONSchema=function(e,t,n){return s(n,{id:`${e}.${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]=h(n,e[0]),e[1]=h(i,e[1]),e[2]=h(l,e[2]),e[3]=h(c,e[3])}function i(e,t,n,i,s,r){return t=h(h(t,e),h(i,r)),h(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 u(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 h(e,t){return e+t&4294967295}t.md5=u,u("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.find=t.filter=t.omitKeys=t.pickKeys=t.asName=void 0;const i=n(899);function s(e,t=[],n=!1){let i=t;if(!i.length)return{};if(e&&i.length){let t={};return i.forEach((i=>{n&&void 0===e[i]||(t[i]=e[i])})),t}return e}function r(e,t){return e.filter((e=>Object.entries(t).every((([t,n])=>e[t]===n))))}function o(e){for(var t in e)return!1;return!0}function a(e){return Object.keys(e)}t.asName=function(e){if(null==e||!e.toString||!e.toString())throw"Expecting a non empty string";return`"${e.toString().replace(/"/g,'""')}"`},t.pickKeys=s,t.omitKeys=function(e,t){return s(e,a(e).filter((e=>!t.includes(e))))},t.filter=r,t.find=function(e,t){return r(e,t)[0]},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=>{o(this.changed)&&this.options.onSendStart&&this.options.onSendStart(),e.map((e=>{var t;const{initial:n,current:i,delta:s}={...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,delta:s}),this.changed[r].current={...this.changed[r].current,...i},this.changed[r].delta={...this.changed[r].delta,...s}})),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:r=2}=this.options;if(this.isSendingTimeout||this.sending&&!o(this.sending))return;if(!this.changed||o(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=>{let t={};return Object.keys(e.current).map((n=>{const i=e.initial?.[n],s=e.current[n];var r,o;![this.options.synced_field,...this.options.id_fields].includes(n)&&((r=i)===(o=s)||(["number","string","boolean"].includes(typeof r)?r===o:JSON.stringify(r)===JSON.stringify(o)))||(t[n]=s)})),t})),e&&console.log(this.options.id," SENDING lr->",l[l.length-1]),this.isSendingTimeout||(this.isSendingTimeout=setTimeout((()=>{this.isSendingTimeout=void 0,o(this.changed)||this.sendItems()}),s)),this.isOnSending=!0;try{await t(l,c),r&&(this.sentHistory={...this.sentHistory,...d},this.willDeleteHistory||(this.willDeleteHistory=setTimeout((()=>{this.willDeleteHistory=void 0,this.sentHistory={}}),1e3*r)))}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]),o(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||!(o(this.sending)&&o(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=o,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=a}},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 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.asName=t.debug=void 0;const i=n(792);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return i.asName}});const 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:a,onDisconnect:l,onReconnect:c,onSchemaChange:u=!0,onReload:p}=e;if((0,t.debug)("prostgles",{initOpts:e}),u){let e;"function"==typeof u&&(e=u),r.removeAllListeners(i.CHANNELS.SCHEMA_CHANGED),e&&r.on(i.CHANNELS.SCHEMA_CHANGED,e)}const d=i.CHANNELS._preffix;let m,f={},h={},g={},y={},b=!1;function O(e,n,i){return(0,t.debug)("_unsubscribe",{channelName:e,handler:i}),new Promise(((t,s)=>{f[e]?(f[e].handlers=f[e].handlers.filter((e=>e!==i)),f[e].handlers.length||(r.emit(n,{},((e,t)=>{e&&console.error(e)})),r.removeListener(e,f[e].onCall),delete f[e]),t(!0)):t(!0)}))}function v({tableName:e,command:t,param1:n,param2:i},s){return new Promise(((o,a)=>{r.emit(d,{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 _({tableName:e,command:t,param1:n,param2:i}){return new Promise(((s,o)=>{r.emit(d,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{e?(console.error(e),o(e)):t&&s(t)}))}))}const S=new o((async function({tableName:e,command:n,param1:i,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,i)=>{g[e]&&(g[e].triggers=g[e].triggers.filter((e=>e.onPullRequest!==n.onPullRequest&&e.onSyncRequest!==n.onSyncRequest&&e.onUpdates!==n.onUpdates)),g[e].triggers.length||(r.emit(e+"unsync",{},((e,n)=>{e?i(e):t(n)})),r.removeListener(e,g[e].onCall),delete g[e]))}))}(e,o)},syncData:function(t,n,i){r.emit(e,{onSyncRequest:{...l({}),...{data:t}||{},...{deleted:n}||{}}},i?e=>{i(e)}:null)}})}const p=Object.keys(g).find((t=>{let r=g[t];return r.tableName===e&&r.command===n&&JSON.stringify(r.param1||{})===JSON.stringify(i||{})&&JSON.stringify(r.param2||{})===JSON.stringify(s||{})}));if(p)return g[p].triggers.push(o),u(p);{const d=await v({tableName:e,command:n,param1:i,param2:s},l),{channelName:m,synced_field:f,id_fields:h}=d;function y(t,n){t&&g[m]&&g[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 g[m]={tableName:e,command:n,param1:i,param2:s,triggers:[o],syncInfo:d,onCall:y},r.on(m,y),u(m)}}),(([{tableName:e}])=>e)),N=new o((async function(e,{tableName:t,command:n,param1:i,param2:s},o,a){function l(n,r){let s={unsubscribe:function(){return O(n,r,o)},filter:{...i}};return e[t].update&&(s={...s,update:function(n,r){return e[t].update(i,n,r)}}),e[t].delete&&(s={...s,delete:function(n){return e[t].delete(i,n)}}),Object.freeze(s)}const c=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(c)return f[c].handlers.push(o),f[c].errorHandlers.push(a),setTimeout((()=>{o&&(null==f?void 0:f[c].lastData)&&o(null==f?void 0:f[c].lastData)}),10),l(c,f[c].unsubChannel);const{channelName:u,channelNameReady:p,channelNameUnsubscribe:d}=await _({tableName:t,command:n,param1:i,param2:s}),m=function(e,t){f[u]?e.data?(f[u].lastData=e.data,f[u].handlers.forEach((t=>{t(e.data)}))):e.err?f[u].errorHandlers.forEach((t=>{t(e.err)})):console.error("INTERNAL ERROR: Unexpected data format from subscription: ",e):console.warn("Orphaned subscription: ",u)},h=a||function(e){console.error(`Uncaught error within running subscription \n ${u}`,e)};return r.on(u,m),f[u]={lastData:void 0,tableName:t,command:n,param1:i,param2:s,onCall:m,unsubChannel:d,handlers:[o],errorHandlers:[h],destroy:()=>{f[u]&&(Object.values(f[u]).map((e=>{e&&e.handlers&&e.handlers.map((e=>O(u,d,e)))})),delete f[u])}},r.emit(p,{now:Date.now()}),l(u,d)}),(([e,{tableName:t}])=>t));async function x(e,t,n,i){return N.run([e,t,n,i])}return new Promise(((e,o)=>{r.removeAllListeners(i.CHANNELS.CONNECTION),r.on(i.CHANNELS.CONNECTION,(e=>(o(e),"ok"))),l&&r.on("disconnect",l),r.on(i.CHANNELS.SCHEMA,(({schema:l,methods:u,tableSchema:O,auth:N,rawSQL:j,joinTables:E=[],err:T})=>{if((0,t.debug)("destroySyncs",{subscriptions:f,syncedTables:h}),Object.values(f).map((e=>e.destroy())),f={},g={},Object.values(h).map((e=>{e&&e.destroy&&e.destroy()})),h={},b&&c&&(c(r,T),T))return void console.error(T);if(T)throw o(T),T;b=!0;let w=JSON.parse(JSON.stringify(l)),P=JSON.parse(JSON.stringify(u)),C={},A={};if(N){if(N.pathGuard&&s){const e=e=>{var t,n;(null==e?void 0:e.shouldReload)&&(p?p():"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)}))}A={...N},[i.CHANNELS.LOGIN,i.CHANNELS.LOGOUT,i.CHANNELS.REGISTER].map((e=>{N[e]&&(A[e]=function(t){return new Promise(((n,i)=>{r.emit(d+e,t,((e,t)=>{e?i(e):n(t)}))}))})}))}P.map((e=>{const t="string"==typeof e,n=function(...e){return new Promise(((t,n)=>{r.emit(i.CHANNELS.METHOD,{method:s,params:e},((e,i)=>{e?n(e):t(i)}))}))},s=t?e:e.name;C[s]=t?n:{...e,run:n}})),C=Object.freeze(C),j&&(w.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)=>{m=m||{config:t,listeners:[]},m.listeners.length||(r.removeAllListeners(t.socketChannel),r.on(t.socketChannel,(e=>{m&&m.listeners&&m.listeners.length?m.listeners.map((t=>{t(e)})):r.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&&r&&r.emit(m.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)=>{y=y||{},y[t.notifChannel]?y[t.notifChannel].listeners.push(e):(y[t.notifChannel]={config:t,listeners:[e]},r.removeAllListeners(t.socketChannel),r.on(t.socketChannel,(e=>{y[t.notifChannel]&&y[t.notifChannel].listeners&&y[t.notifChannel].listeners.length?y[t.notifChannel].listeners.map((t=>{t(e)})):r.emit(y[t.notifChannel].config.socketUnsubChannel,{})})))})(e,t),{...t,removeListener:()=>((e,t)=>{y&&y[t.notifChannel]&&(y[t.notifChannel].listeners=y[t.notifChannel].listeners.filter((t=>t!==e)),!y[t.notifChannel].listeners.length&&y[t.notifChannel].config&&y[t.notifChannel].config.socketUnsubChannel&&r&&(r.emit(y[t.notifChannel].config.socketUnsubChannel,{}),delete y[t.notifChannel]))})(e,t)}),n={...t,addListener:e};s(n)}}))}))});const k=e=>"[object Object]"===Object.prototype.toString.call(e),J=(e,t,n,i)=>{if(!k(e)||!k(t)||"function"!=typeof n||i&&"function"!=typeof i)throw"Expecting: ( basicFilter<object>, options<object>, onChange<function> , onError?<function>) but got something else"},D=["subscribe","subscribeOne"];Object.keys(w).forEach((e=>{Object.keys(w[e]).sort(((e,t)=>D.includes(e)-D.includes(t))).forEach((t=>{if(["find","findOne"].includes(t)&&(w[e].getJoinedTables=function(){return(E||[]).filter((t=>Array.isArray(t)&&t.includes(e))).flat().filter((t=>t!==e))}),"sync"===t){if(w[e]._syncInfo={...w[e][t]},n){w[e].getSync=(t,i={})=>n.create({name:e,filter:t,db:w,...i});const t=async(t={},i={},r)=>{const s=`${e}.${JSON.stringify(t)}.${JSON.stringify(i)}`;return h[s]||(h[s]=await n.create({...i,name:e,filter:t,db:w,onError:r})),h[s]};w[e].sync=async(e,n={handlesOnData:!0,select:"*"},i,r)=>{J(e,n,i,r);const s=await t(e,n,r);return await s.sync(i,n.handlesOnData)},w[e].syncOne=async(e,n={handlesOnData:!0},i,r)=>{J(e,n,i,r);const s=await t(e,n,r);return await s.syncOne(e,i,n.handlesOnData)}}w[e]._sync=function(n,i,r){return async function(e,t){return S.run([e,t])}({tableName:e,command:t,param1:n,param2:i},r)}}else if(D.includes(t)){const n=function(n,i,r,s){return J(n,i,r,s),x(w,{tableName:e,command:t,param1:n,param2:i},r,s)};w[e][t]=n;const i="subscribeOne";w[e][t+"Hook"]=function(e,r,s){return{start:o=>n(e,r,t!==i?o:e=>{o(e[0])},s),args:[e,r,s]}},t!==i&&D.includes(i)||(w[e][i]=function(n,i,r,s){return J(n,i,r,s),x(w,{tableName:e,command:t,param1:n,param2:i},(e=>{r(e[0])}),s)})}else w[e][t]=function(n,i,s){return new Promise(((o,a)=>{r.emit(d,{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 _(t),r.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting old subscriptions",e)}})),g&&Object.keys(g).length&&Object.keys(g).filter((e=>g[e].triggers&&g[e].triggers.length)).map((async e=>{try{let t=g[e];await v(t,t.triggers[0].onSyncRequest),r.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting olf subscriptions",e)}})),E.flat().map((e=>{function t(t=!0,n,i,r){return{[t?"$leftJoin":"$innerJoin"]:e,filter:n,select:i,...r}}w.innerJoin=w.innerJoin||{},w.leftJoin=w.leftJoin||{},w.innerJoinOne=w.innerJoinOne||{},w.leftJoinOne=w.leftJoinOne||{},w.leftJoin[e]=(e,n,i={})=>t(!0,e,n,i),w.innerJoin[e]=(e,n,i={})=>t(!1,e,n,i),w.leftJoinOne[e]=(e,n,i={})=>t(!0,e,n,{...i,limit:1}),w.innerJoinOne[e]=(e,n,i={})=>t(!1,e,n,{...i,limit:1})})),(async()=>{try{await a(w,C,O,A,b)}catch(e){console.error("Prostgles: Error within onReady: \n",e),o(e)}e(w)})()}))}))};class o{constructor(e,t){this.queue=[],this.isRunning=!1,this.func=e,this.groupBy=t}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=async e=>{if(e){const t=await this.func(...e.arguments);e.onResult(t)}};if(this.groupBy){const t=[],n=[];this.queue.forEach((async(e,i)=>{const r=this.groupBy(e.arguments);t.includes(r)||(t.push(r),n.push({index:i,item:e}))})),n.slice(0).reverse().forEach((e=>{this.queue.splice(e.index,1)})),await Promise.all(n.map((t=>e(t.item))))}else{const t=this.queue.shift();await e(t)}this.isRunning=!1,this.queue.length&&n()};return n(),t}}},792:function(e){var t;this||window,t=()=>(()=>{"use strict";var e={31:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CONTENT_TYPE_TO_EXT=void 0,t.CONTENT_TYPE_TO_EXT={"text/html":["html","htm","shtml"],"text/css":["css"],"text/csv":["csv"],"text/tsv":["tsv"],"text/xml":["xml"],"text/mathml":["mml"],"text/plain":["txt"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/x-component":["htc"],"image/gif":["gif"],"image/jpeg":["jpeg","jpg"],"image/png":["png"],"image/tiff":["tif","tiff"],"image/vnd.wap.wbmp":["wbmp"],"image/x-icon":["ico"],"image/x-jng":["jng"],"image/x-ms-bmp":["bmp"],"image/svg+xml":["svg"],"image/webp":["webp"],"application/sql":["sql"],"application/x-javascript":["js"],"application/atom+xml":["atom"],"application/rss+xml":["rss"],"application/java-archive":["jar","war","ear"],"application/mac-binhex40":["hqx"],"application/msword":["doc","docx"],"application/pdf":["pdf"],"application/postscript":["ps","eps","ai"],"application/rtf":["rtf"],"application/vnd.ms-excel":["xls","xlsx"],"application/vnd.ms-powerpoint":["ppt","pptx"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/x-7z-compressed":["7z"],"application/x-cocoa":["cco"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-makeself":["run"],"application/x-perl":["pl","pm"],"application/x-pilot":["prc","pdb"],"application/x-rar-compressed":["rar"],"application/x-redhat-package-manager":["rpm"],"application/x-sea":["sea"],"application/x-shockwave-flash":["swf"],"application/x-stuffit":["sit"],"application/x-tcl":["tcl","tk"],"application/x-x509-ca-cert":["der","pem","crt"],"application/x-xpinstall":["xpi"],"application/xhtml+xml":["xhtml"],"application/zip":["zip"],"application/octet-stream":["bin","exe","dll","deb","dmg","eot","iso","img","msi","msp","msm"],"audio/midi":["mid","midi","kar"],"audio/mpeg":["mp3"],"audio/ogg":["ogg"],"audio/x-realaudio":["ra"],"video/3gpp":["3gpp","3gp"],"video/mpeg":["mpeg","mpg"],"video/quicktime":["mov"],"video/x-flv":["flv"],"video/x-mng":["mng"],"video/x-ms-asf":["asx","asf"],"video/x-ms-wmv":["wmv"],"video/x-msvideo":["avi"],"video/mp4":["m4v","mp4"],"video/webm":["webm"]}},444:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.COMPLEX_FILTER_KEY=t.EXISTS_KEYS=t.GeomFilter_Funcs=t.GeomFilterKeys=t.ArrayFilterOperands=t.TextFilter_FullTextSearchFilterKeys=t.TextFilterFTSKeys=t.TextFilterKeys=t.JsonbFilterKeys=t.JsonbOperands=t.CompareInFilterKeys=t.CompareFilterKeys=void 0;const i=n(128);t.CompareFilterKeys=["=","$eq","<>",">","<",">=","<=","$eq","$ne","$gt","$gte","$lte"],t.CompareInFilterKeys=["$in","$nin"],t.JsonbOperands={"@>":{Operator:"@>","Right Operand Type":"jsonb",Description:"Does the left JSON value contain the right JSON path/value entries at the top level?",Example:'\'{"a":1, "b":2}\'::jsonb @> \'{"b":2}\'::jsonb'},"<@":{Operator:"<@","Right Operand Type":"jsonb",Description:"Are the left JSON path/value entries contained at the top level within the right JSON value?",Example:'\'{"b":2}\'::jsonb <@ \'{"a":1, "b":2}\'::jsonb'},"?":{Operator:"?","Right Operand Type":"text",Description:"Does the string exist as a top-level key within the JSON value?",Example:"'{\"a\":1, \"b\":2}'::jsonb ? 'b'"},"?|":{Operator:"?|","Right Operand Type":"text[]",Description:"Do any of these array strings exist as top-level keys?",Example:"'{\"a\":1, \"b\":2, \"c\":3}'::jsonb ?| array['b', 'c']"},"?&":{Operator:"?&","Right Operand Type":"text[]",Description:"Do all of these array strings exist as top-level keys?",Example:"'[\"a\", \"b\"]'::jsonb ?& array['a', 'b']"},"||":{Operator:"||","Right Operand Type":"jsonb",Description:"Concatenate two jsonb values into a new jsonb value",Example:'\'["a", "b"]\'::jsonb || \'["c", "d"]\'::jsonb'},"-":{Operator:"-","Right Operand Type":"integer",Description:"Delete the array element with specified index (Negative integers count from the end). Throws an error if top level container is not an array.",Example:'\'["a", "b"]\'::jsonb - 1'},"#-":{Operator:"#-","Right Operand Type":"text[]",Description:"Delete the field or element with specified path (for JSON arrays, negative integers count from the end)",Example:"'[\"a\", {\"b\":1}]'::jsonb #- '{1,b}'"},"@?":{Operator:"@?","Right Operand Type":"jsonpath",Description:"Does JSON path return any item for the specified JSON value?",Example:"'{\"a\":[1,2,3,4,5]}'::jsonb @? '$.a[*] ? (@ > 2)'"},"@@":{Operator:"@@","Right Operand Type":"jsonpath",Description:"Returns the result of JSON path predicate check for the specified JSON value. Only the first item of the result is taken into account. If the result is not Boolean, then null is returned.",Example:"'{\"a\":[1,2,3,4,5]}'::jsonb @@ '$.a[*] > 2'"}},t.JsonbFilterKeys=(0,i.getKeys)(t.JsonbOperands),t.TextFilterKeys=["$ilike","$like","$nilike","$nlike"],t.TextFilterFTSKeys=["@@","@>","<@","$contains","$containedBy"],t.TextFilter_FullTextSearchFilterKeys=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"],t.ArrayFilterOperands=["@>","<@","=","$eq","$contains","$containedBy","&&","$overlaps"],t.GeomFilterKeys=["~","~=","@","|&>","|>>",">>","=","<<|","<<","&>","&<|","&<","&&&","&&"],t.GeomFilter_Funcs=["ST_MakeEnvelope","st_makeenvelope","ST_MakePolygon","st_makepolygon"],t.EXISTS_KEYS=["$exists","$notExists","$existsJoined","$notExistsJoined"],t.COMPLEX_FILTER_KEY="$filter"},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.CONTENT_TYPE_TO_EXT=t.getKeys=t.isObject=t.isDefined=t.get=t.WAL=t.unpatchText=t.stableStringify=t.isEmpty=t.getTextPatch=t.omitKeys=t.pickKeys=t.asName=t.RULE_METHODS=t.CHANNELS=t.JOIN_PARAMS=t.JOIN_KEYS=t.TS_PG_Types=t._PG_geometric=t._PG_postgis=t._PG_interval=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","time","timetz","interval","name","cidr","inet","macaddr","macaddr8","int4range","int8range","numrange","tsvector"],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_interval=["interval"],t._PG_postgis=["geometry","geography"],t._PG_geometric=["point","line","lseg","box","path","polygon","circle"];const s={string:[...t._PG_strings,...t._PG_date,...t._PG_geometric,...t._PG_postgis,"lseg"],number:t._PG_numbers,boolean:t._PG_bool,any:[...t._PG_json,...t._PG_interval]};t.TS_PG_Types={...s,"number[]":s.number.map((e=>`_${e}`)),"boolean[]":s.boolean.map((e=>`_${e}`)),"string[]":s.string.map((e=>`_${e}`)),"any[]":s.any.map((e=>`_${e}`))},t.JOIN_KEYS=["$innerJoin","$leftJoin"],t.JOIN_PARAMS=["select","filter","$path","$condition","offset","limit","orderBy"];const o="_psqlWS_.";t.CHANNELS={SCHEMA_CHANGED:o+"schema-changed",SCHEMA:o+"schema",DEFAULT:o,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",CONNECTION:"_psqlWS_.connection",_preffix:o},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 a=n(128);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return a.asName}}),Object.defineProperty(t,"pickKeys",{enumerable:!0,get:function(){return a.pickKeys}}),Object.defineProperty(t,"omitKeys",{enumerable:!0,get:function(){return a.omitKeys}}),Object.defineProperty(t,"getTextPatch",{enumerable:!0,get:function(){return a.getTextPatch}}),Object.defineProperty(t,"isEmpty",{enumerable:!0,get:function(){return a.isEmpty}}),Object.defineProperty(t,"stableStringify",{enumerable:!0,get:function(){return a.stableStringify}}),Object.defineProperty(t,"unpatchText",{enumerable:!0,get:function(){return a.unpatchText}}),Object.defineProperty(t,"WAL",{enumerable:!0,get:function(){return a.WAL}}),Object.defineProperty(t,"get",{enumerable:!0,get:function(){return a.get}}),Object.defineProperty(t,"isDefined",{enumerable:!0,get:function(){return a.isDefined}}),Object.defineProperty(t,"isObject",{enumerable:!0,get:function(){return a.isObject}}),Object.defineProperty(t,"getKeys",{enumerable:!0,get:function(){return a.getKeys}}),r(n(444),t);var l=n(31);Object.defineProperty(t,"CONTENT_TYPE_TO_EXT",{enumerable:!0,get:function(){return l.CONTENT_TYPE_TO_EXT}}),r(n(929),t)},929:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getJSONBSchemaAsJSONSchema=t.DATA_TYPES=t.PrimitiveArrayTypes=t.PrimitiveTypes=void 0;const i=n(128);t.PrimitiveTypes=["boolean","number","integer","string","Date","time","timestamp","any"],t.PrimitiveArrayTypes=t.PrimitiveTypes.map((e=>`${e}[]`)),t.DATA_TYPES=[...t.PrimitiveTypes,...t.PrimitiveArrayTypes];const r=(e,t)=>{const{type:n,arrayOf:s,arrayOfType:o,description:a,nullable:l,oneOf:c,oneOfType:u,title:p,record:d,...m}="string"==typeof e?{type:e}:e;let f={};const h={...(m.enum||m.allowedValues?.length)&&{enum:m.allowedValues?.slice(0)??m.enum.slice(0)},...!!a&&{description:a},...!!p&&{title:p}};if(m.enum?.length&&(h.type=typeof m.enum[0]),"string"==typeof n||s||o){if(n&&"string"!=typeof n)throw"Not expected";f=s||o||n?.endsWith("[]")?{type:"array",items:s||o?r(s||{type:o}):n?.startsWith("any")?{type:void 0}:{type:n?.slice(0,-2),...m.allowedValues&&{enum:m.allowedValues.slice(0)}}}:{type:n}}else(0,i.isObject)(n)?f={type:"object",required:(0,i.getKeys)(n).filter((e=>{const t=n[e];return"string"==typeof t||!t.optional})),properties:(0,i.getKeys)(n).reduce(((e,t)=>({...e,[t]:r(n[t])})),{})}:c||u?f={oneOf:(c||u.map((e=>({type:e})))).map((e=>r(e)))}:d&&(f={type:"object",...d.values&&!d.keysEnum&&{additionalProperties:r(d.values)},...d.keysEnum&&{properties:d.keysEnum.reduce(((e,t)=>({...e,[t]:d.values?r(d.values):{type:{}}})),{})}});if(l){const e={type:"null"};f.oneOf?f.oneOf.push(e):f.enum&&!f.enum.includes(null)?f.enum.push(null):f={oneOf:[f,e]}}return{...t?{$id:t?.id,$schema:"https://json-schema.org/draft/2020-12/schema"}:void 0,...h,...f}};t.getJSONBSchemaAsJSONSchema=function(e,t,n){return r(n,{id:`${e}.${t}`})}},899:(e,t)=>{function n(e,t){var n=e[0],i=e[1],l=e[2],c=e[3];n=r(n,i,l,c,t[0],7,-680876936),c=r(c,n,i,l,t[1],12,-389564586),l=r(l,c,n,i,t[2],17,606105819),i=r(i,l,c,n,t[3],22,-1044525330),n=r(n,i,l,c,t[4],7,-176418897),c=r(c,n,i,l,t[5],12,1200080426),l=r(l,c,n,i,t[6],17,-1473231341),i=r(i,l,c,n,t[7],22,-45705983),n=r(n,i,l,c,t[8],7,1770035416),c=r(c,n,i,l,t[9],12,-1958414417),l=r(l,c,n,i,t[10],17,-42063),i=r(i,l,c,n,t[11],22,-1990404162),n=r(n,i,l,c,t[12],7,1804603682),c=r(c,n,i,l,t[13],12,-40341101),l=r(l,c,n,i,t[14],17,-1502002290),n=s(n,i=r(i,l,c,n,t[15],22,1236535329),l,c,t[1],5,-165796510),c=s(c,n,i,l,t[6],9,-1069501632),l=s(l,c,n,i,t[11],14,643717713),i=s(i,l,c,n,t[0],20,-373897302),n=s(n,i,l,c,t[5],5,-701558691),c=s(c,n,i,l,t[10],9,38016083),l=s(l,c,n,i,t[15],14,-660478335),i=s(i,l,c,n,t[4],20,-405537848),n=s(n,i,l,c,t[9],5,568446438),c=s(c,n,i,l,t[14],9,-1019803690),l=s(l,c,n,i,t[3],14,-187363961),i=s(i,l,c,n,t[8],20,1163531501),n=s(n,i,l,c,t[13],5,-1444681467),c=s(c,n,i,l,t[2],9,-51403784),l=s(l,c,n,i,t[7],14,1735328473),n=o(n,i=s(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,r,s){return t=d(d(t,e),d(i,s)),d(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 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 p(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,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(r,s),t=0;t<16;t++)s[t]=0;return s[14]=8*i,n(r,s),r}(e))}function d(e,t){return e+t&4294967295}t.md5=p,p("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.find=t.filter=t.omitKeys=t.pickKeys=t.asName=void 0;const i=n(899);function r(e,t=[],n=!1){let i=t;if(!i.length)return{};if(e&&i.length){let t={};return i.forEach((i=>{n&&void 0===e[i]||(t[i]=e[i])})),t}return e}function s(e,t){return e.filter((e=>Object.entries(t).every((([t,n])=>e[t]===n))))}function o(e){for(var t in e)return!1;return!0}function a(e){return Object.keys(e)}t.asName=function(e){if(null==e||!e.toString||!e.toString())throw"Expecting a non empty string";return`"${e.toString().replace(/"/g,'""')}"`},t.pickKeys=r,t.omitKeys=function(e,t){return r(e,a(e).filter((e=>!t.includes(e))))},t.filter=s,t.find=function(e,t){return s(e,t)[0]},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,l=Object.keys(t).sort(r&&r(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,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=>{o(this.changed)&&this.options.onSendStart&&this.options.onSendStart(),e.map((e=>{var t;const{initial:n,current:i,delta:r}={...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,delta:r}),this.changed[s].current={...this.changed[s].current,...i},this.changed[s].delta={...this.changed[s].delta,...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:i,throttle:r,historyAgeSeconds:s=2}=this.options;if(this.isSendingTimeout||this.sending&&!o(this.sending))return;if(!this.changed||o(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=>{let t={};return Object.keys(e.current).map((n=>{const i=e.initial?.[n],r=e.current[n];var s,o;![this.options.synced_field,...this.options.id_fields].includes(n)&&((s=i)===(o=r)||(["number","string","boolean"].includes(typeof s)?s===o:JSON.stringify(s)===JSON.stringify(o)))||(t[n]=r)})),t})),e&&console.log(this.options.id," SENDING lr->",l[l.length-1]),this.isSendingTimeout||(this.isSendingTimeout=setTimeout((()=>{this.isSendingTimeout=void 0,o(this.changed)||this.sendItems()}),r)),this.isOnSending=!0;try{await t(l,c),s&&(this.sentHistory={...this.sentHistory,...u},this.willDeleteHistory||(this.willDeleteHistory=setTimeout((()=>{this.willDeleteHistory=void 0,this.sentHistory={}}),1e3*s)))}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]),o(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||!(o(this.sending)&&o(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=o,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=a}},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}));
|
|
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.asName=t.debug=void 0;const i=n(792);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return i.asName}});const 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:a,onDisconnect:l,onReconnect:c,onSchemaChange:u=!0,onReload:p}=e;if((0,t.debug)("prostgles",{initOpts:e}),u){let e;"function"==typeof u&&(e=u),r.removeAllListeners(i.CHANNELS.SCHEMA_CHANGED),e&&r.on(i.CHANNELS.SCHEMA_CHANGED,e)}const d=i.CHANNELS._preffix;let m,f={},h={},g={},y={},b=!1;function O(e,n,i){return(0,t.debug)("_unsubscribe",{channelName:e,handler:i}),new Promise(((t,s)=>{f[e]?(f[e].handlers=f[e].handlers.filter((e=>e!==i)),f[e].handlers.length||(r.emit(n,{},((e,t)=>{e&&console.error(e)})),r.removeListener(e,f[e].onCall),delete f[e]),t(!0)):t(!0)}))}function v({tableName:e,command:t,param1:n,param2:i},s){return new Promise(((o,a)=>{r.emit(d,{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 _({tableName:e,command:t,param1:n,param2:i}){return new Promise(((s,o)=>{r.emit(d,{tableName:e,command:t,param1:n,param2:i},((e,t)=>{e?(console.error(e),o(e)):t&&s(t)}))}))}const S=new o((async function({tableName:e,command:n,param1:i,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,i)=>{g[e]&&(g[e].triggers=g[e].triggers.filter((e=>e.onPullRequest!==n.onPullRequest&&e.onSyncRequest!==n.onSyncRequest&&e.onUpdates!==n.onUpdates)),g[e].triggers.length||(r.emit(e+"unsync",{},((e,n)=>{e?i(e):t(n)})),r.removeListener(e,g[e].onCall),delete g[e]))}))}(e,o)},syncData:function(t,n,i){r.emit(e,{onSyncRequest:{...l({}),...{data:t}||{},...{deleted:n}||{}}},i?e=>{i(e)}:null)}})}const p=Object.keys(g).find((t=>{let r=g[t];return r&&r.tableName===e&&r.command===n&&JSON.stringify(r.param1||{})===JSON.stringify(i||{})&&JSON.stringify(r.param2||{})===JSON.stringify(s||{})}));if(p)return g[p].triggers.push(o),u(p);{const d=await v({tableName:e,command:n,param1:i,param2:s},l),{channelName:m,synced_field:f,id_fields:h}=d;function y(t,n){t&&g[m]&&g[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 g[m]={tableName:e,command:n,param1:i,param2:s,triggers:[o],syncInfo:d,onCall:y},r.on(m,y),u(m)}}),(([{tableName:e}])=>e)),N=new o((async function(e,{tableName:t,command:n,param1:i,param2:s},o,a){function l(n,r){let s={unsubscribe:function(){return O(n,r,o)},filter:{...i}};return e[t].update&&(s={...s,update:function(n,r){return e[t].update(i,n,r)}}),e[t].delete&&(s={...s,delete:function(n){return e[t].delete(i,n)}}),Object.freeze(s)}const c=Object.entries(f).find((([e])=>{let r=f[e];return r&&r.tableName===t&&r.command===n&&JSON.stringify(r.param1||{})===JSON.stringify(i||{})&&JSON.stringify(r.param2||{})===JSON.stringify(s||{})}));if(c){const e=c[0];return c[1].handlers.push(o),c[1].errorHandlers.push(a),setTimeout((()=>{var t,n;o&&(null===(t=null==f?void 0:f[e])||void 0===t?void 0:t.lastData)&&o(null===(n=null==f?void 0:f[e])||void 0===n?void 0:n.lastData)}),10),l(e,c[1].unsubChannel)}const{channelName:u,channelNameReady:p,channelNameUnsubscribe:d}=await _({tableName:t,command:n,param1:i,param2:s}),m=function(e,t){const n=f[u];n?e.data?(n.lastData=e.data,n.handlers.forEach((t=>{t(e.data)}))):e.err?n.errorHandlers.forEach((t=>{t(e.err)})):console.error("INTERNAL ERROR: Unexpected data format from subscription: ",e):console.warn("Orphaned subscription: ",u)},h=a||function(e){console.error(`Uncaught error within running subscription \n ${u}`,e)};return r.on(u,m),f[u]={lastData:void 0,tableName:t,command:n,param1:i,param2:s,onCall:m,unsubChannel:d,handlers:[o],errorHandlers:[h],destroy:()=>{f[u]&&(Object.values(f[u]).map((e=>{e&&e.handlers&&e.handlers.map((e=>O(u,d,e)))})),delete f[u])}},r.emit(p,{now:Date.now()}),l(u,d)}),(([e,{tableName:t}])=>t));async function x(e,t,n,i){return N.run([e,t,n,i])}return new Promise(((e,o)=>{r.removeAllListeners(i.CHANNELS.CONNECTION),r.on(i.CHANNELS.CONNECTION,(e=>(o(e),"ok"))),l&&r.on("disconnect",l),r.on(i.CHANNELS.SCHEMA,(({schema:l,methods:u,tableSchema:O,auth:N,rawSQL:E,joinTables:j=[],err:T})=>{if((0,t.debug)("destroySyncs",{subscriptions:f,syncedTables:h}),Object.values(f).map((e=>e.destroy())),f={},g={},Object.values(h).map((e=>{e&&e.destroy&&e.destroy()})),h={},b&&c&&(c(r,T),T))return void console.error(T);if(T)throw o(T),T;b=!0;let w=JSON.parse(JSON.stringify(l)),P=JSON.parse(JSON.stringify(u)),C={},A={};if(N){if(N.pathGuard&&s){const e=e=>{var t,n;(null==e?void 0:e.shouldReload)&&(p?p():"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)}))}A={...N},[i.CHANNELS.LOGIN,i.CHANNELS.LOGOUT,i.CHANNELS.REGISTER].map((e=>{N[e]&&(A[e]=function(t){return new Promise(((n,i)=>{r.emit(d+e,t,((e,t)=>{e?i(e):n(t)}))}))})}))}P.map((e=>{const t="string"==typeof e,n=function(...e){return new Promise(((t,n)=>{r.emit(i.CHANNELS.METHOD,{method:s,params:e},((e,i)=>{e?n(e):t(i)}))}))},s=t?e:e.name;C[s]=t?n:{...e,run:n}})),C=Object.freeze(C),E&&(w.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)=>{m=m||{config:t,listeners:[]},m.listeners.length||(r.removeAllListeners(t.socketChannel),r.on(t.socketChannel,(e=>{m&&m.listeners&&m.listeners.length?m.listeners.map((t=>{t(e)})):r.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&&r&&r.emit(m.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)=>{var n;y=y||{},y[t.notifChannel]?null===(n=y[t.notifChannel])||void 0===n||n.listeners.push(e):(y[t.notifChannel]={config:t,listeners:[e]},r.removeAllListeners(t.socketChannel),r.on(t.socketChannel,(e=>{var n,i;(null===(n=y[t.notifChannel])||void 0===n?void 0:n.listeners.length)?y[t.notifChannel].listeners.map((t=>{t(e)})):r.emit(null===(i=y[t.notifChannel])||void 0===i?void 0:i.config.socketUnsubChannel,{})})))})(e,t),{...t,removeListener:()=>((e,t)=>{const n=y[t.notifChannel];n&&(n.listeners=n.listeners.filter((t=>t!==e)),!n.listeners.length&&n.config&&n.config.socketUnsubChannel&&r&&(r.emit(n.config.socketUnsubChannel,{}),delete y[t.notifChannel]))})(e,t)}),n={...t,addListener:e};s(n)}}))}))});const k=e=>"[object Object]"===Object.prototype.toString.call(e),J=(e,t,n,i)=>{if(!k(e)||!k(t)||"function"!=typeof n||i&&"function"!=typeof i)throw"Expecting: ( basicFilter<object>, options<object>, onChange<function> , onError?<function>) but got something else"},D=["subscribe","subscribeOne"];(0,i.getKeys)(w).forEach((e=>{Object.keys(w[e]).sort(((e,t)=>D.includes(e)-D.includes(t))).forEach((t=>{if(["find","findOne"].includes(t)&&(w[e].getJoinedTables=function(){return(j||[]).filter((t=>Array.isArray(t)&&t.includes(e))).flat().filter((t=>t!==e))}),"sync"===t){if(w[e]._syncInfo={...w[e][t]},n){w[e].getSync=(t,i={})=>n.create({name:e,filter:t,db:w,...i});const t=async(t={},i={},r)=>{const s=`${e}.${JSON.stringify(t)}.${JSON.stringify(i)}`;return h[s]||(h[s]=await n.create({...i,name:e,filter:t,db:w,onError:r})),h[s]};w[e].sync=async(e,n={handlesOnData:!0,select:"*"},i,r)=>{J(e,n,i,r);const s=await t(e,n,r);return await s.sync(i,n.handlesOnData)},w[e].syncOne=async(e,n={handlesOnData:!0},i,r)=>{J(e,n,i,r);const s=await t(e,n,r);return await s.syncOne(e,i,n.handlesOnData)}}w[e]._sync=function(n,i,r){return async function(e,t){return S.run([e,t])}({tableName:e,command:t,param1:n,param2:i},r)}}else if(D.includes(t)){const n=function(n,i,r,s){return J(n,i,r,s),x(w,{tableName:e,command:t,param1:n,param2:i},r,s)};w[e][t]=n;const i="subscribeOne";w[e][t+"Hook"]=function(e,r,s){return{start:o=>n(e,r,t!==i?o:e=>{o(e[0])},s),args:[e,r,s]}},t!==i&&D.includes(i)||(w[e][i]=function(n,i,r,s){return J(n,i,r,s),x(w,{tableName:e,command:t,param1:n,param2:i},(e=>{r(e[0])}),s)})}else w[e][t]=function(n,i,s){return new Promise(((o,a)=>{r.emit(d,{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 _(t),r.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting old subscriptions",e)}})),g&&Object.keys(g).length&&(0,i.getKeys)(g).filter((e=>{var t;return null===(t=g[e])||void 0===t?void 0:t.triggers.length})).map((async e=>{try{let t=g[e];await v(t,t.triggers[0].onSyncRequest),r.on(e,t.onCall)}catch(e){console.error("There was an issue reconnecting olf subscriptions",e)}})),j.flat().map((e=>{function t(t=!0,n,i,r){return{[t?"$leftJoin":"$innerJoin"]:e,filter:n,select:i,...r}}w.innerJoin=w.innerJoin||{},w.leftJoin=w.leftJoin||{},w.innerJoinOne=w.innerJoinOne||{},w.leftJoinOne=w.leftJoinOne||{},w.leftJoin[e]=(e,n,i={})=>t(!0,e,n,i),w.innerJoin[e]=(e,n,i={})=>t(!1,e,n,i),w.leftJoinOne[e]=(e,n,i={})=>t(!0,e,n,{...i,limit:1}),w.innerJoinOne[e]=(e,n,i={})=>t(!1,e,n,{...i,limit:1})})),(async()=>{try{await a(w,C,O,A,b)}catch(e){console.error("Prostgles: Error within onReady: \n",e),o(e)}e(w)})()}))}))};class o{constructor(e,t){this.queue=[],this.isRunning=!1,this.func=e,this.groupBy=t}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=async e=>{if(e){const t=await this.func(...e.arguments);e.onResult(t)}};if(this.groupBy){const t=[],n=[];this.queue.forEach((async(e,i)=>{const r=this.groupBy(e.arguments);t.includes(r)||(t.push(r),n.push({index:i,item:e}))})),n.slice(0).reverse().forEach((e=>{this.queue.splice(e.index,1)})),await Promise.all(n.map((t=>e(t.item))))}else{const t=this.queue.shift();await e(t)}this.isRunning=!1,this.queue.length&&n()};return n(),t}}},792:function(e){var t;this||window,t=()=>(()=>{"use strict";var e={31:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CONTENT_TYPE_TO_EXT=void 0,t.CONTENT_TYPE_TO_EXT={"text/html":["html","htm","shtml"],"text/css":["css"],"text/csv":["csv"],"text/tsv":["tsv"],"text/xml":["xml"],"text/mathml":["mml"],"text/plain":["txt"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/x-component":["htc"],"image/gif":["gif"],"image/jpeg":["jpeg","jpg"],"image/png":["png"],"image/tiff":["tif","tiff"],"image/vnd.wap.wbmp":["wbmp"],"image/x-icon":["ico"],"image/x-jng":["jng"],"image/x-ms-bmp":["bmp"],"image/svg+xml":["svg"],"image/webp":["webp"],"application/sql":["sql"],"application/x-javascript":["js"],"application/atom+xml":["atom"],"application/rss+xml":["rss"],"application/java-archive":["jar","war","ear"],"application/mac-binhex40":["hqx"],"application/msword":["doc","docx"],"application/pdf":["pdf"],"application/postscript":["ps","eps","ai"],"application/rtf":["rtf"],"application/vnd.ms-excel":["xls","xlsx"],"application/vnd.ms-powerpoint":["ppt","pptx"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/x-7z-compressed":["7z"],"application/x-cocoa":["cco"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-makeself":["run"],"application/x-perl":["pl","pm"],"application/x-pilot":["prc","pdb"],"application/x-rar-compressed":["rar"],"application/x-redhat-package-manager":["rpm"],"application/x-sea":["sea"],"application/x-shockwave-flash":["swf"],"application/x-stuffit":["sit"],"application/x-tcl":["tcl","tk"],"application/x-x509-ca-cert":["der","pem","crt"],"application/x-xpinstall":["xpi"],"application/xhtml+xml":["xhtml"],"application/zip":["zip"],"application/octet-stream":["bin","exe","dll","deb","dmg","eot","iso","img","msi","msp","msm"],"audio/midi":["mid","midi","kar"],"audio/mpeg":["mp3"],"audio/ogg":["ogg"],"audio/x-realaudio":["ra"],"video/3gpp":["3gpp","3gp"],"video/mpeg":["mpeg","mpg"],"video/quicktime":["mov"],"video/x-flv":["flv"],"video/x-mng":["mng"],"video/x-ms-asf":["asx","asf"],"video/x-ms-wmv":["wmv"],"video/x-msvideo":["avi"],"video/mp4":["m4v","mp4"],"video/webm":["webm"]}},444:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.COMPLEX_FILTER_KEY=t.EXISTS_KEYS=t.GeomFilter_Funcs=t.GeomFilterKeys=t.ArrayFilterOperands=t.TextFilter_FullTextSearchFilterKeys=t.TextFilterFTSKeys=t.TextFilterKeys=t.JsonbFilterKeys=t.JsonbOperands=t.CompareInFilterKeys=t.CompareFilterKeys=void 0;const i=n(128);t.CompareFilterKeys=["=","$eq","<>",">","<",">=","<=","$eq","$ne","$gt","$gte","$lte"],t.CompareInFilterKeys=["$in","$nin"],t.JsonbOperands={"@>":{Operator:"@>","Right Operand Type":"jsonb",Description:"Does the left JSON value contain the right JSON path/value entries at the top level?",Example:'\'{"a":1, "b":2}\'::jsonb @> \'{"b":2}\'::jsonb'},"<@":{Operator:"<@","Right Operand Type":"jsonb",Description:"Are the left JSON path/value entries contained at the top level within the right JSON value?",Example:'\'{"b":2}\'::jsonb <@ \'{"a":1, "b":2}\'::jsonb'},"?":{Operator:"?","Right Operand Type":"text",Description:"Does the string exist as a top-level key within the JSON value?",Example:"'{\"a\":1, \"b\":2}'::jsonb ? 'b'"},"?|":{Operator:"?|","Right Operand Type":"text[]",Description:"Do any of these array strings exist as top-level keys?",Example:"'{\"a\":1, \"b\":2, \"c\":3}'::jsonb ?| array['b', 'c']"},"?&":{Operator:"?&","Right Operand Type":"text[]",Description:"Do all of these array strings exist as top-level keys?",Example:"'[\"a\", \"b\"]'::jsonb ?& array['a', 'b']"},"||":{Operator:"||","Right Operand Type":"jsonb",Description:"Concatenate two jsonb values into a new jsonb value",Example:'\'["a", "b"]\'::jsonb || \'["c", "d"]\'::jsonb'},"-":{Operator:"-","Right Operand Type":"integer",Description:"Delete the array element with specified index (Negative integers count from the end). Throws an error if top level container is not an array.",Example:'\'["a", "b"]\'::jsonb - 1'},"#-":{Operator:"#-","Right Operand Type":"text[]",Description:"Delete the field or element with specified path (for JSON arrays, negative integers count from the end)",Example:"'[\"a\", {\"b\":1}]'::jsonb #- '{1,b}'"},"@?":{Operator:"@?","Right Operand Type":"jsonpath",Description:"Does JSON path return any item for the specified JSON value?",Example:"'{\"a\":[1,2,3,4,5]}'::jsonb @? '$.a[*] ? (@ > 2)'"},"@@":{Operator:"@@","Right Operand Type":"jsonpath",Description:"Returns the result of JSON path predicate check for the specified JSON value. Only the first item of the result is taken into account. If the result is not Boolean, then null is returned.",Example:"'{\"a\":[1,2,3,4,5]}'::jsonb @@ '$.a[*] > 2'"}},t.JsonbFilterKeys=(0,i.getKeys)(t.JsonbOperands),t.TextFilterKeys=["$ilike","$like","$nilike","$nlike"],t.TextFilterFTSKeys=["@@","@>","<@","$contains","$containedBy"],t.TextFilter_FullTextSearchFilterKeys=["to_tsquery","plainto_tsquery","phraseto_tsquery","websearch_to_tsquery"],t.ArrayFilterOperands=["@>","<@","=","$eq","$contains","$containedBy","&&","$overlaps"],t.GeomFilterKeys=["~","~=","@","|&>","|>>",">>","=","<<|","<<","&>","&<|","&<","&&&","&&"],t.GeomFilter_Funcs=["ST_MakeEnvelope","st_makeenvelope","ST_MakePolygon","st_makepolygon"],t.EXISTS_KEYS=["$exists","$notExists","$existsJoined","$notExistsJoined"],t.COMPLEX_FILTER_KEY="$filter"},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.CONTENT_TYPE_TO_EXT=t.getKeys=t.isObject=t.isDefined=t.get=t.WAL=t.unpatchText=t.stableStringify=t.isEmpty=t.getTextPatch=t.omitKeys=t.pickKeys=t.asName=t.RULE_METHODS=t.CHANNELS=t.JOIN_PARAMS=t.JOIN_KEYS=t.TS_PG_Types=t._PG_geometric=t._PG_postgis=t._PG_interval=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","time","timetz","interval","name","cidr","inet","macaddr","macaddr8","int4range","int8range","numrange","tsvector"],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_interval=["interval"],t._PG_postgis=["geometry","geography"],t._PG_geometric=["point","line","lseg","box","path","polygon","circle"];const s={string:[...t._PG_strings,...t._PG_date,...t._PG_geometric,...t._PG_postgis,"lseg"],number:t._PG_numbers,boolean:t._PG_bool,any:[...t._PG_json,...t._PG_interval]};t.TS_PG_Types={...s,"number[]":s.number.map((e=>`_${e}`)),"boolean[]":s.boolean.map((e=>`_${e}`)),"string[]":s.string.map((e=>`_${e}`)),"any[]":s.any.map((e=>`_${e}`))},t.JOIN_KEYS=["$innerJoin","$leftJoin"],t.JOIN_PARAMS=["select","filter","$path","$condition","offset","limit","orderBy"];const o="_psqlWS_.";t.CHANNELS={SCHEMA_CHANGED:o+"schema-changed",SCHEMA:o+"schema",DEFAULT:o,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",CONNECTION:"_psqlWS_.connection",_preffix:o},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 a=n(128);Object.defineProperty(t,"asName",{enumerable:!0,get:function(){return a.asName}}),Object.defineProperty(t,"pickKeys",{enumerable:!0,get:function(){return a.pickKeys}}),Object.defineProperty(t,"omitKeys",{enumerable:!0,get:function(){return a.omitKeys}}),Object.defineProperty(t,"getTextPatch",{enumerable:!0,get:function(){return a.getTextPatch}}),Object.defineProperty(t,"isEmpty",{enumerable:!0,get:function(){return a.isEmpty}}),Object.defineProperty(t,"stableStringify",{enumerable:!0,get:function(){return a.stableStringify}}),Object.defineProperty(t,"unpatchText",{enumerable:!0,get:function(){return a.unpatchText}}),Object.defineProperty(t,"WAL",{enumerable:!0,get:function(){return a.WAL}}),Object.defineProperty(t,"get",{enumerable:!0,get:function(){return a.get}}),Object.defineProperty(t,"isDefined",{enumerable:!0,get:function(){return a.isDefined}}),Object.defineProperty(t,"isObject",{enumerable:!0,get:function(){return a.isObject}}),Object.defineProperty(t,"getKeys",{enumerable:!0,get:function(){return a.getKeys}}),r(n(444),t);var l=n(31);Object.defineProperty(t,"CONTENT_TYPE_TO_EXT",{enumerable:!0,get:function(){return l.CONTENT_TYPE_TO_EXT}}),r(n(929),t)},929:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getJSONBSchemaAsJSONSchema=t.DATA_TYPES=t.PrimitiveArrayTypes=t.PrimitiveTypes=void 0;const i=n(128);t.PrimitiveTypes=["boolean","number","integer","string","Date","time","timestamp","any"],t.PrimitiveArrayTypes=t.PrimitiveTypes.map((e=>`${e}[]`)),t.DATA_TYPES=[...t.PrimitiveTypes,...t.PrimitiveArrayTypes];const r=(e,t)=>{const{type:n,arrayOf:s,arrayOfType:o,description:a,nullable:l,oneOf:c,oneOfType:u,title:p,record:d,...m}="string"==typeof e?{type:e}:e;let f={};const h={...(m.enum||m.allowedValues?.length)&&{enum:m.allowedValues?.slice(0)??m.enum.slice(0)},...!!a&&{description:a},...!!p&&{title:p}};if(m.enum?.length&&(h.type=typeof m.enum[0]),"string"==typeof n||s||o){if(n&&"string"!=typeof n)throw"Not expected";f=s||o||n?.endsWith("[]")?{type:"array",items:s||o?r(s||{type:o}):n?.startsWith("any")?{type:void 0}:{type:n?.slice(0,-2),...m.allowedValues&&{enum:m.allowedValues.slice(0)}}}:{type:n}}else(0,i.isObject)(n)?f={type:"object",required:(0,i.getKeys)(n).filter((e=>{const t=n[e];return"string"==typeof t||!t.optional})),properties:(0,i.getKeys)(n).reduce(((e,t)=>({...e,[t]:r(n[t])})),{})}:c||u?f={oneOf:(c||u.map((e=>({type:e})))).map((e=>r(e)))}:d&&(f={type:"object",...d.values&&!d.keysEnum&&{additionalProperties:r(d.values)},...d.keysEnum&&{properties:d.keysEnum.reduce(((e,t)=>({...e,[t]:d.values?r(d.values):{type:{}}})),{})}});if(l){const e={type:"null"};f.oneOf?f.oneOf.push(e):f.enum&&!f.enum.includes(null)?f.enum.push(null):f={oneOf:[f,e]}}return{...t?{$id:t?.id,$schema:"https://json-schema.org/draft/2020-12/schema"}:void 0,...h,...f}};t.getJSONBSchemaAsJSONSchema=function(e,t,n){return r(n,{id:`${e}.${t}`})}},899:(e,t)=>{function n(e,t){var n=e[0],i=e[1],l=e[2],c=e[3];n=r(n,i,l,c,t[0],7,-680876936),c=r(c,n,i,l,t[1],12,-389564586),l=r(l,c,n,i,t[2],17,606105819),i=r(i,l,c,n,t[3],22,-1044525330),n=r(n,i,l,c,t[4],7,-176418897),c=r(c,n,i,l,t[5],12,1200080426),l=r(l,c,n,i,t[6],17,-1473231341),i=r(i,l,c,n,t[7],22,-45705983),n=r(n,i,l,c,t[8],7,1770035416),c=r(c,n,i,l,t[9],12,-1958414417),l=r(l,c,n,i,t[10],17,-42063),i=r(i,l,c,n,t[11],22,-1990404162),n=r(n,i,l,c,t[12],7,1804603682),c=r(c,n,i,l,t[13],12,-40341101),l=r(l,c,n,i,t[14],17,-1502002290),n=s(n,i=r(i,l,c,n,t[15],22,1236535329),l,c,t[1],5,-165796510),c=s(c,n,i,l,t[6],9,-1069501632),l=s(l,c,n,i,t[11],14,643717713),i=s(i,l,c,n,t[0],20,-373897302),n=s(n,i,l,c,t[5],5,-701558691),c=s(c,n,i,l,t[10],9,38016083),l=s(l,c,n,i,t[15],14,-660478335),i=s(i,l,c,n,t[4],20,-405537848),n=s(n,i,l,c,t[9],5,568446438),c=s(c,n,i,l,t[14],9,-1019803690),l=s(l,c,n,i,t[3],14,-187363961),i=s(i,l,c,n,t[8],20,1163531501),n=s(n,i,l,c,t[13],5,-1444681467),c=s(c,n,i,l,t[2],9,-51403784),l=s(l,c,n,i,t[7],14,1735328473),n=o(n,i=s(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,r,s){return t=d(d(t,e),d(i,s)),d(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 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 p(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,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(r,s),t=0;t<16;t++)s[t]=0;return s[14]=8*i,n(r,s),r}(e))}function d(e,t){return e+t&4294967295}t.md5=p,p("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.find=t.filter=t.omitKeys=t.pickKeys=t.asName=void 0;const i=n(899);function r(e,t=[],n=!1){let i=t;if(!i.length)return{};if(e&&i.length){let t={};return i.forEach((i=>{n&&void 0===e[i]||(t[i]=e[i])})),t}return e}function s(e,t){return e.filter((e=>Object.entries(t).every((([t,n])=>e[t]===n))))}function o(e){for(var t in e)return!1;return!0}function a(e){return Object.keys(e)}t.asName=function(e){if(null==e||!e.toString||!e.toString())throw"Expecting a non empty string";return`"${e.toString().replace(/"/g,'""')}"`},t.pickKeys=r,t.omitKeys=function(e,t){return r(e,a(e).filter((e=>!t.includes(e))))},t.filter=s,t.find=function(e,t){return s(e,t)[0]},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,l=Object.keys(t).sort(r&&r(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,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=>{o(this.changed)&&this.options.onSendStart&&this.options.onSendStart(),e.map((e=>{var t;const{initial:n,current:i,delta:r}={...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,delta:r}),this.changed[s].current={...this.changed[s].current,...i},this.changed[s].delta={...this.changed[s].delta,...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:i,throttle:r,historyAgeSeconds:s=2}=this.options;if(this.isSendingTimeout||this.sending&&!o(this.sending))return;if(!this.changed||o(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=>{let t={};return Object.keys(e.current).map((n=>{const i=e.initial?.[n],r=e.current[n];var s,o;![this.options.synced_field,...this.options.id_fields].includes(n)&&((s=i)===(o=r)||(["number","string","boolean"].includes(typeof s)?s===o:JSON.stringify(s)===JSON.stringify(o)))||(t[n]=r)})),t})),e&&console.log(this.options.id," SENDING lr->",l[l.length-1]),this.isSendingTimeout||(this.isSendingTimeout=setTimeout((()=>{this.isSendingTimeout=void 0,o(this.changed)||this.sendItems()}),r)),this.isOnSending=!0;try{await t(l,c),s&&(this.sentHistory={...this.sentHistory,...u},this.willDeleteHistory||(this.willDeleteHistory=setTimeout((()=>{this.willDeleteHistory=void 0,this.sentHistory={}}),1e3*s)))}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]),o(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||!(o(this.sending)&&o(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=o,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=a}},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
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TableHandler,
|
|
1
|
+
import { TableHandler, DbJoinMaker, AnyObject, SubscriptionHandler, SQLHandler, DBSchemaTable, MethodHandler, SQLResult, DBSchema, ViewHandler, asName, FullFilter, SubscribeParams, OnError, GetSelectReturnType } from "prostgles-types";
|
|
2
2
|
import type { Sync, SyncOne } from "./SyncedTable";
|
|
3
3
|
export declare const debug: any;
|
|
4
4
|
export { MethodHandler, SQLResult, asName };
|
|
@@ -9,16 +9,16 @@ export type ViewHandlerClient<T extends AnyObject = AnyObject, S = void> = ViewH
|
|
|
9
9
|
sync?: Sync<T>;
|
|
10
10
|
syncOne?: SyncOne<T>;
|
|
11
11
|
_sync?: any;
|
|
12
|
-
subscribeHook: <SubParams extends SubscribeParams<T>>(filter?: FullFilter<T, S>, options?: SubParams, onError?: OnError) => {
|
|
13
|
-
start: ((onChange: (items: GetSelectReturnType<SubParams, T, false>[]) => any) => Promise<SubscriptionHandler<T>>);
|
|
12
|
+
subscribeHook: <SubParams extends SubscribeParams<T, S>>(filter?: FullFilter<T, S>, options?: SubParams, onError?: OnError) => {
|
|
13
|
+
start: ((onChange: (items: GetSelectReturnType<S, SubParams, T, false>[]) => any) => Promise<SubscriptionHandler<T>>);
|
|
14
14
|
args: [
|
|
15
15
|
filter?: FullFilter<T, S>,
|
|
16
16
|
options?: SubscribeParams<T>,
|
|
17
17
|
onError?: OnError
|
|
18
18
|
];
|
|
19
19
|
};
|
|
20
|
-
subscribeOneHook: <SubParams extends SubscribeParams<T>>(filter?: FullFilter<T, S>, options?: SubscribeParams<T>, onError?: OnError) => {
|
|
21
|
-
start: (onChange: (item: GetSelectReturnType<SubParams, T, false> | undefined) => any) => Promise<SubscriptionHandler<T>>;
|
|
20
|
+
subscribeOneHook: <SubParams extends SubscribeParams<T, S>>(filter?: FullFilter<T, S>, options?: SubscribeParams<T>, onError?: OnError) => {
|
|
21
|
+
start: (onChange: (item: GetSelectReturnType<S, SubParams, T, false> | undefined) => any) => Promise<SubscriptionHandler<T>>;
|
|
22
22
|
args: [
|
|
23
23
|
filter?: FullFilter<T, S>,
|
|
24
24
|
options?: SubscribeParams<T>,
|
|
@@ -34,14 +34,6 @@ export type TableHandlerClient<T extends AnyObject = AnyObject, S = void> = Tabl
|
|
|
34
34
|
syncOne?: SyncOne<T>;
|
|
35
35
|
_sync?: any;
|
|
36
36
|
};
|
|
37
|
-
export type TableHandlerClientBasic = TableHandlerBasic & {
|
|
38
|
-
getJoinedTables: () => string[];
|
|
39
|
-
_syncInfo?: any;
|
|
40
|
-
getSync?: any;
|
|
41
|
-
sync?: Sync;
|
|
42
|
-
syncOne?: SyncOne;
|
|
43
|
-
_sync?: any;
|
|
44
|
-
};
|
|
45
37
|
export type DBHandlerClient<Tables extends Record<string, AnyObject> = Record<string, AnyObject>> = {
|
|
46
38
|
[key in keyof Tables]: Partial<TableHandlerClient<Tables[key]>>;
|
|
47
39
|
} & DbJoinMaker & {
|
|
@@ -50,22 +42,6 @@ export type DBHandlerClient<Tables extends Record<string, AnyObject> = Record<st
|
|
|
50
42
|
export type DBOFullyTyped<Schema = void> = Schema extends DBSchema ? {
|
|
51
43
|
[tov_name in keyof Schema]: Schema[tov_name]["is_view"] extends true ? ViewHandlerClient<Schema[tov_name]["columns"], Schema> : TableHandlerClient<Schema[tov_name]["columns"], Schema>;
|
|
52
44
|
} & Pick<DBHandlerClient, "sql"> : DBHandlerClient;
|
|
53
|
-
export type DBHandlerClientBasic = {
|
|
54
|
-
[key: string]: Partial<TableHandlerClientBasic>;
|
|
55
|
-
} & {
|
|
56
|
-
innerJoin: TableJoinBasic;
|
|
57
|
-
leftJoin: TableJoinBasic;
|
|
58
|
-
innerJoinOne: TableJoinBasic;
|
|
59
|
-
leftJoinOne: TableJoinBasic;
|
|
60
|
-
} & {
|
|
61
|
-
/**
|
|
62
|
-
*
|
|
63
|
-
* @param query <string> query. e.g.: SELECT * FROM users;
|
|
64
|
-
* @param params <any[] | object> query arguments to be escaped. e.g.: { name: 'dwadaw' }
|
|
65
|
-
* @param options <object> { returnType: "statement" | "rows" | "noticeSubscription" }
|
|
66
|
-
*/
|
|
67
|
-
sql?: SQLHandler;
|
|
68
|
-
};
|
|
69
45
|
export type Auth = {
|
|
70
46
|
register?: (params: any) => Promise<any>;
|
|
71
47
|
login?: (params: any) => Promise<any>;
|
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,EACL,YAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"prostgles.d.ts","sourceRoot":"","sources":["../lib/prostgles.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,YAAY,EAAE,WAAW,EAET,SAAS,EAAE,mBAAmB,EAC9C,UAAU,EAAqC,aAAa,EACjC,aAAa,EAA+D,SAAS,EAAE,QAAQ,EAAE,WAAW,EACvI,MAAM,EAGN,UAAU,EACV,eAAe,EACf,OAAO,EACP,mBAAmB,EAEpB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EAAe,IAAI,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAIhE,eAAO,MAAM,KAAK,EAAE,GAInB,CAAC;AAEF,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC;AAE5C,MAAM,MAAM,iBAAiB,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,EAAE,CAAC,GAAG,IAAI,IAAI,WAAW,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG;IAC7F,eAAe,EAAE,MAAM,MAAM,EAAE,CAAC;IAChC,SAAS,CAAC,EAAE,GAAG,CAAC;IAChB,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IACrB,KAAK,CAAC,EAAE,GAAG,CAAC;IACZ,aAAa,EAAE,CAAC,SAAS,SAAS,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,EACrD,MAAM,CAAC,EAAE,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,EACzB,OAAO,CAAC,EAAE,SAAS,EACnB,OAAO,CAAC,EAAE,OAAO,KACd;QACH,KAAK,EAAE,CAAC,CACN,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,KAAK,GAAG,KACpE,OAAO,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QACrC,IAAI,EAAE;YACJ,MAAM,CAAC,EAAE,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC;YACzB,OAAO,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC;YAC5B,OAAO,CAAC,EAAE,OAAO;SAClB,CAAA;KACF,CAAC;IACF,gBAAgB,EAAE,CAAC,SAAS,SAAS,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,EACxD,MAAM,CAAC,EAAE,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,EACzB,OAAO,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC,EAC5B,OAAO,CAAC,EAAE,OAAO,KACd;QACH,KAAK,EAAE,CACL,QAAQ,EAAG,CAAC,IAAI,EAAE,mBAAmB,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,KAAK,CAAC,GAAG,SAAS,KAAK,GAAG,KAC9E,OAAO,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,CAAC;QACrC,IAAI,EAAE;YACJ,MAAM,CAAC,EAAE,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC;YACzB,OAAO,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC;YAC5B,OAAO,CAAC,EAAE,OAAO;SAClB,CAAA;KACF,CAAA;CACF,CAAA;AAED,MAAM,MAAM,kBAAkB,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,EAAE,CAAC,GAAG,IAAI,IAAI,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG;IAC/F,eAAe,EAAE,MAAM,MAAM,EAAE,CAAC;IAChC,SAAS,CAAC,EAAE,GAAG,CAAC;IAChB,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IACrB,KAAK,CAAC,EAAE,GAAG,CAAC;CACb,CAAA;AAWD,MAAM,MAAM,eAAe,CAAC,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,IAAI;KACjG,GAAG,IAAI,MAAM,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;CAChE,GAAG,WAAW,GAAG;IAChB,GAAG,CAAC,EAAE,UAAU,CAAC;CAClB,CAAC;AAGF,MAAM,MAAM,aAAa,CAAC,MAAM,GAAG,IAAI,IAAI,MAAM,SAAS,QAAQ,GAAG;KAClE,QAAQ,IAAI,MAAM,MAAM,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,SAAS,IAAI,GACpE,iBAAiB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC,GACtD,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CACxD,GAAG,IAAI,CAAC,eAAe,EAAE,KAAK,CAAC,GAChC,eAAe,CAAC;AA6BhB,MAAM,MAAM,IAAI,GAAG;IACjB,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;CACZ,CAAA;AAED,MAAM,MAAM,WAAW,CAAC,QAAQ,GAAG,IAAI,IAAI;IACzC,MAAM,EAAE,GAAG,CAAC;IAEZ;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;IAEtB;;OAEG;IACH,cAAc,CAAC,EAAE,KAAK,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC;IACtC,OAAO,EAAE,CAAC,GAAG,EAAE,aAAa,CAAC,QAAQ,CAAC,EAAE,OAAO,EAAE,aAAa,GAAG,SAAS,EAAE,WAAW,EAAE,aAAa,EAAE,GAAG,SAAS,EAAE,IAAI,EAAE,IAAI,GAAG,SAAS,EAAE,WAAW,EAAE,OAAO,KAAK,GAAG,CAAC;IAE3K;;OAEG;IACH,WAAW,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,EAAE,KAAK,CAAC,EAAE,GAAG,KAAK,GAAG,CAAC;IAChD,YAAY,CAAC,EAAE,CAAC,MAAM,EAAE,GAAG,KAAK,GAAG,CAAC;CACrC,CAAA;AAuBD,MAAM,MAAM,eAAe,GAAG;IAAE,IAAI,EAAE,MAAM,EAAE,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAA;CAAE,CAAA;AAQnE,MAAM,MAAM,QAAQ,GAAG;IACrB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAA;CACpB,CAAA;AASD,wBAAgB,SAAS,CAAC,QAAQ,EAAE,QAAQ,EAAE,WAAW,CAAC,QAAQ,CAAC,EAAE,WAAW,EAAE,GAAG,oBA2uBpF"}
|
package/dist/prostgles.js
CHANGED
|
@@ -42,35 +42,39 @@ function prostgles(initOpts, syncedTable) {
|
|
|
42
42
|
let syncs = {};
|
|
43
43
|
let notifSubs = {};
|
|
44
44
|
const removeNotifListener = (listener, conf) => {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
45
|
+
const channelSubs = notifSubs[conf.notifChannel];
|
|
46
|
+
if (channelSubs) {
|
|
47
|
+
channelSubs.listeners = channelSubs.listeners.filter(nl => nl !== listener);
|
|
48
|
+
if (!channelSubs.listeners.length && channelSubs.config && channelSubs.config.socketUnsubChannel && socket) {
|
|
49
|
+
socket.emit(channelSubs.config.socketUnsubChannel, {});
|
|
49
50
|
delete notifSubs[conf.notifChannel];
|
|
50
51
|
}
|
|
51
52
|
}
|
|
52
53
|
};
|
|
53
54
|
const addNotifListener = (listener, conf) => {
|
|
55
|
+
var _a;
|
|
54
56
|
notifSubs = notifSubs || {};
|
|
55
|
-
|
|
57
|
+
const channelSubs = notifSubs[conf.notifChannel];
|
|
58
|
+
if (!channelSubs) {
|
|
56
59
|
notifSubs[conf.notifChannel] = {
|
|
57
60
|
config: conf,
|
|
58
61
|
listeners: [listener]
|
|
59
62
|
};
|
|
60
63
|
socket.removeAllListeners(conf.socketChannel);
|
|
61
64
|
socket.on(conf.socketChannel, (notif) => {
|
|
62
|
-
|
|
65
|
+
var _a, _b;
|
|
66
|
+
if ((_a = notifSubs[conf.notifChannel]) === null || _a === void 0 ? void 0 : _a.listeners.length) {
|
|
63
67
|
notifSubs[conf.notifChannel].listeners.map(l => {
|
|
64
68
|
l(notif);
|
|
65
69
|
});
|
|
66
70
|
}
|
|
67
71
|
else {
|
|
68
|
-
socket.emit(notifSubs[conf.notifChannel].config.socketUnsubChannel, {});
|
|
72
|
+
socket.emit((_b = notifSubs[conf.notifChannel]) === null || _b === void 0 ? void 0 : _b.config.socketUnsubChannel, {});
|
|
69
73
|
}
|
|
70
74
|
});
|
|
71
75
|
}
|
|
72
76
|
else {
|
|
73
|
-
notifSubs[conf.notifChannel].listeners.push(listener);
|
|
77
|
+
(_a = notifSubs[conf.notifChannel]) === null || _a === void 0 ? void 0 : _a.listeners.push(listener);
|
|
74
78
|
}
|
|
75
79
|
};
|
|
76
80
|
let noticeSubs;
|
|
@@ -218,7 +222,8 @@ function prostgles(initOpts, syncedTable) {
|
|
|
218
222
|
}
|
|
219
223
|
const existingChannel = Object.keys(syncs).find(ch => {
|
|
220
224
|
let s = syncs[ch];
|
|
221
|
-
return (s
|
|
225
|
+
return (s &&
|
|
226
|
+
s.tableName === tableName &&
|
|
222
227
|
s.command === command &&
|
|
223
228
|
JSON.stringify(s.param1 || {}) === JSON.stringify(param1 || {}) &&
|
|
224
229
|
JSON.stringify(s.param2 || {}) === JSON.stringify(param2 || {})
|
|
@@ -348,40 +353,44 @@ function prostgles(initOpts, syncedTable) {
|
|
|
348
353
|
}
|
|
349
354
|
return Object.freeze(res);
|
|
350
355
|
}
|
|
351
|
-
const existing = Object.
|
|
356
|
+
const existing = Object.entries(subscriptions).find(([ch]) => {
|
|
352
357
|
let s = subscriptions[ch];
|
|
353
|
-
return (s
|
|
358
|
+
return (s &&
|
|
359
|
+
s.tableName === tableName &&
|
|
354
360
|
s.command === command &&
|
|
355
361
|
JSON.stringify(s.param1 || {}) === JSON.stringify(param1 || {}) &&
|
|
356
362
|
JSON.stringify(s.param2 || {}) === JSON.stringify(param2 || {}));
|
|
357
363
|
});
|
|
358
364
|
if (existing) {
|
|
359
|
-
|
|
360
|
-
|
|
365
|
+
const existingCh = existing[0];
|
|
366
|
+
existing[1].handlers.push(onChange);
|
|
367
|
+
existing[1].errorHandlers.push(_onError);
|
|
361
368
|
/* Reuse existing sub config */
|
|
362
369
|
// if(subscriptions[existing].handlers.includes(onChange)){
|
|
363
370
|
// console.warn("Duplicate subscription handler was added for:", subscriptions[existing])
|
|
364
371
|
// }
|
|
365
372
|
setTimeout(() => {
|
|
366
|
-
|
|
367
|
-
|
|
373
|
+
var _a, _b;
|
|
374
|
+
if (onChange && ((_a = subscriptions === null || subscriptions === void 0 ? void 0 : subscriptions[existingCh]) === null || _a === void 0 ? void 0 : _a.lastData)) {
|
|
375
|
+
onChange((_b = subscriptions === null || subscriptions === void 0 ? void 0 : subscriptions[existingCh]) === null || _b === void 0 ? void 0 : _b.lastData);
|
|
368
376
|
}
|
|
369
377
|
}, 10);
|
|
370
|
-
return makeHandler(
|
|
378
|
+
return makeHandler(existingCh, existing[1].unsubChannel);
|
|
371
379
|
}
|
|
372
380
|
const { channelName, channelNameReady, channelNameUnsubscribe } = await addServerSub({ tableName, command, param1, param2 });
|
|
373
381
|
const onCall = function (data, cb) {
|
|
374
382
|
/* TO DO: confirm receiving data or server will unsubscribe */
|
|
375
383
|
// if(cb) cb(true);
|
|
376
|
-
|
|
384
|
+
const sub = subscriptions[channelName];
|
|
385
|
+
if (sub) {
|
|
377
386
|
if (data.data) {
|
|
378
|
-
|
|
379
|
-
|
|
387
|
+
sub.lastData = data.data;
|
|
388
|
+
sub.handlers.forEach(h => {
|
|
380
389
|
h(data.data);
|
|
381
390
|
});
|
|
382
391
|
}
|
|
383
392
|
else if (data.err) {
|
|
384
|
-
|
|
393
|
+
sub.errorHandlers.forEach(h => {
|
|
385
394
|
h(data.err);
|
|
386
395
|
});
|
|
387
396
|
}
|
|
@@ -561,7 +570,7 @@ function prostgles(initOpts, syncedTable) {
|
|
|
561
570
|
}
|
|
562
571
|
};
|
|
563
572
|
const sub_commands = ["subscribe", "subscribeOne"];
|
|
564
|
-
|
|
573
|
+
(0, prostgles_types_1.getKeys)(dbo).forEach(tableName => {
|
|
565
574
|
const all_commands = Object.keys(dbo[tableName]);
|
|
566
575
|
all_commands
|
|
567
576
|
.sort((a, b) => sub_commands.includes(a) - sub_commands.includes(b))
|
|
@@ -660,8 +669,9 @@ function prostgles(initOpts, syncedTable) {
|
|
|
660
669
|
});
|
|
661
670
|
}
|
|
662
671
|
if (syncs && Object.keys(syncs).length) {
|
|
663
|
-
|
|
664
|
-
|
|
672
|
+
(0, prostgles_types_1.getKeys)(syncs).filter(ch => {
|
|
673
|
+
var _a;
|
|
674
|
+
return (_a = syncs[ch]) === null || _a === void 0 ? void 0 : _a.triggers.length;
|
|
665
675
|
}).map(async (ch) => {
|
|
666
676
|
try {
|
|
667
677
|
let s = syncs[ch];
|
package/lib/SyncedTable.ts
CHANGED
|
@@ -228,8 +228,8 @@ export class SyncedTable {
|
|
|
228
228
|
if (batch.length) {
|
|
229
229
|
|
|
230
230
|
res = {
|
|
231
|
-
c_fr: this.getRowSyncObj(batch[0]),
|
|
232
|
-
c_lr: this.getRowSyncObj(batch[batch.length - 1]),
|
|
231
|
+
c_fr: this.getRowSyncObj(batch[0]!),
|
|
232
|
+
c_lr: this.getRowSyncObj(batch[batch.length - 1]!),
|
|
233
233
|
c_count: batch.length
|
|
234
234
|
};
|
|
235
235
|
}
|
|
@@ -602,7 +602,7 @@ export class SyncedTable {
|
|
|
602
602
|
this.getItems().map(d => {
|
|
603
603
|
allItems.push({ ...d });
|
|
604
604
|
const dIdx = items.findIndex(_d => this.matchesIdObj(d, _d));
|
|
605
|
-
allDeltas.push(deltas[dIdx]);
|
|
605
|
+
allDeltas.push(deltas[dIdx]!);
|
|
606
606
|
});
|
|
607
607
|
|
|
608
608
|
/* Notify main subscription */
|
|
@@ -737,7 +737,7 @@ export class SyncedTable {
|
|
|
737
737
|
|
|
738
738
|
private get tableHandler(): Pick<TableHandler, "update" | "updateBatch" | "delete"> | undefined {
|
|
739
739
|
const tblHandler = this.db[this.name];
|
|
740
|
-
if(tblHandler
|
|
740
|
+
if(tblHandler?.update && tblHandler.updateBatch){
|
|
741
741
|
return tblHandler as any;
|
|
742
742
|
}
|
|
743
743
|
|
package/lib/prostgles.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
*--------------------------------------------------------------------------------------------*/
|
|
6
6
|
|
|
7
7
|
import {
|
|
8
|
-
TableHandler,
|
|
8
|
+
TableHandler, DbJoinMaker,
|
|
9
9
|
TableJoinBasic, CHANNELS, DBNotifConfig,
|
|
10
10
|
DBNoticeConfig, AnyObject, SubscriptionHandler,
|
|
11
11
|
SQLHandler, DBEventHandles, AuthGuardLocation, DBSchemaTable,
|
|
@@ -16,7 +16,8 @@ import {
|
|
|
16
16
|
FullFilter,
|
|
17
17
|
SubscribeParams,
|
|
18
18
|
OnError,
|
|
19
|
-
GetSelectReturnType
|
|
19
|
+
GetSelectReturnType,
|
|
20
|
+
getKeys
|
|
20
21
|
} from "prostgles-types";
|
|
21
22
|
|
|
22
23
|
import type { DbTableSync, Sync, SyncOne } from "./SyncedTable";
|
|
@@ -38,13 +39,13 @@ export type ViewHandlerClient<T extends AnyObject = AnyObject, S = void> = ViewH
|
|
|
38
39
|
sync?: Sync<T>;
|
|
39
40
|
syncOne?: SyncOne<T>;
|
|
40
41
|
_sync?: any;
|
|
41
|
-
subscribeHook: <SubParams extends SubscribeParams<T>>(
|
|
42
|
+
subscribeHook: <SubParams extends SubscribeParams<T, S>>(
|
|
42
43
|
filter?: FullFilter<T, S>,
|
|
43
44
|
options?: SubParams,
|
|
44
45
|
onError?: OnError
|
|
45
46
|
) => {
|
|
46
47
|
start: ((
|
|
47
|
-
onChange: (items: GetSelectReturnType<SubParams, T, false>[]) => any
|
|
48
|
+
onChange: (items: GetSelectReturnType<S, SubParams, T, false>[]) => any
|
|
48
49
|
) => Promise<SubscriptionHandler<T>>) //ReturnType<ViewHandler<T, S>["subscribe"]>)
|
|
49
50
|
args: [
|
|
50
51
|
filter?: FullFilter<T, S>,
|
|
@@ -52,13 +53,13 @@ export type ViewHandlerClient<T extends AnyObject = AnyObject, S = void> = ViewH
|
|
|
52
53
|
onError?: OnError
|
|
53
54
|
]
|
|
54
55
|
};
|
|
55
|
-
subscribeOneHook: <SubParams extends SubscribeParams<T>>(
|
|
56
|
+
subscribeOneHook: <SubParams extends SubscribeParams<T, S>>(
|
|
56
57
|
filter?: FullFilter<T, S>,
|
|
57
58
|
options?: SubscribeParams<T>,
|
|
58
59
|
onError?: OnError
|
|
59
60
|
) => {
|
|
60
61
|
start: (
|
|
61
|
-
onChange: (item: GetSelectReturnType<SubParams, T, false> | undefined) => any
|
|
62
|
+
onChange: (item: GetSelectReturnType<S, SubParams, T, false> | undefined) => any
|
|
62
63
|
) => Promise<SubscriptionHandler<T>>;
|
|
63
64
|
args: [
|
|
64
65
|
filter?: FullFilter<T, S>,
|
|
@@ -77,14 +78,14 @@ export type TableHandlerClient<T extends AnyObject = AnyObject, S = void> = Tabl
|
|
|
77
78
|
_sync?: any;
|
|
78
79
|
}
|
|
79
80
|
|
|
80
|
-
export type TableHandlerClientBasic = TableHandlerBasic & {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}
|
|
81
|
+
// export type TableHandlerClientBasic = TableHandlerBasic & {
|
|
82
|
+
// getJoinedTables: () => string[];
|
|
83
|
+
// _syncInfo?: any;
|
|
84
|
+
// getSync?: any;
|
|
85
|
+
// sync?: Sync;
|
|
86
|
+
// syncOne?: SyncOne;
|
|
87
|
+
// _sync?: any;
|
|
88
|
+
// }
|
|
88
89
|
|
|
89
90
|
export type DBHandlerClient<Tables extends Record<string, AnyObject> = Record<string, AnyObject>> = {
|
|
90
91
|
[key in keyof Tables]: Partial<TableHandlerClient<Tables[key]>>;
|
|
@@ -109,23 +110,23 @@ const db: DBHandlerClient<{ tbl1: { col1: string; col2: number } }> = 1 as any;
|
|
|
109
110
|
res.col2;
|
|
110
111
|
});
|
|
111
112
|
|
|
112
|
-
export type DBHandlerClientBasic = {
|
|
113
|
-
|
|
114
|
-
} & {
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
} & {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
};
|
|
113
|
+
// export type DBHandlerClientBasic = {
|
|
114
|
+
// [key: string]: Partial<TableHandlerClientBasic>;
|
|
115
|
+
// } & {
|
|
116
|
+
// innerJoin: TableJoinBasic;
|
|
117
|
+
// leftJoin: TableJoinBasic;
|
|
118
|
+
// innerJoinOne: TableJoinBasic;
|
|
119
|
+
// leftJoinOne: TableJoinBasic;
|
|
120
|
+
// } & {
|
|
121
|
+
|
|
122
|
+
// /**
|
|
123
|
+
// *
|
|
124
|
+
// * @param query <string> query. e.g.: SELECT * FROM users;
|
|
125
|
+
// * @param params <any[] | object> query arguments to be escaped. e.g.: { name: 'dwadaw' }
|
|
126
|
+
// * @param options <object> { returnType: "statement" | "rows" | "noticeSubscription" }
|
|
127
|
+
// */
|
|
128
|
+
// sql?: SQLHandler;
|
|
129
|
+
// };
|
|
129
130
|
|
|
130
131
|
export type Auth = {
|
|
131
132
|
register?: (params: any) => Promise<any>;
|
|
@@ -226,10 +227,11 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
226
227
|
}
|
|
227
228
|
} = {};
|
|
228
229
|
const removeNotifListener = (listener: any, conf: DBNotifConfig) => {
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
230
|
+
const channelSubs = notifSubs[conf.notifChannel]
|
|
231
|
+
if (channelSubs) {
|
|
232
|
+
channelSubs.listeners = channelSubs.listeners.filter(nl => nl !== listener);
|
|
233
|
+
if (!channelSubs.listeners.length && channelSubs.config && channelSubs.config.socketUnsubChannel && socket) {
|
|
234
|
+
socket.emit(channelSubs.config.socketUnsubChannel, {});
|
|
233
235
|
delete notifSubs[conf.notifChannel];
|
|
234
236
|
}
|
|
235
237
|
}
|
|
@@ -237,24 +239,25 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
237
239
|
const addNotifListener = (listener: any, conf: DBNotifConfig) => {
|
|
238
240
|
notifSubs = notifSubs || {};
|
|
239
241
|
|
|
240
|
-
|
|
242
|
+
const channelSubs = notifSubs[conf.notifChannel]
|
|
243
|
+
if (!channelSubs) {
|
|
241
244
|
notifSubs[conf.notifChannel] = {
|
|
242
245
|
config: conf,
|
|
243
246
|
listeners: [listener]
|
|
244
247
|
};
|
|
245
248
|
socket.removeAllListeners(conf.socketChannel);
|
|
246
249
|
socket.on(conf.socketChannel, (notif: any) => {
|
|
247
|
-
if (notifSubs[conf.notifChannel]
|
|
248
|
-
notifSubs[conf.notifChannel]
|
|
250
|
+
if (notifSubs[conf.notifChannel]?.listeners.length) {
|
|
251
|
+
notifSubs[conf.notifChannel]!.listeners.map(l => {
|
|
249
252
|
l(notif);
|
|
250
253
|
})
|
|
251
254
|
} else {
|
|
252
|
-
socket.emit(notifSubs[conf.notifChannel]
|
|
255
|
+
socket.emit(notifSubs[conf.notifChannel]?.config.socketUnsubChannel, {});
|
|
253
256
|
}
|
|
254
257
|
});
|
|
255
258
|
|
|
256
259
|
} else {
|
|
257
|
-
notifSubs[conf.notifChannel]
|
|
260
|
+
notifSubs[conf.notifChannel]?.listeners.push(listener);
|
|
258
261
|
}
|
|
259
262
|
};
|
|
260
263
|
|
|
@@ -310,14 +313,14 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
310
313
|
|
|
311
314
|
return new Promise((resolve, reject) => {
|
|
312
315
|
if (subscriptions[channelName]) {
|
|
313
|
-
subscriptions[channelName]
|
|
314
|
-
if (!subscriptions[channelName]
|
|
316
|
+
subscriptions[channelName]!.handlers = subscriptions[channelName]!.handlers.filter(h => h !== handler);
|
|
317
|
+
if (!subscriptions[channelName]!.handlers.length) {
|
|
315
318
|
socket.emit(unsubChannel, {}, (err: any, _res: any) => {
|
|
316
319
|
// console.log("unsubscribed", err, res);
|
|
317
320
|
if (err) console.error(err);
|
|
318
321
|
// else resolve(res);
|
|
319
322
|
});
|
|
320
|
-
socket.removeListener(channelName, subscriptions[channelName]
|
|
323
|
+
socket.removeListener(channelName, subscriptions[channelName]!.onCall);
|
|
321
324
|
delete subscriptions[channelName];
|
|
322
325
|
|
|
323
326
|
/* Not waiting for server confirmation to speed things up */
|
|
@@ -335,18 +338,18 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
335
338
|
debug("_unsync", { channelName, triggers })
|
|
336
339
|
return new Promise((resolve, reject) => {
|
|
337
340
|
if (syncs[channelName]) {
|
|
338
|
-
syncs[channelName]
|
|
341
|
+
syncs[channelName]!.triggers = syncs[channelName]!.triggers.filter(tr => (
|
|
339
342
|
tr.onPullRequest !== triggers.onPullRequest &&
|
|
340
343
|
tr.onSyncRequest !== triggers.onSyncRequest &&
|
|
341
344
|
tr.onUpdates !== triggers.onUpdates
|
|
342
345
|
));
|
|
343
346
|
|
|
344
|
-
if (!syncs[channelName]
|
|
347
|
+
if (!syncs[channelName]!.triggers.length) {
|
|
345
348
|
socket.emit(channelName + "unsync", {}, (err: any, res: any) => {
|
|
346
349
|
if (err) reject(err);
|
|
347
350
|
else resolve(res);
|
|
348
351
|
});
|
|
349
|
-
socket.removeListener(channelName, syncs[channelName]
|
|
352
|
+
socket.removeListener(channelName, syncs[channelName]!.onCall);
|
|
350
353
|
delete syncs[channelName];
|
|
351
354
|
}
|
|
352
355
|
}
|
|
@@ -418,6 +421,7 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
418
421
|
const existingChannel = Object.keys(syncs).find(ch => {
|
|
419
422
|
let s = syncs[ch];
|
|
420
423
|
return (
|
|
424
|
+
s &&
|
|
421
425
|
s.tableName === tableName &&
|
|
422
426
|
s.command === command &&
|
|
423
427
|
JSON.stringify(s.param1 || {}) === JSON.stringify(param1 || {}) &&
|
|
@@ -431,7 +435,7 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
431
435
|
});
|
|
432
436
|
|
|
433
437
|
if (existingChannel) {
|
|
434
|
-
syncs[existingChannel]
|
|
438
|
+
syncs[existingChannel]!.triggers.push(triggers);
|
|
435
439
|
return makeHandler(existingChannel);
|
|
436
440
|
} else {
|
|
437
441
|
const sync_info = await addServerSync({ tableName, command, param1, param2 }, onSyncRequest);
|
|
@@ -448,7 +452,7 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
448
452
|
|
|
449
453
|
if (!syncs[channelName]) return;
|
|
450
454
|
|
|
451
|
-
syncs[channelName]
|
|
455
|
+
syncs[channelName]!.triggers.map(({ onUpdates, onSyncRequest, onPullRequest }) => {
|
|
452
456
|
// onChange(data.data);
|
|
453
457
|
if (data.data) {
|
|
454
458
|
Promise.resolve(onUpdates(data))
|
|
@@ -552,9 +556,10 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
552
556
|
return Object.freeze(res);
|
|
553
557
|
}
|
|
554
558
|
|
|
555
|
-
const existing = Object.
|
|
559
|
+
const existing = Object.entries(subscriptions).find(([ch]) => {
|
|
556
560
|
let s = subscriptions[ch];
|
|
557
561
|
return (
|
|
562
|
+
s &&
|
|
558
563
|
s.tableName === tableName &&
|
|
559
564
|
s.command === command &&
|
|
560
565
|
JSON.stringify(s.param1 || {}) === JSON.stringify(param1 || {}) &&
|
|
@@ -563,18 +568,19 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
563
568
|
});
|
|
564
569
|
|
|
565
570
|
if (existing) {
|
|
566
|
-
|
|
567
|
-
|
|
571
|
+
const existingCh = existing[0];
|
|
572
|
+
existing[1].handlers.push(onChange);
|
|
573
|
+
existing[1].errorHandlers.push(_onError);
|
|
568
574
|
/* Reuse existing sub config */
|
|
569
575
|
// if(subscriptions[existing].handlers.includes(onChange)){
|
|
570
576
|
// console.warn("Duplicate subscription handler was added for:", subscriptions[existing])
|
|
571
577
|
// }
|
|
572
578
|
setTimeout(() => {
|
|
573
|
-
if (onChange && subscriptions?.[
|
|
574
|
-
onChange(subscriptions?.[
|
|
579
|
+
if (onChange && subscriptions?.[existingCh]?.lastData) {
|
|
580
|
+
onChange(subscriptions?.[existingCh]?.lastData)
|
|
575
581
|
}
|
|
576
582
|
}, 10)
|
|
577
|
-
return makeHandler(
|
|
583
|
+
return makeHandler(existingCh, existing[1].unsubChannel);
|
|
578
584
|
}
|
|
579
585
|
|
|
580
586
|
const { channelName, channelNameReady, channelNameUnsubscribe } = await addServerSub({ tableName, command, param1, param2 })
|
|
@@ -582,14 +588,15 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
582
588
|
const onCall = function (data: any, cb: Function) {
|
|
583
589
|
/* TO DO: confirm receiving data or server will unsubscribe */
|
|
584
590
|
// if(cb) cb(true);
|
|
585
|
-
|
|
591
|
+
const sub = subscriptions[channelName];
|
|
592
|
+
if (sub) {
|
|
586
593
|
if (data.data) {
|
|
587
|
-
|
|
588
|
-
|
|
594
|
+
sub.lastData = data.data;
|
|
595
|
+
sub.handlers.forEach(h => {
|
|
589
596
|
h(data.data);
|
|
590
597
|
});
|
|
591
598
|
} else if (data.err) {
|
|
592
|
-
|
|
599
|
+
sub.errorHandlers.forEach(h => {
|
|
593
600
|
h(data.err);
|
|
594
601
|
});
|
|
595
602
|
} else {
|
|
@@ -614,7 +621,7 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
614
621
|
errorHandlers: [onError],
|
|
615
622
|
destroy: () => {
|
|
616
623
|
if (subscriptions[channelName]) {
|
|
617
|
-
Object.values(subscriptions[channelName]).map((s: Subscription) => {
|
|
624
|
+
Object.values(subscriptions[channelName]!).map((s: Subscription) => {
|
|
618
625
|
if (s && s.handlers) s.handlers.map(h => _unsubscribe(channelName, channelNameUnsubscribe, h))
|
|
619
626
|
});
|
|
620
627
|
delete subscriptions[channelName];
|
|
@@ -780,9 +787,9 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
780
787
|
}
|
|
781
788
|
}
|
|
782
789
|
const sub_commands = ["subscribe", "subscribeOne"] as const;
|
|
783
|
-
|
|
790
|
+
getKeys(dbo).forEach(tableName => {
|
|
784
791
|
const all_commands = Object.keys(dbo[tableName]);
|
|
785
|
-
|
|
792
|
+
|
|
786
793
|
all_commands
|
|
787
794
|
.sort((a, b) => <never>sub_commands.includes(a as any) - <never>sub_commands.includes(b as any))
|
|
788
795
|
.forEach(command => {
|
|
@@ -875,7 +882,7 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
875
882
|
if (subscriptions && Object.keys(subscriptions).length) {
|
|
876
883
|
Object.keys(subscriptions).map(async ch => {
|
|
877
884
|
try {
|
|
878
|
-
let s = subscriptions[ch]
|
|
885
|
+
let s = subscriptions[ch]!;
|
|
879
886
|
await addServerSub(s);
|
|
880
887
|
socket.on(ch, s.onCall);
|
|
881
888
|
} catch (err) {
|
|
@@ -884,12 +891,12 @@ export function prostgles<DBSchema>(initOpts: InitOptions<DBSchema>, syncedTable
|
|
|
884
891
|
});
|
|
885
892
|
}
|
|
886
893
|
if (syncs && Object.keys(syncs).length) {
|
|
887
|
-
|
|
888
|
-
return syncs[ch]
|
|
894
|
+
getKeys(syncs).filter(ch => {
|
|
895
|
+
return syncs[ch]?.triggers.length
|
|
889
896
|
}).map(async ch => {
|
|
890
897
|
try {
|
|
891
|
-
let s = syncs[ch]
|
|
892
|
-
await addServerSync(s, s.triggers[0]
|
|
898
|
+
let s = syncs[ch]!;
|
|
899
|
+
await addServerSync(s, s.triggers[0]!.onSyncRequest);
|
|
893
900
|
socket.on(ch, s.onCall);
|
|
894
901
|
} catch (err) {
|
|
895
902
|
console.error("There was an issue reconnecting olf subscriptions", err)
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "prostgles-client",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.7",
|
|
4
4
|
"description": "Reactive client for Postgres",
|
|
5
5
|
"main": "dist/prostgles-full.js",
|
|
6
6
|
"types": "dist/prostgles-full.d.ts",
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"prostgles-types": "^4.0.
|
|
8
|
+
"prostgles-types": "^4.0.9"
|
|
9
9
|
},
|
|
10
10
|
"devDependencies": {
|
|
11
11
|
"@types/node": "^14.14.14",
|
package/tsconfig.json
CHANGED