palbase 0.19.0 → 0.19.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/{RIQJUVZK.js → 2D6UTNAS.js} +1 -1
- package/dist/chunks/{Y4THIE6E.js → 34FI7FDO.js} +2 -2
- package/dist/chunks/{2XM3DQXS.js → 3DPITTIG.js} +2 -2
- package/dist/chunks/{43RXGTTL.js → 5IKIPSPK.js} +1 -1
- package/dist/chunks/{MI3PAKT3.js → 63ALEOYV.js} +2 -2
- package/dist/chunks/{Z4YKS2EK.js → 65XX646N.js} +2 -2
- package/dist/chunks/{HM7G4WGJ.js → AFNLDC5V.js} +2 -2
- package/dist/chunks/{ZW57VOIW.js → AJUTYIGD.js} +2 -2
- package/dist/chunks/{SGASB5G4.js → ANPIBUP7.js} +2 -2
- package/dist/chunks/{B6OLQP6W.js → B64PN4SN.js} +2 -2
- package/dist/chunks/{V2GWROU3.js → CGPI3ZD2.js} +2 -2
- package/dist/chunks/{TOPRHPT6.js → EEZBV4BZ.js} +1 -1
- package/dist/chunks/{V6TFL4HC.js → EOMNR25V.js} +2 -2
- package/dist/chunks/{PRIISRPI.js → GYAC4XGQ.js} +2 -2
- package/dist/chunks/{KE4DEYSH.js → HNFLACEJ.js} +1 -1
- package/dist/chunks/{QOUBSZM4.js → KLXOLRFH.js} +1 -1
- package/dist/chunks/{LCBMI6UP.js → LH6MM4NX.js} +1 -1
- package/dist/chunks/{26R7KNH7.js → M23DJASA.js} +2 -2
- package/dist/chunks/{LRWWDIJZ.js → MLQQWG2B.js} +2 -2
- package/dist/chunks/{WHKAPZX7.js → OMXEFKCT.js} +3 -3
- package/dist/chunks/{424IEUQX.js → OSREI5EV.js} +2 -2
- package/dist/chunks/{EDIQ4SAO.js → PLAWOADG.js} +2 -2
- package/dist/chunks/{F5CWCOSS.js → SPRDYHDI.js} +1 -1
- package/dist/cli.js +103 -103
- 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/cloud/src/generated/project.d.ts +1 -1
- package/types/internal/src/modules/ai.d.ts +3 -3
- package/types/internal/src/modules/notify.d.ts +1 -1
- package/types/web/src/consent.d.ts +1 -1
- package/types/web/src/socket.d.ts +6 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.19.
|
|
2
|
-
import{a,b,c,d,e,f}from"../chunks/
|
|
1
|
+
/*! palbase 0.19.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a,b,c,d,e,f}from"../chunks/MLQQWG2B.js";import"../chunks/M23DJASA.js";import"../chunks/LH6MM4NX.js";import"../chunks/AJUTYIGD.js";import"../chunks/34FI7FDO.js";import"../chunks/65XX646N.js";import"../chunks/5IKIPSPK.js";import"../chunks/2D6UTNAS.js";export{e as AIResponseError,b as AISchemaError,d as ToolError,f as createAI,a as partial,c as prepare};
|
package/dist/backend/engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.19.
|
|
2
|
-
import{ia as w,ma as h}from"../chunks/
|
|
1
|
+
/*! palbase 0.19.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{ia as w,ma as h}from"../chunks/AFNLDC5V.js";import"../chunks/63ALEOYV.js";import"../chunks/PLAWOADG.js";import"../chunks/MLQQWG2B.js";import"../chunks/M23DJASA.js";import"../chunks/OSREI5EV.js";import"../chunks/EEZBV4BZ.js";import"../chunks/KLXOLRFH.js";import"../chunks/LH6MM4NX.js";import"../chunks/AJUTYIGD.js";import"../chunks/34FI7FDO.js";import"../chunks/65XX646N.js";import"../chunks/5IKIPSPK.js";import"../chunks/2D6UTNAS.js";import{binding as R,createDatabase as v}from"palgres";var y=new WeakMap;function q(p,e,a){if(!a?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=a.schemas,n=y.get(p);n||y.set(p,n=new Map);let r=n.get(u);r||n.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",g=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},f=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(f);i||(i=v({sql:p,schemas:u,binding:R(0,!0),roles:g,...a.fields!==void 0?{fields:a.fields}:{}}),r.set(f,i));let b=JSON.parse(e.claimsJson),m=i.then(s=>s.request({role:o,claims:b},{diagnostics:a.diagnostics,signal:a.signal})),d=s=>new Proxy(()=>{},{apply:async(t,D,c)=>{let l=(await m).client;return s(l).apply(l,c)}});return{client:new Proxy({},{get(s,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:d(l=>l.asService()[c])}):d(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async s=>(await m).rollback(s)}}export{w as createApp,q as createRequestDatabase,h as makeMemoryCache};
|
package/dist/backend/env.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.19.
|
|
1
|
+
/*! palbase 0.19.2 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.19.
|
|
2
|
-
import{$ as It,A as dt,B as F,C as ut,D as pt,E as ft,F as gt,G as mt,H as bt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as Tt,R as _t,S as xt,T as Rt,U as Ot,V as Ct,W as Bt,X as Ft,Y as se,Z as Mt,_ as $t,a as Q,aa as Lt,b as X,ba as Ut,c as Z,ca as Dt,d as Ne,da as jt,e as qe,ea as Nt,f as We,fa as qt,g as Ke,ga as M,h as Ve,ha as Gt,i as Ge,ia as $,j as ze,ja as V,k as He,ka as zt,l as Ye,la as Ht,m as Je,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as st,t as rt,u as nt,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/HM7G4WGJ.js";import{a as Wt,b as Kt}from"../chunks/MI3PAKT3.js";import{a as ne}from"../chunks/KE4DEYSH.js";import{a as x,b as ee,c as te,f as m,g as ht,h as d,j as re,k as Vt}from"../chunks/EDIQ4SAO.js";import"../chunks/LRWWDIJZ.js";import"../chunks/26R7KNH7.js";import{d as _,j as De,k as je,l as H,m as B,t as Y,u as J}from"../chunks/424IEUQX.js";import"../chunks/TOPRHPT6.js";import"../chunks/QOUBSZM4.js";import"../chunks/LCBMI6UP.js";import{o as Ue}from"../chunks/ZW57VOIW.js";import"../chunks/Y4THIE6E.js";import{b as A,c as K}from"../chunks/Z4YKS2EK.js";import"../chunks/43RXGTTL.js";import"../chunks/RIQJUVZK.js";import"reflect-metadata";import{existsSync as G,writeFileSync as xs,writeSync as Rs}from"node:fs";import{createServer as Os}from"node:http";import{dirname as k,join as z,resolve as xe}from"node:path";import{Readable as Cs}from"node:stream";var Yt=2e3,Jt=1e4,Qt=/^[A-Za-z0-9_-]{1,64}$/,Xt=512,I=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,s={}){this.sink=e,this.linesPerSecond=s.linesPerSecond??10,this.batchSize=Math.min(100,s.batchSize??100),this.flushMs=s.flushMs??2e3,this.maxPending=s.maxPending??2e3,this.sendMs=s.sendMs??Jt,this.shutdownMs=s.shutdownMs??Yt,this.now=s.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,s,r=new Promise(a=>s=a),n=setTimeout(()=>{e=!0,s()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),r]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,s=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),s>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${s} dropped`)}log(e){let s=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(s-this.refilled)/1e3*this.linesPerSecond),this.refilled=s,this.unlogged>0&&s-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=s),this.tokens<1){this.unlogged===0&&(this.unloggedSince=s),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[r](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Qt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Xt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),s=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let n=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await s.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let i=a.status,o=i??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Zt}from"node:crypto";import{bind as es,bunDriver as ts,createDatabase as ss,envBlock as rs,createSearchWorker as ns,cutOff as as,forgetUser as os,MigrationOpen as is,MigrationRefused as ls,Migrator as ce,renewingBunPool as ae,VersionNotMigrated as cs}from"palgres";import{toModel as de}from"palgres/dsl";var ds=["start","complete","rollback","plan","status","types"],us=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function ue(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!ds.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let s of e)if(s.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function U(t){return de(pe(t))}function ps(t){return t.tables.some(e=>e.search!==void 0)}function D(t){return t.tables.some(e=>!e.ignored&&e.columns.some(s=>s.user!==void 0&&!s.ignored))}function he(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let s=Number(e);if(!Number.isSafeInteger(s)||s<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return s}function hs(t){if(!Number.isSafeInteger(t)||t<3)throw new Error(`[palbase] db.driver: a pool of ${t} connection(s) \u2014 the engine needs at least 3: one request's transaction and the two further ones it may hold`);let e=Math.floor(t/3);return{concurrency:e,nestedConcurrency:e*2}}var oe=5;function fe(t,e){if(t.driver)return t.driver;let s=globalThis.Bun;if(!s)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let r=e-1;return n=>{let a=ae(()=>new s.SQL({url:n,prepare:!1,max:r})),i=ae(()=>new s.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:ts(a,i),poolSize:r,close:async()=>{await a.close({timeout:oe}),await i.close({timeout:oe})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await R(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function me(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let s=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await R("types",rs(s,{module:"palbase/backend/env"}),e),0}async function be(t,e,s){let r=e.PALBASE_DB_OWNER_URL;if(!r)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!us.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=fe(t,he(e)),i=a(r),o,c=l=>d.error(`[palbase] migrate ${s}: ${l}`);try{let l=U(t),u=new ce(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let g=new URL(r);g.pathname=`/${f}`;let y=a(g.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>fs(e)});if(s==="plan"){let f=await u.plan(l);return await R(s,f),f.refusals.length>0?1:0}if(s==="status")return await R(s,await u.status()),0;let h=s==="start"?await gs(u,l,n):s==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${s}: done`,{result:h}),await R(s,h),0}catch(l){return l instanceof ls?(d.error(`[palbase] migrate ${s}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):as(l)?(d.error(`[palbase] migrate ${s}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??ie(l)}`),75):(d.error(`[palbase] migrate ${s}: failed`,{error:l}),c(`failed \u2014 ${ie(l)}`),1)}finally{await i.close().catch(()=>{})}}async function fs(t){let e=t.PALBASE_URL,s=t.PALBASE_SECRET_KEY;if(!e||!s)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let r=_({url:e,secretKey:s}).fields;return await r.load(),r.close(),r}async function gs(t,e,s){try{return await t.start(e)}catch(r){if(!(r instanceof is)||s!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return d.warn(`[palbase] migrate start: the migration ${r.openedBy} opened (version ${r.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var ms=(t,e)=>{process.stdout.write(t,()=>e())};function R(t,e,s=ms){return new Promise(r=>s(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
1
|
+
/*! palbase 0.19.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{$ as It,A as dt,B as F,C as ut,D as pt,E as ft,F as gt,G as mt,H as bt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as Tt,R as _t,S as xt,T as Rt,U as Ot,V as Ct,W as Bt,X as Ft,Y as se,Z as Mt,_ as $t,a as Q,aa as Lt,b as X,ba as Ut,c as Z,ca as Dt,d as Ne,da as jt,e as qe,ea as Nt,f as We,fa as qt,g as Ke,ga as M,h as Ve,ha as Gt,i as Ge,ia as $,j as ze,ja as V,k as He,ka as zt,l as Ye,la as Ht,m as Je,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as st,t as rt,u as nt,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/AFNLDC5V.js";import{a as Wt,b as Kt}from"../chunks/63ALEOYV.js";import{a as ne}from"../chunks/HNFLACEJ.js";import{a as x,b as ee,c as te,f as m,g as ht,h as d,j as re,k as Vt}from"../chunks/PLAWOADG.js";import"../chunks/MLQQWG2B.js";import"../chunks/M23DJASA.js";import{d as _,j as De,k as je,l as H,m as B,t as Y,u as J}from"../chunks/OSREI5EV.js";import"../chunks/EEZBV4BZ.js";import"../chunks/KLXOLRFH.js";import"../chunks/LH6MM4NX.js";import{o as Ue}from"../chunks/AJUTYIGD.js";import"../chunks/34FI7FDO.js";import{b as A,c as K}from"../chunks/65XX646N.js";import"../chunks/5IKIPSPK.js";import"../chunks/2D6UTNAS.js";import"reflect-metadata";import{existsSync as G,writeFileSync as xs,writeSync as Rs}from"node:fs";import{createServer as Os}from"node:http";import{dirname as k,join as z,resolve as xe}from"node:path";import{Readable as Cs}from"node:stream";var Yt=2e3,Jt=1e4,Qt=/^[A-Za-z0-9_-]{1,64}$/,Xt=512,I=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,s={}){this.sink=e,this.linesPerSecond=s.linesPerSecond??10,this.batchSize=Math.min(100,s.batchSize??100),this.flushMs=s.flushMs??2e3,this.maxPending=s.maxPending??2e3,this.sendMs=s.sendMs??Jt,this.shutdownMs=s.shutdownMs??Yt,this.now=s.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,s,r=new Promise(a=>s=a),n=setTimeout(()=>{e=!0,s()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),r]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,s=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),s>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${s} dropped`)}log(e){let s=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(s-this.refilled)/1e3*this.linesPerSecond),this.refilled=s,this.unlogged>0&&s-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=s),this.tokens<1){this.unlogged===0&&(this.unloggedSince=s),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[r](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Qt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Xt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),s=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let n=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await s.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let i=a.status,o=i??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Zt}from"node:crypto";import{bind as es,bunDriver as ts,createDatabase as ss,envBlock as rs,createSearchWorker as ns,cutOff as as,forgetUser as os,MigrationOpen as is,MigrationRefused as ls,Migrator as ce,renewingBunPool as ae,VersionNotMigrated as cs}from"palgres";import{toModel as de}from"palgres/dsl";var ds=["start","complete","rollback","plan","status","types"],us=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function ue(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!ds.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let s of e)if(s.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function U(t){return de(pe(t))}function ps(t){return t.tables.some(e=>e.search!==void 0)}function D(t){return t.tables.some(e=>!e.ignored&&e.columns.some(s=>s.user!==void 0&&!s.ignored))}function he(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let s=Number(e);if(!Number.isSafeInteger(s)||s<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return s}function hs(t){if(!Number.isSafeInteger(t)||t<3)throw new Error(`[palbase] db.driver: a pool of ${t} connection(s) \u2014 the engine needs at least 3: one request's transaction and the two further ones it may hold`);let e=Math.floor(t/3);return{concurrency:e,nestedConcurrency:e*2}}var oe=5;function fe(t,e){if(t.driver)return t.driver;let s=globalThis.Bun;if(!s)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let r=e-1;return n=>{let a=ae(()=>new s.SQL({url:n,prepare:!1,max:r})),i=ae(()=>new s.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:ts(a,i),poolSize:r,close:async()=>{await a.close({timeout:oe}),await i.close({timeout:oe})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await R(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function me(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let s=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await R("types",rs(s,{module:"palbase/backend/env"}),e),0}async function be(t,e,s){let r=e.PALBASE_DB_OWNER_URL;if(!r)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!us.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=fe(t,he(e)),i=a(r),o,c=l=>d.error(`[palbase] migrate ${s}: ${l}`);try{let l=U(t),u=new ce(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let g=new URL(r);g.pathname=`/${f}`;let y=a(g.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>fs(e)});if(s==="plan"){let f=await u.plan(l);return await R(s,f),f.refusals.length>0?1:0}if(s==="status")return await R(s,await u.status()),0;let h=s==="start"?await gs(u,l,n):s==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${s}: done`,{result:h}),await R(s,h),0}catch(l){return l instanceof ls?(d.error(`[palbase] migrate ${s}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):as(l)?(d.error(`[palbase] migrate ${s}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??ie(l)}`),75):(d.error(`[palbase] migrate ${s}: failed`,{error:l}),c(`failed \u2014 ${ie(l)}`),1)}finally{await i.close().catch(()=>{})}}async function fs(t){let e=t.PALBASE_URL,s=t.PALBASE_SECRET_KEY;if(!e||!s)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let r=_({url:e,secretKey:s}).fields;return await r.load(),r.close(),r}async function gs(t,e,s){try{return await t.start(e)}catch(r){if(!(r instanceof is)||s!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return d.warn(`[palbase] migrate start: the migration ${r.openedBy} opened (version ${r.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var ms=(t,e)=>{process.stdout.write(t,()=>e())};function R(t,e,s=ms){return new Promise(r=>s(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
3
3
|
`,r))}function ie(t){return(t instanceof Error?t.message:String(t)).split(`
|
|
4
4
|
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function bs(t,e){try{return await new ce(t).plan(e)}catch{return}}var le="palbase.idempotency_keys.response_body";function ys(t,e){let s=null,r=!1,n=async()=>{let o=e.currentKey();if(!(r||o===s)){r=!0;try{let c=await t.reseal();s=o;let l=c.reduce((u,h)=>u+h.resealed,0);l>0&&d.info(`[palbase] fields: ${l} value(s) sealed again with key ${o}`,{report:c})}catch(c){d.warn(`[palbase] fields: sealing again with key ${o} stopped; tried again in a minute`,{error:c})}finally{r=!1}}},a=setTimeout(n,1e4),i=setInterval(n,6e4);for(let o of[a,i])o.unref?.();return()=>{clearTimeout(a),clearInterval(i)}}var L=class extends Error{digest;plan;constructor(e,s){super([`[palbase] this schema (${e}) has no version in the database yet: palbase db:push tries it there (a database of your own: palbase db:push --url <its address>)`,...s?ws(s):[" palbase db:plan says what it would change"]].join(`
|
|
5
5
|
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=s}};function ws(t){let e=[t.adoption?` takes the database over as version 1${t.to>1?`, then version 1 \u2192 ${t.to}`:""}`:` version ${t.from??"none"} \u2192 ${t.to}`];t.changes.length===0&&t.refusals.length===0&&e.push(" nothing to change");for(let s of t.changes)e.push(` + ${s}`);for(let s of t.refusals)e.push(` \u2717 ${s}`);return e}var Ps=8e4;async function ye(t,e,s,r){let n=t.url??e.PALBASE_DB_URL;if(!n)throw new Error("[palbase] db.url / PALBASE_DB_URL is the database the app connects to");let a=pe(t),i=de(a),o=fe(t,he(e))(n);try{let c=!1,l=p=>{c||(c=!0,d.warn(`[palbase] database: not answering yet (${p instanceof Error?p.message:String(p)}) \u2014 waiting for it, as one waking does`))},u=await es(o.engine,i,{waitMs:r.onPlatform?Ps:0,onUnreachable:l}).catch(async p=>{throw r.onPlatform||!(p instanceof cs)?p:new L(p.digest,await bs(o.pool,i))}),h=Zt("sha256",s).update("palgres page cursor").digest("hex"),f=t.embed??r.embed,g=r.fields,y=await ss({sql:o.engine,schemas:a,binding:u,cursorSecret:h,admission:hs(o.poolSize),embed:f,log:p=>d.warn(`[palbase] ${p}`),fields:async()=>(await g.load(),g)}),S=g.loaded?ys(y,g):()=>{},b=ps(i)?ns({sql:o.engine,embed:f,log:p=>d.info(`[palbase] ${p}`)}):void 0;return{model:i,binding:u,app:y,requests:t.requests??"caller",forget:p=>os(o.engine,u,i,p),...b?{search:b}:{},keptAnswers:{seal:p=>g.loaded?g.encrypt(le,p):p,open:async p=>g.isEncrypted(p)?(g.loaded||await g.load(),g.decrypt(le,p)):p},close:async()=>{S(),g.close(),await o.close()}}}catch(c){throw await o.close(),c}}function Ss(t){let e=Buffer.from(t,"base64"),s=new Array(e.byteLength/4);for(let r=0;r<s.length;r++)s[r]=e.readFloatLE(r*4);return s}function we(t){return async({texts:e,model:s,dimensions:r})=>{let{data:n}=await t.ai.createEmbeddings({body:{input:e,model:s,dimensions:r}});return{model:n.model,vectors:n.vectors.map(Ss)}}}var vs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Pe(t,e,s){let r=[],n=t.url??e.PALBASE_URL??"",a="";try{let u=new URL(n);a=u.origin,u.protocol!=="https:"&&u.hostname!=="localhost"&&u.hostname!=="127.0.0.1"&&r.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(u.pathname!=="/"||u.search||u.hash)&&r.push("palbase.url / PALBASE_URL is the project origin alone")}catch{r.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let i=t.projectId??e.PALBASE_PROJECT_ID??"";vs.test(i)||r.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let o=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(o)||r.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let c=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;c!==void 0&&!/^[0-9a-f]{64}$/.test(c)&&r.push("palbase.platformSecret / PALBASE_PLATFORM_SECRET is the key the platform signs its calls to this machine with (64 hex characters): the platform sets it, unset off the platform");let l=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(s.needsWebhookSecret&&(c!==void 0||l!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(l??"")&&r.push("palbase.webhookSecret / PALBASE_WEBHOOK_SECRET is the project's webhook endpoint secret (whsec_\u2026): the platform delivers this app events \u2014 its @On handlers', or user.deleted for the users its tables keep"),r.length>0)throw new Error(`[palbase] the app cannot start:
|
|
@@ -9,4 +9,4 @@ ${r.join(`
|
|
|
9
9
|
`)}
|
|
10
10
|
`}function Ae(t,e,s=ks){let r=Buffer.from(e,"utf8"),n=new Int32Array(new SharedArrayBuffer(4));for(let a=0;a<r.length;)try{a+=s(t,r,a,r.length-a)}catch(i){if(i.code!=="EAGAIN")throw i;Atomics.wait(n,0,0,5)}}var ke=2e4,Ee=5e3,Bs=15e3,Fs="/_palbase/health";function Ms(t){let e=new Set,s=r=>{if(e.has(r))return!1;e.add(r);let n=F(r,Q);return n?n.providers.some(a=>F(a,X)!==void 0&&F(a,Z)===void 0)||n.imports.some(s):!1};return t.some(s)}var $s={async create(t,e={}){let s=Array.isArray(t)?t:[t],r=e.env??process.env,n=ue(r);if(n!==void 0){let w=n==="types"?await me(e.db):e.db?await be(e.db,r,n):await ge(n);throw process.exit(w),new j(w)}let a=r.PALBASE_CONTRACT_OUT;if(a){let w;try{await _e(Te(r)),w=await Is(s,e,r)}catch(v){throw Rs(2,`[palbase] the contract: ${v instanceof Error?v.message:String(v)}
|
|
11
11
|
`),process.exit(1),new O}throw a==="/dev/stdout"?Ae(1,ve(w)):xs(a,`${w}
|
|
12
|
-
`),process.exit(0),new O}let i=Te(r),o=await _e(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),re(o?void 0:i);let c=e.db?U(e.db):void 0,l=await J({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Ms(s)||c!==void 0&&D(c),h=Pe(e.palbase??{},r,{needsWebhookSecret:u});u&&h.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=_({url:h.url,secretKey:h.secretKey}),g=e.port??Number(r.PORT??"8080");if(!Number.isInteger(g)||g<0||g>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??r.PORT)}`);let y=e.db?await ye(e.db,r,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&D(y.model)?{"user.deleted":[w=>Ls(y,w)]}:void 0,b=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new I(f.analytics),C=()=>$({modules:s,verifier:new B({issuer:h.url,projectId:h.projectId,standing:H({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:r,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:js(e.cors,r.PALBASE_WEB_ORIGINS),platform:b,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),T=C(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await T.start();break}catch(v){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:v}),await new Promise(Le=>setTimeout(Le,W)),W*=2,T=C()}return Us(T,f,g,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Te(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let s=k(xe(e));for(;!G(z(s,"package.json"))&&k(s)!==s;)s=k(s);return G(z(s,"package.json"))?s:process.cwd()}async function _e(t){try{return await ne(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Is(t,e,s){let r=xe(s.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(r))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${r||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=k(r);for(;!G(z(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/PRIISRPI.js"),{routeContracts:i}=await import("../chunks/V6TFL4HC.js"),o=a(n,r);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=$({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:_({url:c,secretKey:"pb_contract_s"}),env:s,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:se()},events:e.db&&D(U(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var O=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Ls(t,e){let s=e.data?.user_id;if(typeof s!="string"||s==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(s);d.info(`[palbase] user ${s} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them`)}async function Us(t,e,s,r,n,a){let i,o={on:!1},c=(b,p)=>new URL(b.url).pathname===Fs&&b.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(b,p),l=Os((b,p)=>{Ds(c,b,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((b,p)=>{l.once("error",p),l.listen(s,r,()=>b())})}catch(b){throw await t.stop(),await a?.close(),b}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=b=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(T=>l.close(()=>T()));l.closeIdleConnections();let C=setTimeout(()=>l.closeAllConnections(),b);await p,clearTimeout(C),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(ke),g=!1,y=()=>{if(g){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}g=!0;let b=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},ke+Bs);b.unref(),f().then(()=>{clearTimeout(b),process.exit(0)},p=>{clearTimeout(b),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=b=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:b});let p=setTimeout(()=>process.exit(1),Ee+1e3);h(Ee).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Ds(t,e,s,r){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{s.statusCode=400,s.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let g of f)i.append(h,g);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;s.on("close",()=>{s.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?Cs.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress});if(s.statusCode=u.status,u.headers.forEach((h,f)=>s.setHeader(f,h)),r.on&&s.setHeader("connection","close"),u.body)for await(let h of u.body)s.write(h);s.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),s.headersSent||(s.statusCode=500),s.end()}}function js(t,e,s=r=>console.warn(r)){let r=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(r.length===0||t?.origins==="*")return t;let n=r.filter(o=>V(o)),a=r.filter(o=>!V(o));a.length>0&&s(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as Jr,boolean as Qr,check as Xr,date as Zr,defineSchema as en,defineTable as tn,enumType as sn,foreignKey as rn,index as nn,integer as an,jsonb as on,numeric as ln,ownedByUser as cn,policy as dn,raw as un,sqlType as pn,text as hn,timestamp as fn,userRef as gn,uuid as mn}from"palgres/dsl";import{increment as yn,now as wn}from"palgres";function E(t){if(t instanceof A)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let s=await t();return{data:await e(s.data),error:null,status:s.status}}catch(s){return E(s)}}var Ns=x("Secrets",{async get(t){if(Y(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),qs=100,Ws=1e3,Ks=168*3600,Vs={s:1,m:60,h:3600,d:86400};function Gs(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let s=0;for(let[,r,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))s+=Math.round(Number(r)*Vs[n]*1e3);return Math.ceil(s/1e3)}function $e(t,e,s){let r="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(r,"path",i)).join("%2F")}catch(i){throw i instanceof A&&i.code==="invalid_path_parameter"?new A({op:r,status:0,code:"invalid_path_parameter",message:`${r}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${m.url}/storage/public/${K(r,"bucket",t)}/${n}`;return s?`${a}?variant=${encodeURIComponent(s)}`:a}function Re(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function zs(t){return{async upload(e,s,r){let n=r?.contentType??(s instanceof Blob&&s.type!==""?s.type:void 0);try{let a=await m.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:s,contentType:n});return{data:Re(a.data),error:null,status:a.status}}catch(a){return a instanceof A&&a.status===412&&a.code==="object_exists"?{data:null,error:{code:"already_exists",message:"An object already exists at that path: upload with { upsert: true } to replace it"},status:409}:E(a)}},async download(e){try{let s=await m.storage.getObject({path:{bucket:t,path:e}});if(s.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=s.data;try{return{data:await r.blob(),error:null,status:s.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(s){return E(s)}},getPublicUrl(e,s){return $e(t,e,s?.variant)},async createSignedUrl(e,s){let r=Gs(s?.expiresIn);return r===void 0||r<1||r>Ks?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(s?.expiresIn)})`},status:400}:P(()=>m.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,s){let r=s?.limit??qs,n=s?.offset??0;if(!Number.isInteger(r)||r<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<r;){let c=Math.max(1,Math.min(Ws,n+r-a.length)),l=await m.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<r&&a.push(Re(u));if(i=l.data.next_cursor,!i)break}}catch(c){return E(c)}return{data:a,error:null,status:o}},async remove(e){let s=[];for(let r of e){try{await m.storage.deleteObject({path:{bucket:t,path:r}})}catch(n){return E(n)}s.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:s,error:null,status:200}},move(e,s){return P(()=>m.storage.moveObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})},copy(e,s){return P(()=>m.storage.copyObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})}}}var Hs={bucket:zs},Oe=t=>ee("Storage",t,Hs),Ys={bucket:t=>Oe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Oe("buckets").bucket(e):void 0})},Js=x("Notifications",{push:{send(t){let{to:e,...s}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>m.notify.sendPush({body:{...s,to:r}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:s,...r}=t,n={...r,...s!==void 0?{template:s}:{}};if(!Array.isArray(e))return P(()=>m.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await m.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return E(c)}return{data:{message_ids:a},error:null,status:i}}}}),Ce=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Be=t=>typeof t=="string"?{name:t}:null,Fe=t=>t==="override"?"user":t,Qs=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Ie(){return te.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Ie();return P(()=>e?m.flags.getUserValues({path:{user_id:e}}):m.flags.getValues(),s=>s.values??{})}var Me={setOverrideForUser:(t,e,s)=>P(()=>m.flags.putUserValue({path:{user_id:t,key:e},body:{value:s}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),setOverridesForUser:(t,e)=>P(()=>m.flags.putUserValues({path:{user_id:t},body:{values:e}}),s=>({values:s.values??{}})),clearOverrideForUser:(t,e)=>P(()=>m.flags.deleteUserValue({path:{user_id:t,key:e}}),s=>({key:s.key,value:s.value,source:Fe(s.source)})),clearAllOverridesForUser:t=>P(()=>m.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>m.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Xs=x("Flags",{async isEnabled(t,e){let s=r=>(d.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await N(e);return r.error?s(`${r.error.code}: ${r.error.message}`):Ce(r.data[t])}catch(r){return s(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let s=await N(e);return s.error?{data:null,error:s.error,status:s.status}:{data:Be(s.data[t]),error:null,status:s.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([s,r])=>{let n=Be(r);return{name:s,enabled:Ce(r),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,s){let r,n=!1,a;s!==void 0?(r=e,n=!0,a=s):Qs(e)?a=e:e!==void 0&&(r=e,n=!0);let i=await N(a);if(i.error)return n?{data:r??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?r??null:o,error:null,status:i.status}},async setOverride(t,e){let s=Ie();return s?Me.setOverrideForUser(s,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Me}}),Zs=x("Realtime",{broadcast(t,e,s){return P(()=>m.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:s??{}}]}}),()=>{})},state:{set(t,e,s){return P(()=>m.realtime.writeState({body:{ops:[{topic:t,key:e,value:s}]}}),()=>{})},clear(t,e){return P(()=>m.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as _n}from"zod";export{nt as AttestedDevice,je as AuthUnavailable,At as Authorize,$t as BadRequest,He as Body,zt as CACHE_MAX_TTL,Ht as Cache,Pt as ChatPart,rt as Client,It as Conflict,O as ContractRunEnded,Ne as Controller,ct as Cron,ht as Database,Lt as DeadlockDetected,Ge as Delete,Ot as DiError,Ue as EVENT_TYPES,Xs as Flags,Ft as Forbidden,vt as Gateway,St as GatewayRefusal,qe as Get,Je as Headers,Ut as HttpError,ot as Injectable,d as Log,Gt as MAX_BODY_BYTES,j as MigrationRunEnded,it as Module,Dt as NotFound,Js as Notifications,lt as On,Et as OnConnect,Tt as OnDisconnect,_t as OnEmpty,kt as OnFirst,Ze as OptionalUser,Ct as PalError,m as Palbase,A as PalbaseError,$s as PalbaseFactory,Qe as Param,Ve as Patch,We as Post,Ke as Put,ze as Query,Ye as QueryParams,Zs as Realtime,et as Req,tt as RequestId,at as Resolve,L as SchemaNotPushed,Ns as Secrets,jt as SerializationFailure,Ys as Storage,xt as Subscribe,gt as Task,ft as TaskFailure,mt as Tasks,bt as TestUserTemplate,De as TokenError,B as TokenVerifier,Nt as TooManyRequests,st as TraceId,Bt as Unauthorized,qt as UniqueViolation,yt as Upload,wt as UploadedObject,Xe as User,dt as Webhook,Jr as bigint,Qr as boolean,Xr as check,$ as createApp,Zr as date,Mt as defineError,en as defineSchema,tn as defineTable,Kt as encrypt,Wt as encrypted,sn as enumType,rn as foreignKey,ut as getRegisteredControllers,pt as getRoutes,Rt as getWebhookManifest,yn as increment,nn as index,an as integer,on as jsonb,wn as now,ln as numeric,cn as ownedByUser,dn as policy,un as raw,pn as sqlType,Vt as t,hn as text,fn as timestamp,gn as userRef,mn as uuid,_n as z};
|
|
12
|
+
`),process.exit(0),new O}let i=Te(r),o=await _e(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),re(o?void 0:i);let c=e.db?U(e.db):void 0,l=await J({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Ms(s)||c!==void 0&&D(c),h=Pe(e.palbase??{},r,{needsWebhookSecret:u});u&&h.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=_({url:h.url,secretKey:h.secretKey}),g=e.port??Number(r.PORT??"8080");if(!Number.isInteger(g)||g<0||g>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??r.PORT)}`);let y=e.db?await ye(e.db,r,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&D(y.model)?{"user.deleted":[w=>Ls(y,w)]}:void 0,b=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new I(f.analytics),C=()=>$({modules:s,verifier:new B({issuer:h.url,projectId:h.projectId,standing:H({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:r,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:js(e.cors,r.PALBASE_WEB_ORIGINS),platform:b,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),T=C(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await T.start();break}catch(v){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:v}),await new Promise(Le=>setTimeout(Le,W)),W*=2,T=C()}return Us(T,f,g,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Te(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let s=k(xe(e));for(;!G(z(s,"package.json"))&&k(s)!==s;)s=k(s);return G(z(s,"package.json"))?s:process.cwd()}async function _e(t){try{return await ne(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Is(t,e,s){let r=xe(s.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(r))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${r||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=k(r);for(;!G(z(n,"package.json"))&&k(n)!==n;)n=k(n);let{analyzeProject:a}=await import("../chunks/GYAC4XGQ.js"),{routeContracts:i}=await import("../chunks/EOMNR25V.js"),o=a(n,r);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=$({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:_({url:c,secretKey:"pb_contract_s"}),env:s,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:se()},events:e.db&&D(U(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var O=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Ls(t,e){let s=e.data?.user_id;if(typeof s!="string"||s==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(s);d.info(`[palbase] user ${s} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them`)}async function Us(t,e,s,r,n,a){let i,o={on:!1},c=(b,p)=>new URL(b.url).pathname===Fs&&b.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(b,p),l=Os((b,p)=>{Ds(c,b,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((b,p)=>{l.once("error",p),l.listen(s,r,()=>b())})}catch(b){throw await t.stop(),await a?.close(),b}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=b=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(T=>l.close(()=>T()));l.closeIdleConnections();let C=setTimeout(()=>l.closeAllConnections(),b);await p,clearTimeout(C),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(ke),g=!1,y=()=>{if(g){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}g=!0;let b=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},ke+Bs);b.unref(),f().then(()=>{clearTimeout(b),process.exit(0)},p=>{clearTimeout(b),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=b=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:b});let p=setTimeout(()=>process.exit(1),Ee+1e3);h(Ee).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Ds(t,e,s,r){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{s.statusCode=400,s.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let g of f)i.append(h,g);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;s.on("close",()=>{s.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?Cs.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress});if(s.statusCode=u.status,u.headers.forEach((h,f)=>s.setHeader(f,h)),r.on&&s.setHeader("connection","close"),u.body)for await(let h of u.body)s.write(h);s.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),s.headersSent||(s.statusCode=500),s.end()}}function js(t,e,s=r=>console.warn(r)){let r=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(r.length===0||t?.origins==="*")return t;let n=r.filter(o=>V(o)),a=r.filter(o=>!V(o));a.length>0&&s(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as Jr,boolean as Qr,check as Xr,date as Zr,defineSchema as en,defineTable as tn,enumType as sn,foreignKey as rn,index as nn,integer as an,jsonb as on,numeric as ln,ownedByUser as cn,policy as dn,raw as un,sqlType as pn,text as hn,timestamp as fn,userRef as gn,uuid as mn}from"palgres/dsl";import{increment as yn,now as wn}from"palgres";function E(t){if(t instanceof A)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let s=await t();return{data:await e(s.data),error:null,status:s.status}}catch(s){return E(s)}}var Ns=x("Secrets",{async get(t){if(Y(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),qs=100,Ws=1e3,Ks=168*3600,Vs={s:1,m:60,h:3600,d:86400};function Gs(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let s=0;for(let[,r,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))s+=Math.round(Number(r)*Vs[n]*1e3);return Math.ceil(s/1e3)}function $e(t,e,s){let r="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(r,"path",i)).join("%2F")}catch(i){throw i instanceof A&&i.code==="invalid_path_parameter"?new A({op:r,status:0,code:"invalid_path_parameter",message:`${r}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${m.url}/storage/public/${K(r,"bucket",t)}/${n}`;return s?`${a}?variant=${encodeURIComponent(s)}`:a}function Re(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function zs(t){return{async upload(e,s,r){let n=r?.contentType??(s instanceof Blob&&s.type!==""?s.type:void 0);try{let a=await m.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:s,contentType:n});return{data:Re(a.data),error:null,status:a.status}}catch(a){return a instanceof A&&a.status===412&&a.code==="object_exists"?{data:null,error:{code:"already_exists",message:"An object already exists at that path: upload with { upsert: true } to replace it"},status:409}:E(a)}},async download(e){try{let s=await m.storage.getObject({path:{bucket:t,path:e}});if(s.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=s.data;try{return{data:await r.blob(),error:null,status:s.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(s){return E(s)}},getPublicUrl(e,s){return $e(t,e,s?.variant)},async createSignedUrl(e,s){let r=Gs(s?.expiresIn);return r===void 0||r<1||r>Ks?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(s?.expiresIn)})`},status:400}:P(()=>m.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,s){let r=s?.limit??qs,n=s?.offset??0;if(!Number.isInteger(r)||r<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<r;){let c=Math.max(1,Math.min(Ws,n+r-a.length)),l=await m.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<r&&a.push(Re(u));if(i=l.data.next_cursor,!i)break}}catch(c){return E(c)}return{data:a,error:null,status:o}},async remove(e){let s=[];for(let r of e){try{await m.storage.deleteObject({path:{bucket:t,path:r}})}catch(n){return E(n)}s.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:s,error:null,status:200}},move(e,s){return P(()=>m.storage.moveObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})},copy(e,s){return P(()=>m.storage.copyObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})}}}var Hs={bucket:zs},Oe=t=>ee("Storage",t,Hs),Ys={bucket:t=>Oe("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Oe("buckets").bucket(e):void 0})},Js=x("Notifications",{push:{send(t){let{to:e,...s}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>m.notify.sendPush({body:{...s,to:r}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:s,...r}=t,n={...r,...s!==void 0?{template:s}:{}};if(!Array.isArray(e))return P(()=>m.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await m.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return E(c)}return{data:{message_ids:a},error:null,status:i}}}}),Ce=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Be=t=>typeof t=="string"?{name:t}:null,Fe=t=>t==="override"?"user":t,Qs=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Ie(){return te.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Ie();return P(()=>e?m.flags.getUserValues({path:{user_id:e}}):m.flags.getValues(),s=>s.values??{})}var Me={setOverrideForUser:(t,e,s)=>P(()=>m.flags.putUserValue({path:{user_id:t,key:e},body:{value:s}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),setOverridesForUser:(t,e)=>P(()=>m.flags.putUserValues({path:{user_id:t},body:{values:e}}),s=>({values:s.values??{}})),clearOverrideForUser:(t,e)=>P(()=>m.flags.deleteUserValue({path:{user_id:t,key:e}}),s=>({key:s.key,value:s.value,source:Fe(s.source)})),clearAllOverridesForUser:t=>P(()=>m.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>m.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Xs=x("Flags",{async isEnabled(t,e){let s=r=>(d.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await N(e);return r.error?s(`${r.error.code}: ${r.error.message}`):Ce(r.data[t])}catch(r){return s(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let s=await N(e);return s.error?{data:null,error:s.error,status:s.status}:{data:Be(s.data[t]),error:null,status:s.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([s,r])=>{let n=Be(r);return{name:s,enabled:Ce(r),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,s){let r,n=!1,a;s!==void 0?(r=e,n=!0,a=s):Qs(e)?a=e:e!==void 0&&(r=e,n=!0);let i=await N(a);if(i.error)return n?{data:r??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?r??null:o,error:null,status:i.status}},async setOverride(t,e){let s=Ie();return s?Me.setOverrideForUser(s,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Me}}),Zs=x("Realtime",{broadcast(t,e,s){return P(()=>m.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:s??{}}]}}),()=>{})},state:{set(t,e,s){return P(()=>m.realtime.writeState({body:{ops:[{topic:t,key:e,value:s}]}}),()=>{})},clear(t,e){return P(()=>m.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as _n}from"zod";export{nt as AttestedDevice,je as AuthUnavailable,At as Authorize,$t as BadRequest,He as Body,zt as CACHE_MAX_TTL,Ht as Cache,Pt as ChatPart,rt as Client,It as Conflict,O as ContractRunEnded,Ne as Controller,ct as Cron,ht as Database,Lt as DeadlockDetected,Ge as Delete,Ot as DiError,Ue as EVENT_TYPES,Xs as Flags,Ft as Forbidden,vt as Gateway,St as GatewayRefusal,qe as Get,Je as Headers,Ut as HttpError,ot as Injectable,d as Log,Gt as MAX_BODY_BYTES,j as MigrationRunEnded,it as Module,Dt as NotFound,Js as Notifications,lt as On,Et as OnConnect,Tt as OnDisconnect,_t as OnEmpty,kt as OnFirst,Ze as OptionalUser,Ct as PalError,m as Palbase,A as PalbaseError,$s as PalbaseFactory,Qe as Param,Ve as Patch,We as Post,Ke as Put,ze as Query,Ye as QueryParams,Zs as Realtime,et as Req,tt as RequestId,at as Resolve,L as SchemaNotPushed,Ns as Secrets,jt as SerializationFailure,Ys as Storage,xt as Subscribe,gt as Task,ft as TaskFailure,mt as Tasks,bt as TestUserTemplate,De as TokenError,B as TokenVerifier,Nt as TooManyRequests,st as TraceId,Bt as Unauthorized,qt as UniqueViolation,yt as Upload,wt as UploadedObject,Xe as User,dt as Webhook,Jr as bigint,Qr as boolean,Xr as check,$ as createApp,Zr as date,Mt as defineError,en as defineSchema,tn as defineTable,Kt as encrypt,Wt as encrypted,sn as enumType,rn as foreignKey,ut as getRegisteredControllers,pt as getRoutes,Rt as getWebhookManifest,yn as increment,nn as index,an as integer,on as jsonb,wn as now,ln as numeric,cn as ownedByUser,dn as policy,un as raw,pn as sqlType,Vt as t,hn as text,fn as timestamp,gn as userRef,mn as uuid,_n as z};
|
package/dist/backend/stack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.19.
|
|
1
|
+
/*! palbase 0.19.2 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.19.
|
|
2
|
-
import{a as u}from"../chunks/
|
|
1
|
+
/*! palbase 0.19.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as u}from"../chunks/HNFLACEJ.js";import{c as p,i as c}from"../chunks/PLAWOADG.js";import"../chunks/MLQQWG2B.js";import{b as l,c as g,d as f,e as y}from"../chunks/B64PN4SN.js";import"../chunks/M23DJASA.js";import"../chunks/EEZBV4BZ.js";import"../chunks/LH6MM4NX.js";import"../chunks/AJUTYIGD.js";import"../chunks/34FI7FDO.js";import"../chunks/65XX646N.js";import"../chunks/5IKIPSPK.js";import"../chunks/2D6UTNAS.js";import"reflect-metadata";import{randomUUID as m}from"node:crypto";import{createFakeClient as w,typedDatabase as d}from"palgres/testing";function T(t,n,a){if(a?.acceptLanguage!==void 0&&a.strings===void 0)throw new TypeError("withServices: acceptLanguage chooses among the languages of a strings table, and none was given \u2014 { strings: await loadStringsTable(appRoot), acceptLanguage }");let{Database:r,...o}=t,e=a?.strings;return p.run({requestId:`test_${m()}`,database:r===void 0?void 0:d(r),services:o,...e!==void 0?{strings:e,locales:c(a?.acceptLanguage??null,e.source),usedLocales:[]}:{}},n)}function b(){let t=new Map,n=new Map,a=[],r=e=>{if(t.has(e))return t.get(e);if(n.has(e))return n.get(e);if(a.includes(e)){let s=[...a.slice(a.indexOf(e)),e].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${s.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}a.push(e);try{let s=Reflect.getMetadata("design:paramtypes",e)??[],i=new e(...s.map(r));return n.set(e,i),i}finally{a.pop()}},o={with(e,s){return t.set(e,s),o},get:e=>r(e)};return o}function h(){let t=w();return{db:d(t),raw:t,queries:t.queries,seed:(n,a)=>t.seed(n,a),inserted:n=>t.inserted(n),updated:n=>t.updated(n),deleted:n=>t.deleted(n)}}export{l as TestApiError,y as api,g as createTestApi,h as fakeDatabase,b as isolated,u as loadStringsTable,f as testRun,T as withServices};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.19.
|
|
1
|
+
/*! palbase 0.19.2 — 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,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.19.
|
|
2
|
-
import{b as c,f as u}from"./
|
|
1
|
+
/*! palbase 0.19.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as c,f as u}from"./65XX646N.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.19.
|
|
2
|
-
import{b as M,c as N,d as T}from"./26R7KNH7.js";import{a as z,f as Q,g as Y,j as Z,k as X,l as ee,o as G,p as te,q as ne}from"./QOUBSZM4.js";import{d as A}from"./Y4THIE6E.js";import{a as b,b as V,c as _,e as j}from"./Z4YKS2EK.js";var l=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 oe(t){return t instanceof l||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function q(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??qe(e,"request_id"),data:E(e,"data"),cause:t};if(t.code==="network_error")return new l("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new l("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new l("attestationRequired",n);if(t.status===401)return new l("unauthorized",n);if(t.status===429)return new l("rateLimited",{...n,retryAfter:Ne(e)??t.retryAfter});let s=Me(e);return t.status===400&&s?new l("validation",{...n,fields:s}):new l("server",n)}function R(t){return t instanceof V||t instanceof Error&&t.name==="PalbaseError"}function se(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 Me(t){let e=E(E(t,"data"),"fields");if(se(e))return e;let n=E(t,"fields");return se(n)?n:void 0}function Ne(t){return re(t,"retry_after")??re(E(t,"data"),"retryAfter")}function E(t,e){if(typeof t=="object"&&t!==null)return t[e]}function re(t,e){let n=E(t,e);return typeof n=="number"?n:void 0}function qe(t,e){let n=E(t,e);return typeof n=="string"?n:void 0}var De=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ke=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__"]),Be=new Set(Ke),Le=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function P(t){return t==="then"||t==="toJSON"||Le.has(t)}function ae(t){return t==="call"||t==="join"||P(t)}function ie(t){return typeof t=="string"&&De.test(t)&&!Be.has(t)&&!P(t)}function de(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function le(t){j(t)}function ce(t){return j(t).origin}var I=class{me;reader;messages=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;taken=[];older=[];oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;told=!1;ended=!1;constructor(e=()=>{},n,s){this.me=e,this.reader=n,this.chatId=s}get hasOlder(){return this.olderLeft}loadOlder(e={}){return this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading}async readOlder(e){if(!this.olderLeft)return!1;let s={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.signal?{signal:e.signal}:{}},r;if(e.load)r=await e.load(s);else{let a=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");r=await this.reader.parts(a,s)}if(this.ended)return!1;let o=(r?.parts??[]).map(a=>M(a)).filter(a=>a!==void 0);return this.older=[...o,...this.older],this.olderCursor=r?.nextCursor,this.olderLeft=typeof r?.nextCursor=="string"&&r.nextCursor!=="",this.refold(),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}refold(){this.messages.clear(),this.responses.clear(),this.order.length=0,this.turn=null,this.goal=null,this.goalWords.clear(),this.voiceWords.clear(),this.voice=null,this.history.clear(),this.forkedFrom=null,this.calls.clear();for(let e of this.older)this.fold(e);for(let e of this.taken)this.fold(e);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;for(let e of[...this.enders])e()}}takePayload(e){let n=M(e);n&&this.take(n)}take(e){if(this.ended)return;this.taken.push(e);let n=e.seq;typeof n=="number"&&n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.fold(e)&&this.changed()}fold(e){switch(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(n.thought.has(e.seq))return!1;n.thought.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:N(n.text),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(n.text),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});break;case"voice":{let n=`${e.voice_id}\0${e.status}`;if(this.voiceWords.has(n))return!1;this.voiceWords.add(n),(e.status==="closed"?this.voice===null||this.voice.voice_id===e.voice_id:!this.voiceWords.has(`${e.voice_id}\0closed`))&&(this.voice=e),this.order.push({type:"voice",event:e});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);n.text=n.text.slice(0,T(n.text,e.offset))+e.text;break}case"reset":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,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);if(n.runId=e.run_id,n.agent=e.name,n.parentId===null){n.parentId=e.parent_response_id;let s=this.order.findIndex(r=>r.type==="response"&&r.key===e.response_id);s>=0&&this.order.splice(s,1)}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=Fe(e),s=this.messages.get(n),r=e.status==="delivered"||e.status==="failed"?e.status:"pending";this.messages.set(n,{clientId:e.client_id,id:e.id??s?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:s?.status==="delivered"?"delivered":r,error:e.error??null,responseId:e.response_id??s?.responseId??null,createdAt:e.created_at??s?.createdAt??"",mine:!1,metadata:e.metadata??s?.metadata??{},history:!1,truncated:!1,kind:e.kind??s?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:s?.voice??null,attachments:e.attachments?ue(e.attachments):s?.attachments??[]}),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}),this.changed()}place(e,n){let s=e.response_id??null,o=s!==null&&![...this.messages.entries()].some(([a,i])=>a!==n&&i.responseId===s)?this.order.findIndex(a=>a.type==="response"&&a.key===s):-1;o>=0?this.order.splice(o,0,{type:"message",key:n}):this.order.push({type:"message",key:n})}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",marks:new Map,thought:new Set,runId:null,agent:null,parentId:null,startedBy:void 0,goal:null},this.responses.set(e,n),this.order.push({type:"response",key:e})),n}changed(){this.snapshot=void 0,!this.told&&(this.told=!0,queueMicrotask(()=>{this.told=!1;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=d=>e!==void 0&&d.startedBy===e,s=new Map;for(let d of this.responses.values()){let u=d.parentId!==null?this.responses.get(d.parentId)??d:d;s.set(d.id,We(d,u.startedBy??null,n(u),d.goal??u.goal))}let r=new Map([...this.messages].map(([d,u])=>[d,e!==void 0&&u.author===e?{...u,mine:!0}:u])),o=[...this.history.entries()].sort(([d],[u])=>d-u).flatMap(([d,u])=>u.map((f,m)=>He(f,`${d}:${m}`,e))),a=[...o];for(let d of this.order)d.type==="goal"?a.push({type:"goal",goal:d.event}):d.type==="voice"?a.push({type:"voice",voice:d.event}):d.type==="message"?a.push({type:"message",message:r.get(d.key)}):this.responses.get(d.key).parentId===null&&a.push({type:"response",response:s.get(d.key)});let i=o.flatMap(d=>d.type==="message"?[d.message]:[]),c=o.flatMap(d=>d.type==="response"?[d.response]:[]),p=[...this.calls.values()].filter(d=>s.get(d.response_id)?.mine===!0);return{items:a,messages:[...i,...r.values()],responses:[...c,...s.values()],turn:this.turn,waiting:{approvals:p.filter(d=>d.status==="awaiting_approval"),outputs:p.filter(d=>d.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Je(this.voice,e):null}}};function Je(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 ue(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 Fe(t){return`${t.author??""}\0${t.client_id}`}function We(t,e,n,s){let r=[...t.marks.values()].map((c,p)=>({m:c,i:p,at:T(t.text,Math.max(0,Number(c.text_offset)||0))}));r.sort((c,p)=>c.at-p.at||c.i-p.i);let o=[],a=[],i=0;for(let{m:c,at:p}of r)p>i&&o.push({type:"text",text:t.text.slice(i,p)}),i=Math.max(i,p),c.type==="thinking"?(o.push({type:"thinking",thinking:c.thinking}),a.push(c.thinking)):o.push(c.type==="tool"?{type:"tool",tool:c}:{type:"agent",agent:c});return i<t.text.length&&o.push({type:"text",text:t.text.slice(i)}),{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 He(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:ue(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var D=[["ApiKeyAuth","userJWT"]];function pe(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:D,answers:{200:"json"},query:s,signal:n.signal})).data;return r.next_cursor===void 0?{parts:r.parts}:{parts:r.parts,nextCursor:r.next_cursor}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:D,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:D,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var $=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},he=new WeakMap;async function fe(t,e,n,s={},r=()=>{},o){let{pattern:a,events:i,messages:c,durable:p,chat:d}=Ue(e),u=Ve(a,n),f=he.get(t);f||he.set(t,f=new Map);let m=f,g=m.get(u)??{count:0};m.set(u,g),g.count++;let y=t.channel(u,p&&s.history!==!1?{after:0}:{});if(d&&!g.chat){let h=n.chatId,k=new I(r,o,typeof h=="string"&&h!==""?h:void 0);g.chat=k,g.unchat=y.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let x=()=>{--g.count>0||(m.delete(u),g.unchat?.(),g.chat?.end(),y.leave())};try{await y.join()}catch{let h=y.state==="refused"?ge(y.refusal,"unavailable"):"socket closed";throw x(),new $(`gateway ${JSON.stringify(u)} was not joined: ${h}`,h)}let C=!1,S=new Set,W=()=>{if(!C){C=!0,Ge();for(let h of[...S])h();x()}},Ge=y.onClosed(W),H=h=>{if(C)return()=>{};let k=y.on("broadcast",v=>{typeof v.event=="string"&&i.has(v.event)&&h(v.event,b(v.payload))}),w=()=>{S.delete(w),k()};return S.add(w),w},U={topic:u,get seq(){return y.logSeq},on(h,k){if(typeof h=="function")return H((w,v)=>h({event:w,payload:v}));if(!i.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no event ${JSON.stringify(String(h))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(a)}: on(${JSON.stringify(h)}, \u2026) takes the function the event is handed to`);return H((w,v)=>{w===h&&k(v)})},off(h){S.has(h)&&h()},async send(h,k){if(!c.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no message ${JSON.stringify(String(h))}`);let w=C?{status:"error",response:{reason:"not joined"}}:await y.push("broadcast",{type:"broadcast",event:h,payload:k});if(w.status==="ok")return b(w.response.reply);let v=ge(w.response,"unavailable");throw new $(`gateway ${JSON.stringify(u)} did not take ${JSON.stringify(h)}: ${v}`,v)},leave:W};return d&&Object.defineProperty(U,"chat",{value:g.chat,enumerable:!0}),U}function Ue(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 Ve(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 ge(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ze=3600*1e3,O=new Map;function Qe(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=O.get(s);if(!n&&r&&Date.now()-r.at<ze)return r.list;let o=(async()=>{let a=te(),i;try{i=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:a},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(c){throw new l("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:c})}try{return await ne(i,e.signer,e.projectId,a)}catch(c){throw new l("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:c})}})();return O.set(s,{list:o,at:Date.now()}),o.catch(()=>{O.get(s)?.list===o&&O.delete(s)}),o}async function ye(t,e,n,s,r,o){let i=(await Qe(t,e,o)).keys[0];return Y(i.kid,i.key,Q(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,n,s,(r,o)=>Z(t.key,r,o))}function me(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):G(e,"/response",n,async(r,o)=>{if(!X(o))throw new l("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ee(t.key,r,o)}catch(a){throw new l("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:a})}})}function we(t){return t instanceof l&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
|
|
1
|
+
/*! palbase 0.19.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as M,c as N,d as T}from"./M23DJASA.js";import{a as z,f as Q,g as Y,j as Z,k as X,l as ee,o as G,p as te,q as ne}from"./KLXOLRFH.js";import{d as A}from"./34FI7FDO.js";import{a as b,b as V,c as _,e as j}from"./65XX646N.js";var l=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 oe(t){return t instanceof l||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function q(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??qe(e,"request_id"),data:E(e,"data"),cause:t};if(t.code==="network_error")return new l("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new l("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new l("attestationRequired",n);if(t.status===401)return new l("unauthorized",n);if(t.status===429)return new l("rateLimited",{...n,retryAfter:Ne(e)??t.retryAfter});let s=Me(e);return t.status===400&&s?new l("validation",{...n,fields:s}):new l("server",n)}function R(t){return t instanceof V||t instanceof Error&&t.name==="PalbaseError"}function se(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 Me(t){let e=E(E(t,"data"),"fields");if(se(e))return e;let n=E(t,"fields");return se(n)?n:void 0}function Ne(t){return re(t,"retry_after")??re(E(t,"data"),"retryAfter")}function E(t,e){if(typeof t=="object"&&t!==null)return t[e]}function re(t,e){let n=E(t,e);return typeof n=="number"?n:void 0}function qe(t,e){let n=E(t,e);return typeof n=="string"?n:void 0}var De=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ke=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__"]),Be=new Set(Ke),Le=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function P(t){return t==="then"||t==="toJSON"||Le.has(t)}function ae(t){return t==="call"||t==="join"||P(t)}function ie(t){return typeof t=="string"&&De.test(t)&&!Be.has(t)&&!P(t)}function de(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function le(t){j(t)}function ce(t){return j(t).origin}var I=class{me;reader;messages=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;taken=[];older=[];oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;told=!1;ended=!1;constructor(e=()=>{},n,s){this.me=e,this.reader=n,this.chatId=s}get hasOlder(){return this.olderLeft}loadOlder(e={}){return this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading}async readOlder(e){if(!this.olderLeft)return!1;let s={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.signal?{signal:e.signal}:{}},r;if(e.load)r=await e.load(s);else{let a=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");r=await this.reader.parts(a,s)}if(this.ended)return!1;let o=(r?.parts??[]).map(a=>M(a)).filter(a=>a!==void 0);return this.older=[...o,...this.older],this.olderCursor=r?.nextCursor,this.olderLeft=typeof r?.nextCursor=="string"&&r.nextCursor!=="",this.refold(),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}refold(){this.messages.clear(),this.responses.clear(),this.order.length=0,this.turn=null,this.goal=null,this.goalWords.clear(),this.voiceWords.clear(),this.voice=null,this.history.clear(),this.forkedFrom=null,this.calls.clear();for(let e of this.older)this.fold(e);for(let e of this.taken)this.fold(e);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;for(let e of[...this.enders])e()}}takePayload(e){let n=M(e);n&&this.take(n)}take(e){if(this.ended)return;this.taken.push(e);let n=e.seq;typeof n=="number"&&n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.fold(e)&&this.changed()}fold(e){switch(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(n.thought.has(e.seq))return!1;n.thought.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:N(n.text),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(n.text),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});break;case"voice":{let n=`${e.voice_id}\0${e.status}`;if(this.voiceWords.has(n))return!1;this.voiceWords.add(n),(e.status==="closed"?this.voice===null||this.voice.voice_id===e.voice_id:!this.voiceWords.has(`${e.voice_id}\0closed`))&&(this.voice=e),this.order.push({type:"voice",event:e});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);n.text=n.text.slice(0,T(n.text,e.offset))+e.text;break}case"reset":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,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);if(n.runId=e.run_id,n.agent=e.name,n.parentId===null){n.parentId=e.parent_response_id;let s=this.order.findIndex(r=>r.type==="response"&&r.key===e.response_id);s>=0&&this.order.splice(s,1)}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=Fe(e),s=this.messages.get(n),r=e.status==="delivered"||e.status==="failed"?e.status:"pending";this.messages.set(n,{clientId:e.client_id,id:e.id??s?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:s?.status==="delivered"?"delivered":r,error:e.error??null,responseId:e.response_id??s?.responseId??null,createdAt:e.created_at??s?.createdAt??"",mine:!1,metadata:e.metadata??s?.metadata??{},history:!1,truncated:!1,kind:e.kind??s?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:s?.voice??null,attachments:e.attachments?ue(e.attachments):s?.attachments??[]}),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}),this.changed()}place(e,n){let s=e.response_id??null,o=s!==null&&![...this.messages.entries()].some(([a,i])=>a!==n&&i.responseId===s)?this.order.findIndex(a=>a.type==="response"&&a.key===s):-1;o>=0?this.order.splice(o,0,{type:"message",key:n}):this.order.push({type:"message",key:n})}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",marks:new Map,thought:new Set,runId:null,agent:null,parentId:null,startedBy:void 0,goal:null},this.responses.set(e,n),this.order.push({type:"response",key:e})),n}changed(){this.snapshot=void 0,!this.told&&(this.told=!0,queueMicrotask(()=>{this.told=!1;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=d=>e!==void 0&&d.startedBy===e,s=new Map;for(let d of this.responses.values()){let u=d.parentId!==null?this.responses.get(d.parentId)??d:d;s.set(d.id,We(d,u.startedBy??null,n(u),d.goal??u.goal))}let r=new Map([...this.messages].map(([d,u])=>[d,e!==void 0&&u.author===e?{...u,mine:!0}:u])),o=[...this.history.entries()].sort(([d],[u])=>d-u).flatMap(([d,u])=>u.map((f,m)=>He(f,`${d}:${m}`,e))),a=[...o];for(let d of this.order)d.type==="goal"?a.push({type:"goal",goal:d.event}):d.type==="voice"?a.push({type:"voice",voice:d.event}):d.type==="message"?a.push({type:"message",message:r.get(d.key)}):this.responses.get(d.key).parentId===null&&a.push({type:"response",response:s.get(d.key)});let i=o.flatMap(d=>d.type==="message"?[d.message]:[]),c=o.flatMap(d=>d.type==="response"?[d.response]:[]),p=[...this.calls.values()].filter(d=>s.get(d.response_id)?.mine===!0);return{items:a,messages:[...i,...r.values()],responses:[...c,...s.values()],turn:this.turn,waiting:{approvals:p.filter(d=>d.status==="awaiting_approval"),outputs:p.filter(d=>d.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Je(this.voice,e):null}}};function Je(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 ue(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 Fe(t){return`${t.author??""}\0${t.client_id}`}function We(t,e,n,s){let r=[...t.marks.values()].map((c,p)=>({m:c,i:p,at:T(t.text,Math.max(0,Number(c.text_offset)||0))}));r.sort((c,p)=>c.at-p.at||c.i-p.i);let o=[],a=[],i=0;for(let{m:c,at:p}of r)p>i&&o.push({type:"text",text:t.text.slice(i,p)}),i=Math.max(i,p),c.type==="thinking"?(o.push({type:"thinking",thinking:c.thinking}),a.push(c.thinking)):o.push(c.type==="tool"?{type:"tool",tool:c}:{type:"agent",agent:c});return i<t.text.length&&o.push({type:"text",text:t.text.slice(i)}),{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 He(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:ue(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var D=[["ApiKeyAuth","userJWT"]];function pe(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:D,answers:{200:"json"},query:s,signal:n.signal})).data;return r.next_cursor===void 0?{parts:r.parts}:{parts:r.parts,nextCursor:r.next_cursor}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:D,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:D,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var $=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},he=new WeakMap;async function fe(t,e,n,s={},r=()=>{},o){let{pattern:a,events:i,messages:c,durable:p,chat:d}=Ue(e),u=Ve(a,n),f=he.get(t);f||he.set(t,f=new Map);let m=f,g=m.get(u)??{count:0};m.set(u,g),g.count++;let y=t.channel(u,p&&s.history!==!1?{after:0}:{});if(d&&!g.chat){let h=n.chatId,k=new I(r,o,typeof h=="string"&&h!==""?h:void 0);g.chat=k,g.unchat=y.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let x=()=>{--g.count>0||(m.delete(u),g.unchat?.(),g.chat?.end(),y.leave())};try{await y.join()}catch{let h=y.state==="refused"?ge(y.refusal,"unavailable"):"socket closed";throw x(),new $(`gateway ${JSON.stringify(u)} was not joined: ${h}`,h)}let C=!1,S=new Set,W=()=>{if(!C){C=!0,Ge();for(let h of[...S])h();x()}},Ge=y.onClosed(W),H=h=>{if(C)return()=>{};let k=y.on("broadcast",v=>{typeof v.event=="string"&&i.has(v.event)&&h(v.event,b(v.payload))}),w=()=>{S.delete(w),k()};return S.add(w),w},U={topic:u,get seq(){return y.logSeq},on(h,k){if(typeof h=="function")return H((w,v)=>h({event:w,payload:v}));if(!i.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no event ${JSON.stringify(String(h))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(a)}: on(${JSON.stringify(h)}, \u2026) takes the function the event is handed to`);return H((w,v)=>{w===h&&k(v)})},off(h){S.has(h)&&h()},async send(h,k){if(!c.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no message ${JSON.stringify(String(h))}`);let w=C?{status:"error",response:{reason:"not joined"}}:await y.push("broadcast",{type:"broadcast",event:h,payload:k});if(w.status==="ok")return b(w.response.reply);let v=ge(w.response,"unavailable");throw new $(`gateway ${JSON.stringify(u)} did not take ${JSON.stringify(h)}: ${v}`,v)},leave:W};return d&&Object.defineProperty(U,"chat",{value:g.chat,enumerable:!0}),U}function Ue(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 Ve(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 ge(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ze=3600*1e3,O=new Map;function Qe(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=O.get(s);if(!n&&r&&Date.now()-r.at<ze)return r.list;let o=(async()=>{let a=te(),i;try{i=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:a},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(c){throw new l("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:c})}try{return await ne(i,e.signer,e.projectId,a)}catch(c){throw new l("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:c})}})();return O.set(s,{list:o,at:Date.now()}),o.catch(()=>{O.get(s)?.list===o&&O.delete(s)}),o}async function ye(t,e,n,s,r,o){let i=(await Qe(t,e,o)).keys[0];return Y(i.kid,i.key,Q(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,n,s,(r,o)=>Z(t.key,r,o))}function me(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):G(e,"/response",n,async(r,o)=>{if(!X(o))throw new l("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ee(t.key,r,o)}catch(a){throw new l("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:a})}})}function we(t){return t instanceof l&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
|
|
3
3
|
`);let n=[],s=this.pending.indexOf(`
|
|
4
4
|
`);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&n.push({event:this.eventName,payload:this.dataLines.join(`
|
|
5
5
|
`)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let 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(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.19.
|
|
1
|
+
/*! palbase 0.19.2 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.19.
|
|
2
|
-
import{b as d,m as k}from"./
|
|
1
|
+
/*! palbase 0.19.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as d,m as k}from"./KLXOLRFH.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.19.
|
|
2
|
-
import{a as g,b}from"./
|
|
1
|
+
/*! palbase 0.19.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as g,b}from"./5IKIPSPK.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=E(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=v(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await $(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status]??(r.ownResponse&&i.status>=200&&i.status<300?"raw":void 0);if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await O(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function $(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:U(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function U(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function E(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function v(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+P(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(e.secretKey??e.token);case"PalbaseBearer":return!!e.token;case"userJWT":return!!a&&!e.token;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):(o==="SecretKeyAuth"||o==="AdminAuth"||o==="PalbaseBearer")&&e.token?n.set("authorization",`Bearer ${e.token}`):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function P(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function O(t,e){let n=await B(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=_(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function B(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function _(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,E as e,R as f};
|