palbase 0.71.0 → 0.72.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 +11 -11
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{6DOVOQD7.js → 3MF6NROQ.js} +2 -2
- package/dist/chunks/{FHSOCZK5.js → 7TZJLWWX.js} +2 -2
- package/dist/chunks/CYS75YV4.js +2 -0
- package/dist/chunks/{4RTYKYU6.js → D5I74USX.js} +2 -2
- package/dist/chunks/{C7I5HJWB.js → DE7BWXBF.js} +1 -1
- package/dist/chunks/{WDNAIUED.js → E2MNCFOU.js} +1 -1
- package/dist/chunks/{WMXNVSHQ.js → F4LE2YZX.js} +2 -2
- package/dist/chunks/{STC7LMPR.js → I4SH2RTD.js} +1 -1
- package/dist/chunks/{NWKQOVQV.js → JMNQRIEG.js} +2 -2
- package/dist/chunks/{S6FTHDCG.js → JP55FW66.js} +2 -2
- package/dist/chunks/{NNFT2MAJ.js → JXIKBG4D.js} +1 -1
- package/dist/chunks/{P2ZR3LIZ.js → LDFOUUBT.js} +2 -2
- package/dist/chunks/{PZEHNKUJ.js → MB6ITBD2.js} +1 -1
- package/dist/chunks/{AVLXOKYL.js → MVVULWTH.js} +2 -2
- package/dist/chunks/{KWAJFRHM.js → O6JNTYC5.js} +2 -2
- package/dist/chunks/{6I2XBWUM.js → OY2MT7N5.js} +2 -2
- package/dist/chunks/{F5D2WPY6.js → QDPRR5PE.js} +2 -2
- package/dist/chunks/{5EP5JREH.js → QROXSSPQ.js} +1 -1
- package/dist/chunks/{WYZDZ7QZ.js → S3N7N6UD.js} +2 -2
- package/dist/chunks/UXU6RXU3.js +23 -0
- package/dist/chunks/{6G26LJYB.js → WWXBXZUO.js} +1 -1
- package/dist/chunks/XUYC354U.js +2 -0
- package/dist/chunks/{P2PPTVZS.js → Y7ZJ3M5F.js} +2 -2
- package/dist/chunks/ZHSM4NCV.js +13 -0
- package/dist/cli.js +342 -342
- 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/backend/src/index.d.ts +1 -1
- package/types/backend/src/services.d.ts +47 -0
- package/types/cloud/src/generated/project.d.ts +2 -1
- package/types/internal/src/modules/commerce.d.ts +4244 -0
- package/types/internal/src/modules/events.d.ts +4 -3
- package/types/internal/src/modules/index.d.ts +1 -0
- package/types/internal/src/modules/payments.d.ts +851 -2
- package/types/server/src/commerce.d.ts +78 -0
- package/types/server/src/index.d.ts +2 -1
- package/types/server/src/payments.d.ts +6 -0
- package/types/server/src/server.d.ts +2 -0
- package/types/web/src/client.d.ts +3 -0
- package/types/web/src/commerce.d.ts +130 -0
- package/types/web/src/index.d.ts +1 -0
- package/dist/chunks/AYPODLGK.js +0 -23
- package/dist/chunks/E3JCXDTW.js +0 -2
- package/dist/chunks/LCZZSEYY.js +0 -2
- package/dist/chunks/WL7Z55QJ.js +0 -13
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.72.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a,b,c,d,e,f,g}from"../chunks/O6JNTYC5.js";import"../chunks/D5I74USX.js";import"../chunks/JXIKBG4D.js";import"../chunks/XUYC354U.js";import"../chunks/3MF6NROQ.js";import"../chunks/LDFOUUBT.js";import"../chunks/WWXBXZUO.js";import"../chunks/E2MNCFOU.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.72.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import"../chunks/E2MNCFOU.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.72.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{ha as w,la as h}from"../chunks/S3N7N6UD.js";import"../chunks/OY2MT7N5.js";import"../chunks/QDPRR5PE.js";import"../chunks/O6JNTYC5.js";import"../chunks/D5I74USX.js";import"../chunks/CYS75YV4.js";import"../chunks/DE7BWXBF.js";import"../chunks/JXIKBG4D.js";import"../chunks/XUYC354U.js";import"../chunks/QROXSSPQ.js";import"../chunks/3MF6NROQ.js";import"../chunks/LDFOUUBT.js";import"../chunks/WWXBXZUO.js";import"../chunks/E2MNCFOU.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.72.0 — Palbase SDK License (see LICENSE) */
|
package/dist/backend/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{$ as $t,A as I,B as dt,C as ut,D as pt,E as ft,F as ht,G as gt,H as bt,I as mt,J as yt,K as wt,L as Pt,M as St,N as vt,O as At,P as kt,Q as Et,R as Rt,S as _t,T as xt,U as Ot,V as Tt,W as Ct,X as ne,Y as Bt,Z as Ft,_ as Lt,a as Z,aa as It,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 ze,ja as Vt,k as He,ka as Gt,l as Ye,m as Je,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as st,t as rt,u as nt,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/WYZDZ7QZ.js";import{a as Nt,b as qt}from"../chunks/6I2XBWUM.js";import{a as oe}from"../chunks/STC7LMPR.js";import{a as C,b as se,c as re,f as b,g as V,h as d,j as ae,k as Kt}from"../chunks/F5D2WPY6.js";import"../chunks/KWAJFRHM.js";import"../chunks/4RTYKYU6.js";import{d as T,j as Ue,k as je,l as J,m as $,y as Q,z as X}from"../chunks/E3JCXDTW.js";import"../chunks/C7I5HJWB.js";import"../chunks/NNFT2MAJ.js";import{r as De}from"../chunks/LCZZSEYY.js";import"../chunks/5EP5JREH.js";import"../chunks/6DOVOQD7.js";import{b as _,c as W}from"../chunks/P2ZR3LIZ.js";import"../chunks/6G26LJYB.js";import"../chunks/WDNAIUED.js";import"reflect-metadata";import{existsSync as H,writeFileSync as $s,writeSync as Is}from"node:fs";import{createServer as Ms}from"node:http";import{dirname as x,join as Y,resolve as xe}from"node:path";import{Readable as Ds}from"node:stream";var zt=2e3,Ht=1e4,Yt=/^[A-Za-z0-9_-]{1,64}$/,Jt=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,s={}){this.sink=e,this.linesPerSecond=s.linesPerSecond??10,this.batchSize=Math.min(100,s.batchSize??100),this.flushMs=s.flushMs??2e3,this.maxPending=s.maxPending??2e3,this.sendMs=s.sendMs??Ht,this.shutdownMs=s.shutdownMs??zt,this.now=s.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,s,r=new Promise(a=>s=a),n=setTimeout(()=>{e=!0,s()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),r]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,s=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),s>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${s} dropped`)}log(e){let s=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(s-this.refilled)/1e3*this.linesPerSecond),this.refilled=s,this.unlogged>0&&s-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=s),this.tokens<1){this.unlogged===0&&(this.unloggedSince=s),this.unlogged++;return}this.tokens-=1;let r=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[r](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Yt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Jt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),s=this.sink,r={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=r;let n=setTimeout(()=>r.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await s.sendTraceBatch({body:{traces:e},signal:r.call.signal})}catch(a){if(r.letGo)return;let l=a.status,i=l??(r.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:l===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${i}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Qt}from"node:crypto";import{readFileSync as Xt}from"node:fs";import{bind as Zt,bunDriver as es,createDatabase as ts,pooledBinding as ss,sayRunning as rs,envBlock as ns,createSearchWorker as as,cutOff as os,forgetUserIn as is,MigrationOpen as ls,MigrationRefused as cs,Migrator as de,VersionNotMigrated as ds}from"palgres";import{toModel as us}from"palgres/dsl";var ps=["start","complete","rollback","plan","status","types"],fs=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function ue(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!ps.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function pe(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let s of e)if(s.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function fe(t){let e=t.access;if(e===void 0||typeof e=="string")return e;try{return Xt(e,"utf8")}catch(s){throw new Error(`[palbase] db.access: ${e.href} could not be read (${s instanceof Error?s.message:String(s)}) \u2014 it is the file the app's access schema is in`)}}function F(t){let e=fe(t);return us(pe(t),e===void 0?{}:{access:e})}function hs(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(s=>s.user!==void 0&&!s.ignored))}function he(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let s=Number(e);if(!Number.isSafeInteger(s)||s<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return s}function gs(t,e){if(t.url!==void 0||t.driver!==void 0)return;let s=e.PALBASE_DB_POOLED_URL;return s===void 0||s===""?void 0:s}function bs(t){let e=t.PALBASE_DB_POOLED_CONNECTIONS;if(e===void 0||e==="")return 12;let s=Number(e);if(!Number.isSafeInteger(s)||s<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 s}var ms=2,ys=5e3;async function ws(t,e,s=ys){let r=await t.reserve();try{await r.unsafe(e)}catch(o){throw r.release(),o}let n=r,a=!1,l=!1,i=async()=>{if(n!==void 0)try{await n.unsafe("SELECT 1");return}catch{n.release(),n=void 0}let o=await t.reserve();try{await o.unsafe(e)}catch(u){throw o.release(),u}a?o.release():n=o},c=setInterval(()=>{l||a||(l=!0,i().catch(o=>d.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 ${s/1e3} s`)).finally(()=>{l=!1}))},s);return c.unref?.(),{stop(){a=!0,clearInterval(c),n?.release(),n=void 0}}}function Ps(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 z(t,e){if(t.driver)return t.driver;let s=globalThis.Bun;if(!s)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let r=e-1;return n=>{let a=new s.SQL({url:n,prepare:!1,max:r}),l=new s.SQL({url:n,prepare:!1,max:1});return{pool:{reserve:()=>a.reserve(),unsafe:(i,c)=>a.unsafe(i,c),begin:i=>a.begin(i)},engine:es(a,l),poolSize:r,close:async()=>{await a.close({timeout:ie}),await l.close({timeout:ie})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await B(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let s=Array.isArray(t.schemas)?t.schemas:[t.schemas],r=fe(t);return await B("types",ns(s,{module:"palbase/backend/env",...r===void 0?{}:{access:r}}),e),0}async function me(t,e,s){let r=e.PALBASE_DB_OWNER_URL;if(!r)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!fs.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=z(t,he(e)),l=a(r),i,c=o=>d.error(`[palbase] migrate ${s}: ${o}`);try{let o=F(t),u=new de(l.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(i=f.trim()),d.info(f)},shadow:f=>{let w=new URL(r);w.pathname=`/${f}`;let m=a(w.toString());return{reserve:()=>m.pool.reserve(),end:()=>m.close()}},openedBy:n,fields:()=>Ss(e)});if(s==="plan"){let f=await u.plan(o);return await B(s,f),f.refusals.length>0?1:0}if(s==="status")return await B(s,await u.status()),0;let p=s==="start"?await vs(u,o,n):s==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${s}: done`,{result:p}),await B(s,p),0}catch(o){return o instanceof cs?(d.error(`[palbase] migrate ${s}: refused`,{refusals:o.refusals}),c(`refused \u2014 ${o.refusals.join("; ")}`),1):os(o)?(d.error(`[palbase] migrate ${s}: cut off; run again, it goes on from where it stopped`,{error:o}),c(`cut off \u2014 ${i??le(o)}`),75):(d.error(`[palbase] migrate ${s}: failed`,{error:o}),c(`failed \u2014 ${le(o)}`),1)}finally{await l.close().catch(()=>{})}}async function Ss(t){let e=t.PALBASE_URL,s=t.PALBASE_SECRET_KEY;if(!e||!s)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let r=T({url:e,secretKey:s}).fields;return await r.load(),r.close(),r}async function vs(t,e,s){try{return await t.start(e)}catch(r){if(!(r instanceof ls)||s!=="deploy"||!r.openedBy?.startsWith("cli:"))throw r;return d.warn(`[palbase] migrate start: the migration ${r.openedBy} opened (version ${r.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var As=(t,e)=>{process.stdout.write(t,()=>e())};function B(t,e,s=As){return new Promise(r=>s(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
3
|
-
`,
|
|
4
|
-
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function
|
|
5
|
-
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=
|
|
6
|
-
- ${
|
|
7
|
-
- `)}`);return{url:a,projectId:l,secretKey:i,webhookSecret:
|
|
8
|
-
${
|
|
1
|
+
/*! palbase 0.72.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{$ as Lt,A as $,B as ut,C as dt,D as pt,E as mt,F as gt,G as ft,H as ht,I as bt,J as yt,K as wt,L as Pt,M as St,N as vt,O as kt,P as At,Q as Rt,R as Et,S as _t,T as Ot,U as xt,V as Tt,W as Ct,X as ne,Y as Bt,Z as Ft,_ as It,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 Ye,m as Je,n as Qe,o as Xe,p as Ze,q as et,r as tt,s as rt,t as st,u as nt,v as at,w as ot,x as it,y as lt,z as ct}from"../chunks/S3N7N6UD.js";import{a as Nt,b as qt}from"../chunks/OY2MT7N5.js";import{a as oe}from"../chunks/I4SH2RTD.js";import{a as E,b as re,c as se,f as d,g as V,h as u,j as ae,k as Kt}from"../chunks/QDPRR5PE.js";import"../chunks/O6JNTYC5.js";import"../chunks/D5I74USX.js";import{C as Q,D as X,d as C,j as Ue,k as je,l as J,m as L}from"../chunks/CYS75YV4.js";import"../chunks/DE7BWXBF.js";import"../chunks/JXIKBG4D.js";import{s as De}from"../chunks/XUYC354U.js";import"../chunks/QROXSSPQ.js";import"../chunks/3MF6NROQ.js";import{b as O,c as W}from"../chunks/LDFOUUBT.js";import"../chunks/WWXBXZUO.js";import"../chunks/E2MNCFOU.js";import"reflect-metadata";import{existsSync as z,writeFileSync as Lr,writeSync as $r}from"node:fs";import{createServer as Mr}from"node:http";import{dirname as x,join as Y,resolve as Oe}from"node:path";import{Readable as Dr}from"node:stream";var Ht=2e3,zt=1e4,Yt=/^[A-Za-z0-9_-]{1,64}$/,Jt=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,r={}){this.sink=e,this.linesPerSecond=r.linesPerSecond??10,this.batchSize=Math.min(100,r.batchSize??100),this.flushMs=r.flushMs??2e3,this.maxPending=r.maxPending??2e3,this.sendMs=r.sendMs??zt,this.shutdownMs=r.shutdownMs??Ht,this.now=r.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,r,s=new Promise(a=>r=a),n=setTimeout(()=>{e=!0,r()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),s]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,r=(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`))),r>0&&u.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${r} dropped`)}log(e){let r=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(r-this.refilled)/1e3*this.linesPerSecond),this.refilled=r,this.unlogged>0&&r-this.unloggedSince>=6e4&&(u.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=r),this.tokens<1){this.unlogged===0&&(this.unloggedSince=r),this.unlogged++;return}this.tokens-=1;let s=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;u[s](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Yt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Jt),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),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let l=a.status,i=l??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:l===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),u.warn(`[palbase] request traces were not sent to analytics (${i}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Qt}from"node:crypto";import{readFileSync as Xt}from"node:fs";import{bind as Zt,bunDriver as er,createDatabase as tr,pooledBinding as rr,sayRunning as sr,envBlock as nr,createSearchWorker as ar,cutOff as or,forgetUserIn as ir,MigrationOpen as lr,MigrationRefused as cr,Migrator as ue,VersionNotMigrated as ur}from"palgres";import{toModel as dr}from"palgres/dsl";var pr=["start","complete","rollback","plan","status","types"],mr=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function de(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!pr.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 r of e)if(r.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 me(t){let e=t.access;if(e===void 0||typeof e=="string")return e;try{return Xt(e,"utf8")}catch(r){throw new Error(`[palbase] db.access: ${e.href} could not be read (${r instanceof Error?r.message:String(r)}) \u2014 it is the file the app's access schema is in`)}}function F(t){let e=me(t);return dr(pe(t),e===void 0?{}:{access:e})}function gr(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(r=>r.user!==void 0&&!r.ignored))}function ge(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let r=Number(e);if(!Number.isSafeInteger(r)||r<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 r}function fr(t,e){if(t.url!==void 0||t.driver!==void 0)return;let r=e.PALBASE_DB_POOLED_URL;return r===void 0||r===""?void 0:r}function hr(t){let e=t.PALBASE_DB_POOLED_CONNECTIONS;if(e===void 0||e==="")return 12;let r=Number(e);if(!Number.isSafeInteger(r)||r<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 r}var br=2,yr=5e3;async function wr(t,e,r=yr){let s=await t.reserve();try{await s.unsafe(e)}catch(o){throw s.release(),o}let n=s,a=!1,l=!1,i=async()=>{if(n!==void 0)try{await n.unsafe("SELECT 1");return}catch{n.release(),n=void 0}let o=await t.reserve();try{await o.unsafe(e)}catch(p){throw o.release(),p}a?o.release():n=o},c=setInterval(()=>{l||a||(l=!0,i().catch(o=>u.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 ${r/1e3} s`)).finally(()=>{l=!1}))},r);return c.unref?.(),{stop(){a=!0,clearInterval(c),n?.release(),n=void 0}}}function Pr(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 r=globalThis.Bun;if(!r)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 s=e-1;return n=>{let a=new r.SQL({url:n,prepare:!1,max:s}),l=new r.SQL({url:n,prepare:!1,max:1});return{pool:{reserve:()=>a.reserve(),unsafe:(i,c)=>a.unsafe(i,c),begin:i=>a.begin(i)},engine:er(a,l),poolSize:s,close:async()=>{await a.close({timeout:ie}),await l.close({timeout:ie})}}}}async function fe(t){return t==="rollback"?(u.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await B(t,{state:"none"}),0):(u.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function he(t,e){if(!t)return u.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas],s=me(t);return await B("types",nr(r,{module:"palbase/backend/env",...s===void 0?{}:{access:s}}),e),0}async function be(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return u.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!mr.test(n))return u.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=H(t,ge(e)),l=a(s),i,c=o=>u.error(`[palbase] migrate ${r}: ${o}`);try{let o=F(t),p=new ue(l.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(i=f.trim()),u.info(f)},shadow:f=>{let P=new URL(s);P.pathname=`/${f}`;let y=a(P.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>Sr(e)});if(r==="plan"){let f=await p.plan(o);return await B(r,f),f.refusals.length>0?1:0}if(r==="status")return await B(r,await p.status()),0;let m=r==="start"?await vr(p,o,n):r==="complete"?await p.complete():await p.rollback();return u.info(`[palbase] migrate ${r}: done`,{result:m}),await B(r,m),0}catch(o){return o instanceof cr?(u.error(`[palbase] migrate ${r}: refused`,{refusals:o.refusals}),c(`refused \u2014 ${o.refusals.join("; ")}`),1):or(o)?(u.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:o}),c(`cut off \u2014 ${i??le(o)}`),75):(u.error(`[palbase] migrate ${r}: failed`,{error:o}),c(`failed \u2014 ${le(o)}`),1)}finally{await l.close().catch(()=>{})}}async function Sr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)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 s=C({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function vr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof lr)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return u.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var kr=(t,e)=>{process.stdout.write(t,()=>e())};function B(t,e,r=kr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
|
|
3
|
+
`,s))}function le(t){return(t instanceof Error?t.message:String(t)).split(`
|
|
4
|
+
`)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function Ar(t,e){try{return await new ue(t).plan(e)}catch{return}}var ce="palbase.idempotency_keys.response_body";function Rr(t,e){let r=null,s=!1,n=async()=>{let i=e.currentKey();if(!(s||i===r)){s=!0;try{let c=await t.reseal();r=i;let o=c.reduce((p,m)=>p+m.resealed,0);o>0&&u.info(`[palbase] fields: ${o} value(s) sealed again with key ${i}`,{report:c})}catch(c){u.warn(`[palbase] fields: sealing again with key ${i} stopped; tried again in a minute`,{error:c})}finally{s=!1}}},a=setTimeout(n,1e4),l=setInterval(n,6e4);for(let i of[a,l])i.unref?.();return()=>{clearTimeout(a),clearInterval(l)}}var j=class extends Error{digest;plan;constructor(e,r){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>)`,...r?Er(r):[" palbase db:plan says what it would change"]].join(`
|
|
5
|
+
`)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function Er(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 r of t.changes)e.push(` + ${r}`);for(let r of t.refusals)e.push(` \u2717 ${r}`);return e}var _r=8e4;async function ye(t,e,r,s){let n=t.url??e.PALBASE_DB_URL;if(!n)throw new Error("[palbase] db.url / PALBASE_DB_URL is the database the app connects to");let a=pe(t),l=F(t),i=fr(t,e),c=H(t,i===void 0?ge(e):br)(n),o,p;try{let m=!1,f=b=>{m||(m=!0,u.warn(`[palbase] database: not answering yet (${b instanceof Error?b.message:String(b)}) \u2014 waiting for it, as one waking does`))},P=await Zt(c.engine,l,{waitMs:s.onPlatform?_r:0,onUnreachable:f}).catch(async b=>{throw s.onPlatform||!(b instanceof ur)?b:new j(b.digest,await Ar(c.pool,l))});i!==void 0&&(p=await wr(c.pool,sr(P)),o=H(t,hr(e))(i));let y=o??c,k=Qt("sha256",r).update("palgres page cursor").digest("hex"),w=t.embed??s.embed,h=s.fields,A=await tr({sql:y.engine,schemas:a,binding:o===void 0?P:rr(P),...o===void 0?{}:{prepare:!1},cursorSecret:k,admission:Pr(y.poolSize),embed:w,log:b=>u.warn(`[palbase] ${b}`),fields:async()=>(await h.load(),h)}),R=h.loaded?Rr(A,h):()=>{},_=gr(l)?ar({sql:y.engine,embed:w,log:b=>u.info(`[palbase] ${b}`)}):void 0;return{model:l,binding:P,app:A,requests:t.requests??"caller",forget:(b,S)=>ir({attempt:v=>S.$attempt(v)},P,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()=>{R(),h.close(),await o?.close(),p?.stop(),await c.close()}}}catch(m){throw await o?.close().catch(()=>{}),p?.stop(),await c.close(),m}}function Or(t){let e=Buffer.from(t,"base64"),r=new Array(e.byteLength/4);for(let s=0;s<r.length;s++)r[s]=e.readFloatLE(s*4);return r}function we(t){return async({texts:e,model:r,dimensions:s})=>{let{data:n}=await t.ai.createEmbeddings({body:{input:e,model:r,dimensions:s}});return{model:n.model,vectors:n.vectors.map(Or)}}}var xr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Pe(t,e,r){let s=[],n=t.url??e.PALBASE_URL??"",a="";try{let p=new URL(n);a=p.origin,p.protocol!=="https:"&&p.hostname!=="localhost"&&p.hostname!=="127.0.0.1"&&s.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(p.pathname!=="/"||p.search||p.hash)&&s.push("palbase.url / PALBASE_URL is the project origin alone")}catch{s.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let l=t.projectId??e.PALBASE_PROJECT_ID??"";xr.test(l)||s.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)||s.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let c=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;c!==void 0&&!/^[0-9a-f]{64}$/.test(c)&&s.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(r.needsWebhookSecret&&(c!==void 0||o!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(o??"")&&s.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"),s.length>0)throw new Error(`[palbase] the app cannot start:
|
|
6
|
+
- ${s.join(`
|
|
7
|
+
- `)}`);return{url:a,projectId:l,secretKey:i,webhookSecret:r.needsWebhookSecret?o:void 0,platformSecret:c}}import{createHash as Tr}from"node:crypto";import{writeSync as Cr}from"node:fs";import{gzipSync as Br}from"node:zlib";var Fr="palbase-contract-v1 begin",Ir="palbase-contract-v1 end",Se=76;function ve(t){let e=Buffer.from(t,"utf8"),r=Br(e).toString("base64"),s=[`${Fr} ${Tr("sha256").update(e).digest("hex")} ${e.length}`];for(let n=0;n<r.length;n+=Se)s.push(r.slice(n,n+Se));return s.push(Ir),`
|
|
8
|
+
${s.join(`
|
|
9
9
|
`)}
|
|
10
|
-
`}async function
|
|
11
|
-
`),process.exit(1),new
|
|
12
|
-
`),process.exit(0),new L}let l=Re(r),i=await _e(l);i&&d.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 c=e.db?F(e.db):void 0,o=await X({env:r,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&d.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&&d.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 u=Ns(s)||c!==void 0&&N(c),p=Pe(e.palbase??{},r,{needsWebhookSecret:u});u&&p.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=T({url:p.url,secretKey:p.secretKey}),w=e.port??Number(r.PORT??"8080");if(!Number.isInteger(w)||w<0||w>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??r.PORT)}`);let m=e.db?await ye(e.db,r,p.secretKey,{onPlatform:p.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;m&&d.info(`[palbase] database: version ${m.binding.version}`);let A=m&&N(m.model)?{"user.deleted":[P=>Ws(m,P)]}:void 0,y=p.platformSecret===void 0?void 0:{secret:p.platformSecret},h=e.requestTelemetry===!1?void 0:new U(f.analytics),k=()=>D({modules:s,verifier:new $({issuer:p.url,projectId:p.projectId,standing:J({url:p.url,secretKey:p.secretKey})}),server:f,webhookSecret:p.webhookSecret,env:r,projectId:p.projectId,telemetry:h,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:zs(e.cors,r.PALBASE_WEB_ORIGINS),platform:y,events:A,database:m&&{app:m.app,requests:m.requests,keptAnswers:m.keptAnswers},strings:i}),E=k(),R=e.boot?.attempts??5,g=e.boot?.backoffMs??1e3;for(let P=1;;P++)try{await E.start();break}catch(v){if(P>=R)throw d.error(`[palbase] the app did not start after ${R} attempts`,{error:v}),v;d.warn(`[palbase] the app did not start (attempt ${P} of ${R}); trying again in ${g} ms`,{error:v}),await new Promise(Me=>setTimeout(Me,g)),g*=2,E=k()}return Vs(E,f,w,e.host??"0.0.0.0",e.exitOnFatal??!0,m)}};function Re(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let s=x(xe(e));for(;!H(Y(s,"package.json"))&&x(s)!==s;)s=x(s);return H(Y(s,"package.json"))?s: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 Ks(t,e,s){let r=xe(s.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(r))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${r||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=x(r);for(;!H(Y(n,"package.json"))&&x(n)!==n;)n=x(n);let{analyzeProject:a}=await import("../chunks/FHSOCZK5.js"),{routeContracts:l}=await import("../chunks/AVLXOKYL.js"),i=a(n,r);for(let u of i.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",o=D({modules:t,verifier:new $({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:T({url:c,secretKey:"pb_contract_s"}),env:s,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await l(i.routes),errors:ne()},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 Ws(t,e){let s=e.data?.user_id;if(typeof s!="string"||s==="")throw new Error("[palbase] user.deleted without a user_id");let r=await t.forget(s,V.$asService());d.info(`[palbase] user ${s} 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 Vs(t,e,s,r,n,a){let l,i={on:!1},c=(y,h)=>new URL(y.url).pathname===js&&y.method==="GET"?Promise.resolve(i.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(y,h),o=Ms((y,h)=>{Gs(c,y,h,i).finally(()=>{i.on&&o.closeIdleConnections()})});o.keepAliveTimeout=29e4,o.headersTimeout=3e5;try{await new Promise((y,h)=>{o.once("error",h),o.listen(s,r,()=>y())})}catch(y){throw await t.stop(),await a?.close(),y}let u=o.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let p=y=>l??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),i.on=!0;let h=new Promise(E=>o.close(()=>E()));o.closeIdleConnections();let k=setTimeout(()=>o.closeAllConnections(),y);await h,clearTimeout(k),process.off("SIGINT",m),process.off("uncaughtException",A),process.off("unhandledRejection",A);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",m)}})(),f=()=>p(ke),w=!1,m=()=>{if(w){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}w=!0;let y=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},ke+Us);y.unref(),f().then(()=>{clearTimeout(y),process.exit(0)},h=>{clearTimeout(y),d.error("[palbase] stopping failed; the process ends",{error:h}),process.exit(1)})},A=y=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:y});let h=setTimeout(()=>process.exit(1),Ee+1e3);p(Ee).finally(()=>{clearTimeout(h),process.exit(1)})};return process.on("SIGTERM",m),process.once("SIGINT",m),n&&(process.on("uncaughtException",A),process.on("unhandledRejection",A)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Gs(t,e,s,r){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{s.statusCode=400,s.end();return}let l=new Headers;for(let[p,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let w of f)l.append(p,w);else l.set(p,f);let i=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;s.on("close",()=>{s.writableFinished||c.abort(new Error("the client closed the connection"))});let o=new Request(a,{method:e.method,headers:l,body:i?Ds.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(o,{remoteAddress:e.socket.remoteAddress,target:n});if(s.statusCode=u.status,u.headers.forEach((p,f)=>s.setHeader(f,p)),r.on&&s.setHeader("connection","close"),u.body)for await(let p of u.body)s.write(p);s.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),s.headersSent||(s.statusCode=500),s.end()}}function zs(t,e,s=r=>console.warn(r)){let r=(e??"").split(",").map(i=>i.trim()).filter(i=>i!=="");if(r.length===0||t?.origins==="*")return t;let n=r.filter(i=>G(i)),a=r.filter(i=>!G(i));a.length>0&&s(`[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??[],...n])];return l.length===0?t:{...t,origins:l}}import{bigint as nn,boolean as an,check as on,date as ln,defineSchema as cn,defineTable as dn,enumType as un,foreignKey as pn,index as fn,integer as hn,jsonb as gn,numeric as bn,ownedByUser as mn,policy as yn,raw as wn,sqlType as Pn,text as Sn,timestamp as vn,userRef as An,uuid as kn}from"palgres/dsl";import{AccessRefused as Rn}from"palgres";import{increment as xn,now as On}from"palgres";function O(t){if(t instanceof _)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function S(t,e){try{let s=await t();return{data:await e(s.data),error:null,status:s.status}}catch(s){return O(s)}}var Hs=C("Secrets",{async get(t){if(Q(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Ys=100,Js=1e3,Qs=168*3600,Xs={s:1,m:60,h:3600,d:86400};function Zs(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let s=0;for(let[,r,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))s+=Math.round(Number(r)*Xs[n]*1e3);return Math.ceil(s/1e3)}function $e(t,e,s){let r="getPublicUrl",n;try{n=String(e).split("/").map(l=>W(r,"path",l)).join("%2F")}catch(l){throw l instanceof _&&l.code==="invalid_path_parameter"?new _({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=`${b.url}/storage/public/${W(r,"bucket",t)}/${n}`;return s?`${a}?variant=${encodeURIComponent(s)}`:a}function Oe(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function er(t){return{async upload(e,s,r){let n=r?.contentType??(s instanceof Blob&&s.type!==""?s.type:void 0);try{let a=await b.storage.putObject({path:{bucket:t,path:e},headers:r?.upsert?void 0:{"If-None-Match":"*"},body:s,contentType:n});return{data:Oe(a.data),error:null,status:a.status}}catch(a){return a instanceof _&&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}:O(a)}},async download(e){try{let s=await b.storage.getObject({path:{bucket:t,path:e}});if(s.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let r=s.data;try{return{data:await r.blob(),error:null,status:s.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(s){return O(s)}},getPublicUrl(e,s){return $e(t,e,s?.variant)},async createSignedUrl(e,s){let r=Zs(s?.expiresIn);return r===void 0||r<1||r>Qs?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(s?.expiresIn)})`},status:400}:S(()=>b.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:r}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,s){let r=s?.limit??Ys,n=s?.offset??0;if(!Number.isInteger(r)||r<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],l,i=200;try{for(;a.length<r;){let c=Math.max(1,Math.min(Js,n+r-a.length)),o=await b.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...l?{cursor:l}:{}}});i=o.status;for(let u of o.data.objects)n>0?n--:a.length<r&&a.push(Oe(u));if(l=o.data.next_cursor,!l)break}}catch(c){return O(c)}return{data:a,error:null,status:i}},async remove(e){let s=[];for(let r of e){try{await b.storage.deleteObject({path:{bucket:t,path:r}})}catch(n){return O(n)}s.push({path:r,name:r,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:s,error:null,status:200}},move(e,s){return S(()=>b.storage.moveObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})},copy(e,s){return S(()=>b.storage.copyObject({path:{bucket:t},body:{from:e,to:s}}),()=>{})}}}var tr={bucket:er},Te=t=>se("Storage",t,tr),sr={bucket:t=>Te("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Te("buckets").bucket(e):void 0})},rr=C("Notifications",{push:{send(t){let{to:e,...s}=t,r=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return S(()=>b.notify.sendPush({body:{...s,to:r}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:s,...r}=t,n={...r,...s!==void 0?{template:s}:{}};if(!Array.isArray(e))return S(()=>b.notify.sendEmail({body:{...n,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 c=await b.notify.sendEmail({body:{...n,to:i}});l=c.status,a.push(c.data.message_id??null)}catch(c){return O(c)}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,nr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Ie(){return re.getStore()?.userId}function K(t){let e=t&&"userId"in t?t.userId??void 0:Ie();return S(()=>e?b.flags.getUserValues({path:{user_id:e}}):b.flags.getValues(),s=>s.values??{})}var Le={setOverrideForUser:(t,e,s)=>S(()=>b.flags.putUserValue({path:{user_id:t,key:e},body:{value:s}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),setOverridesForUser:(t,e)=>S(()=>b.flags.putUserValues({path:{user_id:t},body:{values:e}}),s=>({values:s.values??{}})),clearOverrideForUser:(t,e)=>S(()=>b.flags.deleteUserValue({path:{user_id:t,key:e}}),s=>({key:s.key,value:s.value,source:Fe(s.source)})),clearAllOverridesForUser:t=>S(()=>b.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>S(()=>b.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},ar=C("Flags",{async isEnabled(t,e){let s=r=>(d.warn(`[palbase] flag "${t}" could not be read (${r}): treating it as off`),!1);try{let r=await K(e);return r.error?s(`${r.error.code}: ${r.error.message}`):Ce(r.data[t])}catch(r){return s(r instanceof Error?r.message:String(r))}},async getVariant(t,e){let s=await K(e);return s.error?{data:null,error:s.error,status:s.status}:{data:Be(s.data[t]),error:null,status:s.status}},async getAll(t){let e=await K(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([s,r])=>{let n=Be(r);return{name:s,enabled:Ce(r),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,s){let r,n=!1,a;s!==void 0?(r=e,n=!0,a=s):nr(e)?a=e:e!==void 0&&(r=e,n=!0);let l=await K(a);if(l.error)return n?{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 s=Ie();return s?Le.setOverrideForUser(s,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Le}}),or=C("Realtime",{broadcast(t,e,s){return S(()=>b.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:s??{}}]}}),()=>{})},state:{set(t,e,s){return S(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,value:s}]}}),()=>{})},clear(t,e){return S(()=>b.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as Mn}from"zod";export{Rn as AccessRefused,rt as AttestedDevice,je as AuthUnavailable,St as Authorize,Ft as BadRequest,He as Body,Vt as CACHE_MAX_TTL,Gt as Cache,yt as ChatPart,st as Client,Lt as Conflict,L as ContractRunEnded,Ne as Controller,lt as Cron,V as Database,$t as DeadlockDetected,Ge as Delete,xt as DiError,De as EVENT_TYPES,ar as Flags,Ct as Forbidden,Pt as Gateway,wt as GatewayRefusal,qe as Get,Je as Headers,It as HttpError,at as Injectable,d as Log,Wt as MAX_BODY_BYTES,q as MigrationRunEnded,ot as Module,Mt as NotFound,rr as Notifications,it as On,At as OnConnect,kt as OnDisconnect,Et as OnEmpty,vt as OnFirst,Ze as OptionalUser,Ot as PalError,b as Palbase,_ as PalbaseError,qs as PalbaseFactory,Qe as Param,Ve as Patch,Ke as Post,We as Put,ze as Query,Ye as QueryParams,or as Realtime,et as Req,tt as RequestId,nt as Resolve,j as SchemaNotPushed,Hs as Secrets,Dt as SerializationFailure,sr as Storage,Rt as Subscribe,ft as Task,pt as TaskFailure,ht as Tasks,gt as TestUserTemplate,Ue as TokenError,$ as TokenVerifier,Ut as TooManyRequests,Tt as Unauthorized,jt as UniqueViolation,bt as Upload,mt as UploadedObject,Xe as User,ct as Webhook,nn as bigint,an as boolean,on as check,D as createApp,ln as date,Bt as defineError,cn as defineSchema,dn as defineTable,qt as encrypt,Nt as encrypted,un as enumType,pn as foreignKey,dt as getRegisteredControllers,ut as getRoutes,_t as getWebhookManifest,xn as increment,fn as index,hn as integer,gn as jsonb,On as now,bn as numeric,mn as ownedByUser,yn as policy,wn as raw,Pn as sqlType,Kt as t,Sn as text,vn as timestamp,An as userRef,kn as uuid,Mn as z};
|
|
10
|
+
`}async function ke(t,e,r=Cr){let s=Buffer.from(e,"utf8");for(let n=0;n<s.length;)try{n+=r(t,s,n,s.length-n)}catch(a){if(a.code!=="EAGAIN")throw a;await new Promise(l=>setTimeout(l,5))}}var Ae=2e4,Re=5e3,Ur=15e3,jr="/_palbase/health";function Nr(t){let e=new Set,r=s=>{if(e.has(s))return!1;e.add(s);let n=$(s,Z);return n?n.providers.some(a=>$(a,ee)!==void 0&&$(a,te)===void 0)||n.imports.some(r):!1};return t.some(r)}var qr={async create(t,e={}){let r=Array.isArray(t)?t:[t],s=e.env??process.env,n=de(s);if(n!==void 0){let S=n==="types"?await he(e.db):e.db?await be(e.db,s,n):await fe(n);throw process.exit(S),new q(S)}let a=s.PALBASE_CONTRACT_OUT;if(a){let S;try{await _e(Ee(s)),S=await Kr(r,e,s)}catch(v){throw $r(2,`[palbase] the contract: ${v instanceof Error?v.message:String(v)}
|
|
11
|
+
`),process.exit(1),new I}throw a==="/dev/stdout"?await ke(1,ve(S)):Lr(a,`${S}
|
|
12
|
+
`),process.exit(0),new I}let l=Ee(s),i=await _e(l);i&&u.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 c=e.db?F(e.db):void 0,o=await X({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});o&&u.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&&u.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${o.refused.map(S=>JSON.stringify(S)).join(", ")}`);let p=Nr(r)||c!==void 0&&N(c),m=Pe(e.palbase??{},s,{needsWebhookSecret:p});p&&m.webhookSecret===void 0&&u.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}),P=e.port??Number(s.PORT??"8080");if(!Number.isInteger(P)||P<0||P>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let y=e.db?await ye(e.db,s,m.secretKey,{onPlatform:m.platformSecret!==void 0,embed:we(f),fields:f.fields}):void 0;y&&u.info(`[palbase] database: version ${y.binding.version}`);let k=y&&N(y.model)?{"user.deleted":[S=>Wr(y,S)]}: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:r,verifier:new L({issuer:m.url,projectId:m.projectId,standing:J({url:m.url,secretKey:m.secretKey})}),server:f,webhookSecret:m.webhookSecret,env:s,projectId:m.projectId,telemetry:h,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:Hr(e.cors,s.PALBASE_WEB_ORIGINS),platform:w,events:k,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:i}),R=A(),_=e.boot?.attempts??5,b=e.boot?.backoffMs??1e3;for(let S=1;;S++)try{await R.start();break}catch(v){if(S>=_)throw u.error(`[palbase] the app did not start after ${_} attempts`,{error:v}),v;u.warn(`[palbase] the app did not start (attempt ${S} of ${_}); trying again in ${b} ms`,{error:v}),await new Promise(Me=>setTimeout(Me,b)),b*=2,R=A()}return Vr(R,f,P,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 r=x(Oe(e));for(;!z(Y(r,"package.json"))&&x(r)!==r;)r=x(r);return z(Y(r,"package.json"))?r: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 Kr(t,e,r){let s=Oe(r.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(s))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${s||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=x(s);for(;!z(Y(n,"package.json"))&&x(n)!==n;)n=x(n);let{analyzeProject:a}=await import("../chunks/7TZJLWWX.js"),{routeContracts:l}=await import("../chunks/MVVULWTH.js"),i=a(n,s);for(let p of i.warnings)u.warn(`[palbase] the contract: ${p}`);let c="https://contract.palbase.invalid",o=D({modules:t,verifier:new L({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:C({url:c,secretKey:"pb_contract_s"}),env:r,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:ne()},events:e.db&&N(F(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(o.contract())}var I=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 Wr(t,e){let r=e.data?.user_id;if(typeof r!="string"||r==="")throw new Error("[palbase] user.deleted without a user_id");let s=await t.forget(r,V.$asService());u.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them${s.relationships===void 0?"":`, ${s.relationships} relationship(s) of the access schema taken back`}`)}async function Vr(t,e,r,s,n,a){let l,i={on:!1},c=(w,h)=>new URL(w.url).pathname===jr&&w.method==="GET"?Promise.resolve(i.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(w,h),o=Mr((w,h)=>{Gr(c,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(r,s,()=>w())})}catch(w){throw await t.stop(),await a?.close(),w}let p=o.address().port;u.info(`[palbase] serving ${t.routes.length} route(s) on :${p}`,{routes:t.routes}),a?.search?.start();let m=w=>l??=(async()=>{u.info("[palbase] stopping: finishing the requests in flight"),i.on=!0;let h=new Promise(R=>o.close(()=>R()));o.closeIdleConnections();let A=setTimeout(()=>o.closeAllConnections(),w);await h,clearTimeout(A),process.off("SIGINT",y),process.off("uncaughtException",k),process.off("unhandledRejection",k);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>m(Ae),P=!1,y=()=>{if(P){u.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}P=!0;let w=setTimeout(()=>{u.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ae+Ur);w.unref(),f().then(()=>{clearTimeout(w),process.exit(0)},h=>{clearTimeout(w),u.error("[palbase] stopping failed; the process ends",{error:h}),process.exit(1)})},k=w=>{u.error("[palbase] the app crashed; stopping so the machine starts it again",{error:w});let h=setTimeout(()=>process.exit(1),Re+1e3);m(Re).finally(()=>{clearTimeout(h),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",k),process.on("unhandledRejection",k)),{routes:t.routes,palbase:e,port:p,handle:c,close:f}}async function Gr(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.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 P of f)l.append(m,P);else l.set(m,f);let i=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let o=new Request(a,{method:e.method,headers:l,body:i?Dr.toWeb(e):void 0,duplex:"half",signal:c.signal}),p=await t(o,{remoteAddress:e.socket.remoteAddress,target:n});if(r.statusCode=p.status,p.headers.forEach((m,f)=>r.setHeader(f,m)),s.on&&r.setHeader("connection","close"),p.body)for await(let m of p.body)r.write(m);r.end()}catch(n){u.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function Hr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(i=>i.trim()).filter(i=>i!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(i=>G(i)),a=s.filter(i=>!G(i));a.length>0&&r(`[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??[],...n])];return l.length===0?t:{...t,origins:l}}import{bigint as on,boolean as ln,check as cn,date as un,defineSchema as dn,defineTable as pn,enumType as mn,foreignKey as gn,index as fn,integer as hn,jsonb as bn,numeric as yn,ownedByUser as wn,policy as Pn,raw as Sn,sqlType as vn,text as kn,timestamp as An,userRef as Rn,uuid as En}from"palgres/dsl";import{AccessRefused as On}from"palgres";import{increment as Tn,now as Cn}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 g(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return T(r)}}var zr=E("Secrets",{async get(t){if(Q(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),Yr=100,Jr=1e3,Qr=168*3600,Xr={s:1,m:60,h:3600,d:86400};function Zr(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let r=0;for(let[,s,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))r+=Math.round(Number(s)*Xr[n]*1e3);return Math.ceil(r/1e3)}function Le(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(l=>W(s,"path",l)).join("%2F")}catch(l){throw l instanceof O&&l.code==="invalid_path_parameter"?new O({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):l}let a=`${d.url}/storage/public/${W(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`: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,Le(t.bucket,t.path,e)]))}}function es(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await d.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});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 r=await d.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return T(r)}},getPublicUrl(e,r){return Le(t,e,r?.variant)},async createSignedUrl(e,r){let s=Zr(r?.expiresIn);return s===void 0||s<1||s>Qr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:g(()=>d.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??Yr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],l,i=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(Jr,n+s-a.length)),o=await d.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...l?{cursor:l}:{}}});i=o.status;for(let p of o.data.objects)n>0?n--:a.length<s&&a.push(xe(p));if(l=o.data.next_cursor,!l)break}}catch(c){return T(c)}return{data:a,error:null,status:i}},async remove(e){let r=[];for(let s of e){try{await d.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return T(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return g(()=>d.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return g(()=>d.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var ts={bucket:es},Te=t=>re("Storage",t,ts),rs={bucket:t=>Te("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Te("buckets").bucket(e):void 0})},ss=E("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return g(()=>d.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return g(()=>d.notify.sendEmail({body:{...n,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 c=await d.notify.sendEmail({body:{...n,to:i}});l=c.status,a.push(c.data.message_id??null)}catch(c){return T(c)}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,ns=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function $e(){return se.getStore()?.userId}function K(t){let e=t&&"userId"in t?t.userId??void 0:$e();return g(()=>e?d.flags.getUserValues({path:{user_id:e}}):d.flags.getValues(),r=>r.values??{})}var Ie={setOverrideForUser:(t,e,r)=>g(()=>d.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Fe(s.source)})),setOverridesForUser:(t,e)=>g(()=>d.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>g(()=>d.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Fe(r.source)})),clearAllOverridesForUser:t=>g(()=>d.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>g(()=>d.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},as=E("Flags",{async isEnabled(t,e){let r=s=>(u.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await K(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Ce(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await K(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Be(r.data[t]),error:null,status:r.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(([r,s])=>{let n=Be(s);return{name:r,enabled:Ce(s),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,r){let s,n=!1,a;r!==void 0?(s=e,n=!0,a=r):ns(e)?a=e:e!==void 0&&(s=e,n=!0);let l=await K(a);if(l.error)return n?{data:s??null,error:null,status:l.status}:{data:null,error:l.error,status:l.status};let i=l.data[t];return{data:i===void 0?s??null:i,error:null,status:l.status}},async setOverride(t,e){let r=$e();return r?Ie.setOverrideForUser(r,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 Ie}}),os=E("Realtime",{broadcast(t,e,r){return g(()=>d.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return g(()=>d.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return g(()=>d.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}}),is=E("Commerce",{getSettings(){return g(()=>d.commerce.getCommerceSettings({}),t=>t)},listStores(t){return g(()=>d.commerce.listStores({query:t}),e=>e)},listProducts(t){return g(()=>d.commerce.listProducts({query:t}),e=>e)},createQuickProduct(t){return g(()=>d.commerce.createQuickProduct({body:t}),e=>e)},getOrder(t){return g(()=>d.commerce.getOrder({path:{order_id:t}}),e=>e)},listOrders(t){return g(()=>d.commerce.listOrders({query:t}),e=>e)},listStoreOrders(t){return g(()=>d.commerce.listStoreOrders({query:t}),e=>e)},adjustInventory(t){return g(()=>d.commerce.adjustInventory({body:t}),e=>e)},recomputeBuyBox(t){return g(()=>d.commerce.recomputeVariantBuyBox({path:{variant_id:t}}),e=>e)}}),ls=E("Promotions",{listRules(t){return g(()=>d.commerce.listPromotionRules({query:t}),e=>e)},createRule(t){return g(()=>d.commerce.createPromotionRule({body:t}),e=>e)},evaluate(t){return g(()=>d.commerce.evaluatePromotions({body:t}),e=>e)},hold(t){return g(()=>d.commerce.holdPromotions({body:t}),e=>e)},commitHold(t,e={}){return g(()=>d.commerce.commitPromotionHold({path:{hold_id:t},body:e}),r=>r)},releaseHold(t){return g(()=>d.commerce.releasePromotionHold({path:{hold_id:t}}),e=>e)},reverseRedemption(t){return g(()=>d.commerce.reversePromotionRedemption({path:{redemption_id:t}}),e=>e)}});import{z as Un}from"zod";export{On as AccessRefused,st as AttestedDevice,je as AuthUnavailable,St as Authorize,Ft as BadRequest,ze as Body,Vt as CACHE_MAX_TTL,Gt as Cache,yt as ChatPart,rt as Client,is as Commerce,It as Conflict,I as ContractRunEnded,Ne as Controller,lt as Cron,V as Database,Lt as DeadlockDetected,Ge as Delete,Ot as DiError,De as EVENT_TYPES,as as Flags,Ct as Forbidden,Pt as Gateway,wt as GatewayRefusal,qe as Get,Je as Headers,$t as HttpError,at as Injectable,u as Log,Wt as MAX_BODY_BYTES,q as MigrationRunEnded,ot as Module,Mt as NotFound,ss as Notifications,it as On,kt as OnConnect,At as OnDisconnect,Rt as OnEmpty,vt as OnFirst,Ze as OptionalUser,xt as PalError,d as Palbase,O as PalbaseError,qr as PalbaseFactory,Qe as Param,Ve as Patch,Ke as Post,ls as Promotions,We as Put,He as Query,Ye as QueryParams,os as Realtime,et as Req,tt as RequestId,nt as Resolve,j as SchemaNotPushed,zr as Secrets,Dt as SerializationFailure,rs as Storage,Et as Subscribe,mt as Task,pt as TaskFailure,gt as Tasks,ft as TestUserTemplate,Ue as TokenError,L as TokenVerifier,Ut as TooManyRequests,Tt as Unauthorized,jt as UniqueViolation,ht as Upload,bt as UploadedObject,Xe as User,ct as Webhook,on as bigint,ln as boolean,cn as check,D as createApp,un as date,Bt as defineError,dn as defineSchema,pn as defineTable,qt as encrypt,Nt as encrypted,mn as enumType,gn as foreignKey,ut as getRegisteredControllers,dt as getRoutes,_t as getWebhookManifest,Tn as increment,fn as index,hn as integer,bn as jsonb,Cn as now,yn as numeric,wn as ownedByUser,Pn as policy,Sn as raw,vn as sqlType,Kt as t,kn as text,An as timestamp,Rn as userRef,En as uuid,Un as z};
|
package/dist/backend/stack.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.72.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.72.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as l,c as g,d as f,e as m}from"../chunks/JMNQRIEG.js";import{a as u}from"../chunks/I4SH2RTD.js";import{c,i as p}from"../chunks/QDPRR5PE.js";import"../chunks/O6JNTYC5.js";import"../chunks/D5I74USX.js";import"../chunks/DE7BWXBF.js";import"../chunks/JXIKBG4D.js";import"../chunks/XUYC354U.js";import"../chunks/3MF6NROQ.js";import"../chunks/LDFOUUBT.js";import"../chunks/WWXBXZUO.js";import"../chunks/E2MNCFOU.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};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{b as c,f as u}from"./
|
|
1
|
+
/*! palbase 0.72.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as c,f as u}from"./LDFOUUBT.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import"./
|
|
1
|
+
/*! palbase 0.72.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import"./E2MNCFOU.js";import{realpathSync as Je}from"node:fs";import{resolve as ge}from"node:path";import vt from"typescript";import{existsSync as he,readFileSync as be}from"node:fs";import{createRequire as Qe}from"node:module";import{dirname as re,join as G,relative as We,resolve as xe,sep as ne}from"node:path";var b=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},Z=new Set(["palbase/backend","@palbase/backend","palgres"]),Ge=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function we(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new b(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var Ze={bun:"bun-types",node:"@types/node"},He=Qe(import.meta.url);function Xe(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=Ze[i],a=e.resolveTypeReferenceDirective(i,G(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=He.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(be(c,"utf8"));s.push(G(re(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function ke(e,t){we(e);let n=G(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(he(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new b(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
|
|
3
3
|
`)}`);let o=e.parseJsonConfigFileContent(i.config,e.sys,t);r=o.options,s=o.fileNames.filter(c=>/\.d\.[cm]?ts$/.test(c));let a=Xe(e,t,r);r={...r,types:a.types},s=[...s,...a.files]}return{options:{...r,strictNullChecks:!0,noEmit:!0,skipLibCheck:!0},ambient:s}}function Ee(e,t,n,r,s){we(e);let i=e.createProgram([...new Set(n)],r,s);return{ts:e,root:t,program:i,checker:i.getTypeChecker(),packages:new Map}}function $(e,t){let n=xe(t);return!n.includes(`${ne}node_modules${ne}`)&&!/\.d\.[cm]?ts$/.test(n)&&(n===e.root||n.startsWith(e.root+ne))}function v(e,t){return!!t&&$(e,t.getSourceFile().fileName)}function Ce(e,t){let n=[],r=re(xe(t)),s=null;for(;;){let i=e.packages.get(r);if(i!==void 0){s=i;break}n.push(r);let o=G(r,"package.json");if(he(o)){try{let c=JSON.parse(be(o,"utf8")).name;s=typeof c=="string"?c:null}catch{s=null}break}let a=re(r);if(a===r)break;r=a}for(let i of n)e.packages.set(i,s);return s}function se(e,t){if($(e,t))return!1;let n=Ce(e,t)??"";return n==="palbase"?/[\\/]types[\\/]backend[\\/]/.test(t):Z.has(n)}function ie(e,t){if($(e,t))return!1;let n=Ce(e,t)??"";return Z.has(n)||n==="palbase"||n.startsWith("@palbase/")}function O(e,t){let n=t.getSourceFile(),{line:r}=n.getLineAndCharacterOfPosition(t.getStart(n));return`${We(e.root,n.fileName)}:${r+1}`}function T(e,t){for(;t;){if(e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isNonNullExpression(t)||e.isAwaitExpression(t)||e.isTypeAssertionExpression(t)||e.isSatisfiesExpression(t)){t=t.expression;continue}return t}return t}function H(e,t){if(t&&t.flags&e.ts.SymbolFlags.Alias){let n=e.checker.getAliasedSymbol(t);if(n&&n.declarations)return n}return t}function L(e,t){let n=H(e,e.checker.getSymbolAtLocation(t));return n&&(n.valueDeclaration||n.declarations&&n.declarations[0])||null}function ye(e,t){let n=t;for(;n&&!e.isImportDeclaration(n)&&!e.isExportDeclaration(n);)n=n.parent;return n&&(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier&&e.isStringLiteral(n.moduleSpecifier)?n.moduleSpecifier.text:null}function I(e,t){let n=e.ts;if(t=T(n,t),!t)return null;if(n.isPropertyAccessExpression(t)){let i=e.checker.getSymbolAtLocation(t.expression);return i&&(i.declarations||[]).some(a=>n.isNamespaceImport(a)&&Z.has(ye(n,a)??""))?t.name.text:null}if(!n.isIdentifier(t))return null;let r=e.checker.getSymbolAtLocation(t),s=new Set;for(;r&&!s.has(r);){s.add(r);for(let i of r.declarations||[]){if((n.isImportSpecifier(i)||n.isExportSpecifier(i))&&Z.has(ye(n,i)??""))return(i.propertyName||i.name).text;if(se(e,i.getSourceFile().fileName))return r.name}if(!(r.flags&n.SymbolFlags.Alias))return null;r=e.checker.getImmediateAliasedSymbol(r)}return null}function Te(e,t){let n=t.expression;return I(e,e.ts.isCallExpression(n)?n.expression:n)}function P(e,t){return t&&(e.isIdentifier(t)||e.isPrivateIdentifier(t)||e.isStringLiteral(t)||e.isNumericLiteral(t))?t.text:null}function X(e,t){let n=e.ts,r=[];for(let s of t.statements){if(!n.isClassDeclaration(s)||!(n.getDecorators(s)||[]).some(o=>Te(e,o)==="Controller"))continue;if(!s.name)throw new b(`${O(e,s)} \u2014 a @Controller class needs a name \u2014 its routes' errors are bound to it by name`);let i=[];for(let o of s.members)if(!(!n.isMethodDeclaration(o)||!o.body)&&(n.getDecorators(o)||[]).some(a=>Ge.has(Te(e,a)??""))){if(P(n,o.name)===null)throw new b(`${O(e,o)} \u2014 a route method needs a plain name; the contract reaches it by name`);i.push(o)}r.push({cls:s,routes:i})}return r}var Ye=new Set([2307,2580,2582,2583,2584,2591,2592,2593,2688,2867,2868,7016]);function et(e){let t=e.getSymbol();return t?.getName()==="Response"&&(t.declarations??[]).length>0&&(t.declarations??[]).every(n=>n.getSourceFile().isDeclarationFile)}function Ne(e){let{ts:t,program:n,checker:r}=e,s=!1;return function(o,a){let c=o.getSourceFile().fileName,l=o.name.getText(o.getSourceFile()),u=d=>{throw new b(`${c} \u2014 ${a}.${l}: cannot infer a safe response contract (${d}). Use a named Zod return schema for this response; any/unknown is never emitted as a successful contract.`)};if(!s){let d=[];for(let p of n.getSourceFiles()){if(d.length>=5)break;p.isDeclarationFile||n.isSourceFileFromExternalLibrary(p)||/[\\/]node_modules[\\/]/.test(p.fileName)||ie(e,p.fileName)||d.push(...n.getSemanticDiagnostics(p).filter(x=>x.category===t.DiagnosticCategory.Error&&!Ye.has(x.code)))}d.length&&u(t.formatDiagnostics(d.slice(0,5),{getCanonicalFileName:p=>p,getCurrentDirectory:()=>e.root,getNewLine:()=>`
|
|
4
4
|
`})),s=!0}let m=r.getSignatureFromDeclaration(o),g=m&&r.getAwaitedType(r.getReturnTypeOfSignature(m));if(!g)return u("unresolved return type");if(g.flags&(t.TypeFlags.Void|t.TypeFlags.Undefined))return{kind:"void"};if(et(g))return{kind:"raw"};function y(d){let p=d.getSymbol();if(p?.getName()!=="Encrypted"||!(p.declarations??[]).some(S=>ie(e,S.getSourceFile().fileName)))return;let x=r.getTypeArguments(d);return x.length===1?x[0]:void 0}let f=new Set,V=0;function h(d,p){if(++V>2e3||f.size>24)return u(`${p}: contract is too large; name its schema`);let x=d.flags,S=t.TypeFlags;if(x&(S.Any|S.Unknown|S.Never|S.TypeParameter))return u(`${p}: ${r.typeToString(d)}`);let pe=y(d);if(pe)return`encrypted(${h(pe,p)})`;let Se=w=>{let k=r.getPropertiesOfType(w);if(!(w.flags&S.Object)||k.length!==1||k[0].name!=="__pg"||!(k[0].flags&t.SymbolFlags.Optional)||r.getIndexInfosOfType(w).length)return!1;let N=r.getTypeOfSymbolAtLocation(k[0],o);return(N.isUnion()?N.types:[N]).every(E=>E.flags&(S.StringLiteral|S.Undefined))};if(d.isIntersection()){let w=d.types.filter(k=>!Se(k));if(w.length===1&&w.length<d.types.length)return h(w[0],p)}if(Se(d))return u(`${p}: unknown PostgreSQL payload; name its response schema`);if(x&S.StringLiteral)return`z.literal(${JSON.stringify(d.value)})`;if(x&S.NumberLiteral)return`z.literal(${JSON.stringify(d.value)})`;if(x&S.BooleanLiteral)return`z.literal(${r.typeToString(d)==="true"})`;if(x&S.String)return"z.string()";if(x&S.TemplateLiteral){let w=d;if(w.types.length>8||!w.types.every(E=>E.flags&S.String))return u(`${p}: template literal requires an explicit schema`);let k=E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N="^"+k(w.texts[0]);for(let E of w.texts.slice(1,-1))if(E){let te=k(E);N+=`(?:(?!${te})[\\s\\S])*${te}`}return N+="[\\s\\S]*"+k(w.texts.at(-1))+"$(?![\\s\\S])",N.length>4096?u(`${p}: template pattern is too large`):`z.string().regex(new RegExp(${JSON.stringify(N)}))`}if(x&S.Number)return"z.number()";if(x&S.Boolean)return"z.boolean()";if(x&S.Null)return"z.null()";if(x&S.Undefined)return"z.undefined()";if(f.has(d))return u(`${p}: recursive response`);f.add(d);try{if(d.isUnion()){if(d.types.length>32)return u(`${p}: union has more than 32 alternatives`);let A=d.types.some(M=>M.flags&S.Null),W=d.types.some(M=>M.flags&S.Undefined),j=d.types.filter(M=>!(M.flags&(S.Null|S.Undefined)));return(j.length===0?A?"z.null()":"z.undefined()":j.length===1?h(j[0],p):`z.union([${j.map(M=>h(M,p)).join(",")}])`)+(A&&j.length?".nullable()":"")+(W?".optional()":"")}if(r.isTupleType(d))return u(`${p}: tuple requires an explicit schema`);if(r.isArrayType(d)){let A=r.getTypeArguments(d)[0];return A.flags&S.Never?"z.array(z.string()).length(0)":`z.array(${h(A,`${p}[]`)})`}let w=d.isIntersection()&&d.types.every(A=>A.flags&S.Object);if(!(x&S.Object)&&!w||d.getCallSignatures().length||d.getConstructSignatures().length)return u(`${p}: non-JSON type ${r.typeToString(d)}`);let k=d.symbol?.declarations?.[0];if(k&&(t.isClassDeclaration(k)||t.isClassExpression(k)))return u(`${p}: class instance ${r.typeToString(d)}`);let N=r.getPropertiesOfType(d),E=r.getIndexInfosOfType(d);return E.length?E.length!==1||!(E[0].keyType.flags&S.String)||N.length?u(`${p}: mixed or non-string index signature`):`z.record(z.string(), ${h(E[0].type,`${p}.*`)})`:N.length?`z.object({${N.map(A=>{if(A.escapedName.toString().startsWith("__@"))return u(`${p}: symbol property`);let W=A.getName(),j=h(r.getTypeOfSymbolAtLocation(A,o),`${p}.${W}`);return`${JSON.stringify(W)}:${j}${A.flags&t.SymbolFlags.Optional?".optional()":""}`}).join(",")}}).strict()`:u(`${p}: empty structural type`)}finally{f.delete(d)}}return{kind:"expression",expression:h(g,"return")}}}import{resolve as tt}from"node:path";var oe=Symbol("not a named schema");function Ae(e,t,n,r){let{ts:s}=e,i=r.getSourceFile(),o=r.name.getText(i),a=f=>new b(`${i.fileName} \u2014 ${n}.${o}: ${f}`);function c(f){if(s.isTypeReferenceNode(f)&&f.typeName.getText(i)==="Promise"&&f.typeArguments&&f.typeArguments.length===1)return c(f.typeArguments[0]);if(f.kind===s.SyntaxKind.VoidKeyword||f.kind===s.SyntaxKind.UndefinedKeyword)return null;let V=s.isArrayTypeNode(f)?f.elementType:s.isTypeReferenceNode(f)&&f.typeName.getText(i)==="Array"&&f.typeArguments&&f.typeArguments.length===1?f.typeArguments[0]:void 0,h=l(V??f);return h===oe?h:{...h,isArray:V!==void 0}}function l(f){if(s.isTypeReferenceNode(f)&&!f.typeArguments)return{typeName:f.typeName.getText(i),node:f.typeName};if(s.isTypeReferenceNode(f)&&f.typeArguments&&f.typeArguments.length===1){let V=f.typeName.getText(i);if(/^(z\.)?(infer|output|input)$/.test(V)){let h=f.typeArguments[0];if(s.isTypeQueryNode(h))return{typeName:h.exprName.getText(i),node:h.exprName};if(s.isTypeReferenceNode(h)&&!h.typeArguments)return{typeName:h.typeName.getText(i),node:h.typeName}}}if(f.kind===s.SyntaxKind.VoidKeyword)throw a("void cannot appear inside an array/Promise here");return oe}let u=()=>t(r,n);if(!r.type)return u();let m=c(r.type);if(m===null)return{kind:"void"};if(m===oe)return u();let g=nt(e,m.node);if(!g)return u();let y=rt(e,g.symbol);return y?{kind:"schema",...y,array:m.isArray}:u()}function nt(e,t){let{ts:n,checker:r}=e,s=r.getSymbolAtLocation(n.isQualifiedName(t)?t.right:t),i=H(e,s);if(!i||!(i.flags&n.SymbolFlags.Variable))return null;let o=i.valueDeclaration;return!o||!n.isVariableDeclaration(o)||!r.getTypeOfSymbolAtLocation(i,o).getProperty("~standard")?null:{symbol:i}}function rt(e,t){let n=t.valueDeclaration?.getSourceFile();if(!n||n.isDeclarationFile)return null;let r=e.checker.getSymbolAtLocation(n);if(!r)return null;let s=e.checker.getExportsOfModule(r).filter(i=>H(e,i)===t).map(i=>i.name);return s.length===0?null:{file:tt(n.fileName),exportName:s.includes(t.name)?t.name:s[0]}}var ue={BadRequest:{code:"bad_request",status:400,codeArg:null},Unauthorized:{code:"unauthorized",status:401,codeArg:1},Forbidden:{code:"forbidden",status:403,codeArg:1},NotFound:{code:"not_found",status:404,codeArg:1},Conflict:{code:"conflict",status:409,codeArg:1},UniqueViolation:{code:"unique_violation",status:409,codeArg:2},SerializationFailure:{code:"serialization_failure",status:409,codeArg:null},DeadlockDetected:{code:"deadlock_detected",status:409,codeArg:null},TooManyRequests:{code:"too_many_requests",status:429,codeArg:null}},st=new Set(["HttpError","PalError"]),it=[{member:"page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"$page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"NotFound",code:"not_found",status:404}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"updateScoped",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}}],ot=new Map([["expectOne",0],["expectNone",0],["expectAtLeast",1],["expectAtMost",1]]);function $e(e){let t={...e,ids:new WeakMap,nextId:1,providerSet:null,concrete:null,summaries:new Map,warnings:new Map,statusOf:null,round:0,cyclic:!1,grew:!1};return{analyze(n){let r;for(;t.round+=1,t.cyclic=!1,t.grew=!1,r=At(t,n),!(!t.cyclic||!t.grew););for(let s of t.summaries.values())s.final=!0;return r},warnings(){return[...t.warnings.values()]}}}function at(e,t,n){throw new b(`${O(e,t)} \u2014 ${n}`)}function q(e,t){let n=e.ids.get(t);return n||(n=e.nextId++,e.ids.set(t,n)),n}function de(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Static)!==0}function Fe(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Abstract)!==0}function F(e,t){return!!t&&(e.isClassDeclaration(t)||e.isClassExpression(t))}function Oe(e,t){if(!t)return null;if(F(e,t))return t;if((e.isVariableDeclaration(t)||e.isPropertyDeclaration(t)||e.isPropertyAssignment(t))&&t.initializer){let n=T(e,t.initializer);if(e.isClassExpression(n))return n}return null}function ct(e,t){if(t.name)return t.name.text;let n=t.parent;if(n&&(e.isVariableDeclaration(n)||e.isPropertyDeclaration(n)||e.isPropertyAssignment(n))&&n.name&&P(e,n.name))return P(e,n.name)??void 0}function _(e,t){let n=e.ts,r=T(n,t);if(!r)return null;let s=Oe(n,L(e,n.isPropertyAccessExpression(r)?r.name:r));return s&&v(e,s)?s:null}function J(e,t){let n=e.ts,r=(t.heritageClauses||[]).find(i=>i.token===n.SyntaxKind.ExtendsKeyword),s=r&&r.types[0]&&r.types[0].expression;return s?_(e,s):null}function Re(e,t,n){for(let r=J(e,t);r;r=J(e,r))if(r===n)return!0;return!1}function U(e,t,n,r){let s=e.ts;for(let i=t;i;i=J(e,i))for(let o of i.members)if(!(P(s,o.name)!==n||de(s,o)!==r)){if((s.isMethodDeclaration(o)||s.isGetAccessorDeclaration(o))&&o.body)return{fn:o,owner:i};if(s.isPropertyDeclaration(o)&&o.initializer){let a=T(s,o.initializer);if(s.isArrowFunction(a)||s.isFunctionExpression(a))return{fn:a,owner:i}}}return null}function lt(e){let t=e.ts;if(e.providerSet)return e.providerSet;let n=new Set;for(let r of e.program.getSourceFiles())if($(e,r.fileName)){for(let s of r.statements)if(t.isClassDeclaration(s))for(let i of t.getDecorators(s)||[]){let o=i.expression;if(!t.isCallExpression(o)||I(e,o.expression)!=="Module")continue;let a=T(t,o.arguments[0]);if(!(!a||!t.isObjectLiteralExpression(a)))for(let c of a.properties){if(!t.isPropertyAssignment(c)||P(t,c.name)!=="providers")continue;let l=T(t,c.initializer);if(t.isArrayLiteralExpression(l))for(let u of l.elements){let m=_(e,u);m&&n.add(m)}}}}return e.providerSet=n,n}function ve(e){let t=e.ts;if(e.concrete)return e.concrete;let n=[],r=s=>{F(t,s)&&!Fe(t,s)&&n.push(s),t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.concrete=n,n}function ze(e,t){let n=t.name?e.checker.getSymbolAtLocation(t.name):t.symbol;return n?e.checker.getDeclaredTypeOfSymbol(n):null}function ut(e,t){let n=t&&(t.getSymbol()||t.aliasSymbol),r=n&&(n.declarations||[]).find(s=>F(e.ts,s));return r&&F(e.ts,r)&&v(e,r)?r:null}function ae(e,t){return t.type?e.checker.getTypeFromTypeNode(t.type):e.checker.getTypeAtLocation(t.name||t)}function Q(e,t,n){let r=e.ts;if(!t)return;if(t.isUnion()){for(let l of t.types)Q(e,l,n);return}let s=r.TypeFlags,i=s.StringLike|s.NumberLike|s.BigIntLike|s.BooleanLike|s.EnumLike|s.ESSymbolLike|s.VoidLike|s.Null;if(t.flags&(s.Any|s.Unknown|i))return;let o=t.getSymbol();if(!o)return;let a=(o.declarations||[]).find(l=>F(r,l));if(a&&F(r,a)){if(!v(e,a))return;Fe(r,a)||n.add(a);for(let l of ve(e))Re(e,l,a)&&n.add(l);return}if((o.declarations||[]).some(l=>v(e,l)))for(let l of ve(e)){let u=ze(e,l);u&&e.checker.isTypeAssignableTo(u,t)&&n.add(l)}}function fe(e,t,n){let r=ut(e,t);if(r){let s=lt(e);if(s.has(r)){n.add(r);return}let i=[...s].filter(o=>o!==r&&Re(e,o,r));if(i.length===1){n.add(i[0]);return}}Q(e,t,n)}function ft(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function je(e,t){return t.fn&&ft(e,t.fn)?t:{receiver:null,owner:null,fn:null}}function C(e,t,n,r=new Set){let s=e.ts,i=new Set;if(t=T(s,t),!t)return i;let o=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`;if(r.has(o))return i;r.add(o);let a=c=>{for(let l of c)i.add(l)};if(s.isNewExpression(t)){let c=_(e,t.expression);return c&&i.add(c),i}if(t.kind===s.SyntaxKind.ThisKeyword)return n.receiver&&i.add(n.receiver),i;if(s.isConditionalExpression(t))return a(C(e,t.whenTrue,n,r)),a(C(e,t.whenFalse,n,r)),i;if(s.isBinaryExpression(t)){let c=t.operatorToken.kind,l=s.SyntaxKind;if(c===l.QuestionQuestionToken||c===l.BarBarToken||c===l.AmpersandAmpersandToken)return a(C(e,t.left,n,r)),a(C(e,t.right,n,r)),i;if(c===l.CommaToken||c===l.EqualsToken)return a(C(e,t.right,n,r)),i}if(s.isCallExpression(t)){for(let c of ee(e,t,n))for(let l of Y(s,c.fn))a(C(e,l,c.ctx,r));if(i.size>0)return i}else if(s.isIdentifier(t)||s.isPropertyAccessExpression(t)){let c=L(e,s.isPropertyAccessExpression(t)?t.name:t);if(c&&s.isVariableDeclaration(c))return c.initializer&&a(C(e,c.initializer,je(c,n),r)),(!((s.getCombinedNodeFlags(c)&s.NodeFlags.Const)!==0)||!c.initializer)&&Q(e,ae(e,c),i),i;if(c&&s.isParameter(c)){let l=ae(e,c);return c.parent&&s.isConstructorDeclaration(c.parent)?fe(e,l,i):Q(e,l,i),i}if(c&&s.isPropertyDeclaration(c))return c.initializer?a(C(e,c.initializer,{receiver:c.parent,owner:c.parent,fn:null},r)):fe(e,ae(e,c),i),i;if(c&&s.isGetAccessorDeclaration(c)&&c.body){for(let l of Y(s,c))a(C(e,l,{receiver:c.parent,owner:c.parent,fn:c},r));if(i.size>0)return i}if(c&&s.isPropertyAssignment(c)&&(a(C(e,c.initializer,{receiver:null,owner:null,fn:null},r)),i.size>0))return i}return Q(e,e.checker.getTypeAtLocation(t),i),i}function Y(e,t){if(e.isArrowFunction(t)&&!e.isBlock(t.body))return[t.body];let n=e.isFunctionLike(t)?t.body:void 0;if(!n)return[];let r=[],s=i=>{if(e.isReturnStatement(i)){i.expression&&r.push(i.expression);return}e.isFunctionLike(i)||F(e,i)||e.forEachChild(i,s)};return e.forEachChild(n,s),r}function Me(e,t){return e.isPropertyAccessExpression(t)?t.name.text:e.isElementAccessExpression(t)&&e.isStringLiteralLike(t.argumentExpression)?t.argumentExpression.text:null}function Ie(e,t){return e.isPropertyAccessExpression(t)?t.name:t.argumentExpression}function dt(e,t){let n=e.ts,r=Me(n,t);if(r===null)return[];let s=e.checker.getSymbolAtLocation(Ie(n,t)),i=new Map;for(let o of s&&s.declarations||[]){if(!se(e,o.getSourceFile().fileName))continue;let a=o.parent,c=a&&a.name&&n.isIdentifier(a.name)?a.name.text:"";for(let l of it)l.member===r&&(!l.container||l.container.test(c))&&i.set(l.error.code,l.error)}return[...i.values()]}function mt(e,t){let n=e.checker.getSymbolAtLocation(Ie(e.ts,t));return n?(n.declarations||[]).some(r=>v(e,r)):!0}function Be(e,t,n){let r=e.ts,s=[];for(let i=t;i;i=J(e,i)){for(let a of i.members){if(!r.isPropertyDeclaration(a)||!a.initializer||de(r,a))continue;let c=T(r,a.initializer);r.isArrowFunction(c)||r.isFunctionExpression(c)||s.push({fn:a.initializer,ctx:{receiver:n,owner:i,fn:null}})}let o=i.members.find(a=>r.isConstructorDeclaration(a)&&!!a.body);if(o){s.push({fn:o,ctx:{receiver:n,owner:i,fn:o}});break}}return s}function ee(e,t,n){let r=e.ts,s=T(r,t.expression);if(s.kind===r.SyntaxKind.SuperKeyword){let c=n.owner&&J(e,n.owner);return c?Be(e,c,n.receiver):[]}let i=Me(r,s);if(i!==null){let c=s,l=T(r,c.expression);if(l.kind===r.SyntaxKind.SuperKeyword){let g=n.owner&&J(e,n.owner),y=g&&U(e,g,i,!1);return y?[{fn:y.fn,ctx:{receiver:n.receiver,owner:y.owner,fn:y.fn}}]:[]}let u=r.isIdentifier(l)||r.isPropertyAccessExpression(l)?_(e,l):null;if(u){let g=U(e,u,i,!0);return g?[{fn:g.fn,ctx:{receiver:null,owner:g.owner,fn:g.fn}}]:[]}if(!mt(e,c))return[];let m=[];for(let g of C(e,l,n)){let y=U(e,g,i,!1);y&&m.push({fn:y.fn,ctx:{receiver:g,owner:y.owner,fn:y.fn}})}if(m.length>0)return m}let o=e.checker.getResolvedSignature(t),a=o&&o.declaration;if(a&&!r.isJSDocSignature(a)&&a.body&&v(e,a)){let c=a,l=c.parent&&F(r,c.parent)?c.parent:null,u=l&&!de(r,c)?l:null;return[{fn:c,ctx:{receiver:u,owner:l,fn:c}}]}return[]}function De(e,t,n){let r=e.ts,s=T(r,t);if(!s)return[];if(r.isPropertyAccessExpression(s)){let i=L(e,s.name);if(!(i&&v(e,i)&&(r.isMethodDeclaration(i)||r.isPropertyDeclaration(i))))return[];let a=[];for(let c of C(e,s.expression,n)){let l=U(e,c,s.name.text,!1);l&&a.push({fn:l.fn,ctx:{receiver:c,owner:l.owner,fn:l.fn}})}return a}if(r.isIdentifier(s)){let i=L(e,s);if(!i||!v(e,i))return[];if(r.isFunctionDeclaration(i)&&i.body)return[{fn:i,ctx:{receiver:null,owner:null,fn:i}}];if(r.isVariableDeclaration(i)&&i.initializer){let o=T(r,i.initializer);if(r.isArrowFunction(o)||r.isFunctionExpression(o))return[{fn:o,ctx:{receiver:null,owner:null,fn:o}}]}}return[]}function K(e,t,n){let r=e.ts,s=T(r,t);if(!s)return null;if(n==="string"&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return[s.text];if(n==="number"&&r.isNumericLiteral(s))return[Number(s.text)];let i=e.checker.getTypeAtLocation(s),o=[];for(let a of i.isUnion()?i.types:[i])if(n==="string"&&a.isStringLiteral())o.push(a.value);else if(n==="number"&&a.isNumberLiteral())o.push(a.value);else return null;return o.length>0?[...new Set(o)]:null}function Le(e,t,n){let r=O(e,t);e.warnings.has(r)||e.warnings.set(r,`${r} \u2014 ${n}`)}function gt(e,t){let n=T(e,t);return!n||e.isIdentifier(n)&&n.text==="undefined"||n.kind===e.SyntaxKind.VoidExpression}function Pe(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return/^[A-Za-z]/.test(t)?t:`E${t}`}function Ke(e,t,n,r,s){if(st.has(t)){let c=K(e,n[0],"number"),l=K(e,n[1],"string");return!l||!c||c.length!==1?(Le(e,r,`new ${t}(status, code, \u2026) with a code or status decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code and status literal types (or declare it with defineError)`),[]):l.map(u=>({name:s&&l.length===1?s:Pe(u),code:u,status:c[0]}))}let i=Object.prototype.hasOwnProperty.call(ue,t)?ue[t]:null;if(!i)return[];let o=[i.code];if(i.codeArg!==null&&n.length>i.codeArg&&!gt(e.ts,n[i.codeArg])&&(o=K(e,n[i.codeArg],"string"),!o))return Le(e,r,`new ${t}(\u2026) with a code decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code a literal type (or declare it with defineError)`),[];let a=o;return a.map(c=>({name:s&&a.length===1?s:c===i.code?t:Pe(c),code:c,status:i.status}))}function me(e,t){let n=e.ts,r=t.initializer&&T(n,t.initializer);return r&&n.isCallExpression(r)&&I(e,r.expression)==="defineError"?r:null}function _e(e,t,n){let r=K(e,n.arguments[0],"string"),s=K(e,n.arguments[1],"number"),i=r&&r.length===1?r[0]:null,o=s&&s.length===1?s[0]:null;return(i===null||o===null)&&at(e,n,`defineError(...) for "${t.name.getText()}" declares a typed error, so its code and status must be known when the project is built (a literal, or a constant of literal type)`),{name:t.name.getText(),code:i,status:o}}function pt(e,t){let n=null,r=s=>{if(!(n||e.isFunctionLike(s))){if(e.isCallExpression(s)&&s.expression.kind===e.SyntaxKind.SuperKeyword){n=s;return}e.forEachChild(s,r)}};return t.body&&e.forEachChild(t.body,r),n}function Ve(e,t,n,r){let s=e.ts,i=(t.heritageClauses||[]).find(f=>f.token===s.SyntaxKind.ExtendsKeyword),o=i&&i.types[0]&&i.types[0].expression;if(!o)return[];let a=t.members.find(f=>s.isConstructorDeclaration(f)&&!!f.body),c=n,l=r;if(a){let f=pt(s,a);if(!f)return[];c=f.arguments,l=f}let u=ct(s,t),m=I(e,o);if(m)return Ke(e,m,c,l,u);let g=L(e,o);if(g&&s.isVariableDeclaration(g)){let f=me(e,g);return f?[{..._e(e,g,f),name:u||g.name.getText()}]:[]}let y=_(e,o);if(y){let f=Ve(e,y,c,l);return f.length===1&&u?[{...f[0],name:u}]:f}return[]}function St(e,t){let n=e.ts,r=t.arguments||[],s=I(e,t.expression);if(s)return Ke(e,s,r,t);let i=T(n,t.expression),o=L(e,n.isPropertyAccessExpression(i)?i.name:i);if(!o)return[];if(n.isVariableDeclaration(o)){let c=me(e,o);if(c)return[_e(e,o,c)]}let a=Oe(n,o);return a&&v(e,a)?Ve(e,a,r,t):[]}function z(e,t,n,r,s,i,o=new Set){let a=e.ts;if(t=T(a,t),!t)return;let c=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`;if(!o.has(c)){if(o.add(c),a.isNewExpression(t)){let l=O(e,t);R(e,r,s,i,St(e,t).map(u=>({...u,site:l})));return}if(a.isConditionalExpression(t)){z(e,t.whenTrue,n,r,s,i,o),z(e,t.whenFalse,n,r,s,i,o);return}if(a.isBinaryExpression(t)){let l=a.SyntaxKind,u=t.operatorToken.kind;(u===l.QuestionQuestionToken||u===l.BarBarToken)&&z(e,t.left,n,r,s,i,o),z(e,t.right,n,r,s,i,o);return}if(a.isCallExpression(t)){for(let l of ee(e,t,n))for(let u of Y(a,l.fn))z(e,u,l.ctx,r,s,i,o);return}if(a.isIdentifier(t)||a.isPropertyAccessExpression(t)){let l=L(e,a.isPropertyAccessExpression(t)?t.name:t);if(l&&(a.isVariableDeclaration(l)||a.isPropertyDeclaration(l))&&l.initializer){let u=a.isVariableDeclaration(l)?je(l,n):n;z(e,l.initializer,u,r,s,i,o)}}}}function ce(e,t){let n=e.ts;if(!n.isFunctionLike(t))return!1;if((n.getCombinedModifierFlags(t)&n.ModifierFlags.Async)!==0)return!0;let r=e.checker.getSignatureFromDeclaration(t);if(!r)return!1;let s=e.checker.getReturnTypeOfSignature(r);return e.checker.getAwaitedType(s)!==s}function yt(e,t,n){let r=null;for(let s=t.parent;s&&s!==n;s=s.parent)e.isFunctionLike(s)&&(e.getCombinedModifierFlags(s)&e.ModifierFlags.Async)!==0&&(r=s);return r}function Tt(e,t,n){for(let r=t.parent;r&&r!==n;r=r.parent)if(e.isAwaitExpression(r)||e.isForOfStatement(r)&&r.awaitModifier)return!0;return!1}function ht(e,t,n,r){for(let s=t.scopes.length-1;s>=0;s--){let i=t.scopes[s],o=yt(e.ts,n,i.node),a=r||o!==null;if(i.kind==="try"){if(!a||Tt(e.ts,o||n,i.node))return i.sink}else if(i.kind==="settle"){if(a)return null}else if(i.kind==="catch"&&a&&!i.rethrows)return null}return t.root}function bt(e){let t=e.ts;if(e.statusOf)return e.statusOf;let n=new Map;for(let[s,i]of Object.entries(ue))n.set(i.code,{status:i.status,site:`palbase/backend ${s}`});let r=s=>{if(t.isVariableDeclaration(s)&&t.isIdentifier(s.name)){let i=me(e,s),o=i&&K(e,i.arguments[0],"string"),a=i&&K(e,i.arguments[1],"number");o&&a&&o.length===1&&a.length===1&&!n.has(o[0])&&n.set(o[0],{status:a[0],site:O(e,s)})}t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.statusOf=n,n}function xt(e,t){let n=bt(e),r=n.get(t.code);if(!r){n.set(t.code,{status:t.status,site:t.site});return}if(r.status!==t.status)throw new b(`"${t.code}" is thrown with status ${t.status} (${t.site}) but the code carries status ${r.status} (${r.site}) \u2014 a client matches an error by its code, so one code carries one status. Throw the code's own class, or give the error its own code`)}function R(e,t,n,r,s){for(let o of s)xt(e,o);let i=ht(e,t,n,r);if(i)for(let o of s)i.has(o.code)||i.set(o.code,o)}function Ue(e,t,n){if(!n)return!1;let r=!1,s=o=>{let a=!1,c=l=>{a||(e.isIdentifier(l)&&l.text===n?a=!0:e.forEachChild(l,c))};return c(o),a},i=o=>{r||e.isFunctionLike(o)&&o!==t||(e.isThrowStatement(o)&&o.expression&&s(o.expression)?r=!0:e.forEachChild(o,i))};return i(t),r}function wt(e,t){let n=T(e,t);if(n&&(e.isArrowFunction(n)||e.isFunctionExpression(n))){let r=n.parameters[0];return r?e.isIdentifier(r.name)?e.isBlock(n.body)?Ue(e,n.body,r.name.text):!1:!0:!1}return!0}function kt(e,t,n){let r=e.ts;if(!r.isPropertyAccessExpression(t)||t.name.text!==n)return!1;let s=T(r,t.expression);if(!r.isIdentifier(s)||s.text!=="Promise")return!1;let i=L(e,s);return!i||!v(e,i)}function B(e,t,n){let r=e.ts,s=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`,i=e.summaries.get(s);if(i&&(i.final||i.round===e.round))return i.busy&&(e.cyclic=!0),i.errors;i={errors:i?new Map(i.errors):new Map,busy:!0,round:e.round,final:!1},e.summaries.set(s,i);let o=i.errors.size,a={root:i.errors,scopes:[]};if(r.isFunctionLike(t)){let c=t;for(let l of c.parameters||[])l.initializer&&D(e,l.initializer,n,a);c.body&&D(e,c.body,n,a)}else D(e,t,n,a);return i.busy=!1,i.errors.size!==o&&(e.grew=!0),i.errors}function le(e,t){return{root:e.root,scopes:[...e.scopes,t]}}function D(e,t,n,r){let s=e.ts;if(s.isTryStatement(t)){let o=new Map;D(e,t.tryBlock,n,le(r,{kind:"try",node:t.tryBlock,sink:o}));let a=t.catchClause;(!a||(a.variableDeclaration&&s.isIdentifier(a.variableDeclaration.name)?Ue(s,a.block,a.variableDeclaration.name.text):a.variableDeclaration))&&R(e,r,t,!1,[...o.values()]),a&&D(e,a.block,n,r),t.finallyBlock&&D(e,t.finallyBlock,n,r);return}if(s.isThrowStatement(t))t.expression&&z(e,t.expression,n,r,t,!1);else if(s.isCallExpression(t)){let o=T(s,t.expression);if(kt(e,o,"allSettled")){D(e,t.expression,n,r);let u=le(r,{kind:"settle",node:t});for(let m of t.arguments)D(e,m,n,u);return}let a=s.isPropertyAccessExpression(o)?o.name.text==="catch"?0:o.name.text==="then"&&t.arguments.length>1?1:-1:-1;if(a>=0){let u=o,m=wt(s,t.arguments[a]);D(e,u.expression,n,le(r,{kind:"catch",node:u.expression,rethrows:m}));for(let g of t.arguments)D(e,g,n,r);return}let c=s.isPropertyAccessExpression(o)?ot.get(o.name.text):void 0;c!==void 0&&t.arguments[c]&&z(e,t.arguments[c],n,r,t,!0);let l=dt(e,o);if(l.length>0){let u=O(e,t);R(e,r,t,!0,l.map(m=>({...m,site:u})))}for(let u of ee(e,t,n))R(e,r,t,ce(e,u.fn),[...B(e,u.fn,u.ctx).values()]);for(let u of t.arguments)for(let m of De(e,u,n))R(e,r,u,ce(e,m.fn),[...B(e,m.fn,m.ctx).values()])}else if(s.isNewExpression(t)){let o=_(e,t.expression);if(o)for(let a of Be(e,o,o))R(e,r,t,!1,[...B(e,a.fn,a.ctx).values()]);for(let a of t.arguments||[])for(let c of De(e,a,n))R(e,r,a,ce(e,c.fn),[...B(e,c.fn,c.ctx).values()])}else if(s.isPropertyAccessExpression(t)&&!(t.parent&&s.isCallExpression(t.parent)&&t.parent.expression===t)){let o=L(e,t.name);if(o&&s.isGetAccessorDeclaration(o)&&o.body&&v(e,o))for(let a of C(e,t.expression,n)){let c=U(e,a,t.name.text,!1);c&&R(e,r,t,!1,[...B(e,c.fn,{receiver:a,owner:c.owner,fn:c.fn}).values()])}}if(F(s,t))return;let i=s.isFunctionExpression(t)||s.isFunctionDeclaration(t)?{receiver:null,owner:null,fn:t}:n;s.forEachChild(t,o=>D(e,o,i,r))}function qe(e,t,n){let r=e.ts;if(n.has(t))return[];if(n.add(t),I(e,t.expression)==="Resolve")return[t];let s=[];for(let i of ee(e,t,{receiver:null,owner:null,fn:null}))for(let o of Y(r,i.fn)){let a=T(r,o);r.isCallExpression(a)&&s.push(...qe(e,a,n))}return s}function Et(e,t){let n=e.ts,r=[];for(let s of t.parameters)for(let i of n.getDecorators(s)||[]){let o=T(n,i.expression);if(n.isCallExpression(o))for(let a of qe(e,o,new Set)){let c=_(e,a.arguments[0]);if(!c)continue;let l=new Set;fe(e,ze(e,c),l);for(let u of l){let m=U(e,u,"resolve",!1);m&&r.push({fn:m.fn,ctx:{receiver:u,owner:m.owner,fn:m.fn}})}}}return r}function Ct(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Nt(e,t,n){let r=new Map;for(let i of Et(e,n))for(let o of B(e,i.fn,i.ctx).values())r.has(o.code)||r.set(o.code,o);for(let i of B(e,n,{receiver:t,owner:t,fn:n}).values())r.has(i.code)||r.set(i.code,i);let s=new Map;for(let i of r.values()){let o=Ct(i.name),a=s.get(o);if(a)throw new b(`${t.name.text}.${P(e.ts,n.name)} can throw two errors named "${i.name}" \u2014 "${a.code}" (${a.site}) and "${i.code}" (${i.site}). Every client names an error case after it; give one of them its own defineError`);s.set(o,i)}return[...r.values()].map(({name:i,code:o,status:a})=>({name:i,code:o,status:a}))}function At(e,t){let n=[];for(let{cls:r,routes:s}of X(e,t)){let i={};for(let o of s)i[P(e.ts,o.name)]=Nt(e,r,o);n.push({className:r.name.text,ops:i})}return n}function Gt(e,t,n={}){let r=n.typescript??vt,s=Je(ge(e)),{options:i,ambient:o}=ke(r,s);return Dt(Ee(r,s,[Je(ge(t)),...o],i))}function Dt(e){let t=e.ts,n=Ne(e),r=$e(e),s=[],i=e.program.getSourceFiles().filter(a=>$(e,a.fileName)).sort((a,c)=>a.fileName<c.fileName?-1:a.fileName>c.fileName?1:0),o=[];for(let a of i){let c=X(e,a);if(c.length===0)continue;let l=new Map;for(let{cls:u,routes:m}of c)for(let g of m)try{l.set(`${u.name.text}.${P(t,g.name)}`,Ae(e,n,u.name.text,g))}catch(y){if(!(y instanceof b))throw y;o.push(y.message)}if(!(o.length>0))for(let{className:u,ops:m}of r.analyze(a))for(let[g,y]of Object.entries(m))s.push({file:ge(a.fileName),className:u,method:g,returns:l.get(`${u}.${g}`),throws:y})}if(o.length===1)throw new b(o[0]);if(o.length>1)throw new b(`${o.length} routes have no contract:
|
|
5
5
|
${o.map(a=>`- ${a}`).join(`
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! palbase 0.72.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{b as C}from"./DE7BWXBF.js";import{a as le}from"./JXIKBG4D.js";import{a as K,b as U,c as L,d as I,e as N,f as $,g as D,h as B,j as F,k as q,l as V,m as J,n as z,o as Y,p as G,q as X,r as Z}from"./XUYC354U.js";import{a as w,c as te,d as ne,e as re,f as oe,h as se,i as ie,j as R,k as ae,l as ce,o as A}from"./QROXSSPQ.js";import{a as Q,b as ee}from"./3MF6NROQ.js";import{b as x,d as v}from"./LDFOUUBT.js";var f=class extends Error{status=400;code;data;constructor(e,t,r={}){super(t),this.name="TransitRefusal",this.code=e,this.data=r}},Me=6e4,Oe=1e3;function M(n){return/^t[1-9][0-9]{0,5}$/.test(n)?Number(n.slice(1)):0}var k=class{keys=new Map;retired=new Set;order=[];project;timer;fetchedAt=0;heldFrom=0;fetching;opts;now;sleep;constructor(e){this.opts=e,this.now=e.now??Date.now,this.sleep=e.sleep??(t=>new Promise(r=>setTimeout(r,t)))}get loaded(){return this.project!==void 0}get projectId(){if(this.project===void 0)throw new Error("the project's transit keys are not loaded: await palbase.transit.load() at startup");return this.project}current(){return this.order[0]}async load(e){await this.refresh(e),this.timer===void 0&&(this.timer=setInterval(()=>{this.refresh().catch(()=>{})},Me),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}refresh(e){return this.fetching??=(async()=>{let t=this.now();try{let r=await this.opts.fetch(e),o=new Map;for(let s of r.keys){let i=ne(s.key);o.set(s.id,{privateKey:i,publicKey:this.keys.get(s.id)?.publicKey??await re(i)})}this.keys=o,this.order=r.keys.map(s=>s.id),this.retired=new Set(r.retired),this.project=r.project,this.fetchedAt=this.now(),this.heldFrom=t}finally{this.fetching=void 0}})(),this.fetching}newest(){return Math.max(0,...this.order.map(M),...[...this.retired].map(M))}async key(e){let t=this.now();for(;M(e)>this.newest()&&this.heldFrom<t;){let s=this.fetchedAt+Oe-this.now();if(s>0){await this.sleep(s);continue}await this.refresh()}let r=this.keys.get(e),o=this.current();if(this.retired.has(e))throw new f("encryption_key_retired",`the request is sealed to ${e}, retired: fetch the project's keys again`,{current:o});if(r===void 0)throw new f("encryption_key_unknown",`the request is sealed to ${e}, which the project has not made`,{current:o});return r}async request(e){if(e.header===void 0||e.header===null||e.header==="")throw new f("encryption_required",`this route carries encrypted fields: the request names its key in ${w}`,{field:w,current:this.current()});let t;try{t=se(e.header).kid}catch{throw new f("encryption_unopenable",`${w} is not one`,{field:w})}let r=await this.key(t),o;try{o=oe(this.projectId,e.method,e.path,e.params??[])}catch{throw new f("encryption_unopenable","the request's path holds a value no key is sealed for",{field:w})}try{return new E(t,await ie(e.header,r.privateKey,r.publicKey,o))}catch(s){throw s instanceof te?new f("encryption_unopenable","the request's key does not open: sealed for another project, route or path, or changed",{field:w}):s}}},E=class{kid;key;constructor(e,t){this.kid=e,this.key=t}async open(e,t,r){return A(e,t,r,async(o,s)=>{if(!ae(s))throw new f("encryption_required",`${o} is an encrypted field: it came plain`,{field:o});try{return await ce(this.key,o,s)}catch{throw new f("encryption_unopenable",`${o} does not open: changed, moved from another field, or another request's`,{field:o})}})}async seal(e,t){return A(e,"/response",t,(r,o)=>R(this.key,r,o))}sealField(e,t){return R(this.key,e,t)}};var He=/^pb_[a-z0-9]+_s/;function O(n){if(le())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!He.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=ee(v({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??Q),t=Y.client(e);return{ai:K.client(e),analytics:U.client(e),auth:L.client(e),cache:I.client(e),calls:N.client(e),fields:new C({fetch:async r=>(await t.getFieldKeys({signal:r})).data}),flags:D.client(e),iap:B.client(e),machines:F.client(e),messaging:q.client(e),notify:V.client(e),payments:J.client(e),commerce:$.client(e),realtime:z.client(e),secrets:t,storage:G.client(e),stores:X.client(e),workspaces:Z.client(e),transit:new k({fetch:async r=>(await t.getTransitKeys({signal:r})).data}),transport:e,url:new URL(n.url).origin}}var p=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},je=300,Ke=/^[0-9]{1,12}$/,Ue=/^[0-9a-f]{64}$/,de=8,Le=/^whsec_[0-9A-Za-z]{32,}$/,Ie=1024*1024;async function ue(n){if(typeof n.secret!="string"||!Le.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await pe(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(he(n.body)))}catch{throw new p("invalid_body","the signed body is not JSON")}if(!qe(e))throw new p("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function pe(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=he(n.body),{t,v1:r}=ye(n),o=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=new Uint8Array(await crypto.subtle.sign("HMAC",o,Fe(new TextEncoder().encode(`${t}.`),e))),i=!1;for(let l of r)Be(s,De(l))&&(i=!0);if(!i)throw new p("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function ye(n){let e=n.toleranceSeconds??je;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new p("missing_signature","the request carries no Palbase-Signature header");let o,s=[];for(let i of r.split(",")){let l=i.indexOf("=");if(l<=0)throw new p("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=i.slice(0,l).trim(),a=i.slice(l+1).trim();if(c==="t"){if(o!==void 0||!Ke.test(a))throw new p("malformed_signature","Palbase-Signature carries one t, in unix seconds");o=a}else if(c==="v1"){if(!Ue.test(a))throw new p("malformed_signature","a v1 is 64 lowercase hex characters");if(s.length===de)throw new p("malformed_signature",`Palbase-Signature carries at most ${de} v1`);s.push(a)}}if(o===void 0||s.length===0)throw new p("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(o))>e)throw new p("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:o,v1:s}}async function Ne(n,e,t={}){let r=await $e(n,t.maxBytes??Ie);return ue({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function $e(n,e){let t=()=>new p("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let o=n.body.getReader(),s=[],i=0;for(;;){let{done:a,value:d}=await o.read();if(a)break;if(i+=d.byteLength,i>e)throw await o.cancel().catch(()=>{}),t();s.push(d)}let l=new Uint8Array(i),c=0;for(let a of s)l.set(a,c),c+=a.byteLength;return l}function he(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function De(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function Be(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function Fe(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function qe(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var fe=60,Ve=60,Je=8*1024,ze=1e5;function H(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function we(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}function me(n){let e=we(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var _=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=ze){this.max=e}spend(e,t){if(t>=e.until)throw new u("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let o=r.get(e.jti);if(o!==void 0&&o>t)throw new u("proof","the DPoP proof is not taken: it was used before");o!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[o,s]of t){if(s>r)break;t.delete(o),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,o]of this.byKey){for(let[s,i]of o)i>e||(o.delete(s),this.held--);o.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,o)=>o[1].size-r[1].size);for(let[r,o]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=o.size}}};async function Ye(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return H(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function ge(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function be(n,e,t,r){let o=Ce=>{throw new u("proof",`the DPoP proof is not taken: ${Ce}`)},s=t.proof;if(!s)return o("there is none (a DPoP-bound token comes with a DPoP header)");if(s.length>Je)return o("it is too long");let i=s.split(".");if(i.length!==3)return o("it is not a JWS of three parts");let l=me(i[0]),c=me(i[1]);if(!l||!c)return o("its header or claims are not base64url JSON");if(l.typ!=="dpop+jwt")return o("its typ is not dpop+jwt");if(l.alg!=="ES256")return o(`it is signed with ${String(l.alg)}; only ES256 is taken`);let a=l.jwk;if(!a||typeof a!="object"||a.kty!=="EC"||a.crv!=="P-256"||typeof a.x!="string"||typeof a.y!="string")return o("its header carries no P-256 public key");if("d"in a)return o("its header carries a private key");if(await Ye(a.x,a.y)!==e)return o("it is signed by a key the token does not name");let d;try{d=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:a.x,y:a.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return o("its key is not a P-256 point")}let y=we(i[2]);if(!y||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},d,y,new TextEncoder().encode(`${i[0]}.${i[1]}`)).catch(()=>!1))return o("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return o(`it is for ${String(c.htm)}, not ${t.method}`);let h=typeof c.htu=="string"?ge(c.htu):void 0,m=ge(t.url);if(!h||!m||h!==m)return o(`it is for ${String(c.htu)}, not ${m??t.url}`);let S=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-S)>fe)return o("it was not made within a minute of now");let Re=H(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==Re)return o("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return o("it has no jti (or one longer than 256)");let Ae=H(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:Ae,until:(c.iat+fe+Ve)*1e3+1}}var u=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},b=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}},Ge=new Set(["invalid_api_key","missing_api_key","secret_key_in_browser"]);function Xe(n){return async e=>{let t=v({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch});try{return await t.send({op:"SessionStanding",method:"GET",path:"/auth/session/standing",auth:[["ApiKeyAuth","userJWT"]],answers:{204:"empty"}}),!0}catch(r){if(r instanceof x&&r.status===401&&!Ge.has(r.code))return!1;throw new b("a session's standing could not be told",{cause:r})}}}var W={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},ke=60,Ze=16*1024,Qe=10*6e4,et=5e4,Se=n=>typeof n=="string"&&Object.hasOwn(W,n),j=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new _;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>Ze)throw new u("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new u("malformed","the token is not a JWS of three parts");let o=ve(r[0]),s=ve(r[1]);if(!o||!s)throw new u("malformed","the token header or claims are not base64url JSON");let i=o.alg;if(!Se(i))throw new u("algorithm",`the token is signed with ${String(i)}; only ES256 and PS256 are taken`);let l=o.kid;if(typeof l!="string"||l==="")throw new u("malformed","the token header names no kid");let c=await this.key(l);if(!c)throw new u("unknown_key",`no key ${l} in the project's key set`);if(c.alg!==i)throw new u("algorithm",`key ${l} is ${c.alg}, the token says ${i}`);let a=_e(r[2]);if(!a)throw new u("malformed","the signature is not base64url");let d=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(W[c.alg].verify,c.key,a,d).catch(()=>!1))throw new u("signature","the signature does not verify");let g=this.check(s),h=s.cnf,m;if(h!==void 0){if(!t)throw new u("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof h!="object"||h===null||typeof h.jkt!="string"||h.jkt==="")throw new u("bound","the token is bound to a key it does not name (cnf.jkt)");m=await be(e,h.jkt,t,this.now())}else if(t)throw new u("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,g.sessionId))throw new u("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return m&&this.seenProofs.spend(m,this.now()),g}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:nt(e.headers),r=t.get("authorization")??"";if(r==="")return null;let o=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!o)throw new u("malformed","the Authorization header is not a Bearer or DPoP token");let s=o[1].toLowerCase()==="dpop",i=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(o[2],s?{proof:t.get("dpop"),method:e.method,url:Ee(t,i)}:void 0)}async stands(e,t){let r=this.now(),o=this.standings.get(t);if(o&&r<o.until)return o.live;let s=this.asking.get(t);s||(s=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,s));let i;try{i=await s}catch(c){let a=this.standings.get(t),d=this.now();if(a&&d<a.at+this.standingStaleMs)return a.until=Math.min(d+this.standingTtlMs,a.at+this.standingStaleMs),a.live;throw new b("a session's standing cannot be read now",{cause:c})}let l=this.now();return this.standings.delete(t),this.standings.set(t,{live:i,at:l,until:l+this.standingTtlMs}),this.standings.size>et&&this.standings.delete(this.standings.keys().next().value),i}check(e){if(e.iss!==this.issuer)throw new u("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new u("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new u("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+ke<=r)throw new u("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-ke>r))throw new u("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new u("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new u("not_a_session","the token is no session's");let o=e.custom_claims;if(o!==void 0&&(typeof o!="object"||o===null||o.type!==void 0))throw new u("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let o=this.keys.size>0&&t<this.keysUntil+Qe;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!o)throw new b("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(s){if(!o)throw s}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(s){throw this.lastFailure=s,new b("the project's key set cannot be read now",{cause:s})}this.lastFailure=void 0;let r=new Map;for(let s of Array.isArray(e.keys)?e.keys:[]){let i=s.alg;if(typeof s.kid!="string"||!Se(i))continue;let l=W[i];if(s.kty!==l.kty||s.use!==void 0&&s.use!=="sig")continue;let{d:c,...a}=s;try{r.set(s.kid,{alg:i,key:await crypto.subtle.importKey("jwk",a,l.import,!1,["verify"])})}catch{}}this.keys=r;let o=rt(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(o,this.refetchIntervalMs),this.maxKeyAgeMs)}};function Ee(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),o=n.get("host")??e.host;return tt.test(o)?`${r}://${o}${e.pathname}`:""}var tt=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function nt(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let o of Array.isArray(r)?r:[r])e.append(t,o);return e}function rt(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function _e(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function ve(n){let e=_e(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function ot(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var T=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function st(n,e,t,r){let{idempotencyKey:o,amount:s,ttlSeconds:i,metadata:l}=t;if(typeof o!="string"||o==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:s,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...i!==void 0?{ttl_seconds:i}:{},...l!==void 0?{metadata:l}:{}},a=(await n.iap.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":o},body:c})).data;if(a.status!=="held")throw new T(a);let d={customer_id:a.customer,spend_id:a.id},y;try{y=await r(a)}catch(g){throw await n.iap.releaseSpend({path:d}).catch(()=>{}),g}return await n.iap.commitSpend({path:d}),y}var it=new Set(["provider_unavailable","authentication_required","three_ds_failed"]);function at(n){return n!==void 0&&it.has(n)}function ct(n,e){return{[Te]:!0,commitAmount:n,value:e}}var Te=Symbol("palbase.payments.settleWalletHold");function lt(n){return typeof n=="object"&&n!==null&&Te in n}var P=class extends Error{hold;constructor(e){super(`wallet hold ${JSON.stringify(e.id)} is already ${e.status}: the work is not run again (use a new Idempotency-Key for a new hold)`),this.name="WalletHoldSettled",this.hold=e}};async function dt(n,e,t){let{idempotencyKey:r,walletKey:o,amount:s,ttlSeconds:i,reference:l,metadata:c}=e;if(typeof r!="string"||r.trim()==="")throw new TypeError("idempotencyKey is required for withWalletHold so retries never reserve funds twice");if(!Number.isInteger(s)||s<=0)throw new TypeError("amount must be a positive integer in minor units");let a={wallet_key:o,amount:s,...e.customerId!==void 0?{customer_id:e.customerId}:{spend_token:e.spendToken},...i!==void 0?{ttl_seconds:i}:{},...l!==void 0?{reference:l}:{},...c!==void 0?{metadata:c}:{}},d=(await n.payments.createWalletHold({headers:{"Idempotency-Key":r},body:a})).data;if(d.status!=="held")throw new P(d);let y;try{y=await t(d)}catch(g){throw await n.payments.releaseWalletHold({path:{hold_id:d.id}}).catch(()=>{}),g}return lt(y)?(y.commitAmount<=0?await n.payments.releaseWalletHold({path:{hold_id:d.id}}):await n.payments.commitWalletHold({path:{hold_id:d.id},body:{amount:y.commitAmount}}),y.value):(await n.payments.commitWalletHold({path:{hold_id:d.id}}),y)}function ut(n){return n.type.startsWith("payments.")}function pt(n){return n.type.startsWith("commerce.")}function yt(n){return n.type.startsWith("promotions.")}var ht=300,ft=/^[0-9]{1,12}$/;function mt(n){return typeof n=="string"?new TextEncoder().encode(n):n instanceof ArrayBuffer?new Uint8Array(n):n}function gt(n){if(n.startsWith("whsec_")){let e=n.slice(6);try{let t=atob(e),r=new Uint8Array(t.length);for(let o=0;o<t.length;o++)r[o]=t.charCodeAt(o);return r}catch{}}return new TextEncoder().encode(n)}function wt(n,e){if(n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}function bt(n){try{let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}catch{return null}}async function Pe(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the commerce hook signing secret (whsec_\u2026)");let e=n.webhookId?.trim()??"",t=n.webhookTimestamp?.trim()??"",r=n.webhookSignature?.trim()??"";if(!e||!t||!r)throw new p("missing_signature","webhook-id, webhook-timestamp, and webhook-signature headers are required");if(!ft.test(t))throw new p("malformed_signature","webhook-timestamp must be unix seconds");let o=n.toleranceSeconds??ht,s=Math.floor((n.now?.()??Date.now())/1e3);if(Math.abs(s-Number(t))>o)throw new p("stale_timestamp",`webhook-timestamp ${t} is outside tolerance (${o}s)`);let i=mt(n.body),l=new TextEncoder().encode(`${e}.${t}.`),c=new Uint8Array(l.length+i.length);c.set(l,0),c.set(i,l.length);let a=gt(n.secret),d=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),y=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),g=new Uint8Array(await crypto.subtle.sign("HMAC",y,c)),h=!1;for(let m of r.split(/\s+/)){if(!m.startsWith("v1,"))continue;let S=bt(m.slice(3));if(S&&wt(g,S)){h=!0;break}}if(!h)throw new p("signature_mismatch","no v1 signature in webhook-signature matches the payload")}function kt(n){return async e=>{let t=new Uint8Array(await e.arrayBuffer()),r=e.headers.get("webhook-id")??"";try{await Pe({secret:n.secret,webhookId:r,webhookTimestamp:e.headers.get("webhook-timestamp"),webhookSignature:e.headers.get("webhook-signature"),body:t,toleranceSeconds:n.toleranceSeconds,now:n.now})}catch(i){let l=i instanceof p?i.code:"signature_mismatch",c=i instanceof Error?i.message:"invalid hook signature";return new Response(JSON.stringify({error:l,error_description:c}),{status:401,headers:{"content-type":"application/json"}})}let o;try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{return new Response(JSON.stringify({error:"invalid_body",error_description:"hook body is not valid JSON"}),{status:400,headers:{"content-type":"application/json"}})}let s=await n.handle({hookPoint:e.headers.get("x-palbase-hook-point")??"",webhookId:r,payload:o,request:e});return new Response(JSON.stringify(s),{status:200,headers:{"content-type":"application/json"}})}}async function*St(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let o=r.next_cursor??void 0;if(o!==void 0&&t.has(o))throw new Error(`the listing answered a cursor it had answered before (${o})`);o!==void 0&&t.add(o),e=o}while(e)}var vt=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Et=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function xe(n){return!vt.test(n)||Et.test(n)||/_PROXY$/i.test(n)}var _t=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|CONTRACT_ENTRY|WEB_ORIGINS|SECRETS|DB_[A-Z0-9_]+))$/;function Tt(n){return _t.test(n)}async function Pt(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t==="production")throw new TypeError("PALBASE_SECRETS=production: a production secret's value is never read back \u2014 only the machines that start with it are given it. Run here with PALBASE_SECRETS=development (palbase env:pull writes it), and set a value for this computer with palbase secrets:set NAME --dev");if(t!=="development")throw new TypeError(`PALBASE_SECRETS is development, not ${t}`);let r=n.url??e.PALBASE_URL??"",o=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||o==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let s=O({url:new URL(r).origin,secretKey:o,fetch:n.fetch}),{data:i}=await s.secrets.getEnvironmentValues({path:{environment:t}}),l=[],c=[],a=[];for(let[d,y]of Object.entries(i.values)){if(xe(d)){a.push(d);continue}if(e[d]!==void 0&&e[d]!==""){c.push(d);continue}e[d]=y,l.push(d)}return{set:t,loaded:l.sort(),kept:c.sort(),refused:a.sort()}}export{f as a,k as b,E as c,O as d,p as e,ue as f,pe as g,ye as h,Ne as i,u as j,b as k,Xe as l,j as m,Ee as n,ot as o,T as p,st as q,at as r,ct as s,P as t,dt as u,ut as v,pt as w,yt as x,Pe as y,kt as z,St as A,xe as B,Tt as C,Pt as D};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as d,b as u}from"./P2ZR3LIZ.js";var g={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"},c=new WeakSet;function f(t){if(!(t instanceof u)||c.has(t))return t;let n=g[t.code];if(!n)return t;let i=new u({op:t.op,status:t.status,code:t.code,message:`${n(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return c.add(i),i}function m(t){return t.catch(n=>{throw f(n)})}function h(t){if(typeof t!="object"||t===null)return;let n=t,i=n.data;if(typeof n.type!="string"||typeof i!="object"||i===null||Array.isArray(i))return;let e=d(i),s=typeof n.id=="number"&&Number.isSafeInteger(n.id)?n.id:0;switch(n.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:s,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let r={...e,type:"turn",seq:s};return r.waiting??=null,r.error??=null,r}case"text":{let r=e.offset;return typeof e.response_id!="string"||typeof r!="number"||!Number.isInteger(r)||r<0?void 0:{type:"text",response_id:e.response_id,offset:r,text:typeof e.text=="string"?e.text:""}}case"reset":{let r=e.offset;return typeof e.response_id!="string"||typeof r!="number"||!Number.isInteger(r)||r<0?void 0:{type:"reset",response_id:e.response_id,offset:r}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let r=e.omitted_bytes;return{...e,type:"tool",seq:s,omittedBytes:typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:s}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let r=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:s,response_id:e.response_id,run_id:r,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:s,response_id:e.response_id,run_id:r,...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:r,...a}=e;return{...a,type:"goal",seq:s,...typeof r=="number"?{turn:r}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let r=e.items.filter(o=>typeof o=="object"&&o!==null&&(o.role==="user"||o.role==="assistant")&&typeof o.text=="string"),a=e.forked_from;return{type:"history",forked_from:a&&typeof a.chat_id=="string"?a:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:r}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:s,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:s,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:s,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:s,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:s,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:s,...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 n=d(t);if(!(typeof n.chat_id!="string"||n.chat_id===""||typeof n.run_status!="string"||typeof n.target_generation!="number")&&!(typeof n.target_summary!="object"||n.target_summary===null))return{chat_id:n.chat_id,run_status:n.run_status,...typeof n.active_run_id=="string"&&n.active_run_id!==""?{active_run_id:n.active_run_id}:{},...typeof n.workspace_id=="string"&&n.workspace_id!==""?{workspace_id:n.workspace_id}:{},target_generation:n.target_generation,target_summary:n.target_summary,updated_at:typeof n.updated_at=="string"?n.updated_at:""}}function v(t){let n=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n+=1:e<2048?n+=2:e>=55296&&e<=56319&&i+1<t.length&&(t.charCodeAt(i+1)&64512)===56320?(n+=4,i++):n+=3}return n}function p(t,n){if(n<=0)return 0;let i=0;for(let e=0;e<t.length;e++){let s=t.charCodeAt(e),r=3,a=1;if(s<128?r=1:s<2048?r=2:s>=55296&&s<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(r=4,a=2),i+=r,i>=n)return e+a;e+=a-1}return t.length}function w(t,n){return t.slice(p(t,n))}export{m as a,h as b,y as c,v as d,p as e,w as f};
|
|
1
|
+
/*! palbase 0.72.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as d,b as u}from"./LDFOUUBT.js";var g={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"},c=new WeakSet;function f(t){if(!(t instanceof u)||c.has(t))return t;let n=g[t.code];if(!n)return t;let i=new u({op:t.op,status:t.status,code:t.code,message:`${n(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return c.add(i),i}function m(t){return t.catch(n=>{throw f(n)})}function h(t){if(typeof t!="object"||t===null)return;let n=t,i=n.data;if(typeof n.type!="string"||typeof i!="object"||i===null||Array.isArray(i))return;let e=d(i),s=typeof n.id=="number"&&Number.isSafeInteger(n.id)?n.id:0;switch(n.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:s,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let r={...e,type:"turn",seq:s};return r.waiting??=null,r.error??=null,r}case"text":{let r=e.offset;return typeof e.response_id!="string"||typeof r!="number"||!Number.isInteger(r)||r<0?void 0:{type:"text",response_id:e.response_id,offset:r,text:typeof e.text=="string"?e.text:""}}case"reset":{let r=e.offset;return typeof e.response_id!="string"||typeof r!="number"||!Number.isInteger(r)||r<0?void 0:{type:"reset",response_id:e.response_id,offset:r}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let r=e.omitted_bytes;return{...e,type:"tool",seq:s,omittedBytes:typeof r=="number"&&Number.isSafeInteger(r)&&r>0?r:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:s}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let r=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:s,response_id:e.response_id,run_id:r,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:s,response_id:e.response_id,run_id:r,...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:r,...a}=e;return{...a,type:"goal",seq:s,...typeof r=="number"?{turn:r}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let r=e.items.filter(o=>typeof o=="object"&&o!==null&&(o.role==="user"||o.role==="assistant")&&typeof o.text=="string"),a=e.forked_from;return{type:"history",forked_from:a&&typeof a.chat_id=="string"?a:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:r}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:s,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:s,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:s,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:s,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:s,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:s,...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 n=d(t);if(!(typeof n.chat_id!="string"||n.chat_id===""||typeof n.run_status!="string"||typeof n.target_generation!="number")&&!(typeof n.target_summary!="object"||n.target_summary===null))return{chat_id:n.chat_id,run_status:n.run_status,...typeof n.active_run_id=="string"&&n.active_run_id!==""?{active_run_id:n.active_run_id}:{},...typeof n.workspace_id=="string"&&n.workspace_id!==""?{workspace_id:n.workspace_id}:{},target_generation:n.target_generation,target_summary:n.target_summary,updated_at:typeof n.updated_at=="string"?n.updated_at:""}}function v(t){let n=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n+=1:e<2048?n+=2:e>=55296&&e<=56319&&i+1<t.length&&(t.charCodeAt(i+1)&64512)===56320?(n+=4,i++):n+=3}return n}function p(t,n){if(n<=0)return 0;let i=0;for(let e=0;e<t.length;e++){let s=t.charCodeAt(e),r=3,a=1;if(s<128?r=1:s<2048?r=2:s>=55296&&s<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(r=4,a=2),i+=r,i>=n)return e+a;e+=a-1}return t.length}function w(t,n){return t.slice(p(t,n))}export{m as a,h as b,y as c,v as d,p as e,w as f};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.72.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var s=class extends Error{code;constructor(t,e){super(e),this.name="FieldError",this.code=t}},f="pbe1.",g="pbl1.",k=6e4,p="[A-Za-z_][A-Za-z0-9_$]{0,62}",w=new RegExp(`^${p}\\.${p}(\\.${p})?$`);function v(o){return w.test(o)}var h=class{crypto;keys=new Map;lookupKey;timer;opts;now;constructor(t){this.opts=t,this.now=t.now??Date.now}get loaded(){return this.lookupKey!==void 0}async load(t){this.crypto??=await import("node:crypto"),this.take(await this.opts.fetch(t)),this.timer===void 0&&(this.timer=setInterval(()=>{this.opts.fetch().then(e=>this.take(e),()=>{})},k),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}take(t){let e=new Map;for(let r of t.keys)e.set(r.id,{id:r.id,key:Buffer.from(r.key,"base64url"),activatesAt:Date.parse(r.activates_at)});this.keys=e,this.lookupKey=Buffer.from(t.lookup,"base64url")}ready(){if(this.crypto===void 0||this.lookupKey===void 0)throw new s("not_loaded","the project's field keys are not loaded: await palbase.fields.load() at startup");return this.crypto}currentKey(){this.ready();let t;for(let e of this.keys.values())e.activatesAt<=this.now()&&(t===void 0||e.activatesAt>=t.activatesAt)&&(t=e);if(t===void 0)throw new s("unknown_key","the project has no field key in force");return t.id}encrypt(t,e){let r=this.ready();l(t);let n=this.currentKey(),i=r.randomBytes(12);return b(r,this.keys.get(n).key,i,n,t,e)}decrypt(t,e){let r=this.ready();if(l(t),!e.startsWith(f))throw new s("not_encrypted",`${t} holds a value that is not encrypted`);let n=e.slice(f.length),i=n.indexOf("."),a=i<0?n:n.slice(0,i),u=this.keys.get(a);if(u===void 0)throw new s("unknown_key",`${t} was sealed with field key ${a}, which this project does not hold`);let c=Buffer.from(n.slice(i+1),"base64url");if(i<0||c.length<28||c.toString("base64url")!==n.slice(i+1))throw new s("unopenable",`${t} holds a value that does not open here`);try{let d=r.createDecipheriv("aes-256-gcm",u.key,c.subarray(0,12));return d.setAAD(y(t)),d.setAuthTag(c.subarray(c.length-16)),Buffer.concat([d.update(c.subarray(12,c.length-16)),d.final()]).toString("utf8")}catch{throw new s("unopenable",`${t} holds a value that does not open here: tampered, or another column's`)}}isEncrypted(t){return t.startsWith(f)}lookup(t,e){let r=this.ready();return l(t),m(r,this.lookupKey,t,e)}};function l(o){if(!v(o))throw new TypeError(`a field's address is table.column, or schema.table.column, not ${JSON.stringify(o)}`)}function y(o){return Buffer.from(`pbe1\0${o}`,"utf8")}function b(o,t,e,r,n,i){let a=o.createCipheriv("aes-256-gcm",t,e);a.setAAD(y(n));let u=Buffer.concat([e,a.update(i,"utf8"),a.final(),a.getAuthTag()]);return`${f}${r}.${u.toString("base64url")}`}function m(o,t,e,r){let n=o.createHmac("sha256",t);return n.update(`pbl1\0${e}\0`,"utf8"),n.update(r,"utf8"),`${g}${n.digest("base64url")}`}export{s as a,h as b};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.72.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
|