palbase 0.51.0 → 0.51.1

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.
Files changed (47) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +3 -3
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{EDNVQ4JL.js → 4PPFSLQW.js} +2 -2
  8. package/dist/chunks/{VTDNYFKI.js → 6TFDOHT4.js} +2 -2
  9. package/dist/chunks/{262XXIZR.js → 77KKSGFT.js} +2 -2
  10. package/dist/chunks/{4N4YEPF7.js → 7XJCDA36.js} +2 -2
  11. package/dist/chunks/{KPHXI5Y7.js → A2WD3XRQ.js} +1 -1
  12. package/dist/chunks/{IKEE4LBO.js → A5CZXTHL.js} +1 -1
  13. package/dist/chunks/{7R5VYTBT.js → BS2ZZBET.js} +2 -2
  14. package/dist/chunks/{O46W6X6E.js → CVW45VKU.js} +1 -1
  15. package/dist/chunks/{JHWPYG5N.js → DOFSL7OH.js} +1 -1
  16. package/dist/chunks/{6MMMVWDY.js → ED2JZRMF.js} +2 -2
  17. package/dist/chunks/{IHI5K54A.js → EQSGX2P5.js} +3 -3
  18. package/dist/chunks/{ATWAZAG2.js → F6NKEFR2.js} +1 -1
  19. package/dist/chunks/{XRG6B3N6.js → FXNLGZVC.js} +2 -2
  20. package/dist/chunks/{JV5WBRF6.js → I2G437SJ.js} +2 -2
  21. package/dist/chunks/{JDVUUCZ6.js → IGOLB5KI.js} +2 -2
  22. package/dist/chunks/{SM4ZINGC.js → K54TOCRX.js} +1 -1
  23. package/dist/chunks/{OTVQ3EBH.js → MA5G227L.js} +2 -2
  24. package/dist/chunks/NAQ2ZLAT.js +13 -0
  25. package/dist/chunks/{NY2ZPGNN.js → NBDKEIXP.js} +2 -2
  26. package/dist/chunks/{K6R5SBI5.js → OLNQWW5N.js} +2 -2
  27. package/dist/chunks/{YHAR4WUH.js → PPGCDKAN.js} +2 -2
  28. package/dist/chunks/{6JSKJTLV.js → RJ3QR6BS.js} +1 -1
  29. package/dist/chunks/{5JTHF6QW.js → XZJHF3OE.js} +2 -2
  30. package/dist/cli.js +2 -2
  31. package/dist/cloud/index.js +2 -2
  32. package/dist/refuse/ai.js +1 -1
  33. package/dist/refuse/backend.js +1 -1
  34. package/dist/refuse/cloud.js +1 -1
  35. package/dist/refuse/server.js +1 -1
  36. package/dist/server/index.js +2 -2
  37. package/dist/server/testing.js +2 -2
  38. package/dist/web/index.js +2 -2
  39. package/dist/web/message.js +2 -2
  40. package/dist/web/palbe.js +2 -2
  41. package/dist/web/paywall.js +2 -2
  42. package/dist/web/push-sw.js +1 -1
  43. package/dist/web/ssr.js +2 -2
  44. package/dist/web/vite.js +2 -2
  45. package/package.json +2 -2
  46. package/types/web/src/socket.d.ts +5 -0
  47. package/dist/chunks/QN55ZKNQ.js +0 -13
package/dist/refuse/ai.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
2
  throw new Error("palbase/ai is for servers: it speaks with the project secret key, which never goes into a browser or a mobile app \u2014 call your backend, and let it ask the model");
@@ -1,2 +1,2 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
2
  throw new Error("palbase/backend is a server framework: it runs on your backend, never in a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs)");
@@ -1,2 +1,2 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
2
  throw new Error("palbase/cloud is for servers: its access token opens the organization's projects, so it belongs on your server and never in a browser or a mobile app \u2014 have your app call your server");
@@ -1,2 +1,2 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
2
  throw new Error("palbase/server is for servers: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");
@@ -1,2 +1,2 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
2
- import{a as e,b as f,c as g,d as h,e as i,f as j,g as k,h as l,i as m,j as n,k as o,l as p,m as q,n as r,o as s,p as t,q as u,r as v,s as w,t as x,u as y}from"../chunks/EDNVQ4JL.js";import{a as c,b as d}from"../chunks/KPHXI5Y7.js";import"../chunks/ATWAZAG2.js";import"../chunks/O46W6X6E.js";import{p as b}from"../chunks/262XXIZR.js";import"../chunks/K6R5SBI5.js";import{b as a}from"../chunks/OTVQ3EBH.js";import"../chunks/JHWPYG5N.js";import"../chunks/IKEE4LBO.js";export{o as AuthUnavailable,b as EVENT_TYPES,c as FieldError,d as Fields,a as PalbaseError,t as ReservationSettled,n as TokenError,q as TokenVerifier,f as Transit,e as TransitRefusal,g as TransitRequest,i as WebhookSignatureError,h as createServer,s as isEntitled,y as loadSecrets,v as pages,x as platformOwn,w as processOwn,r as requestAddress,p as sessionStanding,l as signatureHeader,k as verifySignature,j as verifyWebhook,m as verifyWebhookRequest,u as withReservation};
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as e,b as f,c as g,d as h,e as i,f as j,g as k,h as l,i as m,j as n,k as o,l as p,m as q,n as r,o as s,p as t,q as u,r as v,s as w,t as x,u as y}from"../chunks/4PPFSLQW.js";import{a as c,b as d}from"../chunks/A2WD3XRQ.js";import"../chunks/F6NKEFR2.js";import"../chunks/CVW45VKU.js";import{p as b}from"../chunks/77KKSGFT.js";import"../chunks/OLNQWW5N.js";import{b as a}from"../chunks/MA5G227L.js";import"../chunks/DOFSL7OH.js";import"../chunks/A5CZXTHL.js";export{o as AuthUnavailable,b as EVENT_TYPES,c as FieldError,d as Fields,a as PalbaseError,t as ReservationSettled,n as TokenError,q as TokenVerifier,f as Transit,e as TransitRefusal,g as TransitRequest,i as WebhookSignatureError,h as createServer,s as isEntitled,y as loadSecrets,v as pages,x as platformOwn,w as processOwn,r as requestAddress,p as sessionStanding,l as signatureHeader,k as verifySignature,j as verifyWebhook,m as verifyWebhookRequest,u as withReservation};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
2
- import{a,b,c,d,e}from"../chunks/JV5WBRF6.js";import"../chunks/KPHXI5Y7.js";import"../chunks/JHWPYG5N.js";import"../chunks/IKEE4LBO.js";export{b as TestApiError,e as api,c as createTestApi,a as testFields,d as testRun};
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
+ import{a,b,c,d,e}from"../chunks/I2G437SJ.js";import"../chunks/A2WD3XRQ.js";import"../chunks/DOFSL7OH.js";import"../chunks/A5CZXTHL.js";export{b as TestApiError,e as api,c as createTestApi,a as testFields,d as testRun};
package/dist/web/index.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
2
- import{A as de,B as ye,a as I,b as j,c as q,d as G,e as D,f as H,g as N,h as U,i as B,j as F,k as J,l as K,m as W,n as X,o as Y,p as Z,q as ee,r as te,s as ne,t as re,u as oe,v as se,w as ae,x as ie,y as ce,z as pe}from"../chunks/IHI5K54A.js";import{a as _,b as Q,f as z}from"../chunks/QN55ZKNQ.js";import"../chunks/NY2ZPGNN.js";import"../chunks/YHAR4WUH.js";import"../chunks/4N4YEPF7.js";import"../chunks/6JSKJTLV.js";import{b as k,c as O,d as T,f as x,g as R,j as A,k as V,l as M,m as E,o as P}from"../chunks/ATWAZAG2.js";import"../chunks/262XXIZR.js";import"../chunks/K6R5SBI5.js";import{b as L}from"../chunks/OTVQ3EBH.js";import"../chunks/JHWPYG5N.js";import"../chunks/IKEE4LBO.js";var le="oai-events";async function ue(e){if(typeof e?.start!="function")throw new TypeError("connectVoice: start(sdp) is the round trip to the app's backend, which starts the voice (chats.voice.start) and answers { id, sdp }");let r=e.rtc??he(),t=e.signal;t?.throwIfAborted();let l=e.audio??ge(),f=e.microphone===void 0,c=e.microphone??await r.getUserMedia({audio:!0});if(t?.aborted){if(f)for(let n of c.getTracks())n.stop();throw t.reason}let o=new r.RTCPeerConnection,s=!1,u=()=>{if(!s){if(s=!0,m.close(),o.close(),f)for(let n of c.getTracks())n.stop();l.srcObject!==null&&(l.srcObject=null)}};o.addEventListener("track",n=>{l.srcObject=n.streams[0]??new MediaStream([n.track]),l.play?.()?.catch?.(()=>{})}),o.addEventListener("connectionstatechange",()=>e.onState?.(o.connectionState));for(let n of c.getAudioTracks())o.addTrack(n,c);let m=o.createDataChannel(le);m.addEventListener("message",n=>{let d=me(n.data);d!==void 0&&e.onError?.(d)});let p=()=>u();t?.addEventListener("abort",p,{once:!0});try{await o.setLocalDescription(await o.createOffer()),t?.throwIfAborted(),await fe(o,e.iceTimeoutMs??1e4,t);let n=o.localDescription?.sdp;if(!n)throw new Error("connectVoice: the peer connection made no offer");let d=await e.start(n);if(t?.throwIfAborted(),typeof d?.id!="string"||d.id===""||typeof d.sdp!="string"||d.sdp==="")throw new TypeError("connectVoice: start answered no voice \u2014 it is { id, sdp }, chats.voice.start's answer as the backend got it");return await o.setRemoteDescription({type:"answer",sdp:d.sdp}),t?.removeEventListener("abort",p),{id:d.id,peer:o,audio:l,microphone:c,get muted(){return c.getAudioTracks().every(h=>!h.enabled)},mute(h){for(let w of c.getAudioTracks())w.enabled=!h},close:u}}catch(n){throw t?.removeEventListener("abort",p),u(),t?.aborted?t.reason:n}}function fe(e,r,t){return e.iceGatheringState==="complete"?Promise.resolve():t?.aborted?Promise.reject(t.reason):new Promise((l,f)=>{let c=()=>{clearTimeout(u),e.removeEventListener("icegatheringstatechange",o),t?.removeEventListener("abort",s)},o=()=>{e.iceGatheringState==="complete"&&(c(),l())},s=()=>{c(),f(t?.reason)},u=setTimeout(()=>{c(),f(new Error(`connectVoice: the network candidates were not gathered in ${r} ms`))},r);e.addEventListener("icegatheringstatechange",o),t?.addEventListener("abort",s,{once:!0})})}function me(e){if(typeof e=="string")try{let r=JSON.parse(e);return r.type!=="error"?void 0:typeof r.error?.message=="string"?r.error.message:typeof r.error?.code=="string"?r.error.code:"the voice failed"}catch{return}}function he(){let e=globalThis;if(typeof e.RTCPeerConnection!="function"||typeof e.navigator?.mediaDevices?.getUserMedia!="function")throw new TypeError("connectVoice: this runtime has no WebRTC (RTCPeerConnection, navigator.mediaDevices): a chat's voice is a browser's");let r=e.navigator.mediaDevices;return{RTCPeerConnection:e.RTCPeerConnection,getUserMedia:t=>r.getUserMedia(t)}}function ge(){let e=globalThis.document;if(!e)throw new TypeError("connectVoice: give audio \u2014 the element the voice plays in \u2014 where there is no document");let r=e.createElement("audio");return r.autoplay=!0,r}var i=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0;function we(e,r,t){let l=i(i(i(e)?.components)?.schemas)??{},f=(p,n)=>{let d=new Set,h=(b,g,y)=>{let a=i(b);if(!a)return;if(typeof a.$ref=="string"){if(y.has(a.$ref)||!a.$ref.startsWith("#/components/schemas/"))return;h(l[a.$ref.slice(21)],g,new Set(y).add(a.$ref));return}if(a[k]===!0){d.add(g);return}for(let C of["anyOf","oneOf","allOf"]){let S=a[C];if(Array.isArray(S))for(let $ of S)h($,g,y)}let v=i(a.properties);if(v)for(let[C,S]of Object.entries(v))h(S,`${g}/${E(C)}`,y);i(a.items)&&h(a.items,`${g}/*`,y);for(let C of["additionalProperties","patternProperties","prefixItems"])if(a[C]!==void 0&&w(a[C],new Set(y)))throw new Error(`${t}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},w=(b,g)=>{if(Array.isArray(b))return b.some(a=>w(a,g));let y=i(b);return y?y[k]===!0?!0:typeof y.$ref=="string"&&!g.has(y.$ref)&&y.$ref.startsWith("#/components/schemas/")?(g.add(y.$ref),w(l[y.$ref.slice(21)],g)):Object.values(y).some(a=>typeof a=="object"&&a!==null&&w(a,g)):!1};return h(p,n,new Set),[...d]},c=p=>i(i(i(p)?.["application/json"])?.schema),o=[];o.push(...f(c(i(r.requestBody)?.content),"/body"));for(let p of Array.isArray(r.parameters)?r.parameters:[]){let n=i(p);if(!n)continue;let d=f(n.schema,`/query/${E(String(n.name))}`);if(d.length!==0){if(n.in!=="query")throw new Error(`${t}: ${String(n.in)} parameter ${String(n.name)} is marked encrypted \u2014 a body's or a query's field is`);if(d.some(h=>h.split("/").length!==3))throw new Error(`${t}: an encrypted query field is one of the query's own names`);o.push(...d)}}let s=i(r.responses)??{},u=Object.keys(s).filter(p=>/^2\d\d$/.test(p)).sort((p,n)=>p==="200"?-1:n==="200"?1:p.localeCompare(n)),m=u.length>0?f(c(i(s[u[0]])?.content),"/response"):[];if(o.length+m.length!==0){if(r["x-palbase-sse"]!==void 0&&m.length>0)throw new Error(`${t}: a streamed answer carries no encrypted field`);if(r["x-palbase-upload"]!==void 0)throw new Error(`${t}: an upload goes through storage, which seals nothing \u2014 it carries no encrypted field`);return{request:o,response:m}}}async function Ce(e){let r=`${e.method.toUpperCase()} ${e.path}`,t=i(i(i(i(e.contract)?.paths)?.[e.path])?.[e.method.toLowerCase()]),l=t?we(e.contract,t,r):void 0;if(!l)return{body:e.body,query:e.query,open:async s=>s};let{key:f,header:c}=await R(e.key.kid,T(e.key.publicKey),x(e.projectId,e.method,e.path,e.params??[])),o=(s,u)=>s==null?s:P(s,u,l.request,(m,p)=>A(f,m,p));return{header:c,body:await o(e.body,"/body"),query:await o(e.query,"/query"),open:s=>s===void 0?Promise.resolve(s):P(s,"/response",l.response,async(u,m)=>{if(!V(m))throw new O("unopenable",`${r}: ${u} came plain where the contract says it is encrypted`);return M(f,u,m)})}}export{N as Analytics,_ as BackendError,de as CallPlace,ce as CallSession,pe as Calls,G as Channel,U as Consent,ne as ConversationList,oe as ConversationView,re as DeletedGroupList,Z as Flags,z as GatewayError,J as InApp,B as Inbox,H as Installation,te as Messaging,W as Notify,L as PalbaseError,ie as PlaceBusyError,X as Purchases,D as RealtimeSocket,F as SESSION_START,ae as ScheduledList,I as SessionChangedError,se as ThreadView,K as WebPush,ue as connectVoice,ye as createClient,Ce as encryptedCall,ee as indexedDBKeyValue,Q as isBackendError,q as localStore,j as memoryStore,Y as redemptionToken};
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
+ import{A as de,B as ye,a as I,b as j,c as q,d as G,e as D,f as H,g as N,h as U,i as B,j as F,k as J,l as K,m as W,n as X,o as Y,p as Z,q as ee,r as te,s as ne,t as re,u as oe,v as se,w as ae,x as ie,y as ce,z as pe}from"../chunks/EQSGX2P5.js";import{a as _,b as Q,f as z}from"../chunks/NAQ2ZLAT.js";import"../chunks/NBDKEIXP.js";import"../chunks/PPGCDKAN.js";import"../chunks/7XJCDA36.js";import"../chunks/RJ3QR6BS.js";import{b as k,c as O,d as T,f as x,g as R,j as A,k as V,l as M,m as E,o as P}from"../chunks/F6NKEFR2.js";import"../chunks/77KKSGFT.js";import"../chunks/OLNQWW5N.js";import{b as L}from"../chunks/MA5G227L.js";import"../chunks/DOFSL7OH.js";import"../chunks/A5CZXTHL.js";var le="oai-events";async function ue(e){if(typeof e?.start!="function")throw new TypeError("connectVoice: start(sdp) is the round trip to the app's backend, which starts the voice (chats.voice.start) and answers { id, sdp }");let r=e.rtc??he(),t=e.signal;t?.throwIfAborted();let l=e.audio??ge(),f=e.microphone===void 0,c=e.microphone??await r.getUserMedia({audio:!0});if(t?.aborted){if(f)for(let n of c.getTracks())n.stop();throw t.reason}let o=new r.RTCPeerConnection,s=!1,u=()=>{if(!s){if(s=!0,m.close(),o.close(),f)for(let n of c.getTracks())n.stop();l.srcObject!==null&&(l.srcObject=null)}};o.addEventListener("track",n=>{l.srcObject=n.streams[0]??new MediaStream([n.track]),l.play?.()?.catch?.(()=>{})}),o.addEventListener("connectionstatechange",()=>e.onState?.(o.connectionState));for(let n of c.getAudioTracks())o.addTrack(n,c);let m=o.createDataChannel(le);m.addEventListener("message",n=>{let d=me(n.data);d!==void 0&&e.onError?.(d)});let p=()=>u();t?.addEventListener("abort",p,{once:!0});try{await o.setLocalDescription(await o.createOffer()),t?.throwIfAborted(),await fe(o,e.iceTimeoutMs??1e4,t);let n=o.localDescription?.sdp;if(!n)throw new Error("connectVoice: the peer connection made no offer");let d=await e.start(n);if(t?.throwIfAborted(),typeof d?.id!="string"||d.id===""||typeof d.sdp!="string"||d.sdp==="")throw new TypeError("connectVoice: start answered no voice \u2014 it is { id, sdp }, chats.voice.start's answer as the backend got it");return await o.setRemoteDescription({type:"answer",sdp:d.sdp}),t?.removeEventListener("abort",p),{id:d.id,peer:o,audio:l,microphone:c,get muted(){return c.getAudioTracks().every(h=>!h.enabled)},mute(h){for(let w of c.getAudioTracks())w.enabled=!h},close:u}}catch(n){throw t?.removeEventListener("abort",p),u(),t?.aborted?t.reason:n}}function fe(e,r,t){return e.iceGatheringState==="complete"?Promise.resolve():t?.aborted?Promise.reject(t.reason):new Promise((l,f)=>{let c=()=>{clearTimeout(u),e.removeEventListener("icegatheringstatechange",o),t?.removeEventListener("abort",s)},o=()=>{e.iceGatheringState==="complete"&&(c(),l())},s=()=>{c(),f(t?.reason)},u=setTimeout(()=>{c(),f(new Error(`connectVoice: the network candidates were not gathered in ${r} ms`))},r);e.addEventListener("icegatheringstatechange",o),t?.addEventListener("abort",s,{once:!0})})}function me(e){if(typeof e=="string")try{let r=JSON.parse(e);return r.type!=="error"?void 0:typeof r.error?.message=="string"?r.error.message:typeof r.error?.code=="string"?r.error.code:"the voice failed"}catch{return}}function he(){let e=globalThis;if(typeof e.RTCPeerConnection!="function"||typeof e.navigator?.mediaDevices?.getUserMedia!="function")throw new TypeError("connectVoice: this runtime has no WebRTC (RTCPeerConnection, navigator.mediaDevices): a chat's voice is a browser's");let r=e.navigator.mediaDevices;return{RTCPeerConnection:e.RTCPeerConnection,getUserMedia:t=>r.getUserMedia(t)}}function ge(){let e=globalThis.document;if(!e)throw new TypeError("connectVoice: give audio \u2014 the element the voice plays in \u2014 where there is no document");let r=e.createElement("audio");return r.autoplay=!0,r}var i=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0;function we(e,r,t){let l=i(i(i(e)?.components)?.schemas)??{},f=(p,n)=>{let d=new Set,h=(b,g,y)=>{let a=i(b);if(!a)return;if(typeof a.$ref=="string"){if(y.has(a.$ref)||!a.$ref.startsWith("#/components/schemas/"))return;h(l[a.$ref.slice(21)],g,new Set(y).add(a.$ref));return}if(a[k]===!0){d.add(g);return}for(let C of["anyOf","oneOf","allOf"]){let S=a[C];if(Array.isArray(S))for(let $ of S)h($,g,y)}let v=i(a.properties);if(v)for(let[C,S]of Object.entries(v))h(S,`${g}/${E(C)}`,y);i(a.items)&&h(a.items,`${g}/*`,y);for(let C of["additionalProperties","patternProperties","prefixItems"])if(a[C]!==void 0&&w(a[C],new Set(y)))throw new Error(`${t}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},w=(b,g)=>{if(Array.isArray(b))return b.some(a=>w(a,g));let y=i(b);return y?y[k]===!0?!0:typeof y.$ref=="string"&&!g.has(y.$ref)&&y.$ref.startsWith("#/components/schemas/")?(g.add(y.$ref),w(l[y.$ref.slice(21)],g)):Object.values(y).some(a=>typeof a=="object"&&a!==null&&w(a,g)):!1};return h(p,n,new Set),[...d]},c=p=>i(i(i(p)?.["application/json"])?.schema),o=[];o.push(...f(c(i(r.requestBody)?.content),"/body"));for(let p of Array.isArray(r.parameters)?r.parameters:[]){let n=i(p);if(!n)continue;let d=f(n.schema,`/query/${E(String(n.name))}`);if(d.length!==0){if(n.in!=="query")throw new Error(`${t}: ${String(n.in)} parameter ${String(n.name)} is marked encrypted \u2014 a body's or a query's field is`);if(d.some(h=>h.split("/").length!==3))throw new Error(`${t}: an encrypted query field is one of the query's own names`);o.push(...d)}}let s=i(r.responses)??{},u=Object.keys(s).filter(p=>/^2\d\d$/.test(p)).sort((p,n)=>p==="200"?-1:n==="200"?1:p.localeCompare(n)),m=u.length>0?f(c(i(s[u[0]])?.content),"/response"):[];if(o.length+m.length!==0){if(r["x-palbase-sse"]!==void 0&&m.length>0)throw new Error(`${t}: a streamed answer carries no encrypted field`);if(r["x-palbase-upload"]!==void 0)throw new Error(`${t}: an upload goes through storage, which seals nothing \u2014 it carries no encrypted field`);return{request:o,response:m}}}async function Ce(e){let r=`${e.method.toUpperCase()} ${e.path}`,t=i(i(i(i(e.contract)?.paths)?.[e.path])?.[e.method.toLowerCase()]),l=t?we(e.contract,t,r):void 0;if(!l)return{body:e.body,query:e.query,open:async s=>s};let{key:f,header:c}=await R(e.key.kid,T(e.key.publicKey),x(e.projectId,e.method,e.path,e.params??[])),o=(s,u)=>s==null?s:P(s,u,l.request,(m,p)=>A(f,m,p));return{header:c,body:await o(e.body,"/body"),query:await o(e.query,"/query"),open:s=>s===void 0?Promise.resolve(s):P(s,"/response",l.response,async(u,m)=>{if(!V(m))throw new O("unopenable",`${r}: ${u} came plain where the contract says it is encrypted`);return M(f,u,m)})}}export{N as Analytics,_ as BackendError,de as CallPlace,ce as CallSession,pe as Calls,G as Channel,U as Consent,ne as ConversationList,oe as ConversationView,re as DeletedGroupList,Z as Flags,z as GatewayError,J as InApp,B as Inbox,H as Installation,te as Messaging,W as Notify,L as PalbaseError,ie as PlaceBusyError,X as Purchases,D as RealtimeSocket,F as SESSION_START,ae as ScheduledList,I as SessionChangedError,se as ThreadView,K as WebPush,ue as connectVoice,ye as createClient,Ce as encryptedCall,ee as indexedDBKeyValue,Q as isBackendError,q as localStore,j as memoryStore,Y as redemptionToken};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
2
- import{a as i}from"../chunks/4N4YEPF7.js";import{a as e,b as s,c as t,d as p,e as o,f as a,h as r,j as n,k as y,p as M,q as l,t as g}from"../chunks/6JSKJTLV.js";import"../chunks/IKEE4LBO.js";export{n as MESSAGE_COMPONENTS,a as MESSAGE_ICONS,r as MESSAGE_SCHEMA,s as assetId,y as countdownValues,e as fontFamily,o as htmlDocument,t as prepareAssets,i as presentMessage,g as renderMessage,M as resolveMessage,l as resolveMessageWithPaths,p as unzip};
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as i}from"../chunks/7XJCDA36.js";import{a as e,b as s,c as t,d as p,e as o,f as a,h as r,j as n,k as y,p as M,q as l,t as g}from"../chunks/RJ3QR6BS.js";import"../chunks/A5CZXTHL.js";export{n as MESSAGE_COMPONENTS,a as MESSAGE_ICONS,r as MESSAGE_SCHEMA,s as assetId,y as countdownValues,e as fontFamily,o as htmlDocument,t as prepareAssets,i as presentMessage,g as renderMessage,M as resolveMessage,l as resolveMessageWithPaths,p as unzip};
package/dist/web/palbe.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
2
- import{c as e,d as r,i as t}from"../chunks/QN55ZKNQ.js";import"../chunks/NY2ZPGNN.js";import"../chunks/ATWAZAG2.js";import"../chunks/K6R5SBI5.js";import"../chunks/OTVQ3EBH.js";import"../chunks/JHWPYG5N.js";import"../chunks/IKEE4LBO.js";export{e as RESERVED_CLIENT_NAMES,t as __registerBackend,r as isClientName};
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
+ import{c as e,d as r,i as t}from"../chunks/NAQ2ZLAT.js";import"../chunks/NBDKEIXP.js";import"../chunks/F6NKEFR2.js";import"../chunks/OLNQWW5N.js";import"../chunks/MA5G227L.js";import"../chunks/DOFSL7OH.js";import"../chunks/A5CZXTHL.js";export{e as RESERVED_CLIENT_NAMES,t as __registerBackend,r as isClientName};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
2
- import{a as f,b as d,c as m,d as u,e as A,f as c,g as R}from"../chunks/YHAR4WUH.js";import{a as e,b as a,c as t,d as l,e as r,f as o,g as p,i as y,k as s,l as P,n,o as i,s as w}from"../chunks/6JSKJTLV.js";import"../chunks/OTVQ3EBH.js";import"../chunks/JHWPYG5N.js";import"../chunks/IKEE4LBO.js";export{y as PAYWALL_COMPONENTS,o as PAYWALL_ICONS,p as PAYWALL_SCHEMA,c as Paywall,a as assetId,f as attributesHeader,s as countdownValues,R as defaultPaywall,e as fontFamily,u as formatPeriod,m as formatPrice,r as htmlDocument,A as packageValues,P as packagesOf,d as parseDuration,t as prepareAssets,w as renderPaywall,n as resolvePaywall,i as resolvePaywallWithPaths,l as unzip};
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as f,b as d,c as m,d as u,e as A,f as c,g as R}from"../chunks/PPGCDKAN.js";import{a as e,b as a,c as t,d as l,e as r,f as o,g as p,i as y,k as s,l as P,n,o as i,s as w}from"../chunks/RJ3QR6BS.js";import"../chunks/MA5G227L.js";import"../chunks/DOFSL7OH.js";import"../chunks/A5CZXTHL.js";export{y as PAYWALL_COMPONENTS,o as PAYWALL_ICONS,p as PAYWALL_SCHEMA,c as Paywall,a as assetId,f as attributesHeader,s as countdownValues,R as defaultPaywall,e as fontFamily,u as formatPeriod,m as formatPrice,r as htmlDocument,A as packageValues,P as packagesOf,d as parseDuration,t as prepareAssets,w as renderPaywall,n as resolvePaywall,i as resolvePaywallWithPaths,l as unzip};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
2
  "use strict";(()=>{function g(t,l){if(t)try{let o=new URL(t,l);if(o.protocol==="https:"||o.protocol==="http:"&&(o.hostname==="localhost"||o.hostname==="127.0.0.1"))return o.href}catch{}}function w(t){let l=new URL(t.location.href).searchParams,o=l.get("url")??"",p=l.get("key")??"",c=(e,n)=>!e||!o?Promise.resolve():t.fetch(`${o.replace(/\/$/,"")}/notify/receipts`,{method:"POST",headers:{"content-type":"application/json",apikey:p},body:JSON.stringify({receipts:[{receipt:e,status:n}]}),keepalive:!0}).catch(()=>{}),f=async(e,n)=>{for(let s of await t.clients.matchAll({type:"window",includeUncontrolled:!0}))s.postMessage({type:"palbase.push",event:e,url:n.url,data:n.data})};t.addEventListener("push",(e=>{let n={};try{n=e.data?.json()??{}}catch{}let s={url:n.url,receipt:n.receipt,data:n.data},a=n.data?.type==="messaging.message"||n.data?.pb_call==="incoming",u=async()=>a&&(await t.clients.matchAll({type:"window",includeUncontrolled:!0})).some(i=>i.focused===!0),r=async()=>{let i=n.data?.pb_call==="missed"?n.data.call_id:void 0;if(i)for(let d of await t.registration.getNotifications?.({tag:i})??[])d.close()};e.waitUntil(Promise.all([u(),r().catch(()=>{})]).then(([i])=>i?void 0:t.registration.showNotification(n.title??"",{body:n.body,image:n.image,tag:n.tag,data:s})).then(()=>Promise.all([c(n.receipt,"delivered"),f("received",s)])))})),t.addEventListener("notificationclick",(e=>{e.notification.close();let n=e.notification.data??{},s=n.data?.pb_call!==void 0,a=g(n.url,t.location.origin)??(s?g(t.registration.scope??"/",t.location.origin):void 0),u=async()=>{if(!a)return;let r=await t.clients.matchAll({type:"window",includeUncontrolled:!0}),i=r.find(d=>d.url===a)??(s&&!n.url?r.find(d=>d.focused)??r[0]:void 0);i?await i.focus():await t.clients.openWindow(a)};e.waitUntil(Promise.all([c(n.receipt,"opened"),u(),f("opened",n)]))})),t.addEventListener("notificationclose",(e=>{e.waitUntil(c(e.notification.data?.receipt,"dismissed"))}))}typeof self<"u"&&typeof self.registration=="object"&&!("document"in self)&&w(self);})();
package/dist/web/ssr.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
2
- import{B as g}from"../chunks/IHI5K54A.js";import"../chunks/QN55ZKNQ.js";import"../chunks/NY2ZPGNN.js";import"../chunks/YHAR4WUH.js";import"../chunks/4N4YEPF7.js";import"../chunks/6JSKJTLV.js";import"../chunks/ATWAZAG2.js";import"../chunks/262XXIZR.js";import"../chunks/K6R5SBI5.js";import"../chunks/OTVQ3EBH.js";import"../chunks/JHWPYG5N.js";import"../chunks/IKEE4LBO.js";var A=Object.freeze({"Cache-Control":"private, no-cache, no-store, must-revalidate, max-age=0",Expires:"0",Pragma:"no-cache"}),x={path:"/",sameSite:"lax",secure:!0,httpOnly:!1,maxAge:400*24*60*60},h=3180,$=5*6e4;function b(e,t={}){let s=/^pb_([a-z0-9]+)_c/.exec(e)?.[1];if(s===void 0)throw new TypeError("publishableKey is the project publishable key (pb_<ref>_c\u2026)");let o={...x,...t};return`${o.secure===!0&&!o.domain&&(o.path??"/")==="/"?"__Host-":""}pb-${s}-session`}var v=e=>{let t=new TextEncoder().encode(JSON.stringify(e)),s="";for(let o of t)s+=String.fromCharCode(o);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},_=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),s=JSON.parse(new TextDecoder().decode(Uint8Array.from(t,o=>o.charCodeAt(0))));return typeof s.accessToken!="string"||typeof s.refreshToken!="string"||typeof s.expiresAt!="number"||typeof s.userId!="string"?null:s}catch{return null}},f="__Host-",C=!1;function w(e,t,s={},o=!1){let r={...x,...s},d=async()=>new Map((await t.getAll()).map(n=>[n.name,n.value])),m=n=>a=>a===n||a.startsWith(`${n}.`)&&/^\d+$/.test(a.slice(n.length+1)),S=m(e),k=e.startsWith(f)?e.slice(f.length):f+e,O=m(k),y=async n=>{if(!t.setAll)return;let a=n===null?[]:n.length<=h?[[e,n]]:Array.from({length:Math.ceil(n.length/h)},(i,u)=>[`${e}.${u}`,n.slice(u*h,(u+1)*h)]),l=new Set(a.map(([i])=>i)),c=a.map(([i,u])=>({name:i,value:u,options:r})),p=await d();for(let i of p.keys())S(i)&&!l.has(i)&&c.push({name:i,value:"",options:{...r,maxAge:0}});if(e.startsWith(f))for(let i of p.keys())O(i)&&c.push({name:i,value:"",options:{...r,maxAge:0}});c.length>0&&await t.setAll(c,{...A})};return{async load(){let n=await d(),a=[...n.keys()];!C&&!a.some(S)&&a.some(O)&&(C=!0,console.warn(`palbase: the request holds a session cookie named ${k}, and this client reads ${e}: no one is signed in here. The browser's client and the server's name it from the same cookieOptions \u2014 on http (localhost) the server's needs cookieOptions: { secure: false }.`));let l=n.get(e);if(l===void 0){let c="";for(let p=0;n.has(`${e}.${p}`);p++)c+=n.get(`${e}.${p}`);l=c}return l?_(l):null},save:n=>y(v(n)),clear:()=>y(null),shared:o}}function P(e){let{cookies:t,cookieOptions:s,...o}=e,r=e.refresh??(t.setAll?"before":"never");return g({...o,refresh:r,storage:w(b(e.publishableKey,s),t,s)})}function T(){let e=()=>{let t=globalThis.document;if(!t)throw new Error("documentCookies: there is no document here \u2014 a server gives its request's cookies to createServerClient");return t};return{getAll:()=>e().cookie.split(";").map(t=>t.trim()).filter(t=>t.includes("=")).map(t=>{let s=t.indexOf("=");return{name:t.slice(0,s),value:t.slice(s+1)}}),setAll(t){for(let s of t){let o=s.options,r=[`Path=${o.path??"/"}`,o.domain?`Domain=${o.domain}`:"",o.maxAge!==void 0?`Max-Age=${o.maxAge}`:"",o.expires?`Expires=${o.expires.toUTCString()}`:"",o.sameSite?`SameSite=${o.sameSite.charAt(0).toUpperCase()}${o.sameSite.slice(1)}`:"",o.secure?"Secure":""].filter(Boolean);e().cookie=[`${s.name}=${s.value}`,...r].join("; ")}}}}function M(e){let{cookieOptions:t,...s}=e,r={secure:globalThis.location?.protocol==="https:",...t};return g({...s,storage:w(b(e.publishableKey,r),T(),r,!0)})}async function N(e){let t=await e.auth.currentSession();if(!t||(t.expiresAt-Date.now()<=$&&await e.auth.refreshSession().catch(()=>{}),!await e.auth.currentSession()))return null;try{return(await e.auth.api.verifyTokenUser()).data}catch(s){if(s.status===401)return null;throw s}}export{A as NO_STORE_HEADERS,x as SESSION_COOKIE_OPTIONS,w as cookieSessionStore,M as createBrowserClient,P as createServerClient,T as documentCookies,N as keepSession,b as sessionCookieName};
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
+ import{B as g}from"../chunks/EQSGX2P5.js";import"../chunks/NAQ2ZLAT.js";import"../chunks/NBDKEIXP.js";import"../chunks/PPGCDKAN.js";import"../chunks/7XJCDA36.js";import"../chunks/RJ3QR6BS.js";import"../chunks/F6NKEFR2.js";import"../chunks/77KKSGFT.js";import"../chunks/OLNQWW5N.js";import"../chunks/MA5G227L.js";import"../chunks/DOFSL7OH.js";import"../chunks/A5CZXTHL.js";var A=Object.freeze({"Cache-Control":"private, no-cache, no-store, must-revalidate, max-age=0",Expires:"0",Pragma:"no-cache"}),x={path:"/",sameSite:"lax",secure:!0,httpOnly:!1,maxAge:400*24*60*60},h=3180,$=5*6e4;function b(e,t={}){let s=/^pb_([a-z0-9]+)_c/.exec(e)?.[1];if(s===void 0)throw new TypeError("publishableKey is the project publishable key (pb_<ref>_c\u2026)");let o={...x,...t};return`${o.secure===!0&&!o.domain&&(o.path??"/")==="/"?"__Host-":""}pb-${s}-session`}var v=e=>{let t=new TextEncoder().encode(JSON.stringify(e)),s="";for(let o of t)s+=String.fromCharCode(o);return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},_=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),s=JSON.parse(new TextDecoder().decode(Uint8Array.from(t,o=>o.charCodeAt(0))));return typeof s.accessToken!="string"||typeof s.refreshToken!="string"||typeof s.expiresAt!="number"||typeof s.userId!="string"?null:s}catch{return null}},f="__Host-",C=!1;function w(e,t,s={},o=!1){let r={...x,...s},d=async()=>new Map((await t.getAll()).map(n=>[n.name,n.value])),m=n=>a=>a===n||a.startsWith(`${n}.`)&&/^\d+$/.test(a.slice(n.length+1)),S=m(e),k=e.startsWith(f)?e.slice(f.length):f+e,O=m(k),y=async n=>{if(!t.setAll)return;let a=n===null?[]:n.length<=h?[[e,n]]:Array.from({length:Math.ceil(n.length/h)},(i,u)=>[`${e}.${u}`,n.slice(u*h,(u+1)*h)]),l=new Set(a.map(([i])=>i)),c=a.map(([i,u])=>({name:i,value:u,options:r})),p=await d();for(let i of p.keys())S(i)&&!l.has(i)&&c.push({name:i,value:"",options:{...r,maxAge:0}});if(e.startsWith(f))for(let i of p.keys())O(i)&&c.push({name:i,value:"",options:{...r,maxAge:0}});c.length>0&&await t.setAll(c,{...A})};return{async load(){let n=await d(),a=[...n.keys()];!C&&!a.some(S)&&a.some(O)&&(C=!0,console.warn(`palbase: the request holds a session cookie named ${k}, and this client reads ${e}: no one is signed in here. The browser's client and the server's name it from the same cookieOptions \u2014 on http (localhost) the server's needs cookieOptions: { secure: false }.`));let l=n.get(e);if(l===void 0){let c="";for(let p=0;n.has(`${e}.${p}`);p++)c+=n.get(`${e}.${p}`);l=c}return l?_(l):null},save:n=>y(v(n)),clear:()=>y(null),shared:o}}function P(e){let{cookies:t,cookieOptions:s,...o}=e,r=e.refresh??(t.setAll?"before":"never");return g({...o,refresh:r,storage:w(b(e.publishableKey,s),t,s)})}function T(){let e=()=>{let t=globalThis.document;if(!t)throw new Error("documentCookies: there is no document here \u2014 a server gives its request's cookies to createServerClient");return t};return{getAll:()=>e().cookie.split(";").map(t=>t.trim()).filter(t=>t.includes("=")).map(t=>{let s=t.indexOf("=");return{name:t.slice(0,s),value:t.slice(s+1)}}),setAll(t){for(let s of t){let o=s.options,r=[`Path=${o.path??"/"}`,o.domain?`Domain=${o.domain}`:"",o.maxAge!==void 0?`Max-Age=${o.maxAge}`:"",o.expires?`Expires=${o.expires.toUTCString()}`:"",o.sameSite?`SameSite=${o.sameSite.charAt(0).toUpperCase()}${o.sameSite.slice(1)}`:"",o.secure?"Secure":""].filter(Boolean);e().cookie=[`${s.name}=${s.value}`,...r].join("; ")}}}}function M(e){let{cookieOptions:t,...s}=e,r={secure:globalThis.location?.protocol==="https:",...t};return g({...s,storage:w(b(e.publishableKey,r),T(),r,!0)})}async function N(e){let t=await e.auth.currentSession();if(!t||(t.expiresAt-Date.now()<=$&&await e.auth.refreshSession().catch(()=>{}),!await e.auth.currentSession()))return null;try{return(await e.auth.api.verifyTokenUser()).data}catch(s){if(s.status===401)return null;throw s}}export{A as NO_STORE_HEADERS,x as SESSION_COOKIE_OPTIONS,w as cookieSessionStore,M as createBrowserClient,P as createServerClient,T as documentCookies,N as keepSession,b as sessionCookieName};
package/dist/web/vite.js CHANGED
@@ -1,3 +1,3 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
2
- import"../chunks/IKEE4LBO.js";import{execFile as $}from"node:child_process";import{existsSync as y,mkdtempSync as k,readFileSync as S,rmSync as x,writeFileSync as P}from"node:fs";import{createRequire as O}from"node:module";import{tmpdir as W}from"node:os";import{dirname as g,join as o,relative as u,resolve as v,sep as d}from"node:path";var E=/\.(?:ts|js|mts|mjs)$/;function F(n){if(!/^[a-z][a-z0-9-]*$/.test(n.app))throw new TypeError(`palbase({ app }): ${JSON.stringify(n.app)} is an app's slug (palbase apps:list)`);let c=process.cwd(),p="",i="",f=()=>v(c,n.dir??"palbase"),m=()=>{let e=n.environments[p];if(!e)throw new Error(`palbase: the mode "${p}" is not built against any environment \u2014 say which in vite.config: palbase({ environments: { ${JSON.stringify(p)}: '<environment slug>' } })`);return e};return{name:"palbase",enforce:"pre",config(e,s){p=s.mode,i=s.command??"";let r=e.build?.rollupOptions?.onwarn;return{build:{rollupOptions:{onwarn(t,a){let l=String(t.exporter??t.id??"");if(t.code==="MISSING_EXPORT"&&l.includes(`${d}environments${d}`))throw new Error(`palbase: ${t.message} \u2014 ${m()}'s backend has no such route (palbase apps:sync brings what it has)`);r?r(t,a):a(t)}}}}},configResolved(e){c=e.root,p=e.mode,i=e.command??i},async buildStart(){i!=="build"||n.typecheck===!1||await j(c,m(),n.tsconfig)},resolveId(e,s){if(!s)return null;let r=f();if(e==="palbase"||e.startsWith("palbase/")){let w=u(r,s);return w.startsWith("..")||w===""?null:this.resolve(e,o(c,"index.html"),{skipSelf:!0})}if(!(e.startsWith(".")||e.startsWith("/")))return null;let t=v(g(s),e);if(E.test(t)||(t+=".ts"),g(t)!==r&&g(t)!==o(r,"palbe"))return null;let a=u(r,t),l=`${n.app}.ts`;if(a!==l&&!a.startsWith(`palbe${d}`))return null;let h=m(),b=o(r,"environments",h,a===l?l:o("palbe",a.slice(`palbe${d}`.length)));if(!y(b))throw new Error(`palbase: ${u(c,b)} is not there \u2014 palbase apps:sync writes it (is ${n.app} set in ${h}, and has ${h} that machine?)`);return b}}}async function j(n,c,p){let i=p?v(n,p):["tsconfig.app.json","tsconfig.json"].map(e=>o(n,e)).find(y);if(!i)return;if(!y(i))throw new Error(`palbase({ tsconfig }): ${u(n,i)} is not there`);let f;try{let e=O(o(n,"package.json")).resolve("typescript/package.json"),s=JSON.parse(S(e,"utf8")).bin?.tsc;if(!s)throw new Error("no tsc");f=o(g(e),s)}catch{throw new Error("palbase: the build type-checks the app against its environment with the app's TypeScript, and the app has none (npm i -D typescript) \u2014 or say palbase({ typecheck: false })")}let m=k(o(W(),"palbase-typecheck-"));try{let e=o(m,"tsconfig.json");P(e,JSON.stringify({extends:i,compilerOptions:{noEmit:!0,composite:!1,incremental:!1,moduleSuffixes:[`.${c}`,""]}}));let s=await new Promise(r=>$(process.execPath,[f,"-p",e,"--pretty","false"],{cwd:n,maxBuffer:16<<20},(t,a,l)=>r({code:t?typeof t.code=="number"?t.code:1:0,text:`${a}${l}`.trim()})));if(s.code!==0)throw new Error(`palbase: the app does not type-check against ${c}, the environment this build is made for \u2014 a route its backend does not have, or a call that does not fit it:
1
+ /*! palbase 0.51.1 — Palbase SDK License (see LICENSE) */
2
+ import"../chunks/A5CZXTHL.js";import{execFile as $}from"node:child_process";import{existsSync as y,mkdtempSync as k,readFileSync as S,rmSync as x,writeFileSync as P}from"node:fs";import{createRequire as O}from"node:module";import{tmpdir as W}from"node:os";import{dirname as g,join as o,relative as u,resolve as v,sep as d}from"node:path";var E=/\.(?:ts|js|mts|mjs)$/;function F(n){if(!/^[a-z][a-z0-9-]*$/.test(n.app))throw new TypeError(`palbase({ app }): ${JSON.stringify(n.app)} is an app's slug (palbase apps:list)`);let c=process.cwd(),p="",i="",f=()=>v(c,n.dir??"palbase"),m=()=>{let e=n.environments[p];if(!e)throw new Error(`palbase: the mode "${p}" is not built against any environment \u2014 say which in vite.config: palbase({ environments: { ${JSON.stringify(p)}: '<environment slug>' } })`);return e};return{name:"palbase",enforce:"pre",config(e,s){p=s.mode,i=s.command??"";let r=e.build?.rollupOptions?.onwarn;return{build:{rollupOptions:{onwarn(t,a){let l=String(t.exporter??t.id??"");if(t.code==="MISSING_EXPORT"&&l.includes(`${d}environments${d}`))throw new Error(`palbase: ${t.message} \u2014 ${m()}'s backend has no such route (palbase apps:sync brings what it has)`);r?r(t,a):a(t)}}}}},configResolved(e){c=e.root,p=e.mode,i=e.command??i},async buildStart(){i!=="build"||n.typecheck===!1||await j(c,m(),n.tsconfig)},resolveId(e,s){if(!s)return null;let r=f();if(e==="palbase"||e.startsWith("palbase/")){let w=u(r,s);return w.startsWith("..")||w===""?null:this.resolve(e,o(c,"index.html"),{skipSelf:!0})}if(!(e.startsWith(".")||e.startsWith("/")))return null;let t=v(g(s),e);if(E.test(t)||(t+=".ts"),g(t)!==r&&g(t)!==o(r,"palbe"))return null;let a=u(r,t),l=`${n.app}.ts`;if(a!==l&&!a.startsWith(`palbe${d}`))return null;let h=m(),b=o(r,"environments",h,a===l?l:o("palbe",a.slice(`palbe${d}`.length)));if(!y(b))throw new Error(`palbase: ${u(c,b)} is not there \u2014 palbase apps:sync writes it (is ${n.app} set in ${h}, and has ${h} that machine?)`);return b}}}async function j(n,c,p){let i=p?v(n,p):["tsconfig.app.json","tsconfig.json"].map(e=>o(n,e)).find(y);if(!i)return;if(!y(i))throw new Error(`palbase({ tsconfig }): ${u(n,i)} is not there`);let f;try{let e=O(o(n,"package.json")).resolve("typescript/package.json"),s=JSON.parse(S(e,"utf8")).bin?.tsc;if(!s)throw new Error("no tsc");f=o(g(e),s)}catch{throw new Error("palbase: the build type-checks the app against its environment with the app's TypeScript, and the app has none (npm i -D typescript) \u2014 or say palbase({ typecheck: false })")}let m=k(o(W(),"palbase-typecheck-"));try{let e=o(m,"tsconfig.json");P(e,JSON.stringify({extends:i,compilerOptions:{noEmit:!0,composite:!1,incremental:!1,moduleSuffixes:[`.${c}`,""]}}));let s=await new Promise(r=>$(process.execPath,[f,"-p",e,"--pretty","false"],{cwd:n,maxBuffer:16<<20},(t,a,l)=>r({code:t?typeof t.code=="number"?t.code:1:0,text:`${a}${l}`.trim()})));if(s.code!==0)throw new Error(`palbase: the app does not type-check against ${c}, the environment this build is made for \u2014 a route its backend does not have, or a call that does not fit it:
3
3
  ${s.text}`)}finally{x(m,{recursive:!0,force:!0})}}export{F as palbase};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "palbase",
3
- "version": "0.51.0",
3
+ "version": "0.51.1",
4
4
  "description": "Palbase for JavaScript: the web client (palbase/web), the server SDK (palbase/server), an organization's management SDK (palbase/cloud), the backend framework (palbase/backend), AI (palbase/ai) and the CLI (npx palbase).",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "homepage": "https://palbase.studio",
@@ -150,7 +150,7 @@
150
150
  "@types/node": "26.6.4",
151
151
  "bun-types": "1.4.2",
152
152
  "livekit-client": "^2.23.0",
153
- "palgres": "0.51.0",
153
+ "palgres": "0.51.1",
154
154
  "reflect-metadata": "^0.2.2",
155
155
  "typescript": "~6.0.3",
156
156
  "zod": "^4.6.5"
@@ -107,6 +107,9 @@ export declare class RealtimeSocket {
107
107
  private reconnectTimer;
108
108
  private attempts;
109
109
  private closedByUs;
110
+ /** The joins asked, numbered; and the user's sockets, counted by each close for good: a join asked before is not sent after. */
111
+ private asks;
112
+ private epoch;
110
113
  /** The socket was open since it was last closed by the client: an opening after it is a reopening. */
111
114
  private wasOpen;
112
115
  private current;
@@ -153,6 +156,8 @@ export declare class RealtimeSocket {
153
156
  private dropped;
154
157
  private sendJoin;
155
158
  private ask;
159
+ /** A join left unanswered, asked again on the same socket after a pause that grows with each one. */
160
+ private askOnLater;
156
161
  private awaitReply;
157
162
  private receive;
158
163
  private push;
@@ -1,13 +0,0 @@
1
- /*! palbase 0.51.0 — Palbase SDK License (see LICENSE) */
2
- import{b as N,c as T,d as x}from"./NY2ZPGNN.js";import{a as Q,f as Y,g as Z,j as X,k as ee,l as te,o as G,p as ne,q as se}from"./ATWAZAG2.js";import{d as A}from"./K6R5SBI5.js";import{a as b,b as z,c as _,e as M}from"./OTVQ3EBH.js";var c=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function ae(t){return t instanceof c||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function q(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??Ke(e,"request_id"),data:E(e,"data"),cause:t};if(t.code==="network_error")return new c("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new c("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new c("attestationRequired",n);if(t.status===401)return new c("unauthorized",n);if(t.status===429)return new c("rateLimited",{...n,retryAfter:Be(e)??t.retryAfter});let s=De(e);return t.status===400&&s?new c("validation",{...n,fields:s}):new c("server",n)}function I(t){return t instanceof z||t instanceof Error&&t.name==="PalbaseError"}function re(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function De(t){let e=E(E(t,"data"),"fields");if(re(e))return e;let n=E(t,"fields");return re(n)?n:void 0}function Be(t){return oe(t,"retry_after")??oe(E(t,"data"),"retryAfter")}function E(t,e){if(typeof t=="object"&&t!==null)return t[e]}function oe(t,e){let n=E(t,e);return typeof n=="number"?n:void 0}function Ke(t,e){let n=E(t,e);return typeof n=="string"?n:void 0}var Le=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Je=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),We=new Set(Je),Fe=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function P(t){return t==="then"||t==="toJSON"||Fe.has(t)}function ie(t){return t==="call"||t==="join"||P(t)}function de(t){return typeof t=="string"&&Le.test(t)&&!We.has(t)&&!P(t)}function le(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function ue(t){M(t)}function ce(t){return M(t).origin}var $=class t{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},n,s){this.me=e,this.reader=n,this.chatId=s}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let n=e.turns;do{if(!this.olderLeft)return!1;let r={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...n!==void 0?{turns:n}:{},...e.signal?{signal:e.signal}:{}},o;if(e.load)o=await e.load(r);else{let d=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");o=await this.reader.parts(d,r)}if(this.ended)return!1;let i=(o?.parts??[]).map(d=>N(d)).filter(d=>d!==void 0);if(this.olderCursor=o?.nextCursor,this.olderLeft=typeof o?.nextCursor=="string"&&o.nextCursor!=="",this.before(i),n===void 0||typeof o?.turns!="number")break;n-=o.turns}while(n>0);return this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){let n=new t(this.me);n.thoughts=this.thoughts,n.lowest=this.lowest-e.length;let s=n.lowest;for(let a of e)n.at=s++,n.fold(a);this.folded+=n.folded,this.lowest=n.lowest,this.chatId??=n.chatId;let r=new Map;for(let[a,p]of n.messages){let y=this.told.get(a),f=p;if(y)for(let m of y)f=he(f,m);else f=this.messages.get(a)??p;r.set(a,f),this.told.set(a,[...n.told.get(a)??[],...y??[]])}for(let[a,p]of this.messages)r.has(a)||r.set(a,p);this.messages.clear();for(let[a,p]of r)this.messages.set(a,p);let o=new Map;for(let[a,p]of n.responses){let y=this.responses.get(a);o.set(a,y?Ve(p,y):p)}for(let[a,p]of this.responses)o.has(a)||o.set(a,p);this.responses.clear();for(let[a,p]of o)this.responses.set(a,p);let i=new Set;for(let a of n.order)(a.type==="message"||a.type==="response")&&i.add(`${a.type}\0${a.key}`);let d=[...n.order],u=new Set([...n.messages.values()].flatMap(a=>a.responseId?[a.responseId]:[]));for(let a of this.order)if(!((a.type==="message"||a.type==="response")&&i.has(`${a.type}\0${a.key}`))&&!(a.type==="goal"&&a.event.seq>0&&n.goalWords.has(a.event.seq))&&!(a.type==="voice"&&n.voiceWords.has(B(a.event)))){if(a.type==="message"&&a.began&&a.turn!==null){let p=this.responses.get(a.turn);u.has(a.turn)?d.push({...a,began:!1,at:a.arrived}):d.push({...a,at:p&&p.at<a.arrived?p.at-.5:a.arrived});continue}d.push(a)}d.sort((a,p)=>a.at-p.at),this.order=d;for(let a of n.goalWords)this.goalWords.add(a);this.goal=null;for(let a of d)a.type==="goal"&&this.goalSaid(a.event);for(let a of n.voiceWords)this.voiceWords.add(a);let h=new Set;this.voice=null;for(let a of d)a.type==="voice"&&(this.voice=pe(this.voice,a.event,h));this.turn??=n.turn;let l=new Map([...n.calls,...this.calls]);this.calls.clear();for(let[a,p]of l)this.calls.set(a,p);for(let[a,p]of n.history)this.history.has(a)||this.history.set(a,p);this.forkedFrom??=n.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(i=>e=i)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0;for(let e of[...this.enders])e()}}takePayload(e){let n=N(e);n&&this.take(n)}take(e){if(this.ended)return;let n=e.seq;typeof n=="number"&&n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.at=this.next++,this.fold(e)&&this.changed()}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:n.from+T(n.text),loose:n.cut===null,thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:n.from+T(n.text),loose:n.cut===null,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let n=B(e);if(this.voiceWords.has(n))return!1;this.voice=pe(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);ze(n,e.offset,e.text),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"reset":{let n=this.response(e.response_id);e.offset<=n.from?(n.text="",n.from=Math.max(0,e.offset)):n.text=n.text.slice(0,x(n.text,e.offset-n.from)),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let n=this.response(e.response_id);n.runId=e.run_id,n.agent=e.name,n.named=!0,n.parentId??=e.parent_response_id;break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let n=Ue(e),s=this.messages.get(n);this.messages.set(n,he(s,e));let r=this.told.get(n);r?r.push(e):this.told.set(n,[e]),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,n){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([u,h])=>u!==n&&h.responseId===s),o=r?this.responses.get(s):void 0,i={type:"message",key:n,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},d=o?this.order.findIndex(u=>u.type==="response"&&u.key===s):-1;d>=0?this.order.splice(d,0,i):this.order.push(i)}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,n),this.order.push({type:"response",key:e,at:this.at})),n}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=l=>e!==void 0&&l.startedBy===e,s=new Map;for(let l of this.responses.values()){let a=l.parentId!==null?this.responses.get(l.parentId)??l:l;s.set(l.id,Qe(l,a.startedBy??null,n(a),l.goal??a.goal))}let r=new Map([...this.messages].map(([l,a])=>[l,e!==void 0&&a.author===e?{...a,mine:!0}:a])),o=[...this.history.entries()].sort(([l],[a])=>l-a).flatMap(([l,a])=>a.map((p,y)=>Ye(p,`${l}:${y}`,e))),i=[...o];for(let l of this.order)l.type==="goal"?i.push({type:"goal",goal:l.event}):l.type==="voice"?i.push({type:"voice",voice:l.event}):l.type==="message"?i.push({type:"message",message:r.get(l.key)}):this.responses.get(l.key).parentId===null&&i.push({type:"response",response:s.get(l.key)});let d=o.flatMap(l=>l.type==="message"?[l.message]:[]),u=o.flatMap(l=>l.type==="response"?[l.response]:[]),h=[...this.calls.values()].filter(l=>s.get(l.response_id)?.mine===!0);return{items:i,messages:[...d,...r.values()],responses:[...u,...s.values()],turn:this.turn,waiting:{approvals:h.filter(l=>l.status==="awaiting_approval"),outputs:h.filter(l=>l.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?He(this.voice,e):null}}};function B(t){return`${t.voice_id}\0${t.status}`}function pe(t,e,n){return n.add(B(e)),(e.status==="closed"?t===null||t.voice_id===e.voice_id:!n.has(`${e.voice_id}\0closed`))?e:t}function he(t,e){let n=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??t?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:t?.status==="delivered"?"delivered":n,error:e.error??null,responseId:e.response_id??t?.responseId??null,createdAt:e.created_at??t?.createdAt??"",mine:!1,metadata:e.metadata??t?.metadata??{},history:!1,truncated:!1,kind:e.kind??t?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:t?.voice??null,attachments:e.attachments?fe(e.attachments):t?.attachments??[]}}function Ve(t,e){let n={...t,marks:new Map(t.marks)};e.status!==null&&(n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=e.end),e.startedBy!==void 0&&(n.startedBy=e.startedBy),e.goal&&(n.goal=e.goal),e.named&&(n.runId=e.runId,n.agent=e.agent,n.named=!0),n.parentId=t.parentId??e.parentId,e.cut!==null&&(t.text===""||e.cut<=t.from?(n.text=e.text,n.from=e.text===""?Math.max(0,e.cut):e.from):n.text=t.text.slice(0,x(t.text,e.cut-t.from))+e.text,n.cut=t.cut===null?e.cut:Math.min(t.cut,e.cut));let s=t.cut===null?null:t.from+T(t.text);for(let[r,o]of e.marks){let i=n.marks.get(r);i?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable"?n.marks.set(r,{...i,thinking:{...i.thinking,text:i.thinking.text+o.thinking.text}}):o.type==="thinking"&&o.loose&&s!==null?n.marks.set(r,{...o,text_offset:s,loose:!1}):n.marks.set(r,o)}return n}function He(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function fe(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Ue(t){return`${t.author??""}\0${t.client_id}`}function ze(t,e,n){if(t.text===""||e<=t.from){t.from=Math.max(0,e),t.text=n;return}t.text=t.text.slice(0,x(t.text,e-t.from))+n}function Qe(t,e,n,s){let r=[...t.marks.values()].map((u,h)=>({m:u,i:h,at:x(t.text,Math.max(0,(Number(u.text_offset)||0)-t.from))}));r.sort((u,h)=>u.at-h.at||u.i-h.i);let o=[],i=[],d=0;for(let{m:u,at:h}of r)h>d&&o.push({type:"text",text:t.text.slice(d,h)}),d=Math.max(d,h),u.type==="thinking"?(o.push({type:"thinking",thinking:u.thinking}),i.push(u.thinking)):o.push(u.type==="tool"?{type:"tool",tool:u}:{type:"agent",agent:u});return d<t.text.length&&o.push({type:"text",text:t.text.slice(d)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:o,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:i,goal:s,history:!1,truncated:!1}}function Ye(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:fe(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var D=[["ApiKeyAuth","userJWT"]];function ge(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.turns!==void 0&&(s.turns=n.turns),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:D,answers:{200:"json"},query:s,signal:n.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:D,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:D,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var O=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},ye=new WeakMap;async function we(t,e,n,s={},r=()=>{},o){let{pattern:i,events:d,messages:u,durable:h,chat:l}=Ze(e),a=Xe(i,n),p=ye.get(t);p||ye.set(t,p=new Map);let y=p,f=y.get(a)??{count:0};y.set(a,f),f.count++;let m=t.channel(a,h&&s.history!==!1?{after:0}:{});if(l&&!f.chat){let g=n.chatId,k=new $(r,o,typeof g=="string"&&g!==""?g:void 0);f.chat=k,f.unchat=m.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let C=()=>{--f.count>0||(y.delete(a),f.unchat?.(),f.chat?.end(),m.leave())};try{await m.join()}catch{let g=m.state==="refused"?me(m.refusal,"unavailable"):"socket closed";throw C(),new O(`gateway ${JSON.stringify(a)} was not joined: ${g}`,g)}let S=!1,R=new Set,V=()=>{if(!S){S=!0,qe();for(let g of[...R])g();C()}},qe=m.onClosed(V),H=g=>{if(S)return()=>{};let k=m.on("broadcast",v=>{typeof v.event=="string"&&d.has(v.event)&&g(v.event,b(v.payload))}),w=()=>{R.delete(w),k()};return R.add(w),w},U={topic:a,get seq(){return m.logSeq},on(g,k){if(typeof g=="function")return H((w,v)=>g({event:w,payload:v}));if(!d.has(g))throw new TypeError(`gateway ${JSON.stringify(i)} declares no event ${JSON.stringify(String(g))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(i)}: on(${JSON.stringify(g)}, \u2026) takes the function the event is handed to`);return H((w,v)=>{w===g&&k(v)})},off(g){R.has(g)&&g()},async send(g,k){if(!u.has(g))throw new TypeError(`gateway ${JSON.stringify(i)} declares no message ${JSON.stringify(String(g))}`);let w=S?{status:"error",response:{reason:"not joined"}}:await m.push("broadcast",{type:"broadcast",event:g,payload:k});if(w.status==="ok")return b(w.response.reply);let v=me(w.response,"unavailable");throw new O(`gateway ${JSON.stringify(a)} did not take ${JSON.stringify(g)}: ${v}`,v)},leave:V};return l&&Object.defineProperty(U,"chat",{value:f.chat,enumerable:!0}),U}function Ze(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function Xe(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(n,r)?n[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function me(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var et=3600*1e3,j=new Map;function tt(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=j.get(s);if(!n&&r&&Date.now()-r.at<et)return r.list;let o=(async()=>{let i=ne(),d;try{d=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:i},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(u){throw new c("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:u})}try{return await se(d,e.signer,e.projectId,i)}catch(u){throw new c("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:u})}})();return j.set(s,{list:o,at:Date.now()}),o.catch(()=>{j.get(s)?.list===o&&j.delete(s)}),o}async function ve(t,e,n,s,r,o){let d=(await tt(t,e,o)).keys[0];return Z(d.kid,d.key,Y(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,n,s,(r,o)=>X(t.key,r,o))}function ke(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):G(e,"/response",n,async(r,o)=>{if(!ee(o))throw new c("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await te(t.key,r,o)}catch(i){throw new c("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:i})}})}function be(t){return t instanceof c&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var L=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
3
- `);let n=[],s=this.pending.indexOf(`
4
- `);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&n.push({event:this.eventName,payload:this.dataLines.join(`
5
- `)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let i=o.slice(5);this.dataLines.push(i.startsWith(" ")?i.slice(1):i)}else if(o.startsWith("event:")){let i=o.slice(6);this.eventName=i.startsWith(" ")?i.slice(1):i}}s=this.pending.indexOf(`
6
- `)}return n}};async function*_e(t,e){let n=t.getReader(),s=new TextDecoder,r=new L;try{for(;;){let{done:o,value:i}=await n.read();if(o)break;for(let d of r.consume(s.decode(i,{stream:!0}))){if(d.event==="error")throw new c("network",{code:"stream_failed",message:`stream failed: ${d.payload}`});let u;try{u=JSON.parse(d.payload)}catch{throw new c("decode",{code:"invalid_frame",message:`stream frame is not valid JSON: ${d.payload.slice(0,120)}`})}yield b(u)}}}finally{e.abort();try{await n.cancel()}catch{}}}var nt={},xe=new WeakMap;function Lt(t,e,n,s,r,o=()=>{}){xe.set(t,{project:e,machine:n,storage:s,socket:r,me:o})}var Ce=new Map,Ee=new WeakMap;function Jt(t,e,n,s,r,o){if(!de(e))throw new c("validation",{code:"reserved_namespace",message:`Cannot register backend ${JSON.stringify(String(e))}: a backend's name is an identifier the client does not keep.`});let i=ce(t);if(!le(n))throw new TypeError(`${JSON.stringify(String(n))} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);ue(s),Te(r);for(let d of Object.keys(r))if(ie(d))throw Se(d);if(o!==void 0)it(o);else if(Re(r))throw new c("validation",{code:"invalid_namespace_tree",message:`Backend ${e}: its routes carry encrypted fields, and its module holds no project id and signing key to seal them with \u2014 generate it again with palbase apps:sync`});(Ce.get(e)??st(e)).set(i,{machine:n,url:s,tree:r,...o?{transit:{...o}}:{}})}function st(t){let e=new Map;return Ce.set(t,e),Object.defineProperty(nt,t,{configurable:!0,get(){return rt(this,t,e)}}),e}function rt(t,e,n){let s=xe.get(t);if(!s)return;let r=n.get(s.project);if(!r)throw new TypeError(`pb.${e} is the backend of ${[...n.keys()].join(" and ")}: this client is ${s.project}'s, and its user's session never goes to another project's machine`);let o=Ee.get(t);o||Ee.set(t,o=new Map);let i=o.get(e);if(i?.registration===r)return i.ns;let d={machine:()=>s.machine(r.url),storage:s.storage,name:r.machine,...r.transit?{transit:{project:s.storage,config:r.transit}}:{}},u=Object.assign({call:(h,l,a)=>ht(d.machine,h,l,a),join:(h,l,a)=>we(s.socket,h,l,a,s.me,ge(s.storage))},Ie(r.tree,d));return o.set(e,{registration:r,ns:u}),u}function Se(t){return new c("validation",{code:"reserved_namespace",message:`Cannot register endpoint namespace ${JSON.stringify(t)}: the name is reserved.`})}function J(t){return typeof t.path=="string"&&typeof t.method=="string"}function ot(t,e){if(t.pathParams!==void 0){if(!Array.isArray(t.pathParams)||!t.pathParams.every(n=>typeof n=="string"))throw new c("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams must be an array of strings.`});for(let n of t.pathParams)if(!t.path.includes(`{${n}}`))throw new c("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams entry '${n}' has no '{${n}}' placeholder in the path.`})}if(t.sse!==void 0&&typeof t.sse!="boolean")throw new c("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': sse must be a boolean.`});if(t.idempotent!==void 0&&typeof t.idempotent!="boolean")throw new c("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': idempotent must be a boolean.`});if(t.upload!==void 0&&typeof t.upload!="boolean")throw new c("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': upload must be a boolean.`});if(t.upload===!0&&(t.method!=="POST"||t.sse===!0))throw new c("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an upload endpoint is a POST, and no stream.`});if(t.sse===!0&&t.input==="query")throw new c("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an sse endpoint cannot take query input.`});if(t.input!==void 0&&t.input!=="body"&&t.input!=="query"&&t.input!=="none")throw new c("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': input must be 'body', 'query' or 'none'.`});if(t.encryption!==void 0&&at(t,e),t.errors!==void 0){for(let[n,s]of Object.entries(t.errors))if(typeof s!="function")throw new c("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': errors['${n}'] must be a function.`})}}function at(t,e){let n=t.encryption,s=r=>new c("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': encryption ${r}.`});if(typeof n!="object"||n===null)throw s("is { request, response }");for(let[r,o]of[["request",["/body/","/query/"]],["response",["/response"]]]){let i=n[r];if(i!==void 0&&(!Array.isArray(i)||!i.every(d=>typeof d=="string"&&o.some(u=>d===u||d.startsWith(u.endsWith("/")?u:`${u}/`)))))throw s(`${r} is a list of places under ${o.join(" or ")}`)}if(t.upload===!0)throw s("is no upload\u2019s: storage seals nothing");if(t.sse===!0&&(n.response?.length??0)>0)throw s("of a streamed answer is none")}function Re(t){return J(t)?t.encryption!==void 0:Object.values(t).some(e=>Re(e))}function it(t){if(typeof t!="object"||t===null||typeof t.projectId!="string"||!/^[0-9a-f-]{36}$/.test(t.projectId)||typeof t.signer!="string"||!/^[A-Za-z0-9_-]{43}$/.test(t.signer))throw new c("validation",{code:"invalid_namespace_tree",message:"The backend's encryption is { projectId, signer }: the project's id and its Ed25519 signing key, base64url"})}function Te(t){if(typeof t!="object"||t===null)throw new c("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});let e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null)throw new c("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});for(let[n,s]of Object.entries(t)){if(P(n))throw Se(n);typeof s=="object"&&s!==null&&J(s)?(s.method=s.method.toUpperCase(),ot(s,s.path)):Te(s)}}function Ie(t,e){if(J(t))return t.upload===!0?async(...s)=>ct(e,t,s):async(...s)=>Oe(e.machine(),t,s,e.transit);let n={};for(let[s,r]of Object.entries(t))n[s]=Ie(r,e);return n}function W(t){if(t==null)return"";let e=Object.entries(t).filter(([,s])=>s!=null).sort(([s],[r])=>s<r?-1:s>r?1:0);return e.length===0?"":`?${e.map(([s,r])=>{if(typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")throw new c("validation",{code:"invalid_query_value",message:`Query parameter '${s}' must be a string, number, or boolean.`});return`${encodeURIComponent(s)}=${encodeURIComponent(String(r))}`}).join("&")}`}function Pe(t,e,n){try{return _(t.path,e,n)}catch(s){if(!I(s)||s.code!=="invalid_path_parameter")throw s;let r=String(n);throw new c("validation",{code:"invalid_path_parameter",message:`${t.path}: ${e} cannot be ${r===""?"empty":JSON.stringify(r)}`})}}function $e(t,e){let n=t.pathParams??[],s=t.path;for(let r=0;r<n.length;r++){let o=e[r];if(typeof o!="string"&&typeof o!="number")throw new c("validation",{code:"missing_path_param",message:`${t.path}: path parameter '${n[r]}' must be a string or number`});s=s.replace(`{${n[r]}}`,Pe(t,`path parameter '${n[r]}'`,o))}return s}var dt=new Set(["POST","PUT","PATCH","DELETE"]);async function Oe(t,e,n,s){let r=e.pathParams??[],o=$e(e,n),i=o;if(e.input==="none"&&n.length>r.length+1)throw new c("validation",{code:"unexpected_argument",message:`${e.path}: endpoint takes no input \u2014 pass only path params and options`});let d=e.input==="none"?void 0:n[r.length],u=e.input==="none"?r.length:r.length+1,h=n[u],l;if(e.input==="query")i+=W(d);else if(e.input!=="none")if(e.method==="GET"){if(d!==void 0)throw new c("validation",{code:"unsupported_get_input",message:`${e.path}: GET endpoints take no body input`})}else l=d;let a={...h?.headers};if(dt.has(e.method)&&!Object.keys(a).some(p=>p.toLowerCase()==="idempotency-key")&&(a["Idempotency-Key"]=A()),e.encryption!==void 0){if(!s)throw new c("validation",{code:"encryption_unconfigured",message:`${e.method} ${e.path}: the route carries encrypted fields, and this backend's module holds no key to seal them with`});return lt(t,e,o,d,l,a,h?.signal,r.map((p,y)=>String(n[y])),s)}try{return e.sse===!0?await Ne(t,e,i,l,a,h?.signal):await Ae(t,e,i,l,a,h?.signal)}catch(p){throw F(e,p)}}async function lt(t,e,n,s,r,o,i,d,u){let h=e.encryption;for(let l=0;;l++){let a=await ve(u.project,u.config,e.method,e.path,d,l>0);try{let p=e.input==="query"?n+W(await K(a,s,"/query",h.request)):n,y=await K(a,r,"/body",h.request),f={...o,[Q]:a.header};return e.sse===!0?await Ne(t,e,p,y,f,i):b(await ke(a,await Ae(t,e,p,y,f,i),h.response,`${e.method} ${e.path}`))}catch(p){if(l===0&&be(p))continue;throw F(e,p)}}}function F(t,e){return t.errors&&ae(e)&&Object.hasOwn(t.errors,e.code)?t.errors[e.code](e):e}var ut=[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]];async function ct(t,e,n){let s=e.pathParams??[],r=$e(e,n),o=e.input==="none"?s.length:s.length+1;if(n.length>o+2)throw new c("validation",{code:"unexpected_argument",message:`${e.path}: an upload takes its path params, ${e.input==="none"?"":"its input, "}the file and options`});let i=e.input==="none"?void 0:n[s.length],d=n[o],u=n[o+1];if(!(d instanceof Blob))throw new c("validation",{code:"invalid_file",message:`${e.path}: the file is a Blob (a File is one)`});let h=`/storage/upload/${t.name}/${Pe(e,"the route",r.slice(1))}`;e.input==="query"&&(h+=W(i));let l=pt(e.input==="query"?void 0:i,d),a=l.body.size,p=0,y=f=>{p=f;try{u?.onProgress?.({loaded:f,total:a})}catch{}};u?.onProgress&&y(0);try{let f;try{let m={op:`Upload ${e.path}`,method:"POST",path:h,auth:ut,answers:je,body:{kind:"raw",contentType:l.type,value:l.body},signal:u?.signal,...u?.onProgress?{onUploadProgress:C=>y(C)}:{}};f=(await t.storage.send(m)).data}catch(m){throw I(m)?q(m):m}return u?.onProgress&&p<a&&y(a),await Ge(e,f,u?.signal)}catch(f){throw F(e,f)}}function pt(t,e){let n=`Palbase-${A()}`,s=d=>d.replaceAll('"',"_").replace(/[\r\n]/g,""),r=typeof e.name=="string"?e.name:"blob",o=(d,u)=>`--${n}\r
7
- Content-Disposition: form-data; ${d}\r
8
- Content-Type: ${u}\r
9
- \r
10
- `,i=[];return t!==void 0&&i.push(o('name="body"',"application/json"),JSON.stringify(t),`\r
11
- `),i.push(o(`name="file"; filename="${s(r)}"`,s(e.type)||"application/octet-stream"),e,`\r
12
- --${n}--\r
13
- `),{body:new Blob(i),type:`multipart/form-data; boundary=${n}`}}async function ht(t,e,n,s){if(typeof e!="string"||e===""||e==="/")throw new c("validation",{code:"invalid_endpoint_name",message:'Endpoint name must be a non-empty path like "todos/create"'});let r=e.startsWith("/")?e:`/${e}`;return Oe(t(),{method:"POST",path:r},[n,s])}var je=Object.fromEntries(Array.from({length:100},(t,e)=>[200+e,"raw"])),ft=[["userJWT"],[]];async function Me(t,e,n,s,r,o){let i={op:`${e.method} ${e.path}`,method:e.method,path:n,auth:ft,answers:je,headers:r,...s===void 0?{}:{body:{kind:"json",contentType:"application/json",value:s}},idempotent:e.idempotent===!0,signal:o};try{return(await t.send(i)).data}catch(d){throw I(d)?q(d):d}}async function Ae(t,e,n,s,r,o){return Ge(e,await Me(t,e,n,s,r,o),o)}async function Ge(t,e,n){let s=e.headers.get("x-request-id")??void 0,r;try{r=await e.text()}catch(o){throw n?.aborted?o:new c("network",{code:"network_error",message:`${t.method} ${t.path}: the answer did not arrive whole`,status:e.status,requestId:s,cause:o})}if(r!=="")try{return b(JSON.parse(r))}catch(o){throw new c("decode",{code:"invalid_json",message:`${t.method} ${t.path}: the answer is not JSON`,status:e.status,requestId:s,cause:o})}}async function Ne(t,e,n,s,r,o){let i=new AbortController;o&&(o.aborted?i.abort():o.addEventListener("abort",()=>i.abort(),{once:!0}));let d=await Me(t,e,n,s,{accept:"text/event-stream",...r},i.signal);if(!d.body)throw new c("network",{code:"empty_stream",message:"the server answered a streaming route with no body",status:d.status});return _e(d.body,i)}export{c as a,ae as b,Je as c,de as d,ge as e,O as f,nt as g,Lt as h,Jt as i};