palbase 0.37.1 → 0.37.2

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 (46) 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/{IZ6RIKPB.js → 4Y47I6LA.js} +2 -2
  8. package/dist/chunks/{XYRYBY7I.js → 5HYKOPCW.js} +2 -2
  9. package/dist/chunks/{RAPT7CYO.js → 72CHRRHY.js} +1 -1
  10. package/dist/chunks/{LEBJY4WH.js → A6LIFQOQ.js} +3 -3
  11. package/dist/chunks/{QA6474UP.js → AF3XUGHY.js} +2 -2
  12. package/dist/chunks/{YOR7K46P.js → C4ENQSIX.js} +1 -1
  13. package/dist/chunks/{AYPQOPOF.js → CHXCVOON.js} +1 -1
  14. package/dist/chunks/{GHUIGLRJ.js → GEZH3OTX.js} +2 -2
  15. package/dist/chunks/{H6LQPKWU.js → HMDMAILZ.js} +1 -1
  16. package/dist/chunks/{TPQAYDWC.js → IOVYIATC.js} +1 -1
  17. package/dist/chunks/{DQYLTIE5.js → JCHW52YV.js} +2 -2
  18. package/dist/chunks/{I6H2425X.js → L3S7O5FQ.js} +2 -2
  19. package/dist/chunks/{PMT4A5UW.js → LANEQ73A.js} +2 -2
  20. package/dist/chunks/{YO6MPQJ4.js → NFFQO2UC.js} +2 -2
  21. package/dist/chunks/{NPJJBKWB.js → P5EW3DTQ.js} +2 -2
  22. package/dist/chunks/{YT7ZMYMN.js → QK2S67K3.js} +2 -2
  23. package/dist/chunks/{VU2SS32B.js → RVRPBQ4W.js} +2 -2
  24. package/dist/chunks/{UA3CCXS4.js → SEECU52P.js} +2 -2
  25. package/dist/chunks/{MW7YMYNO.js → UBQK5O7J.js} +1 -1
  26. package/dist/chunks/{JEA6LCOK.js → VAPNSTWC.js} +2 -2
  27. package/dist/chunks/{GCVJJS4Y.js → YLLZC52Q.js} +1 -1
  28. package/dist/chunks/{SRDV2B4P.js → YQQHL67Y.js} +2 -2
  29. package/dist/chunks/{6FVAAS5I.js → ZDENVL2U.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/internal/src/messaging/store.d.ts +2 -0
@@ -1,2 +1,2 @@
1
- /*! palbase 0.37.1 — Palbase SDK License (see LICENSE) */
2
- import{b}from"./MW7YMYNO.js";import{a as k,b as A}from"./AYPQOPOF.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
1
+ /*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
2
+ import{b}from"./UBQK5O7J.js";import{a as k,b as A}from"./CHXCVOON.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.37.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
2
2
  var K="pbt1.",E="Palbase-Encryption";var z="x-palbase-encrypted",o=class extends Error{code;constructor(t,n){super(n),this.name="TransitError",this.code=t}},h=new TextEncoder,P=new TextDecoder("utf-8",{fatal:!0}),l=()=>{let e=globalThis.crypto?.subtle;if(!e)throw new Error("encrypted fields need WebCrypto (crypto.subtle): a secure context \u2014 https, or localhost");return e};function y(e){return new Uint8Array(new ArrayBuffer(e))}function f(...e){let t=y(e.reduce((r,i)=>r+i.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function d(e){return f(e)}function m(e,t){let n=y(t);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return n}function x(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(e){let t=e.replace(/=+$/,"");if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)throw new o("malformed","not base64url");let n=atob(t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4)),r=y(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}var S=f(h.encode("KEM"),m(32,2)),g=f(h.encode("HPKE"),m(32,2),m(1,2),m(1,2)),v=h.encode("HPKE-v1"),X=16,H=12,T=32,$=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function N(e,t){let n=await l().importKey("raw",e.length===0?y(32):d(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await l().sign("HMAC",n,d(t)))}async function k(e,t,n,r){return N(t,f(v,e,h.encode(n),r))}async function U(e,t,n,r,i){let a=f(m(i,2),v,e,h.encode(n),r),s=y(i),c=y(0);for(let u=1,p=0;p<i;u++)c=await N(t,f(c,a,Uint8Array.of(u))),s.set(c.subarray(0,Math.min(c.length,i-p)),p),p+=c.length;return s}async function j(e){if(e.length!==32)throw new o("malformed","an X25519 private key is 32 bytes");return l().importKey("pkcs8",f($,e),{name:"X25519"},!1,["deriveBits"])}async function C(e){if(e.length!==32)throw new o("malformed","an X25519 public key is 32 bytes");return l().importKey("raw",d(e),{name:"X25519"},!1,[])}async function O(e,t){return new Uint8Array(await l().deriveBits({name:"X25519",public:t},e,256))}async function R(e,t,n){let r=await k(S,y(0),"eae_prk",e);return U(S,r,"shared_secret",f(t,n),T)}async function _(e,t){let n=await k(g,y(0),"psk_id_hash",y(0)),r=await k(g,y(0),"info_hash",t),i=f(Uint8Array.of(0),n,r),a=await k(g,e,"secret",y(0));return{key:await U(g,a,"key",i,X),nonce:await U(g,a,"base_nonce",i,H)}}async function b(e,t,n,r,i){let a=await l().importKey("raw",d(t),"AES-GCM",!1,[e]);return new Uint8Array(await l()[e]({name:"AES-GCM",iv:d(n),additionalData:d(r)},a,d(i)))}async function V(e,t,n,r=y(0),i){let a,s;if(i)a=await j(i.privateKey),s=d(i.publicKey);else{let B=await l().generateKey({name:"X25519"},!0,["deriveBits"]);a=B.privateKey,s=new Uint8Array(await l().exportKey("raw",B.publicKey))}let c=await R(await O(a,await C(e)),s,e),{key:u,nonce:p}=await _(c,t);return{enc:s,ct:await b("encrypt",u,p,r,n)}}async function q(e,t,n,r,i,a=y(0)){if(n.length!==32)throw new o("malformed","an encapsulated X25519 key is 32 bytes");try{let s=await R(await O(await j(e),await C(n)),n,t),{key:c,nonce:u}=await _(s,r);return await b("decrypt",c,u,a,i)}catch{throw new o("unopenable","the request's key does not open with the project's key it names")}}async function Z(e){let t=await l().importKey("pkcs8",f($,e),{name:"X25519"},!0,["deriveBits"]),n=await l().exportKey("jwk",t);return w(n.x)}function Q(e,t,n,r=[]){if(r.some(i=>i.includes("\0")))throw new o("malformed","a path's value holds no NUL");return h.encode(["palbase-encryption","1",e,t.toUpperCase(),L(n),...r].join("\0"))}function L(e){return e.replace(/\{[^/{}]*\}/g,"{}")}async function Y(e,t,n,r={}){let i=r.key?d(r.key):crypto.getRandomValues(y(32)),{enc:a,ct:s}=await V(t,n,i,y(0),r.ephemeral);return{kid:e,key:i,header:`1.${e}.${x(a)}.${x(s)}`}}function J(e){let t=e.trim().split(".");if(t.length!==4||t[0]!=="1"||!/^t[1-9][0-9]{0,5}$/.test(t[1]))throw new o("malformed",`${E} is 1.<key id>.<enc>.<ct>`);let n=w(t[2]),r=w(t[3]);if(n.length!==32||r.length!==48)throw new o("malformed",`${E} carries a 32-byte encapsulated key and a sealed 32-byte key`);return{kid:t[1],enc:n,ct:r}}async function ee(e,t,n,r){let{enc:i,ct:a}=J(e),s=await q(t,n,i,r,a);if(s.length!==32)throw new o("unopenable","the request's key is not 32 bytes");return s}function I(e){return h.encode(`pbt1\0${e}`)}async function te(e,t,n,r){let i=r?d(r):crypto.getRandomValues(y(12)),a=JSON.stringify(n);if(a===void 0)throw new o("malformed",`${t}: an encrypted field holds a JSON value`);let s=await b("encrypt",e,i,I(t),h.encode(a));return K+x(f(i,s))}function F(e){return typeof e=="string"&&e.startsWith(K)}async function ne(e,t,n){if(!F(n))throw new o("unopenable",`${t} is not an encrypted field`);let r;try{r=w(n.slice(K.length))}catch{throw new o("unopenable",`${t} is not an encrypted field`)}if(r.length<28)throw new o("unopenable",`${t} is too short to be an encrypted field`);let i;try{i=await b("decrypt",e,r.subarray(0,12),I(t),r.subarray(12))}catch{throw new o("unopenable",`${t} does not open: changed, moved from another field, or another request's`)}try{return JSON.parse(P.decode(i))}catch{throw new o("unopenable",`${t} opens to no JSON value`)}}function D(e){return e.replace(/~/g,"~0").replace(/\//g,"~1").replace(/\*/g,"~2")}function G(e){return e.replace(/~2/g,"*").replace(/~1/g,"/").replace(/~0/g,"~")}var M=Symbol("items");function W(e,t){if(!(e!==t&&!e.startsWith(t+"/")))return e===t?[]:e.slice(t.length+1).split("/").map(n=>n==="*"?M:G(n))}async function re(e,t,n,r){let i=e;for(let a of n){let s=W(a,t);s!==void 0&&(i=await A(i,s,t,r))}return i}async function A(e,t,n,r){if(t.length===0)return e===void 0?void 0:r(n,e);let[i,...a]=t;if(i===M){if(!Array.isArray(e))return e;let c=[];for(let[u,p]of e.entries())c.push(await A(p,a,`${n}/${u}`,r));return c}if(Array.isArray(e)){if(!/^(0|[1-9][0-9]*)$/.test(i)||Number(i)>=e.length)return e;let c=[...e];return c[Number(i)]=await A(c[Number(i)],a,`${n}/${i}`,r),c}if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,i))return e;let s={...e};return s[i]=await A(s[i],a,`${n}/${D(i)}`,r),s}function ie(){return x(crypto.getRandomValues(y(16)))}async function se(e,t,n,r){let i,a=!1;try{i=w(e.payload);let u=await l().importKey("raw",w(t),{name:"Ed25519"},!1,["verify"]);a=await l().verify({name:"Ed25519"},u,w(e.signature),i)}catch{throw new o("unverified","the project's key list does not verify")}if(!a)throw new o("unverified","the project's key list is not signed with the project's key");let s;try{s=JSON.parse(P.decode(i))}catch{throw new o("unverified","the project's key list is no JSON")}if(s.v!==1||s.project!==n||typeof s.issued_at!="string"||!Array.isArray(s.keys)||s.keys.length===0)throw new o("unverified","the key list is not this project's, or holds no key");if(s.nonce!==r)throw new o("unverified","the key list was not asked for just now: its nonce is not the one sent");let c=s.keys.map(u=>{if(typeof u.kid!="string"||!/^t[1-9][0-9]{0,5}$/.test(u.kid)||typeof u.key!="string")throw new o("unverified","a key of the list is malformed");let p=w(u.key);if(p.length!==32)throw new o("unverified","a key of the list is not an X25519 public key");return{kid:u.kid,key:p}});return{project:s.project,issuedAt:s.issued_at,keys:c}}export{E as a,z as b,o as c,w as d,Z as e,Q as f,Y as g,J as h,ee as i,te as j,F as k,ne as l,D as m,G as n,re as o,ie as p,se as q};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.37.1 — Palbase SDK License (see LICENSE) */
2
- import{b as R}from"./MW7YMYNO.js";import{a as m,c as G,d as X,e as Z,f as Q,h as ee,i as te,j as A,k as ne,l as re,o as P}from"./GCVJJS4Y.js";import{a as se}from"./H6LQPKWU.js";import{a as U,b as C,c as L,d as $,e as N,f as I,h as F,i as D,j as W,k as B,l as H,m as q,n as z,o as V}from"./I6H2425X.js";import{a as J,b as Y}from"./PMT4A5UW.js";import{b as T,d as v}from"./IZ6RIKPB.js";var f=class extends Error{status=400;code;data;constructor(e,t,r={}){super(t),this.name="TransitRefusal",this.code=e,this.data=r}},Te=6e4,Ae=1e3;function x(n){return/^t[1-9][0-9]{0,5}$/.test(n)?Number(n.slice(1)):0}var k=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(t=>new Promise(r=>setTimeout(r,t)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Te),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let t=this.now();try{let r=await this.opts.fetch(e),s=new Map;for(let i of r.keys){let o=X(i.key);s.set(i.id,{privateKey:o,publicKey:this.keys.get(i.id)?.publicKey??await Z(o)})}this.keys=s,this.order=r.keys.map(i=>i.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=t}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(x),...[...this.retired].map(x))}async key(e){let t=this.now();for(;x(e)>this.newest()&&this.heldFrom<t;){let i=this.fetchedAt+Ae-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let r=this.keys.get(e),s=this.current();if(this.retired.has(e))throw new f("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:s});if(r===void 0)throw new f("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:s});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new f("encryption_required",`this route carries encrypted fields: the request names its key in ${m}`,{field:m,current:this.current()});let t;try{t=ee(e.header).kid}catch{throw new f("encryption_unopenable",`${m} is not one`,{field:m})}let r=await this.key(t),s;try{s=Q(this.projectId,e.method,e.path,e.params??[])}catch{throw new f("encryption_unopenable","the request's path holds a value no key is sealed for",{field:m})}try{return new S(t,await te(e.header,r.privateKey,r.publicKey,s))}catch(i){throw i instanceof G?new f("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:m}):i}}},S=class{kid;key;constructor(e,t){this.kid=e,this.key=t}async open(e,t,r){return P(e,t,r,async(s,i)=>{if(!ne(i))throw new f("encryption_required",`${s} is an encrypted field: it came plain`,{field:s});try{return await re(this.key,s,i)}catch{throw new f("encryption_unopenable",`${s} does not open: changed, moved from another field, or another request's`,{field:s})}})}async seal(e,t){return P(e,"/response",t,(r,s)=>A(this.key,r,s))}sealField(e,t){return A(this.key,e,t)}};var Pe=/^pb_[a-z0-9]+_s/;function O(n){if(se())throw new TypeError("palbase/server runs on a server: 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");if(typeof n.secretKey!="string"||!Pe.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=Y(v({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??J),t=q.client(e);return{ai:U.client(e),analytics:C.client(e),auth:L.client(e),cache:$.client(e),calls:N.client(e),fields:new R({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:I.client(e),machines:F.client(e),messaging:D.client(e),notify:W.client(e),purchases:B.client(e),realtime:H.client(e),secrets:t,storage:z.client(e),stores:V.client(e),transit:new k({fetch:async r=>(await t.getTransitKeys({signal:r})).data}),transport:e,url:new URL(n.url).origin}}var h=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},xe=300,Oe=/^[0-9]{1,12}$/,je=/^[0-9a-f]{64}$/,ie=8,Me=/^whsec_[0-9A-Za-z]{32,}$/,Ke=1024*1024;async function oe(n){if(typeof n.secret!="string"||!Me.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await ae(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(de(n.body)))}catch{throw new h("invalid_body","the signed body is not JSON")}if(!Ie(e))throw new h("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function ae(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=de(n.body),{t,v1:r}=ce(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",s,Ne(new TextEncoder().encode(`${t}.`),e))),o=!1;for(let d of r)$e(i,Le(d))&&(o=!0);if(!o)throw new h("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function ce(n){let e=n.toleranceSeconds??xe;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new h("missing_signature","the request carries no Palbase-Signature header");let s,i=[];for(let o of r.split(",")){let d=o.indexOf("=");if(d<=0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=o.slice(0,d).trim(),a=o.slice(d+1).trim();if(c==="t"){if(s!==void 0||!Oe.test(a))throw new h("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=a}else if(c==="v1"){if(!je.test(a))throw new h("malformed_signature","a v1 is 64 lowercase hex characters");if(i.length===ie)throw new h("malformed_signature",`Palbase-Signature carries at most ${ie} v1`);i.push(a)}}if(s===void 0||i.length===0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new h("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:i}}async function Ue(n,e,t={}){let r=await Ce(n,t.maxBytes??Ke);return oe({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function Ce(n,e){let t=()=>new h("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),i=[],o=0;for(;;){let{done:a,value:l}=await s.read();if(a)break;if(o+=l.byteLength,o>e)throw await s.cancel().catch(()=>{}),t();i.push(l)}let d=new Uint8Array(o),c=0;for(let a of i)d.set(a,c),c+=a.byteLength;return d}function de(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function Le(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function $e(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function Ne(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function Ie(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var ue=60,Fe=60,De=8*1024,We=1e5;function j(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fe(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function le(n){let e=fe(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var E=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=We){this.max=e}spend(e,t){if(t>=e.until)throw new u("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new u("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,i]of t){if(i>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[i,o]of s)o>e||(s.delete(i),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function Be(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function he(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function pe(n,e,t,r){let s=_e=>{throw new u("proof",`the DPoP proof is not taken: ${_e}`)},i=t.proof;if(!i)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(i.length>De)return s("it is too long");let o=i.split(".");if(o.length!==3)return s("it is not a JWS of three parts");let d=le(o[0]),c=le(o[1]);if(!d||!c)return s("its header or claims are not base64url JSON");if(d.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(d.alg!=="ES256")return s(`it is signed with ${String(d.alg)}; only ES256 is taken`);let a=d.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return s("its header carries no P-256 public key");if("d"in a)return s("its header carries a private key");if(await Be(a.x,a.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let y=fe(o[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${o[0]}.${o[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let p=typeof c.htu=="string"?he(c.htu):void 0,g=he(t.url);if(!p||!g||p!==g)return s(`it is for ${String(c.htu)}, not ${g??t.url}`);let ve=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-ve)>ue)return s("it was not made within a minute of now");let Se=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==Se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let Ee=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:Ee,until:(c.iat+ue+Fe)*1e3+1}}var u=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},w=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},He=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function qe(n){return async e=>{let t=v({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof T&&r.status===401&&!He.has(r.code))return!1;throw new w("a session's standing could not be told",{cause:r})}}}var M={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},ye=60,ze=16*1024,Ve=10*6e4,Je=5e4,ge=n=>typeof n=="string"&&Object.hasOwn(M,n),K=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new E;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>ze)throw new u("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new u("malformed","the token is not a JWS of three parts");let s=me(r[0]),i=me(r[1]);if(!s||!i)throw new u("malformed","the token header or claims are not base64url JSON");let o=s.alg;if(!ge(o))throw new u("algorithm",`the token is signed with ${String(o)}; only ES256 and PS256 are taken`);let d=s.kid;if(typeof d!="string"||d==="")throw new u("malformed","the token header names no kid");let c=await this.key(d);if(!c)throw new u("unknown_key",`no key ${d} in the project's key set`);if(c.alg!==o)throw new u("algorithm",`key ${d} is ${c.alg}, the token says ${o}`);let a=be(r[2]);if(!a)throw new u("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(M[c.alg].verify,c.key,a,l).catch(()=>!1))throw new u("signature","the signature does not verify");let b=this.check(i),p=i.cnf,g;if(p!==void 0){if(!t)throw new u("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof p!="object"||p===null||typeof p.jkt!="string"||p.jkt==="")throw new u("bound","the token is bound to a key it does not name (cnf.jkt)");g=await pe(e,p.jkt,t,this.now())}else if(t)throw new u("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,b.sessionId))throw new u("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return g&&this.seenProofs.spend(g,this.now()),b}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:Ge(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new u("malformed","the Authorization header is not a Bearer or DPoP token");let i=s[1].toLowerCase()==="dpop",o=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],i?{proof:t.get("dpop"),method:e.method,url:we(t,o)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let i=this.asking.get(t);i||(i=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,i));let o;try{o=await i}catch(c){let a=this.standings.get(t),l=this.now();if(a&&l<a.at+this.standingStaleMs)return a.until=Math.min(l+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new w("a session's standing cannot be read now",{cause:c})}let d=this.now();return this.standings.delete(t),this.standings.set(t,{live:o,at:d,until:d+this.standingTtlMs}),this.standings.size>Je&&this.standings.delete(this.standings.keys().next().value),o}check(e){if(e.iss!==this.issuer)throw new u("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new u("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new u("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+ye<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-ye>r))throw new u("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new u("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new u("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new u("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Ve;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new w("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(i){if(!s)throw i}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(i){throw this.lastFailure=i,new w("the project's key set cannot be read now",{cause:i})}this.lastFailure=void 0;let r=new Map;for(let i of Array.isArray(e.keys)?e.keys:[]){let o=i.alg;if(typeof i.kid!="string"||!ge(o))continue;let d=M[o];if(i.kty!==d.kty||i.use!==void 0&&i.use!=="sig")continue;let{d:c,...a}=i;try{r.set(i.kid,{alg:o,key:await crypto.subtle.importKey("jwk",a,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Xe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function we(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Ye.test(s)?`${r}://${s}${e.pathname}`:""}var Ye=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function Ge(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Xe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function be(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function me(n){let e=be(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Ze(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var _=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Qe(n,e,t,r){let{idempotencyKey:s,amount:i,ttlSeconds:o,metadata:d}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:i,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...o!==void 0?{ttl_seconds:o}:{},...d!==void 0?{metadata:d}:{}},a=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(a.status!=="held")throw new _(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(b){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),b}return await n.purchases.commitSpend({path:l}),y}async function*et(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,nt=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function ke(n){return!tt.test(n)||nt.test(n)||/_PROXY$/i.test(n)}var rt=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function st(n){return rt.test(n)}async function it(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let i=O({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:o}=await i.secrets.getEnvironmentValues({path:{environment:t}}),d=[],c=[],a=[];for(let[l,y]of Object.entries(o.values)){if(ke(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,d.push(l)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:a.sort()}}export{f as a,k as b,S as c,O as d,h as e,oe as f,ae as g,ce as h,Ue as i,u as j,w as k,qe as l,K as m,we as n,Ze as o,_ as p,Qe as q,et as r,ke as s,st as t,it as u};
1
+ /*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
2
+ import{b as R}from"./UBQK5O7J.js";import{a as m,c as G,d as X,e as Z,f as Q,h as ee,i as te,j as A,k as ne,l as re,o as P}from"./YLLZC52Q.js";import{a as se}from"./HMDMAILZ.js";import{a as U,b as C,c as L,d as $,e as N,f as I,h as F,i as D,j as W,k as B,l as H,m as q,n as z,o as V}from"./L3S7O5FQ.js";import{a as J,b as Y}from"./LANEQ73A.js";import{b as T,d as v}from"./4Y47I6LA.js";var f=class extends Error{status=400;code;data;constructor(e,t,r={}){super(t),this.name="TransitRefusal",this.code=e,this.data=r}},Te=6e4,Ae=1e3;function x(n){return/^t[1-9][0-9]{0,5}$/.test(n)?Number(n.slice(1)):0}var k=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(t=>new Promise(r=>setTimeout(r,t)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Te),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let t=this.now();try{let r=await this.opts.fetch(e),s=new Map;for(let i of r.keys){let o=X(i.key);s.set(i.id,{privateKey:o,publicKey:this.keys.get(i.id)?.publicKey??await Z(o)})}this.keys=s,this.order=r.keys.map(i=>i.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=t}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(x),...[...this.retired].map(x))}async key(e){let t=this.now();for(;x(e)>this.newest()&&this.heldFrom<t;){let i=this.fetchedAt+Ae-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let r=this.keys.get(e),s=this.current();if(this.retired.has(e))throw new f("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:s});if(r===void 0)throw new f("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:s});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new f("encryption_required",`this route carries encrypted fields: the request names its key in ${m}`,{field:m,current:this.current()});let t;try{t=ee(e.header).kid}catch{throw new f("encryption_unopenable",`${m} is not one`,{field:m})}let r=await this.key(t),s;try{s=Q(this.projectId,e.method,e.path,e.params??[])}catch{throw new f("encryption_unopenable","the request's path holds a value no key is sealed for",{field:m})}try{return new S(t,await te(e.header,r.privateKey,r.publicKey,s))}catch(i){throw i instanceof G?new f("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:m}):i}}},S=class{kid;key;constructor(e,t){this.kid=e,this.key=t}async open(e,t,r){return P(e,t,r,async(s,i)=>{if(!ne(i))throw new f("encryption_required",`${s} is an encrypted field: it came plain`,{field:s});try{return await re(this.key,s,i)}catch{throw new f("encryption_unopenable",`${s} does not open: changed, moved from another field, or another request's`,{field:s})}})}async seal(e,t){return P(e,"/response",t,(r,s)=>A(this.key,r,s))}sealField(e,t){return A(this.key,e,t)}};var Pe=/^pb_[a-z0-9]+_s/;function O(n){if(se())throw new TypeError("palbase/server runs on a server: 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");if(typeof n.secretKey!="string"||!Pe.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=Y(v({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??J),t=q.client(e);return{ai:U.client(e),analytics:C.client(e),auth:L.client(e),cache:$.client(e),calls:N.client(e),fields:new R({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:I.client(e),machines:F.client(e),messaging:D.client(e),notify:W.client(e),purchases:B.client(e),realtime:H.client(e),secrets:t,storage:z.client(e),stores:V.client(e),transit:new k({fetch:async r=>(await t.getTransitKeys({signal:r})).data}),transport:e,url:new URL(n.url).origin}}var h=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},xe=300,Oe=/^[0-9]{1,12}$/,je=/^[0-9a-f]{64}$/,ie=8,Me=/^whsec_[0-9A-Za-z]{32,}$/,Ke=1024*1024;async function oe(n){if(typeof n.secret!="string"||!Me.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await ae(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(de(n.body)))}catch{throw new h("invalid_body","the signed body is not JSON")}if(!Ie(e))throw new h("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function ae(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=de(n.body),{t,v1:r}=ce(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",s,Ne(new TextEncoder().encode(`${t}.`),e))),o=!1;for(let d of r)$e(i,Le(d))&&(o=!0);if(!o)throw new h("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function ce(n){let e=n.toleranceSeconds??xe;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new h("missing_signature","the request carries no Palbase-Signature header");let s,i=[];for(let o of r.split(",")){let d=o.indexOf("=");if(d<=0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=o.slice(0,d).trim(),a=o.slice(d+1).trim();if(c==="t"){if(s!==void 0||!Oe.test(a))throw new h("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=a}else if(c==="v1"){if(!je.test(a))throw new h("malformed_signature","a v1 is 64 lowercase hex characters");if(i.length===ie)throw new h("malformed_signature",`Palbase-Signature carries at most ${ie} v1`);i.push(a)}}if(s===void 0||i.length===0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new h("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:i}}async function Ue(n,e,t={}){let r=await Ce(n,t.maxBytes??Ke);return oe({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function Ce(n,e){let t=()=>new h("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),i=[],o=0;for(;;){let{done:a,value:l}=await s.read();if(a)break;if(o+=l.byteLength,o>e)throw await s.cancel().catch(()=>{}),t();i.push(l)}let d=new Uint8Array(o),c=0;for(let a of i)d.set(a,c),c+=a.byteLength;return d}function de(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function Le(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function $e(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function Ne(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function Ie(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var ue=60,Fe=60,De=8*1024,We=1e5;function j(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fe(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function le(n){let e=fe(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var E=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=We){this.max=e}spend(e,t){if(t>=e.until)throw new u("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new u("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,i]of t){if(i>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[i,o]of s)o>e||(s.delete(i),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function Be(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function he(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function pe(n,e,t,r){let s=_e=>{throw new u("proof",`the DPoP proof is not taken: ${_e}`)},i=t.proof;if(!i)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(i.length>De)return s("it is too long");let o=i.split(".");if(o.length!==3)return s("it is not a JWS of three parts");let d=le(o[0]),c=le(o[1]);if(!d||!c)return s("its header or claims are not base64url JSON");if(d.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(d.alg!=="ES256")return s(`it is signed with ${String(d.alg)}; only ES256 is taken`);let a=d.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return s("its header carries no P-256 public key");if("d"in a)return s("its header carries a private key");if(await Be(a.x,a.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let y=fe(o[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${o[0]}.${o[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let p=typeof c.htu=="string"?he(c.htu):void 0,g=he(t.url);if(!p||!g||p!==g)return s(`it is for ${String(c.htu)}, not ${g??t.url}`);let ve=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-ve)>ue)return s("it was not made within a minute of now");let Se=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==Se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let Ee=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:Ee,until:(c.iat+ue+Fe)*1e3+1}}var u=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},w=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},He=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function qe(n){return async e=>{let t=v({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof T&&r.status===401&&!He.has(r.code))return!1;throw new w("a session's standing could not be told",{cause:r})}}}var M={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},ye=60,ze=16*1024,Ve=10*6e4,Je=5e4,ge=n=>typeof n=="string"&&Object.hasOwn(M,n),K=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new E;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>ze)throw new u("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new u("malformed","the token is not a JWS of three parts");let s=me(r[0]),i=me(r[1]);if(!s||!i)throw new u("malformed","the token header or claims are not base64url JSON");let o=s.alg;if(!ge(o))throw new u("algorithm",`the token is signed with ${String(o)}; only ES256 and PS256 are taken`);let d=s.kid;if(typeof d!="string"||d==="")throw new u("malformed","the token header names no kid");let c=await this.key(d);if(!c)throw new u("unknown_key",`no key ${d} in the project's key set`);if(c.alg!==o)throw new u("algorithm",`key ${d} is ${c.alg}, the token says ${o}`);let a=be(r[2]);if(!a)throw new u("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(M[c.alg].verify,c.key,a,l).catch(()=>!1))throw new u("signature","the signature does not verify");let b=this.check(i),p=i.cnf,g;if(p!==void 0){if(!t)throw new u("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof p!="object"||p===null||typeof p.jkt!="string"||p.jkt==="")throw new u("bound","the token is bound to a key it does not name (cnf.jkt)");g=await pe(e,p.jkt,t,this.now())}else if(t)throw new u("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,b.sessionId))throw new u("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return g&&this.seenProofs.spend(g,this.now()),b}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:Ge(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new u("malformed","the Authorization header is not a Bearer or DPoP token");let i=s[1].toLowerCase()==="dpop",o=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],i?{proof:t.get("dpop"),method:e.method,url:we(t,o)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let i=this.asking.get(t);i||(i=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,i));let o;try{o=await i}catch(c){let a=this.standings.get(t),l=this.now();if(a&&l<a.at+this.standingStaleMs)return a.until=Math.min(l+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new w("a session's standing cannot be read now",{cause:c})}let d=this.now();return this.standings.delete(t),this.standings.set(t,{live:o,at:d,until:d+this.standingTtlMs}),this.standings.size>Je&&this.standings.delete(this.standings.keys().next().value),o}check(e){if(e.iss!==this.issuer)throw new u("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new u("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new u("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+ye<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-ye>r))throw new u("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new u("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new u("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new u("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Ve;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new w("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(i){if(!s)throw i}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(i){throw this.lastFailure=i,new w("the project's key set cannot be read now",{cause:i})}this.lastFailure=void 0;let r=new Map;for(let i of Array.isArray(e.keys)?e.keys:[]){let o=i.alg;if(typeof i.kid!="string"||!ge(o))continue;let d=M[o];if(i.kty!==d.kty||i.use!==void 0&&i.use!=="sig")continue;let{d:c,...a}=i;try{r.set(i.kid,{alg:o,key:await crypto.subtle.importKey("jwk",a,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Xe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function we(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Ye.test(s)?`${r}://${s}${e.pathname}`:""}var Ye=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function Ge(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Xe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function be(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function me(n){let e=be(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Ze(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var _=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Qe(n,e,t,r){let{idempotencyKey:s,amount:i,ttlSeconds:o,metadata:d}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:i,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...o!==void 0?{ttl_seconds:o}:{},...d!==void 0?{metadata:d}:{}},a=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(a.status!=="held")throw new _(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(b){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),b}return await n.purchases.commitSpend({path:l}),y}async function*et(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,nt=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function ke(n){return!tt.test(n)||nt.test(n)||/_PROXY$/i.test(n)}var rt=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function st(n){return rt.test(n)}async function it(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let i=O({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:o}=await i.secrets.getEnvironmentValues({path:{environment:t}}),d=[],c=[],a=[];for(let[l,y]of Object.entries(o.values)){if(ke(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,d.push(l)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:a.sort()}}export{f as a,k as b,S as c,O as d,h as e,oe as f,ae as g,ce as h,Ue as i,u as j,w as k,qe as l,K as m,we as n,Ze as o,_ as p,Qe as q,et as r,ke as s,st as t,it as u};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.37.1 — Palbase SDK License (see LICENSE) */
2
- import{b as d,m as k}from"./GCVJJS4Y.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
1
+ /*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
2
+ import{b as d,m as k}from"./YLLZC52Q.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- /*! palbase 0.37.1 — Palbase SDK License (see LICENSE) */
2
+ /*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
3
3
  var Ub=Object.defineProperty;var We=(e,t)=>{for(var n in t)Ub(e,n,{get:t[n],enumerable:!0})};import{parseArgs as Pw}from"node:util";var zb=Symbol.for("palbase.data"),Bb=globalThis,sp=Bb[zb]??=new WeakSet;function Fb(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function Oa(e){let t=[e];for(;t.length>0;){let n=t.pop();if(!(typeof n!="object"||n===null||sp.has(n)||Fb(n))){sp.add(n);for(let s of Array.isArray(n)?n:Object.values(n))t.push(s)}}return e}var Jb="X-PoW-Challenge-ID",Wb="X-PoW-Nonce";function ap(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:s,difficulty:a}=t.challenge;return typeof n!="string"||typeof s!="string"||typeof a!="number"||!Number.isInteger(a)||a<0?null:{id:n,prefix:s,difficulty:a}}function Vb(e){return 8*2**e}var Wn;async function Hb(){if(Wn)return Wn;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let s=(await import("node:crypto")).createHash;if(typeof s=="function")return Wn=a=>new Uint8Array(s("sha256").update(a).digest()),Wn}catch{}let t=new TextEncoder;return Wn=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),Wn}function Yb(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var Xb=4096,Zb=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function rp(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await Hb(),s=Vb(e.difficulty),a=Date.now()+(t.timeLimitMs??12e4);for(let r=0;r<s;r++){if(r%Xb===0&&r>0){if(await Zb(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>a)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${r} attempts`)}let i=n(e.prefix+r),o=i instanceof Uint8Array?i:await i;if(Yb(o)>=e.difficulty)return{[Jb]:e.id,[Wb]:String(r)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${s} attempts`)}var j=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="PalbaseError",this.op=t.op,this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.retryAfter=t.retryAfter,this.body=t.body}};function c(e,t,n){let s=String(n);if(s===""||s==="."||s==="..")throw new j({op:e,status:0,code:"invalid_path_parameter",message:`${e}: ${t} cannot be ${s===""?"empty":JSON.stringify(s)}`});return encodeURIComponent(s)}var Qb=new Set(["apikey","authorization"]),ew=64*1024;function vi(e){let t=Ma(e.baseUrl),n=e.fetch??globalThis.fetch,s=e.solveProofOfWork??!0,a=async(r,i)=>{let o=sw(t,r),l=new Headers;for(let[b,w]of Object.entries(r.headers??{}))w!=null&&!Qb.has(b.toLowerCase())&&l.set(b,String(w));for(let[b,w]of Object.entries(i))l.set(b,w);await aw(r,e.credentials,l),l.has("accept")||l.set("accept","application/json");let d={method:r.method,headers:l,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(l.set("content-type",r.body.contentType),d.body=rw(r.body.kind,r.body.value),Vn(d.body)||(d.duplex="half"));let p;try{p=r.onUploadProgress&&e.xmlHttpRequest?await tw(e.xmlHttpRequest,r.op,o,d,r.onUploadProgress):await n(o,d)}catch(b){throw r.signal?.aborted||b instanceof j?b:new j({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${t.origin}`,cause:b})}let u=r.answers[p.status]??(r.ownResponse&&p.status>=200&&p.status<300?"raw":void 0);if(u===void 0)throw p.status>=200&&p.status<300?(await p.body?.cancel(),new j({op:r.op,status:p.status,code:"undeclared_answer",message:`${r.op}: the server answered ${p.status}, which its contract does not declare; the request may have taken effect`})):await ow(r.op,p);let m;switch(u){case"json":try{m=Oa(await p.json())}catch(b){throw new j({op:r.op,status:p.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:b})}break;case"raw":m=p;break;default:await p.body?.cancel(),m=void 0}return{status:p.status,data:m,headers:p.headers}};return{async send(r){try{return await a(r,{})}catch(i){let o=s&&i instanceof j&&i.status===403?ap(i.body):null,l=r.body?.value;if(!o||r.body?.kind==="raw"&&!Vn(l))throw i;let d=i,p;try{p=await rp(o,{signal:r.signal})}catch(u){throw r.signal?.aborted?u:new j({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${u instanceof Error?u.message:String(u)}`,requestId:d.requestId,body:d.body,cause:u})}return a(r,p)}}}}function tw(e,t,n,s,a){return new Promise((r,i)=>{let o=s.signal;if(o?.aborted)return i(o.reason);let l=new e,d=()=>l.abort();o?.addEventListener("abort",d,{once:!0});let p=u=>{o?.removeEventListener("abort",d),u()};l.open(s.method??"GET",n.href),l.responseType="arraybuffer",new Headers(s.headers).forEach((u,m)=>l.setRequestHeader(m,u)),l.upload&&(l.upload.onprogress=u=>{u.lengthComputable&&a(u.loaded,u.total)}),l.onload=()=>p(()=>{if(l.responseURL!==""&&l.responseURL!==n.href){i(new j({op:t,status:0,code:"undeclared_redirect",message:`${t}: the server redirected; the answer is another address's, and was not read`}));return}if(l.status<200||l.status>599)return i(new TypeError(`${t}: answered ${l.status}`));let u=l.status===204||l.status===205||l.status===304;r(new Response(u?null:l.response,{status:l.status,statusText:l.statusText,headers:nw(l.getAllResponseHeaders())}))}),l.onerror=()=>p(()=>i(new TypeError(`${t}: the request failed`))),l.onabort=()=>p(()=>i(o?.reason??new DOMException("The request was aborted","AbortError"))),l.send(s.body)})}function nw(e){let t=new Headers;for(let n of e.split(/\r?\n/)){let s=n.indexOf(":");if(!(s<=0))try{t.append(n.slice(0,s).trim(),n.slice(s+1).trim())}catch{}}return t}function Ma(e){let t;try{t=new URL(e)}catch{throw new TypeError(`baseUrl ${JSON.stringify(e)} is not an absolute URL`)}let n=t.hostname==="localhost"||t.hostname.endsWith(".localhost")||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${t.origin}`);if(t.username||t.password||t.search||t.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(t.pathname!=="/"&&t.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return t}function sw(e,t){if(!t.path.startsWith("/")||t.path.startsWith("//"))throw new j({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path ${JSON.stringify(t.path)} is not absolute`});let n=new URL(t.path+iw(t.query),e);if(n.origin!==e.origin)throw new j({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path leaves the project's origin`});return n}async function aw(e,t,n){if(e.auth.length===0)return;let s=e.auth.some(i=>i.includes("userJWT"))?await t.accessToken?.():void 0,a=i=>{switch(i){case"ApiKeyAuth":return!!(t.publishableKey??t.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(t.secretKey??t.token);case"PalbaseBearer":return!!t.token;case"userJWT":return!!s&&!t.token;default:return!1}},r=e.auth.filter(i=>i.every(a)).reduce((i,o)=>i===void 0||o.length>i.length?o:i,void 0);if(!r)throw new j({op:e.op,status:0,code:"missing_credential",message:`${e.op} needs one of: ${e.auth.map(i=>i.length===0?"nothing":i.join(" + ")).join(" | ")}`});for(let i of r)i==="ApiKeyAuth"?n.set("apikey",t.publishableKey??t.secretKey):(i==="SecretKeyAuth"||i==="AdminAuth"||i==="PalbaseBearer")&&t.token?n.set("authorization",`Bearer ${t.token}`):i==="SecretKeyAuth"||i==="AdminAuth"?n.set("apikey",t.secretKey):i==="userJWT"&&n.set("authorization",`Bearer ${s}`)}function rw(e,t){switch(e){case"json":return JSON.stringify(t);case"form":{let n=new URLSearchParams;for(let[s,a]of Object.entries(t))_i(n,s,a);return n}case"raw":return t}}function Vn(e){return!!(e==null||typeof e=="string"||e instanceof URLSearchParams||e instanceof Blob||e instanceof FormData||e instanceof ArrayBuffer||ArrayBuffer.isView(e))}function iw(e){if(!e)return"";let t=new URLSearchParams;for(let[s,a]of Object.entries(e))_i(t,s,a);let n=t.toString();return n===""?"":`?${n}`}function _i(e,t,n){if(n!=null){if(Array.isArray(n)){for(let s of n)_i(e,t,s);return}if(n instanceof Date){e.append(t,n.toISOString());return}e.append(t,typeof n=="object"?JSON.stringify(n):String(n))}}async function ow(e,t){let n=await lw(t,ew).catch(()=>""),s;try{s=n===""?void 0:JSON.parse(n)}catch{s=n}let a=pw(s)?s:void 0,r=Number(t.headers.get("retry-after")),i=t.status>=300&&t.status<400;return new j({op:e,status:t.status,code:a?.error??(i?"undeclared_redirect":`http_${t.status}`),message:a?.error_description??(i?`${e}: the server redirected (${t.status}); the request was not followed, its credentials stay here`:`${e}: ${t.status} ${t.statusText}`.trim()),requestId:a?.request_id??t.headers.get("x-request-id")??void 0,retryAfter:a?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:s})}async function lw(e,t){if(!e.body)return"";let n=e.body.getReader(),s=[],a=0;for(;a<t;){let{done:o,value:l}=await n.read();if(o)break;s.push(l),a+=l.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(a,t)),i=0;for(let o of s){let l=Math.min(o.byteLength,r.byteLength-i);if(r.set(o.subarray(0,l),i),i+=l,i>=r.byteLength)break}return new TextDecoder().decode(r)}function pw(e){return typeof e=="object"&&e!==null&&typeof e.error=="string"}var xa={project:{type:"string",short:"P",value:"project",description:"the project (name or id; org/project when the name is in two organizations)"},env:{type:"string",short:"E",value:"env",description:"the project's environment (slug or ref)"},json:{type:"boolean",description:"print the answer as JSON"},"non-interactive":{type:"boolean",description:"never ask: refuse what would need a question"},yes:{type:"boolean",short:"y",description:"confirm a change to a production environment without asking"},debug:{type:"boolean",description:"print each request the command sends"},help:{type:"boolean",short:"h",description:"show help"}};var y=class extends Error{exitCode;hint;code;reported;constructor(t,n,s={}){super(n),this.name="CliError",this.code=t,this.hint=s.hint,this.exitCode=s.exitCode??1,this.reported=s.reported??!1}};function g(e,t){return new y("usage",e,{hint:t,exitCode:2})}var Ia=class{io;json;constructor(t,n){this.io=t,this.json=n}result(t,n){this.json?this.io.stdout(`${JSON.stringify(t,null,2)}
4
4
  `):n()}line(t=""){this.io.stdout(`${K(t)}
5
5
  `)}note(t){this.io.stderr(`${K(t)}
@@ -9,7 +9,7 @@ var Ub=Object.defineProperty;var We=(e,t)=>{for(var n in t)Ub(e,n,{get:t[n],enum
9
9
  `);let i;try{i=await this.io.fetch(t,{method:n.method,headers:{...n.headers,...a},body:n.body,signal:n.signal,...s?{}:{duplex:"half"},redirect:"manual"})}catch(l){throw n.signal?.aborted?l:new y("network_error",`${new URL(t).origin} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(this.debug&&this.io.stderr(`< ${i.status} ${i.headers.get("x-request-id")??""}
10
10
  `),i.status!==503||!s||r>=kw||!_w.has(await $i(i)??""))return i;await i.body?.cancel();let o=Number(i.headers.get("retry-after")??"");await this.io.sleep((Number.isFinite(o)&&o>0?Math.min(o,30):1)*1e3)}}async exchange(t,n,s){let a=await this.token(),r=await this.send(t,n,s,a.value);if(r.status===401&&a.renewable){let i=await this.renew(await this.currentSession());r=await this.send(t,n,s,i.access_token)}return{res:r,renewable:a.renewable}}async answered(t,n,s,a){if(s.status===204)return;let r=await s.text(),i=r===""?void 0:Sw(r);if(s.ok)return i;let o=i??{};throw s.status===401?o.error==="token_not_for_machines"?_p(new URL(this.cloud.studioApi).host):a?Hn():this.tokenRefused("Studio"):new j({op:`${t} ${n}`,status:s.status,code:o.error??`http_${s.status}`,message:o.error_description??`Studio answered ${s.status}`,requestId:o.request_id??s.headers.get("x-request-id")??void 0,body:i})}tokenRefused(t){return(this.io.env.PALBASE_TOKEN??"").startsWith("pbe_")?new y("token_refused",`${t} refused PALBASE_TOKEN, an environment's token: it ended (a few hours at most), it was revoked, or what minted it no longer holds`,{hint:"mint another: palbase env:tokens:create --scope <scope> (an admin), or with the environment's secret key (Studio's POST /environments/{ref}/tokens)"}):(this.io.env.PALBASE_TOKEN??"").startsWith("pbu_")?new y("token_refused",`${t} refused PALBASE_TOKEN, an account token: it was revoked, it ended, or, in this organization, the one who made it left it`,{hint:"its maker makes a new one: palbase account:tokens:create <name>"}):new y("token_refused",`${t} refused PALBASE_TOKEN: it was revoked, it ended, or the one who made it no longer holds its role`,{hint:"an admin makes a new one: palbase tokens:create <name>"})}async token(){let t=this.io.env.PALBASE_TOKEN;return t&&t!==""?{value:t,renewable:!1}:{value:(await this.currentSession()).access_token,renewable:!0}}async renew(t){let n=await yp(this.io,this.cloud,t);return await this.state.writeSession(n),this.session=n,n}async send(t,n,s,a){let r=`${this.cloud.studioApi}${vw}${n}`;this.debug&&this.io.stderr(`> ${t} ${r}
11
11
  `);try{let i=await this.io.fetch(r,{method:t,headers:{...a===void 0?{}:{authorization:`Bearer ${a}`},accept:"application/json",...s===void 0?{}:{"content-type":"application/json"}},body:s===void 0?void 0:JSON.stringify(s),redirect:"manual"});return this.debug&&this.io.stderr(`< ${i.status} ${i.headers.get("x-request-id")??""}
12
- `),i}catch(i){throw new y("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${i instanceof Error?i.message:String(i)}`)}}};function _p(e){return new y("token_not_for_machines",`the platform's edge refused PALBASE_TOKEN at ${e}, taking it for a machine's address (token_not_for_machines): the token itself was not refused`,{hint:"nothing is wrong with the token: run this again in a few minutes, and tell Palbase if it lasts"})}async function $i(e){let t=await e.clone().json().catch(()=>null),n=t&&typeof t=="object"?t.error:void 0;return typeof n=="string"&&/^(console|token|edge)_/.test(n)?n:void 0}function Sw(e){try{return JSON.parse(e)}catch{return e}}var kp={version:"0.37.1"};var Ka=kp.version;async function Rp(e,t,n){let s=new Map(n.map(i=>[i.name,i])),a=e.includes("--json"),r=e.includes("--debug");try{let{name:i,at:o}=Aw(e);if(i===void 0)return e.includes("--version")?(t.stdout(`palbase ${Ka}
12
+ `),i}catch(i){throw new y("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${i instanceof Error?i.message:String(i)}`)}}};function _p(e){return new y("token_not_for_machines",`the platform's edge refused PALBASE_TOKEN at ${e}, taking it for a machine's address (token_not_for_machines): the token itself was not refused`,{hint:"nothing is wrong with the token: run this again in a few minutes, and tell Palbase if it lasts"})}async function $i(e){let t=await e.clone().json().catch(()=>null),n=t&&typeof t=="object"?t.error:void 0;return typeof n=="string"&&/^(console|token|edge)_/.test(n)?n:void 0}function Sw(e){try{return JSON.parse(e)}catch{return e}}var kp={version:"0.37.2"};var Ka=kp.version;async function Rp(e,t,n){let s=new Map(n.map(i=>[i.name,i])),a=e.includes("--json"),r=e.includes("--debug");try{let{name:i,at:o}=Aw(e);if(i===void 0)return e.includes("--version")?(t.stdout(`palbase ${Ka}
13
13
  `),0):(t.stdout(Ap(n)),e.length===0||e.includes("--help")||e.includes("-h")?0:2);if(i==="help"){let S=e[o+1],$=S===void 0?void 0:s.get(S);if(S!==void 0&&!$)throw Sp(S,n);return t.stdout($?Pp($):Ap(n)),0}let l=s.get(i);if(!l)throw Sp(i,n);let d=[...e.slice(0,o),...e.slice(o+1)];if(d.includes("--help")||d.includes("-h"))return t.stdout(Pp(l)),0;let{flags:p,positionals:u}=Rw(l,d),m=l.args??{min:0,max:0};if(u.length<m.min)throw g(`${l.name} needs ${m.min===1?"an argument":`${m.min} arguments`}`,Ai(l));if(u.length>m.max)throw g(`${l.name} takes ${m.max===0?"no argument":`at most ${m.max}`}: ${JSON.stringify(u.slice(m.max))} is left over`,Ai(l));let b={project:p.project,env:p.env,json:p.json===!0,nonInteractive:p["non-interactive"]===!0,yes:p.yes===!0,debug:p.debug===!0},w=up(t.env),_=new La(mp(t.configDir,w)),T={io:t,state:_,out:new Ia(t,b.json),global:b,args:u,flags:p,interactive:t.interactive&&!b.nonInteractive,cloud:w,studio:new Na(t,w,_,b.debug)};return await l.run(T)??0}catch(i){return Tw(i,t,a,r)}}function Aw(e){let t=new Set;for(let[n,s]of Object.entries(xa))s.type==="string"&&(t.add(`--${n}`),s.short&&t.add(`-${s.short}`));for(let n=0;n<e.length;n++){let s=e[n];if(s==="--")return{at:-1};if(t.has(s)){n++;continue}if(!s.startsWith("-"))return{name:s,at:n}}return{at:-1}}function Rw(e,t){let n={...xa,...e.flags??{}},s={};for(let[a,r]of Object.entries(n))s[a]={type:r.type,...r.short?{short:r.short}:{},...r.multiple?{multiple:!0}:{}};try{let{values:a,positionals:r}=Pw({args:t,options:s,strict:!0,allowPositionals:!0});return{flags:a,positionals:r}}catch(a){throw g(a instanceof Error?a.message.replace(/^.*?: /,""):String(a),`palbase help ${e.name}`)}}function Tw(e,t,n,s){let a="error",r,i,o=1,l;return e instanceof y?(a=e.code,r=e.message,i=e.hint,o=e.exitCode):e instanceof j?(a=e.code,r=e.message,l=e.requestId,e.code==="token_out_of_scope"&&t.env.PALBASE_TOKEN&&(r=`${e.op} refused PALBASE_TOKEN: ${e.message}`,i="this is the token's reach, fixed when it was minted: a person's yes does not change it \u2014 mint a token whose scopes name this call, or have a person run it signed in")):r=e instanceof Error?e.message:String(e),n&&e instanceof y&&e.reported||(n&&t.stdout(`${JSON.stringify({error:a,message:r,...i?{hint:i}:{},...l?{request_id:l}:{}},null,2)}
14
14
  `),t.stderr(`error: ${K(r)}${l?` (request ${K(l)})`:""}
15
15
  `),i&&t.stderr(` ${K(i)}
@@ -1,2 +1,2 @@
1
- /*! palbase 0.37.1 — Palbase SDK License (see LICENSE) */
2
- import{a as I}from"../chunks/H6LQPKWU.js";import{a as P,b as S,c as k,e as A,f as w,g as C,h as T,i as R,j,k as E,l as x,m as D,n as U,o as M}from"../chunks/I6H2425X.js";import{a as G,b as B}from"../chunks/PMT4A5UW.js";import{b as y,c as r,d as v}from"../chunks/IZ6RIKPB.js";import"../chunks/AYPQOPOF.js";import"../chunks/RAPT7CYO.js";function L(t){let e=P.client(t),a=S.client(t),s=k.client(t),p=A.client(t),g=w.client(t),m=C.client(t),i=T.client(t),d=R.client(t),l=j.client(t),n=E.client(t),h=x.client(t),c=D.client(t),u=U.client(t),o=M.client(t);return{ai:{draftAgent:e.draftAgent,listAgents:e.listAgents,getAgent:e.getAgent,putAgent:e.putAgent,deleteAgent:e.deleteAgent,publishAgent:e.publishAgent,rollbackAgent:e.rollbackAgent,listAgentVersions:e.listAgentVersions,listChats:e.listChats,createChat:e.createChat,getChat:e.getChat,deleteChat:e.deleteChat,decideChatApproval:e.decideChatApproval,forkChat:e.forkChat,getChatGoal:e.getChatGoal,setChatGoal:e.setChatGoal,clearChatGoal:e.clearChatGoal,updateChatGoal:e.updateChatGoal,putChatMember:e.putChatMember,deleteChatMember:e.deleteChatMember,listChatMessages:e.listChatMessages,sendChatMessage:e.sendChatMessage,getChatMessageAttachment:e.getChatMessageAttachment,listChatParts:e.listChatParts,putChatPipe:e.putChatPipe,deleteChatPipe:e.deleteChatPipe,sendSubagentMessage:e.sendSubagentMessage,stopSubagent:e.stopSubagent,stopChat:e.stopChat,listTurnToolCalls:e.listTurnToolCalls,getChatToolCall:e.getChatToolCall,answerChatToolCall:e.answerChatToolCall,listChatTurnArtifacts:e.listChatTurnArtifacts,getChatTurnArtifact:e.getChatTurnArtifact,getChatTurnCost:e.getChatTurnCost,startChatVoice:e.startChatVoice,getChatVoice:e.getChatVoice,closeChatVoice:e.closeChatVoice,commandChatVoice:e.commandChatVoice,getChatWorkspaceFile:e.getChatWorkspaceFile,addChatWorkspaceRepo:e.addChatWorkspaceRepo,createEmbeddings:e.createEmbeddings,listEndpoints:e.listEndpoints,putEndpoint:e.putEndpoint,deleteEndpoint:e.deleteEndpoint,createImage:e.createImage,getImage:e.getImage,getImageFile:e.getImageFile,listModels:e.listModels,listProviders:e.listProviders,connectProvider:e.connectProvider,disconnectProvider:e.disconnectProvider,listRepos:e.listRepos,putRepo:e.putRepo,deleteRepo:e.deleteRepo,createResponse:e.createResponse,getResponse:e.getResponse,cancelResponse:e.cancelResponse,followResponse:e.followResponse,getSettings:e.getSettings,putSettings:e.putSettings,getSpend:e.getSpend,askSupport:e.askSupport,listTools:e.listTools,listUsage:e.listUsage},analytics:{listAudiences:a.listAudiences,createAudience:a.createAudience,previewAudience:a.previewAudience,getAudience:a.getAudience,deleteAudience:a.deleteAudience,updateAudience:a.updateAudience,listAudienceMembers:a.listAudienceMembers,alias:a.alias,batch:a.batch,getEventBreakdown:a.getEventBreakdown,capture:a.capture,sendConsoleHistory:a.sendConsoleHistory,getConsoleConfig:a.getConsoleConfig,listConsoleRecords:a.listConsoleRecords,listEventNames:a.listEventNames,listEvents:a.listEvents,getEventTimeline:a.getEventTimeline,runFunnel:a.runFunnel,identify:a.identify,page:a.page,sendPerf:a.sendPerf,listPerfGroups:a.listPerfGroups,getPerfConfig:a.getPerfConfig,getPerfTimeline:a.getPerfTimeline,listRequestLines:a.listRequestLines,getMachineTraffic:a.getMachineTraffic,runRetention:a.runRetention,screen:a.screen,getSettings:a.getSettings,putSettings:a.putSettings,getSummary:a.getSummary,listTraces:a.listTraces,sendTrace:a.sendTrace,sendTraceBatch:a.sendTraceBatch,getTraceHops:a.getTraceHops,listSessionTraces:a.listSessionTraces,getTraceSummary:a.getTraceSummary,getTraceTimeline:a.getTraceTimeline,searchPeople:a.searchPeople,setPersonProperties:a.setPersonProperties,getPerson:a.getPerson,listPersonEvents:a.listPersonEvents,getEventCatalog:a.getEventCatalog,defineEvent:a.defineEvent},auth:{adminVerifyDeviceAssertion:s.adminVerifyDeviceAssertion,adminGetAttestPolicy:s.adminGetAttestPolicy,adminGetAttestObservations:s.adminGetAttestObservations,adminRecordAttestObservations:s.adminRecordAttestObservations,adminListAuditEvents:s.adminListAuditEvents,adminExportAuditEvents:s.adminExportAuditEvents,adminVerifyAuditTrail:s.adminVerifyAuditTrail,adminGetAuthSettings:s.adminGetAuthSettings,adminUpdateAuthSettings:s.adminUpdateAuthSettings,adminGetBreachWatch:s.adminGetBreachWatch,adminListHooks:s.adminListHooks,adminCreateHook:s.adminCreateHook,adminUpdateHook:s.adminUpdateHook,adminDeleteHook:s.adminDeleteHook,adminListHookExecutions:s.adminListHookExecutions,adminListIntegrations:s.adminListIntegrations,adminPutIntegration:s.adminPutIntegration,adminDeleteIntegration:s.adminDeleteIntegration,adminListOAuthClients:s.adminListOAuthClients,adminCreateOAuthClient:s.adminCreateOAuthClient,adminGetOAuthClient:s.adminGetOAuthClient,adminDeleteOAuthClient:s.adminDeleteOAuthClient,adminUpdateOAuthClient:s.adminUpdateOAuthClient,adminListProviders:s.adminListProviders,adminGetPhoneSettings:s.adminGetPhoneSettings,adminUpdatePhoneSettings:s.adminUpdatePhoneSettings,adminToggleProvider:s.adminToggleProvider,adminListRoles:s.adminListRoles,adminUpsertRole:s.adminUpsertRole,adminDeleteRole:s.adminDeleteRole,adminListServiceAccounts:s.adminListServiceAccounts,adminCreateServiceAccount:s.adminCreateServiceAccount,adminGetServiceAccount:s.adminGetServiceAccount,adminRevokeServiceAccount:s.adminRevokeServiceAccount,adminRotateServiceAccount:s.adminRotateServiceAccount,adminListSessions:s.adminListSessions,adminRevokeSession:s.adminRevokeSession,adminListSigningKeys:s.adminListSigningKeys,adminRotateSigningKey:s.adminRotateSigningKey,socialAdminConfig:s.socialAdminConfig,socialCredentialPut:s.socialCredentialPut,socialCredentialDelete:s.socialCredentialDelete,socialProviderPatch:s.socialProviderPatch,adminGetStats:s.adminGetStats,adminSendTestTemplate:s.adminSendTestTemplate,adminListTestUsers:s.adminListTestUsers,adminCreateTestUsers:s.adminCreateTestUsers,adminSetTestUserPhone:s.adminSetTestUserPhone,adminCreateTestSignupAddress:s.adminCreateTestSignupAddress,adminDeleteTestUser:s.adminDeleteTestUser,adminCreateCustomToken:s.adminCreateCustomToken,adminListUsers:s.adminListUsers,adminCreateUser:s.adminCreateUser,adminImportUsers:s.adminImportUsers,adminGetUser:s.adminGetUser,adminDeleteUser:s.adminDeleteUser,adminUpdateUser:s.adminUpdateUser,adminBanUser:s.adminBanUser,adminGetUserConsents:s.adminGetUserConsents,adminRevokeUserCredentials:s.adminRevokeUserCredentials,adminExportUser:s.adminExportUser,adminListUserMfaFactors:s.adminListUserMfaFactors,adminResetUserMfa:s.adminResetUserMfa,adminResetUserPassword:s.adminResetUserPassword,adminListUserRoles:s.adminListUserRoles,adminAssignUserRole:s.adminAssignUserRole,adminRevokeUserRole:s.adminRevokeUserRole,adminRevokeUserSessions:s.adminRevokeUserSessions,adminUnbanUser:s.adminUnbanUser,adminGetInstallationConsents:s.adminGetInstallationConsents,adminRefuseConsents:s.adminRefuseConsents},calls:{adminListCalls:p.adminListCalls,adminGetCall:p.adminGetCall,adminEndCall:p.adminEndCall,createCallTicket:p.createCallTicket,getCallSettings:p.getCallSettings,putCallSettings:p.putCallSettings,rotateCallHookSecret:p.rotateCallHookSecret},flags:{getValues:g.getValues,batchUserValues:g.batchUserValues,getDelta:g.getDelta,getEvaluations:g.getEvaluations,listExperiments:g.listExperiments,startExperiment:g.startExperiment,getExperiment:g.getExperiment,getExperimentResults:g.getExperimentResults,stopExperiment:g.stopExperiment,declareExperimentWinner:g.declareExperimentWinner,getCurrentInstallations:g.getCurrentInstallations,getInstallationsDaily:g.getInstallationsDaily,getSnapshot:g.getSnapshot,listDefinitions:g.listDefinitions,getDefinition:g.getDefinition,putDefinition:g.putDefinition,deleteDefinition:g.deleteDefinition,activateTemplates:g.activateTemplates,getActiveTemplate:g.getActiveTemplate,getTemplateCapabilities:g.getTemplateCapabilities,getTemplateDraft:g.getTemplateDraft,createTemplateDraft:g.createTemplateDraft,discardTemplateDraft:g.discardTemplateDraft,putTemplateParameter:g.putTemplateParameter,removeTemplateParameter:g.removeTemplateParameter,reviewTemplateDraft:g.reviewTemplateDraft,publishTemplate:g.publishTemplate,getPublishReceipt:g.getPublishReceipt,restoreTemplateVersion:g.restoreTemplateVersion,listTemplateVersions:g.listTemplateVersions,getTemplateVersion:g.getTemplateVersion,getUserValues:g.getUserValues,putUserValues:g.putUserValues,deleteUserValues:g.deleteUserValues,putUserValue:g.putUserValue,deleteUserValue:g.deleteUserValue},journeys:{listJourneys:m.listJourneys,createJourney:m.createJourney,listPersonRuns:m.listPersonRuns,simulateJourney:m.simulateJourney,validateJourney:m.validateJourney,getJourney:m.getJourney,updateJourney:m.updateJourney,deleteJourney:m.deleteJourney,copyJourney:m.copyJourney,publishJourney:m.publishJourney,listJourneyRuns:m.listJourneyRuns,getJourneyStats:m.getJourneyStats,stopJourney:m.stopJourney,testJourney:m.testJourney},machines:{listMachines:i.listMachines,createMachine:i.createMachine,listMachineSizes:i.listMachineSizes,getMachineNetwork:i.getMachineNetwork,connectGitHub:i.connectGitHub,listInstallations:i.listInstallations,linkInstallation:i.linkInstallation,shareInstallation:i.shareInstallation,unlinkInstallation:i.unlinkInstallation,listRepositories:i.listRepositories,getMachine:i.getMachine,deleteMachine:i.deleteMachine,updateMachine:i.updateMachine,listBuilds:i.listBuilds,deployMachine:i.deployMachine,listMachinePreviews:i.listMachinePreviews,putMachinePreview:i.putMachinePreview,deleteMachinePreview:i.deleteMachinePreview,listMachineDomains:i.listMachineDomains,addMachineDomain:i.addMachineDomain,deleteMachineDomain:i.deleteMachineDomain,updateMachineDomain:i.updateMachineDomain,getBuild:i.getBuild,getBuildLog:i.getBuildLog,rollbackMachine:i.rollbackMachine,listDatabases:i.listDatabases,createDatabase:i.createDatabase,listDatabaseSizes:i.listDatabaseSizes,getDatabase:i.getDatabase,deleteDatabase:i.deleteDatabase,updateDatabase:i.updateDatabase,undeleteDatabase:i.undeleteDatabase,purgeDatabase:i.purgeDatabase,getDatabaseCredentials:i.getDatabaseCredentials,changeDatabasePassword:i.changeDatabasePassword,readMachineLogs:i.readMachineLogs,getMachineMetrics:i.getMachineMetrics,getMachineContract:i.getMachineContract,restoreDatabase:i.restoreDatabase,getDatabaseSchema:i.getDatabaseSchema,getDatabaseMetrics:i.getDatabaseMetrics,queryDatabase:i.queryDatabase,listCrons:i.listCrons,listCronRuns:i.listCronRuns,runCron:i.runCron,pauseCron:i.pauseCron,resumeCron:i.resumeCron,listTasks:i.listTasks,enqueueTask:i.enqueueTask,getTask:i.getTask,cancelTask:i.cancelTask,retryTask:i.retryTask,listTaskTypes:i.listTaskTypes,makeTemplatedTestUsers:i.makeTemplatedTestUsers,templateTestUser:i.templateTestUser,deleteTemplatedTestUser:i.deleteTemplatedTestUser,listSites:i.listSites,createSite:i.createSite,getSite:i.getSite,deleteSite:i.deleteSite,updateSite:i.updateSite,listSiteReleases:i.listSiteReleases,createSiteRelease:i.createSiteRelease,uploadSiteFile:i.uploadSiteFile,finishSiteRelease:i.finishSiteRelease,rollbackSite:i.rollbackSite,listSiteBuilds:i.listSiteBuilds,deploySite:i.deploySite,listSitePreviews:i.listSitePreviews,listSiteDomains:i.listSiteDomains,addSiteDomain:i.addSiteDomain,deleteSiteDomain:i.deleteSiteDomain,updateSiteDomain:i.updateSiteDomain,getSiteBuild:i.getSiteBuild,authorizeSitePreview:i.authorizeSitePreview,authorizeMachinePreview:i.authorizeMachinePreview,openMachinePreview:i.openMachinePreview,moveMachine:i.moveMachine},messaging:{adminAccessLog:d.adminAccessLog,adminListConversations:d.adminListConversations,adminCreateConversation:d.adminCreateConversation,adminGetConversation:d.adminGetConversation,adminDeleteConversation:d.adminDeleteConversation,adminUpdateConversation:d.adminUpdateConversation,adminAddMembers:d.adminAddMembers,adminRemoveMember:d.adminRemoveMember,adminListMessages:d.adminListMessages,adminSendMessage:d.adminSendMessage,adminDeleteMessage:d.adminDeleteMessage,adminFileUrl:d.adminFileUrl,adminPutProfile:d.adminPutProfile,adminListReports:d.adminListReports,adminGetReport:d.adminGetReport,adminReportFileUrl:d.adminReportFileUrl,adminResolveReport:d.adminResolveReport,getSettings:d.getSettings,putSettings:d.putSettings,rotateHookSecret:d.rotateHookSecret},notify:{getDeliverability:l.getDeliverability,listDevices:l.listDevices,getDeviceStats:l.getDeviceStats,deleteMyDevice:l.deleteMyDevice,sendEmail:l.sendEmail,listInAppCampaigns:l.listInAppCampaigns,createInAppCampaign:l.createInAppCampaign,getInAppCampaign:l.getInAppCampaign,putInAppCampaign:l.putInAppCampaign,deleteInAppCampaign:l.deleteInAppCampaign,getInAppCampaignStats:l.getInAppCampaignStats,listInAppTemplates:l.listInAppTemplates,sendInbox:l.sendInbox,listInboxMessages:l.listInboxMessages,listNotifyMessages:l.listNotifyMessages,getNotifyMessage:l.getNotifyMessage,cancelMessage:l.cancelMessage,getMetricsSummary:l.getMetricsSummary,listNotifyProviders:l.listNotifyProviders,putNotifyProvider:l.putNotifyProvider,deleteNotifyProvider:l.deleteNotifyProvider,sendPush:l.sendPush,getNotifySettings:l.getNotifySettings,putNotifySettings:l.putNotifySettings,sendSms:l.sendSms,listEmailTemplates:l.listEmailTemplates,getEmailTemplate:l.getEmailTemplate,putEmailTemplate:l.putEmailTemplate,deleteEmailTemplate:l.deleteEmailTemplate,listPushTemplates:l.listPushTemplates,getPushTemplate:l.getPushTemplate,putPushTemplate:l.putPushTemplate,deletePushTemplate:l.deletePushTemplate,listSmsTemplates:l.listSmsTemplates,getSmsTemplate:l.getSmsTemplate,putSmsTemplate:l.putSmsTemplate,deleteSmsTemplate:l.deleteSmsTemplate,listWhatsAppTemplates:l.listWhatsAppTemplates,getWhatsAppTemplate:l.getWhatsAppTemplate,putWhatsAppTemplate:l.putWhatsAppTemplate,deleteWhatsAppTemplate:l.deleteWhatsAppTemplate,listTestUserMessages:l.listTestUserMessages,listTopics:l.listTopics,createTopic:l.createTopic,deleteTopic:l.deleteTopic,changeTopic:l.changeTopic,addTopicSubscribers:l.addTopicSubscribers,removeTopicSubscriber:l.removeTopicSubscriber,listUserDevices:l.listUserDevices,getUserPreferences:l.getUserPreferences,setUserPreferences:l.setUserPreferences,startVerification:l.startVerification,checkVerification:l.checkVerification,getWebPushStatus:l.getWebPushStatus,sendWhatsApp:l.sendWhatsApp,listWhatsAppInbound:l.listWhatsAppInbound},purchases:{getAppleAccount:n.getAppleAccount,disconnectApple:n.disconnectApple,createAppleGrant:n.createAppleGrant,getAppleReadiness:n.getAppleReadiness,setXcodeCertificate:n.setXcodeCertificate,clearXcodeCertificate:n.clearXcodeCertificate,getGoogleAccount:n.getGoogleAccount,connectGoogle:n.connectGoogle,disconnectGoogle:n.disconnectGoogle,getCatalog:n.getCatalog,saveCatalog:n.saveCatalog,planCatalog:n.planCatalog,getCatalogPlan:n.getCatalogPlan,confirmCatalogPlan:n.confirmCatalogPlan,declineCatalogPlan:n.declineCatalogPlan,validateCatalog:n.validateCatalog,listCharts:n.listCharts,getChartsOverview:n.getChartsOverview,getChart:n.getChart,getCustomer:n.getCustomer,grantCredits:n.grantCredits,listCreditEntries:n.listCreditEntries,forgiveCredits:n.forgiveCredits,listCustomerGrants:n.listCustomerGrants,grantEntitlement:n.grantEntitlement,revokeGrant:n.revokeGrant,holdSpend:n.holdSpend,setCustomerLimit:n.setCustomerLimit,clearCustomerLimit:n.clearCustomerLimit,grantLimit:n.grantLimit,spend:n.spend,commitSpend:n.commitSpend,extendHold:n.extendHold,releaseSpend:n.releaseSpend,reverseSpend:n.reverseSpend,listExperiments:n.listExperiments,startExperiment:n.startExperiment,getExperiment:n.getExperiment,getExperimentResults:n.getExperimentResults,stopExperiment:n.stopExperiment,declareExperimentWinner:n.declareExperimentWinner,getOfferings:n.getOfferings,listPaywalls:n.listPaywalls,createPaywall:n.createPaywall,listPaywallAssets:n.listPaywallAssets,registerPaywallAsset:n.registerPaywallAsset,deletePaywallAsset:n.deletePaywallAsset,listPaywallTemplates:n.listPaywallTemplates,getPaywallTemplateAsset:n.getPaywallTemplateAsset,validatePaywall:n.validatePaywall,getPaywall:n.getPaywall,deletePaywall:n.deletePaywall,savePaywallDraft:n.savePaywallDraft,publishPaywall:n.publishPaywall,listPaywallVersions:n.listPaywallVersions,getPaywallVersion:n.getPaywallVersion,listPlacements:n.listPlacements,listAttributeKeys:n.listAttributeKeys,setPlacement:n.setPlacement,deletePlacement:n.deletePlacement,recordPaywallExposure:n.recordPaywallExposure,getPlacementPaywall:n.getPlacementPaywall,previewPlacement:n.previewPlacement,getPlacementResults:n.getPlacementResults,getPlacementRules:n.getPlacementRules,setPlacementRules:n.setPlacementRules,getSettings:n.getSettings,updateSettings:n.updateSettings,getStripeAccount:n.getStripeAccount,disconnectStripe:n.disconnectStripe,checkStripeAccount:n.checkStripeAccount,createCheckout:n.createCheckout,createCheckoutRedemption:n.createCheckoutRedemption,createStripeGrant:n.createStripeGrant,createStripeAppInstall:n.createStripeAppInstall,getOfferStats:n.getOfferStats,listCoupons:n.listCoupons,createCoupon:n.createCoupon,getCoupon:n.getCoupon,revokeCoupon:n.revokeCoupon,listCouponCodes:n.listCouponCodes,setXcodeOfferKey:n.setXcodeOfferKey,searchCustomers:n.searchCustomers,getCustomerHistory:n.getCustomerHistory,listCatalogRevisions:n.listCatalogRevisions,getCatalogRevision:n.getCatalogRevision,restoreCatalogRevision:n.restoreCatalogRevision,extendSubscription:n.extendSubscription,refundSubscription:n.refundSubscription,cancelSubscription:n.cancelSubscription},realtime:{broadcast:h.broadcast,getChannels:h.getChannels,putChannels:h.putChannels,getLimits:h.getLimits,putLimits:h.putLimits,revalidate:h.revalidate,writeState:h.writeState,getStats:h.getStats},secrets:{listSecretAudit:c.listSecretAudit,listFieldKeys:c.listFieldKeys,getFieldKeys:c.getFieldKeys,openFields:c.openFields,sealPlaceholder:c.sealPlaceholder,rotateFieldKeys:c.rotateFieldKeys,listTransitKeys:c.listTransitKeys,getTransitKeys:c.getTransitKeys,getTransitPublicKeys:c.getTransitPublicKeys,rotateTransitKeys:c.rotateTransitKeys,retireTransitKey:c.retireTransitKey,listSecrets:c.listSecrets,getEnvironmentValues:c.getEnvironmentValues,getSecret:c.getSecret,putSecret:c.putSecret,deleteSecret:c.deleteSecret,rollbackSecret:c.rollbackSecret,listSecretVersions:c.listSecretVersions},storage:{listBuckets:u.listBuckets,getBucket:u.getBucket,putBucket:u.putBucket,deleteBucket:u.deleteBucket,copyObject:u.copyObject,moveObject:u.moveObject,listObjects:u.listObjects,getObject:u.getObject,putObject:u.putObject,deleteObject:u.deleteObject,headObject:u.headObject,createSignedUrl:u.createSignedUrl,createUploadUrl:u.createUploadUrl,getStorageStats:u.getStorageStats},stores:{listActions:o.listActions,getAction:o.getAction,confirmAction:o.confirmAction,declineAction:o.declineAction,getAppleAccount:o.getAppleAccount,disconnectApple:o.disconnectApple,checkAppleAccount:o.checkAppleAccount,createAppleGrant:o.createAppleGrant,getSandboxReadiness:o.getSandboxReadiness,listSandboxTesters:o.listSandboxTesters,clearSandboxPurchaseHistory:o.clearSandboxPurchaseHistory,updateSandboxTester:o.updateSandboxTester,listApps:o.listApps,listFeedback:o.listFeedback,getFeedback:o.getFeedback,listGroups:o.listGroups,createGroup:o.createGroup,linkApp:o.linkApp,getListing:o.getListing,setListing:o.setListing,planListing:o.planListing,createPackage:o.createPackage,uploadScreenshot:o.uploadScreenshot,getReviewInfo:o.getReviewInfo,setReviewInfo:o.setReviewInfo,getUploadKey:o.getUploadKey,getAppStoreVersion:o.getAppStoreVersion,prepareAppStoreVersion:o.prepareAppStoreVersion,planPhasedRelease:o.planPhasedRelease,planReleaseVersion:o.planReleaseVersion,planSubmitReview:o.planSubmitReview,planWithdrawReview:o.planWithdrawReview,getAppVitals:o.getAppVitals,getAppWebhook:o.getAppWebhook,makeAppWebhook:o.makeAppWebhook,pingAppWebhook:o.pingAppWebhook,getGoogleAccount:o.getGoogleAccount,connectGoogle:o.connectGoogle,disconnectGoogle:o.disconnectGoogle,checkGoogleAccount:o.checkGoogleAccount,deleteGroup:o.deleteGroup,renameGroup:o.renameGroup,addGroupBuild:o.addGroupBuild,listTesters:o.listTesters,setTesters:o.setTesters,listPackages:o.listPackages,getPackage:o.getPackage,planBetaReview:o.planBetaReview,listDeliveries:o.listDeliveries,deliver:o.deliver,getSignedBundleLink:o.getSignedBundleLink,planExpire:o.planExpire,planExportCompliance:o.planExportCompliance,setWhatToTest:o.setWhatToTest,getAppleSession:o.getAppleSession,disconnectAppleSession:o.disconnectAppleSession,checkAppleSession:o.checkAppleSession,createAppleIdGrant:o.createAppleIdGrant,getAppReview:o.getAppReview,getReviewAttachment:o.getReviewAttachment,setReviewDraft:o.setReviewDraft,sendReviewDraft:o.sendReviewDraft,getAppPrivacy:o.getAppPrivacy,setAppPrivacy:o.setAppPrivacy,makeAppRecord:o.makeAppRecord,removeAppRecord:o.removeAppRecord,listMadeAppleKeys:o.listMadeAppleKeys,makeAppleKey:o.makeAppleKey,revokeMadeAppleKey:o.revokeMadeAppleKey,shareAppleSession:o.shareAppleSession,unshareAppleSession:o.unshareAppleSession}}}function K(t){return{orgs:{async list(e){return t.send({op:"orgs.list",method:"GET",path:"/v1/orgs",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e?.signal})},async create(e){return t.send({op:"orgs.create",method:"POST",path:"/v1/orgs",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async get(e){return t.send({op:"orgs.get",method:"GET",path:"/v1/orgs/"+r("orgs.get","id",e.path.id),auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async takeAway(e){return t.send({op:"orgs.takeAway",method:"DELETE",path:"/v1/orgs/"+r("orgs.takeAway","id",e.path.id),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async rename(e){return t.send({op:"orgs.rename",method:"PATCH",path:"/v1/orgs/"+r("orgs.rename","id",e.path.id),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async members(e){return t.send({op:"orgs.members",method:"GET",path:"/v1/orgs/"+r("orgs.members","id",e.path.id)+"/members",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async auditLog(e){return t.send({op:"orgs.auditLog",method:"GET",path:"/v1/orgs/"+r("orgs.auditLog","id",e.path.id)+"/audit",auth:[["PalbaseBearer"]],answers:{200:"json"},query:e.query,signal:e.signal})}},invitations:{async mine(e){return t.send({op:"invitations.mine",method:"GET",path:"/v1/invitations",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e?.signal})},async accept(e){return t.send({op:"invitations.accept",method:"POST",path:"/v1/invitations/"+r("invitations.accept","id",e.path.id)+"/accept",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})}},orgWebhooks:{async list(e){return t.send({op:"orgWebhooks.list",method:"GET",path:"/v1/orgs/"+r("orgWebhooks.list","id",e.path.id)+"/webhooks",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async add(e){return t.send({op:"orgWebhooks.add",method:"POST",path:"/v1/orgs/"+r("orgWebhooks.add","id",e.path.id)+"/webhooks",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async remove(e){return t.send({op:"orgWebhooks.remove",method:"DELETE",path:"/v1/orgs/"+r("orgWebhooks.remove","id",e.path.id)+"/webhooks/"+r("orgWebhooks.remove","endpoint",e.path.endpoint),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})}},projects:{async mine(e){return t.send({op:"projects.mine",method:"GET",path:"/v1/projects",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e?.signal})},async environmentsMine(e){return t.send({op:"projects.environmentsMine",method:"GET",path:"/v1/environments",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e?.signal})},async list(e){return t.send({op:"projects.list",method:"GET",path:"/v1/orgs/"+r("projects.list","id",e.path.id)+"/projects",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async create(e){return t.send({op:"projects.create",method:"POST",path:"/v1/orgs/"+r("projects.create","id",e.path.id)+"/projects",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async get(e){return t.send({op:"projects.get",method:"GET",path:"/v1/projects/"+r("projects.get","id",e.path.id),auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async remove(e){return t.send({op:"projects.remove",method:"DELETE",path:"/v1/projects/"+r("projects.remove","id",e.path.id),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async rename(e){return t.send({op:"projects.rename",method:"PATCH",path:"/v1/projects/"+r("projects.rename","id",e.path.id),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async addEnvironment(e){return t.send({op:"projects.addEnvironment",method:"POST",path:"/v1/projects/"+r("projects.addEnvironment","id",e.path.id)+"/environments",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async environment(e){return t.send({op:"projects.environment",method:"GET",path:"/v1/environments/"+r("projects.environment","ref",e.path.ref),auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async removeEnvironment(e){return t.send({op:"projects.removeEnvironment",method:"DELETE",path:"/v1/environments/"+r("projects.removeEnvironment","ref",e.path.ref),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,query:e.query,headers:e.headers,signal:e.signal})},async renameEnvironment(e){return t.send({op:"projects.renameEnvironment",method:"PATCH",path:"/v1/environments/"+r("projects.renameEnvironment","ref",e.path.ref),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async keys(e){return t.send({op:"projects.keys",method:"GET",path:"/v1/environments/"+r("projects.keys","ref",e.path.ref)+"/keys",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async usage(e){return t.send({op:"projects.usage",method:"GET",path:"/v1/environments/"+r("projects.usage","ref",e.path.ref)+"/usage",auth:[["PalbaseBearer"]],answers:{200:"json"},query:e.query,signal:e.signal})},async personalKey(e){return t.send({op:"projects.personalKey",method:"POST",path:"/v1/environments/"+r("projects.personalKey","ref",e.path.ref)+"/personal-key",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async revokePersonalKey(e){return t.send({op:"projects.revokePersonalKey",method:"DELETE",path:"/v1/environments/"+r("projects.revokePersonalKey","ref",e.path.ref)+"/personal-key/"+r("projects.revokePersonalKey","key",e.path.key),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async shareInstallation(e){return t.send({op:"projects.shareInstallation",method:"POST",path:"/v1/environments/"+r("projects.shareInstallation","ref",e.path.ref)+"/github/installations",auth:[["PalbaseBearer"]],answers:{},ownResponse:!0,idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})}},apps:{async list(e){return t.send({op:"apps.list",method:"GET",path:"/v1/projects/"+r("apps.list","id",e.path.id)+"/apps",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async create(e){return t.send({op:"apps.create",method:"POST",path:"/v1/projects/"+r("apps.create","id",e.path.id)+"/apps",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async get(e){return t.send({op:"apps.get",method:"GET",path:"/v1/projects/"+r("apps.get","id",e.path.id)+"/apps/"+r("apps.get","app",e.path.app),auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async remove(e){return t.send({op:"apps.remove",method:"DELETE",path:"/v1/projects/"+r("apps.remove","id",e.path.id)+"/apps/"+r("apps.remove","app",e.path.app),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})},async update(e){return t.send({op:"apps.update",method:"PATCH",path:"/v1/projects/"+r("apps.update","id",e.path.id)+"/apps/"+r("apps.update","app",e.path.app),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async restore(e){return t.send({op:"apps.restore",method:"POST",path:"/v1/projects/"+r("apps.restore","id",e.path.id)+"/apps/"+r("apps.restore","app",e.path.app)+"/restore",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})},async setIn(e){return t.send({op:"apps.setIn",method:"PUT",path:"/v1/environments/"+r("apps.setIn","ref",e.path.ref)+"/apps/"+r("apps.setIn","app",e.path.app),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async removeFrom(e){return t.send({op:"apps.removeFrom",method:"DELETE",path:"/v1/environments/"+r("apps.removeFrom","ref",e.path.ref)+"/apps/"+r("apps.removeFrom","app",e.path.app),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async config(e){return t.send({op:"apps.config",method:"GET",path:"/v1/environments/"+r("apps.config","ref",e.path.ref)+"/apps/"+r("apps.config","app",e.path.app)+"/config",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})}},snippets:{async list(e){return t.send({op:"snippets.list",method:"GET",path:"/v1/environments/"+r("snippets.list","ref",e.path.ref)+"/snippets",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async create(e){return t.send({op:"snippets.create",method:"POST",path:"/v1/environments/"+r("snippets.create","ref",e.path.ref)+"/snippets",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async remove(e){return t.send({op:"snippets.remove",method:"DELETE",path:"/v1/environments/"+r("snippets.remove","ref",e.path.ref)+"/snippets/"+r("snippets.remove","id",e.path.id),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async change(e){return t.send({op:"snippets.change",method:"PATCH",path:"/v1/environments/"+r("snippets.change","ref",e.path.ref)+"/snippets/"+r("snippets.change","id",e.path.id),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})}},chartViews:{async list(e){return t.send({op:"chartViews.list",method:"GET",path:"/v1/environments/"+r("chartViews.list","ref",e.path.ref)+"/chart-views",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async create(e){return t.send({op:"chartViews.create",method:"POST",path:"/v1/environments/"+r("chartViews.create","ref",e.path.ref)+"/chart-views",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async remove(e){return t.send({op:"chartViews.remove",method:"DELETE",path:"/v1/environments/"+r("chartViews.remove","ref",e.path.ref)+"/chart-views/"+r("chartViews.remove","id",e.path.id),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async change(e){return t.send({op:"chartViews.change",method:"PATCH",path:"/v1/environments/"+r("chartViews.change","ref",e.path.ref)+"/chart-views/"+r("chartViews.change","id",e.path.id),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})}},webhooks:{async list(e){return t.send({op:"webhooks.list",method:"GET",path:"/v1/environments/"+r("webhooks.list","ref",e.path.ref)+"/webhooks",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async add(e){return t.send({op:"webhooks.add",method:"POST",path:"/v1/environments/"+r("webhooks.add","ref",e.path.ref)+"/webhooks",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async deliveries(e){return t.send({op:"webhooks.deliveries",method:"GET",path:"/v1/environments/"+r("webhooks.deliveries","ref",e.path.ref)+"/webhooks/deliveries",auth:[["PalbaseBearer"]],answers:{200:"json"},query:e.query,signal:e.signal})},async redeliver(e){return t.send({op:"webhooks.redeliver",method:"POST",path:"/v1/environments/"+r("webhooks.redeliver","ref",e.path.ref)+"/webhooks/deliveries/"+r("webhooks.redeliver","delivery",e.path.delivery)+"/redeliver",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})},async change(e){return t.send({op:"webhooks.change",method:"PUT",path:"/v1/environments/"+r("webhooks.change","ref",e.path.ref)+"/webhooks/"+r("webhooks.change","endpoint",e.path.endpoint),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async remove(e){return t.send({op:"webhooks.remove",method:"DELETE",path:"/v1/environments/"+r("webhooks.remove","ref",e.path.ref)+"/webhooks/"+r("webhooks.remove","endpoint",e.path.endpoint),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})}},environmentTokens:{async list(e){return t.send({op:"environmentTokens.list",method:"GET",path:"/v1/environments/"+r("environmentTokens.list","ref",e.path.ref)+"/tokens",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async mint(e){return t.send({op:"environmentTokens.mint",method:"POST",path:"/v1/environments/"+r("environmentTokens.mint","ref",e.path.ref)+"/tokens",auth:[["PalbaseBearer"],[]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async revoke(e){return t.send({op:"environmentTokens.revoke",method:"DELETE",path:"/v1/environments/"+r("environmentTokens.revoke","ref",e.path.ref)+"/tokens/"+r("environmentTokens.revoke","id",e.path.id),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})}},billing:{async bill(e){return t.send({op:"billing.bill",method:"GET",path:"/v1/orgs/"+r("billing.bill","id",e.path.id)+"/billing",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async confirm(e){return t.send({op:"billing.confirm",method:"POST",path:"/v1/orgs/"+r("billing.confirm","id",e.path.id)+"/billing/checkout/"+r("billing.confirm","session",e.path.session)+"/confirm",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})},async cards(e){return t.send({op:"billing.cards",method:"GET",path:"/v1/orgs/"+r("billing.cards","id",e.path.id)+"/billing/cards",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async defaultCard(e){return t.send({op:"billing.defaultCard",method:"PUT",path:"/v1/orgs/"+r("billing.defaultCard","id",e.path.id)+"/billing/cards/"+r("billing.defaultCard","card",e.path.card)+"/default",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})},async removeCard(e){return t.send({op:"billing.removeCard",method:"DELETE",path:"/v1/orgs/"+r("billing.removeCard","id",e.path.id)+"/billing/cards/"+r("billing.removeCard","card",e.path.card),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})},async customer(e){return t.send({op:"billing.customer",method:"GET",path:"/v1/orgs/"+r("billing.customer","id",e.path.id)+"/billing/customer",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async setCustomer(e){return t.send({op:"billing.setCustomer",method:"PUT",path:"/v1/orgs/"+r("billing.setCustomer","id",e.path.id)+"/billing/customer",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async charges(e){return t.send({op:"billing.charges",method:"GET",path:"/v1/orgs/"+r("billing.charges","id",e.path.id)+"/billing/charges",auth:[["PalbaseBearer"]],answers:{200:"json"},query:e.query,signal:e.signal})},async csv(e){return t.send({op:"billing.csv",method:"GET",path:"/v1/orgs/"+r("billing.csv","id",e.path.id)+"/billing/charges.csv",auth:[["PalbaseBearer"]],answers:{},ownResponse:!0,query:e.query,signal:e.signal})},async invoices(e){return t.send({op:"billing.invoices",method:"GET",path:"/v1/orgs/"+r("billing.invoices","id",e.path.id)+"/billing/invoices",auth:[["PalbaseBearer"]],answers:{200:"json"},query:e.query,signal:e.signal})},async payer(e){return t.send({op:"billing.payer",method:"PUT",path:"/v1/orgs/"+r("billing.payer","id",e.path.id)+"/billing/payer",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async paid(e){return t.send({op:"billing.paid",method:"GET",path:"/v1/orgs/"+r("billing.paid","id",e.path.id)+"/billing/paid",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async stopPaying(e){return t.send({op:"billing.stopPaying",method:"DELETE",path:"/v1/orgs/"+r("billing.stopPaying","id",e.path.id)+"/billing/paid/"+r("billing.stopPaying","org",e.path.org),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async report(e){return t.send({op:"billing.report",method:"GET",path:"/v1/orgs/"+r("billing.report","id",e.path.id)+"/billing/report",auth:[["PalbaseBearer"]],answers:{200:"json"},query:e.query,signal:e.signal})},async reportCsv(e){return t.send({op:"billing.reportCsv",method:"GET",path:"/v1/orgs/"+r("billing.reportCsv","id",e.path.id)+"/billing/report.csv",auth:[["PalbaseBearer"]],answers:{},ownResponse:!0,query:e.query,signal:e.signal})},async environment(e){return t.send({op:"billing.environment",method:"GET",path:"/v1/orgs/"+r("billing.environment","id",e.path.id)+"/billing/environments/"+r("billing.environment","ref",e.path.ref),auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async steer(e){return t.send({op:"billing.steer",method:"PATCH",path:"/v1/orgs/"+r("billing.steer","id",e.path.id)+"/billing/environments/"+r("billing.steer","ref",e.path.ref),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})}},accessRequests:{async request(e){return t.send({op:"accessRequests.request",method:"POST",path:"/v1/access-requests",auth:[["PalbaseBearer"],[]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})}},docs:{async search(e){return t.send({op:"docs.search",method:"GET",path:"/v1/docs/search",auth:[["PalbaseBearer"],[]],answers:{200:"json"},query:e.query,signal:e.signal})}}}}function V(t){let{mint:e,revoke:a}=t;return async s=>{let p=await e(s),g=s.body?.role,m=s.body?.on_behalf_of;if(g===void 0&&m===void 0)return p;let i=p.data,d=[];if(g!==void 0&&i.role!==g&&d.push(`role ${g} (it came back ${i.role==null?"at its minter's":i.role})`),m!==void 0&&i.on_behalf_of!==m.trim()&&d.push("on_behalf_of"),d.length===0)return p;let l;try{await a({path:{ref:s.path.ref,id:String(i.id)}})}catch(h){l=h}let n=`Studio minted the token without the ${d.join(" and ")} asked for \u2014 it is older than this SDK`;throw new y({op:"environmentTokens.mint",status:0,code:"token_role_not_kept",message:l===void 0?`environmentTokens.mint: ${n}; the token (${i.id}) was revoked at once and is not returned \u2014 mint it again once Studio is updated`:`environmentTokens.mint: ${n}, and revoking it failed (${l instanceof Error?l.message:String(l)}) \u2014 revoke token ${i.id} of environment ${s.path.ref} yourself, now`,cause:l})}}var _={pbo_:"an organization's",pbu_:"an account's",pbe_:"an environment's"},J=/^[A-Za-z0-9_-]*$/,O=64,b=44;function W(t){if(typeof t!="string"||t==="")return"token is missing: pass an access token, an organization's (pbo_\u2026), an account's (pbu_\u2026) or an environment's (pbe_\u2026)";let e=t.slice(0,4);if(!Object.hasOwn(_,e))return`token has the wrong prefix: an access token starts with pbo_ (an organization's), pbu_ (an account's) or pbe_ (an environment's)${/^pb_[a-z0-9]+_[cs]/.test(t)?" \u2014 a project key belongs in palbase/server or palbase/web":""}`;let a=t.slice(4);if(a.length!==O)return`token has the wrong length: ${_[e]} access token is ${e} and ${O} characters, this one has ${a.length} after it`;if(!J.test(a))return`token is not ${_[e]} access token: after ${e} come base64url characters alone (A\u2013Z, a\u2013z, 0\u20139, - and _)`;let s=X(a),p=(s[b]<<24|s[b+1]<<16|s[b+2]<<8|s[b+3])>>>0;if(Y(e,s.subarray(0,b))!==p)return"token's checksum does not match: it was mistyped or cut, or made before access tokens carried one \u2014 make a new token"}function N(t){return W(t)===void 0}function q(t){let e=W(t);if(e!==void 0)throw new TypeError(e)}var $="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function X(t){let e=new Uint8Array(t.length*6/8),a=0,s=0,p=0;for(let g of t)a=a<<6|$.indexOf(g),s+=6,s>=8&&(s-=8,e[p++]=a>>s&255);return e}var z=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let a=e;for(let s=0;s<8;s++)a=a&1?3988292384^a>>>1:a>>>1;t[e]=a>>>0}return t})();function Y(t,e){let a=4294967295;for(let s=0;s<t.length;s++)a=z[(a^t.charCodeAt(s))&255]^a>>>8;for(let s of e)a=z[(a^s)&255]^a>>>8;return(a^4294967295)>>>0}var F="palbase.studio",Z="palbase";function Q(){let t=globalThis;return typeof t.window<"u"||typeof t.document<"u"||typeof t.importScripts=="function"||I()}var f=class{domain;#e;#t=new Map;constructor(e){if(Q())throw new TypeError("palbase/cloud runs on a server: its access token opens the organization's projects, so it never goes into a browser, a web worker or a mobile app \u2014 keep it on your server, and have your app call that");q(e?.token);let a=e.domain??F;if(typeof a!="string"||!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(a))throw new TypeError(`domain ${JSON.stringify(a)} is not a domain`);this.domain=a;let s=e.token;this.#e=g=>B(v({baseUrl:g,credentials:{token:s},fetch:e.fetch,solveProofOfWork:!1}),e.retry??G);let p=K(this.#e(`https://palbase.app.${a}`));p.environmentTokens.mint=V(p.environmentTokens),Object.assign(this,p)}project(e){if(typeof e!="string"||!/^[a-z0-9]{1,63}$/.test(e))throw new TypeError(`${JSON.stringify(e)} is not an environment's ref`);let a=this.#t.get(e);return a||(a=L(this.#e(e===Z?`https://connect.${this.domain}`:`https://${e}.${this.domain}`)),this.#t.set(e,a)),a}};export{F as DEFAULT_DOMAIN,f as PalbaseCloud,y as PalbaseError,N as tokenIsWellFormed};
1
+ /*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
2
+ import{a as I}from"../chunks/HMDMAILZ.js";import{a as P,b as S,c as k,e as A,f as w,g as C,h as T,i as R,j,k as E,l as x,m as D,n as U,o as M}from"../chunks/L3S7O5FQ.js";import{a as G,b as B}from"../chunks/LANEQ73A.js";import{b as y,c as r,d as v}from"../chunks/4Y47I6LA.js";import"../chunks/CHXCVOON.js";import"../chunks/72CHRRHY.js";function L(t){let e=P.client(t),a=S.client(t),s=k.client(t),p=A.client(t),g=w.client(t),m=C.client(t),i=T.client(t),d=R.client(t),l=j.client(t),n=E.client(t),h=x.client(t),c=D.client(t),u=U.client(t),o=M.client(t);return{ai:{draftAgent:e.draftAgent,listAgents:e.listAgents,getAgent:e.getAgent,putAgent:e.putAgent,deleteAgent:e.deleteAgent,publishAgent:e.publishAgent,rollbackAgent:e.rollbackAgent,listAgentVersions:e.listAgentVersions,listChats:e.listChats,createChat:e.createChat,getChat:e.getChat,deleteChat:e.deleteChat,decideChatApproval:e.decideChatApproval,forkChat:e.forkChat,getChatGoal:e.getChatGoal,setChatGoal:e.setChatGoal,clearChatGoal:e.clearChatGoal,updateChatGoal:e.updateChatGoal,putChatMember:e.putChatMember,deleteChatMember:e.deleteChatMember,listChatMessages:e.listChatMessages,sendChatMessage:e.sendChatMessage,getChatMessageAttachment:e.getChatMessageAttachment,listChatParts:e.listChatParts,putChatPipe:e.putChatPipe,deleteChatPipe:e.deleteChatPipe,sendSubagentMessage:e.sendSubagentMessage,stopSubagent:e.stopSubagent,stopChat:e.stopChat,listTurnToolCalls:e.listTurnToolCalls,getChatToolCall:e.getChatToolCall,answerChatToolCall:e.answerChatToolCall,listChatTurnArtifacts:e.listChatTurnArtifacts,getChatTurnArtifact:e.getChatTurnArtifact,getChatTurnCost:e.getChatTurnCost,startChatVoice:e.startChatVoice,getChatVoice:e.getChatVoice,closeChatVoice:e.closeChatVoice,commandChatVoice:e.commandChatVoice,getChatWorkspaceFile:e.getChatWorkspaceFile,addChatWorkspaceRepo:e.addChatWorkspaceRepo,createEmbeddings:e.createEmbeddings,listEndpoints:e.listEndpoints,putEndpoint:e.putEndpoint,deleteEndpoint:e.deleteEndpoint,createImage:e.createImage,getImage:e.getImage,getImageFile:e.getImageFile,listModels:e.listModels,listProviders:e.listProviders,connectProvider:e.connectProvider,disconnectProvider:e.disconnectProvider,listRepos:e.listRepos,putRepo:e.putRepo,deleteRepo:e.deleteRepo,createResponse:e.createResponse,getResponse:e.getResponse,cancelResponse:e.cancelResponse,followResponse:e.followResponse,getSettings:e.getSettings,putSettings:e.putSettings,getSpend:e.getSpend,askSupport:e.askSupport,listTools:e.listTools,listUsage:e.listUsage},analytics:{listAudiences:a.listAudiences,createAudience:a.createAudience,previewAudience:a.previewAudience,getAudience:a.getAudience,deleteAudience:a.deleteAudience,updateAudience:a.updateAudience,listAudienceMembers:a.listAudienceMembers,alias:a.alias,batch:a.batch,getEventBreakdown:a.getEventBreakdown,capture:a.capture,sendConsoleHistory:a.sendConsoleHistory,getConsoleConfig:a.getConsoleConfig,listConsoleRecords:a.listConsoleRecords,listEventNames:a.listEventNames,listEvents:a.listEvents,getEventTimeline:a.getEventTimeline,runFunnel:a.runFunnel,identify:a.identify,page:a.page,sendPerf:a.sendPerf,listPerfGroups:a.listPerfGroups,getPerfConfig:a.getPerfConfig,getPerfTimeline:a.getPerfTimeline,listRequestLines:a.listRequestLines,getMachineTraffic:a.getMachineTraffic,runRetention:a.runRetention,screen:a.screen,getSettings:a.getSettings,putSettings:a.putSettings,getSummary:a.getSummary,listTraces:a.listTraces,sendTrace:a.sendTrace,sendTraceBatch:a.sendTraceBatch,getTraceHops:a.getTraceHops,listSessionTraces:a.listSessionTraces,getTraceSummary:a.getTraceSummary,getTraceTimeline:a.getTraceTimeline,searchPeople:a.searchPeople,setPersonProperties:a.setPersonProperties,getPerson:a.getPerson,listPersonEvents:a.listPersonEvents,getEventCatalog:a.getEventCatalog,defineEvent:a.defineEvent},auth:{adminVerifyDeviceAssertion:s.adminVerifyDeviceAssertion,adminGetAttestPolicy:s.adminGetAttestPolicy,adminGetAttestObservations:s.adminGetAttestObservations,adminRecordAttestObservations:s.adminRecordAttestObservations,adminListAuditEvents:s.adminListAuditEvents,adminExportAuditEvents:s.adminExportAuditEvents,adminVerifyAuditTrail:s.adminVerifyAuditTrail,adminGetAuthSettings:s.adminGetAuthSettings,adminUpdateAuthSettings:s.adminUpdateAuthSettings,adminGetBreachWatch:s.adminGetBreachWatch,adminListHooks:s.adminListHooks,adminCreateHook:s.adminCreateHook,adminUpdateHook:s.adminUpdateHook,adminDeleteHook:s.adminDeleteHook,adminListHookExecutions:s.adminListHookExecutions,adminListIntegrations:s.adminListIntegrations,adminPutIntegration:s.adminPutIntegration,adminDeleteIntegration:s.adminDeleteIntegration,adminListOAuthClients:s.adminListOAuthClients,adminCreateOAuthClient:s.adminCreateOAuthClient,adminGetOAuthClient:s.adminGetOAuthClient,adminDeleteOAuthClient:s.adminDeleteOAuthClient,adminUpdateOAuthClient:s.adminUpdateOAuthClient,adminListProviders:s.adminListProviders,adminGetPhoneSettings:s.adminGetPhoneSettings,adminUpdatePhoneSettings:s.adminUpdatePhoneSettings,adminToggleProvider:s.adminToggleProvider,adminListRoles:s.adminListRoles,adminUpsertRole:s.adminUpsertRole,adminDeleteRole:s.adminDeleteRole,adminListServiceAccounts:s.adminListServiceAccounts,adminCreateServiceAccount:s.adminCreateServiceAccount,adminGetServiceAccount:s.adminGetServiceAccount,adminRevokeServiceAccount:s.adminRevokeServiceAccount,adminRotateServiceAccount:s.adminRotateServiceAccount,adminListSessions:s.adminListSessions,adminRevokeSession:s.adminRevokeSession,adminListSigningKeys:s.adminListSigningKeys,adminRotateSigningKey:s.adminRotateSigningKey,socialAdminConfig:s.socialAdminConfig,socialCredentialPut:s.socialCredentialPut,socialCredentialDelete:s.socialCredentialDelete,socialProviderPatch:s.socialProviderPatch,adminGetStats:s.adminGetStats,adminSendTestTemplate:s.adminSendTestTemplate,adminListTestUsers:s.adminListTestUsers,adminCreateTestUsers:s.adminCreateTestUsers,adminSetTestUserPhone:s.adminSetTestUserPhone,adminCreateTestSignupAddress:s.adminCreateTestSignupAddress,adminDeleteTestUser:s.adminDeleteTestUser,adminCreateCustomToken:s.adminCreateCustomToken,adminListUsers:s.adminListUsers,adminCreateUser:s.adminCreateUser,adminImportUsers:s.adminImportUsers,adminGetUser:s.adminGetUser,adminDeleteUser:s.adminDeleteUser,adminUpdateUser:s.adminUpdateUser,adminBanUser:s.adminBanUser,adminGetUserConsents:s.adminGetUserConsents,adminRevokeUserCredentials:s.adminRevokeUserCredentials,adminExportUser:s.adminExportUser,adminListUserMfaFactors:s.adminListUserMfaFactors,adminResetUserMfa:s.adminResetUserMfa,adminResetUserPassword:s.adminResetUserPassword,adminListUserRoles:s.adminListUserRoles,adminAssignUserRole:s.adminAssignUserRole,adminRevokeUserRole:s.adminRevokeUserRole,adminRevokeUserSessions:s.adminRevokeUserSessions,adminUnbanUser:s.adminUnbanUser,adminGetInstallationConsents:s.adminGetInstallationConsents,adminRefuseConsents:s.adminRefuseConsents},calls:{adminListCalls:p.adminListCalls,adminGetCall:p.adminGetCall,adminEndCall:p.adminEndCall,createCallTicket:p.createCallTicket,getCallSettings:p.getCallSettings,putCallSettings:p.putCallSettings,rotateCallHookSecret:p.rotateCallHookSecret},flags:{getValues:g.getValues,batchUserValues:g.batchUserValues,getDelta:g.getDelta,getEvaluations:g.getEvaluations,listExperiments:g.listExperiments,startExperiment:g.startExperiment,getExperiment:g.getExperiment,getExperimentResults:g.getExperimentResults,stopExperiment:g.stopExperiment,declareExperimentWinner:g.declareExperimentWinner,getCurrentInstallations:g.getCurrentInstallations,getInstallationsDaily:g.getInstallationsDaily,getSnapshot:g.getSnapshot,listDefinitions:g.listDefinitions,getDefinition:g.getDefinition,putDefinition:g.putDefinition,deleteDefinition:g.deleteDefinition,activateTemplates:g.activateTemplates,getActiveTemplate:g.getActiveTemplate,getTemplateCapabilities:g.getTemplateCapabilities,getTemplateDraft:g.getTemplateDraft,createTemplateDraft:g.createTemplateDraft,discardTemplateDraft:g.discardTemplateDraft,putTemplateParameter:g.putTemplateParameter,removeTemplateParameter:g.removeTemplateParameter,reviewTemplateDraft:g.reviewTemplateDraft,publishTemplate:g.publishTemplate,getPublishReceipt:g.getPublishReceipt,restoreTemplateVersion:g.restoreTemplateVersion,listTemplateVersions:g.listTemplateVersions,getTemplateVersion:g.getTemplateVersion,getUserValues:g.getUserValues,putUserValues:g.putUserValues,deleteUserValues:g.deleteUserValues,putUserValue:g.putUserValue,deleteUserValue:g.deleteUserValue},journeys:{listJourneys:m.listJourneys,createJourney:m.createJourney,listPersonRuns:m.listPersonRuns,simulateJourney:m.simulateJourney,validateJourney:m.validateJourney,getJourney:m.getJourney,updateJourney:m.updateJourney,deleteJourney:m.deleteJourney,copyJourney:m.copyJourney,publishJourney:m.publishJourney,listJourneyRuns:m.listJourneyRuns,getJourneyStats:m.getJourneyStats,stopJourney:m.stopJourney,testJourney:m.testJourney},machines:{listMachines:i.listMachines,createMachine:i.createMachine,listMachineSizes:i.listMachineSizes,getMachineNetwork:i.getMachineNetwork,connectGitHub:i.connectGitHub,listInstallations:i.listInstallations,linkInstallation:i.linkInstallation,shareInstallation:i.shareInstallation,unlinkInstallation:i.unlinkInstallation,listRepositories:i.listRepositories,getMachine:i.getMachine,deleteMachine:i.deleteMachine,updateMachine:i.updateMachine,listBuilds:i.listBuilds,deployMachine:i.deployMachine,listMachinePreviews:i.listMachinePreviews,putMachinePreview:i.putMachinePreview,deleteMachinePreview:i.deleteMachinePreview,listMachineDomains:i.listMachineDomains,addMachineDomain:i.addMachineDomain,deleteMachineDomain:i.deleteMachineDomain,updateMachineDomain:i.updateMachineDomain,getBuild:i.getBuild,getBuildLog:i.getBuildLog,rollbackMachine:i.rollbackMachine,listDatabases:i.listDatabases,createDatabase:i.createDatabase,listDatabaseSizes:i.listDatabaseSizes,getDatabase:i.getDatabase,deleteDatabase:i.deleteDatabase,updateDatabase:i.updateDatabase,undeleteDatabase:i.undeleteDatabase,purgeDatabase:i.purgeDatabase,getDatabaseCredentials:i.getDatabaseCredentials,changeDatabasePassword:i.changeDatabasePassword,readMachineLogs:i.readMachineLogs,getMachineMetrics:i.getMachineMetrics,getMachineContract:i.getMachineContract,restoreDatabase:i.restoreDatabase,getDatabaseSchema:i.getDatabaseSchema,getDatabaseMetrics:i.getDatabaseMetrics,queryDatabase:i.queryDatabase,listCrons:i.listCrons,listCronRuns:i.listCronRuns,runCron:i.runCron,pauseCron:i.pauseCron,resumeCron:i.resumeCron,listTasks:i.listTasks,enqueueTask:i.enqueueTask,getTask:i.getTask,cancelTask:i.cancelTask,retryTask:i.retryTask,listTaskTypes:i.listTaskTypes,makeTemplatedTestUsers:i.makeTemplatedTestUsers,templateTestUser:i.templateTestUser,deleteTemplatedTestUser:i.deleteTemplatedTestUser,listSites:i.listSites,createSite:i.createSite,getSite:i.getSite,deleteSite:i.deleteSite,updateSite:i.updateSite,listSiteReleases:i.listSiteReleases,createSiteRelease:i.createSiteRelease,uploadSiteFile:i.uploadSiteFile,finishSiteRelease:i.finishSiteRelease,rollbackSite:i.rollbackSite,listSiteBuilds:i.listSiteBuilds,deploySite:i.deploySite,listSitePreviews:i.listSitePreviews,listSiteDomains:i.listSiteDomains,addSiteDomain:i.addSiteDomain,deleteSiteDomain:i.deleteSiteDomain,updateSiteDomain:i.updateSiteDomain,getSiteBuild:i.getSiteBuild,authorizeSitePreview:i.authorizeSitePreview,authorizeMachinePreview:i.authorizeMachinePreview,openMachinePreview:i.openMachinePreview,moveMachine:i.moveMachine},messaging:{adminAccessLog:d.adminAccessLog,adminListConversations:d.adminListConversations,adminCreateConversation:d.adminCreateConversation,adminGetConversation:d.adminGetConversation,adminDeleteConversation:d.adminDeleteConversation,adminUpdateConversation:d.adminUpdateConversation,adminAddMembers:d.adminAddMembers,adminRemoveMember:d.adminRemoveMember,adminListMessages:d.adminListMessages,adminSendMessage:d.adminSendMessage,adminDeleteMessage:d.adminDeleteMessage,adminFileUrl:d.adminFileUrl,adminPutProfile:d.adminPutProfile,adminListReports:d.adminListReports,adminGetReport:d.adminGetReport,adminReportFileUrl:d.adminReportFileUrl,adminResolveReport:d.adminResolveReport,getSettings:d.getSettings,putSettings:d.putSettings,rotateHookSecret:d.rotateHookSecret},notify:{getDeliverability:l.getDeliverability,listDevices:l.listDevices,getDeviceStats:l.getDeviceStats,deleteMyDevice:l.deleteMyDevice,sendEmail:l.sendEmail,listInAppCampaigns:l.listInAppCampaigns,createInAppCampaign:l.createInAppCampaign,getInAppCampaign:l.getInAppCampaign,putInAppCampaign:l.putInAppCampaign,deleteInAppCampaign:l.deleteInAppCampaign,getInAppCampaignStats:l.getInAppCampaignStats,listInAppTemplates:l.listInAppTemplates,sendInbox:l.sendInbox,listInboxMessages:l.listInboxMessages,listNotifyMessages:l.listNotifyMessages,getNotifyMessage:l.getNotifyMessage,cancelMessage:l.cancelMessage,getMetricsSummary:l.getMetricsSummary,listNotifyProviders:l.listNotifyProviders,putNotifyProvider:l.putNotifyProvider,deleteNotifyProvider:l.deleteNotifyProvider,sendPush:l.sendPush,getNotifySettings:l.getNotifySettings,putNotifySettings:l.putNotifySettings,sendSms:l.sendSms,listEmailTemplates:l.listEmailTemplates,getEmailTemplate:l.getEmailTemplate,putEmailTemplate:l.putEmailTemplate,deleteEmailTemplate:l.deleteEmailTemplate,listPushTemplates:l.listPushTemplates,getPushTemplate:l.getPushTemplate,putPushTemplate:l.putPushTemplate,deletePushTemplate:l.deletePushTemplate,listSmsTemplates:l.listSmsTemplates,getSmsTemplate:l.getSmsTemplate,putSmsTemplate:l.putSmsTemplate,deleteSmsTemplate:l.deleteSmsTemplate,listWhatsAppTemplates:l.listWhatsAppTemplates,getWhatsAppTemplate:l.getWhatsAppTemplate,putWhatsAppTemplate:l.putWhatsAppTemplate,deleteWhatsAppTemplate:l.deleteWhatsAppTemplate,listTestUserMessages:l.listTestUserMessages,listTopics:l.listTopics,createTopic:l.createTopic,deleteTopic:l.deleteTopic,changeTopic:l.changeTopic,addTopicSubscribers:l.addTopicSubscribers,removeTopicSubscriber:l.removeTopicSubscriber,listUserDevices:l.listUserDevices,getUserPreferences:l.getUserPreferences,setUserPreferences:l.setUserPreferences,startVerification:l.startVerification,checkVerification:l.checkVerification,getWebPushStatus:l.getWebPushStatus,sendWhatsApp:l.sendWhatsApp,listWhatsAppInbound:l.listWhatsAppInbound},purchases:{getAppleAccount:n.getAppleAccount,disconnectApple:n.disconnectApple,createAppleGrant:n.createAppleGrant,getAppleReadiness:n.getAppleReadiness,setXcodeCertificate:n.setXcodeCertificate,clearXcodeCertificate:n.clearXcodeCertificate,getGoogleAccount:n.getGoogleAccount,connectGoogle:n.connectGoogle,disconnectGoogle:n.disconnectGoogle,getCatalog:n.getCatalog,saveCatalog:n.saveCatalog,planCatalog:n.planCatalog,getCatalogPlan:n.getCatalogPlan,confirmCatalogPlan:n.confirmCatalogPlan,declineCatalogPlan:n.declineCatalogPlan,validateCatalog:n.validateCatalog,listCharts:n.listCharts,getChartsOverview:n.getChartsOverview,getChart:n.getChart,getCustomer:n.getCustomer,grantCredits:n.grantCredits,listCreditEntries:n.listCreditEntries,forgiveCredits:n.forgiveCredits,listCustomerGrants:n.listCustomerGrants,grantEntitlement:n.grantEntitlement,revokeGrant:n.revokeGrant,holdSpend:n.holdSpend,setCustomerLimit:n.setCustomerLimit,clearCustomerLimit:n.clearCustomerLimit,grantLimit:n.grantLimit,spend:n.spend,commitSpend:n.commitSpend,extendHold:n.extendHold,releaseSpend:n.releaseSpend,reverseSpend:n.reverseSpend,listExperiments:n.listExperiments,startExperiment:n.startExperiment,getExperiment:n.getExperiment,getExperimentResults:n.getExperimentResults,stopExperiment:n.stopExperiment,declareExperimentWinner:n.declareExperimentWinner,getOfferings:n.getOfferings,listPaywalls:n.listPaywalls,createPaywall:n.createPaywall,listPaywallAssets:n.listPaywallAssets,registerPaywallAsset:n.registerPaywallAsset,deletePaywallAsset:n.deletePaywallAsset,listPaywallTemplates:n.listPaywallTemplates,getPaywallTemplateAsset:n.getPaywallTemplateAsset,validatePaywall:n.validatePaywall,getPaywall:n.getPaywall,deletePaywall:n.deletePaywall,savePaywallDraft:n.savePaywallDraft,publishPaywall:n.publishPaywall,listPaywallVersions:n.listPaywallVersions,getPaywallVersion:n.getPaywallVersion,listPlacements:n.listPlacements,listAttributeKeys:n.listAttributeKeys,setPlacement:n.setPlacement,deletePlacement:n.deletePlacement,recordPaywallExposure:n.recordPaywallExposure,getPlacementPaywall:n.getPlacementPaywall,previewPlacement:n.previewPlacement,getPlacementResults:n.getPlacementResults,getPlacementRules:n.getPlacementRules,setPlacementRules:n.setPlacementRules,getSettings:n.getSettings,updateSettings:n.updateSettings,getStripeAccount:n.getStripeAccount,disconnectStripe:n.disconnectStripe,checkStripeAccount:n.checkStripeAccount,createCheckout:n.createCheckout,createCheckoutRedemption:n.createCheckoutRedemption,createStripeGrant:n.createStripeGrant,createStripeAppInstall:n.createStripeAppInstall,getOfferStats:n.getOfferStats,listCoupons:n.listCoupons,createCoupon:n.createCoupon,getCoupon:n.getCoupon,revokeCoupon:n.revokeCoupon,listCouponCodes:n.listCouponCodes,setXcodeOfferKey:n.setXcodeOfferKey,searchCustomers:n.searchCustomers,getCustomerHistory:n.getCustomerHistory,listCatalogRevisions:n.listCatalogRevisions,getCatalogRevision:n.getCatalogRevision,restoreCatalogRevision:n.restoreCatalogRevision,extendSubscription:n.extendSubscription,refundSubscription:n.refundSubscription,cancelSubscription:n.cancelSubscription},realtime:{broadcast:h.broadcast,getChannels:h.getChannels,putChannels:h.putChannels,getLimits:h.getLimits,putLimits:h.putLimits,revalidate:h.revalidate,writeState:h.writeState,getStats:h.getStats},secrets:{listSecretAudit:c.listSecretAudit,listFieldKeys:c.listFieldKeys,getFieldKeys:c.getFieldKeys,openFields:c.openFields,sealPlaceholder:c.sealPlaceholder,rotateFieldKeys:c.rotateFieldKeys,listTransitKeys:c.listTransitKeys,getTransitKeys:c.getTransitKeys,getTransitPublicKeys:c.getTransitPublicKeys,rotateTransitKeys:c.rotateTransitKeys,retireTransitKey:c.retireTransitKey,listSecrets:c.listSecrets,getEnvironmentValues:c.getEnvironmentValues,getSecret:c.getSecret,putSecret:c.putSecret,deleteSecret:c.deleteSecret,rollbackSecret:c.rollbackSecret,listSecretVersions:c.listSecretVersions},storage:{listBuckets:u.listBuckets,getBucket:u.getBucket,putBucket:u.putBucket,deleteBucket:u.deleteBucket,copyObject:u.copyObject,moveObject:u.moveObject,listObjects:u.listObjects,getObject:u.getObject,putObject:u.putObject,deleteObject:u.deleteObject,headObject:u.headObject,createSignedUrl:u.createSignedUrl,createUploadUrl:u.createUploadUrl,getStorageStats:u.getStorageStats},stores:{listActions:o.listActions,getAction:o.getAction,confirmAction:o.confirmAction,declineAction:o.declineAction,getAppleAccount:o.getAppleAccount,disconnectApple:o.disconnectApple,checkAppleAccount:o.checkAppleAccount,createAppleGrant:o.createAppleGrant,getSandboxReadiness:o.getSandboxReadiness,listSandboxTesters:o.listSandboxTesters,clearSandboxPurchaseHistory:o.clearSandboxPurchaseHistory,updateSandboxTester:o.updateSandboxTester,listApps:o.listApps,listFeedback:o.listFeedback,getFeedback:o.getFeedback,listGroups:o.listGroups,createGroup:o.createGroup,linkApp:o.linkApp,getListing:o.getListing,setListing:o.setListing,planListing:o.planListing,createPackage:o.createPackage,uploadScreenshot:o.uploadScreenshot,getReviewInfo:o.getReviewInfo,setReviewInfo:o.setReviewInfo,getUploadKey:o.getUploadKey,getAppStoreVersion:o.getAppStoreVersion,prepareAppStoreVersion:o.prepareAppStoreVersion,planPhasedRelease:o.planPhasedRelease,planReleaseVersion:o.planReleaseVersion,planSubmitReview:o.planSubmitReview,planWithdrawReview:o.planWithdrawReview,getAppVitals:o.getAppVitals,getAppWebhook:o.getAppWebhook,makeAppWebhook:o.makeAppWebhook,pingAppWebhook:o.pingAppWebhook,getGoogleAccount:o.getGoogleAccount,connectGoogle:o.connectGoogle,disconnectGoogle:o.disconnectGoogle,checkGoogleAccount:o.checkGoogleAccount,deleteGroup:o.deleteGroup,renameGroup:o.renameGroup,addGroupBuild:o.addGroupBuild,listTesters:o.listTesters,setTesters:o.setTesters,listPackages:o.listPackages,getPackage:o.getPackage,planBetaReview:o.planBetaReview,listDeliveries:o.listDeliveries,deliver:o.deliver,getSignedBundleLink:o.getSignedBundleLink,planExpire:o.planExpire,planExportCompliance:o.planExportCompliance,setWhatToTest:o.setWhatToTest,getAppleSession:o.getAppleSession,disconnectAppleSession:o.disconnectAppleSession,checkAppleSession:o.checkAppleSession,createAppleIdGrant:o.createAppleIdGrant,getAppReview:o.getAppReview,getReviewAttachment:o.getReviewAttachment,setReviewDraft:o.setReviewDraft,sendReviewDraft:o.sendReviewDraft,getAppPrivacy:o.getAppPrivacy,setAppPrivacy:o.setAppPrivacy,makeAppRecord:o.makeAppRecord,removeAppRecord:o.removeAppRecord,listMadeAppleKeys:o.listMadeAppleKeys,makeAppleKey:o.makeAppleKey,revokeMadeAppleKey:o.revokeMadeAppleKey,shareAppleSession:o.shareAppleSession,unshareAppleSession:o.unshareAppleSession}}}function K(t){return{orgs:{async list(e){return t.send({op:"orgs.list",method:"GET",path:"/v1/orgs",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e?.signal})},async create(e){return t.send({op:"orgs.create",method:"POST",path:"/v1/orgs",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async get(e){return t.send({op:"orgs.get",method:"GET",path:"/v1/orgs/"+r("orgs.get","id",e.path.id),auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async takeAway(e){return t.send({op:"orgs.takeAway",method:"DELETE",path:"/v1/orgs/"+r("orgs.takeAway","id",e.path.id),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async rename(e){return t.send({op:"orgs.rename",method:"PATCH",path:"/v1/orgs/"+r("orgs.rename","id",e.path.id),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async members(e){return t.send({op:"orgs.members",method:"GET",path:"/v1/orgs/"+r("orgs.members","id",e.path.id)+"/members",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async auditLog(e){return t.send({op:"orgs.auditLog",method:"GET",path:"/v1/orgs/"+r("orgs.auditLog","id",e.path.id)+"/audit",auth:[["PalbaseBearer"]],answers:{200:"json"},query:e.query,signal:e.signal})}},invitations:{async mine(e){return t.send({op:"invitations.mine",method:"GET",path:"/v1/invitations",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e?.signal})},async accept(e){return t.send({op:"invitations.accept",method:"POST",path:"/v1/invitations/"+r("invitations.accept","id",e.path.id)+"/accept",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})}},orgWebhooks:{async list(e){return t.send({op:"orgWebhooks.list",method:"GET",path:"/v1/orgs/"+r("orgWebhooks.list","id",e.path.id)+"/webhooks",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async add(e){return t.send({op:"orgWebhooks.add",method:"POST",path:"/v1/orgs/"+r("orgWebhooks.add","id",e.path.id)+"/webhooks",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async remove(e){return t.send({op:"orgWebhooks.remove",method:"DELETE",path:"/v1/orgs/"+r("orgWebhooks.remove","id",e.path.id)+"/webhooks/"+r("orgWebhooks.remove","endpoint",e.path.endpoint),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})}},projects:{async mine(e){return t.send({op:"projects.mine",method:"GET",path:"/v1/projects",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e?.signal})},async environmentsMine(e){return t.send({op:"projects.environmentsMine",method:"GET",path:"/v1/environments",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e?.signal})},async list(e){return t.send({op:"projects.list",method:"GET",path:"/v1/orgs/"+r("projects.list","id",e.path.id)+"/projects",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async create(e){return t.send({op:"projects.create",method:"POST",path:"/v1/orgs/"+r("projects.create","id",e.path.id)+"/projects",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async get(e){return t.send({op:"projects.get",method:"GET",path:"/v1/projects/"+r("projects.get","id",e.path.id),auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async remove(e){return t.send({op:"projects.remove",method:"DELETE",path:"/v1/projects/"+r("projects.remove","id",e.path.id),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async rename(e){return t.send({op:"projects.rename",method:"PATCH",path:"/v1/projects/"+r("projects.rename","id",e.path.id),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async addEnvironment(e){return t.send({op:"projects.addEnvironment",method:"POST",path:"/v1/projects/"+r("projects.addEnvironment","id",e.path.id)+"/environments",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async environment(e){return t.send({op:"projects.environment",method:"GET",path:"/v1/environments/"+r("projects.environment","ref",e.path.ref),auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async removeEnvironment(e){return t.send({op:"projects.removeEnvironment",method:"DELETE",path:"/v1/environments/"+r("projects.removeEnvironment","ref",e.path.ref),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,query:e.query,headers:e.headers,signal:e.signal})},async renameEnvironment(e){return t.send({op:"projects.renameEnvironment",method:"PATCH",path:"/v1/environments/"+r("projects.renameEnvironment","ref",e.path.ref),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async keys(e){return t.send({op:"projects.keys",method:"GET",path:"/v1/environments/"+r("projects.keys","ref",e.path.ref)+"/keys",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async usage(e){return t.send({op:"projects.usage",method:"GET",path:"/v1/environments/"+r("projects.usage","ref",e.path.ref)+"/usage",auth:[["PalbaseBearer"]],answers:{200:"json"},query:e.query,signal:e.signal})},async personalKey(e){return t.send({op:"projects.personalKey",method:"POST",path:"/v1/environments/"+r("projects.personalKey","ref",e.path.ref)+"/personal-key",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async revokePersonalKey(e){return t.send({op:"projects.revokePersonalKey",method:"DELETE",path:"/v1/environments/"+r("projects.revokePersonalKey","ref",e.path.ref)+"/personal-key/"+r("projects.revokePersonalKey","key",e.path.key),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async shareInstallation(e){return t.send({op:"projects.shareInstallation",method:"POST",path:"/v1/environments/"+r("projects.shareInstallation","ref",e.path.ref)+"/github/installations",auth:[["PalbaseBearer"]],answers:{},ownResponse:!0,idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})}},apps:{async list(e){return t.send({op:"apps.list",method:"GET",path:"/v1/projects/"+r("apps.list","id",e.path.id)+"/apps",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async create(e){return t.send({op:"apps.create",method:"POST",path:"/v1/projects/"+r("apps.create","id",e.path.id)+"/apps",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async get(e){return t.send({op:"apps.get",method:"GET",path:"/v1/projects/"+r("apps.get","id",e.path.id)+"/apps/"+r("apps.get","app",e.path.app),auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async remove(e){return t.send({op:"apps.remove",method:"DELETE",path:"/v1/projects/"+r("apps.remove","id",e.path.id)+"/apps/"+r("apps.remove","app",e.path.app),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})},async update(e){return t.send({op:"apps.update",method:"PATCH",path:"/v1/projects/"+r("apps.update","id",e.path.id)+"/apps/"+r("apps.update","app",e.path.app),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async restore(e){return t.send({op:"apps.restore",method:"POST",path:"/v1/projects/"+r("apps.restore","id",e.path.id)+"/apps/"+r("apps.restore","app",e.path.app)+"/restore",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})},async setIn(e){return t.send({op:"apps.setIn",method:"PUT",path:"/v1/environments/"+r("apps.setIn","ref",e.path.ref)+"/apps/"+r("apps.setIn","app",e.path.app),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async removeFrom(e){return t.send({op:"apps.removeFrom",method:"DELETE",path:"/v1/environments/"+r("apps.removeFrom","ref",e.path.ref)+"/apps/"+r("apps.removeFrom","app",e.path.app),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async config(e){return t.send({op:"apps.config",method:"GET",path:"/v1/environments/"+r("apps.config","ref",e.path.ref)+"/apps/"+r("apps.config","app",e.path.app)+"/config",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})}},snippets:{async list(e){return t.send({op:"snippets.list",method:"GET",path:"/v1/environments/"+r("snippets.list","ref",e.path.ref)+"/snippets",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async create(e){return t.send({op:"snippets.create",method:"POST",path:"/v1/environments/"+r("snippets.create","ref",e.path.ref)+"/snippets",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async remove(e){return t.send({op:"snippets.remove",method:"DELETE",path:"/v1/environments/"+r("snippets.remove","ref",e.path.ref)+"/snippets/"+r("snippets.remove","id",e.path.id),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async change(e){return t.send({op:"snippets.change",method:"PATCH",path:"/v1/environments/"+r("snippets.change","ref",e.path.ref)+"/snippets/"+r("snippets.change","id",e.path.id),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})}},chartViews:{async list(e){return t.send({op:"chartViews.list",method:"GET",path:"/v1/environments/"+r("chartViews.list","ref",e.path.ref)+"/chart-views",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async create(e){return t.send({op:"chartViews.create",method:"POST",path:"/v1/environments/"+r("chartViews.create","ref",e.path.ref)+"/chart-views",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async remove(e){return t.send({op:"chartViews.remove",method:"DELETE",path:"/v1/environments/"+r("chartViews.remove","ref",e.path.ref)+"/chart-views/"+r("chartViews.remove","id",e.path.id),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async change(e){return t.send({op:"chartViews.change",method:"PATCH",path:"/v1/environments/"+r("chartViews.change","ref",e.path.ref)+"/chart-views/"+r("chartViews.change","id",e.path.id),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})}},webhooks:{async list(e){return t.send({op:"webhooks.list",method:"GET",path:"/v1/environments/"+r("webhooks.list","ref",e.path.ref)+"/webhooks",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async add(e){return t.send({op:"webhooks.add",method:"POST",path:"/v1/environments/"+r("webhooks.add","ref",e.path.ref)+"/webhooks",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async deliveries(e){return t.send({op:"webhooks.deliveries",method:"GET",path:"/v1/environments/"+r("webhooks.deliveries","ref",e.path.ref)+"/webhooks/deliveries",auth:[["PalbaseBearer"]],answers:{200:"json"},query:e.query,signal:e.signal})},async redeliver(e){return t.send({op:"webhooks.redeliver",method:"POST",path:"/v1/environments/"+r("webhooks.redeliver","ref",e.path.ref)+"/webhooks/deliveries/"+r("webhooks.redeliver","delivery",e.path.delivery)+"/redeliver",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})},async change(e){return t.send({op:"webhooks.change",method:"PUT",path:"/v1/environments/"+r("webhooks.change","ref",e.path.ref)+"/webhooks/"+r("webhooks.change","endpoint",e.path.endpoint),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async remove(e){return t.send({op:"webhooks.remove",method:"DELETE",path:"/v1/environments/"+r("webhooks.remove","ref",e.path.ref)+"/webhooks/"+r("webhooks.remove","endpoint",e.path.endpoint),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})}},environmentTokens:{async list(e){return t.send({op:"environmentTokens.list",method:"GET",path:"/v1/environments/"+r("environmentTokens.list","ref",e.path.ref)+"/tokens",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async mint(e){return t.send({op:"environmentTokens.mint",method:"POST",path:"/v1/environments/"+r("environmentTokens.mint","ref",e.path.ref)+"/tokens",auth:[["PalbaseBearer"],[]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async revoke(e){return t.send({op:"environmentTokens.revoke",method:"DELETE",path:"/v1/environments/"+r("environmentTokens.revoke","ref",e.path.ref)+"/tokens/"+r("environmentTokens.revoke","id",e.path.id),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})}},billing:{async bill(e){return t.send({op:"billing.bill",method:"GET",path:"/v1/orgs/"+r("billing.bill","id",e.path.id)+"/billing",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async confirm(e){return t.send({op:"billing.confirm",method:"POST",path:"/v1/orgs/"+r("billing.confirm","id",e.path.id)+"/billing/checkout/"+r("billing.confirm","session",e.path.session)+"/confirm",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})},async cards(e){return t.send({op:"billing.cards",method:"GET",path:"/v1/orgs/"+r("billing.cards","id",e.path.id)+"/billing/cards",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async defaultCard(e){return t.send({op:"billing.defaultCard",method:"PUT",path:"/v1/orgs/"+r("billing.defaultCard","id",e.path.id)+"/billing/cards/"+r("billing.defaultCard","card",e.path.card)+"/default",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})},async removeCard(e){return t.send({op:"billing.removeCard",method:"DELETE",path:"/v1/orgs/"+r("billing.removeCard","id",e.path.id)+"/billing/cards/"+r("billing.removeCard","card",e.path.card),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,signal:e.signal})},async customer(e){return t.send({op:"billing.customer",method:"GET",path:"/v1/orgs/"+r("billing.customer","id",e.path.id)+"/billing/customer",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async setCustomer(e){return t.send({op:"billing.setCustomer",method:"PUT",path:"/v1/orgs/"+r("billing.setCustomer","id",e.path.id)+"/billing/customer",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async charges(e){return t.send({op:"billing.charges",method:"GET",path:"/v1/orgs/"+r("billing.charges","id",e.path.id)+"/billing/charges",auth:[["PalbaseBearer"]],answers:{200:"json"},query:e.query,signal:e.signal})},async csv(e){return t.send({op:"billing.csv",method:"GET",path:"/v1/orgs/"+r("billing.csv","id",e.path.id)+"/billing/charges.csv",auth:[["PalbaseBearer"]],answers:{},ownResponse:!0,query:e.query,signal:e.signal})},async invoices(e){return t.send({op:"billing.invoices",method:"GET",path:"/v1/orgs/"+r("billing.invoices","id",e.path.id)+"/billing/invoices",auth:[["PalbaseBearer"]],answers:{200:"json"},query:e.query,signal:e.signal})},async payer(e){return t.send({op:"billing.payer",method:"PUT",path:"/v1/orgs/"+r("billing.payer","id",e.path.id)+"/billing/payer",auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})},async paid(e){return t.send({op:"billing.paid",method:"GET",path:"/v1/orgs/"+r("billing.paid","id",e.path.id)+"/billing/paid",auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async stopPaying(e){return t.send({op:"billing.stopPaying",method:"DELETE",path:"/v1/orgs/"+r("billing.stopPaying","id",e.path.id)+"/billing/paid/"+r("billing.stopPaying","org",e.path.org),auth:[["PalbaseBearer"]],answers:{204:"empty"},idempotent:!0,headers:e.headers,signal:e.signal})},async report(e){return t.send({op:"billing.report",method:"GET",path:"/v1/orgs/"+r("billing.report","id",e.path.id)+"/billing/report",auth:[["PalbaseBearer"]],answers:{200:"json"},query:e.query,signal:e.signal})},async reportCsv(e){return t.send({op:"billing.reportCsv",method:"GET",path:"/v1/orgs/"+r("billing.reportCsv","id",e.path.id)+"/billing/report.csv",auth:[["PalbaseBearer"]],answers:{},ownResponse:!0,query:e.query,signal:e.signal})},async environment(e){return t.send({op:"billing.environment",method:"GET",path:"/v1/orgs/"+r("billing.environment","id",e.path.id)+"/billing/environments/"+r("billing.environment","ref",e.path.ref),auth:[["PalbaseBearer"]],answers:{200:"json"},signal:e.signal})},async steer(e){return t.send({op:"billing.steer",method:"PATCH",path:"/v1/orgs/"+r("billing.steer","id",e.path.id)+"/billing/environments/"+r("billing.steer","ref",e.path.ref),auth:[["PalbaseBearer"]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})}},accessRequests:{async request(e){return t.send({op:"accessRequests.request",method:"POST",path:"/v1/access-requests",auth:[["PalbaseBearer"],[]],answers:{200:"json"},idempotent:!0,headers:e.headers,body:{kind:"json",contentType:"application/json",value:e.body},signal:e.signal})}},docs:{async search(e){return t.send({op:"docs.search",method:"GET",path:"/v1/docs/search",auth:[["PalbaseBearer"],[]],answers:{200:"json"},query:e.query,signal:e.signal})}}}}function V(t){let{mint:e,revoke:a}=t;return async s=>{let p=await e(s),g=s.body?.role,m=s.body?.on_behalf_of;if(g===void 0&&m===void 0)return p;let i=p.data,d=[];if(g!==void 0&&i.role!==g&&d.push(`role ${g} (it came back ${i.role==null?"at its minter's":i.role})`),m!==void 0&&i.on_behalf_of!==m.trim()&&d.push("on_behalf_of"),d.length===0)return p;let l;try{await a({path:{ref:s.path.ref,id:String(i.id)}})}catch(h){l=h}let n=`Studio minted the token without the ${d.join(" and ")} asked for \u2014 it is older than this SDK`;throw new y({op:"environmentTokens.mint",status:0,code:"token_role_not_kept",message:l===void 0?`environmentTokens.mint: ${n}; the token (${i.id}) was revoked at once and is not returned \u2014 mint it again once Studio is updated`:`environmentTokens.mint: ${n}, and revoking it failed (${l instanceof Error?l.message:String(l)}) \u2014 revoke token ${i.id} of environment ${s.path.ref} yourself, now`,cause:l})}}var _={pbo_:"an organization's",pbu_:"an account's",pbe_:"an environment's"},J=/^[A-Za-z0-9_-]*$/,O=64,b=44;function W(t){if(typeof t!="string"||t==="")return"token is missing: pass an access token, an organization's (pbo_\u2026), an account's (pbu_\u2026) or an environment's (pbe_\u2026)";let e=t.slice(0,4);if(!Object.hasOwn(_,e))return`token has the wrong prefix: an access token starts with pbo_ (an organization's), pbu_ (an account's) or pbe_ (an environment's)${/^pb_[a-z0-9]+_[cs]/.test(t)?" \u2014 a project key belongs in palbase/server or palbase/web":""}`;let a=t.slice(4);if(a.length!==O)return`token has the wrong length: ${_[e]} access token is ${e} and ${O} characters, this one has ${a.length} after it`;if(!J.test(a))return`token is not ${_[e]} access token: after ${e} come base64url characters alone (A\u2013Z, a\u2013z, 0\u20139, - and _)`;let s=X(a),p=(s[b]<<24|s[b+1]<<16|s[b+2]<<8|s[b+3])>>>0;if(Y(e,s.subarray(0,b))!==p)return"token's checksum does not match: it was mistyped or cut, or made before access tokens carried one \u2014 make a new token"}function N(t){return W(t)===void 0}function q(t){let e=W(t);if(e!==void 0)throw new TypeError(e)}var $="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";function X(t){let e=new Uint8Array(t.length*6/8),a=0,s=0,p=0;for(let g of t)a=a<<6|$.indexOf(g),s+=6,s>=8&&(s-=8,e[p++]=a>>s&255);return e}var z=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let a=e;for(let s=0;s<8;s++)a=a&1?3988292384^a>>>1:a>>>1;t[e]=a>>>0}return t})();function Y(t,e){let a=4294967295;for(let s=0;s<t.length;s++)a=z[(a^t.charCodeAt(s))&255]^a>>>8;for(let s of e)a=z[(a^s)&255]^a>>>8;return(a^4294967295)>>>0}var F="palbase.studio",Z="palbase";function Q(){let t=globalThis;return typeof t.window<"u"||typeof t.document<"u"||typeof t.importScripts=="function"||I()}var f=class{domain;#e;#t=new Map;constructor(e){if(Q())throw new TypeError("palbase/cloud runs on a server: its access token opens the organization's projects, so it never goes into a browser, a web worker or a mobile app \u2014 keep it on your server, and have your app call that");q(e?.token);let a=e.domain??F;if(typeof a!="string"||!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(a))throw new TypeError(`domain ${JSON.stringify(a)} is not a domain`);this.domain=a;let s=e.token;this.#e=g=>B(v({baseUrl:g,credentials:{token:s},fetch:e.fetch,solveProofOfWork:!1}),e.retry??G);let p=K(this.#e(`https://palbase.app.${a}`));p.environmentTokens.mint=V(p.environmentTokens),Object.assign(this,p)}project(e){if(typeof e!="string"||!/^[a-z0-9]{1,63}$/.test(e))throw new TypeError(`${JSON.stringify(e)} is not an environment's ref`);let a=this.#t.get(e);return a||(a=L(this.#e(e===Z?`https://connect.${this.domain}`:`https://${e}.${this.domain}`)),this.#t.set(e,a)),a}};export{F as DEFAULT_DOMAIN,f as PalbaseCloud,y as PalbaseError,N as tokenIsWellFormed};
package/dist/refuse/ai.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palbase 0.37.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.37.2 — 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.37.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.37.2 — 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.37.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.37.2 — 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.37.1 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.37.2 — 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.37.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/SRDV2B4P.js";import{a as c,b as d}from"../chunks/MW7YMYNO.js";import"../chunks/GCVJJS4Y.js";import"../chunks/H6LQPKWU.js";import{p as b}from"../chunks/I6H2425X.js";import"../chunks/PMT4A5UW.js";import{b as a}from"../chunks/IZ6RIKPB.js";import"../chunks/AYPQOPOF.js";import"../chunks/RAPT7CYO.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.37.2 — 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/YQQHL67Y.js";import{a as c,b as d}from"../chunks/UBQK5O7J.js";import"../chunks/YLLZC52Q.js";import"../chunks/HMDMAILZ.js";import{p as b}from"../chunks/L3S7O5FQ.js";import"../chunks/LANEQ73A.js";import{b as a}from"../chunks/4Y47I6LA.js";import"../chunks/CHXCVOON.js";import"../chunks/72CHRRHY.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.37.1 — Palbase SDK License (see LICENSE) */
2
- import{a,b,c,d,e}from"../chunks/JEA6LCOK.js";import"../chunks/MW7YMYNO.js";import"../chunks/AYPQOPOF.js";import"../chunks/RAPT7CYO.js";export{b as TestApiError,e as api,c as createTestApi,a as testFields,d as testRun};
1
+ /*! palbase 0.37.2 — Palbase SDK License (see LICENSE) */
2
+ import{a,b,c,d,e}from"../chunks/VAPNSTWC.js";import"../chunks/UBQK5O7J.js";import"../chunks/CHXCVOON.js";import"../chunks/72CHRRHY.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.37.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/LEBJY4WH.js";import{a as _,b as Q,f as z}from"../chunks/UA3CCXS4.js";import"../chunks/YT7ZMYMN.js";import"../chunks/GHUIGLRJ.js";import"../chunks/XYRYBY7I.js";import"../chunks/TPQAYDWC.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/GCVJJS4Y.js";import"../chunks/I6H2425X.js";import"../chunks/PMT4A5UW.js";import{b as L}from"../chunks/IZ6RIKPB.js";import"../chunks/AYPQOPOF.js";import"../chunks/RAPT7CYO.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.37.2 — 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/A6LIFQOQ.js";import{a as _,b as Q,f as z}from"../chunks/SEECU52P.js";import"../chunks/QK2S67K3.js";import"../chunks/GEZH3OTX.js";import"../chunks/5HYKOPCW.js";import"../chunks/IOVYIATC.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/YLLZC52Q.js";import"../chunks/L3S7O5FQ.js";import"../chunks/LANEQ73A.js";import{b as L}from"../chunks/4Y47I6LA.js";import"../chunks/CHXCVOON.js";import"../chunks/72CHRRHY.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};