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