palbase 0.76.0 → 0.78.0

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 (78) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai-sdk/index.js +2 -2
  3. package/dist/backend/engine.js +2 -2
  4. package/dist/backend/env.js +1 -1
  5. package/dist/backend/index.js +3 -3
  6. package/dist/backend/stack.js +1 -1
  7. package/dist/backend/test.js +2 -2
  8. package/dist/chunks/3I5XH3A3.js +13 -0
  9. package/dist/chunks/{MKVIRNSJ.js → 3X3ZT72M.js} +2 -2
  10. package/dist/chunks/{TGQGGUE6.js → 5H3UYFOC.js} +2 -2
  11. package/dist/chunks/5OBOVEK6.js +2 -0
  12. package/dist/chunks/{KEGVHELA.js → AKJC5WTU.js} +1 -1
  13. package/dist/chunks/{TUK6NH2Q.js → AMKY4SZU.js} +2 -2
  14. package/dist/chunks/B64J3E3T.js +2 -0
  15. package/dist/chunks/{5RNXCTOO.js → EFELMJMQ.js} +2 -2
  16. package/dist/chunks/{ZCMCYI2D.js → FOZVJW7G.js} +2 -2
  17. package/dist/chunks/{BRDO3ZPT.js → HHKRAOVG.js} +1 -1
  18. package/dist/chunks/{ISMWEEGW.js → HVRVTNMI.js} +1 -1
  19. package/dist/chunks/{SVWF7ABJ.js → JSRN4NOZ.js} +2 -2
  20. package/dist/chunks/{33XOVYAU.js → MA74JJUB.js} +4 -4
  21. package/dist/chunks/{UHN63FGH.js → MFWAOKLM.js} +2 -2
  22. package/dist/chunks/{PGQNRJ2C.js → NG4OMSEK.js} +2 -2
  23. package/dist/chunks/{5YJZAPY2.js → NQUAVRMC.js} +2 -2
  24. package/dist/chunks/{EXLA3A7O.js → Q3GH7I66.js} +2 -2
  25. package/dist/chunks/{3CN6HGTW.js → QL2UAO36.js} +1 -1
  26. package/dist/chunks/{DKYFIOWM.js → QOETZ4FB.js} +1 -1
  27. package/dist/chunks/RP2TPMXT.js +2 -0
  28. package/dist/chunks/S7C7NHZI.js +18 -0
  29. package/dist/chunks/{D6NOE76D.js → SHYJVOD2.js} +1 -1
  30. package/dist/chunks/{A3I7H7QN.js → VP3HFVV4.js} +1 -1
  31. package/dist/chunks/{UOW74IHY.js → XVJ3CMFN.js} +2 -2
  32. package/dist/chunks/{Q4UWBIJ6.js → YQQKZUVS.js} +2 -2
  33. package/dist/cli.js +243 -187
  34. package/dist/cloud/index.js +2 -2
  35. package/dist/refuse/ai-sdk.js +1 -1
  36. package/dist/refuse/ai.js +1 -1
  37. package/dist/refuse/backend.js +1 -1
  38. package/dist/refuse/cloud.js +1 -1
  39. package/dist/refuse/server.js +1 -1
  40. package/dist/server/index.js +2 -2
  41. package/dist/server/testing.js +2 -2
  42. package/dist/web/index.js +2 -2
  43. package/dist/web/message.js +2 -2
  44. package/dist/web/palbe.js +2 -2
  45. package/dist/web/payments-ui.js +2 -2
  46. package/dist/web/paywall.js +2 -2
  47. package/dist/web/push-sw.js +1 -1
  48. package/dist/web/ssr.js +2 -2
  49. package/dist/web/vite.js +2 -2
  50. package/package.json +2 -2
  51. package/types/ai/src/ai.d.ts +6 -2
  52. package/types/ai/src/chats.d.ts +29 -10
  53. package/types/ai/src/index.d.ts +2 -2
  54. package/types/ai/src/pools.d.ts +15 -24
  55. package/types/cloud/src/generated/project.d.ts +3 -3
  56. package/types/cloud/src/generated/studio.d.ts +4 -6
  57. package/types/internal/src/ai-machines.d.ts +120 -0
  58. package/types/internal/src/chat.d.ts +29 -1
  59. package/types/internal/src/modules/ai.d.ts +192 -79
  60. package/types/internal/src/modules/analytics.d.ts +5 -1
  61. package/types/internal/src/modules/auth.d.ts +3 -28
  62. package/types/internal/src/modules/commerce.d.ts +92 -13
  63. package/types/internal/src/modules/events.d.ts +2 -2
  64. package/types/internal/src/modules/iap.d.ts +2 -2
  65. package/types/internal/src/modules/journeys.d.ts +2 -2
  66. package/types/internal/src/modules/machines.d.ts +33 -33
  67. package/types/internal/src/modules/notify.d.ts +2 -2
  68. package/types/internal/src/modules/payments.d.ts +83 -14
  69. package/types/internal/src/modules/stores.d.ts +3 -3
  70. package/types/internal/src/modules/workspaces.d.ts +5 -5
  71. package/types/web/src/ai-machines.d.ts +76 -0
  72. package/types/web/src/chat.d.ts +21 -1
  73. package/types/web/src/index.d.ts +3 -1
  74. package/types/web/src/templates.d.ts +8 -0
  75. package/dist/chunks/2NEPN2ZZ.js +0 -2
  76. package/dist/chunks/3VGWTVKI.js +0 -2
  77. package/dist/chunks/ALT62XIG.js +0 -13
  78. package/dist/chunks/YRYPXVAJ.js +0 -18
@@ -1,2 +1,2 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{b as C}from"./BRDO3ZPT.js";import{a as ue}from"./KEGVHELA.js";import{a as D,b as j,c as U,d as I,e as K,f as q,g as F,h as $,i as N,j as V,k as J,l as z,m as Y,n as G,o as X,p as Z,q as Q,r as ee,s as te}from"./3VGWTVKI.js";import{a as w,c as oe,d as se,e as ie,f as ae,h as ce,i as pe,j as M,k as le,l as de,o as A}from"./A3I7H7QN.js";import{a as ne,b as re}from"./SVWF7ABJ.js";import{b as T,d as b}from"./UOW74IHY.js";var h=class extends Error{status=400;code;data;constructor(e,n,r={}){super(n),this.name="TransitRefusal",this.code=e,this.data=r}},Le=6e4,Be=1e3;function O(t){return/^t[1-9][0-9]{0,5}$/.test(t)?Number(t.slice(1)):0}var S=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??(n=>new Promise(r=>setTimeout(r,n)))}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(()=>{})},Le),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let n=this.now();try{let r=await this.opts.fetch(e),o=new Map;for(let s of r.keys){let i=se(s.key);o.set(s.id,{privateKey:i,publicKey:this.keys.get(s.id)?.publicKey??await ie(i)})}this.keys=o,this.order=r.keys.map(s=>s.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=n}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(O),...[...this.retired].map(O))}async key(e){let n=this.now();for(;O(e)>this.newest()&&this.heldFrom<n;){let s=this.fetchedAt+Be-this.now();if(s>0){await this.sleep(s);continue}await this.refresh()}let r=this.keys.get(e),o=this.current();if(this.retired.has(e))throw new h("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:o});if(r===void 0)throw new h("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:o});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new h("encryption_required",`this route carries encrypted fields: the request names its key in ${w}`,{field:w,current:this.current()});let n;try{n=ce(e.header).kid}catch{throw new h("encryption_unopenable",`${w} is not one`,{field:w})}let r=await this.key(n),o;try{o=ae(this.projectId,e.method,e.path,e.params??[])}catch{throw new h("encryption_unopenable","the request's path holds a value no key is sealed for",{field:w})}try{return new R(n,await pe(e.header,r.privateKey,r.publicKey,o))}catch(s){throw s instanceof oe?new h("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:w}):s}}},R=class{kid;key;constructor(e,n){this.kid=e,this.key=n}async open(e,n,r){return A(e,n,r,async(o,s)=>{if(!le(s))throw new h("encryption_required",`${o} is an encrypted field: it came plain`,{field:o});try{return await de(this.key,o,s)}catch{throw new h("encryption_unopenable",`${o} does not open: changed, moved from another field, or another request's`,{field:o})}})}async seal(e,n){return A(e,"/response",n,(r,o)=>M(this.key,r,o))}sealField(e,n){return M(this.key,e,n)}};var De=/^pb_[a-z0-9]+_s/;function H(t){if(ue())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 t.secretKey!="string"||!De.test(t.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=re(b({baseUrl:t.url,credentials:{secretKey:t.secretKey},fetch:t.fetch,solveProofOfWork:t.solveProofOfWork??!1}),t.retry??ne),n=Z.client(e);return{ai:D.client(e),analytics:j.client(e),auth:U.client(e),cache:I.client(e),calls:K.client(e),fields:new C({fetch:async r=>(await n.getFieldKeys({signal:r})).data}),flags:$.client(e),iap:N.client(e),machines:J.client(e),messaging:z.client(e),notify:Y.client(e),payments:G.client(e),campaigns:q.client(e),commerce:F.client(e),journeys:V.client(e),realtime:X.client(e),secrets:n,storage:Q.client(e),stores:ee.client(e),workspaces:te.client(e),transit:new S({fetch:async r=>(await n.getTransitKeys({signal:r})).data}),transport:e,url:new URL(t.url).origin}}var u=class extends Error{code;constructor(e,n){super(n),this.name="WebhookSignatureError",this.code=e}},Ue=300,Ie=/^[0-9]{1,12}$/,Ke=/^[0-9a-f]{64}$/,ye=8,qe=/^whsec_[0-9A-Za-z]{32,}$/,Fe=1024*1024;async function me(t){if(typeof t.secret!="string"||!qe.test(t.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await he(t);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(ge(t.body)))}catch{throw new u("invalid_body","the signed body is not JSON")}if(!Ye(e))throw new u("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function he(t){if(typeof t.secret!="string"||t.secret==="")throw new TypeError("secret is the key the request was signed with");let e=ge(t.body),{t:n,v1:r}=fe(t),o=await crypto.subtle.importKey("raw",new TextEncoder().encode(t.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=new Uint8Array(await crypto.subtle.sign("HMAC",o,ze(new TextEncoder().encode(`${n}.`),e))),i=!1;for(let p of r)Je(s,Ve(p))&&(i=!0);if(!i)throw new u("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function fe(t){let e=t.toleranceSeconds??Ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(t.toleranceSeconds)})`);let n=(t.now??Date.now)();if(!Number.isFinite(n))throw new TypeError(`now() returns epoch milliseconds (got ${String(n)})`);let r=t.signature;if(typeof r!="string"||r.trim()==="")throw new u("missing_signature","the request carries no Palbase-Signature header");let o,s=[];for(let i of r.split(",")){let p=i.indexOf("=");if(p<=0)throw new u("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=i.slice(0,p).trim(),a=i.slice(p+1).trim();if(c==="t"){if(o!==void 0||!Ie.test(a))throw new u("malformed_signature","Palbase-Signature carries one t, in unix seconds");o=a}else if(c==="v1"){if(!Ke.test(a))throw new u("malformed_signature","a v1 is 64 lowercase hex characters");if(s.length===ye)throw new u("malformed_signature",`Palbase-Signature carries at most ${ye} v1`);s.push(a)}}if(o===void 0||s.length===0)throw new u("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(n/1e3-Number(o))>e)throw new u("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:o,v1:s}}async function $e(t,e,n={}){let r=await Ne(t,n.maxBytes??Fe);return me({toleranceSeconds:n.toleranceSeconds,now:n.now,secret:e,signature:t.headers.get("palbase-signature"),body:r})}async function Ne(t,e){let n=()=>new u("body_too_large",`the body is larger than ${e} bytes`),r=Number(t.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw n();if(!t.body)return new Uint8Array(0);let o=t.body.getReader(),s=[],i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;if(i+=l.byteLength,i>e)throw await o.cancel().catch(()=>{}),n();s.push(l)}let p=new Uint8Array(i),c=0;for(let a of s)p.set(a,c),c+=a.byteLength;return p}function ge(t){if(typeof t=="string")return new TextEncoder().encode(t);if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);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 Ve(t){let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}function Je(t,e){if(t.byteLength!==e.byteLength)return!1;let n=0;for(let r=0;r<t.byteLength;r++)n|=t[r]^e[r];return n===0}function ze(t,e){let n=new Uint8Array(t.byteLength+e.byteLength);return n.set(t,0),n.set(e,t.byteLength),n}function Ye(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var we=60,Ge=60,Xe=8*1024,Ze=1e5;function W(t){let e=t instanceof Uint8Array?t:new Uint8Array(t),n="";for(let r of e)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ve(t){let e=t.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let n=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function ke(t){let e=ve(t);if(e)try{let n=JSON.parse(new TextDecoder().decode(e));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0}catch{return}}var x=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=Ze){this.max=e}spend(e,n){if(n>=e.until)throw new d("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,n);let o=r.get(e.jti);if(o!==void 0&&o>n)throw new d("proof","the DPoP proof is not taken: it was used before");o!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(n),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,n,r){for(let[o,s]of n){if(s>r)break;n.delete(o),this.held--}n.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,o]of this.byKey){for(let[s,i]of o)i>e||(o.delete(s),this.held--);o.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 n=[...this.byKey].sort((r,o)=>o[1].size-r[1].size);for(let[r,o]of n){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=o.size}}};async function Qe(t,e){let n=`{"crv":"P-256","kty":"EC","x":"${t}","y":"${e}"}`;return W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)))}function Se(t){try{let e=new URL(t);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function be(t,e,n,r){let o=We=>{throw new d("proof",`the DPoP proof is not taken: ${We}`)},s=n.proof;if(!s)return o("there is none (a DPoP-bound token comes with a DPoP header)");if(s.length>Xe)return o("it is too long");let i=s.split(".");if(i.length!==3)return o("it is not a JWS of three parts");let p=ke(i[0]),c=ke(i[1]);if(!p||!c)return o("its header or claims are not base64url JSON");if(p.typ!=="dpop+jwt")return o("its typ is not dpop+jwt");if(p.alg!=="ES256")return o(`it is signed with ${String(p.alg)}; only ES256 is taken`);let a=p.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return o("its header carries no P-256 public key");if("d"in a)return o("its header carries a private key");if(await Qe(a.x,a.y)!==e)return o("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 o("its key is not a P-256 point")}let y=ve(i[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${i[0]}.${i[1]}`)).catch(()=>!1))return o("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==n.method.toUpperCase())return o(`it is for ${String(c.htm)}, not ${n.method}`);let m=typeof c.htu=="string"?Se(c.htu):void 0,f=Se(n.url);if(!m||!f||m!==f)return o(`it is for ${String(c.htu)}, not ${f??n.url}`);let v=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-v)>we)return o("it was not made within a minute of now");let Oe=W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)));if(c.ath!==Oe)return o("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return o("it has no jti (or one longer than 256)");let He=W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:He,until:(c.iat+we+Ge)*1e3+1}}var d=class extends Error{reason;constructor(e,n){super(n),this.name="TokenError",this.reason=e}},k=class extends Error{constructor(e,n){super(e,n),this.name="AuthUnavailable"}},et=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function tt(t){return async e=>{let n=b({baseUrl:t.url,credentials:{secretKey:t.secretKey,accessToken:()=>e},fetch:t.fetch});try{return await n.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&&!et.has(r.code))return!1;throw new k("a session's standing could not be told",{cause:r})}}}var L={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}}},Re=60,nt=16*1024,rt=10*6e4,ot=5e4,xe=t=>typeof t=="string"&&Object.hasOwn(L,t),B=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 x;constructor(e){let n=new URL(e.issuer);if(n.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=n.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,n){if(typeof e!="string"||e.length===0||e.length>nt)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let o=Ee(r[0]),s=Ee(r[1]);if(!o||!s)throw new d("malformed","the token header or claims are not base64url JSON");let i=o.alg;if(!xe(i))throw new d("algorithm",`the token is signed with ${String(i)}; only ES256 and PS256 are taken`);let p=o.kid;if(typeof p!="string"||p==="")throw new d("malformed","the token header names no kid");let c=await this.key(p);if(!c)throw new d("unknown_key",`no key ${p} in the project's key set`);if(c.alg!==i)throw new d("algorithm",`key ${p} is ${c.alg}, the token says ${i}`);let a=Pe(r[2]);if(!a)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(L[c.alg].verify,c.key,a,l).catch(()=>!1))throw new d("signature","the signature does not verify");let g=this.check(s),m=s.cnf,f;if(m!==void 0){if(!n)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof m!="object"||m===null||typeof m.jkt!="string"||m.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");f=await be(e,m.jkt,n,this.now())}else if(n)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,g.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return f&&this.seenProofs.spend(f,this.now()),g}async verifyRequest(e){let n=e.headers instanceof Headers?e.headers:it(e.headers),r=n.get("authorization")??"";if(r==="")return null;let o=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!o)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let s=o[1].toLowerCase()==="dpop",i=new URL(e.url,`http://${n.get("host")??"localhost"}`);return this.verify(o[2],s?{proof:n.get("dpop"),method:e.method,url:_e(n,i)}:void 0)}async stands(e,n){let r=this.now(),o=this.standings.get(n);if(o&&r<o.until)return o.live;let s=this.asking.get(n);s||(s=this.standing(e,n).finally(()=>this.asking.delete(n)),this.asking.set(n,s));let i;try{i=await s}catch(c){let a=this.standings.get(n),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 k("a session's standing cannot be read now",{cause:c})}let p=this.now();return this.standings.delete(n),this.standings.set(n,{live:i,at:p,until:p+this.standingTtlMs}),this.standings.size>ot&&this.standings.delete(this.standings.keys().next().value),i}check(e){if(e.iss!==this.issuer)throw new d("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 d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+Re<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-Re>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let o=e.custom_claims;if(o!==void 0&&(typeof o!="object"||o===null||o.type!==void 0))throw new d("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 n=this.now();if(n>=this.keysUntil){let o=this.keys.size>0&&n<this.keysUntil+rt;if(this.lastFailure!==void 0&&n-this.lastFetch<this.refetchIntervalMs){if(!o)throw new k("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(s){if(!o)throw s}}let r=this.keys.get(e);return!r&&n-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,n;try{if(n=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!n.ok)throw new Error(`the project's key set answered ${n.status}`);e=await n.json()}catch(s){throw this.lastFailure=s,new k("the project's key set cannot be read now",{cause:s})}this.lastFailure=void 0;let r=new Map;for(let s of Array.isArray(e.keys)?e.keys:[]){let i=s.alg;if(typeof s.kid!="string"||!xe(i))continue;let p=L[i];if(s.kty!==p.kty||s.use!==void 0&&s.use!=="sig")continue;let{d:c,...a}=s;try{r.set(s.kid,{alg:i,key:await crypto.subtle.importKey("jwk",a,p.import,!1,["verify"])})}catch{}}this.keys=r;let o=at(n.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(o,this.refetchIntervalMs),this.maxKeyAgeMs)}};function _e(t,e){let n=t.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=n==="https"||n==="http"?n:e.protocol.slice(0,-1),o=t.get("host")??e.host;return st.test(o)?`${r}://${o}${e.pathname}`:""}var st=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function it(t){let e=new Headers;for(let[n,r]of Object.entries(t))if(r!==void 0)for(let o of Array.isArray(r)?r:[r])e.append(n,o);return e}function at(t){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(t??"");return e?Number(e[1])*1e3:void 0}function Pe(t){if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)return null;let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(t.length/4)*4,"=")),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Ee(t){let e=Pe(t);if(!e)return null;try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}catch{return null}}function ct(t,e,n=Date.now()){let r=Object.hasOwn(t.entitlements,e)?t.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof n=="number"?n:n.getTime()):!1}var E=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 pt(t,e,n,r){let{idempotencyKey:o,amount:s,ttlSeconds:i,metadata:p}=n;if(typeof o!="string"||o==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:s,...n.credits!==void 0?{credits:n.credits}:{limit:n.limit},...i!==void 0?{ttl_seconds:i}:{},...p!==void 0?{metadata:p}:{}},a=(await t.iap.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":o},body:c})).data;if(a.status!=="held")throw new E(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(g){throw await t.iap.releaseSpend({path:l}).catch(()=>{}),g}return await t.iap.commitSpend({path:l}),y}var lt=new Set(["provider_unavailable","authentication_required","three_ds_failed"]);function dt(t){return t!==void 0&&lt.has(t)}function ut(t,e){return{[Te]:!0,commitAmount:t,value:e}}var Te=Symbol("palbase.payments.settleWalletHold");function yt(t){return typeof t=="object"&&t!==null&&Te in t}var _=class extends Error{hold;constructor(e){super(`wallet hold ${JSON.stringify(e.id)} is already ${e.status}: the work is not run again (use a new Idempotency-Key for a new hold)`),this.name="WalletHoldSettled",this.hold=e}};async function mt(t,e,n){let{idempotencyKey:r,walletKey:o,amount:s,ttlSeconds:i,reference:p,metadata:c}=e;if(typeof r!="string"||r.trim()==="")throw new TypeError("idempotencyKey is required for withWalletHold so retries never reserve funds twice");if(!Number.isInteger(s)||s<=0)throw new TypeError("amount must be a positive integer in minor units");let a={wallet_key:o,amount:s,...e.customerId!==void 0?{customer_id:e.customerId}:{spend_token:e.spendToken},...i!==void 0?{ttl_seconds:i}:{},...p!==void 0?{reference:p}:{},...c!==void 0?{metadata:c}:{}},l=(await t.payments.createWalletHold({headers:{"Idempotency-Key":r},body:a})).data;if(l.status!=="held")throw new _(l);let y;try{y=await n(l)}catch(g){throw await t.payments.releaseWalletHold({path:{hold_id:l.id}}).catch(()=>{}),g}return yt(y)?(y.commitAmount<=0?await t.payments.releaseWalletHold({path:{hold_id:l.id}}):await t.payments.commitWalletHold({path:{hold_id:l.id},body:{amount:y.commitAmount}}),y.value):(await t.payments.commitWalletHold({path:{hold_id:l.id}}),y)}function ht(t){return t.type.startsWith("payments.")}function ft(t){return t.type.startsWith("commerce.")}function gt(t){return t.type.startsWith("promotions.")}var wt=300,kt=/^[0-9]{1,12}$/;function St(t){return typeof t=="string"?new TextEncoder().encode(t):t instanceof ArrayBuffer?new Uint8Array(t):t}function vt(t){if(t.startsWith("whsec_")){let e=t.slice(6);try{let n=atob(e),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}catch{}}return new TextEncoder().encode(t)}function bt(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function Rt(t){try{let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}catch{return null}}async function Me(t){if(typeof t.secret!="string"||t.secret==="")throw new TypeError("secret is the commerce hook signing secret (whsec_\u2026)");let e=t.webhookId?.trim()??"",n=t.webhookTimestamp?.trim()??"",r=t.webhookSignature?.trim()??"";if(!e||!n||!r)throw new u("missing_signature","webhook-id, webhook-timestamp, and webhook-signature headers are required");if(!kt.test(n))throw new u("malformed_signature","webhook-timestamp must be unix seconds");let o=t.toleranceSeconds??wt,s=Math.floor((t.now?.()??Date.now())/1e3);if(Math.abs(s-Number(n))>o)throw new u("stale_timestamp",`webhook-timestamp ${n} is outside tolerance (${o}s)`);let i=St(t.body),p=new TextEncoder().encode(`${e}.${n}.`),c=new Uint8Array(p.length+i.length);c.set(p,0),c.set(i,p.length);let a=vt(t.secret),l=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),y=await crypto.subtle.importKey("raw",l,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),g=new Uint8Array(await crypto.subtle.sign("HMAC",y,c)),m=!1;for(let f of r.split(/\s+/)){if(!f.startsWith("v1,"))continue;let v=Rt(f.slice(3));if(v&&bt(g,v)){m=!0;break}}if(!m)throw new u("signature_mismatch","no v1 signature in webhook-signature matches the payload")}function Ae(t){return async e=>{let n=new Uint8Array(await e.arrayBuffer()),r=e.headers.get("webhook-id")??"";try{await Me({secret:t.secret,webhookId:r,webhookTimestamp:e.headers.get("webhook-timestamp"),webhookSignature:e.headers.get("webhook-signature"),body:n,toleranceSeconds:t.toleranceSeconds,now:t.now})}catch(i){let p=i instanceof u?i.code:"signature_mismatch",c=i instanceof Error?i.message:"invalid hook signature";return new Response(JSON.stringify({error:p,error_description:c}),{status:401,headers:{"content-type":"application/json"}})}let o;try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return new Response(JSON.stringify({error:"invalid_body",error_description:"hook body is not valid JSON"}),{status:400,headers:{"content-type":"application/json"}})}let s=await t.handle({hookPoint:e.headers.get("x-palbase-hook-point")??"",webhookId:r,payload:o,request:e});return new Response(JSON.stringify(s),{status:200,headers:{"content-type":"application/json"}})}}var P=class extends Error{hookPoint;constructor(e){super(`expected x-palbase-hook-point "discovery.rank", got "${e}"`),this.hookPoint=e}};function xt(t){let e=Ae({secret:t.secret,toleranceSeconds:t.toleranceSeconds,now:t.now,handle:n=>{if(n.hookPoint!==""&&n.hookPoint!=="discovery.rank")throw new P(n.hookPoint);return t.handle(n)}});return async n=>{try{return await e(n)}catch(r){if(r instanceof P)return new Response(JSON.stringify({error:"invalid_hook_point",error_description:r.message}),{status:400,headers:{"content-type":"application/json"}});throw r}}}function Et(t){return t.type.startsWith("campaigns.")}function _t(t){return t.type.startsWith("journey.")}async function*Pt(t){let e,n=new Set;do{let r=(await t(e)).data;yield r;let o=r.next_cursor??void 0;if(o!==void 0&&n.has(o))throw new Error(`the listing answered a cursor it had answered before (${o})`);o!==void 0&&n.add(o),e=o}while(e)}var Tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Mt=/^(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 Ce(t){return!Tt.test(t)||Mt.test(t)||/_PROXY$/i.test(t)}var At=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|CONTRACT_ENTRY|WEB_ORIGINS|SECRETS|DB_[A-Z0-9_]+))$/;function Ct(t){return At.test(t)}async function Ot(t={}){let e=t.env??process.env,n=e.PALBASE_SECRETS;if(n===void 0||n==="")return;if(n==="production")throw new TypeError("PALBASE_SECRETS=production: a production secret's value is never read back \u2014 only the machines that start with it are given it. Run here with PALBASE_SECRETS=development (palbase env:pull writes it), and set a value for this computer with palbase secrets:set NAME --dev");if(n!=="development")throw new TypeError(`PALBASE_SECRETS is development, not ${n}`);let r=t.url??e.PALBASE_URL??"",o=t.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||o==="")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 s=H({url:new URL(r).origin,secretKey:o,fetch:t.fetch}),{data:i}=await s.secrets.getEnvironmentValues({path:{environment:n}}),p=[],c=[],a=[];for(let[l,y]of Object.entries(i.values)){if(Ce(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,p.push(l)}return{set:n,loaded:p.sort(),kept:c.sort(),refused:a.sort()}}export{h as a,S as b,R as c,H as d,u as e,me as f,he as g,fe as h,$e as i,d as j,k,tt as l,B as m,_e as n,ct as o,E as p,pt as q,dt as r,ut as s,_ as t,mt as u,ht as v,ft as w,gt as x,Me as y,Ae as z,xt as A,Et as B,_t as C,Pt as D,Ce as E,Ct as F,Ot as G};
1
+ /*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as C}from"./HHKRAOVG.js";import{a as ue}from"./AKJC5WTU.js";import{a as D,b as j,c as U,d as I,e as K,f as q,g as F,h as $,i as N,j as V,k as J,l as z,m as Y,n as G,o as X,p as Z,q as Q,r as ee,s as te}from"./RP2TPMXT.js";import{a as w,c as oe,d as se,e as ie,f as ae,h as ce,i as pe,j as M,k as le,l as de,o as A}from"./VP3HFVV4.js";import{a as ne,b as re}from"./JSRN4NOZ.js";import{b as T,d as b}from"./XVJ3CMFN.js";var h=class extends Error{status=400;code;data;constructor(e,n,r={}){super(n),this.name="TransitRefusal",this.code=e,this.data=r}},Le=6e4,Be=1e3;function O(t){return/^t[1-9][0-9]{0,5}$/.test(t)?Number(t.slice(1)):0}var S=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??(n=>new Promise(r=>setTimeout(r,n)))}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(()=>{})},Le),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let n=this.now();try{let r=await this.opts.fetch(e),o=new Map;for(let s of r.keys){let i=se(s.key);o.set(s.id,{privateKey:i,publicKey:this.keys.get(s.id)?.publicKey??await ie(i)})}this.keys=o,this.order=r.keys.map(s=>s.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=n}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(O),...[...this.retired].map(O))}async key(e){let n=this.now();for(;O(e)>this.newest()&&this.heldFrom<n;){let s=this.fetchedAt+Be-this.now();if(s>0){await this.sleep(s);continue}await this.refresh()}let r=this.keys.get(e),o=this.current();if(this.retired.has(e))throw new h("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:o});if(r===void 0)throw new h("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:o});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new h("encryption_required",`this route carries encrypted fields: the request names its key in ${w}`,{field:w,current:this.current()});let n;try{n=ce(e.header).kid}catch{throw new h("encryption_unopenable",`${w} is not one`,{field:w})}let r=await this.key(n),o;try{o=ae(this.projectId,e.method,e.path,e.params??[])}catch{throw new h("encryption_unopenable","the request's path holds a value no key is sealed for",{field:w})}try{return new R(n,await pe(e.header,r.privateKey,r.publicKey,o))}catch(s){throw s instanceof oe?new h("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:w}):s}}},R=class{kid;key;constructor(e,n){this.kid=e,this.key=n}async open(e,n,r){return A(e,n,r,async(o,s)=>{if(!le(s))throw new h("encryption_required",`${o} is an encrypted field: it came plain`,{field:o});try{return await de(this.key,o,s)}catch{throw new h("encryption_unopenable",`${o} does not open: changed, moved from another field, or another request's`,{field:o})}})}async seal(e,n){return A(e,"/response",n,(r,o)=>M(this.key,r,o))}sealField(e,n){return M(this.key,e,n)}};var De=/^pb_[a-z0-9]+_s/;function H(t){if(ue())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 t.secretKey!="string"||!De.test(t.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=re(b({baseUrl:t.url,credentials:{secretKey:t.secretKey},fetch:t.fetch,solveProofOfWork:t.solveProofOfWork??!1}),t.retry??ne),n=Z.client(e);return{ai:D.client(e),analytics:j.client(e),auth:U.client(e),cache:I.client(e),calls:K.client(e),fields:new C({fetch:async r=>(await n.getFieldKeys({signal:r})).data}),flags:$.client(e),iap:N.client(e),machines:J.client(e),messaging:z.client(e),notify:Y.client(e),payments:G.client(e),campaigns:q.client(e),commerce:F.client(e),journeys:V.client(e),realtime:X.client(e),secrets:n,storage:Q.client(e),stores:ee.client(e),workspaces:te.client(e),transit:new S({fetch:async r=>(await n.getTransitKeys({signal:r})).data}),transport:e,url:new URL(t.url).origin}}var u=class extends Error{code;constructor(e,n){super(n),this.name="WebhookSignatureError",this.code=e}},Ue=300,Ie=/^[0-9]{1,12}$/,Ke=/^[0-9a-f]{64}$/,ye=8,qe=/^whsec_[0-9A-Za-z]{32,}$/,Fe=1024*1024;async function me(t){if(typeof t.secret!="string"||!qe.test(t.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await he(t);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(ge(t.body)))}catch{throw new u("invalid_body","the signed body is not JSON")}if(!Ye(e))throw new u("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function he(t){if(typeof t.secret!="string"||t.secret==="")throw new TypeError("secret is the key the request was signed with");let e=ge(t.body),{t:n,v1:r}=fe(t),o=await crypto.subtle.importKey("raw",new TextEncoder().encode(t.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=new Uint8Array(await crypto.subtle.sign("HMAC",o,ze(new TextEncoder().encode(`${n}.`),e))),i=!1;for(let p of r)Je(s,Ve(p))&&(i=!0);if(!i)throw new u("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function fe(t){let e=t.toleranceSeconds??Ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(t.toleranceSeconds)})`);let n=(t.now??Date.now)();if(!Number.isFinite(n))throw new TypeError(`now() returns epoch milliseconds (got ${String(n)})`);let r=t.signature;if(typeof r!="string"||r.trim()==="")throw new u("missing_signature","the request carries no Palbase-Signature header");let o,s=[];for(let i of r.split(",")){let p=i.indexOf("=");if(p<=0)throw new u("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=i.slice(0,p).trim(),a=i.slice(p+1).trim();if(c==="t"){if(o!==void 0||!Ie.test(a))throw new u("malformed_signature","Palbase-Signature carries one t, in unix seconds");o=a}else if(c==="v1"){if(!Ke.test(a))throw new u("malformed_signature","a v1 is 64 lowercase hex characters");if(s.length===ye)throw new u("malformed_signature",`Palbase-Signature carries at most ${ye} v1`);s.push(a)}}if(o===void 0||s.length===0)throw new u("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(n/1e3-Number(o))>e)throw new u("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:o,v1:s}}async function $e(t,e,n={}){let r=await Ne(t,n.maxBytes??Fe);return me({toleranceSeconds:n.toleranceSeconds,now:n.now,secret:e,signature:t.headers.get("palbase-signature"),body:r})}async function Ne(t,e){let n=()=>new u("body_too_large",`the body is larger than ${e} bytes`),r=Number(t.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw n();if(!t.body)return new Uint8Array(0);let o=t.body.getReader(),s=[],i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;if(i+=l.byteLength,i>e)throw await o.cancel().catch(()=>{}),n();s.push(l)}let p=new Uint8Array(i),c=0;for(let a of s)p.set(a,c),c+=a.byteLength;return p}function ge(t){if(typeof t=="string")return new TextEncoder().encode(t);if(t instanceof Uint8Array)return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);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 Ve(t){let e=new Uint8Array(t.length/2);for(let n=0;n<e.length;n++)e[n]=parseInt(t.slice(n*2,n*2+2),16);return e}function Je(t,e){if(t.byteLength!==e.byteLength)return!1;let n=0;for(let r=0;r<t.byteLength;r++)n|=t[r]^e[r];return n===0}function ze(t,e){let n=new Uint8Array(t.byteLength+e.byteLength);return n.set(t,0),n.set(e,t.byteLength),n}function Ye(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var we=60,Ge=60,Xe=8*1024,Ze=1e5;function W(t){let e=t instanceof Uint8Array?t:new Uint8Array(t),n="";for(let r of e)n+=String.fromCharCode(r);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ve(t){let e=t.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let n=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function ke(t){let e=ve(t);if(e)try{let n=JSON.parse(new TextDecoder().decode(e));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:void 0}catch{return}}var x=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=Ze){this.max=e}spend(e,n){if(n>=e.until)throw new d("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,n);let o=r.get(e.jti);if(o!==void 0&&o>n)throw new d("proof","the DPoP proof is not taken: it was used before");o!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(n),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,n,r){for(let[o,s]of n){if(s>r)break;n.delete(o),this.held--}n.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,o]of this.byKey){for(let[s,i]of o)i>e||(o.delete(s),this.held--);o.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 n=[...this.byKey].sort((r,o)=>o[1].size-r[1].size);for(let[r,o]of n){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=o.size}}};async function Qe(t,e){let n=`{"crv":"P-256","kty":"EC","x":"${t}","y":"${e}"}`;return W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)))}function Se(t){try{let e=new URL(t);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function be(t,e,n,r){let o=We=>{throw new d("proof",`the DPoP proof is not taken: ${We}`)},s=n.proof;if(!s)return o("there is none (a DPoP-bound token comes with a DPoP header)");if(s.length>Xe)return o("it is too long");let i=s.split(".");if(i.length!==3)return o("it is not a JWS of three parts");let p=ke(i[0]),c=ke(i[1]);if(!p||!c)return o("its header or claims are not base64url JSON");if(p.typ!=="dpop+jwt")return o("its typ is not dpop+jwt");if(p.alg!=="ES256")return o(`it is signed with ${String(p.alg)}; only ES256 is taken`);let a=p.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return o("its header carries no P-256 public key");if("d"in a)return o("its header carries a private key");if(await Qe(a.x,a.y)!==e)return o("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 o("its key is not a P-256 point")}let y=ve(i[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,y,new TextEncoder().encode(`${i[0]}.${i[1]}`)).catch(()=>!1))return o("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==n.method.toUpperCase())return o(`it is for ${String(c.htm)}, not ${n.method}`);let m=typeof c.htu=="string"?Se(c.htu):void 0,f=Se(n.url);if(!m||!f||m!==f)return o(`it is for ${String(c.htu)}, not ${f??n.url}`);let v=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-v)>we)return o("it was not made within a minute of now");let Oe=W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)));if(c.ath!==Oe)return o("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return o("it has no jti (or one longer than 256)");let He=W(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:He,until:(c.iat+we+Ge)*1e3+1}}var d=class extends Error{reason;constructor(e,n){super(n),this.name="TokenError",this.reason=e}},k=class extends Error{constructor(e,n){super(e,n),this.name="AuthUnavailable"}},et=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function tt(t){return async e=>{let n=b({baseUrl:t.url,credentials:{secretKey:t.secretKey,accessToken:()=>e},fetch:t.fetch});try{return await n.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&&!et.has(r.code))return!1;throw new k("a session's standing could not be told",{cause:r})}}}var L={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}}},Re=60,nt=16*1024,rt=10*6e4,ot=5e4,xe=t=>typeof t=="string"&&Object.hasOwn(L,t),B=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 x;constructor(e){let n=new URL(e.issuer);if(n.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=n.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,n){if(typeof e!="string"||e.length===0||e.length>nt)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let o=Ee(r[0]),s=Ee(r[1]);if(!o||!s)throw new d("malformed","the token header or claims are not base64url JSON");let i=o.alg;if(!xe(i))throw new d("algorithm",`the token is signed with ${String(i)}; only ES256 and PS256 are taken`);let p=o.kid;if(typeof p!="string"||p==="")throw new d("malformed","the token header names no kid");let c=await this.key(p);if(!c)throw new d("unknown_key",`no key ${p} in the project's key set`);if(c.alg!==i)throw new d("algorithm",`key ${p} is ${c.alg}, the token says ${i}`);let a=Pe(r[2]);if(!a)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(L[c.alg].verify,c.key,a,l).catch(()=>!1))throw new d("signature","the signature does not verify");let g=this.check(s),m=s.cnf,f;if(m!==void 0){if(!n)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof m!="object"||m===null||typeof m.jkt!="string"||m.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");f=await be(e,m.jkt,n,this.now())}else if(n)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,g.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return f&&this.seenProofs.spend(f,this.now()),g}async verifyRequest(e){let n=e.headers instanceof Headers?e.headers:it(e.headers),r=n.get("authorization")??"";if(r==="")return null;let o=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!o)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let s=o[1].toLowerCase()==="dpop",i=new URL(e.url,`http://${n.get("host")??"localhost"}`);return this.verify(o[2],s?{proof:n.get("dpop"),method:e.method,url:_e(n,i)}:void 0)}async stands(e,n){let r=this.now(),o=this.standings.get(n);if(o&&r<o.until)return o.live;let s=this.asking.get(n);s||(s=this.standing(e,n).finally(()=>this.asking.delete(n)),this.asking.set(n,s));let i;try{i=await s}catch(c){let a=this.standings.get(n),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 k("a session's standing cannot be read now",{cause:c})}let p=this.now();return this.standings.delete(n),this.standings.set(n,{live:i,at:p,until:p+this.standingTtlMs}),this.standings.size>ot&&this.standings.delete(this.standings.keys().next().value),i}check(e){if(e.iss!==this.issuer)throw new d("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 d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+Re<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-Re>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let o=e.custom_claims;if(o!==void 0&&(typeof o!="object"||o===null||o.type!==void 0))throw new d("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 n=this.now();if(n>=this.keysUntil){let o=this.keys.size>0&&n<this.keysUntil+rt;if(this.lastFailure!==void 0&&n-this.lastFetch<this.refetchIntervalMs){if(!o)throw new k("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(s){if(!o)throw s}}let r=this.keys.get(e);return!r&&n-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,n;try{if(n=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!n.ok)throw new Error(`the project's key set answered ${n.status}`);e=await n.json()}catch(s){throw this.lastFailure=s,new k("the project's key set cannot be read now",{cause:s})}this.lastFailure=void 0;let r=new Map;for(let s of Array.isArray(e.keys)?e.keys:[]){let i=s.alg;if(typeof s.kid!="string"||!xe(i))continue;let p=L[i];if(s.kty!==p.kty||s.use!==void 0&&s.use!=="sig")continue;let{d:c,...a}=s;try{r.set(s.kid,{alg:i,key:await crypto.subtle.importKey("jwk",a,p.import,!1,["verify"])})}catch{}}this.keys=r;let o=at(n.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(o,this.refetchIntervalMs),this.maxKeyAgeMs)}};function _e(t,e){let n=t.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=n==="https"||n==="http"?n:e.protocol.slice(0,-1),o=t.get("host")??e.host;return st.test(o)?`${r}://${o}${e.pathname}`:""}var st=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function it(t){let e=new Headers;for(let[n,r]of Object.entries(t))if(r!==void 0)for(let o of Array.isArray(r)?r:[r])e.append(n,o);return e}function at(t){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(t??"");return e?Number(e[1])*1e3:void 0}function Pe(t){if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)return null;let e=atob(t.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(t.length/4)*4,"=")),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}function Ee(t){let e=Pe(t);if(!e)return null;try{let n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}catch{return null}}function ct(t,e,n=Date.now()){let r=Object.hasOwn(t.entitlements,e)?t.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof n=="number"?n:n.getTime()):!1}var E=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 pt(t,e,n,r){let{idempotencyKey:o,amount:s,ttlSeconds:i,metadata:p}=n;if(typeof o!="string"||o==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:s,...n.credits!==void 0?{credits:n.credits}:{limit:n.limit},...i!==void 0?{ttl_seconds:i}:{},...p!==void 0?{metadata:p}:{}},a=(await t.iap.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":o},body:c})).data;if(a.status!=="held")throw new E(a);let l={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(g){throw await t.iap.releaseSpend({path:l}).catch(()=>{}),g}return await t.iap.commitSpend({path:l}),y}var lt=new Set(["provider_unavailable","authentication_required","three_ds_failed"]);function dt(t){return t!==void 0&&lt.has(t)}function ut(t,e){return{[Te]:!0,commitAmount:t,value:e}}var Te=Symbol("palbase.payments.settleWalletHold");function yt(t){return typeof t=="object"&&t!==null&&Te in t}var _=class extends Error{hold;constructor(e){super(`wallet hold ${JSON.stringify(e.id)} is already ${e.status}: the work is not run again (use a new Idempotency-Key for a new hold)`),this.name="WalletHoldSettled",this.hold=e}};async function mt(t,e,n){let{idempotencyKey:r,walletKey:o,amount:s,ttlSeconds:i,reference:p,metadata:c}=e;if(typeof r!="string"||r.trim()==="")throw new TypeError("idempotencyKey is required for withWalletHold so retries never reserve funds twice");if(!Number.isInteger(s)||s<=0)throw new TypeError("amount must be a positive integer in minor units");let a={wallet_key:o,amount:s,...e.customerId!==void 0?{customer_id:e.customerId}:{spend_token:e.spendToken},...i!==void 0?{ttl_seconds:i}:{},...p!==void 0?{reference:p}:{},...c!==void 0?{metadata:c}:{}},l=(await t.payments.createWalletHold({headers:{"Idempotency-Key":r},body:a})).data;if(l.status!=="held")throw new _(l);let y;try{y=await n(l)}catch(g){throw await t.payments.releaseWalletHold({path:{hold_id:l.id}}).catch(()=>{}),g}return yt(y)?(y.commitAmount<=0?await t.payments.releaseWalletHold({path:{hold_id:l.id}}):await t.payments.commitWalletHold({path:{hold_id:l.id},body:{amount:y.commitAmount}}),y.value):(await t.payments.commitWalletHold({path:{hold_id:l.id}}),y)}function ht(t){return t.type.startsWith("payments.")}function ft(t){return t.type.startsWith("commerce.")}function gt(t){return t.type.startsWith("promotions.")}var wt=300,kt=/^[0-9]{1,12}$/;function St(t){return typeof t=="string"?new TextEncoder().encode(t):t instanceof ArrayBuffer?new Uint8Array(t):t}function vt(t){if(t.startsWith("whsec_")){let e=t.slice(6);try{let n=atob(e),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}catch{}}return new TextEncoder().encode(t)}function bt(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}function Rt(t){try{let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}catch{return null}}async function Me(t){if(typeof t.secret!="string"||t.secret==="")throw new TypeError("secret is the commerce hook signing secret (whsec_\u2026)");let e=t.webhookId?.trim()??"",n=t.webhookTimestamp?.trim()??"",r=t.webhookSignature?.trim()??"";if(!e||!n||!r)throw new u("missing_signature","webhook-id, webhook-timestamp, and webhook-signature headers are required");if(!kt.test(n))throw new u("malformed_signature","webhook-timestamp must be unix seconds");let o=t.toleranceSeconds??wt,s=Math.floor((t.now?.()??Date.now())/1e3);if(Math.abs(s-Number(n))>o)throw new u("stale_timestamp",`webhook-timestamp ${n} is outside tolerance (${o}s)`);let i=St(t.body),p=new TextEncoder().encode(`${e}.${n}.`),c=new Uint8Array(p.length+i.length);c.set(p,0),c.set(i,p.length);let a=vt(t.secret),l=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),y=await crypto.subtle.importKey("raw",l,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),g=new Uint8Array(await crypto.subtle.sign("HMAC",y,c)),m=!1;for(let f of r.split(/\s+/)){if(!f.startsWith("v1,"))continue;let v=Rt(f.slice(3));if(v&&bt(g,v)){m=!0;break}}if(!m)throw new u("signature_mismatch","no v1 signature in webhook-signature matches the payload")}function Ae(t){return async e=>{let n=new Uint8Array(await e.arrayBuffer()),r=e.headers.get("webhook-id")??"";try{await Me({secret:t.secret,webhookId:r,webhookTimestamp:e.headers.get("webhook-timestamp"),webhookSignature:e.headers.get("webhook-signature"),body:n,toleranceSeconds:t.toleranceSeconds,now:t.now})}catch(i){let p=i instanceof u?i.code:"signature_mismatch",c=i instanceof Error?i.message:"invalid hook signature";return new Response(JSON.stringify({error:p,error_description:c}),{status:401,headers:{"content-type":"application/json"}})}let o;try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return new Response(JSON.stringify({error:"invalid_body",error_description:"hook body is not valid JSON"}),{status:400,headers:{"content-type":"application/json"}})}let s=await t.handle({hookPoint:e.headers.get("x-palbase-hook-point")??"",webhookId:r,payload:o,request:e});return new Response(JSON.stringify(s),{status:200,headers:{"content-type":"application/json"}})}}var P=class extends Error{hookPoint;constructor(e){super(`expected x-palbase-hook-point "discovery.rank", got "${e}"`),this.hookPoint=e}};function xt(t){let e=Ae({secret:t.secret,toleranceSeconds:t.toleranceSeconds,now:t.now,handle:n=>{if(n.hookPoint!==""&&n.hookPoint!=="discovery.rank")throw new P(n.hookPoint);return t.handle(n)}});return async n=>{try{return await e(n)}catch(r){if(r instanceof P)return new Response(JSON.stringify({error:"invalid_hook_point",error_description:r.message}),{status:400,headers:{"content-type":"application/json"}});throw r}}}function Et(t){return t.type.startsWith("campaigns.")}function _t(t){return t.type.startsWith("journey.")}async function*Pt(t){let e,n=new Set;do{let r=(await t(e)).data;yield r;let o=r.next_cursor??void 0;if(o!==void 0&&n.has(o))throw new Error(`the listing answered a cursor it had answered before (${o})`);o!==void 0&&n.add(o),e=o}while(e)}var Tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Mt=/^(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 Ce(t){return!Tt.test(t)||Mt.test(t)||/_PROXY$/i.test(t)}var At=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|CONTRACT_ENTRY|WEB_ORIGINS|SECRETS|DB_[A-Z0-9_]+))$/;function Ct(t){return At.test(t)}async function Ot(t={}){let e=t.env??process.env,n=e.PALBASE_SECRETS;if(n===void 0||n==="")return;if(n==="production")throw new TypeError("PALBASE_SECRETS=production: a production secret's value is never read back \u2014 only the machines that start with it are given it. Run here with PALBASE_SECRETS=development (palbase env:pull writes it), and set a value for this computer with palbase secrets:set NAME --dev");if(n!=="development")throw new TypeError(`PALBASE_SECRETS is development, not ${n}`);let r=t.url??e.PALBASE_URL??"",o=t.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||o==="")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 s=H({url:new URL(r).origin,secretKey:o,fetch:t.fetch}),{data:i}=await s.secrets.getEnvironmentValues({path:{environment:n}}),p=[],c=[],a=[];for(let[l,y]of Object.entries(i.values)){if(Ce(l)){a.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=y,p.push(l)}return{set:n,loaded:p.sort(),kept:c.sort(),refused:a.sort()}}export{h as a,S as b,R as c,H as d,u as e,me as f,he as g,fe as h,$e as i,d as j,k,tt as l,B as m,_e as n,ct as o,E as p,pt as q,dt as r,ut as s,_ as t,mt as u,ht as v,ft as w,gt as x,Me as y,Ae as z,xt as A,Et as B,_t as C,Pt as D,Ce as E,Ct as F,Ot as G};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{n as w}from"./3VGWTVKI.js";import{b as c}from"./UOW74IHY.js";var P=new Set(["succeeded","requires_capture","failed","canceled","expired"]);function S(o){return P.has(o)}var W=new Set(["payments.payment.succeeded","payments.payment.failed","payments.payment.canceled","payments.payment.requires_capture"]),E=new Set(["payments.wallet.balance_changed","payments.wallet.hold_changed"]);function T(o){if(typeof o!="object"||o===null)return null;let e=o;return e.source!=="palbase.payments"||typeof e.intent_id!="string"||e.intent_id.length===0||typeof e.status!="string"||e.status.length===0?null:{source:"palbase.payments",intent_id:e.intent_id,status:e.status,...typeof e.decline_code=="string"&&e.decline_code.length>0?{decline_code:e.decline_code}:{},...typeof e.return_url=="string"&&e.return_url.length>0?{return_url:e.return_url}:{}}}var A={insufficient_funds:"Insufficient funds on this card. Please try another payment method.",card_declined:"Your card was declined by the issuing bank.",do_not_honor:"Your bank declined this transaction. Please contact your bank or use another card.",expired_card:"This card has expired. Please use a valid card.",incorrect_cvc:"The security code (CVC/CVV) is incorrect.",incorrect_number:"The card number is invalid.",invalid_expiry:"The card expiration date is invalid.",authentication_required:"Additional 3D Secure verification is required by your bank.",three_ds_failed:"3D Secure verification failed or was canceled.",otp_invalid:"The verification code is incorrect. Please try again.",otp_expired:"The verification code has expired. Please request a new one.",fraud_suspected:"This transaction was declined for security reasons.",velocity_exceeded:"Too many failed payment attempts. Please wait a moment and try again.",limit_exceeded:"This transaction exceeds your card limit.",card_not_permitted:"This card is not enabled for online or international transactions.",processing_error:"A temporary payment processing error occurred. Please try again.",provider_unavailable:"The payment provider is temporarily unavailable. Please try again.",wallet_frozen:"This wallet is currently frozen and cannot be charged.",wallet_insufficient_balance:"Insufficient wallet balance for this payment."};function B(o){return o?A[o]??"Payment was declined. Please try another payment method.":"Payment could not be completed. Please try again."}var _=class{api;profile;methods;wallet;subscriptions;session;socket;ref;origin;walletListeners=new Set;walletWatch;walletFollowing;lastBalances;eventListeners=new Set;eventWatch;eventFollowing;constructor(e,t,i,s,d){this.api=w.client(e),this.session=t,this.socket=i,this.ref=s,this.origin=d,this.profile={get:async n=>(await this.api.getMyProfile({signal:n?.signal})).data,update:async(n,a)=>(await this.api.updateMyProfile({body:n,signal:a?.signal})).data},this.methods={list:async n=>(await this.api.listMyMethods({signal:n?.signal})).data.methods,add:async(n={})=>{let a={...n.channel!==void 0?{channel:n.channel}:{},...n.vault!==void 0?{vault:n.vault}:{},...n.phone!==void 0?{phone:n.phone}:{},...n.returnUrl!==void 0?{return_url:n.returnUrl}:{},...n.cancelUrl!==void 0?{cancel_url:n.cancelUrl}:{}};return(await this.api.addMyMethod({body:a,signal:n.signal})).data.next_action},remove:async(n,a)=>{await this.api.deleteMyMethod({path:{method_id:n},signal:a?.signal})}},this.wallet={balances:async n=>{let a=this.session.snapshot()?.userId,l=(await this.api.listMyWallets({signal:n?.signal})).data.balances;return this.walletWatch&&this.walletWatch.userId===a&&this.offerBalances(this.walletWatch,l),l},balance:async(n,a)=>(await this.wallet.balances(a)).find(u=>u.wallet_key===n),topUp:async n=>{let a={wallet_key:n.walletKey,amount:n.amount,...n.channel!==void 0?{channel:n.channel}:{},...n.methodId!==void 0?{method_id:n.methodId}:{},...n.saveMethod!==void 0?{save_method:n.saveMethod}:{},...n.useMasterpass!==void 0?{use_masterpass:n.useMasterpass}:{},...n.phone!==void 0?{phone:n.phone}:{},...n.returnUrl!==void 0?{return_url:n.returnUrl}:{},...n.cancelUrl!==void 0?{cancel_url:n.cancelUrl}:{}},l=n.idempotencyKey?{"Idempotency-Key":n.idempotencyKey}:void 0;return(await this.api.topUpMyWallet({body:a,headers:l,signal:n.signal})).data},createSpendToken:async n=>{let a={wallet_key:n.walletKey,...n.maxAmount!==void 0?{max_amount:n.maxAmount}:{},...n.ttlSeconds!==void 0?{ttl_seconds:n.ttlSeconds}:{}};return(await this.api.createMySpendToken({body:a,signal:n.signal})).data},onChange:n=>this.onWalletChange(n)},this.subscriptions={list:async n=>(await this.api.listMySubscriptions({query:{limit:n?.limit,cursor:n?.cursor},signal:n?.signal})).data,cancel:async(n,a)=>(await this.api.cancelMySubscription({path:{subscription_id:n},signal:a?.signal})).data}}async capabilities(e={}){return(await this.api.getCapabilities({query:{...e.currency!==void 0?{currency:e.currency}:{},...e.channel!==void 0?{channel:e.channel}:{}},signal:e.signal})).data}async installments(e){let t={amount:e.amount,currency:e.currency,...e.bin!==void 0?{bin:e.bin}:{},...e.methodId!==void 0?{method_id:e.methodId}:{},...e.channel!==void 0?{channel:e.channel}:{}};return(await this.api.lookupInstallments({body:t,signal:e.signal})).data}async getIntent(e,t={}){return(await this.api.getIntent({path:{intent_id:e},query:t.clientSecret?{client_secret:t.clientSecret}:void 0,signal:t.signal})).data}async confirm(e,t={}){let i={...t.clientSecret!==void 0?{client_secret:t.clientSecret}:{},...t.methodId!==void 0?{method_id:t.methodId}:{},...t.saveMethod!==void 0?{save_method:t.saveMethod}:{},...t.useMasterpass!==void 0?{use_masterpass:t.useMasterpass}:{},...t.phone!==void 0?{phone:t.phone}:{},...t.buyer!==void 0?{buyer:t.buyer}:{},...t.installments!==void 0?{installments:t.installments}:{},...t.providerOptions!==void 0?{provider_options:t.providerOptions}:{}},s=t.idempotencyKey?{"Idempotency-Key":t.idempotencyKey}:void 0;return(await this.api.confirmIntent({path:{intent_id:e},body:i,headers:s,signal:t.signal})).data}async submitOtp(e,t){let i={challenge_id:t.challengeId,otp:t.otp,...t.clientSecret!==void 0?{client_secret:t.clientSecret}:{},...t.saveMethod!==void 0?{save_method:t.saveMethod}:{}};return(await this.api.submitIntentOtp({path:{intent_id:e},body:i,signal:t.signal})).data}async portal(e,t={}){let i={return_url:e,...t.channel!==void 0?{channel:t.channel}:{}};return(await this.api.createMyPortal({body:i,signal:t.signal})).data.url}async waitForIntent(e,t={}){let i=t.timeoutMs??3e5;if(t.signal?.aborted)throw t.signal.reason;return new Promise((s,d)=>{let n=!1,a=!1,l=!1,u=this.socket.channel(`payment_intent:${this.ref}:${e}`),h=()=>{v!==void 0&&clearTimeout(v),x(),u.leave(),y.removeEventListener?.("message",g),t.signal?.removeEventListener("abort",f)},I=r=>{n||(n=!0,h(),s(r))},p=r=>{n||(n=!0,h(),d(r))},m=async()=>{if(!n){if(a){l=!0;return}a=!0;try{for(;;){l=!1;try{let r=await this.getIntent(e,{clientSecret:t.clientSecret,signal:t.signal});if(S(r.status)){I(r);return}}catch(r){if(t.signal?.aborted){p(t.signal.reason);return}if(r instanceof c&&(r.status===401||r.status===403||r.status===404)){p(r);return}}if(n||!l)return}}finally{a=!1}}},x=u.on("broadcast",r=>{typeof r.event=="string"&&W.has(r.event)&&m()}),g=r=>{if(r.origin&&r.origin!=="null"&&r.origin!==this.origin)return;let b=T(r.data);b&&b.intent_id===e&&m()},f=()=>p(t.signal?.reason),y=globalThis;y.addEventListener?.("message",g),t.signal?.addEventListener("abort",f,{once:!0});let v=i>0?setTimeout(()=>{p(new c({op:"WaitForIntent",status:0,code:"payment_timeout",message:`timed out waiting for payment intent ${e}`}))},i):void 0;u.join().catch(()=>{}),m()})}async present(e,t={}){let i=t.clientSecret??e.client_secret,s=e.status!==void 0&&e.amount!==void 0?e:await this.getIntent(e.id,{clientSecret:i,signal:t.signal});for(let d=0;d<6;d++){if(S(s.status))return s;let n=s.next_action;if(!n||n.type==="none")return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal});if(n.type==="redirect"){if(!n.url)throw new c({op:"PresentIntent",status:0,code:"invalid_next_action",message:"redirect next_action is missing url"});if(t.onRedirect)await t.onRedirect(n.url,n);else{let a=globalThis.location;if(!a)throw new c({op:"PresentIntent",status:0,code:"redirect_unavailable",message:"provide onRedirect in non-browser environments"});a.assign(n.url)}return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}if(n.type==="embed"){let a;if(t.onEmbed){let l=await t.onEmbed(n);typeof l=="function"&&(a=l)}else if(t.container)a=k(t.container,n);else throw new c({op:"PresentIntent",status:0,code:"embed_container_required",message:"provide container or onEmbed to present an embedded 3DS/checkout action"});try{return await this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}finally{a?.()}}if(n.type==="otp"||n.type==="masterpass"){if(!t.onOtp)throw new c({op:"PresentIntent",status:0,code:"otp_handler_required",message:"provide onOtp to complete an OTP or Masterpass verification step"});let a=n.challenge_id??"",l=await t.onOtp({intentId:s.id,challengeId:a,maskedPhone:n.masked_phone??n.masterpass?.phone,expiresAt:n.expires_at,masterpass:n.masterpass});if(l===null)throw new c({op:"PresentIntent",status:0,code:"payment_canceled",message:"verification canceled by customer"});let u=typeof l=="string"?l:l.otp,h=typeof l=="string"?void 0:l.saveMethod;s=await this.submitOtp(s.id,{challengeId:a,otp:u,clientSecret:i,saveMethod:h,signal:t.signal});continue}return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}return this.getIntent(s.id,{clientSecret:i,signal:t.signal})}onEvent(e){return this.eventListeners.add(e),this.eventListeners.size===1&&this.startEvents(),()=>{this.eventListeners.delete(e)&&this.eventListeners.size===0&&this.stopEvents()}}onWalletChange(e){if(this.walletListeners.add(e),this.walletListeners.size===1)this.startWalletWatch();else if(this.lastBalances!==void 0){let t=this.lastBalances;queueMicrotask(()=>this.walletListeners.has(e)&&M(e,t))}return()=>{this.walletListeners.delete(e)&&this.walletListeners.size===0&&this.stopWalletWatch()}}startWalletWatch(){this.walletFollowing=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.followWallet(t)}),this.session.session().then(e=>{this.walletFollowing&&!this.walletWatch&&this.lastBalances===void 0&&this.followWallet(e)})}stopWalletWatch(){this.walletFollowing?.(),this.walletFollowing=void 0,this.unfollowWallet(),this.lastBalances=void 0}followWallet(e){if(this.unfollowWallet(),!e){this.tellBalances(null);return}let t=this.socket.channel(`payments:${this.ref}:${e.userId}`),i={userId:e.userId,channel:t,off:()=>{},maxVersion:-1,reading:!1,wanted:!1},s=t.on("broadcast",d=>{typeof d.event=="string"&&E.has(d.event)&&this.walletChanged(i)});i.off=s,this.walletWatch=i,t.join().catch(()=>{}),this.readBalances(i)}unfollowWallet(){let e=this.walletWatch;e&&(this.walletWatch=void 0,e.off(),e.channel.leave())}walletChanged(e){this.walletWatch===e&&(e.reading?e.wanted=!0:this.readBalances(e))}async readBalances(e){e.reading=!0;try{for(;;){e.wanted=!1;try{let t=(await this.api.listMyWallets()).data.balances;if(this.walletWatch!==e)return;this.offerBalances(e,t)}catch{}if(this.walletWatch!==e||!e.wanted)return}}finally{e.reading=!1}}offerBalances(e,t){if(this.walletWatch!==e)return;let i=t.reduce((s,d)=>Math.max(s,d.version),0);e.maxVersion>=0&&i<e.maxVersion||(e.maxVersion=i,this.tellBalances(t))}tellBalances(e){if(!(this.lastBalances===null&&e===null)){this.lastBalances=e;for(let t of[...this.walletListeners])M(t,e)}}startEvents(){this.eventFollowing=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.followEvents(t)}),this.session.session().then(e=>{this.eventFollowing&&!this.eventWatch&&this.followEvents(e)})}stopEvents(){this.eventFollowing?.(),this.eventFollowing=void 0,this.unfollowEvents()}followEvents(e){if(this.unfollowEvents(),!e)return;let t=this.socket.channel(`payments:${this.ref}:${e.userId}`),i=t.on("broadcast",s=>{if(typeof s.event!="string")return;let d={type:s.event,payload:s.payload};for(let n of[...this.eventListeners])try{n(d)}catch{}});this.eventWatch={userId:e.userId,channel:t,off:i},t.join().catch(()=>{})}unfollowEvents(){let e=this.eventWatch;e&&(this.eventWatch=void 0,e.off(),e.channel.leave())}};function k(o,e){let i=o.ownerDocument.createElement("iframe");return i.setAttribute("data-palbase-payments-frame",""),i.setAttribute("title","Secure Payment Verification"),i.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin allow-popups allow-top-navigation-by-user-activation"),i.style.width="100%",i.style.minHeight="480px",i.style.border="0",i.style.borderRadius="8px",i.style.background="#ffffff",e.html?i.srcdoc=e.html:e.url&&(i.src=e.url),o.replaceChildren(i),()=>{i.remove()}}function M(o,e){try{o(e)}catch{}}export{P as a,S as b,T as c,B as d,_ as e,k as f};
1
+ /*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
2
+ import{n as w}from"./RP2TPMXT.js";import{b as c}from"./XVJ3CMFN.js";var P=new Set(["succeeded","requires_capture","failed","canceled","expired"]);function S(o){return P.has(o)}var W=new Set(["payments.payment.succeeded","payments.payment.failed","payments.payment.canceled","payments.payment.requires_capture"]),E=new Set(["payments.wallet.balance_changed","payments.wallet.hold_changed"]);function T(o){if(typeof o!="object"||o===null)return null;let e=o;return e.source!=="palbase.payments"||typeof e.intent_id!="string"||e.intent_id.length===0||typeof e.status!="string"||e.status.length===0?null:{source:"palbase.payments",intent_id:e.intent_id,status:e.status,...typeof e.decline_code=="string"&&e.decline_code.length>0?{decline_code:e.decline_code}:{},...typeof e.return_url=="string"&&e.return_url.length>0?{return_url:e.return_url}:{}}}var A={insufficient_funds:"Insufficient funds on this card. Please try another payment method.",card_declined:"Your card was declined by the issuing bank.",do_not_honor:"Your bank declined this transaction. Please contact your bank or use another card.",expired_card:"This card has expired. Please use a valid card.",incorrect_cvc:"The security code (CVC/CVV) is incorrect.",incorrect_number:"The card number is invalid.",invalid_expiry:"The card expiration date is invalid.",authentication_required:"Additional 3D Secure verification is required by your bank.",three_ds_failed:"3D Secure verification failed or was canceled.",otp_invalid:"The verification code is incorrect. Please try again.",otp_expired:"The verification code has expired. Please request a new one.",fraud_suspected:"This transaction was declined for security reasons.",velocity_exceeded:"Too many failed payment attempts. Please wait a moment and try again.",limit_exceeded:"This transaction exceeds your card limit.",card_not_permitted:"This card is not enabled for online or international transactions.",processing_error:"A temporary payment processing error occurred. Please try again.",provider_unavailable:"The payment provider is temporarily unavailable. Please try again.",wallet_frozen:"This wallet is currently frozen and cannot be charged.",wallet_insufficient_balance:"Insufficient wallet balance for this payment."};function B(o){return o?A[o]??"Payment was declined. Please try another payment method.":"Payment could not be completed. Please try again."}var _=class{api;profile;methods;wallet;subscriptions;session;socket;ref;origin;walletListeners=new Set;walletWatch;walletFollowing;lastBalances;eventListeners=new Set;eventWatch;eventFollowing;constructor(e,t,i,s,d){this.api=w.client(e),this.session=t,this.socket=i,this.ref=s,this.origin=d,this.profile={get:async n=>(await this.api.getMyProfile({signal:n?.signal})).data,update:async(n,a)=>(await this.api.updateMyProfile({body:n,signal:a?.signal})).data},this.methods={list:async n=>(await this.api.listMyMethods({signal:n?.signal})).data.methods,add:async(n={})=>{let a={...n.channel!==void 0?{channel:n.channel}:{},...n.vault!==void 0?{vault:n.vault}:{},...n.phone!==void 0?{phone:n.phone}:{},...n.returnUrl!==void 0?{return_url:n.returnUrl}:{},...n.cancelUrl!==void 0?{cancel_url:n.cancelUrl}:{}};return(await this.api.addMyMethod({body:a,signal:n.signal})).data.next_action},remove:async(n,a)=>{await this.api.deleteMyMethod({path:{method_id:n},signal:a?.signal})}},this.wallet={balances:async n=>{let a=this.session.snapshot()?.userId,l=(await this.api.listMyWallets({signal:n?.signal})).data.balances;return this.walletWatch&&this.walletWatch.userId===a&&this.offerBalances(this.walletWatch,l),l},balance:async(n,a)=>(await this.wallet.balances(a)).find(u=>u.wallet_key===n),topUp:async n=>{let a={wallet_key:n.walletKey,amount:n.amount,...n.channel!==void 0?{channel:n.channel}:{},...n.methodId!==void 0?{method_id:n.methodId}:{},...n.saveMethod!==void 0?{save_method:n.saveMethod}:{},...n.useMasterpass!==void 0?{use_masterpass:n.useMasterpass}:{},...n.phone!==void 0?{phone:n.phone}:{},...n.returnUrl!==void 0?{return_url:n.returnUrl}:{},...n.cancelUrl!==void 0?{cancel_url:n.cancelUrl}:{}},l=n.idempotencyKey?{"Idempotency-Key":n.idempotencyKey}:void 0;return(await this.api.topUpMyWallet({body:a,headers:l,signal:n.signal})).data},createSpendToken:async n=>{let a={wallet_key:n.walletKey,...n.maxAmount!==void 0?{max_amount:n.maxAmount}:{},...n.ttlSeconds!==void 0?{ttl_seconds:n.ttlSeconds}:{}};return(await this.api.createMySpendToken({body:a,signal:n.signal})).data},onChange:n=>this.onWalletChange(n)},this.subscriptions={list:async n=>(await this.api.listMySubscriptions({query:{limit:n?.limit,cursor:n?.cursor},signal:n?.signal})).data,cancel:async(n,a)=>(await this.api.cancelMySubscription({path:{subscription_id:n},signal:a?.signal})).data}}async capabilities(e={}){return(await this.api.getCapabilities({query:{...e.currency!==void 0?{currency:e.currency}:{},...e.channel!==void 0?{channel:e.channel}:{}},signal:e.signal})).data}async installments(e){let t={amount:e.amount,currency:e.currency,...e.bin!==void 0?{bin:e.bin}:{},...e.methodId!==void 0?{method_id:e.methodId}:{},...e.channel!==void 0?{channel:e.channel}:{}};return(await this.api.lookupInstallments({body:t,signal:e.signal})).data}async getIntent(e,t={}){return(await this.api.getIntent({path:{intent_id:e},query:t.clientSecret?{client_secret:t.clientSecret}:void 0,signal:t.signal})).data}async confirm(e,t={}){let i={...t.clientSecret!==void 0?{client_secret:t.clientSecret}:{},...t.methodId!==void 0?{method_id:t.methodId}:{},...t.saveMethod!==void 0?{save_method:t.saveMethod}:{},...t.useMasterpass!==void 0?{use_masterpass:t.useMasterpass}:{},...t.phone!==void 0?{phone:t.phone}:{},...t.buyer!==void 0?{buyer:t.buyer}:{},...t.installments!==void 0?{installments:t.installments}:{},...t.providerOptions!==void 0?{provider_options:t.providerOptions}:{}},s=t.idempotencyKey?{"Idempotency-Key":t.idempotencyKey}:void 0;return(await this.api.confirmIntent({path:{intent_id:e},body:i,headers:s,signal:t.signal})).data}async submitOtp(e,t){let i={challenge_id:t.challengeId,otp:t.otp,...t.clientSecret!==void 0?{client_secret:t.clientSecret}:{},...t.saveMethod!==void 0?{save_method:t.saveMethod}:{}};return(await this.api.submitIntentOtp({path:{intent_id:e},body:i,signal:t.signal})).data}async portal(e,t={}){let i={return_url:e,...t.channel!==void 0?{channel:t.channel}:{}};return(await this.api.createMyPortal({body:i,signal:t.signal})).data.url}async waitForIntent(e,t={}){let i=t.timeoutMs??3e5;if(t.signal?.aborted)throw t.signal.reason;return new Promise((s,d)=>{let n=!1,a=!1,l=!1,u=this.socket.channel(`payment_intent:${this.ref}:${e}`),h=()=>{v!==void 0&&clearTimeout(v),x(),u.leave(),y.removeEventListener?.("message",g),t.signal?.removeEventListener("abort",f)},I=r=>{n||(n=!0,h(),s(r))},p=r=>{n||(n=!0,h(),d(r))},m=async()=>{if(!n){if(a){l=!0;return}a=!0;try{for(;;){l=!1;try{let r=await this.getIntent(e,{clientSecret:t.clientSecret,signal:t.signal});if(S(r.status)){I(r);return}}catch(r){if(t.signal?.aborted){p(t.signal.reason);return}if(r instanceof c&&(r.status===401||r.status===403||r.status===404)){p(r);return}}if(n||!l)return}}finally{a=!1}}},x=u.on("broadcast",r=>{typeof r.event=="string"&&W.has(r.event)&&m()}),g=r=>{if(r.origin&&r.origin!=="null"&&r.origin!==this.origin)return;let b=T(r.data);b&&b.intent_id===e&&m()},f=()=>p(t.signal?.reason),y=globalThis;y.addEventListener?.("message",g),t.signal?.addEventListener("abort",f,{once:!0});let v=i>0?setTimeout(()=>{p(new c({op:"WaitForIntent",status:0,code:"payment_timeout",message:`timed out waiting for payment intent ${e}`}))},i):void 0;u.join().catch(()=>{}),m()})}async present(e,t={}){let i=t.clientSecret??e.client_secret,s=e.status!==void 0&&e.amount!==void 0?e:await this.getIntent(e.id,{clientSecret:i,signal:t.signal});for(let d=0;d<6;d++){if(S(s.status))return s;let n=s.next_action;if(!n||n.type==="none")return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal});if(n.type==="redirect"){if(!n.url)throw new c({op:"PresentIntent",status:0,code:"invalid_next_action",message:"redirect next_action is missing url"});if(t.onRedirect)await t.onRedirect(n.url,n);else{let a=globalThis.location;if(!a)throw new c({op:"PresentIntent",status:0,code:"redirect_unavailable",message:"provide onRedirect in non-browser environments"});a.assign(n.url)}return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}if(n.type==="embed"){let a;if(t.onEmbed){let l=await t.onEmbed(n);typeof l=="function"&&(a=l)}else if(t.container)a=k(t.container,n);else throw new c({op:"PresentIntent",status:0,code:"embed_container_required",message:"provide container or onEmbed to present an embedded 3DS/checkout action"});try{return await this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}finally{a?.()}}if(n.type==="otp"||n.type==="masterpass"){if(!t.onOtp)throw new c({op:"PresentIntent",status:0,code:"otp_handler_required",message:"provide onOtp to complete an OTP or Masterpass verification step"});let a=n.challenge_id??"",l=await t.onOtp({intentId:s.id,challengeId:a,maskedPhone:n.masked_phone??n.masterpass?.phone,expiresAt:n.expires_at,masterpass:n.masterpass});if(l===null)throw new c({op:"PresentIntent",status:0,code:"payment_canceled",message:"verification canceled by customer"});let u=typeof l=="string"?l:l.otp,h=typeof l=="string"?void 0:l.saveMethod;s=await this.submitOtp(s.id,{challengeId:a,otp:u,clientSecret:i,saveMethod:h,signal:t.signal});continue}return this.waitForIntent(s.id,{clientSecret:i,timeoutMs:t.timeoutMs,signal:t.signal})}return this.getIntent(s.id,{clientSecret:i,signal:t.signal})}onEvent(e){return this.eventListeners.add(e),this.eventListeners.size===1&&this.startEvents(),()=>{this.eventListeners.delete(e)&&this.eventListeners.size===0&&this.stopEvents()}}onWalletChange(e){if(this.walletListeners.add(e),this.walletListeners.size===1)this.startWalletWatch();else if(this.lastBalances!==void 0){let t=this.lastBalances;queueMicrotask(()=>this.walletListeners.has(e)&&M(e,t))}return()=>{this.walletListeners.delete(e)&&this.walletListeners.size===0&&this.stopWalletWatch()}}startWalletWatch(){this.walletFollowing=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.followWallet(t)}),this.session.session().then(e=>{this.walletFollowing&&!this.walletWatch&&this.lastBalances===void 0&&this.followWallet(e)})}stopWalletWatch(){this.walletFollowing?.(),this.walletFollowing=void 0,this.unfollowWallet(),this.lastBalances=void 0}followWallet(e){if(this.unfollowWallet(),!e){this.tellBalances(null);return}let t=this.socket.channel(`payments:${this.ref}:${e.userId}`),i={userId:e.userId,channel:t,off:()=>{},maxVersion:-1,reading:!1,wanted:!1},s=t.on("broadcast",d=>{typeof d.event=="string"&&E.has(d.event)&&this.walletChanged(i)});i.off=s,this.walletWatch=i,t.join().catch(()=>{}),this.readBalances(i)}unfollowWallet(){let e=this.walletWatch;e&&(this.walletWatch=void 0,e.off(),e.channel.leave())}walletChanged(e){this.walletWatch===e&&(e.reading?e.wanted=!0:this.readBalances(e))}async readBalances(e){e.reading=!0;try{for(;;){e.wanted=!1;try{let t=(await this.api.listMyWallets()).data.balances;if(this.walletWatch!==e)return;this.offerBalances(e,t)}catch{}if(this.walletWatch!==e||!e.wanted)return}}finally{e.reading=!1}}offerBalances(e,t){if(this.walletWatch!==e)return;let i=t.reduce((s,d)=>Math.max(s,d.version),0);e.maxVersion>=0&&i<e.maxVersion||(e.maxVersion=i,this.tellBalances(t))}tellBalances(e){if(!(this.lastBalances===null&&e===null)){this.lastBalances=e;for(let t of[...this.walletListeners])M(t,e)}}startEvents(){this.eventFollowing=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.followEvents(t)}),this.session.session().then(e=>{this.eventFollowing&&!this.eventWatch&&this.followEvents(e)})}stopEvents(){this.eventFollowing?.(),this.eventFollowing=void 0,this.unfollowEvents()}followEvents(e){if(this.unfollowEvents(),!e)return;let t=this.socket.channel(`payments:${this.ref}:${e.userId}`),i=t.on("broadcast",s=>{if(typeof s.event!="string")return;let d={type:s.event,payload:s.payload};for(let n of[...this.eventListeners])try{n(d)}catch{}});this.eventWatch={userId:e.userId,channel:t,off:i},t.join().catch(()=>{})}unfollowEvents(){let e=this.eventWatch;e&&(this.eventWatch=void 0,e.off(),e.channel.leave())}};function k(o,e){let i=o.ownerDocument.createElement("iframe");return i.setAttribute("data-palbase-payments-frame",""),i.setAttribute("title","Secure Payment Verification"),i.setAttribute("sandbox","allow-scripts allow-forms allow-same-origin allow-popups allow-top-navigation-by-user-activation"),i.style.width="100%",i.style.minHeight="480px",i.style.border="0",i.style.borderRadius="8px",i.style.background="#ffffff",e.html?i.srcdoc=e.html:e.url&&(i.src=e.url),o.replaceChildren(i),()=>{i.remove()}}function M(o,e){try{o(e)}catch{}}export{P as a,S as b,T as c,B as d,_ as e,k as f};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
2
2
  var s=class extends Error{code;constructor(t,e){super(e),this.name="FieldError",this.code=t}},f="pbe1.",g="pbl1.",k=6e4,p="[A-Za-z_][A-Za-z0-9_$]{0,62}",w=new RegExp(`^${p}\\.${p}(\\.${p})?$`);function v(o){return w.test(o)}var h=class{crypto;keys=new Map;lookupKey;timer;opts;now;constructor(t){this.opts=t,this.now=t.now??Date.now}get loaded(){return this.lookupKey!==void 0}async load(t){this.crypto??=await import("node:crypto"),this.take(await this.opts.fetch(t)),this.timer===void 0&&(this.timer=setInterval(()=>{this.opts.fetch().then(e=>this.take(e),()=>{})},k),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}take(t){let e=new Map;for(let r of t.keys)e.set(r.id,{id:r.id,key:Buffer.from(r.key,"base64url"),activatesAt:Date.parse(r.activates_at)});this.keys=e,this.lookupKey=Buffer.from(t.lookup,"base64url")}ready(){if(this.crypto===void 0||this.lookupKey===void 0)throw new s("not_loaded","the project's field keys are not loaded: await palbase.fields.load() at startup");return this.crypto}currentKey(){this.ready();let t;for(let e of this.keys.values())e.activatesAt<=this.now()&&(t===void 0||e.activatesAt>=t.activatesAt)&&(t=e);if(t===void 0)throw new s("unknown_key","the project has no field key in force");return t.id}encrypt(t,e){let r=this.ready();l(t);let n=this.currentKey(),i=r.randomBytes(12);return b(r,this.keys.get(n).key,i,n,t,e)}decrypt(t,e){let r=this.ready();if(l(t),!e.startsWith(f))throw new s("not_encrypted",`${t} holds a value that is not encrypted`);let n=e.slice(f.length),i=n.indexOf("."),a=i<0?n:n.slice(0,i),u=this.keys.get(a);if(u===void 0)throw new s("unknown_key",`${t} was sealed with field key ${a}, which this project does not hold`);let c=Buffer.from(n.slice(i+1),"base64url");if(i<0||c.length<28||c.toString("base64url")!==n.slice(i+1))throw new s("unopenable",`${t} holds a value that does not open here`);try{let d=r.createDecipheriv("aes-256-gcm",u.key,c.subarray(0,12));return d.setAAD(y(t)),d.setAuthTag(c.subarray(c.length-16)),Buffer.concat([d.update(c.subarray(12,c.length-16)),d.final()]).toString("utf8")}catch{throw new s("unopenable",`${t} holds a value that does not open here: tampered, or another column's`)}}isEncrypted(t){return t.startsWith(f)}lookup(t,e){let r=this.ready();return l(t),m(r,this.lookupKey,t,e)}};function l(o){if(!v(o))throw new TypeError(`a field's address is table.column, or schema.table.column, not ${JSON.stringify(o)}`)}function y(o){return Buffer.from(`pbe1\0${o}`,"utf8")}function b(o,t,e,r,n,i){let a=o.createCipheriv("aes-256-gcm",t,e);a.setAAD(y(n));let u=Buffer.concat([e,a.update(i,"utf8"),a.final(),a.getAuthTag()]);return`${f}${r}.${u.toString("base64url")}`}function m(o,t,e,r){let n=o.createHmac("sha256",t);return n.update(`pbl1\0${e}\0`,"utf8"),n.update(r,"utf8"),`${g}${n.digest("base64url")}`}export{s as a,h as b};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
2
2
  var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(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:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(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 l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
2
- import{b as c,f as u}from"./UOW74IHY.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
1
+ /*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as c,f as u}from"./XVJ3CMFN.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};