UNPKG

tinybase

Version:

A reactive data store and sync engine.

2 lines (1 loc) 2.87 kB
const a=a=>typeof a,t="",e=a(t),s="t",n=(a,t)=>a.startsWith(t),i=Promise,r=a=>null==a,c=(a,t,e)=>r(a)?e?.():t(a),o=(a,t,e)=>a.slice(t,e),l=a=>a.length,w=async a=>i.all(a),y=(a,t)=>a.map(t),g=(a,...t)=>a.push(...t),h=Object,f=h.entries,u=(a=[])=>h.fromEntries(a),p=(a,t)=>y(f(a),(([a,e])=>t(e,a))),S=(a,t,e)=>(((a,t)=>t in a)(a,t)||(a[t]=e()),a[t]),d=JSON.stringify,P=JSON.parse,m=a=>d(a,((a,t)=>t instanceof Map?h.fromEntries([...t]):t)),x=(a,t)=>((a,t)=>a?.forEach(t))(a,((a,e)=>t(e,a))),D="/store",R=(t,s,n)=>t+s+(a(n)==e?n:m(n)),b=(a,t,e)=>{const s=l(a);return n(t,a)?[t[s],(e?P:String)(o(t,s+1))]:void 0},C="hasStore",T=u(y(["Origin","Methods","Headers"],(a=>["Access-Control-Allow-"+a,"*"]))),v=async(a,e=t)=>!!await a.get(e+C),O=async(a,e=t)=>{const n={},i={};return x(await a.list(),((a,t)=>c(b(e,a),(([a,e])=>{if(a==s){const[a,s,i]=P("["+e+"]");S(S(n,a,u),s,u)[i]=t}else"v"==a&&(i[e]=t)})))),[n,i]},V=async(a,e,s)=>a.party.broadcast(R(a.config.messagePrefix??t,"s",e),s),E=async(a,e,i,c)=>{const o=a.party.storage,y=a.config.storagePrefix??t,h={[y+C]:1},f=[],u=[];await w(p(e[0],(async(t,e)=>r(t)?!i&&await a.canDelTable(e,c)&&((a,...t)=>a.unshift(...t))(u,H(y,s,e)):await a.canSetTable(e,i,c)&&await w(p(t,(async(t,n)=>r(t)?!i&&await a.canDelRow(e,n,c)&&g(u,H(y,s,e,n)):await a.canSetRow(e,n,i,c)&&await w(p(t,(async(t,l)=>{const w=[e,n,l],u=H(y,s,...w);r(t)?!i&&await a.canDelCell(...w,c)&&g(f,u):await a.canSetCell(...w,t,i,c,await o.get(u))&&(h[u]=t)}))))))))),await w(p(e[1],(async(t,e)=>{const s=y+"v"+e;r(t)?!i&&await a.canDelValue(e,c)&&g(f,s):await a.canSetValue(e,t,i,c,await o.get(s))&&(h[s]=t)}))),0!=l(u)&&x(await o.list(),(a=>u.every((t=>!n(a,t)||g(f,a)&&0)))),await o.delete(f),await o.put(h)},H=(a,t,...e)=>R(a,t,o(m(e),1,-1)),M=async(a,t,e=null)=>new Response(e,{status:t,headers:a.config.responseHeaders});class A{constructor(a){this.party=a,this.config.storePath??=D,this.config.messagePrefix??=t,this.config.storagePrefix??=t,this.config.responseHeaders??=T}config={};async onRequest(a){const{party:{storage:e},config:{storePath:s=D,storagePrefix:n}}=this;if(new URL(a.url).pathname.endsWith(s)){const s=await v(e,n),i=await a.text();return"PUT"==a.method?s?M(this,205):(await E(this,P(i),!0,a),M(this,201)):M(this,200,s?m(await O(e,n)):t)}return M(this,404)}async onMessage(a,e){const{config:{messagePrefix:s=t,storagePrefix:n}}=this;await c(b(s,a,1),(async([a,t])=>{"s"==a&&await v(this.party.storage,n)&&(await E(this,t,!1,e),V(this,t,[e.id]))}))}async canSetTable(a,t,e){return!0}async canDelTable(a,t){return!0}async canSetRow(a,t,e,s){return!0}async canDelRow(a,t,e){return!0}async canSetCell(a,t,e,s,n,i,r){return!0}async canDelCell(a,t,e,s){return!0}async canSetValue(a,t,e,s,n){return!0}async canDelValue(a,t){return!0}}export{A as TinyBasePartyKitServer,V as broadcastChanges,v as hasStoreInStorage,O as loadStoreFromStorage};