palbase 0.77.0 → 0.78.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai-sdk/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/3I5XH3A3.js +13 -0
- package/dist/chunks/{ONLXIZ6E.js → 3X3ZT72M.js} +2 -2
- package/dist/chunks/{JOVXELK5.js → 5H3UYFOC.js} +2 -2
- package/dist/chunks/5OBOVEK6.js +2 -0
- package/dist/chunks/{BDHVYVWT.js → AKJC5WTU.js} +1 -1
- package/dist/chunks/{ZZNNCI6A.js → AMKY4SZU.js} +2 -2
- package/dist/chunks/{CYNLRAAW.js → B64J3E3T.js} +2 -2
- package/dist/chunks/{AUOFL6RB.js → EFELMJMQ.js} +2 -2
- package/dist/chunks/{7RTPVUIH.js → FOZVJW7G.js} +2 -2
- package/dist/chunks/{QWXF6KWI.js → HHKRAOVG.js} +1 -1
- package/dist/chunks/{GFBWGJW3.js → HVRVTNMI.js} +1 -1
- package/dist/chunks/{FN5763FR.js → JSRN4NOZ.js} +2 -2
- package/dist/chunks/{U4VX7NKX.js → MA74JJUB.js} +2 -2
- package/dist/chunks/{RQJ4MX2H.js → MFWAOKLM.js} +2 -2
- package/dist/chunks/{RRS7TQKX.js → NG4OMSEK.js} +2 -2
- package/dist/chunks/{DENZSXKJ.js → NQUAVRMC.js} +2 -2
- package/dist/chunks/{IZVBCAKH.js → Q3GH7I66.js} +2 -2
- package/dist/chunks/{WXT24CE5.js → QL2UAO36.js} +1 -1
- package/dist/chunks/{G3PH5T6N.js → QOETZ4FB.js} +1 -1
- package/dist/chunks/{ES24JS2D.js → RP2TPMXT.js} +2 -2
- package/dist/chunks/{KLK7HZZ7.js → S7C7NHZI.js} +3 -3
- package/dist/chunks/{FE7ZBADH.js → SHYJVOD2.js} +1 -1
- package/dist/chunks/{34HGL5FX.js → VP3HFVV4.js} +1 -1
- package/dist/chunks/{VOLGPAPR.js → XVJ3CMFN.js} +2 -2
- package/dist/chunks/{F6OGRDZB.js → YQQKZUVS.js} +2 -2
- package/dist/cli.js +4 -2
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai-sdk.js +1 -1
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/payments-ui.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/chats.d.ts +7 -0
- package/types/internal/src/chat.d.ts +28 -0
- package/types/internal/src/modules/ai.d.ts +6 -2
- package/types/web/src/chat.d.ts +20 -0
- package/types/web/src/index.d.ts +1 -1
- package/dist/chunks/4M4GEXJS.js +0 -13
- package/dist/chunks/6WCN7VAZ.js +0 -2
package/dist/ai/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a,b,c,d,e,f,g}from"../chunks/
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a,b,c,d,e,f,g}from"../chunks/S7C7NHZI.js";import"../chunks/B64J3E3T.js";import"../chunks/5OBOVEK6.js";import"../chunks/AKJC5WTU.js";import"../chunks/RP2TPMXT.js";import"../chunks/JSRN4NOZ.js";import"../chunks/XVJ3CMFN.js";import"../chunks/HVRVTNMI.js";import"../chunks/SHYJVOD2.js";export{f as AIResponseError,b as AISchemaError,d as ToolError,e as WorkflowParkedError,g as createAI,a as partial,c as prepare};
|
package/dist/ai-sdk/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import"../chunks/
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import"../chunks/SHYJVOD2.js";function M(s){return typeof process<"u"&&process.env?process.env[s]??"":""}function j(s){let a=(s??M("PALBASE_URL")).trim().replace(/\/+$/,"");if(!a)throw new Error("@palbase/ai-sdk: url or PALBASE_URL is required");return a.endsWith("/ai/v1")?a:`${a}/ai/v1`}function N(s){let a=(s??M("PALBASE_SECRET_KEY")).trim();if(!a)throw new Error("@palbase/ai-sdk: apiKey or PALBASE_SECRET_KEY is required");return a}function x(s,a,t){let u={apikey:s,Authorization:`Bearer ${s}`,"Content-Type":"application/json",...a};return t?.sessionId&&(u["X-Palbase-Session-Id"]=t.sessionId),t?.agent&&(u["X-Palbase-Agent"]=t.agent),t?.userId&&(u["X-Palbase-User-Id"]=t.userId),t?.workspaceId&&(u["X-Palbase-Workspace-Id"]=t.workspaceId),t?.fallbacks?.length&&(u["X-Palbase-Fallbacks"]=t.fallbacks.join(",")),u}function I(s){let a=[];for(let t of s){if(typeof t.content=="string"){a.push({role:t.role,content:t.content});continue}if(t.role==="tool"){for(let g of t.content)a.push({role:"tool",tool_call_id:g.toolCallId??"",content:typeof g.output=="string"?g.output:JSON.stringify(g.output??"")});continue}let u=[],k=[];for(let g of t.content)g.type==="text"&&g.text&&u.push(g.text),g.type==="tool-call"&&k.push({id:g.toolCallId??"",type:"function",function:{name:g.toolName??"",arguments:typeof g.input=="string"?g.input:JSON.stringify(g.input??{})}});let T={role:t.role,content:u.join(`
|
|
3
3
|
`)};k.length>0&&(T.tool_calls=k),a.push(T)}return a}function R(s){switch(s){case"stop":return"stop";case"length":return"length";case"tool_calls":return"tool-calls";case"error":return"error";default:return"unknown"}}function L(s={}){let a=j(s.url),t=N(s.apiKey),u=s.fetch??globalThis.fetch,k=(l,c)=>({specificationVersion:"v2",provider:"palbase",modelId:l,async doGenerate(e){let n={model:l,messages:I(e.prompt),stream:!1};e.maxOutputTokens!==void 0&&(n.max_tokens=e.maxOutputTokens),e.temperature!==void 0&&(n.temperature=e.temperature),e.topP!==void 0&&(n.top_p=e.topP),e.tools?.length&&(n.tools=e.tools.map(i=>({type:"function",function:{name:i.name,description:i.description,parameters:i.inputSchema??{type:"object",properties:{}}}})));let o=await u(`${a}/chat/completions`,{method:"POST",headers:x(t,{...s.headers,...e.headers},c),body:JSON.stringify(n),signal:e.abortSignal});if(!o.ok)throw new Error(`Palbase AI HTTP ${o.status}: ${await o.text()}`);let d=await o.json(),r=d.choices?.[0],p=[];r?.message?.content&&p.push({type:"text",text:r.message.content});for(let i of r?.message?.tool_calls??[])p.push({type:"tool-call",toolCallId:i.id,toolName:i.function.name,input:i.function.arguments});let m=d.usage?.prompt_tokens??0,f=d.usage?.completion_tokens??0;return{content:p,finishReason:R(r?.finish_reason),usage:{inputTokens:m,outputTokens:f,totalTokens:d.usage?.total_tokens??m+f},warnings:[]}},async doStream(e){let n={model:l,messages:I(e.prompt),stream:!0,stream_options:{include_usage:!0}};e.maxOutputTokens!==void 0&&(n.max_tokens=e.maxOutputTokens),e.temperature!==void 0&&(n.temperature=e.temperature),e.topP!==void 0&&(n.top_p=e.topP),e.tools?.length&&(n.tools=e.tools.map(b=>({type:"function",function:{name:b.name,description:b.description,parameters:b.inputSchema??{type:"object",properties:{}}}})));let o=await u(`${a}/chat/completions`,{method:"POST",headers:x(t,{...s.headers,...e.headers},c),body:JSON.stringify(n),signal:e.abortSignal});if(!o.ok||!o.body)throw new Error(`Palbase AI stream HTTP ${o.status}: ${await o.text()}`);let d=o.body.getReader(),r=new TextDecoder,p="",m="stop",f={inputTokens:0,outputTokens:0,totalTokens:0},i=new Map;return{stream:new ReadableStream({async pull(b){for(;;){let v=p.indexOf(`
|
|
4
4
|
`);if(v>=0){let S=p.slice(0,v).trim();if(p=p.slice(v+1),!S.startsWith("data:"))continue;let A=S.slice(5).trim();if(A==="[DONE]"){for(let P of i.values())b.enqueue({type:"tool-call",toolCallId:P.id,toolName:P.name,input:P.args});i.clear(),b.enqueue({type:"finish",finishReason:m,usage:f}),b.close();return}try{let P=JSON.parse(A);if(P.usage){let h=P.usage.prompt_tokens??0,y=P.usage.completion_tokens??0;f={inputTokens:h,outputTokens:y,totalTokens:P.usage.total_tokens??h+y}}for(let h of P.choices??[]){h.finish_reason&&(m=R(h.finish_reason)),h.delta?.content&&b.enqueue({type:"text-delta",id:P.id??"text_0",delta:h.delta.content});for(let y of h.delta?.tool_calls??[]){let _=i.get(y.index)??{id:"",name:"",args:""};y.id&&(_.id=y.id),y.function?.name&&(_.name=y.function.name),y.function?.arguments&&(_.args+=y.function.arguments),i.set(y.index,_)}}}catch{}continue}let{value:$,done:C}=await d.read();if(C){for(let S of i.values())b.enqueue({type:"tool-call",toolCallId:S.id,toolName:S.name,input:S.args});b.enqueue({type:"finish",finishReason:m,usage:f}),b.close();return}p+=r.decode($,{stream:!0})}}})}}}),T=l=>({specificationVersion:"v2",provider:"palbase",modelId:l,maxEmbeddingsPerCall:1024,async doEmbed({values:c,abortSignal:e}){let n=await u(`${a}/embeddings`,{method:"POST",headers:x(t,s.headers),body:JSON.stringify({model:l,input:c}),signal:e});if(!n.ok)throw new Error(`Palbase AI embeddings HTTP ${n.status}: ${await n.text()}`);let o=await n.json();return{embeddings:(o.data??[]).map(d=>d.embedding),usage:{tokens:o.usage?.prompt_tokens??o.usage?.total_tokens??0}}}}),g=l=>({specificationVersion:"v2",provider:"palbase",modelId:l,async doGenerate({prompt:c,n:e=1,size:n,abortSignal:o}){let d=await u(`${a}/images/generations`,{method:"POST",headers:x(t,s.headers),body:JSON.stringify({model:l,prompt:c,n:e,size:n,response_format:"b64_json"}),signal:o});if(!d.ok)throw new Error(`Palbase AI images HTTP ${d.status}: ${await d.text()}`);return{images:((await d.json()).data??[]).map(p=>p.b64_json??p.url??""),warnings:[]}}}),E=l=>({specificationVersion:"v1",provider:"palbase",modelId:l,async doGenerate({audio:c,mediaType:e,language:n,diarization:o,abortSignal:d}){let r=new FormData;r.set("model",l),n&&r.set("language",n),o&&r.set("diarization","true"),r.set("file",new Blob([new Uint8Array(c)],{type:e}),"audio.wav");let p=x(t,s.headers);delete p["Content-Type"];let m=await u(`${a}/audio/transcriptions`,{method:"POST",headers:p,body:r,signal:d});if(!m.ok)throw new Error(`Palbase AI transcription HTTP ${m.status}: ${await m.text()}`);let f=await m.json();return{text:f.text,language:f.language,durationInSeconds:f.duration_seconds,segments:(f.segments??[]).map(i=>({speaker:i.speaker,startSecond:i.start,endSecond:i.end,text:i.text}))}}}),O=l=>({specificationVersion:"v1",provider:"palbase",modelId:l,async doGenerate({text:c,voice:e,outputFormat:n,speed:o,abortSignal:d}){let r=await u(`${a}/audio/speech`,{method:"POST",headers:x(t,s.headers),body:JSON.stringify({model:l,input:c,voice:e,response_format:n??"mp3",speed:o}),signal:d});if(!r.ok)throw new Error(`Palbase AI speech HTTP ${r.status}: ${await r.text()}`);return{audio:new Uint8Array(await r.arrayBuffer()),mediaType:r.headers.get("content-type")??"audio/mpeg"}}}),w=((l,c)=>k(l,c));return w.languageModel=k,w.textEmbeddingModel=T,w.image=g,w.transcription=E,w.speech=O,w}export{L as createPalbase};
|
package/dist/backend/engine.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{ha as w,la as h}from"../chunks/
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{ha as w,la as h}from"../chunks/MFWAOKLM.js";import"../chunks/5H3UYFOC.js";import"../chunks/3X3ZT72M.js";import"../chunks/S7C7NHZI.js";import"../chunks/B64J3E3T.js";import"../chunks/5OBOVEK6.js";import"../chunks/EFELMJMQ.js";import"../chunks/HHKRAOVG.js";import"../chunks/AKJC5WTU.js";import"../chunks/RP2TPMXT.js";import"../chunks/VP3HFVV4.js";import"../chunks/JSRN4NOZ.js";import"../chunks/XVJ3CMFN.js";import"../chunks/HVRVTNMI.js";import"../chunks/SHYJVOD2.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.
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{$ as It,A as $,B as ut,C as dt,D as pt,E as gt,F as mt,G as ft,H as ht,I as bt,J as yt,K as wt,L as kt,M as Pt,N as St,O as vt,P as Rt,Q as At,R as Et,S as _t,T as Ot,U as xt,V as Tt,W as Ct,X as se,Y as Bt,Z as Ft,_ as Lt,a as Z,aa as $t,b as ee,ba as Mt,c as te,ca as Dt,d as Ne,da as Ut,e as qe,ea as jt,f as Ke,fa as M,g as We,ga as Wt,h as Ve,ha as D,i as Ge,ia as G,j as He,ja as Vt,k as ze,ka as Gt,l as Je,m as Ye,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as nt,t as rt,u as st,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/RQJ4MX2H.js";import{a as Nt,b as qt}from"../chunks/JOVXELK5.js";import{a as oe}from"../chunks/WXT24CE5.js";import{a as v,b as ne,c as re,f as c,g as V,h as p,j as ae,k as Kt}from"../chunks/ONLXIZ6E.js";import"../chunks/KLK7HZZ7.js";import"../chunks/CYNLRAAW.js";import"../chunks/6WCN7VAZ.js";import{F as Q,G as X,d as C,j as Ue,k as je,l as Y,m as I}from"../chunks/AUOFL6RB.js";import"../chunks/QWXF6KWI.js";import"../chunks/BDHVYVWT.js";import{t as De}from"../chunks/ES24JS2D.js";import"../chunks/34HGL5FX.js";import"../chunks/FN5763FR.js";import{b as O,c as W}from"../chunks/VOLGPAPR.js";import"../chunks/GFBWGJW3.js";import"../chunks/FE7ZBADH.js";import"reflect-metadata";import{existsSync as z,writeFileSync as $n,writeSync as Mn}from"node:fs";import{createServer as Dn}from"node:http";import{dirname as x,join as J,resolve as Oe}from"node:path";import{Readable as Un}from"node:stream";var Ht=2e3,zt=1e4,Jt=/^[A-Za-z0-9_-]{1,64}$/,Yt=512,U=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,n={}){this.sink=e,this.linesPerSecond=n.linesPerSecond??10,this.batchSize=Math.min(100,n.batchSize??100),this.flushMs=n.flushMs??2e3,this.maxPending=n.maxPending??2e3,this.sendMs=n.sendMs??zt,this.shutdownMs=n.shutdownMs??Ht,this.now=n.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,n,r=new Promise(a=>n=a),s=setTimeout(()=>{e=!0,n()},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(s)}e&&this.letGo()}letGo(){let e=this.inFlight,n=(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`))),n>0&&p.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${n} dropped`)}log(e){let n=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(n-this.refilled)/1e3*this.linesPerSecond),this.refilled=n,this.unlogged>0&&n-this.unloggedSince>=6e4&&(p.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=n),this.tokens<1){this.unlogged===0&&(this.unloggedSince=n),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",s=Math.round(e.durationMs*10)/10;p[r](`${e.method} ${e.path} ${e.status} ${s}ms`,{route:e.endpoint,status:e.status,duration_ms:s,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Jt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Yt),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),n=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let s=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return s.unref?.(),this.sending=(async()=>{try{await n.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let l=a.status,i=l??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),d=a.retryAfter;this.pausedUntil=this.now()+(typeof d=="number"&&d>0?d*1e3:l===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),p.warn(`[palbase] request traces were not sent to analytics (${i}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(s),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 Qt}from"node:crypto";import{readFileSync as Xt}from"node:fs";import{bind as Zt,bunDriver as en,createDatabase as tn,pooledBinding as nn,sayRunning as rn,envBlock as sn,createSearchWorker as an,cutOff as on,forgetUserIn as ln,MigrationOpen as cn,MigrationRefused as un,Migrator as ue,VersionNotMigrated as dn}from"palgres";import{toModel as pn}from"palgres/dsl";var gn=["start","complete","rollback","plan","status","types"],mn=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function de(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!gn.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 n of e)if(n.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 ge(t){let e=t.access;if(e===void 0||typeof e=="string")return e;try{return Xt(e,"utf8")}catch(n){throw new Error(`[palbase] db.access: ${e.href} could not be read (${n instanceof Error?n.message:String(n)}) \u2014 it is the file the app's access schema is in`)}}function F(t){let e=ge(t);return pn(pe(t),e===void 0?{}:{access:e})}function fn(t){return t.tables.some(e=>e.search!==void 0)}function N(t){return t.access!==void 0||t.tables.some(e=>!e.ignored&&e.columns.some(n=>n.user!==void 0&&!n.ignored))}function me(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let n=Number(e);if(!Number.isSafeInteger(n)||n<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 n}function hn(t,e){if(t.url!==void 0||t.driver!==void 0)return;let n=e.PALBASE_DB_POOLED_URL;return n===void 0||n===""?void 0:n}function bn(t){let e=t.PALBASE_DB_POOLED_CONNECTIONS;if(e===void 0||e==="")return 12;let n=Number(e);if(!Number.isSafeInteger(n)||n<4)throw new Error(`[palbase] PALBASE_DB_POOLED_CONNECTIONS is how many pooled connections the app keeps open, 4 at least \u2014 not ${e}`);return n}var yn=2,wn=5e3;async function kn(t,e,n=wn){let r=await t.reserve();try{await r.unsafe(e)}catch(o){throw r.release(),o}let s=r,a=!1,l=!1,i=async()=>{if(s!==void 0)try{await s.unsafe("SELECT 1");return}catch{s.release(),s=void 0}let o=await t.reserve();try{await o.unsafe(e)}catch(g){throw o.release(),g}a?o.release():s=o},d=setInterval(()=>{l||a||(l=!0,i().catch(o=>p.warn(`[palbase] database: the session that says this version runs could not be opened again (${o instanceof Error?o.message:String(o)}) \u2014 tried again in ${n/1e3} s`)).finally(()=>{l=!1}))},n);return d.unref?.(),{stop(){a=!0,clearInterval(d),s?.release(),s=void 0}}}function Pn(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 ie=5;function H(t,e){if(t.driver)return t.driver;let n=globalThis.Bun;if(!n)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 s=>{let a=new n.SQL({url:s,prepare:!1,max:r}),l=new n.SQL({url:s,prepare:!1,max:1});return{pool:{reserve:()=>a.reserve(),unsafe:(i,d)=>a.unsafe(i,d),begin:i=>a.begin(i)},engine:en(a,l),poolSize:r,close:async()=>{await a.close({timeout:ie}),await l.close({timeout:ie})}}}}async function fe(t){return t==="rollback"?(p.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await B(t,{state:"none"}),0):(p.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function he(t,e){if(!t)return p.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let n=Array.isArray(t.schemas)?t.schemas:[t.schemas],r=ge(t);return await B("types",sn(n,{module:"palbase/backend/env",...r===void 0?{}:{access:r}}),e),0}async function be(t,e,n){let r=e.PALBASE_DB_OWNER_URL;if(!r)return p.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let s=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!mn.test(s))return p.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=H(t,me(e)),l=a(r),i,d=o=>p.error(`[palbase] migrate ${n}: ${o}`);try{let o=F(t),g=new ue(l.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(i=f.trim()),p.info(f)},shadow:f=>{let k=new URL(r);k.pathname=`/${f}`;let y=a(k.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:s,fields:()=>Sn(e)});if(n==="plan"){let f=await g.plan(o);return await B(n,f),f.refusals.length>0?1:0}if(n==="status")return await B(n,await g.status()),0;let m=n==="start"?await vn(g,o,s):n==="complete"?await g.complete():await g.rollback();return p.info(`[palbase] migrate ${n}: done`,{result:m}),await B(n,m),0}catch(o){return o instanceof un?(p.error(`[palbase] migrate ${n}: refused`,{refusals:o.refusals}),d(`refused \u2014 ${o.refusals.join("; ")}`),1):on(o)?(p.error(`[palbase] migrate ${n}: cut off; run again, it goes on from where it stopped`,{error:o}),d(`cut off \u2014 ${i??le(o)}`),75):(p.error(`[palbase] migrate ${n}: failed`,{error:o}),d(`failed \u2014 ${le(o)}`),1)}finally{await l.close().catch(()=>{})}}async function Sn(t){let e=t.PALBASE_URL,n=t.PALBASE_SECRET_KEY;if(!e||!n)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=C({url:e,secretKey:n}).fields;return await r.load(),r.close(),r}async function vn(t,e,n){try{return await t.start(e)}catch(r){if(!(r instanceof cn)||n!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return p.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 Rn=(t,e)=>{process.stdout.write(t,()=>e())};function B(t,e,n=Rn){return new Promise(r=>n(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{$ as It,A as $,B as ut,C as dt,D as pt,E as gt,F as mt,G as ft,H as ht,I as bt,J as yt,K as wt,L as kt,M as Pt,N as St,O as vt,P as Rt,Q as At,R as Et,S as _t,T as Ot,U as xt,V as Tt,W as Ct,X as se,Y as Bt,Z as Ft,_ as Lt,a as Z,aa as $t,b as ee,ba as Mt,c as te,ca as Dt,d as Ne,da as Ut,e as qe,ea as jt,f as Ke,fa as M,g as We,ga as Wt,h as Ve,ha as D,i as Ge,ia as G,j as He,ja as Vt,k as ze,ka as Gt,l as Je,m as Ye,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as nt,t as rt,u as st,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/MFWAOKLM.js";import{a as Nt,b as qt}from"../chunks/5H3UYFOC.js";import{a as oe}from"../chunks/QL2UAO36.js";import{a as v,b as ne,c as re,f as c,g as V,h as p,j as ae,k as Kt}from"../chunks/3X3ZT72M.js";import"../chunks/S7C7NHZI.js";import"../chunks/B64J3E3T.js";import"../chunks/5OBOVEK6.js";import{F as Q,G as X,d as C,j as Ue,k as je,l as Y,m as I}from"../chunks/EFELMJMQ.js";import"../chunks/HHKRAOVG.js";import"../chunks/AKJC5WTU.js";import{t as De}from"../chunks/RP2TPMXT.js";import"../chunks/VP3HFVV4.js";import"../chunks/JSRN4NOZ.js";import{b as O,c as W}from"../chunks/XVJ3CMFN.js";import"../chunks/HVRVTNMI.js";import"../chunks/SHYJVOD2.js";import"reflect-metadata";import{existsSync as z,writeFileSync as $n,writeSync as Mn}from"node:fs";import{createServer as Dn}from"node:http";import{dirname as x,join as J,resolve as Oe}from"node:path";import{Readable as Un}from"node:stream";var Ht=2e3,zt=1e4,Jt=/^[A-Za-z0-9_-]{1,64}$/,Yt=512,U=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,n={}){this.sink=e,this.linesPerSecond=n.linesPerSecond??10,this.batchSize=Math.min(100,n.batchSize??100),this.flushMs=n.flushMs??2e3,this.maxPending=n.maxPending??2e3,this.sendMs=n.sendMs??zt,this.shutdownMs=n.shutdownMs??Ht,this.now=n.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,n,r=new Promise(a=>n=a),s=setTimeout(()=>{e=!0,n()},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(s)}e&&this.letGo()}letGo(){let e=this.inFlight,n=(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`))),n>0&&p.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${n} dropped`)}log(e){let n=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(n-this.refilled)/1e3*this.linesPerSecond),this.refilled=n,this.unlogged>0&&n-this.unloggedSince>=6e4&&(p.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=n),this.tokens<1){this.unlogged===0&&(this.unloggedSince=n),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",s=Math.round(e.durationMs*10)/10;p[r](`${e.method} ${e.path} ${e.status} ${s}ms`,{route:e.endpoint,status:e.status,duration_ms:s,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Jt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Yt),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),n=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let s=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return s.unref?.(),this.sending=(async()=>{try{await n.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let l=a.status,i=l??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),d=a.retryAfter;this.pausedUntil=this.now()+(typeof d=="number"&&d>0?d*1e3:l===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),p.warn(`[palbase] request traces were not sent to analytics (${i}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(s),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 Qt}from"node:crypto";import{readFileSync as Xt}from"node:fs";import{bind as Zt,bunDriver as en,createDatabase as tn,pooledBinding as nn,sayRunning as rn,envBlock as sn,createSearchWorker as an,cutOff as on,forgetUserIn as ln,MigrationOpen as cn,MigrationRefused as un,Migrator as ue,VersionNotMigrated as dn}from"palgres";import{toModel as pn}from"palgres/dsl";var gn=["start","complete","rollback","plan","status","types"],mn=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function de(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!gn.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 n of e)if(n.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 ge(t){let e=t.access;if(e===void 0||typeof e=="string")return e;try{return Xt(e,"utf8")}catch(n){throw new Error(`[palbase] db.access: ${e.href} could not be read (${n instanceof Error?n.message:String(n)}) \u2014 it is the file the app's access schema is in`)}}function F(t){let e=ge(t);return pn(pe(t),e===void 0?{}:{access:e})}function fn(t){return t.tables.some(e=>e.search!==void 0)}function N(t){return t.access!==void 0||t.tables.some(e=>!e.ignored&&e.columns.some(n=>n.user!==void 0&&!n.ignored))}function me(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let n=Number(e);if(!Number.isSafeInteger(n)||n<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 n}function hn(t,e){if(t.url!==void 0||t.driver!==void 0)return;let n=e.PALBASE_DB_POOLED_URL;return n===void 0||n===""?void 0:n}function bn(t){let e=t.PALBASE_DB_POOLED_CONNECTIONS;if(e===void 0||e==="")return 12;let n=Number(e);if(!Number.isSafeInteger(n)||n<4)throw new Error(`[palbase] PALBASE_DB_POOLED_CONNECTIONS is how many pooled connections the app keeps open, 4 at least \u2014 not ${e}`);return n}var yn=2,wn=5e3;async function kn(t,e,n=wn){let r=await t.reserve();try{await r.unsafe(e)}catch(o){throw r.release(),o}let s=r,a=!1,l=!1,i=async()=>{if(s!==void 0)try{await s.unsafe("SELECT 1");return}catch{s.release(),s=void 0}let o=await t.reserve();try{await o.unsafe(e)}catch(g){throw o.release(),g}a?o.release():s=o},d=setInterval(()=>{l||a||(l=!0,i().catch(o=>p.warn(`[palbase] database: the session that says this version runs could not be opened again (${o instanceof Error?o.message:String(o)}) \u2014 tried again in ${n/1e3} s`)).finally(()=>{l=!1}))},n);return d.unref?.(),{stop(){a=!0,clearInterval(d),s?.release(),s=void 0}}}function Pn(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 ie=5;function H(t,e){if(t.driver)return t.driver;let n=globalThis.Bun;if(!n)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 s=>{let a=new n.SQL({url:s,prepare:!1,max:r}),l=new n.SQL({url:s,prepare:!1,max:1});return{pool:{reserve:()=>a.reserve(),unsafe:(i,d)=>a.unsafe(i,d),begin:i=>a.begin(i)},engine:en(a,l),poolSize:r,close:async()=>{await a.close({timeout:ie}),await l.close({timeout:ie})}}}}async function fe(t){return t==="rollback"?(p.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await B(t,{state:"none"}),0):(p.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function he(t,e){if(!t)return p.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let n=Array.isArray(t.schemas)?t.schemas:[t.schemas],r=ge(t);return await B("types",sn(n,{module:"palbase/backend/env",...r===void 0?{}:{access:r}}),e),0}async function be(t,e,n){let r=e.PALBASE_DB_OWNER_URL;if(!r)return p.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let s=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!mn.test(s))return p.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=H(t,me(e)),l=a(r),i,d=o=>p.error(`[palbase] migrate ${n}: ${o}`);try{let o=F(t),g=new ue(l.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(i=f.trim()),p.info(f)},shadow:f=>{let k=new URL(r);k.pathname=`/${f}`;let y=a(k.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:s,fields:()=>Sn(e)});if(n==="plan"){let f=await g.plan(o);return await B(n,f),f.refusals.length>0?1:0}if(n==="status")return await B(n,await g.status()),0;let m=n==="start"?await vn(g,o,s):n==="complete"?await g.complete():await g.rollback();return p.info(`[palbase] migrate ${n}: done`,{result:m}),await B(n,m),0}catch(o){return o instanceof un?(p.error(`[palbase] migrate ${n}: refused`,{refusals:o.refusals}),d(`refused \u2014 ${o.refusals.join("; ")}`),1):on(o)?(p.error(`[palbase] migrate ${n}: cut off; run again, it goes on from where it stopped`,{error:o}),d(`cut off \u2014 ${i??le(o)}`),75):(p.error(`[palbase] migrate ${n}: failed`,{error:o}),d(`failed \u2014 ${le(o)}`),1)}finally{await l.close().catch(()=>{})}}async function Sn(t){let e=t.PALBASE_URL,n=t.PALBASE_SECRET_KEY;if(!e||!n)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=C({url:e,secretKey:n}).fields;return await r.load(),r.close(),r}async function vn(t,e,n){try{return await t.start(e)}catch(r){if(!(r instanceof cn)||n!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return p.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 Rn=(t,e)=>{process.stdout.write(t,()=>e())};function B(t,e,n=Rn){return new Promise(r=>n(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
3
3
|
`,r))}function le(t){return(t instanceof Error?t.message:String(t)).split(`
|
|
4
4
|
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function An(t,e){try{return await new ue(t).plan(e)}catch{return}}var ce="palbase.idempotency_keys.response_body";function En(t,e){let n=null,r=!1,s=async()=>{let i=e.currentKey();if(!(r||i===n)){r=!0;try{let d=await t.reseal();n=i;let o=d.reduce((g,m)=>g+m.resealed,0);o>0&&p.info(`[palbase] fields: ${o} value(s) sealed again with key ${i}`,{report:d})}catch(d){p.warn(`[palbase] fields: sealing again with key ${i} stopped; tried again in a minute`,{error:d})}finally{r=!1}}},a=setTimeout(s,1e4),l=setInterval(s,6e4);for(let i of[a,l])i.unref?.();return()=>{clearTimeout(a),clearInterval(l)}}var j=class extends Error{digest;plan;constructor(e,n){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>)`,...n?_n(n):[" palbase db:plan says what it would change"]].join(`
|
|
5
5
|
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=n}};function _n(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 n of t.changes)e.push(` + ${n}`);for(let n of t.refusals)e.push(` \u2717 ${n}`);return e}var On=8e4;async function ye(t,e,n,r){let s=t.url??e.PALBASE_DB_URL;if(!s)throw new Error("[palbase] db.url / PALBASE_DB_URL is the database the app connects to");let a=pe(t),l=F(t),i=hn(t,e),d=H(t,i===void 0?me(e):yn)(s),o,g;try{let m=!1,f=b=>{m||(m=!0,p.warn(`[palbase] database: not answering yet (${b instanceof Error?b.message:String(b)}) \u2014 waiting for it, as one waking does`))},k=await Zt(d.engine,l,{waitMs:r.onPlatform?On:0,onUnreachable:f}).catch(async b=>{throw r.onPlatform||!(b instanceof dn)?b:new j(b.digest,await An(d.pool,l))});i!==void 0&&(g=await kn(d.pool,rn(k)),o=H(t,bn(e))(i));let y=o??d,R=Qt("sha256",n).update("palgres page cursor").digest("hex"),w=t.embed??r.embed,h=r.fields,A=await tn({sql:y.engine,schemas:a,binding:o===void 0?k:nn(k),...o===void 0?{}:{prepare:!1},cursorSecret:R,admission:Pn(y.poolSize),embed:w,log:b=>p.warn(`[palbase] ${b}`),fields:async()=>(await h.load(),h)}),E=h.loaded?En(A,h):()=>{},_=fn(l)?an({sql:y.engine,embed:w,log:b=>p.info(`[palbase] ${b}`)}):void 0;return{model:l,binding:k,app:A,requests:t.requests??"caller",forget:(b,P)=>ln({attempt:S=>P.$attempt(S)},k,l,b),..._?{search:_}:{},keptAnswers:{seal:b=>h.loaded?h.encrypt(ce,b):b,open:async b=>h.isEncrypted(b)?(h.loaded||await h.load(),h.decrypt(ce,b)):b},close:async()=>{E(),h.close(),await o?.close(),g?.stop(),await d.close()}}}catch(m){throw await o?.close().catch(()=>{}),g?.stop(),await d.close(),m}}function xn(t){let e=Buffer.from(t,"base64"),n=new Array(e.byteLength/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function we(t){return async({texts:e,model:n,dimensions:r})=>{let{data:s}=await t.ai.createEmbeddings({body:{input:e,model:n,dimensions:r}});return{model:s.model,vectors:s.vectors.map(xn)}}}var Tn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function ke(t,e,n){let r=[],s=t.url??e.PALBASE_URL??"",a="";try{let g=new URL(s);a=g.origin,g.protocol!=="https:"&&g.hostname!=="localhost"&&g.hostname!=="127.0.0.1"&&r.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(g.pathname!=="/"||g.search||g.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 l=t.projectId??e.PALBASE_PROJECT_ID??"";Tn.test(l)||r.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let i=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(i)||r.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let d=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;d!==void 0&&!/^[0-9a-f]{64}$/.test(d)&&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 o=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(n.needsWebhookSecret&&(d!==void 0||o!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(o??"")&&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
|
`}async function ve(t,e,n=Bn){let r=Buffer.from(e,"utf8");for(let s=0;s<r.length;)try{s+=n(t,r,s,r.length-s)}catch(a){if(a.code!=="EAGAIN")throw a;await new Promise(l=>setTimeout(l,5))}}var Re=2e4,Ae=5e3,jn=15e3,Nn="/_palbase/health";function qn(t){let e=new Set,n=r=>{if(e.has(r))return!1;e.add(r);let s=$(r,Z);return s?s.providers.some(a=>$(a,ee)!==void 0&&$(a,te)===void 0)||s.imports.some(n):!1};return t.some(n)}var Kn={async create(t,e={}){let n=Array.isArray(t)?t:[t],r=e.env??process.env,s=de(r);if(s!==void 0){let P=s==="types"?await he(e.db):e.db?await be(e.db,r,s):await fe(s);throw process.exit(P),new q(P)}let a=r.PALBASE_CONTRACT_OUT;if(a){let P;try{await _e(Ee(r)),P=await Wn(n,e,r)}catch(S){throw Mn(2,`[palbase] the contract: ${S instanceof Error?S.message:String(S)}
|
|
11
11
|
`),process.exit(1),new L}throw a==="/dev/stdout"?await ve(1,Se(P)):$n(a,`${P}
|
|
12
|
-
`),process.exit(0),new L}let l=Ee(r),i=await _e(l);i&&p.info(`[palbase] strings: ${i.source} and ${i.locales.length-1} other language(s), ${Object.keys(i.strings).length} sentence(s), from ${l}/palbase/strings`),ae(i?void 0:l);let d=e.db?F(e.db):void 0,o=await X({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&p.info(`[palbase] secrets: ${o.loaded.length} from the project's ${o.set} set${o.kept.length>0?`; ${o.kept.join(", ")} kept as the environment gives them`:""}`),o&&o.refused.length>0&&p.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(P=>JSON.stringify(P)).join(", ")}`);let g=qn(n)||d!==void 0&&N(d),m=ke(e.palbase??{},r,{needsWebhookSecret:g});g&&m.webhookSecret===void 0&&p.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=C({url:m.url,secretKey:m.secretKey}),k=e.port??Number(r.PORT??"8080");if(!Number.isInteger(k)||k<0||k>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,m.secretKey,{onPlatform:m.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&p.info(`[palbase] database: version ${y.binding.version}`);let R=y&&N(y.model)?{"user.deleted":[P=>Vn(y,P)]}:void 0,w=m.platformSecret===void 0?void 0:{secret:m.platformSecret},h=e.requestTelemetry===!1?void 0:new U(f.analytics),A=()=>D({modules:n,verifier:new I({issuer:m.url,projectId:m.projectId,standing:Y({url:m.url,secretKey:m.secretKey})}),server:f,webhookSecret:m.webhookSecret,env:r,projectId:m.projectId,telemetry:h,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:zn(e.cors,r.PALBASE_WEB_ORIGINS),platform:w,events:R,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:i}),E=A(),_=e.boot?.attempts??5,b=e.boot?.backoffMs??1e3;for(let P=1;;P++)try{await E.start();break}catch(S){if(P>=_)throw p.error(`[palbase] the app did not start after ${_} attempts`,{error:S}),S;p.warn(`[palbase] the app did not start (attempt ${P} of ${_}); trying again in ${b} ms`,{error:S}),await new Promise(Me=>setTimeout(Me,b)),b*=2,E=A()}return Gn(E,f,k,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Ee(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let n=x(Oe(e));for(;!z(J(n,"package.json"))&&x(n)!==n;)n=x(n);return z(J(n,"package.json"))?n:process.cwd()}async function _e(t){try{return await oe(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Wn(t,e,n){let r=Oe(n.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 s=x(r);for(;!z(J(s,"package.json"))&&x(s)!==s;)s=x(s);let{analyzeProject:a}=await import("../chunks/RRS7TQKX.js"),{routeContracts:l}=await import("../chunks/IZVBCAKH.js"),i=a(s,r);for(let g of i.warnings)p.warn(`[palbase] the contract: ${g}`);let d="https://contract.palbase.invalid",o=D({modules:t,verifier:new I({issuer:d,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:C({url:d,secretKey:"pb_contract_s"}),env:n,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 l(i.routes),errors:se()},events:e.db&&N(F(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(o.contract())}var L=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},q=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Vn(t,e){let n=e.data?.user_id;if(typeof n!="string"||n==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(n,V.$asService());p.info(`[palbase] user ${n} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them${r.relationships===void 0?"":`, ${r.relationships} relationship(s) of the access schema taken back`}`)}async function Gn(t,e,n,r,s,a){let l,i={on:!1},d=(w,h)=>new URL(w.url).pathname===Nn&&w.method==="GET"?Promise.resolve(i.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(w,h),o=Dn((w,h)=>{Hn(d,w,h,i).finally(()=>{i.on&&o.closeIdleConnections()})});o.keepAliveTimeout=29e4,o.headersTimeout=3e5;try{await new Promise((w,h)=>{o.once("error",h),o.listen(n,r,()=>w())})}catch(w){throw await t.stop(),await a?.close(),w}let g=o.address().port;p.info(`[palbase] serving ${t.routes.length} route(s) on :${g}`,{routes:t.routes}),a?.search?.start();let m=w=>l??=(async()=>{p.info("[palbase] stopping: finishing the requests in flight"),i.on=!0;let h=new Promise(E=>o.close(()=>E()));o.closeIdleConnections();let A=setTimeout(()=>o.closeAllConnections(),w);await h,clearTimeout(A),process.off("SIGINT",y),process.off("uncaughtException",R),process.off("unhandledRejection",R);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>m(Re),k=!1,y=()=>{if(k){p.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}k=!0;let w=setTimeout(()=>{p.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Re+jn);w.unref(),f().then(()=>{clearTimeout(w),process.exit(0)},h=>{clearTimeout(w),p.error("[palbase] stopping failed; the process ends",{error:h}),process.exit(1)})},R=w=>{p.error("[palbase] the app crashed; stopping so the machine starts it again",{error:w});let h=setTimeout(()=>process.exit(1),Ae+1e3);m(Ae).finally(()=>{clearTimeout(h),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),s&&(process.on("uncaughtException",R),process.on("unhandledRejection",R)),{routes:t.routes,palbase:e,port:g,handle:d,close:f}}async function Hn(t,e,n,r){try{let s=e.url??"/",a;try{if(!s.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${s}`)}catch{n.statusCode=400,n.end();return}let l=new Headers;for(let[m,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let k of f)l.append(m,k);else l.set(m,f);let i=e.method!=="GET"&&e.method!=="HEAD",d=new AbortController;n.on("close",()=>{n.writableFinished||d.abort(new Error("the client closed the connection"))});let o=new Request(a,{method:e.method,headers:l,body:i?Un.toWeb(e):void 0,duplex:"half",signal:d.signal}),g=await t(o,{remoteAddress:e.socket.remoteAddress,target:s});if(n.statusCode=g.status,g.headers.forEach((m,f)=>n.setHeader(f,m)),r.on&&n.setHeader("connection","close"),g.body)for await(let m of g.body)n.write(m);n.end()}catch(s){p.error("[palbase] the request could not be answered",{error:s}),n.headersSent||(n.statusCode=500),n.end()}}function zn(t,e,n=r=>console.warn(r)){let r=(e??"").split(",").map(i=>i.trim()).filter(i=>i!=="");if(r.length===0||t?.origins==="*")return t;let s=r.filter(i=>G(i)),a=r.filter(i=>!G(i));a.length>0&&n(`[palbase] the project's web origins ${a.map(i=>JSON.stringify(i)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let l=[...new Set([...t?.origins??[],...s])];return l.length===0?t:{...t,origins:l}}import{bigint as cs,boolean as us,check as ds,date as ps,defineSchema as gs,defineTable as ms,enumType as fs,foreignKey as hs,index as bs,integer as ys,jsonb as ws,numeric as ks,ownedByUser as Ps,policy as Ss,raw as vs,sqlType as Rs,text as As,timestamp as Es,userRef as _s,uuid as Os}from"palgres/dsl";import{AccessRefused as Ts}from"palgres";import{increment as Bs,now as Fs}from"palgres";function T(t){if(t instanceof O)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function u(t,e){try{let n=await t();return{data:await e(n.data),error:null,status:n.status}}catch(n){return T(n)}}var Jn=v("Secrets",{async get(t){if(Q(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Yn=100,Qn=1e3,Xn=168*3600,Zn={s:1,m:60,h:3600,d:86400};function er(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let n=0;for(let[,r,,s]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))n+=Math.round(Number(r)*Zn[s]*1e3);return Math.ceil(n/1e3)}function Ie(t,e,n){let r="getPublicUrl",s;try{s=String(e).split("/").map(l=>W(r,"path",l)).join("%2F")}catch(l){throw l instanceof O&&l.code==="invalid_path_parameter"?new O({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`}):l}let a=`${c.url}/storage/public/${W(r,"bucket",t)}/${s}`;return n?`${a}?variant=${encodeURIComponent(n)}`:a}function xe(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,Ie(t.bucket,t.path,e)]))}}function tr(t){return{async upload(e,n,r){let s=r?.contentType??(n instanceof Blob&&n.type!==""?n.type:void 0);try{let a=await c.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:n,contentType:s});return{data:xe(a.data),error:null,status:a.status}}catch(a){return a instanceof O&&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}:T(a)}},async download(e){try{let n=await c.storage.getObject({path:{bucket:t,path:e}});if(n.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=n.data;try{return{data:await r.blob(),error:null,status:n.status}}catch(s){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${s instanceof Error?s.message:String(s)}`},status:0}}}catch(n){return T(n)}},getPublicUrl(e,n){return Ie(t,e,n?.variant)},async createSignedUrl(e,n){let r=er(n?.expiresIn);return r===void 0||r<1||r>Xn?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(n?.expiresIn)})`},status:400}:u(()=>c.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),s=>({signedUrl:s.url,expiresAt:s.expires_at}))},async list(e,n){let r=n?.limit??Yn,s=n?.offset??0;if(!Number.isInteger(r)||r<0||!Number.isInteger(s)||s<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],l,i=200;try{for(;a.length<r;){let d=Math.max(1,Math.min(Qn,s+r-a.length)),o=await c.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:d,...l?{cursor:l}:{}}});i=o.status;for(let g of o.data.objects)s>0?s--:a.length<r&&a.push(xe(g));if(l=o.data.next_cursor,!l)break}}catch(d){return T(d)}return{data:a,error:null,status:i}},async remove(e){let n=[];for(let r of e){try{await c.storage.deleteObject({path:{bucket:t,path:r}})}catch(s){return T(s)}n.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:n,error:null,status:200}},move(e,n){return u(()=>c.storage.moveObject({path:{bucket:t},body:{from:e,to:n}}),()=>{})},copy(e,n){return u(()=>c.storage.copyObject({path:{bucket:t},body:{from:e,to:n}}),()=>{})}}}var nr={bucket:tr},Te=t=>ne("Storage",t,nr),rr={bucket:t=>Te("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Te("buckets").bucket(e):void 0})},sr=v("Notifications",{push:{send(t){let{to:e,...n}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return u(()=>c.notify.sendPush({body:{...n,to:r}}),s=>({message_ids:s.message_ids,recipients:s.message_ids.length,skipped_user_ids:s.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:n,...r}=t,s={...r,...n!==void 0?{template:n}:{}};if(!Array.isArray(e))return u(()=>c.notify.sendEmail({body:{...s,to:e}}),i=>({...i.message_id!==void 0?{message_id:i.message_id}:{},...i.skipped?{skipped:!0}:{}}));let a=[],l=202;for(let i of e)try{let d=await c.notify.sendEmail({body:{...s,to:i}});l=d.status,a.push(d.data.message_id??null)}catch(d){return T(d)}return{data:{message_ids:a},error:null,status:l}}}}),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,ar=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function $e(){return re.getStore()?.userId}function K(t){let e=t&&"userId"in t?t.userId??void 0:$e();return u(()=>e?c.flags.getUserValues({path:{user_id:e}}):c.flags.getValues(),n=>n.values??{})}var Le={setOverrideForUser:(t,e,n)=>u(()=>c.flags.putUserValue({path:{user_id:t,key:e},body:{value:n}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),setOverridesForUser:(t,e)=>u(()=>c.flags.putUserValues({path:{user_id:t},body:{values:e}}),n=>({values:n.values??{}})),clearOverrideForUser:(t,e)=>u(()=>c.flags.deleteUserValue({path:{user_id:t,key:e}}),n=>({key:n.key,value:n.value,source:Fe(n.source)})),clearAllOverridesForUser:t=>u(()=>c.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>u(()=>c.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},or=v("Flags",{async isEnabled(t,e){let n=r=>(p.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await K(e);return r.error?n(`${r.error.code}: ${r.error.message}`):Ce(r.data[t])}catch(r){return n(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let n=await K(e);return n.error?{data:null,error:n.error,status:n.status}:{data:Be(n.data[t]),error:null,status:n.status}},async getAll(t){let e=await K(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([n,r])=>{let s=Be(r);return{name:n,enabled:Ce(r),...s?{variant:s}:{}}}),error:null,status:e.status}},async get(t,e,n){let r,s=!1,a;n!==void 0?(r=e,s=!0,a=n):ar(e)?a=e:e!==void 0&&(r=e,s=!0);let l=await K(a);if(l.error)return s?{data:r??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let i=l.data[t];return{data:i===void 0?r??null:i,error:null,status:l.status}},async setOverride(t,e){let n=$e();return n?Le.setOverrideForUser(n,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 Le}}),ir=v("Realtime",{broadcast(t,e,n){return u(()=>c.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:n??{}}]}}),()=>{})},state:{set(t,e,n){return u(()=>c.realtime.writeState({body:{ops:[{topic:t,key:e,value:n}]}}),()=>{})},clear(t,e){return u(()=>c.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}}),lr=v("Commerce",{getSettings(){return u(()=>c.commerce.getCommerceSettings({}),t=>t)},listStores(t){return u(()=>c.commerce.listStores({query:t}),e=>e)},listProducts(t){return u(()=>c.commerce.listProducts({query:t}),e=>e)},createQuickProduct(t){return u(()=>c.commerce.createQuickProduct({body:t}),e=>e)},getOrder(t){return u(()=>c.commerce.getOrder({path:{order_id:t}}),e=>e)},listOrders(t){return u(()=>c.commerce.listOrders({query:t}),e=>e)},listStoreOrders(t){return u(()=>c.commerce.listStoreOrders({query:t}),e=>e)},adjustInventory(t){return u(()=>c.commerce.adjustInventory({body:t}),e=>e)},recomputeBuyBox(t){return u(()=>c.commerce.recomputeVariantBuyBox({path:{variant_id:t}}),e=>e)}}),cr=v("Promotions",{listRules(t){return u(()=>c.commerce.listPromotionRules({query:t}),e=>e)},createRule(t){return u(()=>c.commerce.createPromotionRule({body:t}),e=>e)},evaluate(t){return u(()=>c.commerce.evaluatePromotions({body:t}),e=>e)},hold(t){return u(()=>c.commerce.holdPromotions({body:t}),e=>e)},commitHold(t,e={}){return u(()=>c.commerce.commitPromotionHold({path:{hold_id:t},body:e}),n=>n)},releaseHold(t){return u(()=>c.commerce.releasePromotionHold({path:{hold_id:t}}),e=>e)},reverseRedemption(t){return u(()=>c.commerce.reversePromotionRedemption({path:{redemption_id:t}}),e=>e)}}),ur=v("Campaigns",{listBroadcasts(){return u(()=>c.campaigns.listBroadcasts({}),t=>t)},createBroadcast(t){return u(()=>c.campaigns.createBroadcast({body:t}),e=>e)},startBroadcast(t){return u(()=>c.campaigns.startBroadcast({path:{id:t}}),e=>e)},pauseBroadcast(t){return u(()=>c.campaigns.pauseBroadcast({path:{id:t}}),e=>e)},cancelBroadcast(t){return u(()=>c.campaigns.cancelBroadcast({path:{id:t}}),e=>e)},getBroadcastStats(t){return u(()=>c.campaigns.getBroadcastStats({path:{id:t}}),e=>e)},recordConversion(t){return u(()=>c.campaigns.recordBroadcastConversion({body:t}),e=>e)},listOnSite(){return u(()=>c.campaigns.listOnSiteCampaigns({}),t=>t)},createOnSite(t){return u(()=>c.campaigns.createOnSiteCampaign({body:t}),e=>e)},listTrackingLinks(){return u(()=>c.campaigns.listTrackingLinks({}),t=>t)},createTrackingLink(t){return u(()=>c.campaigns.createTrackingLink({body:t}),e=>e)},attributeLinkConversion(t){return u(()=>c.campaigns.attributeLinkConversion({body:t}),e=>e)}}),dr=v("Journeys",{list(t){return u(()=>c.journeys.listJourneys({query:t}),e=>e)},get(t){return u(()=>c.journeys.getJourney({path:{key:t}}),e=>e)},validate(t){return u(()=>c.journeys.validateJourney({body:{definition:t}}),e=>e)},publish(t){return u(()=>c.journeys.publishJourney({path:{key:t}}),e=>e)},stop(t){return u(()=>c.journeys.stopJourney({path:{key:t}}),e=>e)},listBlueprints(){return u(()=>c.journeys.listBlueprints({}),t=>t)},listStoreBlueprints(t){return u(()=>c.journeys.listStoreBlueprints({path:{store_id:t}}),e=>e)},activateStoreBlueprint(t,e){return u(()=>c.journeys.activateStoreBlueprint({path:{store_id:t},body:e}),n=>n)},deleteStoreBlueprint(t,e){return u(()=>c.journeys.deleteStoreBlueprint({path:{store_id:t,key:e}}),()=>{})}});import{z as Ns}from"zod";export{Ts as AccessRefused,rt as AttestedDevice,je as AuthUnavailable,Pt as Authorize,Ft as BadRequest,ze as Body,Vt as CACHE_MAX_TTL,Gt as Cache,ur as Campaigns,yt as ChatPart,nt as Client,lr as Commerce,Lt as Conflict,L as ContractRunEnded,Ne as Controller,lt as Cron,V as Database,It as DeadlockDetected,Ge as Delete,Ot as DiError,De as EVENT_TYPES,or as Flags,Ct as Forbidden,kt as Gateway,wt as GatewayRefusal,qe as Get,Ye as Headers,$t as HttpError,at as Injectable,dr as Journeys,p as Log,Wt as MAX_BODY_BYTES,q as MigrationRunEnded,ot as Module,Mt as NotFound,sr as Notifications,it as On,vt as OnConnect,Rt as OnDisconnect,At as OnEmpty,St as OnFirst,Ze as OptionalUser,xt as PalError,c as Palbase,O as PalbaseError,Kn as PalbaseFactory,Qe as Param,Ve as Patch,Ke as Post,cr as Promotions,We as Put,He as Query,Je as QueryParams,ir as Realtime,et as Req,tt as RequestId,st as Resolve,j as SchemaNotPushed,Jn as Secrets,Dt as SerializationFailure,rr as Storage,Et as Subscribe,gt as Task,pt as TaskFailure,mt as Tasks,ft as TestUserTemplate,Ue as TokenError,I as TokenVerifier,Ut as TooManyRequests,Tt as Unauthorized,jt as UniqueViolation,ht as Upload,bt as UploadedObject,Xe as User,ct as Webhook,cs as bigint,us as boolean,ds as check,D as createApp,ps as date,Bt as defineError,gs as defineSchema,ms as defineTable,qt as encrypt,Nt as encrypted,fs as enumType,hs as foreignKey,ut as getRegisteredControllers,dt as getRoutes,_t as getWebhookManifest,Bs as increment,bs as index,ys as integer,ws as jsonb,Fs as now,ks as numeric,Ps as ownedByUser,Ss as policy,vs as raw,Rs as sqlType,Kt as t,As as text,Es as timestamp,_s as userRef,Os as uuid,Ns as z};
|
|
12
|
+
`),process.exit(0),new L}let l=Ee(r),i=await _e(l);i&&p.info(`[palbase] strings: ${i.source} and ${i.locales.length-1} other language(s), ${Object.keys(i.strings).length} sentence(s), from ${l}/palbase/strings`),ae(i?void 0:l);let d=e.db?F(e.db):void 0,o=await X({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&p.info(`[palbase] secrets: ${o.loaded.length} from the project's ${o.set} set${o.kept.length>0?`; ${o.kept.join(", ")} kept as the environment gives them`:""}`),o&&o.refused.length>0&&p.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(P=>JSON.stringify(P)).join(", ")}`);let g=qn(n)||d!==void 0&&N(d),m=ke(e.palbase??{},r,{needsWebhookSecret:g});g&&m.webhookSecret===void 0&&p.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=C({url:m.url,secretKey:m.secretKey}),k=e.port??Number(r.PORT??"8080");if(!Number.isInteger(k)||k<0||k>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,m.secretKey,{onPlatform:m.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&p.info(`[palbase] database: version ${y.binding.version}`);let R=y&&N(y.model)?{"user.deleted":[P=>Vn(y,P)]}:void 0,w=m.platformSecret===void 0?void 0:{secret:m.platformSecret},h=e.requestTelemetry===!1?void 0:new U(f.analytics),A=()=>D({modules:n,verifier:new I({issuer:m.url,projectId:m.projectId,standing:Y({url:m.url,secretKey:m.secretKey})}),server:f,webhookSecret:m.webhookSecret,env:r,projectId:m.projectId,telemetry:h,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:zn(e.cors,r.PALBASE_WEB_ORIGINS),platform:w,events:R,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:i}),E=A(),_=e.boot?.attempts??5,b=e.boot?.backoffMs??1e3;for(let P=1;;P++)try{await E.start();break}catch(S){if(P>=_)throw p.error(`[palbase] the app did not start after ${_} attempts`,{error:S}),S;p.warn(`[palbase] the app did not start (attempt ${P} of ${_}); trying again in ${b} ms`,{error:S}),await new Promise(Me=>setTimeout(Me,b)),b*=2,E=A()}return Gn(E,f,k,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function Ee(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let n=x(Oe(e));for(;!z(J(n,"package.json"))&&x(n)!==n;)n=x(n);return z(J(n,"package.json"))?n:process.cwd()}async function _e(t){try{return await oe(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function Wn(t,e,n){let r=Oe(n.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 s=x(r);for(;!z(J(s,"package.json"))&&x(s)!==s;)s=x(s);let{analyzeProject:a}=await import("../chunks/NG4OMSEK.js"),{routeContracts:l}=await import("../chunks/Q3GH7I66.js"),i=a(s,r);for(let g of i.warnings)p.warn(`[palbase] the contract: ${g}`);let d="https://contract.palbase.invalid",o=D({modules:t,verifier:new I({issuer:d,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:C({url:d,secretKey:"pb_contract_s"}),env:n,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 l(i.routes),errors:se()},events:e.db&&N(F(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(o.contract())}var L=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},q=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Vn(t,e){let n=e.data?.user_id;if(typeof n!="string"||n==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(n,V.$asService());p.info(`[palbase] user ${n} deleted: ${r.deleted} row(s) gone, ${r.detached} forgot them${r.relationships===void 0?"":`, ${r.relationships} relationship(s) of the access schema taken back`}`)}async function Gn(t,e,n,r,s,a){let l,i={on:!1},d=(w,h)=>new URL(w.url).pathname===Nn&&w.method==="GET"?Promise.resolve(i.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(w,h),o=Dn((w,h)=>{Hn(d,w,h,i).finally(()=>{i.on&&o.closeIdleConnections()})});o.keepAliveTimeout=29e4,o.headersTimeout=3e5;try{await new Promise((w,h)=>{o.once("error",h),o.listen(n,r,()=>w())})}catch(w){throw await t.stop(),await a?.close(),w}let g=o.address().port;p.info(`[palbase] serving ${t.routes.length} route(s) on :${g}`,{routes:t.routes}),a?.search?.start();let m=w=>l??=(async()=>{p.info("[palbase] stopping: finishing the requests in flight"),i.on=!0;let h=new Promise(E=>o.close(()=>E()));o.closeIdleConnections();let A=setTimeout(()=>o.closeAllConnections(),w);await h,clearTimeout(A),process.off("SIGINT",y),process.off("uncaughtException",R),process.off("unhandledRejection",R);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>m(Re),k=!1,y=()=>{if(k){p.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}k=!0;let w=setTimeout(()=>{p.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Re+jn);w.unref(),f().then(()=>{clearTimeout(w),process.exit(0)},h=>{clearTimeout(w),p.error("[palbase] stopping failed; the process ends",{error:h}),process.exit(1)})},R=w=>{p.error("[palbase] the app crashed; stopping so the machine starts it again",{error:w});let h=setTimeout(()=>process.exit(1),Ae+1e3);m(Ae).finally(()=>{clearTimeout(h),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),s&&(process.on("uncaughtException",R),process.on("unhandledRejection",R)),{routes:t.routes,palbase:e,port:g,handle:d,close:f}}async function Hn(t,e,n,r){try{let s=e.url??"/",a;try{if(!s.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${s}`)}catch{n.statusCode=400,n.end();return}let l=new Headers;for(let[m,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let k of f)l.append(m,k);else l.set(m,f);let i=e.method!=="GET"&&e.method!=="HEAD",d=new AbortController;n.on("close",()=>{n.writableFinished||d.abort(new Error("the client closed the connection"))});let o=new Request(a,{method:e.method,headers:l,body:i?Un.toWeb(e):void 0,duplex:"half",signal:d.signal}),g=await t(o,{remoteAddress:e.socket.remoteAddress,target:s});if(n.statusCode=g.status,g.headers.forEach((m,f)=>n.setHeader(f,m)),r.on&&n.setHeader("connection","close"),g.body)for await(let m of g.body)n.write(m);n.end()}catch(s){p.error("[palbase] the request could not be answered",{error:s}),n.headersSent||(n.statusCode=500),n.end()}}function zn(t,e,n=r=>console.warn(r)){let r=(e??"").split(",").map(i=>i.trim()).filter(i=>i!=="");if(r.length===0||t?.origins==="*")return t;let s=r.filter(i=>G(i)),a=r.filter(i=>!G(i));a.length>0&&n(`[palbase] the project's web origins ${a.map(i=>JSON.stringify(i)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let l=[...new Set([...t?.origins??[],...s])];return l.length===0?t:{...t,origins:l}}import{bigint as cs,boolean as us,check as ds,date as ps,defineSchema as gs,defineTable as ms,enumType as fs,foreignKey as hs,index as bs,integer as ys,jsonb as ws,numeric as ks,ownedByUser as Ps,policy as Ss,raw as vs,sqlType as Rs,text as As,timestamp as Es,userRef as _s,uuid as Os}from"palgres/dsl";import{AccessRefused as Ts}from"palgres";import{increment as Bs,now as Fs}from"palgres";function T(t){if(t instanceof O)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function u(t,e){try{let n=await t();return{data:await e(n.data),error:null,status:n.status}}catch(n){return T(n)}}var Jn=v("Secrets",{async get(t){if(Q(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Yn=100,Qn=1e3,Xn=168*3600,Zn={s:1,m:60,h:3600,d:86400};function er(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let n=0;for(let[,r,,s]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))n+=Math.round(Number(r)*Zn[s]*1e3);return Math.ceil(n/1e3)}function Ie(t,e,n){let r="getPublicUrl",s;try{s=String(e).split("/").map(l=>W(r,"path",l)).join("%2F")}catch(l){throw l instanceof O&&l.code==="invalid_path_parameter"?new O({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`}):l}let a=`${c.url}/storage/public/${W(r,"bucket",t)}/${s}`;return n?`${a}?variant=${encodeURIComponent(n)}`:a}function xe(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,Ie(t.bucket,t.path,e)]))}}function tr(t){return{async upload(e,n,r){let s=r?.contentType??(n instanceof Blob&&n.type!==""?n.type:void 0);try{let a=await c.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:n,contentType:s});return{data:xe(a.data),error:null,status:a.status}}catch(a){return a instanceof O&&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}:T(a)}},async download(e){try{let n=await c.storage.getObject({path:{bucket:t,path:e}});if(n.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=n.data;try{return{data:await r.blob(),error:null,status:n.status}}catch(s){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${s instanceof Error?s.message:String(s)}`},status:0}}}catch(n){return T(n)}},getPublicUrl(e,n){return Ie(t,e,n?.variant)},async createSignedUrl(e,n){let r=er(n?.expiresIn);return r===void 0||r<1||r>Xn?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(n?.expiresIn)})`},status:400}:u(()=>c.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),s=>({signedUrl:s.url,expiresAt:s.expires_at}))},async list(e,n){let r=n?.limit??Yn,s=n?.offset??0;if(!Number.isInteger(r)||r<0||!Number.isInteger(s)||s<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],l,i=200;try{for(;a.length<r;){let d=Math.max(1,Math.min(Qn,s+r-a.length)),o=await c.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:d,...l?{cursor:l}:{}}});i=o.status;for(let g of o.data.objects)s>0?s--:a.length<r&&a.push(xe(g));if(l=o.data.next_cursor,!l)break}}catch(d){return T(d)}return{data:a,error:null,status:i}},async remove(e){let n=[];for(let r of e){try{await c.storage.deleteObject({path:{bucket:t,path:r}})}catch(s){return T(s)}n.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:n,error:null,status:200}},move(e,n){return u(()=>c.storage.moveObject({path:{bucket:t},body:{from:e,to:n}}),()=>{})},copy(e,n){return u(()=>c.storage.copyObject({path:{bucket:t},body:{from:e,to:n}}),()=>{})}}}var nr={bucket:tr},Te=t=>ne("Storage",t,nr),rr={bucket:t=>Te("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Te("buckets").bucket(e):void 0})},sr=v("Notifications",{push:{send(t){let{to:e,...n}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return u(()=>c.notify.sendPush({body:{...n,to:r}}),s=>({message_ids:s.message_ids,recipients:s.message_ids.length,skipped_user_ids:s.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:n,...r}=t,s={...r,...n!==void 0?{template:n}:{}};if(!Array.isArray(e))return u(()=>c.notify.sendEmail({body:{...s,to:e}}),i=>({...i.message_id!==void 0?{message_id:i.message_id}:{},...i.skipped?{skipped:!0}:{}}));let a=[],l=202;for(let i of e)try{let d=await c.notify.sendEmail({body:{...s,to:i}});l=d.status,a.push(d.data.message_id??null)}catch(d){return T(d)}return{data:{message_ids:a},error:null,status:l}}}}),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,ar=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function $e(){return re.getStore()?.userId}function K(t){let e=t&&"userId"in t?t.userId??void 0:$e();return u(()=>e?c.flags.getUserValues({path:{user_id:e}}):c.flags.getValues(),n=>n.values??{})}var Le={setOverrideForUser:(t,e,n)=>u(()=>c.flags.putUserValue({path:{user_id:t,key:e},body:{value:n}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),setOverridesForUser:(t,e)=>u(()=>c.flags.putUserValues({path:{user_id:t},body:{values:e}}),n=>({values:n.values??{}})),clearOverrideForUser:(t,e)=>u(()=>c.flags.deleteUserValue({path:{user_id:t,key:e}}),n=>({key:n.key,value:n.value,source:Fe(n.source)})),clearAllOverridesForUser:t=>u(()=>c.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>u(()=>c.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},or=v("Flags",{async isEnabled(t,e){let n=r=>(p.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await K(e);return r.error?n(`${r.error.code}: ${r.error.message}`):Ce(r.data[t])}catch(r){return n(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let n=await K(e);return n.error?{data:null,error:n.error,status:n.status}:{data:Be(n.data[t]),error:null,status:n.status}},async getAll(t){let e=await K(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([n,r])=>{let s=Be(r);return{name:n,enabled:Ce(r),...s?{variant:s}:{}}}),error:null,status:e.status}},async get(t,e,n){let r,s=!1,a;n!==void 0?(r=e,s=!0,a=n):ar(e)?a=e:e!==void 0&&(r=e,s=!0);let l=await K(a);if(l.error)return s?{data:r??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let i=l.data[t];return{data:i===void 0?r??null:i,error:null,status:l.status}},async setOverride(t,e){let n=$e();return n?Le.setOverrideForUser(n,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 Le}}),ir=v("Realtime",{broadcast(t,e,n){return u(()=>c.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:n??{}}]}}),()=>{})},state:{set(t,e,n){return u(()=>c.realtime.writeState({body:{ops:[{topic:t,key:e,value:n}]}}),()=>{})},clear(t,e){return u(()=>c.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}}),lr=v("Commerce",{getSettings(){return u(()=>c.commerce.getCommerceSettings({}),t=>t)},listStores(t){return u(()=>c.commerce.listStores({query:t}),e=>e)},listProducts(t){return u(()=>c.commerce.listProducts({query:t}),e=>e)},createQuickProduct(t){return u(()=>c.commerce.createQuickProduct({body:t}),e=>e)},getOrder(t){return u(()=>c.commerce.getOrder({path:{order_id:t}}),e=>e)},listOrders(t){return u(()=>c.commerce.listOrders({query:t}),e=>e)},listStoreOrders(t){return u(()=>c.commerce.listStoreOrders({query:t}),e=>e)},adjustInventory(t){return u(()=>c.commerce.adjustInventory({body:t}),e=>e)},recomputeBuyBox(t){return u(()=>c.commerce.recomputeVariantBuyBox({path:{variant_id:t}}),e=>e)}}),cr=v("Promotions",{listRules(t){return u(()=>c.commerce.listPromotionRules({query:t}),e=>e)},createRule(t){return u(()=>c.commerce.createPromotionRule({body:t}),e=>e)},evaluate(t){return u(()=>c.commerce.evaluatePromotions({body:t}),e=>e)},hold(t){return u(()=>c.commerce.holdPromotions({body:t}),e=>e)},commitHold(t,e={}){return u(()=>c.commerce.commitPromotionHold({path:{hold_id:t},body:e}),n=>n)},releaseHold(t){return u(()=>c.commerce.releasePromotionHold({path:{hold_id:t}}),e=>e)},reverseRedemption(t){return u(()=>c.commerce.reversePromotionRedemption({path:{redemption_id:t}}),e=>e)}}),ur=v("Campaigns",{listBroadcasts(){return u(()=>c.campaigns.listBroadcasts({}),t=>t)},createBroadcast(t){return u(()=>c.campaigns.createBroadcast({body:t}),e=>e)},startBroadcast(t){return u(()=>c.campaigns.startBroadcast({path:{id:t}}),e=>e)},pauseBroadcast(t){return u(()=>c.campaigns.pauseBroadcast({path:{id:t}}),e=>e)},cancelBroadcast(t){return u(()=>c.campaigns.cancelBroadcast({path:{id:t}}),e=>e)},getBroadcastStats(t){return u(()=>c.campaigns.getBroadcastStats({path:{id:t}}),e=>e)},recordConversion(t){return u(()=>c.campaigns.recordBroadcastConversion({body:t}),e=>e)},listOnSite(){return u(()=>c.campaigns.listOnSiteCampaigns({}),t=>t)},createOnSite(t){return u(()=>c.campaigns.createOnSiteCampaign({body:t}),e=>e)},listTrackingLinks(){return u(()=>c.campaigns.listTrackingLinks({}),t=>t)},createTrackingLink(t){return u(()=>c.campaigns.createTrackingLink({body:t}),e=>e)},attributeLinkConversion(t){return u(()=>c.campaigns.attributeLinkConversion({body:t}),e=>e)}}),dr=v("Journeys",{list(t){return u(()=>c.journeys.listJourneys({query:t}),e=>e)},get(t){return u(()=>c.journeys.getJourney({path:{key:t}}),e=>e)},validate(t){return u(()=>c.journeys.validateJourney({body:{definition:t}}),e=>e)},publish(t){return u(()=>c.journeys.publishJourney({path:{key:t}}),e=>e)},stop(t){return u(()=>c.journeys.stopJourney({path:{key:t}}),e=>e)},listBlueprints(){return u(()=>c.journeys.listBlueprints({}),t=>t)},listStoreBlueprints(t){return u(()=>c.journeys.listStoreBlueprints({path:{store_id:t}}),e=>e)},activateStoreBlueprint(t,e){return u(()=>c.journeys.activateStoreBlueprint({path:{store_id:t},body:e}),n=>n)},deleteStoreBlueprint(t,e){return u(()=>c.journeys.deleteStoreBlueprint({path:{store_id:t,key:e}}),()=>{})}});import{z as Ns}from"zod";export{Ts as AccessRefused,rt as AttestedDevice,je as AuthUnavailable,Pt as Authorize,Ft as BadRequest,ze as Body,Vt as CACHE_MAX_TTL,Gt as Cache,ur as Campaigns,yt as ChatPart,nt as Client,lr as Commerce,Lt as Conflict,L as ContractRunEnded,Ne as Controller,lt as Cron,V as Database,It as DeadlockDetected,Ge as Delete,Ot as DiError,De as EVENT_TYPES,or as Flags,Ct as Forbidden,kt as Gateway,wt as GatewayRefusal,qe as Get,Ye as Headers,$t as HttpError,at as Injectable,dr as Journeys,p as Log,Wt as MAX_BODY_BYTES,q as MigrationRunEnded,ot as Module,Mt as NotFound,sr as Notifications,it as On,vt as OnConnect,Rt as OnDisconnect,At as OnEmpty,St as OnFirst,Ze as OptionalUser,xt as PalError,c as Palbase,O as PalbaseError,Kn as PalbaseFactory,Qe as Param,Ve as Patch,Ke as Post,cr as Promotions,We as Put,He as Query,Je as QueryParams,ir as Realtime,et as Req,tt as RequestId,st as Resolve,j as SchemaNotPushed,Jn as Secrets,Dt as SerializationFailure,rr as Storage,Et as Subscribe,gt as Task,pt as TaskFailure,mt as Tasks,ft as TestUserTemplate,Ue as TokenError,I as TokenVerifier,Ut as TooManyRequests,Tt as Unauthorized,jt as UniqueViolation,ht as Upload,bt as UploadedObject,Xe as User,ct as Webhook,cs as bigint,us as boolean,ds as check,D as createApp,ps as date,Bt as defineError,gs as defineSchema,ms as defineTable,qt as encrypt,Nt as encrypted,fs as enumType,hs as foreignKey,ut as getRegisteredControllers,dt as getRoutes,_t as getWebhookManifest,Bs as increment,bs as index,ys as integer,ws as jsonb,Fs as now,ks as numeric,Ps as ownedByUser,Ss as policy,vs as raw,Rs as sqlType,Kt as t,As as text,Es as timestamp,_s as userRef,Os as uuid,Ns as z};
|
package/dist/backend/stack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/test.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as l,c as g,d as f,e as m}from"../chunks/
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as l,c as g,d as f,e as m}from"../chunks/YQQKZUVS.js";import{a as u}from"../chunks/QL2UAO36.js";import{c,i as p}from"../chunks/3X3ZT72M.js";import"../chunks/S7C7NHZI.js";import"../chunks/B64J3E3T.js";import"../chunks/5OBOVEK6.js";import"../chunks/HHKRAOVG.js";import"../chunks/AKJC5WTU.js";import"../chunks/RP2TPMXT.js";import"../chunks/JSRN4NOZ.js";import"../chunks/XVJ3CMFN.js";import"../chunks/HVRVTNMI.js";import"../chunks/SHYJVOD2.js";import"reflect-metadata";import{randomUUID as y}from"node:crypto";import{createFakeClient as w,typedDatabase as h}from"palgres/testing";function b(s,t,e){if(e?.acceptLanguage!==void 0&&e.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:n,...o}=s,a=e?.strings;return c.run({requestId:`test_${y()}`,database:n===void 0?void 0:d(n),services:o,...a!==void 0?{strings:a,locales:p(e?.acceptLanguage??null,a.source),usedLocales:[]}:{}},t)}function T(){let s=new Map,t=new Map,e=[],n=a=>{if(s.has(a))return s.get(a);if(t.has(a))return t.get(a);if(e.includes(a)){let r=[...e.slice(e.indexOf(a)),a].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${r.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}e.push(a);try{let r=Reflect.getMetadata("design:paramtypes",a)??[],i=new a(...r.map(n));return t.set(a,i),i}finally{e.pop()}},o={with(a,r){return s.set(a,r),o},get:a=>n(a)};return o}var k="a database in memory keeps rows, not relationships, and answers no access question \u2014 give it the schema (fakeDatabase({ access: <the schema file's text> })), or test what asks Database.$access against Postgres; the schema itself is held to its expectations with `palbase access:test`";function d(s){let t=s.access;return h(s,t===void 0?{unanswered:k}:{access:t.names,via:t.via,as:"authenticated"})}function v(s={}){let t=w(s);return{db:d(t),raw:t,queries:t.queries,seed:(e,n)=>t.seed(e,n),inserted:e=>t.inserted(e),updated:e=>t.updated(e),deleted:e=>t.deleted(e),signedInAs(e){if(!t.access)throw new TypeError("fakeDatabase().signedInAs: this database was made without an access schema \u2014 fakeDatabase({ access: <the schema file's text> })");t.access.signedInAs(e)}}}export{l as TestApiError,m as api,g as createTestApi,v as fakeDatabase,T as isolated,u as loadStringsTable,f as testRun,b as withServices};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as D,d as I,e as R}from"./5OBOVEK6.js";import{a as Y,f as Z,g as X,j as ee,k as te,l as ne,o as N,p as se,q as re}from"./VP3HFVV4.js";import{d as G}from"./JSRN4NOZ.js";import{a as E,b as Q,c as T,e as q}from"./XVJ3CMFN.js";var f=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function ae(t){return t instanceof f||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function K(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??Qe(e,"request_id"),data:S(e,"data"),cause:t};if(t.code==="network_error")return new f("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new f("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new f("attestationRequired",n);if(t.status===401)return new f("unauthorized",n);if(t.status===429)return new f("rateLimited",{...n,retryAfter:ze(e)??t.retryAfter});let s=Ue(e);return t.status===400&&s?new f("validation",{...n,fields:s}):new f("server",n)}function P(t){return t instanceof Q||t instanceof Error&&t.name==="PalbaseError"}function oe(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Ue(t){let e=S(S(t,"data"),"fields");if(oe(e))return e;let n=S(t,"fields");return oe(n)?n:void 0}function ze(t){return ie(t,"retry_after")??ie(S(t,"data"),"retryAfter")}function S(t,e){if(typeof t=="object"&&t!==null)return t[e]}function ie(t,e){let n=S(t,e);return typeof n=="number"?n:void 0}function Qe(t,e){let n=S(t,e);return typeof n=="string"?n:void 0}var Ye=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ze=Object.freeze(["adoptSession","ai","analytics","anonymousTelemetry","appContext","appEvent","appVersion","auth","callOnSignOut","calls","cancelCallOnSignOut","captureOnce","chatToolCall","chatWorkspaceFile","configuration","consent","currentSession","defaults","flags","installation","keychainItem","module","moduleDirectory","notify","offerTaker","onAppEvent","onSessionChange","onSignOut","preferences","realtime","scope","send","setLanguage","setPreferredLanguages","signedInUserNow","socket","storage","storedUserId","telemetry","transport","transportFor","upload","version","watchSessions","palbe","data","stores","iap","payments","commerce","campaigns","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Xe=new Set(Ze),et=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function O(t){return t==="then"||t==="toJSON"||et.has(t)}function de(t){return t==="call"||t==="join"||O(t)}function le(t){return typeof t=="string"&&Ye.test(t)&&!Xe.has(t)&&!O(t)}function ce(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function ue(t){q(t)}function pe(t){return q(t).origin}var $=class t{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;execution={target:null,generation:0,workspaceSeq:0,machineId:null,machineStatus:null,failoverAt:null,lastHandoff:null,compactions:[],offloads:[]};handoffGens=new Set;compactionSeqs=new Set;offloadKeys=new Set;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];racedPages=[];heldTimer;heldSince=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},n,s,r=!0){this.me=e,this.reader=n,this.chatId=s,this.replays=r}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let n=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,d={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...n!==void 0?{turns:n}:{},...e.signal?{signal:e.signal}:{}},a;if(e.load)a=await e.load(d);else{let h=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");a=await this.reader.parts(h,d)}if(this.ended)return!1;let c=(a?.parts??[]).map(h=>D(h)).filter(h=>h!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(c),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=c):this.racing&&(this.racedPages=c.concat(this.racedPages)),n===void 0||typeof a?.turns!="number"||s!==void 0&&this.olderCursor===s)break;n-=a.turns}while(n>0);return this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let p=w(i);p<=0||(this.paged.add(p),(this.pagedFrom===void 0||p<this.pagedFrom)&&(this.pagedFrom=p),(this.pagedTo===void 0||p>this.pagedTo)&&(this.pagedTo=p))}let n=new t(this.me);n.thoughts=this.thoughts,n.lowest=this.lowest-e.length;let s=n.lowest;for(let i of e)n.at=s++,n.fold(i);this.folded+=n.folded,this.lowest=n.lowest,this.chatId??=n.chatId;let r=new Map;for(let[i,p]of n.messages){let y=this.told.get(i)??[],b=p;if(y.length>0)for(let C of y)b=ve(b,C);else b=this.messages.get(i)??p;r.set(i,b);let _=[...n.told.get(i)??[],...y];_.length>0&&this.told.set(i,_)}for(let[i,p]of this.messages)r.has(i)||r.set(i,p);this.messages.clear();for(let[i,p]of r)this.messages.set(i,p);let o=new Map;for(let[i,p]of n.responses){let y=this.responses.get(i);o.set(i,y?nt(p,y):p)}for(let[i,p]of this.responses)o.has(i)||o.set(i,p);this.responses.clear();for(let[i,p]of o)this.responses.set(i,p);let d=new Set;for(let i of n.order)(i.type==="message"||i.type==="response")&&d.add(`${i.type}\0${i.key}`);let a=[...n.order],c=new Set([...n.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&d.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&n.goalWords.has(i.event.seq))&&!(i.type==="voice"&&n.voiceWords.has(L(i.event)))&&!(i.type==="handoff"&&n.handoffGens.has(i.event.generation))&&!(i.type==="compaction"&&i.event.seq>0&&n.compactionSeqs.has(i.event.seq))){if(i.type==="message"&&i.began&&i.turn!==null){let p=this.responses.get(i.turn);c.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:p&&p.at<i.arrived?p.at-.5:i.arrived});continue}a.push(i)}a.sort((i,p)=>i.at-p.at),this.order=a;for(let i of n.goalWords)this.goalWords.add(i);this.goal=null;for(let i of a)i.type==="goal"&&this.goalSaid(i.event);for(let i of n.voiceWords)this.voiceWords.add(i);let h=new Set;this.voice=null;for(let i of a)i.type==="voice"&&(this.voice=ye(this.voice,i.event,h));for(let i of n.handoffGens)this.handoffGens.add(i);for(let i of n.compactionSeqs)this.compactionSeqs.add(i);for(let i of n.offloadKeys)this.offloadKeys.add(i);n.execution.generation>this.execution.generation&&(this.execution={...this.execution,target:n.execution.target,generation:n.execution.generation,workspaceSeq:n.execution.workspaceSeq,lastHandoff:n.execution.lastHandoff}),this.execution.machineStatus===null&&n.execution.machineStatus!==null&&(this.execution={...this.execution,machineId:n.execution.machineId,machineStatus:n.execution.machineStatus,failoverAt:n.execution.failoverAt});let l=[];for(let i of a)i.type==="compaction"&&l.push(i.event);let u=[...n.execution.offloads,...this.execution.offloads.filter(i=>!n.offloadKeys.has(me(i)))];this.execution={...this.execution,compactions:l,offloads:u},this.turn??=n.turn;let g=new Map([...n.calls,...this.calls]);this.calls.clear();for(let[i,p]of g)this.calls.set(i,p);for(let[i,p]of n.history)this.history.has(i)||this.history.set(i,p);this.forkedFrom??=n.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(d=>e=d)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0,clearTimeout(this.heldTimer);for(let e of[...this.enders])e()}}takePayload(e){let n=D(e);n&&this.take(n)}take(e){if(!this.ended){if(this.racing){this.held.length===0&&(this.heldSince=Date.now()),this.held.push(e);let n=w(e);n>0&&this.pagedTo!==void 0&&n>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=ge(setTimeout(()=>this.quiet(),fe)));return}this.takeNow(e)}}quiet(){let e=this.held.map(w).filter(s=>s>0);e.length>0&&e.every(s=>!this.paged.has(s)&&this.pagedFrom!==void 0&&s<this.pagedFrom)&&Date.now()-this.heldSince<tt?this.heldTimer=ge(setTimeout(()=>this.quiet(),fe)):this.sortHeld()}takeNow(e){let n=w(e);n>0&&this.paged.has(n)||(n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),n=this.racedPages;this.racedPages=[];let s=[],r=[],o=e.findIndex(a=>this.paged.has(w(a))),d=o<0?-1:n.findIndex(a=>w(a)===w(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&he(e[o-1-a],n[d-1-a]);)a++;let c=0;for(;o+c<e.length&&d+c<n.length&&he(e[o+c],n[d+c]);)c++;s=e.slice(0,o-a),r=e.slice(o+c)}else{let a=e.find(h=>w(h)>0),c=a!==void 0&&this.pagedFrom!==void 0&&w(a)<this.pagedFrom;for(let h of e){let l=w(h);l>0&&!(this.pagedFrom!==void 0&&l<this.pagedFrom)&&(c=!1),(c?s:r).push(h)}}if(s.length>0){let a=Math.min(...s.map(w).filter(c=>c>0));this.before(s),Number.isFinite(a)&&(this.oldestLive=a,this.olderCursor=void 0)}for(let a of r)this.takeNow(a)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let 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}),A(n.times,e.status,e.at),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:n.from+I(n.text),loose:n.text==="",cutAt:n.cut,thinking:{stepId:null,runId:e.run_id,text:"",startedAt:e.at??null,endedAt:e.at??null,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,...Ee(r.thinking,e.at??null,e.at??null)}:n.marks.set(s,{type:"thinking",text_offset:n.from+I(n.text),loose:n.text==="",cutAt:n.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,startedAt:e.at??null,endedAt:e.at??null,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let n=L(e);if(this.voiceWords.has(n))return!1;this.voice=ye(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);ot(n,e.offset,e.text),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"reset":{let n=this.response(e.response_id);e.offset<=n.from?(n.text="",n.from=Math.max(0,e.offset)):n.text=n.text.slice(0,R(n.text,e.offset-n.from)),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"tool":{let n=this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id);n.marks.set(`tool:${e.call_id}`,e),we(n,`tool:${e.call_id}`,e.status,e.at),this.calls.set(e.call_id,e);break}case"agent":{let n=this.response(e.parent_response_id),s=e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`;if(n.marks.set(s,e),we(n,s,e.status,e.at),!e.response_id)break;let r=this.response(e.response_id);r.runId=e.run_id,r.agent=e.name,r.named=!0,r.parentId??=e.parent_response_id,A(r.times,e.status,e.at);break}case"session.handed_off":{if(this.handoffGens.has(e.generation))return!1;this.handoffGens.add(e.generation),e.generation>=this.execution.generation&&(this.execution={...this.execution,target:e.to_target,generation:e.generation,workspaceSeq:e.workspace_seq,machineId:e.to_target.compute.machine_id??null,failoverAt:null,lastHandoff:e}),this.order.push({type:"handoff",event:e,at:this.at});break}case"session.machine_status":{this.execution={...this.execution,machineId:e.machine_id||this.execution.machineId,machineStatus:e.status,failoverAt:e.failover_at??null};break}case"context.offloaded":{let n=me(e);if(this.offloadKeys.has(n))return!1;this.offloadKeys.add(n),this.execution={...this.execution,offloads:[...this.execution.offloads,e]};break}case"context.compacted":{if(e.seq>0){if(this.compactionSeqs.has(e.seq))return!1;this.compactionSeqs.add(e.seq)}this.execution={...this.execution,compactions:[...this.execution.compactions,e]},this.order.push({type:"compaction",event:e,at:this.at});break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let 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=rt(e),s=this.messages.get(n);this.messages.set(n,ve(s,e));let r=this.told.get(n);r?r.push(e):this.told.set(n,[e]),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,n){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([c,h])=>c!==n&&h.responseId===s),o=r?this.responses.get(s):void 0,d={type:"message",key:n,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},a=o?this.order.findIndex(c=>c.type==="response"&&c.key===s):-1;a>=0?this.order.splice(a,0,d):this.order.push(d)}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,markTimes:new Map,times:{},runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,n),this.order.push({type:"response",key:e,at:this.at})),n}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=l=>e!==void 0&&l.startedBy===e,s=new Map;for(let l of this.responses.values()){let u=l.parentId!==null?this.responses.get(l.parentId)??l:l;s.set(l.id,it(l,u.startedBy??null,n(u),l.goal??u.goal))}let r=new Map([...this.messages].map(([l,u])=>[l,e!==void 0&&u.author===e?{...u,mine:!0}:u])),o=[...this.history.entries()].sort(([l],[u])=>l-u).flatMap(([l,u])=>u.map((g,i)=>dt(g,`${l}:${i}`,e))),d=[...o];for(let l of this.order)l.type==="goal"?d.push({type:"goal",goal:l.event}):l.type==="voice"?d.push({type:"voice",voice:l.event}):l.type==="handoff"?d.push({type:"handoff",handoff:l.event}):l.type==="compaction"?d.push({type:"compaction",compaction:l.event}):l.type==="message"?d.push({type:"message",message:r.get(l.key)}):this.responses.get(l.key).parentId===null&&d.push({type:"response",response:s.get(l.key)});let a=o.flatMap(l=>l.type==="message"?[l.message]:[]),c=o.flatMap(l=>l.type==="response"?[l.response]:[]),h=[...this.calls.values()].filter(l=>s.get(l.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...c,...s.values()],turn:this.turn,waiting:{approvals:h.filter(l=>l.status==="awaiting_approval"),outputs:h.filter(l=>l.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?st(this.voice,e):null,execution:this.execution}}},fe=150,tt=2e3;function he(t,e){let n=w(t);return n>0||w(e)>0?n===w(e):JSON.stringify({...t,at:void 0})===JSON.stringify({...e,at:void 0})}function w(t){let e=t.seq;return typeof e=="number"&&e>0?e:0}function ge(t){return t.unref?.(),t}function L(t){return`${t.voice_id}\0${t.status}`}function me(t){return t.seq>0?`seq:${t.seq}`:`call:${t.call_id}:${t.ref??""}`}function ye(t,e,n){return n.add(L(e)),(e.status==="closed"?t===null||t.voice_id===e.voice_id:!n.has(`${e.voice_id}\0closed`))?e:t}function ve(t,e){let n=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??t?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:t?.status==="delivered"?"delivered":n,error:e.error??null,responseId:e.response_id??t?.responseId??null,createdAt:e.created_at??t?.createdAt??"",mine:!1,metadata:e.metadata??t?.metadata??{},history:!1,truncated:!1,kind:e.kind??t?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:t?.voice??null,attachments:e.attachments?xe(e.attachments):t?.attachments??[]}}function nt(t,e){let n={...t,marks:new Map(t.marks),times:ke(t.times,e.times),markTimes:new Map(t.markTimes)};for(let[r,o]of e.markTimes)n.markTimes.set(r,ke(n.markTimes.get(r)??{},o));e.status!==null&&(n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=e.end),e.startedBy!==void 0&&(n.startedBy=e.startedBy),e.goal&&(n.goal=e.goal),e.named&&(n.runId=e.runId,n.agent=e.agent,n.named=!0),n.parentId=t.parentId??e.parentId,e.cut!==null&&(t.text===""||e.cut<=t.from?(n.text=e.text,n.from=e.text===""?Math.max(0,e.cut):e.from):n.text=t.text.slice(0,R(t.text,e.cut-t.from))+e.text,n.cut=t.cut===null?e.cut:Math.min(t.cut,e.cut));let s=r=>{if(t.text==="")return null;if(r!==null&&r<=t.from)return r;let o=I(t.text);return t.from+(r===null?o:Math.min(o,r-t.from))};for(let[r,o]of e.marks){let d=n.marks.get(r);if(d?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")n.marks.set(r,{...d,thinking:{...d.thinking,text:d.thinking.text+o.thinking.text,...Ee(d.thinking,o.thinking.startedAt,o.thinking.endedAt)}});else if(o.type==="thinking"&&o.loose){let a=s(o.cutAt);n.marks.set(r,a!==null?{...o,text_offset:a,loose:!1}:{...o,cutAt:o.cutAt===null?t.cut:t.cut===null?o.cutAt:Math.min(o.cutAt,t.cut)})}else n.marks.set(r,o)}return n}function st(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 xe(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 rt(t){return`${t.author??""}\0${t.client_id}`}function ot(t,e,n){if(t.text===""||e<=t.from){t.from=Math.max(0,e),t.text=n;return}t.text=t.text.slice(0,R(t.text,e-t.from))+n}function it(t,e,n,s){let r=[...t.marks].map(([l,u],g)=>({key:l,m:u,i:g,at:R(t.text,Math.max(0,(Number(u.text_offset)||0)-t.from))}));r.sort((l,u)=>l.at-u.at||l.i-u.i);let o=[],d=[],a=0;for(let{key:l,m:u,at:g}of r)if(g>a&&o.push({type:"text",text:t.text.slice(a,g)}),a=Math.max(a,g),u.type==="thinking")o.push({type:"thinking",thinking:u.thinking}),d.push(u.thinking);else{let i={...t.markTimes.get(l)};o.push(u.type==="tool"?{type:"tool",tool:u,times:i}:{type:"agent",agent:u,times:i})}a<t.text.length&&o.push({type:"text",text:t.text.slice(a)});let c=Object.values(t.times).sort(),h=at.map(l=>t.times[l]).find(l=>l!==void 0)??null;return{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:d,goal:s,history:!1,truncated:!1,times:{...t.times},startedAt:c[0]??null,endedAt:h}}var at=["completed","failed","canceled","timed_out","budget_exceeded","denied","failed_with_uncertain_side_effect"];function A(t,e,n){if(typeof n!="string"||n==="")return;let s=t[e];(s===void 0||n<s)&&(t[e]=n)}function we(t,e,n,s){if(typeof s!="string"||s==="")return;let r=t.markTimes.get(e);r||t.markTimes.set(e,r={}),A(r,n,s)}function ke(t,e){let n={...t};for(let[s,r]of Object.entries(e))A(n,s,r);return n}function Ee(t,e,n){return{startedAt:t.startedAt===null||e!==null&&e<t.startedAt?e??t.startedAt:t.startedAt,endedAt:t.endedAt===null||n!==null&&n>t.endedAt?n??t.endedAt:t.endedAt}}function dt(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:xe(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,times:{},startedAt:null,endedAt:null}}}var be=[["ApiKeyAuth","userJWT"]];function _e(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.turns!==void 0&&(s.turns=n.turns),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${T("ListChatParts","chat_id",e)}/parts`,auth:be,answers:{200:"json"},query:s,signal:n.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${T("GetChatToolCall","chat_id",e)}/tool-calls/${T("GetChatToolCall","call_id",n)}`,auth:be,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}}}}var M=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},Se=new WeakMap;async function Te(t,e,n,s={},r=()=>{},o){let{pattern:d,events:a,messages:c,durable:h,chat:l}=lt(e),u=ct(d,n),g=Se.get(t);g||Se.set(t,g=new Map);let i=g,p=i.get(u)??{count:0};i.set(u,p),p.count++;let y=t.channel(u,h&&s.history!==!1?{after:0}:{});if(l&&!p.chat){let m=n.chatId,x=new $(r,o,typeof m=="string"&&m!==""?m:void 0,h&&s.history!==!1);p.chat=x,p.unchat=y.on("broadcast",v=>{v.event==="chat"&&x.takePayload(v.payload)})}let b=()=>{--p.count>0||(i.delete(u),p.unchat?.(),p.chat?.end(),y.leave())};try{await y.join()}catch{let m=y.state==="refused"?Ce(y.refusal,"unavailable"):"socket closed";throw b(),new M(`gateway ${JSON.stringify(u)} was not joined: ${m}`,m)}let _=!1,C=new Set,V=()=>{if(!_){_=!0,Ve();for(let m of[...C])m();b()}},Ve=y.onClosed(V),U=m=>{if(_)return()=>{};let x=y.on("broadcast",k=>{typeof k.event=="string"&&a.has(k.event)&&m(k.event,E(k.payload))}),v=()=>{C.delete(v),x()};return C.add(v),v},z={topic:u,get seq(){return y.logSeq},on(m,x){if(typeof m=="function")return U((v,k)=>m({event:v,payload:k}));if(!a.has(m))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(m))}`);if(typeof x!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(m)}, \u2026) takes the function the event is handed to`);return U((v,k)=>{v===m&&x(k)})},off(m){C.has(m)&&m()},async send(m,x){if(!c.has(m))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(m))}`);let v=_?{status:"error",response:{reason:"not joined"}}:await y.push("broadcast",{type:"broadcast",event:m,payload:x});if(v.status==="ok")return E(v.response.reply);let k=Ce(v.response,"unavailable");throw new M(`gateway ${JSON.stringify(u)} did not take ${JSON.stringify(m)}: ${k}`,k)},leave:V};return l&&Object.defineProperty(z,"chat",{value:p.chat,enumerable:!0}),z}function lt(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 ct(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 Ce(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ut=3600*1e3,j=new Map;function pt(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=j.get(s);if(!n&&r&&Date.now()-r.at<ut)return r.list;let o=(async()=>{let d=se(),a;try{a=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:d},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(c){throw new f("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 re(a,e.signer,e.projectId,d)}catch(c){throw new f("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 j.set(s,{list:o,at:Date.now()}),o.catch(()=>{j.get(s)?.list===o&&j.delete(s)}),o}async function Re(t,e,n,s,r,o){let a=(await pt(t,e,o)).keys[0];return X(a.kid,a.key,Z(e.projectId,n,s,r))}function B(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):N(e,n,s,(r,o)=>ee(t.key,r,o))}function Ie(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):N(e,"/response",n,async(r,o)=>{if(!te(o))throw new f("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ne(t.key,r,o)}catch(d){throw new f("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Pe(t){return t instanceof f&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var F=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
|
|
3
|
+
`);let n=[],s=this.pending.indexOf(`
|
|
4
|
+
`);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&n.push({event:this.eventName,payload:this.dataLines.join(`
|
|
5
|
+
`)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let d=o.slice(5);this.dataLines.push(d.startsWith(" ")?d.slice(1):d)}else if(o.startsWith("event:")){let d=o.slice(6);this.eventName=d.startsWith(" ")?d.slice(1):d}}s=this.pending.indexOf(`
|
|
6
|
+
`)}return n}};async function*Oe(t,e){let n=t.getReader(),s=new TextDecoder,r=new F;try{for(;;){let{done:o,value:d}=await n.read();if(o)break;for(let a of r.consume(s.decode(d,{stream:!0}))){if(a.event==="error")throw new f("network",{code:"stream_failed",message:`stream failed: ${a.payload}`});let c;try{c=JSON.parse(a.payload)}catch{throw new f("decode",{code:"invalid_frame",message:`stream frame is not valid JSON: ${a.payload.slice(0,120)}`})}yield E(c)}}}finally{e.abort();try{await n.cancel()}catch{}}}var ft={},Ae=new WeakMap;function en(t,e,n,s,r,o=()=>{}){Ae.set(t,{project:e,machine:n,storage:s,socket:r,me:o})}var Me=new Map,$e=new WeakMap;function tn(t,e,n,s,r,o){if(!le(e))throw new f("validation",{code:"reserved_namespace",message:`Cannot register backend ${JSON.stringify(String(e))}: a backend's name is an identifier the client does not keep.`});let d=pe(t);if(!ce(n))throw new TypeError(`${JSON.stringify(String(n))} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);ue(s),Ge(r);for(let a of Object.keys(r))if(de(a))throw je(a);if(o!==void 0)vt(o);else if(qe(r))throw new f("validation",{code:"invalid_namespace_tree",message:`Backend ${e}: its routes carry encrypted fields, and its module holds no project id and signing key to seal them with \u2014 generate it again with palbase apps:sync`});(Me.get(e)??ht(e)).set(d,{machine:n,url:s,tree:r,...o?{transit:{...o}}:{}})}function ht(t){let e=new Map;return Me.set(t,e),Object.defineProperty(ft,t,{configurable:!0,get(){return gt(this,t,e)}}),e}function gt(t,e,n){let s=Ae.get(t);if(!s)return;let r=n.get(s.project);if(!r)throw new TypeError(`pb.${e} is the backend of ${[...n.keys()].join(" and ")}: this client is ${s.project}'s, and its user's session never goes to another project's machine`);let o=$e.get(t);o||$e.set(t,o=new Map);let d=o.get(e);if(d?.registration===r)return d.ns;let a={machine:()=>s.machine(r.url),storage:s.storage,name:r.machine,...r.transit?{transit:{project:s.storage,config:r.transit}}:{}},c=Object.assign({call:(h,l,u)=>_t(a.machine,h,l,u),join:(h,l,u)=>Te(s.socket,h,l,u,s.me,_e(s.storage))},Ne(r.tree,a));return o.set(e,{registration:r,ns:c}),c}function je(t){return new f("validation",{code:"reserved_namespace",message:`Cannot register endpoint namespace ${JSON.stringify(t)}: the name is reserved.`})}function J(t){return typeof t.path=="string"&&typeof t.method=="string"}function mt(t,e){if(t.pathParams!==void 0){if(!Array.isArray(t.pathParams)||!t.pathParams.every(n=>typeof n=="string"))throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams must be an array of strings.`});for(let n of t.pathParams)if(!t.path.includes(`{${n}}`))throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams entry '${n}' has no '{${n}}' placeholder in the path.`})}if(t.sse!==void 0&&typeof t.sse!="boolean")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': sse must be a boolean.`});if(t.idempotent!==void 0&&typeof t.idempotent!="boolean")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': idempotent must be a boolean.`});if(t.upload!==void 0&&typeof t.upload!="boolean")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': upload must be a boolean.`});if(t.upload===!0&&(t.method!=="POST"||t.sse===!0))throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an upload endpoint is a POST, and no stream.`});if(t.sse===!0&&t.input==="query")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an sse endpoint cannot take query input.`});if(t.input!==void 0&&t.input!=="body"&&t.input!=="query"&&t.input!=="none")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': input must be 'body', 'query' or 'none'.`});if(t.encryption!==void 0&&yt(t,e),t.errors!==void 0){for(let[n,s]of Object.entries(t.errors))if(typeof s!="function")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': errors['${n}'] must be a function.`})}}function yt(t,e){let n=t.encryption,s=r=>new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': encryption ${r}.`});if(typeof n!="object"||n===null)throw s("is { request, response }");for(let[r,o]of[["request",["/body/","/query/"]],["response",["/response"]]]){let d=n[r];if(d!==void 0&&(!Array.isArray(d)||!d.every(a=>typeof a=="string"&&o.some(c=>a===c||a.startsWith(c.endsWith("/")?c:`${c}/`)))))throw s(`${r} is a list of places under ${o.join(" or ")}`)}if(t.upload===!0)throw s("is no upload\u2019s: storage seals nothing");if(t.sse===!0&&(n.response?.length??0)>0)throw s("of a streamed answer is none")}function qe(t){return J(t)?t.encryption!==void 0:Object.values(t).some(e=>qe(e))}function vt(t){if(typeof t!="object"||t===null||typeof t.projectId!="string"||!/^[0-9a-f-]{36}$/.test(t.projectId)||typeof t.signer!="string"||!/^[A-Za-z0-9_-]{43}$/.test(t.signer))throw new f("validation",{code:"invalid_namespace_tree",message:"The backend's encryption is { projectId, signer }: the project's id and its Ed25519 signing key, base64url"})}function Ge(t){if(typeof t!="object"||t===null)throw new f("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});let e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null)throw new f("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});for(let[n,s]of Object.entries(t)){if(O(n))throw je(n);typeof s=="object"&&s!==null&&J(s)?(s.method=s.method.toUpperCase(),mt(s,s.path)):Ge(s)}}function Ne(t,e){if(J(t))return t.upload===!0?async(...s)=>xt(e,t,s):async(...s)=>Le(e.machine(),t,s,e.transit);let n={};for(let[s,r]of Object.entries(t))n[s]=Ne(r,e);return n}function H(t){if(t==null)return"";let e=Object.entries(t).filter(([,s])=>s!=null).sort(([s],[r])=>s<r?-1:s>r?1:0);return e.length===0?"":`?${e.map(([s,r])=>{if(typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")throw new f("validation",{code:"invalid_query_value",message:`Query parameter '${s}' must be a string, number, or boolean.`});return`${encodeURIComponent(s)}=${encodeURIComponent(String(r))}`}).join("&")}`}function De(t,e,n){try{return T(t.path,e,n)}catch(s){if(!P(s)||s.code!=="invalid_path_parameter")throw s;let r=String(n);throw new f("validation",{code:"invalid_path_parameter",message:`${t.path}: ${e} cannot be ${r===""?"empty":JSON.stringify(r)}`})}}function Ke(t,e){let n=t.pathParams??[],s=t.path;for(let r=0;r<n.length;r++){let o=e[r];if(typeof o!="string"&&typeof o!="number")throw new f("validation",{code:"missing_path_param",message:`${t.path}: path parameter '${n[r]}' must be a string or number`});s=s.replace(`{${n[r]}}`,De(t,`path parameter '${n[r]}'`,o))}return s}var wt=new Set(["POST","PUT","PATCH","DELETE"]);async function Le(t,e,n,s){let r=e.pathParams??[],o=Ke(e,n),d=o;if(e.input==="none"&&n.length>r.length+1)throw new f("validation",{code:"unexpected_argument",message:`${e.path}: endpoint takes no input \u2014 pass only path params and options`});let a=e.input==="none"?void 0:n[r.length],c=e.input==="none"?r.length:r.length+1,h=n[c],l;if(e.input==="query")d+=H(a);else if(e.input!=="none")if(e.method==="GET"){if(a!==void 0)throw new f("validation",{code:"unsupported_get_input",message:`${e.path}: GET endpoints take no body input`})}else l=a;let u={...h?.headers};if(wt.has(e.method)&&!Object.keys(u).some(g=>g.toLowerCase()==="idempotency-key")&&(u["Idempotency-Key"]=G()),e.encryption!==void 0){if(!s)throw new f("validation",{code:"encryption_unconfigured",message:`${e.method} ${e.path}: the route carries encrypted fields, and this backend's module holds no key to seal them with`});return kt(t,e,o,a,l,u,h?.signal,r.map((g,i)=>String(n[i])),s)}try{return e.sse===!0?await We(t,e,d,l,u,h?.signal):await Je(t,e,d,l,u,h?.signal)}catch(g){throw W(e,g)}}async function kt(t,e,n,s,r,o,d,a,c){let h=e.encryption;for(let l=0;;l++){let u=await Re(c.project,c.config,e.method,e.path,a,l>0);try{let g=e.input==="query"?n+H(await B(u,s,"/query",h.request)):n,i=await B(u,r,"/body",h.request),p={...o,[Y]:u.header};return e.sse===!0?await We(t,e,g,i,p,d):E(await Ie(u,await Je(t,e,g,i,p,d),h.response,`${e.method} ${e.path}`))}catch(g){if(l===0&&Pe(g))continue;throw W(e,g)}}}function W(t,e){return t.errors&&ae(e)&&Object.hasOwn(t.errors,e.code)?t.errors[e.code](e):e}var bt=[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]];async function xt(t,e,n){let s=e.pathParams??[],r=Ke(e,n),o=e.input==="none"?s.length:s.length+1;if(n.length>o+2)throw new f("validation",{code:"unexpected_argument",message:`${e.path}: an upload takes its path params, ${e.input==="none"?"":"its input, "}the file and options`});let d=e.input==="none"?void 0:n[s.length],a=n[o],c=n[o+1];if(!(a instanceof Blob))throw new f("validation",{code:"invalid_file",message:`${e.path}: the file is a Blob (a File is one)`});let h=`/storage/upload/${t.name}/${De(e,"the route",r.slice(1))}`;e.input==="query"&&(h+=H(d));let l=Et(e.input==="query"?void 0:d,a),u=l.body.size,g=0,i=p=>{g=p;try{c?.onProgress?.({loaded:p,total:u})}catch{}};c?.onProgress&&i(0);try{let p;try{let y={op:`Upload ${e.path}`,method:"POST",path:h,auth:bt,answers:Be,body:{kind:"raw",contentType:l.type,value:l.body},signal:c?.signal,...c?.onProgress?{onUploadProgress:b=>i(b)}:{}};p=(await t.storage.send(y)).data}catch(y){throw P(y)?K(y):y}return c?.onProgress&&g<u&&i(u),await He(e,p,c?.signal)}catch(p){throw W(e,p)}}function Et(t,e){let n=`Palbase-${G()}`,s=a=>a.replaceAll('"',"_").replace(/[\r\n]/g,""),r=typeof e.name=="string"?e.name:"blob",o=(a,c)=>`--${n}\r
|
|
7
|
+
Content-Disposition: form-data; ${a}\r
|
|
8
|
+
Content-Type: ${c}\r
|
|
9
|
+
\r
|
|
10
|
+
`,d=[];return t!==void 0&&d.push(o('name="body"',"application/json"),JSON.stringify(t),`\r
|
|
11
|
+
`),d.push(o(`name="file"; filename="${s(r)}"`,s(e.type)||"application/octet-stream"),e,`\r
|
|
12
|
+
--${n}--\r
|
|
13
|
+
`),{body:new Blob(d),type:`multipart/form-data; boundary=${n}`}}async function _t(t,e,n,s){if(typeof e!="string"||e===""||e==="/")throw new f("validation",{code:"invalid_endpoint_name",message:'Endpoint name must be a non-empty path like "todos/create"'});let r=e.startsWith("/")?e:`/${e}`;return Le(t(),{method:"POST",path:r},[n,s])}var Be=Object.fromEntries(Array.from({length:100},(t,e)=>[200+e,"raw"])),St=[["userJWT"],[]];async function Fe(t,e,n,s,r,o){let d={op:`${e.method} ${e.path}`,method:e.method,path:n,auth:St,answers:Be,headers:r,...s===void 0?{}:{body:{kind:"json",contentType:"application/json",value:s}},idempotent:e.idempotent===!0,signal:o};try{return(await t.send(d)).data}catch(a){throw P(a)?K(a):a}}async function Je(t,e,n,s,r,o){return He(e,await Fe(t,e,n,s,r,o),o)}async function He(t,e,n){let s=e.headers.get("x-request-id")??void 0,r;try{r=await e.text()}catch(o){throw n?.aborted?o:new f("network",{code:"network_error",message:`${t.method} ${t.path}: the answer did not arrive whole`,status:e.status,requestId:s,cause:o})}if(r!=="")try{return E(JSON.parse(r))}catch(o){throw new f("decode",{code:"invalid_json",message:`${t.method} ${t.path}: the answer is not JSON`,status:e.status,requestId:s,cause:o})}}async function We(t,e,n,s,r,o){let d=new AbortController;o&&(o.aborted?d.abort():o.addEventListener("abort",()=>d.abort(),{once:!0}));let a=await Fe(t,e,n,s,{accept:"text/event-stream",...r},d.signal);if(!a.body)throw new f("network",{code:"empty_stream",message:"the server answered a streaming route with no body",status:a.status});return Oe(a.body,d)}export{f as a,ae as b,Ze as c,le as d,_e as e,M as f,ft as g,en as h,tn as i};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{g as m}from"./
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{g as m}from"./S7C7NHZI.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
|
|
3
3
|
`):process.stdout.write(`${o}
|
|
4
4
|
`)}function k(n){try{return JSON.stringify(n)}catch{let e=new WeakSet;try{return JSON.stringify(n,(s,t)=>{if(typeof t=="bigint")return t.toString();if(typeof t=="object"&&t!==null){if(e.has(t))return"[circular]";e.add(t)}return t})}catch{return JSON.stringify({time:n.time,level:n.level,msg:n.msg,request_id:n.request_id,unwritable:"a field of this line could not be written"})}}}var v=h("Log",{debug:(n,e)=>l("debug",n,e),info:(n,e)=>l("info",n,e),warn:(n,e)=>l("warn",n,e),error:(n,e)=>l("error",n,e)});var L=512,_=8,q=64,D=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,S={"i-klingon":"tlh","en-gb-oed":"en-GB-oxendict","sgn-be-fr":"sfb","zh-cmn-hans":"cmn-Hans","zh-yue":"yue","hy-arevela":"hy-arevela"};function $(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function j(n){let e=n.split("-"),s=(e[0]??"").toLowerCase();return s==="mo"&&e.length===1?"ro-MD":s==="tl"?(e[0]="fil",e.join("-")):s==="sh"?(e[0]="sr",e.length>1&&/^[A-Za-z]{4}$/.test(e[1]??"")||e.splice(1,0,"Latn"),e.join("-")):n}function I(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>q)return;let s=e.toLowerCase(),t=Object.hasOwn(S,s)?S[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales(j(e))[0]}catch{return}if(t===void 0)return}let i=$(t);if(!(i===""||i==="und"||i==="mul"))return t}function z(n){let e=n.split("-"),s=e.findIndex((r,a)=>a>0&&r.length===1),t=s>0?e.slice(0,s):e,i=[],o=r=>{i.includes(r)||i.push(r)};for(let r=t.length;r>1||r===t.length;r--)o(t.slice(0,r).join("-"));if(!t.slice(1).some(r=>/^[A-Za-z]{4}$/.test(r)))try{let r=new Intl.Locale(t.join("-")).maximize().script;r&&o(`${t[0]}-${r}`)}catch{}return o(t[0]),i}function Y(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=L){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,f=r.indexOf(";");if(f>=0){let A=r.slice(f+1);r=r.slice(0,f).trim();for(let p of A.split(";")){let b=p.indexOf("=");if(b<0||p.slice(0,b).trim().toLowerCase()!=="q")continue;let y=p.slice(b+1).trim(),g=D.test(y)?Number(y):Number.NaN;a=Number.isFinite(g)&&g>=0&&g<=1?g:0}}a>0&&i.push({tag:r,q:a,at:i.length})}i.sort((o,r)=>r.q-o.q||o.at-r.at);for(let{tag:o}of i.slice(0,_)){let r=I(o);if(r!==void 0)for(let a of z(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function N(n,e,s){let t=n.strings??{},i=Object.hasOwn(t,e)?t[e]:null;for(let o of s){if(o===n.source)break;let r=i!=null&&Object.hasOwn(i,o)?i[o]:void 0;if(typeof r=="string"&&r!=="")return{text:r,locale:o}}return{text:e,locale:n.source}}var C=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function x(n,e){return n.replace(C,(s,t,i,o)=>{if(o[i-1]==="{"||o[i+s.length]==="}")return s;let r=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return r==null?"":String(r)})}var u;function W(n){u=n===void 0?void 0:{root:n,said:!1}}function Q(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,v.warn(`[palbase] t(): the app has no palbase/strings (looked in ${u.root}) \u2014 every sentence is said as it is written. \`npx palbase strings\` starts the table; an image takes it with COPY palbase ./palbase`)),x(n,e);let{text:i,locale:o}=N(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),x(i,e)}export{h as a,R as b,c,H as d,F as e,Z as f,B as g,v as h,Y as i,W as j,Q as k};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as d,m as k}from"./
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as d,m as k}from"./VP3HFVV4.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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as o,b as u}from"./XVJ3CMFN.js";var c={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it",ai_budget_reached:()=>"the project's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or an owner or admin raises the budget (Studio \u203A AI \u203A Settings, or palbase ai:settings:set --monthly-budget) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",ai_payment_required:()=>"the month's free AI dollar is spent and the project has no paid rights now to pay for Palbase's models (it is on Free, at its month's limit, or its payment account has an unpaid charge): move it to Pay as you go (Studio \u203A Billing) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",billing_unavailable:t=>`Palbase's billing did not say whether its models serve the project${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,client_handoff_disabled:()=>"app users may not hand off chats in this project: enable allow_client_handoff in AI settings, or trigger the handoff from your server",superseded:()=>"this chat has already moved to a newer execution target generation",machine_not_found:()=>"the target machine is not enrolled in this project's runner pools",harness_unavailable:()=>"the requested ACP CLI harness is not ready on the target machine",handoff_requires_idle:()=>"a turn is currently running in this chat: pass when: 'after_turn' or when: 'now' to hand off"},g=new WeakSet;function f(t){if(!(t instanceof u)||g.has(t))return t;let e=c[t.code];if(!e)return t;let r=new u({op:t.op,status:t.status,code:t.code,message:`${e(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(r),r}function m(t){return t.catch(e=>{throw f(e)})}function h(t){if(typeof t!="object"||t===null)return;let e=t,r=e.data;if(typeof e.type!="string"||typeof r!="object"||r===null||Array.isArray(r))return;let n=o(r),i=typeof e.id=="number"&&Number.isSafeInteger(e.id)?e.id:0,s=p(e.type,n,i);return s!==void 0&&s.type!=="history"&&typeof t.at=="string"&&t.at!==""&&(s.at=t.at),s}function p(t,e,r){switch(t){case"message":return typeof e.client_id=="string"?{type:"message",seq:r,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:r};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:r,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:r}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:r,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:r,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...i}=e;return{...i,type:"goal",seq:r,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(s=>typeof s=="object"&&s!==null&&(s.role==="user"||s.role==="assistant")&&typeof s.text=="string"),i=e.forked_from;return{type:"history",forked_from:i&&typeof i.chat_id=="string"?i:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:r,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:r,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};case"session.handed_off":return typeof e.to_target!="object"||e.to_target===null||typeof e.generation!="number"?void 0:{type:"session.handed_off",seq:r,chat_id:typeof e.chat_id=="string"?e.chat_id:"",generation:e.generation,...typeof e.from_target=="object"&&e.from_target!==null?{from_target:e.from_target}:{},to_target:e.to_target,reason:typeof e.reason=="string"?e.reason:"",workspace_seq:typeof e.workspace_seq=="number"?e.workspace_seq:0};case"session.machine_status":return typeof e.status!="string"?void 0:{type:"session.machine_status",seq:r,chat_id:typeof e.chat_id=="string"?e.chat_id:"",machine_id:typeof e.machine_id=="string"?e.machine_id:"",status:e.status,...e.failover_at===null||typeof e.failover_at=="string"?{failover_at:e.failover_at}:{}};case"context.offloaded":return{type:"context.offloaded",seq:r,call_id:typeof e.call_id=="string"?e.call_id:"",...typeof e.storage=="string"?{storage:e.storage}:{},...typeof e.ref=="string"?{ref:e.ref}:{},...typeof e.original_bytes=="number"?{original_bytes:e.original_bytes}:{},...typeof e.stub_bytes=="number"?{stub_bytes:e.stub_bytes}:{}};case"context.compacted":return{type:"context.compacted",seq:r,...typeof e.format=="string"?{format:e.format}:{},...typeof e.messages_compacted=="number"?{messages_compacted:e.messages_compacted}:{},...typeof e.tokens_before=="number"?{tokens_before:e.tokens_before}:{},...typeof e.tokens_after=="number"?{tokens_after:e.tokens_after}:{},...typeof e.preserved_attachments_count=="number"?{preserved_attachments_count:e.preserved_attachments_count}:{},...typeof e.project_directives_count=="number"?{project_directives_count:e.project_directives_count}:{},...typeof e.cache_friendly=="boolean"?{cache_friendly:e.cache_friendly}:{}};default:return}}function y(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e=o(t);if(!(typeof e.chat_id!="string"||e.chat_id===""||typeof e.run_status!="string"||typeof e.target_generation!="number")&&!(typeof e.target_summary!="object"||e.target_summary===null))return{chat_id:e.chat_id,run_status:e.run_status,...typeof e.active_run_id=="string"&&e.active_run_id!==""?{active_run_id:e.active_run_id}:{},...typeof e.workspace_id=="string"&&e.workspace_id!==""?{workspace_id:e.workspace_id}:{},target_generation:e.target_generation,target_summary:e.target_summary,updated_at:typeof e.updated_at=="string"?e.updated_at:""}}function v(t){let e=0;for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);n<128?e+=1:n<2048?e+=2:n>=55296&&n<=56319&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(e+=4,r++):e+=3}return e}function d(t,e){if(e<=0)return 0;let r=0;for(let n=0;n<t.length;n++){let i=t.charCodeAt(n),s=3,a=1;if(i<128?s=1:i<2048?s=2:i>=55296&&i<=56319&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320&&(s=4,a=2),r+=s,r>=e)return n+a;n+=a-1}return t.length}function w(t,e){return t.slice(d(t,e))}export{m as a,h as b,y as c,v as d,d as e,w as f};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
function o(){let n=globalThis;if(typeof n.document<"u"||n.navigator?.product==="ReactNative")return!0;let t=n.navigator?.userAgent;return typeof t=="string"&&t.startsWith("Mozilla/")}export{o as a};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{p as R,t as Y,u as k}from"./
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{p as R,t as Y,u as k}from"./QOETZ4FB.js";var $=40,z=`
|
|
3
3
|
:host{display:contents}
|
|
4
4
|
.pm-modal,.pm-full{position:fixed;inset:0;width:100%;height:100%;max-width:none;max-height:none;margin:0;border:0;background:transparent;color:inherit;overflow:hidden;display:flex;flex-direction:column}
|
|
5
5
|
.pm-modal::backdrop,.pm-full::backdrop{background:transparent}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as l}from"./
|
|
1
|
+
/*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as l}from"./XVJ3CMFN.js";var g=/^[A-Za-z0-9_.:-]{1,160}$/,y=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]/u,p="128 bytes at most, no control, format (bidi, zero-width) or line-separator character";function o(e,t,i){if(typeof e!="string"||!g.test(e))throw new TypeError(`${t}: ${i} (got ${JSON.stringify(e)})`);return e}var f="the machine is one of the person's machines, by its id (machines.list)",c="owner is the user's id";function m(e){return{name:e.name,...e.acp_version!==void 0?{acpVersion:e.acp_version}:{},...e.cli_version!==void 0?{cliVersion:e.cli_version}:{},status:e.status}}function w(e){return{url:e.url,...e.server_name?{serverName:e.server_name}:{},...e.ca_certificate?{caCertificate:e.ca_certificate}:{}}}function h(e){return{id:e.id,name:e.name,owner:e.owner??null,...e.pool_id?{poolId:e.pool_id}:{},...e.os?{os:e.os}:{},...e.arch?{arch:e.arch}:{},state:e.state,lastSeenAt:e.last_seen_at??null,registeredAt:e.registered_at??null,...e.harnesses!==void 0?{harnesses:e.harnesses.map(m)}:{}}}function M(e){if(typeof e.key!="string"||e.key==="")throw new l({op:"createMachineKey",status:502,code:"no_key",message:`the machine key ${e.id} was minted but not said: mint another (it enrols nothing unused in 15 minutes)`});return{id:e.id,key:e.key,owner:e.owner,poolId:e.pool_id,...e.label?{label:e.label}:{},...e.created_at!==void 0?{createdAt:e.created_at}:{},enroll:w(e.enroll)}}function _(e,t){return e.length===t.length&&e.every((i,s)=>d(i,t[s]))}function d(e,t){if(e===t)return!0;if(typeof e!="object"||typeof t!="object"||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;let i=Object.keys(e),s=Object.keys(t);return i.length===s.length&&i.every(a=>Object.prototype.hasOwnProperty.call(t,a)&&d(e[a],t[a]))}function A(e,t,i=f){let s=t==="server",a=i;return{keys:{async create(n){if(typeof n!="object"||n===null)throw new TypeError("machines.keys.create: { os, arch, owner, label }");if(n.os!=="macos"&&n.os!=="linux")throw new TypeError("machines.keys.create: os is the machine's operating system, macos or linux");if(n.arch!=="arm64"&&n.arch!=="amd64")throw new TypeError("machines.keys.create: arch is the machine's architecture, arm64 or amd64");let r={os:n.os,arch:n.arch};if((n.owner!==void 0||s)&&(r.owner=o(n.owner,"machines.keys.create",s?`${c} the machine will belong to: the project's server names one`:c)),n.label!==void 0){if(typeof n.label!="string"||new TextEncoder().encode(n.label).byteLength>128||y.test(n.label))throw new TypeError(`machines.keys.create: label is what the key is for, ${p}`);r.label=n.label}return M((await e.createMachineKey({body:r,signal:n.signal})).data)}},async list(n={}){let r=n.owner!==void 0||s?o(n.owner,"machines.list",s?`${c} whose machines to list: the project's server names one`:c):void 0;return(await e.listMachines({...r!==void 0?{query:{owner:r}}:{},signal:n.signal})).data.machines.map(h)},async get(n,r={}){return h((await e.getMachine({path:{machine:o(n,"machines.get",a)},signal:r.signal})).data)},async cordon(n,r={}){await e.cordonMachine({path:{machine:o(n,"machines.cordon",a)},signal:r.signal})},async resume(n,r={}){await e.resumeMachine({path:{machine:o(n,"machines.resume",a)},signal:r.signal})},async delete(n,r={}){let u=o(n,"machines.delete",a);if(r.now!==void 0&&typeof r.now!="boolean")throw new TypeError("machines.delete: now is true (delete it whatever it does) or false");await e.deleteMachine({path:{machine:u},...r.now!==void 0?{query:{now:r.now}}:{},signal:r.signal})}}}export{m as a,h as b,_ as c,A as d};
|