palbase 0.51.3 → 0.51.4
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/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/{6XXOZPW6.js → 232EZENF.js} +1 -1
- package/dist/chunks/{3ZRVUUO2.js → 2HO42W3S.js} +2 -2
- package/dist/chunks/{XTBIS6QR.js → 35NHGNIS.js} +2 -2
- package/dist/chunks/{UDNL3GYZ.js → 3BI6IQB2.js} +2 -2
- package/dist/chunks/{SD2A2WYF.js → 3VLWKSDI.js} +1 -1
- package/dist/chunks/{QEADIYP6.js → 66NBUMMO.js} +2 -2
- package/dist/chunks/{MO2IFBQX.js → BLSK67RS.js} +2 -2
- package/dist/chunks/{SYTF5ALJ.js → BVIBVRVN.js} +2 -2
- package/dist/chunks/{FJ2Y76ZA.js → D5AC4SYT.js} +2 -2
- package/dist/chunks/{PI7RQUMT.js → D5SLQUY6.js} +2 -2
- package/dist/chunks/{3NZELVU2.js → E2MJDUL2.js} +1 -1
- package/dist/chunks/{R3ARXIXD.js → EHAREIHA.js} +2 -2
- package/dist/chunks/{MHKAJ3QD.js → F6IOQH2K.js} +2 -2
- package/dist/chunks/{FIE4XLWI.js → HMBUUER2.js} +1 -1
- package/dist/chunks/{ABXRIH3L.js → IEJNSFS3.js} +2 -2
- package/dist/chunks/{TTIULHFF.js → JFOZKWRS.js} +2 -2
- package/dist/chunks/{BBDBOJEN.js → NL3A2IOP.js} +2 -2
- package/dist/chunks/NYRKHBWH.js +13 -0
- package/dist/chunks/{XK6RNDF2.js → QZMDY3ER.js} +1 -1
- package/dist/chunks/{XDNICHGM.js → T4KR4WI4.js} +2 -2
- package/dist/chunks/{DCFNOFKH.js → TVVDCRRV.js} +1 -1
- package/dist/chunks/{FNAMFVVE.js → YBKARQSU.js} +1 -1
- package/dist/chunks/{CPHSKADK.js → ZJJWIZAK.js} +2 -2
- package/dist/cli.js +2 -2
- package/dist/cloud/index.js +2 -2
- 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/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/web/src/chat.d.ts +7 -1
- package/dist/chunks/ZSDUZ3UQ.js +0 -13
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.51.
|
|
2
|
-
import{a as s,f as a,g as i}from"./
|
|
1
|
+
/*! palbase 0.51.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as s,f as a,g as i}from"./3BI6IQB2.js";import"./3VLWKSDI.js";import"./QZMDY3ER.js";import{pathToFileURL as m}from"node:url";import{z as u}from"zod";async function w(e){let t=new Map,n=new Map;for(let r of e){let d=`${r.className}.${r.method}`,o=n.get(r.className);if(o!==void 0&&o!==r.file)throw new Error(`two controllers are named ${r.className} (${o}, ${r.file}): the contract tells routes apart by their class's name \u2014 rename one`);n.set(r.className,r.file),t.set(d,{returns:await h(r),throws:r.throws})}return r=>t.get(`${r.controller.name}.${r.fn}`)}async function h(e){let t=`${e.file} \u2014 ${e.className}.${e.method}`;switch(e.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let r=(await import(m(e.returns.file).href))[e.returns.exportName];if(!c(r))throw new Error(`${t}: its return type names ${e.returns.exportName}, which ${e.returns.file} exports as no schema (a zod, valibot or arktype schema)`);if(i(a(r)))throw new Error(`${t}: ${e.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:r,array:e.returns.array}}case"expression":{let n=new Function("z","encrypted",`return (${e.returns.expression});`)(u,s);if(!c(n))throw new Error(`${t}: the schema made of its return type is not one`);return{kind:"json",schema:n,array:!1}}}}function c(e){return typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function"}export{w as routeContracts};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.51.
|
|
2
|
-
import{b as R}from"./3NZELVU2.js";import{a as m,c as G,d as X,e as Z,f as Q,h as ee,i as te,j as A,k as ne,l as re,o as P}from"./SD2A2WYF.js";import{a as se}from"./FIE4XLWI.js";import{a as U,b as C,c as L,d as $,e as N,f as I,h as F,i as D,j as W,k as B,l as H,m as q,n as z,o as V}from"./ABXRIH3L.js";import{a as J,b as Y}from"./R3ARXIXD.js";import{b as T,d as v}from"./3ZRVUUO2.js";var f=class extends Error{status=400;code;data;constructor(e,t,r={}){super(t),this.name="TransitRefusal",this.code=e,this.data=r}},Te=6e4,Ae=1e3;function x(n){return/^t[1-9][0-9]{0,5}$/.test(n)?Number(n.slice(1)):0}var k=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(t=>new Promise(r=>setTimeout(r,t)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Te),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let t=this.now();try{let r=await this.opts.fetch(e),s=new Map;for(let i of r.keys){let o=X(i.key);s.set(i.id,{privateKey:o,publicKey:this.keys.get(i.id)?.publicKey??await Z(o)})}this.keys=s,this.order=r.keys.map(i=>i.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=t}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(x),...[...this.retired].map(x))}async key(e){let t=this.now();for(;x(e)>this.newest()&&this.heldFrom<t;){let i=this.fetchedAt+Ae-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let r=this.keys.get(e),s=this.current();if(this.retired.has(e))throw new f("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:s});if(r===void 0)throw new f("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:s});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new f("encryption_required",`this route carries encrypted fields: the request names its key in ${m}`,{field:m,current:this.current()});let t;try{t=ee(e.header).kid}catch{throw new f("encryption_unopenable",`${m} is not one`,{field:m})}let r=await this.key(t),s;try{s=Q(this.projectId,e.method,e.path,e.params??[])}catch{throw new f("encryption_unopenable","the request's path holds a value no key is sealed for",{field:m})}try{return new S(t,await te(e.header,r.privateKey,r.publicKey,s))}catch(i){throw i instanceof G?new f("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:m}):i}}},S=class{kid;key;constructor(e,t){this.kid=e,this.key=t}async open(e,t,r){return P(e,t,r,async(s,i)=>{if(!ne(i))throw new f("encryption_required",`${s} is an encrypted field: it came plain`,{field:s});try{return await re(this.key,s,i)}catch{throw new f("encryption_unopenable",`${s} does not open: changed, moved from another field, or another request's`,{field:s})}})}async seal(e,t){return P(e,"/response",t,(r,s)=>A(this.key,r,s))}sealField(e,t){return A(this.key,e,t)}};var Pe=/^pb_[a-z0-9]+_s/;function O(n){if(se())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!Pe.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=Y(v({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??J),t=q.client(e);return{ai:U.client(e),analytics:C.client(e),auth:L.client(e),cache:$.client(e),calls:N.client(e),fields:new R({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:I.client(e),machines:F.client(e),messaging:D.client(e),notify:W.client(e),purchases:B.client(e),realtime:H.client(e),secrets:t,storage:z.client(e),stores:V.client(e),transit:new k({fetch:async r=>(await t.getTransitKeys({signal:r})).data}),transport:e,url:new URL(n.url).origin}}var h=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},xe=300,Oe=/^[0-9]{1,12}$/,je=/^[0-9a-f]{64}$/,ie=8,Me=/^whsec_[0-9A-Za-z]{32,}$/,Ke=1024*1024;async function oe(n){if(typeof n.secret!="string"||!Me.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await ae(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(de(n.body)))}catch{throw new h("invalid_body","the signed body is not JSON")}if(!Ie(e))throw new h("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function ae(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=de(n.body),{t,v1:r}=ce(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",s,Ne(new TextEncoder().encode(`${t}.`),e))),o=!1;for(let d of r)$e(i,Le(d))&&(o=!0);if(!o)throw new h("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function ce(n){let e=n.toleranceSeconds??xe;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new h("missing_signature","the request carries no Palbase-Signature header");let s,i=[];for(let o of r.split(",")){let d=o.indexOf("=");if(d<=0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=o.slice(0,d).trim(),a=o.slice(d+1).trim();if(c==="t"){if(s!==void 0||!Oe.test(a))throw new h("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=a}else if(c==="v1"){if(!je.test(a))throw new h("malformed_signature","a v1 is 64 lowercase hex characters");if(i.length===ie)throw new h("malformed_signature",`Palbase-Signature carries at most ${ie} v1`);i.push(a)}}if(s===void 0||i.length===0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new h("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:i}}async function Ue(n,e,t={}){let r=await Ce(n,t.maxBytes??Ke);return oe({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function Ce(n,e){let t=()=>new h("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),i=[],o=0;for(;;){let{done:a,value:u}=await s.read();if(a)break;if(o+=u.byteLength,o>e)throw await s.cancel().catch(()=>{}),t();i.push(u)}let d=new Uint8Array(o),c=0;for(let a of i)d.set(a,c),c+=a.byteLength;return d}function de(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function Le(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function $e(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function Ne(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function Ie(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var le=60,Fe=60,De=8*1024,We=1e5;function j(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fe(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function ue(n){let e=fe(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var E=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=We){this.max=e}spend(e,t){if(t>=e.until)throw new l("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new l("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,i]of t){if(i>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[i,o]of s)o>e||(s.delete(i),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function Be(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function he(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function pe(n,e,t,r){let s=_e=>{throw new l("proof",`the DPoP proof is not taken: ${_e}`)},i=t.proof;if(!i)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(i.length>De)return s("it is too long");let o=i.split(".");if(o.length!==3)return s("it is not a JWS of three parts");let d=ue(o[0]),c=ue(o[1]);if(!d||!c)return s("its header or claims are not base64url JSON");if(d.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(d.alg!=="ES256")return s(`it is signed with ${String(d.alg)}; only ES256 is taken`);let a=d.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return s("its header carries no P-256 public key");if("d"in a)return s("its header carries a private key");if(await Be(a.x,a.y)!==e)return s("it is signed by a key the token does not name");let u;try{u=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let y=fe(o[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},u,y,new TextEncoder().encode(`${o[0]}.${o[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let p=typeof c.htu=="string"?he(c.htu):void 0,g=he(t.url);if(!p||!g||p!==g)return s(`it is for ${String(c.htu)}, not ${g??t.url}`);let ve=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-ve)>le)return s("it was not made within a minute of now");let Se=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==Se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let Ee=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:Ee,until:(c.iat+le+Fe)*1e3+1}}var l=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},w=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},He=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function qe(n){return async e=>{let t=v({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof T&&r.status===401&&!He.has(r.code))return!1;throw new w("a session's standing could not be told",{cause:r})}}}var M={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},ye=60,ze=16*1024,Ve=10*6e4,Je=5e4,ge=n=>typeof n=="string"&&Object.hasOwn(M,n),K=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new E;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>ze)throw new l("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new l("malformed","the token is not a JWS of three parts");let s=me(r[0]),i=me(r[1]);if(!s||!i)throw new l("malformed","the token header or claims are not base64url JSON");let o=s.alg;if(!ge(o))throw new l("algorithm",`the token is signed with ${String(o)}; only ES256 and PS256 are taken`);let d=s.kid;if(typeof d!="string"||d==="")throw new l("malformed","the token header names no kid");let c=await this.key(d);if(!c)throw new l("unknown_key",`no key ${d} in the project's key set`);if(c.alg!==o)throw new l("algorithm",`key ${d} is ${c.alg}, the token says ${o}`);let a=be(r[2]);if(!a)throw new l("malformed","the signature is not base64url");let u=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(M[c.alg].verify,c.key,a,u).catch(()=>!1))throw new l("signature","the signature does not verify");let b=this.check(i),p=i.cnf,g;if(p!==void 0){if(!t)throw new l("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof p!="object"||p===null||typeof p.jkt!="string"||p.jkt==="")throw new l("bound","the token is bound to a key it does not name (cnf.jkt)");g=await pe(e,p.jkt,t,this.now())}else if(t)throw new l("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,b.sessionId))throw new l("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return g&&this.seenProofs.spend(g,this.now()),b}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:Ge(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new l("malformed","the Authorization header is not a Bearer or DPoP token");let i=s[1].toLowerCase()==="dpop",o=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],i?{proof:t.get("dpop"),method:e.method,url:we(t,o)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let i=this.asking.get(t);i||(i=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,i));let o;try{o=await i}catch(c){let a=this.standings.get(t),u=this.now();if(a&&u<a.at+this.standingStaleMs)return a.until=Math.min(u+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new w("a session's standing cannot be read now",{cause:c})}let d=this.now();return this.standings.delete(t),this.standings.set(t,{live:o,at:d,until:d+this.standingTtlMs}),this.standings.size>Je&&this.standings.delete(this.standings.keys().next().value),o}check(e){if(e.iss!==this.issuer)throw new l("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 l("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new l("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+ye<=r)throw new l("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-ye>r))throw new l("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new l("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new l("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new l("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Ve;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new w("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(i){if(!s)throw i}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(i){throw this.lastFailure=i,new w("the project's key set cannot be read now",{cause:i})}this.lastFailure=void 0;let r=new Map;for(let i of Array.isArray(e.keys)?e.keys:[]){let o=i.alg;if(typeof i.kid!="string"||!ge(o))continue;let d=M[o];if(i.kty!==d.kty||i.use!==void 0&&i.use!=="sig")continue;let{d:c,...a}=i;try{r.set(i.kid,{alg:o,key:await crypto.subtle.importKey("jwk",a,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Xe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function we(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Ye.test(s)?`${r}://${s}${e.pathname}`:""}var Ye=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function Ge(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Xe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function be(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function me(n){let e=be(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Ze(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var _=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Qe(n,e,t,r){let{idempotencyKey:s,amount:i,ttlSeconds:o,metadata:d}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:i,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...o!==void 0?{ttl_seconds:o}:{},...d!==void 0?{metadata:d}:{}},a=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(a.status!=="held")throw new _(a);let u={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(b){throw await n.purchases.releaseSpend({path:u}).catch(()=>{}),b}return await n.purchases.commitSpend({path:u}),y}async function*et(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,nt=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function ke(n){return!tt.test(n)||nt.test(n)||/_PROXY$/i.test(n)}var rt=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function st(n){return rt.test(n)}async function it(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t==="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(t!=="development")throw new TypeError(`PALBASE_SECRETS is development, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let i=O({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:o}=await i.secrets.getEnvironmentValues({path:{environment:t}}),d=[],c=[],a=[];for(let[u,y]of Object.entries(o.values)){if(ke(u)){a.push(u);continue}if(e[u]!==void 0&&e[u]!==""){c.push(u);continue}e[u]=y,d.push(u)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:a.sort()}}export{f as a,k as b,S as c,O as d,h as e,oe as f,ae as g,ce as h,Ue as i,l as j,w as k,qe as l,K as m,we as n,Ze as o,_ as p,Qe as q,et as r,ke as s,st as t,it as u};
|
|
1
|
+
/*! palbase 0.51.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as R}from"./E2MJDUL2.js";import{a as m,c as G,d as X,e as Z,f as Q,h as ee,i as te,j as A,k as ne,l as re,o as P}from"./3VLWKSDI.js";import{a as se}from"./HMBUUER2.js";import{a as U,b as C,c as L,d as $,e as N,f as I,h as F,i as D,j as W,k as B,l as H,m as q,n as z,o as V}from"./IEJNSFS3.js";import{a as J,b as Y}from"./EHAREIHA.js";import{b as T,d as v}from"./2HO42W3S.js";var f=class extends Error{status=400;code;data;constructor(e,t,r={}){super(t),this.name="TransitRefusal",this.code=e,this.data=r}},Te=6e4,Ae=1e3;function x(n){return/^t[1-9][0-9]{0,5}$/.test(n)?Number(n.slice(1)):0}var k=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(t=>new Promise(r=>setTimeout(r,t)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Te),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let t=this.now();try{let r=await this.opts.fetch(e),s=new Map;for(let i of r.keys){let o=X(i.key);s.set(i.id,{privateKey:o,publicKey:this.keys.get(i.id)?.publicKey??await Z(o)})}this.keys=s,this.order=r.keys.map(i=>i.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=t}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(x),...[...this.retired].map(x))}async key(e){let t=this.now();for(;x(e)>this.newest()&&this.heldFrom<t;){let i=this.fetchedAt+Ae-this.now();if(i>0){await this.sleep(i);continue}await this.refresh()}let r=this.keys.get(e),s=this.current();if(this.retired.has(e))throw new f("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:s});if(r===void 0)throw new f("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:s});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new f("encryption_required",`this route carries encrypted fields: the request names its key in ${m}`,{field:m,current:this.current()});let t;try{t=ee(e.header).kid}catch{throw new f("encryption_unopenable",`${m} is not one`,{field:m})}let r=await this.key(t),s;try{s=Q(this.projectId,e.method,e.path,e.params??[])}catch{throw new f("encryption_unopenable","the request's path holds a value no key is sealed for",{field:m})}try{return new S(t,await te(e.header,r.privateKey,r.publicKey,s))}catch(i){throw i instanceof G?new f("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:m}):i}}},S=class{kid;key;constructor(e,t){this.kid=e,this.key=t}async open(e,t,r){return P(e,t,r,async(s,i)=>{if(!ne(i))throw new f("encryption_required",`${s} is an encrypted field: it came plain`,{field:s});try{return await re(this.key,s,i)}catch{throw new f("encryption_unopenable",`${s} does not open: changed, moved from another field, or another request's`,{field:s})}})}async seal(e,t){return P(e,"/response",t,(r,s)=>A(this.key,r,s))}sealField(e,t){return A(this.key,e,t)}};var Pe=/^pb_[a-z0-9]+_s/;function O(n){if(se())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!Pe.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=Y(v({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??J),t=q.client(e);return{ai:U.client(e),analytics:C.client(e),auth:L.client(e),cache:$.client(e),calls:N.client(e),fields:new R({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:I.client(e),machines:F.client(e),messaging:D.client(e),notify:W.client(e),purchases:B.client(e),realtime:H.client(e),secrets:t,storage:z.client(e),stores:V.client(e),transit:new k({fetch:async r=>(await t.getTransitKeys({signal:r})).data}),transport:e,url:new URL(n.url).origin}}var h=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},xe=300,Oe=/^[0-9]{1,12}$/,je=/^[0-9a-f]{64}$/,ie=8,Me=/^whsec_[0-9A-Za-z]{32,}$/,Ke=1024*1024;async function oe(n){if(typeof n.secret!="string"||!Me.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await ae(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(de(n.body)))}catch{throw new h("invalid_body","the signed body is not JSON")}if(!Ie(e))throw new h("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function ae(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=de(n.body),{t,v1:r}=ce(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=new Uint8Array(await crypto.subtle.sign("HMAC",s,Ne(new TextEncoder().encode(`${t}.`),e))),o=!1;for(let d of r)$e(i,Le(d))&&(o=!0);if(!o)throw new h("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function ce(n){let e=n.toleranceSeconds??xe;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new h("missing_signature","the request carries no Palbase-Signature header");let s,i=[];for(let o of r.split(",")){let d=o.indexOf("=");if(d<=0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=o.slice(0,d).trim(),a=o.slice(d+1).trim();if(c==="t"){if(s!==void 0||!Oe.test(a))throw new h("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=a}else if(c==="v1"){if(!je.test(a))throw new h("malformed_signature","a v1 is 64 lowercase hex characters");if(i.length===ie)throw new h("malformed_signature",`Palbase-Signature carries at most ${ie} v1`);i.push(a)}}if(s===void 0||i.length===0)throw new h("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new h("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:i}}async function Ue(n,e,t={}){let r=await Ce(n,t.maxBytes??Ke);return oe({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function Ce(n,e){let t=()=>new h("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),i=[],o=0;for(;;){let{done:a,value:u}=await s.read();if(a)break;if(o+=u.byteLength,o>e)throw await s.cancel().catch(()=>{}),t();i.push(u)}let d=new Uint8Array(o),c=0;for(let a of i)d.set(a,c),c+=a.byteLength;return d}function de(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function Le(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function $e(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function Ne(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function Ie(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var le=60,Fe=60,De=8*1024,We=1e5;function j(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function fe(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function ue(n){let e=fe(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var E=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=We){this.max=e}spend(e,t){if(t>=e.until)throw new l("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new l("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,i]of t){if(i>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[i,o]of s)o>e||(s.delete(i),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function Be(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function he(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function pe(n,e,t,r){let s=_e=>{throw new l("proof",`the DPoP proof is not taken: ${_e}`)},i=t.proof;if(!i)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(i.length>De)return s("it is too long");let o=i.split(".");if(o.length!==3)return s("it is not a JWS of three parts");let d=ue(o[0]),c=ue(o[1]);if(!d||!c)return s("its header or claims are not base64url JSON");if(d.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(d.alg!=="ES256")return s(`it is signed with ${String(d.alg)}; only ES256 is taken`);let a=d.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return s("its header carries no P-256 public key");if("d"in a)return s("its header carries a private key");if(await Be(a.x,a.y)!==e)return s("it is signed by a key the token does not name");let u;try{u=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let y=fe(o[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},u,y,new TextEncoder().encode(`${o[0]}.${o[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let p=typeof c.htu=="string"?he(c.htu):void 0,g=he(t.url);if(!p||!g||p!==g)return s(`it is for ${String(c.htu)}, not ${g??t.url}`);let ve=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-ve)>le)return s("it was not made within a minute of now");let Se=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==Se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let Ee=j(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:Ee,until:(c.iat+le+Fe)*1e3+1}}var l=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},w=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},He=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function qe(n){return async e=>{let t=v({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof T&&r.status===401&&!He.has(r.code))return!1;throw new w("a session's standing could not be told",{cause:r})}}}var M={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},ye=60,ze=16*1024,Ve=10*6e4,Je=5e4,ge=n=>typeof n=="string"&&Object.hasOwn(M,n),K=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new E;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>ze)throw new l("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new l("malformed","the token is not a JWS of three parts");let s=me(r[0]),i=me(r[1]);if(!s||!i)throw new l("malformed","the token header or claims are not base64url JSON");let o=s.alg;if(!ge(o))throw new l("algorithm",`the token is signed with ${String(o)}; only ES256 and PS256 are taken`);let d=s.kid;if(typeof d!="string"||d==="")throw new l("malformed","the token header names no kid");let c=await this.key(d);if(!c)throw new l("unknown_key",`no key ${d} in the project's key set`);if(c.alg!==o)throw new l("algorithm",`key ${d} is ${c.alg}, the token says ${o}`);let a=be(r[2]);if(!a)throw new l("malformed","the signature is not base64url");let u=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(M[c.alg].verify,c.key,a,u).catch(()=>!1))throw new l("signature","the signature does not verify");let b=this.check(i),p=i.cnf,g;if(p!==void 0){if(!t)throw new l("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof p!="object"||p===null||typeof p.jkt!="string"||p.jkt==="")throw new l("bound","the token is bound to a key it does not name (cnf.jkt)");g=await pe(e,p.jkt,t,this.now())}else if(t)throw new l("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,b.sessionId))throw new l("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return g&&this.seenProofs.spend(g,this.now()),b}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:Ge(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new l("malformed","the Authorization header is not a Bearer or DPoP token");let i=s[1].toLowerCase()==="dpop",o=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],i?{proof:t.get("dpop"),method:e.method,url:we(t,o)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let i=this.asking.get(t);i||(i=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,i));let o;try{o=await i}catch(c){let a=this.standings.get(t),u=this.now();if(a&&u<a.at+this.standingStaleMs)return a.until=Math.min(u+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new w("a session's standing cannot be read now",{cause:c})}let d=this.now();return this.standings.delete(t),this.standings.set(t,{live:o,at:d,until:d+this.standingTtlMs}),this.standings.size>Je&&this.standings.delete(this.standings.keys().next().value),o}check(e){if(e.iss!==this.issuer)throw new l("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 l("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new l("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+ye<=r)throw new l("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-ye>r))throw new l("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new l("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new l("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new l("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Ve;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new w("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(i){if(!s)throw i}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(i){throw this.lastFailure=i,new w("the project's key set cannot be read now",{cause:i})}this.lastFailure=void 0;let r=new Map;for(let i of Array.isArray(e.keys)?e.keys:[]){let o=i.alg;if(typeof i.kid!="string"||!ge(o))continue;let d=M[o];if(i.kty!==d.kty||i.use!==void 0&&i.use!=="sig")continue;let{d:c,...a}=i;try{r.set(i.kid,{alg:o,key:await crypto.subtle.importKey("jwk",a,d.import,!1,["verify"])})}catch{}}this.keys=r;let s=Xe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function we(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Ye.test(s)?`${r}://${s}${e.pathname}`:""}var Ye=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function Ge(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Xe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function be(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function me(n){let e=be(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Ze(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var _=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Qe(n,e,t,r){let{idempotencyKey:s,amount:i,ttlSeconds:o,metadata:d}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:i,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...o!==void 0?{ttl_seconds:o}:{},...d!==void 0?{metadata:d}:{}},a=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(a.status!=="held")throw new _(a);let u={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(b){throw await n.purchases.releaseSpend({path:u}).catch(()=>{}),b}return await n.purchases.commitSpend({path:u}),y}async function*et(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var tt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,nt=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function ke(n){return!tt.test(n)||nt.test(n)||/_PROXY$/i.test(n)}var rt=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function st(n){return rt.test(n)}async function it(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t==="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(t!=="development")throw new TypeError(`PALBASE_SECRETS is development, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let i=O({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:o}=await i.secrets.getEnvironmentValues({path:{environment:t}}),d=[],c=[],a=[];for(let[u,y]of Object.entries(o.values)){if(ke(u)){a.push(u);continue}if(e[u]!==void 0&&e[u]!==""){c.push(u);continue}e[u]=y,d.push(u)}return{set:t,loaded:d.sort(),kept:c.sort(),refused:a.sort()}}export{f as a,k as b,S as c,O as d,h as e,oe as f,ae as g,ce as h,Ue as i,l as j,w as k,qe as l,K as m,we as n,Ze as o,_ as p,Qe as q,et as r,ke as s,st as t,it as u};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/*! palbase 0.51.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as q,c as I,d as C}from"./35NHGNIS.js";import{a as Y,f as Z,g as X,j as ee,k as te,l as ne,o as N,p as se,q as re}from"./3VLWKSDI.js";import{d as G}from"./EHAREIHA.js";import{a as k,b as Q,c as E,e as A}from"./2HO42W3S.js";var p=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function ae(t){return t instanceof p||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function D(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??Fe(e,"request_id"),data:_(e,"data"),cause:t};if(t.code==="network_error")return new p("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new p("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new p("attestationRequired",n);if(t.status===401)return new p("unauthorized",n);if(t.status===429)return new p("rateLimited",{...n,retryAfter:Ke(e)??t.retryAfter});let s=Be(e);return t.status===400&&s?new p("validation",{...n,fields:s}):new p("server",n)}function P(t){return t instanceof Q||t instanceof Error&&t.name==="PalbaseError"}function oe(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Be(t){let e=_(_(t,"data"),"fields");if(oe(e))return e;let n=_(t,"fields");return oe(n)?n:void 0}function Ke(t){return ie(t,"retry_after")??ie(_(t,"data"),"retryAfter")}function _(t,e){if(typeof t=="object"&&t!==null)return t[e]}function ie(t,e){let n=_(t,e);return typeof n=="number"?n:void 0}function Fe(t,e){let n=_(t,e);return typeof n=="string"?n:void 0}var Le=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Je=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),We=new Set(Je),He=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function $(t){return t==="then"||t==="toJSON"||He.has(t)}function de(t){return t==="call"||t==="join"||$(t)}function le(t){return typeof t=="string"&&Le.test(t)&&!We.has(t)&&!$(t)}function ue(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function ce(t){A(t)}function pe(t){return A(t).origin}var O=class t{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];heldTimer;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},n,s,r=!0){this.me=e,this.reader=n,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 n=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,a={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...n!==void 0?{turns:n}:{},...e.signal?{signal:e.signal}:{}},d;if(e.load)d=await e.load(a);else{let h=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");d=await this.reader.parts(h,a)}if(this.ended)return!1;let u=(d?.parts??[]).map(h=>q(h)).filter(h=>h!==void 0);if(this.olderCursor=d?.nextCursor,this.olderLeft=typeof d?.nextCursor=="string"&&d.nextCursor!=="",this.before(u),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0&&(this.racing=!0),n===void 0||typeof d?.turns!="number"||s!==void 0&&this.olderCursor===s)break;n-=d.turns}while(n>0);return this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let c=S(i);c<=0||(this.paged.add(c),(this.pagedFrom===void 0||c<this.pagedFrom)&&(this.pagedFrom=c),(this.pagedTo===void 0||c>this.pagedTo)&&(this.pagedTo=c))}let n=new t(this.me);n.thoughts=this.thoughts,n.lowest=this.lowest-e.length;let s=n.lowest;for(let i of e)n.at=s++,n.fold(i);this.folded+=n.folded,this.lowest=n.lowest,this.chatId??=n.chatId;let r=new Map;for(let[i,c]of n.messages){let y=this.told.get(i)??[],f=c;if(y.length>0)for(let x of y)f=fe(f,x);else f=this.messages.get(i)??c;r.set(i,f);let m=[...n.told.get(i)??[],...y];m.length>0&&this.told.set(i,m)}for(let[i,c]of this.messages)r.has(i)||r.set(i,c);this.messages.clear();for(let[i,c]of r)this.messages.set(i,c);let o=new Map;for(let[i,c]of n.responses){let y=this.responses.get(i);o.set(i,y?ze(c,y):c)}for(let[i,c]of this.responses)o.has(i)||o.set(i,c);this.responses.clear();for(let[i,c]of o)this.responses.set(i,c);let a=new Set;for(let i of n.order)(i.type==="message"||i.type==="response")&&a.add(`${i.type}\0${i.key}`);let d=[...n.order],u=new Set([...n.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&a.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&n.goalWords.has(i.event.seq))&&!(i.type==="voice"&&n.voiceWords.has(K(i.event)))){if(i.type==="message"&&i.began&&i.turn!==null){let c=this.responses.get(i.turn);u.has(i.turn)?d.push({...i,began:!1,at:i.arrived}):d.push({...i,at:c&&c.at<i.arrived?c.at-.5:i.arrived});continue}d.push(i)}d.sort((i,c)=>i.at-c.at),this.order=d;for(let i of n.goalWords)this.goalWords.add(i);this.goal=null;for(let i of d)i.type==="goal"&&this.goalSaid(i.event);for(let i of n.voiceWords)this.voiceWords.add(i);let h=new Set;this.voice=null;for(let i of d)i.type==="voice"&&(this.voice=he(this.voice,i.event,h));this.turn??=n.turn;let l=new Map([...n.calls,...this.calls]);this.calls.clear();for(let[i,c]of l)this.calls.set(i,c);for(let[i,c]of n.history)this.history.has(i)||this.history.set(i,c);this.forkedFrom??=n.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(a=>e=a)}}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 n=q(e);n&&this.take(n)}take(e){if(!this.ended){if(this.racing){this.held.push(e);let n=S(e);n>0&&this.pagedTo!==void 0&&n>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=Ue(setTimeout(()=>this.sortHeld(),Ve)));return}this.takeNow(e)}}takeNow(e){let n=S(e);n>0&&this.paged.has(n)||(n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),n=[],s=[],r=!0;for(let o of e){let a=S(o);if(a>0){if(this.paged.has(a)){r=!1;continue}r&&this.pagedFrom!==void 0&&a<this.pagedFrom?n.push(o):(r=!1,s.push(o))}else(r?n:s).push(o)}if(n.length>0){let o=Math.min(...n.map(S).filter(a=>a>0));this.before(n),Number.isFinite(o)&&(this.oldestLive=o,this.olderCursor=void 0)}for(let o of s)this.takeNow(o)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:n.from+I(n.text),loose:n.text==="",cutAt:n.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=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:n.from+I(n.text),loose:n.text==="",cutAt:n.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 n=K(e);if(this.voiceWords.has(n))return!1;this.voice=he(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);Ze(n,e.offset,e.text),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"reset":{let n=this.response(e.response_id);e.offset<=n.from?(n.text="",n.from=Math.max(0,e.offset)):n.text=n.text.slice(0,C(n.text,e.offset-n.from)),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let n=this.response(e.response_id);n.runId=e.run_id,n.agent=e.name,n.named=!0,n.parentId??=e.parent_response_id;break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let n=Ye(e),s=this.messages.get(n);this.messages.set(n,fe(s,e));let r=this.told.get(n);r?r.push(e):this.told.set(n,[e]),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,n){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([u,h])=>u!==n&&h.responseId===s),o=r?this.responses.get(s):void 0,a={type:"message",key:n,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},d=o?this.order.findIndex(u=>u.type==="response"&&u.key===s):-1;d>=0?this.order.splice(d,0,a):this.order.push(a)}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,n),this.order.push({type:"response",key:e,at:this.at})),n}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=l=>e!==void 0&&l.startedBy===e,s=new Map;for(let l of this.responses.values()){let i=l.parentId!==null?this.responses.get(l.parentId)??l:l;s.set(l.id,Xe(l,i.startedBy??null,n(i),l.goal??i.goal))}let r=new Map([...this.messages].map(([l,i])=>[l,e!==void 0&&i.author===e?{...i,mine:!0}:i])),o=[...this.history.entries()].sort(([l],[i])=>l-i).flatMap(([l,i])=>i.map((c,y)=>et(c,`${l}:${y}`,e))),a=[...o];for(let l of this.order)l.type==="goal"?a.push({type:"goal",goal:l.event}):l.type==="voice"?a.push({type:"voice",voice:l.event}):l.type==="message"?a.push({type:"message",message:r.get(l.key)}):this.responses.get(l.key).parentId===null&&a.push({type:"response",response:s.get(l.key)});let d=o.flatMap(l=>l.type==="message"?[l.message]:[]),u=o.flatMap(l=>l.type==="response"?[l.response]:[]),h=[...this.calls.values()].filter(l=>s.get(l.response_id)?.mine===!0);return{items:a,messages:[...d,...r.values()],responses:[...u,...s.values()],turn:this.turn,waiting:{approvals:h.filter(l=>l.status==="awaiting_approval"),outputs:h.filter(l=>l.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Qe(this.voice,e):null}}},Ve=150;function S(t){let e=t.seq;return typeof e=="number"&&e>0?e:0}function Ue(t){return t.unref?.(),t}function K(t){return`${t.voice_id}\0${t.status}`}function he(t,e,n){return n.add(K(e)),(e.status==="closed"?t===null||t.voice_id===e.voice_id:!n.has(`${e.voice_id}\0closed`))?e:t}function fe(t,e){let n=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??t?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:t?.status==="delivered"?"delivered":n,error:e.error??null,responseId:e.response_id??t?.responseId??null,createdAt:e.created_at??t?.createdAt??"",mine:!1,metadata:e.metadata??t?.metadata??{},history:!1,truncated:!1,kind:e.kind??t?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:t?.voice??null,attachments:e.attachments?ge(e.attachments):t?.attachments??[]}}function ze(t,e){let n={...t,marks:new Map(t.marks)};e.status!==null&&(n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=e.end),e.startedBy!==void 0&&(n.startedBy=e.startedBy),e.goal&&(n.goal=e.goal),e.named&&(n.runId=e.runId,n.agent=e.agent,n.named=!0),n.parentId=t.parentId??e.parentId,e.cut!==null&&(t.text===""||e.cut<=t.from?(n.text=e.text,n.from=e.text===""?Math.max(0,e.cut):e.from):n.text=t.text.slice(0,C(t.text,e.cut-t.from))+e.text,n.cut=t.cut===null?e.cut:Math.min(t.cut,e.cut));let s=r=>{if(t.text==="")return null;if(r!==null&&r<=t.from)return r;let o=I(t.text);return t.from+(r===null?o:Math.min(o,r-t.from))};for(let[r,o]of e.marks){let a=n.marks.get(r);if(a?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")n.marks.set(r,{...a,thinking:{...a.thinking,text:a.thinking.text+o.thinking.text}});else if(o.type==="thinking"&&o.loose){let d=s(o.cutAt);n.marks.set(r,d!==null?{...o,text_offset:d,loose:!1}:{...o,cutAt:o.cutAt===null?t.cut:t.cut===null?o.cutAt:Math.min(o.cutAt,t.cut)})}else n.marks.set(r,o)}return n}function Qe(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function ge(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Ye(t){return`${t.author??""}\0${t.client_id}`}function Ze(t,e,n){if(t.text===""||e<=t.from){t.from=Math.max(0,e),t.text=n;return}t.text=t.text.slice(0,C(t.text,e-t.from))+n}function Xe(t,e,n,s){let r=[...t.marks.values()].map((u,h)=>({m:u,i:h,at:C(t.text,Math.max(0,(Number(u.text_offset)||0)-t.from))}));r.sort((u,h)=>u.at-h.at||u.i-h.i);let o=[],a=[],d=0;for(let{m:u,at:h}of r)h>d&&o.push({type:"text",text:t.text.slice(d,h)}),d=Math.max(d,h),u.type==="thinking"?(o.push({type:"thinking",thinking:u.thinking}),a.push(u.thinking)):o.push(u.type==="tool"?{type:"tool",tool:u}:{type:"agent",agent:u});return d<t.text.length&&o.push({type:"text",text:t.text.slice(d)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:o,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:a,goal:s,history:!1,truncated:!1}}function et(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:ge(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var B=[["ApiKeyAuth","userJWT"]];function ye(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.turns!==void 0&&(s.turns=n.turns),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${E("ListChatParts","chat_id",e)}/parts`,auth:B,answers:{200:"json"},query:s,signal:n.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${E("GetChatToolCall","chat_id",e)}/tool-calls/${E("GetChatToolCall","call_id",n)}`,auth:B,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${E("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:B,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var M=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},me=new WeakMap;async function ve(t,e,n,s={},r=()=>{},o){let{pattern:a,events:d,messages:u,durable:h,chat:l}=tt(e),i=nt(a,n),c=me.get(t);c||me.set(t,c=new Map);let y=c,f=y.get(i)??{count:0};y.set(i,f),f.count++;let m=t.channel(i,h&&s.history!==!1?{after:0}:{});if(l&&!f.chat){let g=n.chatId,b=new O(r,o,typeof g=="string"&&g!==""?g:void 0,h&&s.history!==!1);f.chat=b,f.unchat=m.on("broadcast",w=>{w.event==="chat"&&b.takePayload(w.payload)})}let x=()=>{--f.count>0||(y.delete(i),f.unchat?.(),f.chat?.end(),m.leave())};try{await m.join()}catch{let g=m.state==="refused"?we(m.refusal,"unavailable"):"socket closed";throw x(),new M(`gateway ${JSON.stringify(i)} was not joined: ${g}`,g)}let T=!1,R=new Set,V=()=>{if(!T){T=!0,De();for(let g of[...R])g();x()}},De=m.onClosed(V),U=g=>{if(T)return()=>{};let b=m.on("broadcast",v=>{typeof v.event=="string"&&d.has(v.event)&&g(v.event,k(v.payload))}),w=()=>{R.delete(w),b()};return R.add(w),w},z={topic:i,get seq(){return m.logSeq},on(g,b){if(typeof g=="function")return U((w,v)=>g({event:w,payload:v}));if(!d.has(g))throw new TypeError(`gateway ${JSON.stringify(a)} declares no event ${JSON.stringify(String(g))}`);if(typeof b!="function")throw new TypeError(`gateway ${JSON.stringify(a)}: on(${JSON.stringify(g)}, \u2026) takes the function the event is handed to`);return U((w,v)=>{w===g&&b(v)})},off(g){R.has(g)&&g()},async send(g,b){if(!u.has(g))throw new TypeError(`gateway ${JSON.stringify(a)} declares no message ${JSON.stringify(String(g))}`);let w=T?{status:"error",response:{reason:"not joined"}}:await m.push("broadcast",{type:"broadcast",event:g,payload:b});if(w.status==="ok")return k(w.response.reply);let v=we(w.response,"unavailable");throw new M(`gateway ${JSON.stringify(i)} did not take ${JSON.stringify(g)}: ${v}`,v)},leave:V};return l&&Object.defineProperty(z,"chat",{value:f.chat,enumerable:!0}),z}function tt(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function nt(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(n,r)?n[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function we(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var st=3600*1e3,j=new Map;function rt(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=j.get(s);if(!n&&r&&Date.now()-r.at<st)return r.list;let o=(async()=>{let a=se(),d;try{d=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:a},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(u){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:u})}try{return await re(d,e.signer,e.projectId,a)}catch(u){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:u})}})();return j.set(s,{list:o,at:Date.now()}),o.catch(()=>{j.get(s)?.list===o&&j.delete(s)}),o}async function be(t,e,n,s,r,o){let d=(await rt(t,e,o)).keys[0];return X(d.kid,d.key,Z(e.projectId,n,s,r))}function F(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):N(e,n,s,(r,o)=>ee(t.key,r,o))}function ke(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):N(e,"/response",n,async(r,o)=>{if(!te(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 ne(t.key,r,o)}catch(a){throw new p("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:a})}})}function Ee(t){return t instanceof p&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var L=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
|
|
3
|
+
`);let n=[],s=this.pending.indexOf(`
|
|
4
|
+
`);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&n.push({event:this.eventName,payload:this.dataLines.join(`
|
|
5
|
+
`)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let a=o.slice(5);this.dataLines.push(a.startsWith(" ")?a.slice(1):a)}else if(o.startsWith("event:")){let a=o.slice(6);this.eventName=a.startsWith(" ")?a.slice(1):a}}s=this.pending.indexOf(`
|
|
6
|
+
`)}return n}};async function*_e(t,e){let n=t.getReader(),s=new TextDecoder,r=new L;try{for(;;){let{done:o,value:a}=await n.read();if(o)break;for(let d of r.consume(s.decode(a,{stream:!0}))){if(d.event==="error")throw new p("network",{code:"stream_failed",message:`stream failed: ${d.payload}`});let u;try{u=JSON.parse(d.payload)}catch{throw new p("decode",{code:"invalid_frame",message:`stream frame is not valid JSON: ${d.payload.slice(0,120)}`})}yield k(u)}}}finally{e.abort();try{await n.cancel()}catch{}}}var ot={},Ce=new WeakMap;function Wt(t,e,n,s,r,o=()=>{}){Ce.set(t,{project:e,machine:n,storage:s,socket:r,me:o})}var Se=new Map,xe=new WeakMap;function Ht(t,e,n,s,r,o){if(!le(e))throw new p("validation",{code:"reserved_namespace",message:`Cannot register backend ${JSON.stringify(String(e))}: a backend's name is an identifier the client does not keep.`});let a=pe(t);if(!ue(n))throw new TypeError(`${JSON.stringify(String(n))} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);ce(s),Ie(r);for(let d of Object.keys(r))if(de(d))throw Te(d);if(o!==void 0)ut(o);else if(Re(r))throw new p("validation",{code:"invalid_namespace_tree",message:`Backend ${e}: its routes carry encrypted fields, and its module holds no project id and signing key to seal them with \u2014 generate it again with palbase apps:sync`});(Se.get(e)??it(e)).set(a,{machine:n,url:s,tree:r,...o?{transit:{...o}}:{}})}function it(t){let e=new Map;return Se.set(t,e),Object.defineProperty(ot,t,{configurable:!0,get(){return at(this,t,e)}}),e}function at(t,e,n){let s=Ce.get(t);if(!s)return;let r=n.get(s.project);if(!r)throw new TypeError(`pb.${e} is the backend of ${[...n.keys()].join(" and ")}: this client is ${s.project}'s, and its user's session never goes to another project's machine`);let o=xe.get(t);o||xe.set(t,o=new Map);let a=o.get(e);if(a?.registration===r)return a.ns;let d={machine:()=>s.machine(r.url),storage:s.storage,name:r.machine,...r.transit?{transit:{project:s.storage,config:r.transit}}:{}},u=Object.assign({call:(h,l,i)=>yt(d.machine,h,l,i),join:(h,l,i)=>ve(s.socket,h,l,i,s.me,ye(s.storage))},Pe(r.tree,d));return o.set(e,{registration:r,ns:u}),u}function Te(t){return new p("validation",{code:"reserved_namespace",message:`Cannot register endpoint namespace ${JSON.stringify(t)}: the name is reserved.`})}function J(t){return typeof t.path=="string"&&typeof t.method=="string"}function dt(t,e){if(t.pathParams!==void 0){if(!Array.isArray(t.pathParams)||!t.pathParams.every(n=>typeof n=="string"))throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams must be an array of strings.`});for(let n of t.pathParams)if(!t.path.includes(`{${n}}`))throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams entry '${n}' has no '{${n}}' placeholder in the path.`})}if(t.sse!==void 0&&typeof t.sse!="boolean")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': sse must be a boolean.`});if(t.idempotent!==void 0&&typeof t.idempotent!="boolean")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': idempotent must be a boolean.`});if(t.upload!==void 0&&typeof t.upload!="boolean")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': upload must be a boolean.`});if(t.upload===!0&&(t.method!=="POST"||t.sse===!0))throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an upload endpoint is a POST, and no stream.`});if(t.sse===!0&&t.input==="query")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an sse endpoint cannot take query input.`});if(t.input!==void 0&&t.input!=="body"&&t.input!=="query"&&t.input!=="none")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': input must be 'body', 'query' or 'none'.`});if(t.encryption!==void 0&<(t,e),t.errors!==void 0){for(let[n,s]of Object.entries(t.errors))if(typeof s!="function")throw new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': errors['${n}'] must be a function.`})}}function lt(t,e){let n=t.encryption,s=r=>new p("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': encryption ${r}.`});if(typeof n!="object"||n===null)throw s("is { request, response }");for(let[r,o]of[["request",["/body/","/query/"]],["response",["/response"]]]){let a=n[r];if(a!==void 0&&(!Array.isArray(a)||!a.every(d=>typeof d=="string"&&o.some(u=>d===u||d.startsWith(u.endsWith("/")?u:`${u}/`)))))throw s(`${r} is a list of places under ${o.join(" or ")}`)}if(t.upload===!0)throw s("is no upload\u2019s: storage seals nothing");if(t.sse===!0&&(n.response?.length??0)>0)throw s("of a streamed answer is none")}function Re(t){return J(t)?t.encryption!==void 0:Object.values(t).some(e=>Re(e))}function ut(t){if(typeof t!="object"||t===null||typeof t.projectId!="string"||!/^[0-9a-f-]{36}$/.test(t.projectId)||typeof t.signer!="string"||!/^[A-Za-z0-9_-]{43}$/.test(t.signer))throw new p("validation",{code:"invalid_namespace_tree",message:"The backend's encryption is { projectId, signer }: the project's id and its Ed25519 signing key, base64url"})}function Ie(t){if(typeof t!="object"||t===null)throw new p("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});let e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null)throw new p("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});for(let[n,s]of Object.entries(t)){if($(n))throw Te(n);typeof s=="object"&&s!==null&&J(s)?(s.method=s.method.toUpperCase(),dt(s,s.path)):Ie(s)}}function Pe(t,e){if(J(t))return t.upload===!0?async(...s)=>ft(e,t,s):async(...s)=>Me(e.machine(),t,s,e.transit);let n={};for(let[s,r]of Object.entries(t))n[s]=Pe(r,e);return n}function W(t){if(t==null)return"";let e=Object.entries(t).filter(([,s])=>s!=null).sort(([s],[r])=>s<r?-1:s>r?1:0);return e.length===0?"":`?${e.map(([s,r])=>{if(typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")throw new p("validation",{code:"invalid_query_value",message:`Query parameter '${s}' must be a string, number, or boolean.`});return`${encodeURIComponent(s)}=${encodeURIComponent(String(r))}`}).join("&")}`}function $e(t,e,n){try{return E(t.path,e,n)}catch(s){if(!P(s)||s.code!=="invalid_path_parameter")throw s;let r=String(n);throw new p("validation",{code:"invalid_path_parameter",message:`${t.path}: ${e} cannot be ${r===""?"empty":JSON.stringify(r)}`})}}function Oe(t,e){let n=t.pathParams??[],s=t.path;for(let r=0;r<n.length;r++){let o=e[r];if(typeof o!="string"&&typeof o!="number")throw new p("validation",{code:"missing_path_param",message:`${t.path}: path parameter '${n[r]}' must be a string or number`});s=s.replace(`{${n[r]}}`,$e(t,`path parameter '${n[r]}'`,o))}return s}var ct=new Set(["POST","PUT","PATCH","DELETE"]);async function Me(t,e,n,s){let r=e.pathParams??[],o=Oe(e,n),a=o;if(e.input==="none"&&n.length>r.length+1)throw new p("validation",{code:"unexpected_argument",message:`${e.path}: endpoint takes no input \u2014 pass only path params and options`});let d=e.input==="none"?void 0:n[r.length],u=e.input==="none"?r.length:r.length+1,h=n[u],l;if(e.input==="query")a+=W(d);else if(e.input!=="none")if(e.method==="GET"){if(d!==void 0)throw new p("validation",{code:"unsupported_get_input",message:`${e.path}: GET endpoints take no body input`})}else l=d;let i={...h?.headers};if(ct.has(e.method)&&!Object.keys(i).some(c=>c.toLowerCase()==="idempotency-key")&&(i["Idempotency-Key"]=G()),e.encryption!==void 0){if(!s)throw new p("validation",{code:"encryption_unconfigured",message:`${e.method} ${e.path}: the route carries encrypted fields, and this backend's module holds no key to seal them with`});return pt(t,e,o,d,l,i,h?.signal,r.map((c,y)=>String(n[y])),s)}try{return e.sse===!0?await qe(t,e,a,l,i,h?.signal):await Ge(t,e,a,l,i,h?.signal)}catch(c){throw H(e,c)}}async function pt(t,e,n,s,r,o,a,d,u){let h=e.encryption;for(let l=0;;l++){let i=await be(u.project,u.config,e.method,e.path,d,l>0);try{let c=e.input==="query"?n+W(await F(i,s,"/query",h.request)):n,y=await F(i,r,"/body",h.request),f={...o,[Y]:i.header};return e.sse===!0?await qe(t,e,c,y,f,a):k(await ke(i,await Ge(t,e,c,y,f,a),h.response,`${e.method} ${e.path}`))}catch(c){if(l===0&&Ee(c))continue;throw H(e,c)}}}function H(t,e){return t.errors&&ae(e)&&Object.hasOwn(t.errors,e.code)?t.errors[e.code](e):e}var ht=[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]];async function ft(t,e,n){let s=e.pathParams??[],r=Oe(e,n),o=e.input==="none"?s.length:s.length+1;if(n.length>o+2)throw new p("validation",{code:"unexpected_argument",message:`${e.path}: an upload takes its path params, ${e.input==="none"?"":"its input, "}the file and options`});let a=e.input==="none"?void 0:n[s.length],d=n[o],u=n[o+1];if(!(d instanceof Blob))throw new p("validation",{code:"invalid_file",message:`${e.path}: the file is a Blob (a File is one)`});let h=`/storage/upload/${t.name}/${$e(e,"the route",r.slice(1))}`;e.input==="query"&&(h+=W(a));let l=gt(e.input==="query"?void 0:a,d),i=l.body.size,c=0,y=f=>{c=f;try{u?.onProgress?.({loaded:f,total:i})}catch{}};u?.onProgress&&y(0);try{let f;try{let m={op:`Upload ${e.path}`,method:"POST",path:h,auth:ht,answers:je,body:{kind:"raw",contentType:l.type,value:l.body},signal:u?.signal,...u?.onProgress?{onUploadProgress:x=>y(x)}:{}};f=(await t.storage.send(m)).data}catch(m){throw P(m)?D(m):m}return u?.onProgress&&c<i&&y(i),await Ne(e,f,u?.signal)}catch(f){throw H(e,f)}}function gt(t,e){let n=`Palbase-${G()}`,s=d=>d.replaceAll('"',"_").replace(/[\r\n]/g,""),r=typeof e.name=="string"?e.name:"blob",o=(d,u)=>`--${n}\r
|
|
7
|
+
Content-Disposition: form-data; ${d}\r
|
|
8
|
+
Content-Type: ${u}\r
|
|
9
|
+
\r
|
|
10
|
+
`,a=[];return t!==void 0&&a.push(o('name="body"',"application/json"),JSON.stringify(t),`\r
|
|
11
|
+
`),a.push(o(`name="file"; filename="${s(r)}"`,s(e.type)||"application/octet-stream"),e,`\r
|
|
12
|
+
--${n}--\r
|
|
13
|
+
`),{body:new Blob(a),type:`multipart/form-data; boundary=${n}`}}async function yt(t,e,n,s){if(typeof e!="string"||e===""||e==="/")throw new p("validation",{code:"invalid_endpoint_name",message:'Endpoint name must be a non-empty path like "todos/create"'});let r=e.startsWith("/")?e:`/${e}`;return Me(t(),{method:"POST",path:r},[n,s])}var je=Object.fromEntries(Array.from({length:100},(t,e)=>[200+e,"raw"])),mt=[["userJWT"],[]];async function Ae(t,e,n,s,r,o){let a={op:`${e.method} ${e.path}`,method:e.method,path:n,auth:mt,answers:je,headers:r,...s===void 0?{}:{body:{kind:"json",contentType:"application/json",value:s}},idempotent:e.idempotent===!0,signal:o};try{return(await t.send(a)).data}catch(d){throw P(d)?D(d):d}}async function Ge(t,e,n,s,r,o){return Ne(e,await Ae(t,e,n,s,r,o),o)}async function Ne(t,e,n){let s=e.headers.get("x-request-id")??void 0,r;try{r=await e.text()}catch(o){throw n?.aborted?o:new p("network",{code:"network_error",message:`${t.method} ${t.path}: the answer did not arrive whole`,status:e.status,requestId:s,cause:o})}if(r!=="")try{return k(JSON.parse(r))}catch(o){throw new p("decode",{code:"invalid_json",message:`${t.method} ${t.path}: the answer is not JSON`,status:e.status,requestId:s,cause:o})}}async function qe(t,e,n,s,r,o){let a=new AbortController;o&&(o.aborted?a.abort():o.addEventListener("abort",()=>a.abort(),{once:!0}));let d=await Ae(t,e,n,s,{accept:"text/event-stream",...r},a.signal);if(!d.body)throw new p("network",{code:"empty_stream",message:"the server answered a streaming route with no body",status:d.status});return _e(d.body,a)}export{p as a,ae as b,Je as c,le as d,ye as e,M as f,ot as g,Wt as h,Ht as i};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.51.
|
|
1
|
+
/*! palbase 0.51.4 — 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,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.51.
|
|
2
|
-
import{p as R,t as k,u as H}from"./
|
|
1
|
+
/*! palbase 0.51.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{p as R,t as k,u as H}from"./232EZENF.js";var N=40,V=`
|
|
3
3
|
:host{display:contents}
|
|
4
4
|
.pm-modal,.pm-full{position:fixed;inset:0;width:100%;height:100%;max-width:none;max-height:none;margin:0;border:0;background:transparent;color:inherit;overflow:hidden;display:flex;flex-direction:column}
|
|
5
5
|
.pm-modal::backdrop,.pm-full::backdrop{background:transparent}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.51.
|
|
1
|
+
/*! palbase 0.51.4 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
import{lstat as j,mkdir as F,readdir as M,readFile as N,rename as J,rm as T,writeFile as v}from"node:fs/promises";import{join as E}from"node:path";var o="palbase/strings",f="_meta.json",p=3,y=2,$=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function m(r){try{return Intl.getCanonicalLocales(r)[0]}catch{return}}function b(r,n){try{return JSON.parse(r)}catch(t){throw new Error(`${n} is not JSON: ${t.message}`)}}async function x(r){let n=E(r,o);try{if(!(await j(n)).isDirectory())throw new Error(`${o} is not a directory: the strings live in a directory of their own`)}catch(e){if(e.code==="ENOENT")return;throw e}let t=new Map;for(let e of await M(n,{withFileTypes:!0}))if(!(e.name.startsWith(".")||!e.name.endsWith(".json"))){if(!e.isFile())throw new Error(`${o}/${e.name} is not a regular file`);t.set(e.name,await N(E(n,e.name),"utf8"))}return t.size===0?void 0:t}async function R(r,n=[p,y]){let t=await x(r);if(t===void 0)return;let e=t.get(f);if(e===void 0)throw new Error(`${o}/${f} is missing: it names the source language, and without it the language files are not a table`);let u=b(e,`${o}/${f}`);if(!$(u))throw new Error(`${o}/${f}: not a JSON object`);let s=u.version;if(s===y&&!n.includes(y))throw new Error(`${o}/${f}: version 2 is the earlier format ({"value", "state"} for each sentence) \u2014 run \`npx palbase strings\` once, and it writes the table as version ${p}`);if(typeof s!="number"||!n.includes(s))throw new Error(`${o}/${f}: version ${JSON.stringify(s)} is not one this reads (${n.join(" or ")})`);let a=u.source;if(typeof a!="string"||m(a)!==a)throw new Error(`${o}/${f}: source ${JSON.stringify(a)} is not a language tag as it is written (${m(String(a))??"en, en-US, zh-Hans"})`);let S=new Map;for(let w of[...t.keys()].sort()){if(w===f)continue;let i=w.slice(0,-5),g=`${o}/${w}`,d=m(i);if(d===void 0)throw new Error(`${g}: ${JSON.stringify(i)} is not a language tag`);if(d!==i)throw new Error(`${g}: the language is written ${d} \u2014 name the file ${d}.json`);if(i===a)throw new Error(`${g}: ${i} is the source language \u2014 its text is the key itself, and it has no file`);if(i==="und"||i==="root"||i.startsWith("x-"))throw new Error(`${g}: ${i} is no language a request names \u2014 name the file for one (en, de, pt-BR)`);let O=b(t.get(w),g);if(!$(O))throw new Error(`${g}: not a JSON object of "sentence": "translation"`);let h=new Map;for(let[l,c]of Object.entries(O))if(s===p){if(typeof c!="string")throw new Error(`${g}: the translation of ${JSON.stringify(l)} is not a string`);h.set(l,c)}else if(typeof c=="string")h.set(l,c);else{if(!$(c)||typeof c.value!="string")throw new Error(`${g}: key ${JSON.stringify(l)} is not {"value": string, "state": string}`);h.set(l,c.state==="missing"?"":c.value)}S.set(i,h)}return{format:s,source:a,languages:S}}async function A(r){let n=await R(r,[p]);if(n===void 0)return;let t={};Object.setPrototypeOf(t,null);for(let[e,u]of n.languages)for(let[s,a]of u)Object.hasOwn(t,s)||(t[s]={},Object.setPrototypeOf(t[s],null)),t[s][e]=a;return{source:n.source,locales:[n.source,...n.languages.keys()],strings:t}}export{A as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.51.
|
|
1
|
+
/*! palbase 0.51.4 — 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,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.51.
|
|
2
|
-
import{a as j,c as Ee,d as Pe,e as Re}from"./
|
|
1
|
+
/*! palbase 0.51.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as j,c as Ee,d as Pe,e as Re}from"./35NHGNIS.js";import{a as Ce}from"./HMBUUER2.js";import{a as Ae}from"./IEJNSFS3.js";import{a as xe,b as ve,c as _e}from"./EHAREIHA.js";import{b as P,d as Se}from"./2HO42W3S.js";async function*Ie(e,t={}){let o=e.getReader(),s=new TextDecoder,i="",d="",l=[],p,r=()=>{o.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:a}=await o.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=s.decode(a,{stream:!0});for(let c=i.indexOf(`
|
|
3
3
|
`);c>=0;c=i.indexOf(`
|
|
4
4
|
`)){let g=i.slice(0,i[c-1]==="\r"?c-1:c);i=i.slice(c+1),g===""?(d!==""&&(yield p===void 0?{event:d,data:l.join(`
|
|
5
5
|
`)}:{event:d,data:l.join(`
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
/*! palbase 0.51.
|
|
2
|
+
/*! palbase 0.51.4 — Palbase SDK License (see LICENSE) */
|
|
3
3
|
var Hw=Object.defineProperty;var Ye=(e,t)=>{for(var n in t)Hw(e,n,{get:t[n],enumerable:!0})};import{parseArgs as Ov}from"node:util";var Yw=Symbol.for("palbase.data"),Xw=globalThis,Ld=Xw[Yw]??=new WeakSet;function Zw(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function Qa(e){let t=[e];for(;t.length>0;){let n=t.pop();if(!(typeof n!="object"||n===null||Ld.has(n)||Zw(n))){Ld.add(n);for(let s of Array.isArray(n)?n:Object.values(n))t.push(s)}}return e}var Qw="X-PoW-Challenge-ID",ev="X-PoW-Nonce";function Dd(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:s,difficulty:a}=t.challenge;return typeof n!="string"||typeof s!="string"||typeof a!="number"||!Number.isInteger(a)||a<0?null:{id:n,prefix:s,difficulty:a}}function tv(e){return 8*2**e}var ps;async function nv(){if(ps)return ps;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let s=(await import("node:crypto")).createHash;if(typeof s=="function")return ps=a=>new Uint8Array(s("sha256").update(a).digest()),ps}catch{}let t=new TextEncoder;return ps=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),ps}function sv(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var av=4096,iv=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function xd(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 nv(),s=tv(e.difficulty),a=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<s;i++){if(i%av===0&&i>0){if(await iv(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>a)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let r=n(e.prefix+i),o=r instanceof Uint8Array?r:await r;if(sv(o)>=e.difficulty)return{[Qw]:e.id,[ev]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${s} attempts`)}var E=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="PalbaseError",this.op=t.op,this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.retryAfter=t.retryAfter,this.body=t.body}};function c(e,t,n){let s=String(n);if(s===""||s==="."||s==="..")throw new E({op:e,status:0,code:"invalid_path_parameter",message:`${e}: ${t} cannot be ${s===""?"empty":JSON.stringify(s)}`});return encodeURIComponent(s)}var rv=new Set(["apikey","authorization"]),ov=64*1024;function Vr(e){let t=ei(e.baseUrl),n=e.fetch??globalThis.fetch,s=e.solveProofOfWork??!0,a=async(i,r)=>{let o=pv(t,i),l=new Headers;for(let[y,w]of Object.entries(i.headers??{}))w!=null&&!rv.has(y.toLowerCase())&&l.set(y,String(w));for(let[y,w]of Object.entries(r))l.set(y,w);await uv(i,e.credentials,l),l.has("accept")||l.set("accept","application/json");let d={method:i.method,headers:l,redirect:"manual",signal:i.signal,...i.keepalive?{keepalive:!0}:{}};i.body&&i.body.value!==void 0&&(l.set("content-type",i.body.contentType),d.body=cv(i.body.kind,i.body.value),us(d.body)||(d.duplex="half"));let p;try{p=i.onUploadProgress&&e.xmlHttpRequest?await lv(e.xmlHttpRequest,i.op,o,d,i.onUploadProgress):await n(o,d)}catch(y){throw i.signal?.aborted||y instanceof E?y:new E({op:i.op,status:0,code:"network_error",message:`${i.op}: the request did not reach ${t.origin}`,cause:y})}let u=i.answers[p.status]??(i.ownResponse&&p.status>=200&&p.status<300?"raw":void 0);if(u===void 0)throw p.status>=200&&p.status<300?(await p.body?.cancel(),new E({op:i.op,status:p.status,code:"undeclared_answer",message:`${i.op}: the server answered ${p.status}, which its contract does not declare; the request may have taken effect`})):await mv(i.op,p);let g;switch(u){case"json":try{g=Qa(await p.json())}catch(y){throw new E({op:i.op,status:p.status,code:"invalid_json",message:`${i.op}: the answer is not JSON`,cause:y})}break;case"raw":g=p;break;default:await p.body?.cancel(),g=void 0}return{status:p.status,data:g,headers:p.headers}};return{async send(i){try{return await a(i,{})}catch(r){let o=s&&r instanceof E&&r.status===403?Dd(r.body):null,l=i.body?.value;if(!o||i.body?.kind==="raw"&&!us(l))throw r;let d=r,p;try{p=await xd(o,{signal:i.signal})}catch(u){throw i.signal?.aborted?u:new E({op:i.op,status:403,code:"pow_unsolved",message:`${i.op}: ${u instanceof Error?u.message:String(u)}`,requestId:d.requestId,body:d.body,cause:u})}return a(i,p)}}}}function lv(e,t,n,s,a){return new Promise((i,r)=>{let o=s.signal;if(o?.aborted)return r(o.reason);let l=new e,d=()=>l.abort();o?.addEventListener("abort",d,{once:!0});let p=u=>{o?.removeEventListener("abort",d),u()};l.open(s.method??"GET",n.href),l.responseType="arraybuffer",new Headers(s.headers).forEach((u,g)=>l.setRequestHeader(g,u)),l.upload&&(l.upload.onprogress=u=>{u.lengthComputable&&a(u.loaded,u.total)}),l.onload=()=>p(()=>{if(l.responseURL!==""&&l.responseURL!==n.href){r(new E({op:t,status:0,code:"undeclared_redirect",message:`${t}: the server redirected; the answer is another address's, and was not read`}));return}if(l.status<200||l.status>599)return r(new TypeError(`${t}: answered ${l.status}`));let u=l.status===204||l.status===205||l.status===304;i(new Response(u?null:l.response,{status:l.status,statusText:l.statusText,headers:dv(l.getAllResponseHeaders())}))}),l.onerror=()=>p(()=>r(new TypeError(`${t}: the request failed`))),l.onabort=()=>p(()=>r(o?.reason??new DOMException("The request was aborted","AbortError"))),l.send(s.body)})}function dv(e){let t=new Headers;for(let n of e.split(/\r?\n/)){let s=n.indexOf(":");if(!(s<=0))try{t.append(n.slice(0,s).trim(),n.slice(s+1).trim())}catch{}}return t}function ei(e){let t;try{t=new URL(e)}catch{throw new TypeError(`baseUrl ${JSON.stringify(e)} is not an absolute URL`)}let n=t.hostname==="localhost"||t.hostname.endsWith(".localhost")||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${t.origin}`);if(t.username||t.password||t.search||t.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(t.pathname!=="/"&&t.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return t}function pv(e,t){if(!t.path.startsWith("/")||t.path.startsWith("//"))throw new E({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path ${JSON.stringify(t.path)} is not absolute`});let n=new URL(t.path+hv(t.query),e);if(n.origin!==e.origin)throw new E({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path leaves the project's origin`});return n}async function uv(e,t,n){if(e.auth.length===0)return;let s=e.auth.some(r=>r.includes("userJWT"))?await t.accessToken?.():void 0,a=r=>{switch(r){case"ApiKeyAuth":return!!(t.publishableKey??t.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(t.secretKey??t.token);case"PalbaseBearer":return!!t.token;case"userJWT":return!!s&&!t.token;default:return!1}},i=e.auth.filter(r=>r.every(a)).reduce((r,o)=>r===void 0||o.length>r.length?o:r,void 0);if(!i)throw new E({op:e.op,status:0,code:"missing_credential",message:`${e.op} needs one of: ${e.auth.map(r=>r.length===0?"nothing":r.join(" + ")).join(" | ")}`});for(let r of i)r==="ApiKeyAuth"?n.set("apikey",t.publishableKey??t.secretKey):(r==="SecretKeyAuth"||r==="AdminAuth"||r==="PalbaseBearer")&&t.token?n.set("authorization",`Bearer ${t.token}`):r==="SecretKeyAuth"||r==="AdminAuth"?n.set("apikey",t.secretKey):r==="userJWT"&&n.set("authorization",`Bearer ${s}`)}function cv(e,t){switch(e){case"json":return JSON.stringify(t);case"form":{let n=new URLSearchParams;for(let[s,a]of Object.entries(t))Hr(n,s,a);return n}case"raw":return t}}function us(e){return!!(e==null||typeof e=="string"||e instanceof URLSearchParams||e instanceof Blob||e instanceof FormData||e instanceof ArrayBuffer||ArrayBuffer.isView(e))}function hv(e){if(!e)return"";let t=new URLSearchParams;for(let[s,a]of Object.entries(e))Hr(t,s,a);let n=t.toString();return n===""?"":`?${n}`}function Hr(e,t,n){if(n!=null){if(Array.isArray(n)){for(let s of n)Hr(e,t,s);return}if(n instanceof Date){e.append(t,n.toISOString());return}e.append(t,typeof n=="object"?JSON.stringify(n):String(n))}}async function mv(e,t){let n=await gv(t,ov).catch(()=>""),s;try{s=n===""?void 0:JSON.parse(n)}catch{s=n}let a=fv(s)?s:void 0,i=Number(t.headers.get("retry-after")),r=t.status>=300&&t.status<400;return new E({op:e,status:t.status,code:a?.error??(r?"undeclared_redirect":`http_${t.status}`),message:a?.error_description??(r?`${e}: the server redirected (${t.status}); the request was not followed, its credentials stay here`:`${e}: ${t.status} ${t.statusText}`.trim()),requestId:a?.request_id??t.headers.get("x-request-id")??void 0,retryAfter:a?.retry_after??(Number.isFinite(i)&&i>0?i:void 0),body:s})}async function gv(e,t){if(!e.body)return"";let n=e.body.getReader(),s=[],a=0;for(;a<t;){let{done:o,value:l}=await n.read();if(o)break;s.push(l),a+=l.byteLength}await n.cancel().catch(()=>{});let i=new Uint8Array(Math.min(a,t)),r=0;for(let o of s){let l=Math.min(o.byteLength,i.byteLength-r);if(i.set(o.subarray(0,l),r),r+=l,r>=i.byteLength)break}return new TextDecoder().decode(i)}function fv(e){return typeof e=="object"&&e!==null&&typeof e.error=="string"}var ti={project:{type:"string",short:"P",value:"project",description:"the project (name or id; org/project when the name is in two organizations)"},env:{type:"string",short:"E",value:"env",description:"the project's environment (slug or ref)"},json:{type:"boolean",description:"print the answer as JSON"},"non-interactive":{type:"boolean",description:"never ask: refuse what would need a question"},yes:{type:"boolean",short:"y",description:"confirm a change to a production environment without asking"},debug:{type:"boolean",description:"print each request the command sends"},help:{type:"boolean",short:"h",description:"show help"}};var f=class extends Error{exitCode;hint;code;reported;constructor(t,n,s={}){super(n),this.name="CliError",this.code=t,this.hint=s.hint,this.exitCode=s.exitCode??1,this.reported=s.reported??!1}};function m(e,t){return new f("usage",e,{hint:t,exitCode:2})}var ni=class{io;json;constructor(t,n){this.io=t,this.json=n}result(t,n){this.json?this.io.stdout(`${JSON.stringify(t,null,2)}
|
|
4
4
|
`):n()}line(t=""){this.io.stdout(`${N(t)}
|
|
5
5
|
`)}note(t){this.io.stderr(`${N(t)}
|
|
@@ -9,7 +9,7 @@ var Hw=Object.defineProperty;var Ye=(e,t)=>{for(var n in t)Hw(e,n,{get:t[n],enum
|
|
|
9
9
|
`);let r;try{r=await this.io.fetch(t,{method:n.method,headers:{...n.headers,...a},body:n.body,signal:n.signal,...s?{}:{duplex:"half"},redirect:"manual"})}catch(l){throw n.signal?.aborted?l:new f("network_error",`${new URL(t).origin} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(this.debug&&this.io.stderr(`< ${r.status} ${r.headers.get("x-request-id")??""}
|
|
10
10
|
`),r.status!==503||!s||i>=Ev||!Tv.has(await Zr(r)??""))return r;await r.body?.cancel();let o=Number(r.headers.get("retry-after")??"");await this.io.sleep((Number.isFinite(o)&&o>0?Math.min(o,30):1)*1e3)}}async exchange(t,n,s){let a=await this.token(),i=await this.send(t,n,s,a.value);if(i.status===401&&a.renewable){let r=await this.renew(await this.currentSession());i=await this.send(t,n,s,r.access_token)}return{res:i,renewable:a.renewable}}async answered(t,n,s,a){if(s.status===204)return;let i=await s.text(),r=i===""?void 0:Cv(i);if(s.ok)return r;let o=r??{};throw s.status===401?o.error==="token_not_for_machines"?Qd(new URL(this.cloud.studioApi).host):a?cs():this.tokenRefused("Studio"):new E({op:`${t} ${n}`,status:s.status,code:o.error??`http_${s.status}`,message:o.error_description??`Studio answered ${s.status}`,requestId:o.request_id??s.headers.get("x-request-id")??void 0,body:r})}tokenRefused(t){return(this.io.env.PALBASE_TOKEN??"").startsWith("pbe_")?new f("token_refused",`${t} refused PALBASE_TOKEN, an environment's token: it ended (a few hours at most), it was revoked, or what minted it no longer holds`,{hint:"mint another: palbase env:tokens:create --scope <scope> (an admin), or with the environment's secret key (Studio's POST /environments/{ref}/tokens)"}):(this.io.env.PALBASE_TOKEN??"").startsWith("pbu_")?new f("token_refused",`${t} refused PALBASE_TOKEN, an account token: it was revoked, it ended, or, in this organization, the one who made it left it`,{hint:"its maker makes a new one: palbase account:tokens:create <name>"}):new f("token_refused",`${t} refused PALBASE_TOKEN: it was revoked, it ended, or the one who made it no longer holds its role`,{hint:"an admin makes a new one: palbase tokens:create <name>"})}async token(){let t=this.io.env.PALBASE_TOKEN;return t&&t!==""?{value:t,renewable:!1}:{value:(await this.currentSession()).access_token,renewable:!0}}async renew(t){let n=await Hd(this.io,this.cloud,t);return await this.state.writeSession(n),this.session=n,n}async send(t,n,s,a){let i=`${this.cloud.studioApi}${Rv}${n}`;this.debug&&this.io.stderr(`> ${t} ${i}
|
|
11
11
|
`);try{let r=await this.io.fetch(i,{method:t,headers:{...a===void 0?{}:{authorization:`Bearer ${a}`},accept:"application/json",...s===void 0?{}:{"content-type":"application/json"}},body:s===void 0?void 0:JSON.stringify(s),redirect:"manual"});return this.debug&&this.io.stderr(`< ${r.status} ${r.headers.get("x-request-id")??""}
|
|
12
|
-
`),r}catch(r){throw new f("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${r instanceof Error?r.message:String(r)}`)}}};function Qd(e){return new f("token_not_for_machines",`the platform's edge refused PALBASE_TOKEN at ${e}, taking it for a machine's address (token_not_for_machines): the token itself was not refused`,{hint:"nothing is wrong with the token: run this again in a few minutes, and tell Palbase if it lasts"})}async function Zr(e){let t=await e.clone().json().catch(()=>null),n=t&&typeof t=="object"?t.error:void 0;return typeof n=="string"&&/^(console|token|edge)_/.test(n)?n:void 0}function Cv(e){try{return JSON.parse(e)}catch{return e}}var ep={version:"0.51.
|
|
12
|
+
`),r}catch(r){throw new f("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${r instanceof Error?r.message:String(r)}`)}}};function Qd(e){return new f("token_not_for_machines",`the platform's edge refused PALBASE_TOKEN at ${e}, taking it for a machine's address (token_not_for_machines): the token itself was not refused`,{hint:"nothing is wrong with the token: run this again in a few minutes, and tell Palbase if it lasts"})}async function Zr(e){let t=await e.clone().json().catch(()=>null),n=t&&typeof t=="object"?t.error:void 0;return typeof n=="string"&&/^(console|token|edge)_/.test(n)?n:void 0}function Cv(e){try{return JSON.parse(e)}catch{return e}}var ep={version:"0.51.4"};var oi=ep.version;async function ip(e,t,n){let s=new Map(n.map(r=>[r.name,r])),a=e.includes("--json"),i=e.includes("--debug");try{let{name:r,at:o}=Mv(e);if(r===void 0)return e.includes("--version")?(t.stdout(`palbase ${oi}
|
|
13
13
|
`),0):(t.stdout(ap(n)),e.length===0||e.includes("--help")||e.includes("-h")?0:2);if(r==="help"){let $=e[o+1],R=$===void 0?void 0:s.get($);if($!==void 0&&!R)throw tp($,n);return t.stdout(R?sp(R):ap(n)),0}let l=s.get(r);if(!l)throw tp(r,n);let d=[...e.slice(0,o),...e.slice(o+1)],p=d.includes("--")?d.slice(0,d.indexOf("--")):d;if(p.includes("--help")||p.includes("-h"))return t.stdout(sp(l)),0;let{flags:u,positionals:g}=Iv(l,d),y=l.args??{min:0,max:0};if(g.length<y.min)throw m(`${l.name} needs ${y.min===1?"an argument":`${y.min} arguments`}`,eo(l));if(g.length>y.max)throw m(`${l.name} takes ${y.max===0?"no argument":`at most ${y.max}`}: ${JSON.stringify(g.slice(y.max))} is left over`,eo(l));let w={project:u.project,env:u.env,json:u.json===!0,nonInteractive:u["non-interactive"]===!0,yes:u.yes===!0,debug:u.debug===!0},_=Bd(t.env),P=new si(Fd(t.configDir,_)),S={io:t,state:P,out:new ni(t,w.json),global:w,args:g,flags:u,interactive:t.interactive&&!w.nonInteractive,cloud:_,studio:new ri(t,_,P,w.debug)};return await l.run(S)??0}catch(r){return Lv(r,t,a,i)}}function Mv(e){let t=new Set;for(let[n,s]of Object.entries(ti))s.type==="string"&&(t.add(`--${n}`),s.short&&t.add(`-${s.short}`));for(let n=0;n<e.length;n++){let s=e[n];if(s==="--")return{at:-1};if(t.has(s)){n++;continue}if(!s.startsWith("-"))return{name:s,at:n}}return{at:-1}}function Iv(e,t){let n={...ti,...e.flags??{}},s={};for(let[a,i]of Object.entries(n))s[a]={type:i.type,...i.short?{short:i.short}:{},...i.multiple?{multiple:!0}:{}};try{let{values:a,positionals:i}=Ov({args:t,options:s,strict:!0,allowPositionals:!0});return{flags:a,positionals:i}}catch(a){throw m(a instanceof Error?a.message.replace(/^.*?: /,""):String(a),`palbase help ${e.name}`)}}function Lv(e,t,n,s){let a="error",i,r,o=1,l;return e instanceof f?(a=e.code,i=e.message,r=e.hint,o=e.exitCode):e instanceof E?(a=e.code,i=e.message,l=e.requestId,e.code==="token_out_of_scope"&&t.env.PALBASE_TOKEN&&(i=`${e.op} refused PALBASE_TOKEN: ${e.message}`,r="this is the token's reach, fixed when it was minted: a person's yes does not change it \u2014 mint a token whose scopes name this call, or have a person run it signed in")):i=e instanceof Error?e.message:String(e),n&&e instanceof f&&e.reported||(n&&t.stdout(`${JSON.stringify({error:a,message:i,...r?{hint:r}:{},...l?{request_id:l}:{}},null,2)}
|
|
14
14
|
`),t.stderr(`error: ${N(i)}${l?` (request ${N(l)})`:""}
|
|
15
15
|
`),r&&t.stderr(` ${N(r)}
|