palbase 0.74.0 → 0.76.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.
- package/dist/ai/index.js +2 -2
- package/dist/ai-sdk/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{RK4CTF2F.js → 2NEPN2ZZ.js} +2 -2
- package/dist/chunks/{FKDQMWI7.js → 33XOVYAU.js} +2 -2
- package/dist/chunks/{53XWB3UV.js → 3CN6HGTW.js} +1 -1
- package/dist/chunks/{OS567PDL.js → 3VGWTVKI.js} +2 -2
- package/dist/chunks/{4DNFXRTX.js → 5RNXCTOO.js} +2 -2
- package/dist/chunks/{BBXGUP7G.js → 5YJZAPY2.js} +2 -2
- package/dist/chunks/{WNPRCDLR.js → A3I7H7QN.js} +1 -1
- package/dist/chunks/{YOCX3MXN.js → ALT62XIG.js} +2 -2
- package/dist/chunks/{AFO74GQQ.js → BRDO3ZPT.js} +1 -1
- package/dist/chunks/{IIQ6QEL2.js → D6NOE76D.js} +1 -1
- package/dist/chunks/{YDHRQOAN.js → DKYFIOWM.js} +1 -1
- package/dist/chunks/{SS3YF6MP.js → EXLA3A7O.js} +2 -2
- package/dist/chunks/{5NLCEWSD.js → ISMWEEGW.js} +1 -1
- package/dist/chunks/{IJBBBAXY.js → KEGVHELA.js} +1 -1
- package/dist/chunks/{U5LDOZB5.js → MKVIRNSJ.js} +2 -2
- package/dist/chunks/{QJPQVLNV.js → PGQNRJ2C.js} +2 -2
- package/dist/chunks/{CVBLXV6M.js → Q4UWBIJ6.js} +2 -2
- package/dist/chunks/{DFIAGTHU.js → SVWF7ABJ.js} +2 -2
- package/dist/chunks/{FYZAVXD4.js → TGQGGUE6.js} +2 -2
- package/dist/chunks/{MKKBGO2H.js → TUK6NH2Q.js} +2 -2
- package/dist/chunks/{7HDSHHGM.js → UHN63FGH.js} +7 -7
- package/dist/chunks/{ZRNXABQJ.js → UOW74IHY.js} +2 -2
- package/dist/chunks/YRYPXVAJ.js +18 -0
- package/dist/chunks/{AKM627JB.js → ZCMCYI2D.js} +2 -2
- package/dist/cli.js +2 -2
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai-sdk.js +1 -1
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/payments-ui.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/index.d.ts +1 -1
- package/types/ai/src/tools.d.ts +18 -0
- package/types/backend/src/gateways.d.ts +9 -0
- package/types/internal/src/modules/ai.d.ts +8 -0
- package/dist/chunks/PF52QMPW.js +0 -18
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as C}from"./AFO74GQQ.js";import{a as ue}from"./IJBBBAXY.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"./OS567PDL.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"./WNPRCDLR.js";import{a as ne,b as re}from"./DFIAGTHU.js";import{b as T,d as b}from"./ZRNXABQJ.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&<.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.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&<.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.
|
|
2
|
-
import{c as O,g as w,l as F,m as _,s as D}from"./YDHRQOAN.js";import{b as h}from"./ZRNXABQJ.js";var M=20,R=2048,S=256,z=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new h({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function j(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>M)throw m(`${n.length} attributes: at most ${M}`);let t=[];for(let i of n){if(!z.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=j(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>R)throw m(`the attributes are ${a.length} bytes: at most ${R}`);return a}function v(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function E(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function x(e,n,t){let a=e/10**E(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(E(n))} ${n}`}}function L(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var X={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function U(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=X[n.split("-")[0].toLowerCase()];return a?a(t):t}function K(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function I(e,n){let t=new Map,a=new Map;for(let r of e){let s=v(r.period);if(!s)continue;let l=r.price.amount/s.months;t.set(r.key,l),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,l))}let i={};for(let r of e){let s={product_name:r.productName,price:x(r.price.amount,r.price.currency,n)},l=v(r.period);if(l){s.period=L(l,n),s.price_per_month=x(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,u=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;u>=.01&&(s.savings=K(u,n))}let f=r.intro?.mode==="free_trial"?v(r.intro.duration):null;f&&(s.trial=U(f,n)),r.offer&&(s.offer_price=x(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.74.0"};var C=`palbase-js/${V.version}`;var b=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,l={},f=[]){this.placement=n,this.source=t,this.definition=a,this.assets=l,this.offerings=i,this.offers=f,this.shown=r,this.deps=s}packages(n){return I(q(this.offerings,F(this.definition),n,W(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?H():void 0,r=this.packages(a),s=D(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let u=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(u,o):globalThis.location.assign(u)}catch(u){if(!t.onError)throw u;t.onError(u,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),l=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",l),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let f=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",l),f()},s}};function H(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function J(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function q(e,n,t,a=new Map){let i=[];for(let r of n){let[s,l]=r.split("."),f=e.products.find(d=>d.key===s),o=f?.channels.web,u=o?.plans.find(d=>d.key===l);if(!f||!o||!u)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:J(o.locales,t)??f.key,price:{amount:u.price.amount,currency:u.price.currency},period:u.period,intro:u.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function W(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var Y={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function G(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:Y,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function $(){try{return globalThis.localStorage}catch{return}}function Q(e){try{let n=$()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?$()?.setItem(e,JSON.stringify(n)):$()?.removeItem(e)}catch{}}async function de(e,n,t,a,i,r={}){let{signal:s,fetch:l}=r,f=T(r.attributes),o=`palbase.paywall.${n}.${t}`,p={checkout:i,expose:async c=>{if(c.shown)try{let k={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":a},body:k})}catch{}}},g=async(c,k)=>new b(t,k,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await O(c.assets??[],{signal:s,...l?{fetch:l}:{}}),c.offers??[]),d=Q(o),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":a,"X-Platform":"web","X-Palbase-SDK":C,...r.appVersion?{"X-Palbase-Client-Version":r.appVersion}:{},...r.app?{"X-Palbase-App":r.app}:{},...r.locale?{"Accept-Language":r.locale}:{},...f!==void 0?{"X-Palbase-Attributes":f}:{},...d?.etag?{"If-None-Match":d.etag}:{}},signal:s})}catch(c){if(c instanceof h&&c.status===404||c instanceof h&&c.status===400&&c.code.startsWith("invalid_"))return P(o,void 0),A(e,t,p,s);if(d&&!s?.aborted)return g(d.answer,"cache");throw c}return y.status===200?(P(o,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&d?g(d.answer,"server"):(P(o,void 0),A(e,t,p,s))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=G(i);return r?new b(n,"default",r,i,void 0,t):null}export{T as a,v as b,x as c,L as d,I as e,b as f,G as g,de as h};
|
|
1
|
+
/*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as O,g as w,l as F,m as _,s as D}from"./DKYFIOWM.js";import{b as h}from"./UOW74IHY.js";var M=20,R=2048,S=256,z=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new h({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function j(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>M)throw m(`${n.length} attributes: at most ${M}`);let t=[];for(let i of n){if(!z.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=j(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>R)throw m(`the attributes are ${a.length} bytes: at most ${R}`);return a}function v(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function E(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function x(e,n,t){let a=e/10**E(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(E(n))} ${n}`}}function L(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var X={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function U(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=X[n.split("-")[0].toLowerCase()];return a?a(t):t}function K(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function I(e,n){let t=new Map,a=new Map;for(let r of e){let s=v(r.period);if(!s)continue;let l=r.price.amount/s.months;t.set(r.key,l),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,l))}let i={};for(let r of e){let s={product_name:r.productName,price:x(r.price.amount,r.price.currency,n)},l=v(r.period);if(l){s.period=L(l,n),s.price_per_month=x(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,u=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;u>=.01&&(s.savings=K(u,n))}let f=r.intro?.mode==="free_trial"?v(r.intro.duration):null;f&&(s.trial=U(f,n)),r.offer&&(s.offer_price=x(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.76.0"};var C=`palbase-js/${V.version}`;var b=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,l={},f=[]){this.placement=n,this.source=t,this.definition=a,this.assets=l,this.offerings=i,this.offers=f,this.shown=r,this.deps=s}packages(n){return I(q(this.offerings,F(this.definition),n,W(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?H():void 0,r=this.packages(a),s=D(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let u=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(u,o):globalThis.location.assign(u)}catch(u){if(!t.onError)throw u;t.onError(u,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),l=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",l),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let f=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",l),f()},s}};function H(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function J(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function q(e,n,t,a=new Map){let i=[];for(let r of n){let[s,l]=r.split("."),f=e.products.find(d=>d.key===s),o=f?.channels.web,u=o?.plans.find(d=>d.key===l);if(!f||!o||!u)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:J(o.locales,t)??f.key,price:{amount:u.price.amount,currency:u.price.currency},period:u.period,intro:u.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function W(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var Y={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function G(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:Y,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function $(){try{return globalThis.localStorage}catch{return}}function Q(e){try{let n=$()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?$()?.setItem(e,JSON.stringify(n)):$()?.removeItem(e)}catch{}}async function de(e,n,t,a,i,r={}){let{signal:s,fetch:l}=r,f=T(r.attributes),o=`palbase.paywall.${n}.${t}`,p={checkout:i,expose:async c=>{if(c.shown)try{let k={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":a},body:k})}catch{}}},g=async(c,k)=>new b(t,k,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await O(c.assets??[],{signal:s,...l?{fetch:l}:{}}),c.offers??[]),d=Q(o),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":a,"X-Platform":"web","X-Palbase-SDK":C,...r.appVersion?{"X-Palbase-Client-Version":r.appVersion}:{},...r.app?{"X-Palbase-App":r.app}:{},...r.locale?{"Accept-Language":r.locale}:{},...f!==void 0?{"X-Palbase-Attributes":f}:{},...d?.etag?{"If-None-Match":d.etag}:{}},signal:s})}catch(c){if(c instanceof h&&c.status===404||c instanceof h&&c.status===400&&c.code.startsWith("invalid_"))return P(o,void 0),A(e,t,p,s);if(d&&!s?.aborted)return g(d.answer,"cache");throw c}return y.status===200?(P(o,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&d?g(d.answer,"server"):(P(o,void 0),A(e,t,p,s))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=G(i);return r?new b(n,"default",r,i,void 0,t):null}export{T as a,v as b,x as c,L as d,I as e,b as f,G as g,de as h};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var K="pbt1.",E="Palbase-Encryption";var z="x-palbase-encrypted",o=class extends Error{code;constructor(t,n){super(n),this.name="TransitError",this.code=t}},h=new TextEncoder,P=new TextDecoder("utf-8",{fatal:!0}),l=()=>{let e=globalThis.crypto?.subtle;if(!e)throw new Error("encrypted fields need WebCrypto (crypto.subtle): a secure context \u2014 https, or localhost");return e};function y(e){return new Uint8Array(new ArrayBuffer(e))}function f(...e){let t=y(e.reduce((r,i)=>r+i.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function d(e){return f(e)}function m(e,t){let n=y(t);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return n}function x(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(e){let t=e.replace(/=+$/,"");if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)throw new o("malformed","not base64url");let n=atob(t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4)),r=y(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}var S=f(h.encode("KEM"),m(32,2)),g=f(h.encode("HPKE"),m(32,2),m(1,2),m(1,2)),v=h.encode("HPKE-v1"),X=16,H=12,T=32,$=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function N(e,t){let n=await l().importKey("raw",e.length===0?y(32):d(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await l().sign("HMAC",n,d(t)))}async function k(e,t,n,r){return N(t,f(v,e,h.encode(n),r))}async function U(e,t,n,r,i){let a=f(m(i,2),v,e,h.encode(n),r),s=y(i),c=y(0);for(let u=1,p=0;p<i;u++)c=await N(t,f(c,a,Uint8Array.of(u))),s.set(c.subarray(0,Math.min(c.length,i-p)),p),p+=c.length;return s}async function j(e){if(e.length!==32)throw new o("malformed","an X25519 private key is 32 bytes");return l().importKey("pkcs8",f($,e),{name:"X25519"},!1,["deriveBits"])}async function C(e){if(e.length!==32)throw new o("malformed","an X25519 public key is 32 bytes");return l().importKey("raw",d(e),{name:"X25519"},!1,[])}async function O(e,t){return new Uint8Array(await l().deriveBits({name:"X25519",public:t},e,256))}async function R(e,t,n){let r=await k(S,y(0),"eae_prk",e);return U(S,r,"shared_secret",f(t,n),T)}async function _(e,t){let n=await k(g,y(0),"psk_id_hash",y(0)),r=await k(g,y(0),"info_hash",t),i=f(Uint8Array.of(0),n,r),a=await k(g,e,"secret",y(0));return{key:await U(g,a,"key",i,X),nonce:await U(g,a,"base_nonce",i,H)}}async function b(e,t,n,r,i){let a=await l().importKey("raw",d(t),"AES-GCM",!1,[e]);return new Uint8Array(await l()[e]({name:"AES-GCM",iv:d(n),additionalData:d(r)},a,d(i)))}async function V(e,t,n,r=y(0),i){let a,s;if(i)a=await j(i.privateKey),s=d(i.publicKey);else{let B=await l().generateKey({name:"X25519"},!0,["deriveBits"]);a=B.privateKey,s=new Uint8Array(await l().exportKey("raw",B.publicKey))}let c=await R(await O(a,await C(e)),s,e),{key:u,nonce:p}=await _(c,t);return{enc:s,ct:await b("encrypt",u,p,r,n)}}async function q(e,t,n,r,i,a=y(0)){if(n.length!==32)throw new o("malformed","an encapsulated X25519 key is 32 bytes");try{let s=await R(await O(await j(e),await C(n)),n,t),{key:c,nonce:u}=await _(s,r);return await b("decrypt",c,u,a,i)}catch{throw new o("unopenable","the request's key does not open with the project's key it names")}}async function Z(e){let t=await l().importKey("pkcs8",f($,e),{name:"X25519"},!0,["deriveBits"]),n=await l().exportKey("jwk",t);return w(n.x)}function Q(e,t,n,r=[]){if(r.some(i=>i.includes("\0")))throw new o("malformed","a path's value holds no NUL");return h.encode(["palbase-encryption","1",e,t.toUpperCase(),L(n),...r].join("\0"))}function L(e){return e.replace(/\{[^/{}]*\}/g,"{}")}async function Y(e,t,n,r={}){let i=r.key?d(r.key):crypto.getRandomValues(y(32)),{enc:a,ct:s}=await V(t,n,i,y(0),r.ephemeral);return{kid:e,key:i,header:`1.${e}.${x(a)}.${x(s)}`}}function J(e){let t=e.trim().split(".");if(t.length!==4||t[0]!=="1"||!/^t[1-9][0-9]{0,5}$/.test(t[1]))throw new o("malformed",`${E} is 1.<key id>.<enc>.<ct>`);let n=w(t[2]),r=w(t[3]);if(n.length!==32||r.length!==48)throw new o("malformed",`${E} carries a 32-byte encapsulated key and a sealed 32-byte key`);return{kid:t[1],enc:n,ct:r}}async function ee(e,t,n,r){let{enc:i,ct:a}=J(e),s=await q(t,n,i,r,a);if(s.length!==32)throw new o("unopenable","the request's key is not 32 bytes");return s}function I(e){return h.encode(`pbt1\0${e}`)}async function te(e,t,n,r){let i=r?d(r):crypto.getRandomValues(y(12)),a=JSON.stringify(n);if(a===void 0)throw new o("malformed",`${t}: an encrypted field holds a JSON value`);let s=await b("encrypt",e,i,I(t),h.encode(a));return K+x(f(i,s))}function F(e){return typeof e=="string"&&e.startsWith(K)}async function ne(e,t,n){if(!F(n))throw new o("unopenable",`${t} is not an encrypted field`);let r;try{r=w(n.slice(K.length))}catch{throw new o("unopenable",`${t} is not an encrypted field`)}if(r.length<28)throw new o("unopenable",`${t} is too short to be an encrypted field`);let i;try{i=await b("decrypt",e,r.subarray(0,12),I(t),r.subarray(12))}catch{throw new o("unopenable",`${t} does not open: changed, moved from another field, or another request's`)}try{return JSON.parse(P.decode(i))}catch{throw new o("unopenable",`${t} opens to no JSON value`)}}function D(e){return e.replace(/~/g,"~0").replace(/\//g,"~1").replace(/\*/g,"~2")}function G(e){return e.replace(/~2/g,"*").replace(/~1/g,"/").replace(/~0/g,"~")}var M=Symbol("items");function W(e,t){if(!(e!==t&&!e.startsWith(t+"/")))return e===t?[]:e.slice(t.length+1).split("/").map(n=>n==="*"?M:G(n))}async function re(e,t,n,r){let i=e;for(let a of n){let s=W(a,t);s!==void 0&&(i=await A(i,s,t,r))}return i}async function A(e,t,n,r){if(t.length===0)return e===void 0?void 0:r(n,e);let[i,...a]=t;if(i===M){if(!Array.isArray(e))return e;let c=[];for(let[u,p]of e.entries())c.push(await A(p,a,`${n}/${u}`,r));return c}if(Array.isArray(e)){if(!/^(0|[1-9][0-9]*)$/.test(i)||Number(i)>=e.length)return e;let c=[...e];return c[Number(i)]=await A(c[Number(i)],a,`${n}/${i}`,r),c}if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,i))return e;let s={...e};return s[i]=await A(s[i],a,`${n}/${D(i)}`,r),s}function ie(){return x(crypto.getRandomValues(y(16)))}async function se(e,t,n,r){let i,a=!1;try{i=w(e.payload);let u=await l().importKey("raw",w(t),{name:"Ed25519"},!1,["verify"]);a=await l().verify({name:"Ed25519"},u,w(e.signature),i)}catch{throw new o("unverified","the project's key list does not verify")}if(!a)throw new o("unverified","the project's key list is not signed with the project's key");let s;try{s=JSON.parse(P.decode(i))}catch{throw new o("unverified","the project's key list is no JSON")}if(s.v!==1||s.project!==n||typeof s.issued_at!="string"||!Array.isArray(s.keys)||s.keys.length===0)throw new o("unverified","the key list is not this project's, or holds no key");if(s.nonce!==r)throw new o("unverified","the key list was not asked for just now: its nonce is not the one sent");let c=s.keys.map(u=>{if(typeof u.kid!="string"||!/^t[1-9][0-9]{0,5}$/.test(u.kid)||typeof u.key!="string")throw new o("unverified","a key of the list is malformed");let p=w(u.key);if(p.length!==32)throw new o("unverified","a key of the list is not an X25519 public key");return{kid:u.kid,key:p}});return{project:s.project,issuedAt:s.issued_at,keys:c}}export{E as a,z as b,o as c,w as d,Z as e,Q as f,Y as g,J as h,ee as i,te as j,F as k,ne as l,D as m,G as n,re as o,ie as p,se as q};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as N,d as I,e as R}from"./RK4CTF2F.js";import{a as Q,f as Y,g as Z,j as X,k as ee,l as te,o as G,p as ne,q as se}from"./WNPRCDLR.js";import{d as A}from"./DFIAGTHU.js";import{a as E,b as z,c as T,e as j}from"./ZRNXABQJ.js";var p=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="BackendError",this.kind=e,this.code=t.code,this.status=t.status??0,this.requestId=t.requestId,this.fields=t.fields,this.retryAfter=t.retryAfter,this.data=t.data}};function ie(n){return n instanceof p||typeof n=="object"&&n!==null&&n.name==="BackendError"&&typeof n.kind=="string"}function D(n){let e=n.body,t={code:n.code,message:n.message,status:n.status,requestId:n.requestId??We(e,"request_id"),data:S(e,"data"),cause:n};if(n.code==="network_error")return new p("network",t);if(n.status===401&&n.code==="insufficient_user_authentication")return new p("stepUpRequired",t);if(n.status===401&&n.code==="app_attest_required")return new p("attestationRequired",t);if(n.status===401)return new p("unauthorized",t);if(n.status===429)return new p("rateLimited",{...t,retryAfter:He(e)??n.retryAfter});let s=Je(e);return n.status===400&&s?new p("validation",{...t,fields:s}):new p("server",t)}function P(n){return n instanceof z||n instanceof Error&&n.name==="PalbaseError"}function re(n){return Array.isArray(n)&&n.length>0&&n.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Je(n){let e=S(S(n,"data"),"fields");if(re(e))return e;let t=S(n,"fields");return re(t)?t:void 0}function He(n){return oe(n,"retry_after")??oe(S(n,"data"),"retryAfter")}function S(n,e){if(typeof n=="object"&&n!==null)return n[e]}function oe(n,e){let t=S(n,e);return typeof t=="number"?t:void 0}function We(n,e){let t=S(n,e);return typeof t=="string"?t:void 0}var Ve=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ue=Object.freeze(["adoptSession","ai","analytics","anonymousTelemetry","appContext","appEvent","appVersion","auth","callOnSignOut","calls","cancelCallOnSignOut","captureOnce","chatToolCall","chatWorkspaceFile","configuration","consent","currentSession","defaults","flags","installation","keychainItem","module","moduleDirectory","notify","offerTaker","onAppEvent","onSessionChange","onSignOut","preferences","realtime","scope","send","setLanguage","setPreferredLanguages","signedInUserNow","socket","storage","storedUserId","telemetry","transport","transportFor","upload","version","watchSessions","palbe","data","stores","iap","payments","commerce","campaigns","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),ze=new Set(Ue),Qe=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function O(n){return n==="then"||n==="toJSON"||Qe.has(n)}function ae(n){return n==="call"||n==="join"||O(n)}function de(n){return typeof n=="string"&&Ve.test(n)&&!ze.has(n)&&!O(n)}function le(n){return typeof n=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(n)}function ce(n){j(n)}function ue(n){return j(n).origin}var $=class n{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;execution={target:null,generation:0,workspaceSeq:0,machineId:null,machineStatus:null,failoverAt:null,lastHandoff:null,compactions:[],offloads:[]};handoffGens=new Set;compactionSeqs=new Set;offloadKeys=new Set;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];racedPages=[];heldTimer;heldSince=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},t,s,r=!0){this.me=e,this.reader=t,this.chatId=s,this.replays=r}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let t=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,d={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...t!==void 0?{turns:t}:{},...e.signal?{signal:e.signal}:{}},a;if(e.load)a=await e.load(d);else{let f=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");a=await this.reader.parts(f,d)}if(this.ended)return!1;let l=(a?.parts??[]).map(f=>N(f)).filter(f=>f!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(l),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=l):this.racing&&(this.racedPages=l.concat(this.racedPages)),t===void 0||typeof a?.turns!="number"||s!==void 0&&this.olderCursor===s)break;t-=a.turns}while(t>0);return this.olderLeft}idFor(e,t){let s=t??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let u=w(i);u<=0||(this.paged.add(u),(this.pagedFrom===void 0||u<this.pagedFrom)&&(this.pagedFrom=u),(this.pagedTo===void 0||u>this.pagedTo)&&(this.pagedTo=u))}let t=new n(this.me);t.thoughts=this.thoughts,t.lowest=this.lowest-e.length;let s=t.lowest;for(let i of e)t.at=s++,t.fold(i);this.folded+=t.folded,this.lowest=t.lowest,this.chatId??=t.chatId;let r=new Map;for(let[i,u]of t.messages){let m=this.told.get(i)??[],k=u;if(m.length>0)for(let C of m)k=ye(k,C);else k=this.messages.get(i)??u;r.set(i,k);let _=[...t.told.get(i)??[],...m];_.length>0&&this.told.set(i,_)}for(let[i,u]of this.messages)r.has(i)||r.set(i,u);this.messages.clear();for(let[i,u]of r)this.messages.set(i,u);let o=new Map;for(let[i,u]of t.responses){let m=this.responses.get(i);o.set(i,m?Ze(u,m):u)}for(let[i,u]of this.responses)o.has(i)||o.set(i,u);this.responses.clear();for(let[i,u]of o)this.responses.set(i,u);let d=new Set;for(let i of t.order)(i.type==="message"||i.type==="response")&&d.add(`${i.type}\0${i.key}`);let a=[...t.order],l=new Set([...t.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&d.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&t.goalWords.has(i.event.seq))&&!(i.type==="voice"&&t.voiceWords.has(K(i.event)))&&!(i.type==="handoff"&&t.handoffGens.has(i.event.generation))&&!(i.type==="compaction"&&i.event.seq>0&&t.compactionSeqs.has(i.event.seq))){if(i.type==="message"&&i.began&&i.turn!==null){let u=this.responses.get(i.turn);l.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:u&&u.at<i.arrived?u.at-.5:i.arrived});continue}a.push(i)}a.sort((i,u)=>i.at-u.at),this.order=a;for(let i of t.goalWords)this.goalWords.add(i);this.goal=null;for(let i of a)i.type==="goal"&&this.goalSaid(i.event);for(let i of t.voiceWords)this.voiceWords.add(i);let f=new Set;this.voice=null;for(let i of a)i.type==="voice"&&(this.voice=me(this.voice,i.event,f));for(let i of t.handoffGens)this.handoffGens.add(i);for(let i of t.compactionSeqs)this.compactionSeqs.add(i);for(let i of t.offloadKeys)this.offloadKeys.add(i);t.execution.generation>this.execution.generation&&(this.execution={...this.execution,target:t.execution.target,generation:t.execution.generation,workspaceSeq:t.execution.workspaceSeq,lastHandoff:t.execution.lastHandoff}),this.execution.machineStatus===null&&t.execution.machineStatus!==null&&(this.execution={...this.execution,machineId:t.execution.machineId,machineStatus:t.execution.machineStatus,failoverAt:t.execution.failoverAt});let c=[];for(let i of a)i.type==="compaction"&&c.push(i.event);let h=[...t.execution.offloads,...this.execution.offloads.filter(i=>!t.offloadKeys.has(ge(i)))];this.execution={...this.execution,compactions:c,offloads:h},this.turn??=t.turn;let y=new Map([...t.calls,...this.calls]);this.calls.clear();for(let[i,u]of y)this.calls.set(i,u);for(let[i,u]of t.history)this.history.has(i)||this.history.set(i,u);this.forkedFrom??=t.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,t,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==t){t=o,yield o;continue}if(this.ended)return;await new Promise(d=>e=d)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0,clearTimeout(this.heldTimer);for(let e of[...this.enders])e()}}takePayload(e){let t=N(e);t&&this.take(t)}take(e){if(!this.ended){if(this.racing){this.held.length===0&&(this.heldSince=Date.now()),this.held.push(e);let t=w(e);t>0&&this.pagedTo!==void 0&&t>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=he(setTimeout(()=>this.quiet(),pe)));return}this.takeNow(e)}}quiet(){let e=this.held.map(w).filter(s=>s>0);e.length>0&&e.every(s=>!this.paged.has(s)&&this.pagedFrom!==void 0&&s<this.pagedFrom)&&Date.now()-this.heldSince<Ye?this.heldTimer=he(setTimeout(()=>this.quiet(),pe)):this.sortHeld()}takeNow(e){let t=w(e);t>0&&this.paged.has(t)||(t>0&&(this.oldestLive===void 0||t<this.oldestLive)&&(this.oldestLive=t),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),t=this.racedPages;this.racedPages=[];let s=[],r=[],o=e.findIndex(a=>this.paged.has(w(a))),d=o<0?-1:t.findIndex(a=>w(a)===w(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&fe(e[o-1-a],t[d-1-a]);)a++;let l=0;for(;o+l<e.length&&d+l<t.length&&fe(e[o+l],t[d+l]);)l++;s=e.slice(0,o-a),r=e.slice(o+l)}else{let a=e.find(f=>w(f)>0),l=a!==void 0&&this.pagedFrom!==void 0&&w(a)<this.pagedFrom;for(let f of e){let c=w(f);c>0&&!(this.pagedFrom!==void 0&&c<this.pagedFrom)&&(l=!1),(l?s:r).push(f)}}if(s.length>0){let a=Math.min(...s.map(w).filter(l=>l>0));this.before(s),Number.isFinite(a)&&(this.oldestLive=a,this.olderCursor=void 0)}for(let a of r)this.takeNow(a)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let t=this.response(e.response_id);t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(t.startedBy=e.user_id),e.goal&&(t.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let t=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){t.marks.set("thinking:unavailable",{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=t.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:t.marks.set(s,{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let t=K(e);if(this.voiceWords.has(t))return!1;this.voice=me(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let t=this.response(e.response_id);tt(t,e.offset,e.text),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"reset":{let t=this.response(e.response_id);e.offset<=t.from?(t.text="",t.from=Math.max(0,e.offset)):t.text=t.text.slice(0,R(t.text,e.offset-t.from)),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let t=this.response(e.response_id);t.runId=e.run_id,t.agent=e.name,t.named=!0,t.parentId??=e.parent_response_id;break}case"session.handed_off":{if(this.handoffGens.has(e.generation))return!1;this.handoffGens.add(e.generation),e.generation>=this.execution.generation&&(this.execution={...this.execution,target:e.to_target,generation:e.generation,workspaceSeq:e.workspace_seq,machineId:e.to_target.compute.machine_id??null,failoverAt:null,lastHandoff:e}),this.order.push({type:"handoff",event:e,at:this.at});break}case"session.machine_status":{this.execution={...this.execution,machineId:e.machine_id||this.execution.machineId,machineStatus:e.status,failoverAt:e.failover_at??null};break}case"context.offloaded":{let t=ge(e);if(this.offloadKeys.has(t))return!1;this.offloadKeys.add(t),this.execution={...this.execution,offloads:[...this.execution.offloads,e]};break}case"context.compacted":{if(e.seq>0){if(this.compactionSeqs.has(e.seq))return!1;this.compactionSeqs.add(e.seq)}this.execution={...this.execution,compactions:[...this.execution.compactions,e]},this.order.push({type:"compaction",event:e,at:this.at});break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let t=this.goal;if(!t||t.id!==e.goal_id)return;let s={...t,events:[...t.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let t=et(e),s=this.messages.get(t);this.messages.set(t,ye(s,e));let r=this.told.get(t);r?r.push(e):this.told.set(t,[e]),s||this.place(e,t),this.changed()}said(e){let t=`voice\0${e.id}`,s=this.messages.get(t);this.messages.set(t,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:t,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,t){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([l,f])=>l!==t&&f.responseId===s),o=r?this.responses.get(s):void 0,d={type:"message",key:t,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},a=o?this.order.findIndex(l=>l.type==="response"&&l.key===s):-1;a>=0?this.order.splice(a,0,d):this.order.push(d)}response(e){let t=this.responses.get(e);return t||(t={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,t),this.order.push({type:"response",key:e,at:this.at})),t}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let t of[...this.listeners])try{t(e)}catch{}}))}build(){let e=this.me(),t=c=>e!==void 0&&c.startedBy===e,s=new Map;for(let c of this.responses.values()){let h=c.parentId!==null?this.responses.get(c.parentId)??c:c;s.set(c.id,nt(c,h.startedBy??null,t(h),c.goal??h.goal))}let r=new Map([...this.messages].map(([c,h])=>[c,e!==void 0&&h.author===e?{...h,mine:!0}:h])),o=[...this.history.entries()].sort(([c],[h])=>c-h).flatMap(([c,h])=>h.map((y,i)=>st(y,`${c}:${i}`,e))),d=[...o];for(let c of this.order)c.type==="goal"?d.push({type:"goal",goal:c.event}):c.type==="voice"?d.push({type:"voice",voice:c.event}):c.type==="handoff"?d.push({type:"handoff",handoff:c.event}):c.type==="compaction"?d.push({type:"compaction",compaction:c.event}):c.type==="message"?d.push({type:"message",message:r.get(c.key)}):this.responses.get(c.key).parentId===null&&d.push({type:"response",response:s.get(c.key)});let a=o.flatMap(c=>c.type==="message"?[c.message]:[]),l=o.flatMap(c=>c.type==="response"?[c.response]:[]),f=[...this.calls.values()].filter(c=>s.get(c.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...l,...s.values()],turn:this.turn,waiting:{approvals:f.filter(c=>c.status==="awaiting_approval"),outputs:f.filter(c=>c.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Xe(this.voice,e):null,execution:this.execution}}},pe=150,Ye=2e3;function fe(n,e){let t=w(n);return t>0||w(e)>0?t===w(e):JSON.stringify(n)===JSON.stringify(e)}function w(n){let e=n.seq;return typeof e=="number"&&e>0?e:0}function he(n){return n.unref?.(),n}function K(n){return`${n.voice_id}\0${n.status}`}function ge(n){return n.seq>0?`seq:${n.seq}`:`call:${n.call_id}:${n.ref??""}`}function me(n,e,t){return t.add(K(e)),(e.status==="closed"?n===null||n.voice_id===e.voice_id:!t.has(`${e.voice_id}\0closed`))?e:n}function ye(n,e){let t=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??n?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:n?.status==="delivered"?"delivered":t,error:e.error??null,responseId:e.response_id??n?.responseId??null,createdAt:e.created_at??n?.createdAt??"",mine:!1,metadata:e.metadata??n?.metadata??{},history:!1,truncated:!1,kind:e.kind??n?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:n?.voice??null,attachments:e.attachments?we(e.attachments):n?.attachments??[]}}function Ze(n,e){let t={...n,marks:new Map(n.marks)};e.status!==null&&(t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=e.end),e.startedBy!==void 0&&(t.startedBy=e.startedBy),e.goal&&(t.goal=e.goal),e.named&&(t.runId=e.runId,t.agent=e.agent,t.named=!0),t.parentId=n.parentId??e.parentId,e.cut!==null&&(n.text===""||e.cut<=n.from?(t.text=e.text,t.from=e.text===""?Math.max(0,e.cut):e.from):t.text=n.text.slice(0,R(n.text,e.cut-n.from))+e.text,t.cut=n.cut===null?e.cut:Math.min(n.cut,e.cut));let s=r=>{if(n.text==="")return null;if(r!==null&&r<=n.from)return r;let o=I(n.text);return n.from+(r===null?o:Math.min(o,r-n.from))};for(let[r,o]of e.marks){let d=t.marks.get(r);if(d?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")t.marks.set(r,{...d,thinking:{...d.thinking,text:d.thinking.text+o.thinking.text}});else if(o.type==="thinking"&&o.loose){let a=s(o.cutAt);t.marks.set(r,a!==null?{...o,text_offset:a,loose:!1}:{...o,cutAt:o.cutAt===null?n.cut:n.cut===null?o.cutAt:Math.min(o.cutAt,n.cut)})}else t.marks.set(r,o)}return t}function Xe(n,e){return{id:n.voice_id,userId:n.user_id,mine:e!==void 0&&n.user_id===e,delegation:n.delegation,status:n.status,seconds:typeof n.seconds=="number"?n.seconds:null,closeReason:n.close_reason??""}}function we(n){return n.map((e,t)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:t,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function et(n){return`${n.author??""}\0${n.client_id}`}function tt(n,e,t){if(n.text===""||e<=n.from){n.from=Math.max(0,e),n.text=t;return}n.text=n.text.slice(0,R(n.text,e-n.from))+t}function nt(n,e,t,s){let r=[...n.marks.values()].map((l,f)=>({m:l,i:f,at:R(n.text,Math.max(0,(Number(l.text_offset)||0)-n.from))}));r.sort((l,f)=>l.at-f.at||l.i-f.i);let o=[],d=[],a=0;for(let{m:l,at:f}of r)f>a&&o.push({type:"text",text:n.text.slice(a,f)}),a=Math.max(a,f),l.type==="thinking"?(o.push({type:"thinking",thinking:l.thinking}),d.push(l.thinking)):o.push(l.type==="tool"?{type:"tool",tool:l}:{type:"agent",agent:l});return a<n.text.length&&o.push({type:"text",text:n.text.slice(a)}),{id:n.id,status:n.status,waiting:n.waiting,end:n.end,error:n.error,text:n.text,parts:o,runId:n.runId,agent:n.agent,parentId:n.parentId,startedBy:e,mine:t,thinking:d,goal:s,history:!1,truncated:!1}}function st(n,e,t){let s=n.text_truncated===!0;if(n.role==="user"){let r=n.author??null;return{type:"message",message:{clientId:n.client_id??"",id:n.message_id??null,text:n.text,author:r,authorName:n.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:n.created_at??"",mine:t!==void 0&&r===t,metadata:n.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:we(n.attachments??[])}}}return{type:"response",response:{id:n.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:n.text,parts:n.text===""?[]:[{type:"text",text:n.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var ve=[["ApiKeyAuth","userJWT"]];function be(n){return{async parts(e,t){let s={};t.limit!==void 0&&(s.limit=t.limit),t.turns!==void 0&&(s.turns=t.turns),t.cursor!==void 0?s.cursor=t.cursor:t.before!==void 0&&(s.before=t.before);let r=(await n.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${T("ListChatParts","chat_id",e)}/parts`,auth:ve,answers:{200:"json"},query:s,signal:t.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,t,s){if(typeof t!="string"||t==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await n.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${T("GetChatToolCall","chat_id",e)}/tool-calls/${T("GetChatToolCall","call_id",t)}`,auth:ve,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}}}}var M=class extends Error{reason;constructor(e,t){super(e),this.name="GatewayError",this.reason=t}},ke=new WeakMap;async function Ee(n,e,t,s={},r=()=>{},o){let{pattern:d,events:a,messages:l,durable:f,chat:c}=rt(e),h=ot(d,t),y=ke.get(n);y||ke.set(n,y=new Map);let i=y,u=i.get(h)??{count:0};i.set(h,u),u.count++;let m=n.channel(h,f&&s.history!==!1?{after:0}:{});if(c&&!u.chat){let g=t.chatId,x=new $(r,o,typeof g=="string"&&g!==""?g:void 0,f&&s.history!==!1);u.chat=x,u.unchat=m.on("broadcast",v=>{v.event==="chat"&&x.takePayload(v.payload)})}let k=()=>{--u.count>0||(i.delete(h),u.unchat?.(),u.chat?.end(),m.leave())};try{await m.join()}catch{let g=m.state==="refused"?xe(m.refusal,"unavailable"):"socket closed";throw k(),new M(`gateway ${JSON.stringify(h)} was not joined: ${g}`,g)}let _=!1,C=new Set,W=()=>{if(!_){_=!0,Fe();for(let g of[...C])g();k()}},Fe=m.onClosed(W),V=g=>{if(_)return()=>{};let x=m.on("broadcast",b=>{typeof b.event=="string"&&a.has(b.event)&&g(b.event,E(b.payload))}),v=()=>{C.delete(v),x()};return C.add(v),v},U={topic:h,get seq(){return m.logSeq},on(g,x){if(typeof g=="function")return V((v,b)=>g({event:v,payload:b}));if(!a.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(g))}`);if(typeof x!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(g)}, \u2026) takes the function the event is handed to`);return V((v,b)=>{v===g&&x(b)})},off(g){C.has(g)&&g()},async send(g,x){if(!l.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(g))}`);let v=_?{status:"error",response:{reason:"not joined"}}:await m.push("broadcast",{type:"broadcast",event:g,payload:x});if(v.status==="ok")return E(v.response.reply);let b=xe(v.response,"unavailable");throw new M(`gateway ${JSON.stringify(h)} did not take ${JSON.stringify(g)}: ${b}`,b)},leave:W};return c&&Object.defineProperty(U,"chat",{value:u.chat,enumerable:!0}),U}function rt(n){let e=typeof n=="object"&&n!==null?n:{},t=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!t(e.events)||!t(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function ot(n,e){let t=typeof e=="object"&&e!==null?e:{};return n.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(t,r)?t[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(n)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(n)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function xe(n,e){let t=n?.reason;return typeof t=="string"&&t!==""?t:e}var it=3600*1e3,q=new Map;function at(n,e,t=!1){let s=`${e.projectId}\0${e.signer}`,r=q.get(s);if(!t&&r&&Date.now()-r.at<it)return r.list;let o=(async()=>{let d=ne(),a;try{a=(await n.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:d},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(l){throw new p("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:l})}try{return await se(a,e.signer,e.projectId,d)}catch(l){throw new p("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:l})}})();return q.set(s,{list:o,at:Date.now()}),o.catch(()=>{q.get(s)?.list===o&&q.delete(s)}),o}async function _e(n,e,t,s,r,o){let a=(await at(n,e,o)).keys[0];return Z(a.kid,a.key,Y(e.projectId,t,s,r))}function L(n,e,t,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,t,s,(r,o)=>X(n.key,r,o))}function Se(n,e,t,s){return e===void 0||!t||t.length===0?Promise.resolve(e):G(e,"/response",t,async(r,o)=>{if(!ee(o))throw new p("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await te(n.key,r,o)}catch(d){throw new p("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Ce(n){return n instanceof p&&(n.code==="encryption_key_retired"||n.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
|
|
1
|
+
/*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as N,d as I,e as R}from"./2NEPN2ZZ.js";import{a as Q,f as Y,g as Z,j as X,k as ee,l as te,o as G,p as ne,q as se}from"./A3I7H7QN.js";import{d as A}from"./SVWF7ABJ.js";import{a as E,b as z,c as T,e as j}from"./UOW74IHY.js";var p=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="BackendError",this.kind=e,this.code=t.code,this.status=t.status??0,this.requestId=t.requestId,this.fields=t.fields,this.retryAfter=t.retryAfter,this.data=t.data}};function ie(n){return n instanceof p||typeof n=="object"&&n!==null&&n.name==="BackendError"&&typeof n.kind=="string"}function D(n){let e=n.body,t={code:n.code,message:n.message,status:n.status,requestId:n.requestId??We(e,"request_id"),data:S(e,"data"),cause:n};if(n.code==="network_error")return new p("network",t);if(n.status===401&&n.code==="insufficient_user_authentication")return new p("stepUpRequired",t);if(n.status===401&&n.code==="app_attest_required")return new p("attestationRequired",t);if(n.status===401)return new p("unauthorized",t);if(n.status===429)return new p("rateLimited",{...t,retryAfter:He(e)??n.retryAfter});let s=Je(e);return n.status===400&&s?new p("validation",{...t,fields:s}):new p("server",t)}function P(n){return n instanceof z||n instanceof Error&&n.name==="PalbaseError"}function re(n){return Array.isArray(n)&&n.length>0&&n.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Je(n){let e=S(S(n,"data"),"fields");if(re(e))return e;let t=S(n,"fields");return re(t)?t:void 0}function He(n){return oe(n,"retry_after")??oe(S(n,"data"),"retryAfter")}function S(n,e){if(typeof n=="object"&&n!==null)return n[e]}function oe(n,e){let t=S(n,e);return typeof t=="number"?t:void 0}function We(n,e){let t=S(n,e);return typeof t=="string"?t:void 0}var Ve=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ue=Object.freeze(["adoptSession","ai","analytics","anonymousTelemetry","appContext","appEvent","appVersion","auth","callOnSignOut","calls","cancelCallOnSignOut","captureOnce","chatToolCall","chatWorkspaceFile","configuration","consent","currentSession","defaults","flags","installation","keychainItem","module","moduleDirectory","notify","offerTaker","onAppEvent","onSessionChange","onSignOut","preferences","realtime","scope","send","setLanguage","setPreferredLanguages","signedInUserNow","socket","storage","storedUserId","telemetry","transport","transportFor","upload","version","watchSessions","palbe","data","stores","iap","payments","commerce","campaigns","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),ze=new Set(Ue),Qe=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function O(n){return n==="then"||n==="toJSON"||Qe.has(n)}function ae(n){return n==="call"||n==="join"||O(n)}function de(n){return typeof n=="string"&&Ve.test(n)&&!ze.has(n)&&!O(n)}function le(n){return typeof n=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(n)}function ce(n){j(n)}function ue(n){return j(n).origin}var $=class n{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;execution={target:null,generation:0,workspaceSeq:0,machineId:null,machineStatus:null,failoverAt:null,lastHandoff:null,compactions:[],offloads:[]};handoffGens=new Set;compactionSeqs=new Set;offloadKeys=new Set;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];racedPages=[];heldTimer;heldSince=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},t,s,r=!0){this.me=e,this.reader=t,this.chatId=s,this.replays=r}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let t=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,d={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...t!==void 0?{turns:t}:{},...e.signal?{signal:e.signal}:{}},a;if(e.load)a=await e.load(d);else{let f=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");a=await this.reader.parts(f,d)}if(this.ended)return!1;let l=(a?.parts??[]).map(f=>N(f)).filter(f=>f!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(l),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=l):this.racing&&(this.racedPages=l.concat(this.racedPages)),t===void 0||typeof a?.turns!="number"||s!==void 0&&this.olderCursor===s)break;t-=a.turns}while(t>0);return this.olderLeft}idFor(e,t){let s=t??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let u=w(i);u<=0||(this.paged.add(u),(this.pagedFrom===void 0||u<this.pagedFrom)&&(this.pagedFrom=u),(this.pagedTo===void 0||u>this.pagedTo)&&(this.pagedTo=u))}let t=new n(this.me);t.thoughts=this.thoughts,t.lowest=this.lowest-e.length;let s=t.lowest;for(let i of e)t.at=s++,t.fold(i);this.folded+=t.folded,this.lowest=t.lowest,this.chatId??=t.chatId;let r=new Map;for(let[i,u]of t.messages){let m=this.told.get(i)??[],k=u;if(m.length>0)for(let C of m)k=ye(k,C);else k=this.messages.get(i)??u;r.set(i,k);let _=[...t.told.get(i)??[],...m];_.length>0&&this.told.set(i,_)}for(let[i,u]of this.messages)r.has(i)||r.set(i,u);this.messages.clear();for(let[i,u]of r)this.messages.set(i,u);let o=new Map;for(let[i,u]of t.responses){let m=this.responses.get(i);o.set(i,m?Ze(u,m):u)}for(let[i,u]of this.responses)o.has(i)||o.set(i,u);this.responses.clear();for(let[i,u]of o)this.responses.set(i,u);let d=new Set;for(let i of t.order)(i.type==="message"||i.type==="response")&&d.add(`${i.type}\0${i.key}`);let a=[...t.order],l=new Set([...t.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&d.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&t.goalWords.has(i.event.seq))&&!(i.type==="voice"&&t.voiceWords.has(K(i.event)))&&!(i.type==="handoff"&&t.handoffGens.has(i.event.generation))&&!(i.type==="compaction"&&i.event.seq>0&&t.compactionSeqs.has(i.event.seq))){if(i.type==="message"&&i.began&&i.turn!==null){let u=this.responses.get(i.turn);l.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:u&&u.at<i.arrived?u.at-.5:i.arrived});continue}a.push(i)}a.sort((i,u)=>i.at-u.at),this.order=a;for(let i of t.goalWords)this.goalWords.add(i);this.goal=null;for(let i of a)i.type==="goal"&&this.goalSaid(i.event);for(let i of t.voiceWords)this.voiceWords.add(i);let f=new Set;this.voice=null;for(let i of a)i.type==="voice"&&(this.voice=me(this.voice,i.event,f));for(let i of t.handoffGens)this.handoffGens.add(i);for(let i of t.compactionSeqs)this.compactionSeqs.add(i);for(let i of t.offloadKeys)this.offloadKeys.add(i);t.execution.generation>this.execution.generation&&(this.execution={...this.execution,target:t.execution.target,generation:t.execution.generation,workspaceSeq:t.execution.workspaceSeq,lastHandoff:t.execution.lastHandoff}),this.execution.machineStatus===null&&t.execution.machineStatus!==null&&(this.execution={...this.execution,machineId:t.execution.machineId,machineStatus:t.execution.machineStatus,failoverAt:t.execution.failoverAt});let c=[];for(let i of a)i.type==="compaction"&&c.push(i.event);let h=[...t.execution.offloads,...this.execution.offloads.filter(i=>!t.offloadKeys.has(ge(i)))];this.execution={...this.execution,compactions:c,offloads:h},this.turn??=t.turn;let y=new Map([...t.calls,...this.calls]);this.calls.clear();for(let[i,u]of y)this.calls.set(i,u);for(let[i,u]of t.history)this.history.has(i)||this.history.set(i,u);this.forkedFrom??=t.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,t,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==t){t=o,yield o;continue}if(this.ended)return;await new Promise(d=>e=d)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0,clearTimeout(this.heldTimer);for(let e of[...this.enders])e()}}takePayload(e){let t=N(e);t&&this.take(t)}take(e){if(!this.ended){if(this.racing){this.held.length===0&&(this.heldSince=Date.now()),this.held.push(e);let t=w(e);t>0&&this.pagedTo!==void 0&&t>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=he(setTimeout(()=>this.quiet(),pe)));return}this.takeNow(e)}}quiet(){let e=this.held.map(w).filter(s=>s>0);e.length>0&&e.every(s=>!this.paged.has(s)&&this.pagedFrom!==void 0&&s<this.pagedFrom)&&Date.now()-this.heldSince<Ye?this.heldTimer=he(setTimeout(()=>this.quiet(),pe)):this.sortHeld()}takeNow(e){let t=w(e);t>0&&this.paged.has(t)||(t>0&&(this.oldestLive===void 0||t<this.oldestLive)&&(this.oldestLive=t),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),t=this.racedPages;this.racedPages=[];let s=[],r=[],o=e.findIndex(a=>this.paged.has(w(a))),d=o<0?-1:t.findIndex(a=>w(a)===w(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&fe(e[o-1-a],t[d-1-a]);)a++;let l=0;for(;o+l<e.length&&d+l<t.length&&fe(e[o+l],t[d+l]);)l++;s=e.slice(0,o-a),r=e.slice(o+l)}else{let a=e.find(f=>w(f)>0),l=a!==void 0&&this.pagedFrom!==void 0&&w(a)<this.pagedFrom;for(let f of e){let c=w(f);c>0&&!(this.pagedFrom!==void 0&&c<this.pagedFrom)&&(l=!1),(l?s:r).push(f)}}if(s.length>0){let a=Math.min(...s.map(w).filter(l=>l>0));this.before(s),Number.isFinite(a)&&(this.oldestLive=a,this.olderCursor=void 0)}for(let a of r)this.takeNow(a)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let t=this.response(e.response_id);t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(t.startedBy=e.user_id),e.goal&&(t.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let t=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){t.marks.set("thinking:unavailable",{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=t.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:t.marks.set(s,{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let t=K(e);if(this.voiceWords.has(t))return!1;this.voice=me(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let t=this.response(e.response_id);tt(t,e.offset,e.text),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"reset":{let t=this.response(e.response_id);e.offset<=t.from?(t.text="",t.from=Math.max(0,e.offset)):t.text=t.text.slice(0,R(t.text,e.offset-t.from)),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let t=this.response(e.response_id);t.runId=e.run_id,t.agent=e.name,t.named=!0,t.parentId??=e.parent_response_id;break}case"session.handed_off":{if(this.handoffGens.has(e.generation))return!1;this.handoffGens.add(e.generation),e.generation>=this.execution.generation&&(this.execution={...this.execution,target:e.to_target,generation:e.generation,workspaceSeq:e.workspace_seq,machineId:e.to_target.compute.machine_id??null,failoverAt:null,lastHandoff:e}),this.order.push({type:"handoff",event:e,at:this.at});break}case"session.machine_status":{this.execution={...this.execution,machineId:e.machine_id||this.execution.machineId,machineStatus:e.status,failoverAt:e.failover_at??null};break}case"context.offloaded":{let t=ge(e);if(this.offloadKeys.has(t))return!1;this.offloadKeys.add(t),this.execution={...this.execution,offloads:[...this.execution.offloads,e]};break}case"context.compacted":{if(e.seq>0){if(this.compactionSeqs.has(e.seq))return!1;this.compactionSeqs.add(e.seq)}this.execution={...this.execution,compactions:[...this.execution.compactions,e]},this.order.push({type:"compaction",event:e,at:this.at});break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let t=this.goal;if(!t||t.id!==e.goal_id)return;let s={...t,events:[...t.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let t=et(e),s=this.messages.get(t);this.messages.set(t,ye(s,e));let r=this.told.get(t);r?r.push(e):this.told.set(t,[e]),s||this.place(e,t),this.changed()}said(e){let t=`voice\0${e.id}`,s=this.messages.get(t);this.messages.set(t,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:t,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,t){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([l,f])=>l!==t&&f.responseId===s),o=r?this.responses.get(s):void 0,d={type:"message",key:t,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},a=o?this.order.findIndex(l=>l.type==="response"&&l.key===s):-1;a>=0?this.order.splice(a,0,d):this.order.push(d)}response(e){let t=this.responses.get(e);return t||(t={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,t),this.order.push({type:"response",key:e,at:this.at})),t}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let t of[...this.listeners])try{t(e)}catch{}}))}build(){let e=this.me(),t=c=>e!==void 0&&c.startedBy===e,s=new Map;for(let c of this.responses.values()){let h=c.parentId!==null?this.responses.get(c.parentId)??c:c;s.set(c.id,nt(c,h.startedBy??null,t(h),c.goal??h.goal))}let r=new Map([...this.messages].map(([c,h])=>[c,e!==void 0&&h.author===e?{...h,mine:!0}:h])),o=[...this.history.entries()].sort(([c],[h])=>c-h).flatMap(([c,h])=>h.map((y,i)=>st(y,`${c}:${i}`,e))),d=[...o];for(let c of this.order)c.type==="goal"?d.push({type:"goal",goal:c.event}):c.type==="voice"?d.push({type:"voice",voice:c.event}):c.type==="handoff"?d.push({type:"handoff",handoff:c.event}):c.type==="compaction"?d.push({type:"compaction",compaction:c.event}):c.type==="message"?d.push({type:"message",message:r.get(c.key)}):this.responses.get(c.key).parentId===null&&d.push({type:"response",response:s.get(c.key)});let a=o.flatMap(c=>c.type==="message"?[c.message]:[]),l=o.flatMap(c=>c.type==="response"?[c.response]:[]),f=[...this.calls.values()].filter(c=>s.get(c.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...l,...s.values()],turn:this.turn,waiting:{approvals:f.filter(c=>c.status==="awaiting_approval"),outputs:f.filter(c=>c.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Xe(this.voice,e):null,execution:this.execution}}},pe=150,Ye=2e3;function fe(n,e){let t=w(n);return t>0||w(e)>0?t===w(e):JSON.stringify(n)===JSON.stringify(e)}function w(n){let e=n.seq;return typeof e=="number"&&e>0?e:0}function he(n){return n.unref?.(),n}function K(n){return`${n.voice_id}\0${n.status}`}function ge(n){return n.seq>0?`seq:${n.seq}`:`call:${n.call_id}:${n.ref??""}`}function me(n,e,t){return t.add(K(e)),(e.status==="closed"?n===null||n.voice_id===e.voice_id:!t.has(`${e.voice_id}\0closed`))?e:n}function ye(n,e){let t=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??n?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:n?.status==="delivered"?"delivered":t,error:e.error??null,responseId:e.response_id??n?.responseId??null,createdAt:e.created_at??n?.createdAt??"",mine:!1,metadata:e.metadata??n?.metadata??{},history:!1,truncated:!1,kind:e.kind??n?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:n?.voice??null,attachments:e.attachments?we(e.attachments):n?.attachments??[]}}function Ze(n,e){let t={...n,marks:new Map(n.marks)};e.status!==null&&(t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=e.end),e.startedBy!==void 0&&(t.startedBy=e.startedBy),e.goal&&(t.goal=e.goal),e.named&&(t.runId=e.runId,t.agent=e.agent,t.named=!0),t.parentId=n.parentId??e.parentId,e.cut!==null&&(n.text===""||e.cut<=n.from?(t.text=e.text,t.from=e.text===""?Math.max(0,e.cut):e.from):t.text=n.text.slice(0,R(n.text,e.cut-n.from))+e.text,t.cut=n.cut===null?e.cut:Math.min(n.cut,e.cut));let s=r=>{if(n.text==="")return null;if(r!==null&&r<=n.from)return r;let o=I(n.text);return n.from+(r===null?o:Math.min(o,r-n.from))};for(let[r,o]of e.marks){let d=t.marks.get(r);if(d?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")t.marks.set(r,{...d,thinking:{...d.thinking,text:d.thinking.text+o.thinking.text}});else if(o.type==="thinking"&&o.loose){let a=s(o.cutAt);t.marks.set(r,a!==null?{...o,text_offset:a,loose:!1}:{...o,cutAt:o.cutAt===null?n.cut:n.cut===null?o.cutAt:Math.min(o.cutAt,n.cut)})}else t.marks.set(r,o)}return t}function Xe(n,e){return{id:n.voice_id,userId:n.user_id,mine:e!==void 0&&n.user_id===e,delegation:n.delegation,status:n.status,seconds:typeof n.seconds=="number"?n.seconds:null,closeReason:n.close_reason??""}}function we(n){return n.map((e,t)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:t,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function et(n){return`${n.author??""}\0${n.client_id}`}function tt(n,e,t){if(n.text===""||e<=n.from){n.from=Math.max(0,e),n.text=t;return}n.text=n.text.slice(0,R(n.text,e-n.from))+t}function nt(n,e,t,s){let r=[...n.marks.values()].map((l,f)=>({m:l,i:f,at:R(n.text,Math.max(0,(Number(l.text_offset)||0)-n.from))}));r.sort((l,f)=>l.at-f.at||l.i-f.i);let o=[],d=[],a=0;for(let{m:l,at:f}of r)f>a&&o.push({type:"text",text:n.text.slice(a,f)}),a=Math.max(a,f),l.type==="thinking"?(o.push({type:"thinking",thinking:l.thinking}),d.push(l.thinking)):o.push(l.type==="tool"?{type:"tool",tool:l}:{type:"agent",agent:l});return a<n.text.length&&o.push({type:"text",text:n.text.slice(a)}),{id:n.id,status:n.status,waiting:n.waiting,end:n.end,error:n.error,text:n.text,parts:o,runId:n.runId,agent:n.agent,parentId:n.parentId,startedBy:e,mine:t,thinking:d,goal:s,history:!1,truncated:!1}}function st(n,e,t){let s=n.text_truncated===!0;if(n.role==="user"){let r=n.author??null;return{type:"message",message:{clientId:n.client_id??"",id:n.message_id??null,text:n.text,author:r,authorName:n.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:n.created_at??"",mine:t!==void 0&&r===t,metadata:n.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:we(n.attachments??[])}}}return{type:"response",response:{id:n.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:n.text,parts:n.text===""?[]:[{type:"text",text:n.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var ve=[["ApiKeyAuth","userJWT"]];function be(n){return{async parts(e,t){let s={};t.limit!==void 0&&(s.limit=t.limit),t.turns!==void 0&&(s.turns=t.turns),t.cursor!==void 0?s.cursor=t.cursor:t.before!==void 0&&(s.before=t.before);let r=(await n.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${T("ListChatParts","chat_id",e)}/parts`,auth:ve,answers:{200:"json"},query:s,signal:t.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,t,s){if(typeof t!="string"||t==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await n.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${T("GetChatToolCall","chat_id",e)}/tool-calls/${T("GetChatToolCall","call_id",t)}`,auth:ve,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}}}}var M=class extends Error{reason;constructor(e,t){super(e),this.name="GatewayError",this.reason=t}},ke=new WeakMap;async function Ee(n,e,t,s={},r=()=>{},o){let{pattern:d,events:a,messages:l,durable:f,chat:c}=rt(e),h=ot(d,t),y=ke.get(n);y||ke.set(n,y=new Map);let i=y,u=i.get(h)??{count:0};i.set(h,u),u.count++;let m=n.channel(h,f&&s.history!==!1?{after:0}:{});if(c&&!u.chat){let g=t.chatId,x=new $(r,o,typeof g=="string"&&g!==""?g:void 0,f&&s.history!==!1);u.chat=x,u.unchat=m.on("broadcast",v=>{v.event==="chat"&&x.takePayload(v.payload)})}let k=()=>{--u.count>0||(i.delete(h),u.unchat?.(),u.chat?.end(),m.leave())};try{await m.join()}catch{let g=m.state==="refused"?xe(m.refusal,"unavailable"):"socket closed";throw k(),new M(`gateway ${JSON.stringify(h)} was not joined: ${g}`,g)}let _=!1,C=new Set,W=()=>{if(!_){_=!0,Fe();for(let g of[...C])g();k()}},Fe=m.onClosed(W),V=g=>{if(_)return()=>{};let x=m.on("broadcast",b=>{typeof b.event=="string"&&a.has(b.event)&&g(b.event,E(b.payload))}),v=()=>{C.delete(v),x()};return C.add(v),v},U={topic:h,get seq(){return m.logSeq},on(g,x){if(typeof g=="function")return V((v,b)=>g({event:v,payload:b}));if(!a.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(g))}`);if(typeof x!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(g)}, \u2026) takes the function the event is handed to`);return V((v,b)=>{v===g&&x(b)})},off(g){C.has(g)&&g()},async send(g,x){if(!l.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(g))}`);let v=_?{status:"error",response:{reason:"not joined"}}:await m.push("broadcast",{type:"broadcast",event:g,payload:x});if(v.status==="ok")return E(v.response.reply);let b=xe(v.response,"unavailable");throw new M(`gateway ${JSON.stringify(h)} did not take ${JSON.stringify(g)}: ${b}`,b)},leave:W};return c&&Object.defineProperty(U,"chat",{value:u.chat,enumerable:!0}),U}function rt(n){let e=typeof n=="object"&&n!==null?n:{},t=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!t(e.events)||!t(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function ot(n,e){let t=typeof e=="object"&&e!==null?e:{};return n.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(t,r)?t[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(n)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(n)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function xe(n,e){let t=n?.reason;return typeof t=="string"&&t!==""?t:e}var it=3600*1e3,q=new Map;function at(n,e,t=!1){let s=`${e.projectId}\0${e.signer}`,r=q.get(s);if(!t&&r&&Date.now()-r.at<it)return r.list;let o=(async()=>{let d=ne(),a;try{a=(await n.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:d},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(l){throw new p("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:l})}try{return await se(a,e.signer,e.projectId,d)}catch(l){throw new p("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:l})}})();return q.set(s,{list:o,at:Date.now()}),o.catch(()=>{q.get(s)?.list===o&&q.delete(s)}),o}async function _e(n,e,t,s,r,o){let a=(await at(n,e,o)).keys[0];return Z(a.kid,a.key,Y(e.projectId,t,s,r))}function L(n,e,t,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,t,s,(r,o)=>X(n.key,r,o))}function Se(n,e,t,s){return e===void 0||!t||t.length===0?Promise.resolve(e):G(e,"/response",t,async(r,o)=>{if(!ee(o))throw new p("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await te(n.key,r,o)}catch(d){throw new p("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Ce(n){return n instanceof p&&(n.code==="encryption_key_retired"||n.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
|
|
3
3
|
`);let t=[],s=this.pending.indexOf(`
|
|
4
4
|
`);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&t.push({event:this.eventName,payload:this.dataLines.join(`
|
|
5
5
|
`)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let d=o.slice(5);this.dataLines.push(d.startsWith(" ")?d.slice(1):d)}else if(o.startsWith("event:")){let d=o.slice(6);this.eventName=d.startsWith(" ")?d.slice(1):d}}s=this.pending.indexOf(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.76.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.
|
|
1
|
+
/*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var Rt=d=>[...new Uint8Array(d)].map(t=>t.toString(16).padStart(2,"0")).join(""),_t=d=>`pw-font-${d}`;function ne(d){return(typeof d=="string"?/^asset:([0-9a-f-]{36})$/.exec(d):null)?.[1]}async function an(d,t={}){let l={},a=t.fetch??((c,p)=>globalThis.fetch(c,p));return await Promise.all(d.map(async c=>{try{if(!/^https:\/\//.test(c.url))return;let p=await a(c.url,{signal:t.signal,credentials:"omit"});if(!p.ok)return;let g=await p.arrayBuffer();if(g.byteLength!==c.bytes&&c.bytes>0||Rt(await globalThis.crypto.subtle.digest("SHA-256",g))!==c.sha256.toLowerCase())return;let b=At(c.kind,new Uint8Array(g));if(b===void 0)return;let y=await Et(c,g,b,t);y&&(l[c.id]=y)}catch{}})),l}var C=(d,t,l=0)=>d.length>=l+t.length&&t.every((a,c)=>d[l+c]===a),W=d=>[...d].map(t=>t.charCodeAt(0));function At(d,t){switch(d){case"image":return C(t,[137,80,78,71,13,10,26,10])?"image/png":C(t,[255,216,255])?"image/jpeg":C(t,W("RIFF"))&&C(t,W("WEBP"),8)?"image/webp":void 0;case"video":return C(t,W("ftyp"),4)?C(t,W("qt "),8)?"video/quicktime":"video/mp4":C(t,[26,69,223,163])?"video/webm":void 0;case"font":return C(t,W("wOF2"))?"font/woff2":C(t,W("wOFF"))?"font/woff":C(t,W("OTTO"))?"font/otf":C(t,[0,1,0,0])||C(t,W("true"))?"font/ttf":void 0;case"html":return C(t,[80,75,3,4])||C(t,[80,75,5,6])?"application/zip":void 0;default:return}}async function Et(d,t,l,a){switch(d.kind){case"image":case"video":return{kind:d.kind,url:URL.createObjectURL(new Blob([t],{type:l}))};case"font":{let c=_t(d.id),p=globalThis.FontFace,g=a.fonts??globalThis.document?.fonts;if(!p||!g)return;let h=new p(c,t,{display:"block"});return await h.load(),g.add(h),{kind:"font",url:"",family:c}}case"html":{let c=await Lt(new Uint8Array(t)),p=Ot(c);return p===void 0?void 0:{kind:"html",url:"",html:p}}}}async function Lt(d){let t=new DataView(d.buffer,d.byteOffset,d.byteLength),l=-1;for(let h=d.length-22;h>=Math.max(0,d.length-22-65535);h--)if(t.getUint32(h,!0)===101010256){l=h;break}if(l<0)throw new Error("not a zip");let a=t.getUint16(l+10,!0),c=t.getUint32(l+16,!0),p=new Map,g=0;for(let h=0;h<a;h++){if(t.getUint32(c,!0)!==33639248)throw new Error("a broken zip");let b=t.getUint16(c+10,!0),y=t.getUint32(c+20,!0),m=t.getUint32(c+24,!0),v=t.getUint16(c+28,!0),A=t.getUint16(c+30,!0),P=t.getUint16(c+32,!0),R=t.getUint32(c+42,!0),x=new TextDecoder().decode(d.subarray(c+46,c+46+v));if(c+=46+v+A+P,x.endsWith("/"))continue;if(x.startsWith("/")||x.split("/").includes(".."))throw new Error("a path leaving the zip");if(g+=m,p.size>=200||g>20971520)throw new Error("a zip too large");let T=R+30+t.getUint16(R+26,!0)+t.getUint16(R+28,!0),O=d.subarray(T,T+y);if(b===0)p.set(x,O);else if(b===8)p.set(x,await Pt(O));else throw new Error("a zip entry compressed another way")}return p}async function Pt(d){let t=new Response(new Uint8Array(d)).body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}var Tt={html:"text/html",css:"text/css",js:"text/javascript",mjs:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};function qe(d,t){let l=Tt[d.split(".").pop()?.toLowerCase()??""]??"application/octet-stream",a="";for(let c=0;c<t.length;c+=32768)a+=String.fromCharCode(...t.subarray(c,c+32768));return`data:${l};base64,${btoa(a)}`}var $t="default-src 'none'; img-src data:; media-src data:; font-src data:; style-src 'unsafe-inline' data:; script-src 'unsafe-inline' data:";function Ot(d){let t=d.get("index.html");if(!t)return;let l=new TextDecoder().decode(t),a=y=>new TextDecoder().decode(d.get(y)),c=y=>{let m=y.replace(/^\.\//,"").split(/[?#]/)[0];return d.has(m)?m:void 0},p=y=>y.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(m,v,A)=>{let P=c(A);return P?`url("${qe(P,d.get(P))}")`:m}),g=globalThis.DOMParser;if(!g)return;let h=new g().parseFromString(l,"text/html");for(let y of[...h.querySelectorAll('link[rel~="stylesheet"][href]')]){let m=c(y.getAttribute("href")),v=h.createElement("style");v.textContent=m?p(a(m)):"",y.replaceWith(v)}for(let y of[...h.querySelectorAll("style")])y.textContent=p(y.textContent??"");for(let y of[...h.querySelectorAll("[src], [href], [poster]")])for(let m of["src","href","poster"]){let v=y.getAttribute(m);if(v===null)continue;let A=c(v);A?y.setAttribute(m,qe(A,d.get(A))):/^(https?:)?\/\//i.test(v)&&y.removeAttribute(m)}for(let y of[...h.querySelectorAll("[style]")])y.setAttribute("style",p(y.getAttribute("style")??""));let b=h.createElement("meta");return b.setAttribute("http-equiv","Content-Security-Policy"),b.setAttribute("content",$t),h.head.prepend(b),`<!doctype html>${h.documentElement.outerHTML}`}var K=(d,t,l)=>`M${d-l} ${t}a${l} ${l} 0 1 0 ${2*l} 0a${l} ${l} 0 1 0 ${-2*l} 0`,de={ad_free:["M3 7h18v10H3z","M4 4l16 16"],bell:["M6 16v-5a6 6 0 0 1 12 0v5l2 2H4z","M10 21a2 2 0 0 0 4 0"],bolt:["M13 2L4 14h7l-1 8 9-12h-7z"],book:["M5 4h11a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3z","M5 17a3 3 0 0 1 3-3h11"],chart:["M3 20h18","M6 20v-8","M11 20V5","M16 20v-6","M21 20V9"],chat:["M4 5h16v11H9l-5 4z"],check:["M5 12l5 5 9-10"],check_circle:[K(12,12,9),"M8 12l3 3 5-6"],clock:[K(12,12,9),"M12 7v5l3 2"],cloud:["M7 18a4 4 0 0 1-.5-7.97A6 6 0 0 1 18 9a4.5 4.5 0 0 1-.5 9z"],crown:["M3 8l4 4 5-7 5 7 4-4-2 11H5z"],download:["M12 4v11","M7 10l5 5 5-5","M4 20h16"],gift:["M3 9h18v4H3z","M5 13v8h14v-8","M12 9v12","M12 9C10 5 6 5 6 7.5S12 9 12 9zm0 0c2-4 6-4 6-1.5S12 9 12 9z"],globe:[K(12,12,9),"M3 12h18","M12 3a14 14 0 0 1 0 18a14 14 0 0 1 0-18z"],heart:["M12 20s-7-4.5-9-9a4.5 4.5 0 0 1 9-3 4.5 4.5 0 0 1 9 3c-2 4.5-9 9-9 9z"],infinity:["M7 9a3 3 0 1 0 0 6c3 0 7-6 10-6a3 3 0 1 1 0 6c-3 0-7-6-10-6z"],lock_open:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 7.5-2"],music:["M9 18V5l11-2v13",K(6,18,3),K(17,16,3)],people:[K(9,8,3.5),"M2 20a7 7 0 0 1 14 0","M16 4.5a3.5 3.5 0 0 1 0 7","M18 14a6 6 0 0 1 4 6"],person:[K(12,8,4),"M4 21a8 8 0 0 1 16 0"],photo:["M3 5h18v14H3z",K(8.5,9.5,1.5),"M3 17l5-5 4 4 3-3 6 6"],shield:["M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"],sparkles:["M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z","M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"],star:["M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3l-5.5 2.9 1-6.2L3 9.6l6.2-.9z"],video:["M3 6h12v12H3z","M15 10l6-3v10l-6-3z"],arrow_right:["M4 12h15","M13 6l6 6-6 6"],calendar:["M4 6h16v15H4z","M4 10h16","M8 3v5","M16 3v5"],close:["M6 6l12 12","M18 6L6 18"],lock:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 8 0v4"],play:["M7 4l13 8-13 8z"],quote:["M5 17c3 0 4-2 4-5V7H4v5h3","M15 17c3 0 4-2 4-5V7h-5v5h3"],trophy:["M7 4h10v5a5 5 0 0 1-10 0z","M7 6H4v2a3 3 0 0 0 3 3","M17 6h3v2a3 3 0 0 1-3 3","M12 14v4","M8 21h8","M9 18h6v3H9z"]};var Be="http://www.w3.org/2000/svg";function pe(d,t,l){let a=d.createElementNS(Be,"svg");a.setAttribute("viewBox","0 0 24 24"),a.setAttribute("width",String(l)),a.setAttribute("height",String(l)),a.setAttribute("fill","none"),a.setAttribute("stroke","currentColor"),a.setAttribute("stroke-width","2"),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round"),a.setAttribute("aria-hidden","true"),a.setAttribute("focusable","false");for(let c of t){let p=d.createElementNS(Be,"path");p.setAttribute("d",c),a.append(p)}return a}var dn=2,pn=2,f=(d,t=!1)=>({kind:"value",value:"plain",def:d,required:t}),j=d=>({kind:"value",value:"color",def:d}),We=d=>({kind:"value",value:"spacing",def:d}),zt=d=>({kind:"value",value:"radius",def:d}),G=(d=!1)=>({kind:"text",required:d}),Me=(d,t=!1)=>({kind:"list",item:d,required:t}),se=(d,t=!1)=>({kind:"object",item:d,required:t}),Ke=(d=!1)=>({kind:"component",required:d}),Re={kind:"components"},Ge={stack:{axis:f("vertical"),spacing:We(0),align:f("center"),distribution:f("start"),scroll:f(!1),children:Re},text:{text:G(),spans:Me("span"),font:f(),size:f(),weight:f(),line_height:f(),letter_spacing:f(),color:{kind:"value",value:"textColor",def:"text"},align:f("center"),max_lines:f(),uppercase:f(!1)},image:{src:f(void 0,!0),fit:f("fit"),aspect:f(),mask:se("mask"),overlay:{kind:"value",value:"textColor"},alt:G(),decorative:f(!1)},icon:{name:f(void 0,!0),color:j("accent"),size:f(24)},video:{src:f(void 0,!0),poster:f(),autoplay:f(!0),loop:f(!0),mute:f(!0),controls:f(!1),fit:f("fill"),aspect:f(),alt:G()},button:{action:se("action",!0),content:Ke(!0)},purchase_button:{content:Ke(!0),package:f()},package:{product:f(void 0,!0),plan:f(void 0,!0),selected:f(!1),offer:f(),children:Re},tabs:{},switch:{},carousel:{pages:Re,peek:f(0),spacing:f(8),loop:f(!1),auto_advance_ms:f(),indicator:se("indicator"),height:f("")},countdown:{},timeline:{items:Me("timeline_item",!0),line_color:j("accent"),line_width:f(2),icon_color:j("on_accent"),color:j("text"),spacing:f(16)},features:{items:Me("feature",!0),icon_color:j("accent"),color:j("text"),spacing:f(12)},spacer:{size:We()},divider:{color:j("muted"),thickness:f(1)},custom_html:{src:f(void 0,!0),height:f("",!0)}},Ht={style:{padding:{kind:"edges"},margin:{kind:"edges"},width:f(""),height:f(""),max_width:f(),background:{kind:"fill"},border:se("border"),corners:{kind:"corners"},shadow:se("shadow"),opacity:f(1)},border:{width:f(),color:j("")},shadow:{color:j(""),radius:f(0),x:f(0),y:f(0)},linear:{type:f(""),angle:f(180),stops:f()},radial:{type:f(""),center_x:f(.5),center_y:f(.5),radius:f(.5),stops:f()},image_fill:{type:f(""),src:f(),fit:f("fill")},video_fill:{type:f(""),src:f(),poster:f(),loop:f(!0)},animation:{type:f(""),duration_ms:f(300),delay_ms:f(0),easing:f("ease_out")},action:{type:f(""),url:f(),sheet:f(),package:f()},mask:{shape:f(""),radius:zt(0),depth:f(16)},span:{text:G(!0),bold:f(!1),italic:f(!1),underline:f(!1),strikethrough:f(!1),color:j(""),link:f()},timeline_item:{icon:f(void 0,!0),title:G(!0),text:G(),color:j("")},feature:{icon:f(void 0,!0),text:G(!0)},indicator:{style:f("dots"),color:j("muted"),active_color:j("accent"),size:f(8),spacing:f(6)},typography:{font:f("system"),size:f(),weight:f(400),line_height:f(),letter_spacing:f(0),text_style:f("body")}},Xe=new Set(["package","purchase_button"]),Ct={action:{type:f(""),url:f(),link:f(),sheet:f(),placement:f(),name:f(),value:f(),offer:f(),code:G(),dismiss:f(!0)},presentation:{type:f(""),position:f("bottom"),auto_dismiss_seconds:f(),dismissible:f(!0),backdrop:j("#00000080")}},jt={modal:["type","dismissible","backdrop"],fullscreen:["type"],banner:["type","position","auto_dismiss_seconds","dismissible"],slide_in:["type","position","auto_dismiss_seconds","dismissible"],toast:["type","position","auto_dismiss_seconds","dismissible"],card:["type"]},Ft={linear:"linear",radial:"radial",image:"image_fill",video:"video_fill"},Nt=["top","bottom","leading","trailing"],Dt=["top_leading","top_trailing","bottom_leading","bottom_trailing"],Jt=Object.keys(Ge),un=Jt.filter(d=>!Xe.has(d)),Ye=/\{\{\s*([^{}]*?)\s*\}\}/g,Q=(d,t)=>typeof d=="object"&&d!==null&&Object.hasOwn(d,t),M=d=>typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{},I=d=>Array.isArray(d)?d:[],X=(d,t)=>d??t;function It(d){let t="";for(let l of new TextEncoder().encode(d)){let a=String.fromCharCode(l);t+=/^[A-Za-z0-9._~-]$/.test(a)?a:`%${l.toString(16).toUpperCase().padStart(2,"0")}`}return t}function Vt(d){let t=Math.floor(d/86400),l=Math.floor(d%86400/3600),a=Math.floor(d%3600/60),c=d%60,p=h=>String(h).padStart(2,"0");return{countdown:t>0?`${t}d ${p(l)}:${p(a)}:${p(c)}`:l>0?`${l}:${p(a)}:${p(c)}`:`${p(a)}:${p(c)}`,days:String(t),hours:p(l),minutes:p(a),seconds:p(c)}}function fn(d){let t=[],l=c=>{if(Array.isArray(c))return c.forEach(l);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.product=="string"&&typeof p.plan=="string"){let g=`${p.product}.${p.plan}`;t.includes(g)||t.push(g)}for(let g of Object.keys(p).sort())l(p[g])},a=d;for(let c of["header","root","footer"])l(a[c]);for(let c of Object.keys(M(a.sheets)).sort())l(M(M(a.sheets)[c]).root);return t}function Ut(d){let t=new Map,l=c=>{if(Array.isArray(c))return c.forEach(l);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.offer=="string"){let g=`${p.product}.${p.plan}`;t.has(g)||t.set(g,p.offer)}for(let g of Object.keys(p).sort())l(p[g])},a=d;for(let c of["header","root","footer","sheets"])l(a[c]);return t}function gn(d,t){return Ae(d,t).tree}function Ae(d,t){return new ue("paywall",d,t).resolve()}function hn(d,t){return Ee(d,t).tree}function Ee(d,t){let{variables:l,...a}=t;return new ue("message",d,{...a,packages:{"":{...l}}}).resolve()}var ue=class{kind;d;opts;lang;texts={};palette;typography={};radii;spacing;packages;offers;selected="";tab="";paths=new WeakMap;tabsShown={};switchesOn={};countdowns={};constructor(t,l,a){this.kind=t,this.d=l,this.opts=a,this.offers=Ut(l);let c={};for(let[y,m]of Object.entries(a.packages??{})){let v={...m};this.open(y)||(m.price!==void 0?v.offer_price=m.price:delete v.offer_price),c[y]=v}this.packages=c;let p=M(this.d.locales),g=String(this.d.default_locale??""),h=a.locale;Q(p,h)||(h=h.split("-")[0]??"",Q(p,h)||(h=g)),this.lang=h;for(let y of[g,h])for(let[m,v]of Object.entries(M(p[y])))typeof v=="string"&&(this.texts[m]=v);let b=M(this.d.theme);this.palette=M(M(b.colors)[a.appearance]);for(let[y,m]of Object.entries(M(b.typography))){let v={};for(let[A,P]of Object.entries(this.objectFields("typography"))){let R=X(M(m)[A],P.def);R!=null&&(v[A]=R)}this.typography[y]=v}this.radii=M(b.radii),this.spacing=M(b.spacing)}open(t){let l=this.offers.get(t);return l!==void 0&&(this.opts.offers??[]).includes(l)}fields(t){if(!(this.kind==="message"&&Xe.has(t)))return Ge[t]}objectFields(t){return(this.kind==="message"?Ct[t]:void 0)??Ht[t]??{}}resolve(){let[t,l]=this.initialState();this.tab=t,this.selected=this.kind==="paywall"?l:"";let a={theme:{colors:this.palette,typography:this.typography,radii:this.radii,spacing:this.spacing}};this.kind==="paywall"&&(a.selected=l);let c=this.d.presentation;if(typeof c=="object"&&c!==null){let g=this.item("presentation",M(c),void 0)??{},h=jt[String(M(c).type)]??[];for(let b of Object.keys(g))h.includes(b)||delete g[b];a.presentation=g}for(let g of["header","root","footer"]){let h=this.d[g];if(typeof h=="object"&&h!==null){let b=this.component(M(h),g,"",!1);b&&(a[g]=b)}}let p={};if(typeof this.d.sheets=="object"&&this.d.sheets!==null){let g={};for(let[h,b]of Object.entries(M(this.d.sheets))){let y=this.component(M(M(b).root),`sheets.${h}.root`,"",!1);y&&(g[h]=y);let m=this.text(M(b).title,this.packages[this.selected]);m!==null&&(p[h]=m)}a.sheets=g}return{tree:a,pathOf:g=>this.paths.get(g),tabs:this.tabsShown,switches:this.switchesOn,sheetTitles:p,countdowns:this.countdowns,language:this.lang}}switchOn(t,l){return this.opts.switches&&Object.hasOwn(this.opts.switches,l)?this.opts.switches[l]:this.opts.switch?this.opts.switch==="on":t.default===!0}tabShown(t,l){let c=I(t.tabs).map(M).map(g=>String(g.id)),p=this.opts.tabs?.[l];return p!==void 0&&c.includes(p)?p:this.opts.tab?this.opts.tab:typeof t.default=="string"&&t.default!==""?t.default:c[0]??""}initialState(){let t="",l="",a="",c="",p=(h,b)=>{if(Array.isArray(h)){h.forEach((m,v)=>p(m,`${b}[${v}]`));return}if(typeof h!="object"||h===null)return;let y=h;switch(y.type){case"package":{let m=`${y.product}.${y.plan}`;a===""&&(a=m),y.selected===!0&&l===""&&(l=m);break}case"switch":{let m=this.switchOn(y,b),v=m?y.on_package:y.off_package;typeof v=="string"&&c===""&&(c=v),p(m?y.on:y.off,`${b}.${m?"on":"off"}`);return}case"tabs":{let m=this.tabShown(y,b);t===""&&(t=m),I(y.tabs).forEach((v,A)=>{let P=M(v);P.id===m&&(typeof P.package=="string"&&c===""&&(c=P.package),p(P.content,`${b}.tabs[${A}].content`))});return}}for(let m of Object.keys(y).sort())m!=="sheets"&&p(y[m],b===""?m:`${b}.${m}`)};for(let h of["header","root","footer"])p(this.d[h],h);let g=this.opts.selected||c||l||a;return[t,g]}holds(t,l){let a=l||this.selected;for(let[c,p]of Object.entries(t))switch(c){case"selected_package":if(!I(p).includes(this.selected))return!1;break;case"intro_eligible":if((this.opts.eligible??[]).includes(a)!==p)return!1;break;case"offer_open":if(this.open(a)!==p)return!1;break;case"platform":if(!I(p).includes(this.opts.platform))return!1;break;case"locale":if(!I(p).includes(this.opts.locale)&&!I(p).includes(this.lang))return!1;break;case"appearance":if(p!==this.opts.appearance)return!1;break;case"tab":if(p!==this.tab)return!1;break}return!0}component(t,l,a,c){if(typeof t.visible=="object"&&t.visible!==null&&!this.holds(M(t.visible),a))return null;let p=String(t.type),g=a,h=c;p==="package"&&(g=`${t.product}.${t.plan}`,h=g===this.selected);let b={type:p};this.paths.set(b,l),Q(t,"id")&&(b.id=t.id);let y={...M(t.style)};h&&Object.assign(y,M(M(t.states).selected)),Object.keys(y).length>0&&(b.style=this.style(y)),typeof t.animation=="object"&&t.animation!==null&&(b.animation=this.defaults(M(t.animation),this.objectFields("animation")));let m=this.packages[g||this.selected];switch(p){case"tabs":return this.tabs(t,b,l,g);case"switch":return this.switchOf(t,b,l,g,h);case"countdown":return this.countdown(t,b,l,g,h);case"purchase_button":{let v=typeof t.package=="string"?t.package:this.selected;b.package=v,this.open(v)&&(b.offer=this.offers.get(v));let A=this.component(M(t.content),`${l}.content`,v,h);return A?(b.content=A,b):null}case"package":b.product=t.product,b.plan=t.plan,b.selected=h,typeof t.offer=="string"&&(this.opts.offers??[]).includes(t.offer)&&(b.offer=t.offer)}for(let[v,A]of Object.entries(this.fields(p)??{})){if(p==="package"&&(v==="product"||v==="plan"||v==="selected"||v==="offer"))continue;let P=t[v],R=Q(t,v);switch(A.kind){case"component":{if(!R)continue;let x=this.component(M(P),`${l}.${v}`,g,h);if(!x&&A.required)return null;x&&(b[v]=x);break}case"components":{let x=[];I(P).forEach((T,O)=>{let V=this.component(M(T),`${l}.${v}[${O}]`,g,h);V&&x.push(V)}),b[v]=x;break}case"text":{let x=this.text(P,m);if(x!==null)b[v]=x;else if(A.required||p==="text"&&v==="text"&&R)return null;break}case"list":{let x=[];for(let T of I(P)){let O=this.item(A.item,M(T),m);O&&x.push(O)}if(p==="text"&&x.length===0&&R)return null;R&&(b[v]=x);break}case"object":{if(R){let x=this.object(M(P),A.item,m);if(x===null&&A.required)return null;b[v]=x}else v==="indicator"&&(b[v]=this.object({},A.item,m));break}case"value":{let x=this.value(X(P,A.def),A);x!=null&&x!==""&&(b[v]=x);break}}}return p==="text"&&this.typeStyle(b),b}typeStyle(t){if(typeof t.size!="string"){t.size!==void 0&&t.size!==null&&(t.text_style="body");return}let l=this.typography[t.size];for(let a of["font","weight","line_height","letter_spacing","text_style"])!Q(t,a)&&l?.[a]!==void 0&&l?.[a]!==null&&(t[a]=l[a]);t.size=l?.size??null}tabs(t,l,a,c){let p=this.tabShown(t,a);this.tabsShown[a]=p;let g=[];return I(t.tabs).forEach((h,b)=>{let y=M(h),m=y.id===p,v=this.component(M(y.label),`${a}.tabs[${b}].label`,c,m);if(g.push({id:y.id,selected:m,label:v}),m){let A=this.component(M(y.content),`${a}.tabs[${b}].content`,c,!1);A&&(l.content=A)}}),l.tabs=g,typeof t.bar=="object"&&t.bar!==null&&(l.bar=this.style(M(t.bar))),l}switchOf(t,l,a,c,p){let g=this.switchOn(t,a);this.switchesOn[a]=g,l.on=g;let h=this.text(t.label,this.packages[c||this.selected]);h!==null&&(l.label=h),l.tint=this.color(String(X(t.tint,"accent")));let b=g?"on":"off",y=this.component(M(t[b]),`${a}.${b}`,c,p);return y&&(l.content=y),l}countdown(t,l,a,c,p){let g=M(t.target),h=this.opts.now??Date.now(),b;if(typeof g.after_open_seconds=="number"?b=Math.trunc(g.after_open_seconds)-(this.opts.openedSecondsAgo??0):b=Math.trunc((Date.parse(String(g.at))-h)/1e3),b>0){l.state="counting",l.remaining_seconds=b,this.countdowns[a]=b;let y=this.packages,m={};for(let[A,P]of Object.entries(y))m[A]={...P,...Vt(b)};this.packages=m;let v=this.component(M(t.counting),`${a}.counting`,c,p);return v&&(l.content=v),this.packages=y,l}if(l.state="ended",l.remaining_seconds=0,typeof t.ended=="object"&&t.ended!==null){let y=this.component(M(t.ended),`${a}.ended`,c,p);y&&(l.content=y)}return l}item(t,l,a){let c={};for(let[p,g]of Object.entries(this.objectFields(t))){let h=l[p];if(g.kind==="text"){let b=this.text(h,a);if(b!==null)c[p]=b;else if(g.required)return null}else{let b=g.def,y=this.value(X(h,b),g);y!=null&&(Q(l,p)||b!=null&&b!=="")&&(c[p]=y)}}return c}object(t,l,a){if(l==="style")return this.style(t);let c=this.item(l,t,a)??{};if(l==="action")for(let p of["url","link"]){if(typeof c[p]!="string")continue;let g=qt(c[p],a);if(g===null)return null;c[p]=g}return c}defaults(t,l){let a={};for(let[c,p]of Object.entries(l)){let g=X(t[c],p.def);g!=null&&g!==""&&(a[c]=g)}return a}style(t){let l={};for(let[a,c]of Object.entries(t)){let p=this.objectFields("style")[a];if(!p){l[a]=c;continue}switch(p.kind){case"edges":l[a]=this.sides(c,Nt,this.spacing);break;case"corners":l[a]=this.sides(c,Dt,this.radii);break;case"fill":l[a]=this.fill(c);break;case"object":{let g=M(c),h={};for(let[b,y]of Object.entries(this.objectFields(p.item))){let m=X(g[b],y.def);m!=null&&m!==""&&(h[b]=this.value(m,y))}l[a]=h;break}default:l[a]=c}}return l}sides(t,l,a){let c={};for(let p of l){let g=typeof t=="object"&&t!==null?X(M(t)[p],0):t;c[p]=_e(g,a)}return c}fill(t){if(typeof t=="string")return{type:"color",color:this.color(t)};let l=M(t),a=this.defaults(l,this.objectFields(Ft[String(l.type)]??""));return Array.isArray(l.stops)&&(a.stops=l.stops.map(c=>({color:this.color(String(M(c).color)),at:M(c).at}))),a}value(t,l){if(l.kind!=="value")return t;switch(l.value){case"color":return typeof t=="string"&&t!==""?this.color(t):t;case"textColor":return typeof t=="string"?this.color(t):t==null?t:this.fill(t);case"spacing":return _e(t,this.spacing);case"radius":return _e(t,this.radii);default:return t}}color(t){let l=Object.hasOwn(this.palette,t)?this.palette[t]:void 0;return typeof l=="string"?l:t}text(t,l){let a;if(typeof t=="string")a=t;else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let p=t.t;a=typeof p=="string"&&Object.hasOwn(this.texts,p)?this.texts[p]:""}else return null;let c=!1;return a=a.replace(Ye,(p,g)=>{let h=l&&Object.hasOwn(l,g)?l[g]:void 0;return typeof h!="string"||h===""?(c=!0,""):h}),c||a.trim()===""?null:a}};function qt(d,t){let l=!1,a=d.replace(Ye,(c,p)=>{let g=t&&Object.hasOwn(t,p)?t[p]:void 0;return typeof g!="string"||g===""?(l=!0,""):It(g)});return l?null:a}function _e(d,t){return typeof d=="string"?Object.hasOwn(t,d)?t[d]:null:d}var Bt={packages:"Choose a plan",close:"Close",restore:"Restore purchases",page:(d,t)=>`${d} of ${t}`},ee={system:'-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',rounded:'ui-rounded, "SF Pro Rounded", Nunito, "Varela Round", system-ui, -apple-system, sans-serif',serif:'ui-serif, "New York", "Iowan Old Style", Georgia, "Times New Roman", serif',mono:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace'},Wt=1.35,Ze=20,Kt=new Set(["button","purchase_button","package","text"]),Gt=new Set(["ar","he","fa","ur","ps","yi","dv","ug","ku","sd"]),Qe={ease_out:"cubic-bezier(0.16, 1, 0.3, 1)",ease_in_out:"cubic-bezier(0.65, 0, 0.35, 1)",spring:"cubic-bezier(0.34, 1.56, 0.64, 1)"},Xt={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"},Yt={start:"flex-start",center:"center",end:"flex-end",space_between:"space-between",space_around:"space-around",space_evenly:"space-evenly"},Zt={stack:["children"],package:["children"],button:["content"],purchase_button:["content"],tabs:["tabs","content"],switch:["content"],carousel:["pages"],countdown:["content"]},Qt={package:["selected"],purchase_button:["package"],switch:["on"],countdown:["state","remaining_seconds"]},en=`
|
|
3
3
|
:host{display:block;height:100%}
|
|
4
4
|
.pw2{position:relative;box-sizing:border-box;display:flex;flex-direction:column;height:100%;overflow:hidden;font-family:${ee.system};font-size:1rem;line-height:1.3;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;text-rendering:optimizeLegibility}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as g,f as y,g as w}from"./
|
|
1
|
+
/*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as g,f as y,g as w}from"./TGQGGUE6.js";import"./A3I7H7QN.js";import"./D6NOE76D.js";import{pathToFileURL as z}from"node:url";import{z as c}from"zod";async function S(r){let l=new Map,t=new Map;for(let s of r){let o=`${s.className}.${s.method}`,i=t.get(s.className);if(i!==void 0&&i!==s.file)throw new Error(`two controllers are named ${s.className} (${i}, ${s.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(s.className,s.file),l.set(o,{returns:await x(s),throws:s.throws})}return s=>l.get(`${s.controller.name}.${s.fn}`)}async function x(r){let l=`${r.file} \u2014 ${r.className}.${r.method}`;switch(r.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let s=(await import(z(r.returns.file).href))[r.returns.exportName];if(!k(s))throw new Error(`${l}: its return type names ${r.returns.exportName}, which ${r.returns.file} exports as no schema (a zod, valibot or arktype schema)`);if(w(y(s)))throw new Error(`${l}: ${r.returns.exportName} marks an encrypted field (encrypted()) \u2014 an answer's is encrypt(value) in what the handler returns, its type Encrypted<T>, which the contract reads`);return{kind:"json",schema:s,array:r.returns.array}}case"expression":{let t=$(r.returns.expression,l);if(!k(t))throw new Error(`${l}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function $(r,l){let t=0,s=()=>{for(;t<r.length&&/\s/.test(r[t]);)t++},o=e=>{throw new Error(`${l}: invalid inferred return schema (${e}) at offset ${t}`)},i=e=>(s(),r.startsWith(e,t)?(t+=e.length,!0):!1),n=e=>{i(e)||o(`expected ${JSON.stringify(e)}`)},f=()=>{s(),r[t]!=='"'&&o("expected string literal");let e=t+1;for(;e<r.length;){let d=r[e];if(d==="\\"){e+=2;continue}if(d==='"'){let h=r.slice(t,e+1);return t=e+1,JSON.parse(h)}e++}return o("unterminated string literal")},p=()=>{if(s(),r[t]==='"')return f();if(r.startsWith("true",t)&&!/[A-Za-z0-9_$]/.test(r[t+4]??""))return t+=4,!0;if(r.startsWith("false",t)&&!/[A-Za-z0-9_$]/.test(r[t+5]??""))return t+=5,!1;let e=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(r.slice(t));return e?(t+=e[0].length,Number(e[0])):o("expected literal value")},u=()=>{s();let e;if(i("encrypted(")){let d=u();n(")"),e=g(d)}else if(i("z.")){let d=t;for(;t<r.length&&/[A-Za-z0-9_]/.test(r[t]);)t++;let h=r.slice(d,t);switch(n("("),h){case"string":n(")"),e=c.string();break;case"number":n(")"),e=c.number();break;case"boolean":n(")"),e=c.boolean();break;case"null":n(")"),e=c.null();break;case"undefined":n(")"),e=c.undefined();break;case"literal":{let a=p();n(")"),e=c.literal(a);break}case"array":{let a=u();n(")"),e=c.array(a);break}case"union":{n("[");let a=[];if(!i("]")){do a.push(u());while(i(","));n("]")}n(")"),a.length<2&&o("z.union requires at least two alternatives"),e=c.union(a);break}case"record":{let a=u();n(",");let m=u();n(")"),e=c.record(a,m);break}case"object":{n("{");let a={};if(!i("}")){do{let m=f();n(":"),a[m]=u()}while(i(","));n("}")}n(")"),e=c.object(a);break}default:return o(`unsupported z.${h}`)}}else return o("expected z.* or encrypted(...)");for(;i(".");){let d=t;for(;t<r.length&&/[A-Za-z0-9_]/.test(r[t]);)t++;let h=r.slice(d,t);switch(n("("),h){case"strict":n(")"),e=e.strict();break;case"nullable":n(")"),e=e.nullable();break;case"optional":n(")"),e=e.optional();break;case"length":{let a=p();if(typeof a!="number"||!Number.isInteger(a)||a<0)return o("expected non-negative integer for .length()");n(")"),e=e.length(a);break}case"regex":{n("new RegExp(");let a=f();n(")"),n(")"),e=e.regex(new RegExp(a));break}default:return o(`unsupported modifier .${h}()`)}}return e},b=u();return s(),t!==r.length&&o("unexpected trailing tokens"),b}function k(r){return typeof r=="object"&&r!==null&&typeof r["~standard"]?.validate=="function"}export{S as routeContracts};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.76.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.
|
|
1
|
+
/*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
function o(){let n=globalThis;if(typeof n.document<"u"||n.navigator?.product==="ReactNative")return!0;let t=n.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}export{o as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{g as m}from"./
|
|
1
|
+
/*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{g as m}from"./YRYPXVAJ.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
|
|
3
3
|
`):process.stdout.write(`${o}
|
|
4
4
|
`)}function k(n){try{return JSON.stringify(n)}catch{let e=new WeakSet;try{return JSON.stringify(n,(s,t)=>{if(typeof t=="bigint")return t.toString();if(typeof t=="object"&&t!==null){if(e.has(t))return"[circular]";e.add(t)}return t})}catch{return JSON.stringify({time:n.time,level:n.level,msg:n.msg,request_id:n.request_id,unwritable:"a field of this line could not be written"})}}}var v=h("Log",{debug:(n,e)=>l("debug",n,e),info:(n,e)=>l("info",n,e),warn:(n,e)=>l("warn",n,e),error:(n,e)=>l("error",n,e)});var L=512,_=8,q=64,D=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,S={"i-klingon":"tlh","en-gb-oed":"en-GB-oxendict","sgn-be-fr":"sfb","zh-cmn-hans":"cmn-Hans","zh-yue":"yue","hy-arevela":"hy-arevela"};function $(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function j(n){let e=n.split("-"),s=(e[0]??"").toLowerCase();return s==="mo"&&e.length===1?"ro-MD":s==="tl"?(e[0]="fil",e.join("-")):s==="sh"?(e[0]="sr",e.length>1&&/^[A-Za-z]{4}$/.test(e[1]??"")||e.splice(1,0,"Latn"),e.join("-")):n}function I(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>q)return;let s=e.toLowerCase(),t=Object.hasOwn(S,s)?S[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales(j(e))[0]}catch{return}if(t===void 0)return}let i=$(t);if(!(i===""||i==="und"||i==="mul"))return t}function z(n){let e=n.split("-"),s=e.findIndex((r,a)=>a>0&&r.length===1),t=s>0?e.slice(0,s):e,i=[],o=r=>{i.includes(r)||i.push(r)};for(let r=t.length;r>1||r===t.length;r--)o(t.slice(0,r).join("-"));if(!t.slice(1).some(r=>/^[A-Za-z]{4}$/.test(r)))try{let r=new Intl.Locale(t.join("-")).maximize().script;r&&o(`${t[0]}-${r}`)}catch{}return o(t[0]),i}function Y(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=L){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,f=r.indexOf(";");if(f>=0){let A=r.slice(f+1);r=r.slice(0,f).trim();for(let p of A.split(";")){let b=p.indexOf("=");if(b<0||p.slice(0,b).trim().toLowerCase()!=="q")continue;let y=p.slice(b+1).trim(),g=D.test(y)?Number(y):Number.NaN;a=Number.isFinite(g)&&g>=0&&g<=1?g:0}}a>0&&i.push({tag:r,q:a,at:i.length})}i.sort((o,r)=>r.q-o.q||o.at-r.at);for(let{tag:o}of i.slice(0,_)){let r=I(o);if(r!==void 0)for(let a of z(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function N(n,e,s){let t=n.strings??{},i=Object.hasOwn(t,e)?t[e]:null;for(let o of s){if(o===n.source)break;let r=i!=null&&Object.hasOwn(i,o)?i[o]:void 0;if(typeof r=="string"&&r!=="")return{text:r,locale:o}}return{text:e,locale:n.source}}var C=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function x(n,e){return n.replace(C,(s,t,i,o)=>{if(o[i-1]==="{"||o[i+s.length]==="}")return s;let r=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return r==null?"":String(r)})}var u;function W(n){u=n===void 0?void 0:{root:n,said:!1}}function Q(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,v.warn(`[palbase] t(): the app has no palbase/strings (looked in ${u.root}) \u2014 every sentence is said as it is written. \`npx palbase strings\` starts the table; an image takes it with COPY palbase ./palbase`)),x(n,e);let{text:i,locale:o}=N(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),x(i,e)}export{h as a,R as b,c,H as d,F as e,Z as f,B as g,v as h,Y as i,W as j,Q as k};
|