palbase 0.74.0 → 0.76.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai-sdk/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{RK4CTF2F.js → 2NEPN2ZZ.js} +2 -2
- package/dist/chunks/{FKDQMWI7.js → 33XOVYAU.js} +2 -2
- package/dist/chunks/{53XWB3UV.js → 3CN6HGTW.js} +1 -1
- package/dist/chunks/{OS567PDL.js → 3VGWTVKI.js} +2 -2
- package/dist/chunks/{4DNFXRTX.js → 5RNXCTOO.js} +2 -2
- package/dist/chunks/{BBXGUP7G.js → 5YJZAPY2.js} +2 -2
- package/dist/chunks/{WNPRCDLR.js → A3I7H7QN.js} +1 -1
- package/dist/chunks/{YOCX3MXN.js → ALT62XIG.js} +2 -2
- package/dist/chunks/{AFO74GQQ.js → BRDO3ZPT.js} +1 -1
- package/dist/chunks/{IIQ6QEL2.js → D6NOE76D.js} +1 -1
- package/dist/chunks/{YDHRQOAN.js → DKYFIOWM.js} +1 -1
- package/dist/chunks/{SS3YF6MP.js → EXLA3A7O.js} +2 -2
- package/dist/chunks/{5NLCEWSD.js → ISMWEEGW.js} +1 -1
- package/dist/chunks/{IJBBBAXY.js → KEGVHELA.js} +1 -1
- package/dist/chunks/{U5LDOZB5.js → MKVIRNSJ.js} +2 -2
- package/dist/chunks/{QJPQVLNV.js → PGQNRJ2C.js} +2 -2
- package/dist/chunks/{CVBLXV6M.js → Q4UWBIJ6.js} +2 -2
- package/dist/chunks/{DFIAGTHU.js → SVWF7ABJ.js} +2 -2
- package/dist/chunks/{FYZAVXD4.js → TGQGGUE6.js} +2 -2
- package/dist/chunks/{MKKBGO2H.js → TUK6NH2Q.js} +2 -2
- package/dist/chunks/{7HDSHHGM.js → UHN63FGH.js} +7 -7
- package/dist/chunks/{ZRNXABQJ.js → UOW74IHY.js} +2 -2
- package/dist/chunks/YRYPXVAJ.js +18 -0
- package/dist/chunks/{AKM627JB.js → ZCMCYI2D.js} +2 -2
- package/dist/cli.js +2 -2
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai-sdk.js +1 -1
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/payments-ui.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/index.d.ts +1 -1
- package/types/ai/src/tools.d.ts +18 -0
- package/types/backend/src/gateways.d.ts +9 -0
- package/types/internal/src/modules/ai.d.ts +8 -0
- package/dist/chunks/PF52QMPW.js +0 -18
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{c as hr,d as gr,e as nn,f as yr,g as wr}from"./FYZAVXD4.js";import{a as Rt,c as ne,d as pr,e as mr,f as be,h as _,i as br}from"./U5LDOZB5.js";import{F as fr,a as dr,e as dt,g as St,h as cr,i as ur,j as At,k as xt,n as lr}from"./4DNFXRTX.js";import{a as Et,b as or,n as ir}from"./WNPRCDLR.js";import{b as ie}from"./ZRNXABQJ.js";import"reflect-metadata";var rn=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],kr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Ot=/^\d+$/;function ba(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let g=s.slice(a+1);if(!Ot.test(g)||Number(g)<1||Number(g)>n)return;d=Number(g)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),b=o.slice(0,g),k=o.slice(g+1);if(!Ot.test(b)||!Ot.test(k)||Number(b)<t||Number(k)>n||Number(b)>Number(k))return;l=Number(b),h=Number(k)}else{if(!Ot.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let g=l;g<=h;g+=d)r.add(g)}return r}function vr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${kr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let g=ba(t[h],rn[h].lo,rn[h].hi);if(!g)return`${kr}; its ${rn[h].name} "${t[h]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let g=r.has(l.getUTCDate()),b=a.has(l.getUTCDay());if(o||d?g&&b:g||b)return}return`"${e}" is never due: no date has that day in that month`}var qe=Symbol.for("palbase.backend.controller"),He=Symbol.for("palbase.backend.routes"),an=Symbol.for("palbase.backend.params"),on=Symbol.for("palbase.backend.injectable"),dn=Symbol.for("palbase.backend.module"),Me=Symbol.for("palbase.backend.events"),Be=Symbol.for("palbase.backend.webhook"),Ee=Symbol.for("palbase.backend.crons"),ke=Symbol.for("palbase.backend.tasks"),Te=Symbol.for("palbase.backend.testUserTemplates");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var sn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[sn]instanceof Set||(e[sn]=new Set),e[sn]}var ze=new Set(["webhooks","_palbase"]);function hd(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&ze.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,qe,()=>({basePath:e,options:t})),se().add(n)}}function Ge(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);de(r.constructor,He,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var gd=Ge("GET"),yd=Ge("POST"),wd=Ge("PUT"),bd=Ge("PATCH"),kd=Ge("DELETE"),vd=Ge("QUERY");function pe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=de(n.constructor,an,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function cn(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var Td=e=>pe("body",{schema:cn("Body",e)}),$d=e=>pe("query",{schema:cn("QueryParams",e)}),_d=e=>pe("headers",e===void 0?{}:{schema:cn("Headers",e)}),Ed=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return pe("param",{name:e})},Sd=()=>pe("user"),Ad=()=>pe("optionalUser"),xd=()=>pe("req"),Rd=()=>pe("requestId"),Od=()=>pe("client"),Pd=()=>pe("attestedDevice");function Cd(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return pe("resolve",{resolver:e,options:t[0]})}function Md(){return e=>{de(e,on,()=>!0),se().add(e)}}function jd(e){return t=>{de(t,dn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var _r=/^[a-z]+(\.[a-z_]+)+$/,ka=/^[a-z][a-z0-9-]{1,62}$/,un=e=>e.startsWith("file.");function Dd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!ka.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!un(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);de(r.constructor,Me,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var ln=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,va=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Tr(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!va.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Nd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=vr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Tr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Tr(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Ee))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Ee,{value:s,enumerable:!1}),se().add(a)}}var $r=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Ta=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ud(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!Ta.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!$r.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${$r.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&$a(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Me)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}de(t,Be,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function $a(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ld(){return[...se()].filter(e=>D(e,qe)!==void 0)}function Id(e){return(D(e,He)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Pt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Gd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}var mn;function Sr(e){mn=e}function fn(){if(!mn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return mn}var _a=720*3600;function Ea(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>_a))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function Sa(e){if(typeof e=="string")return e;let t=e[ke];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Fd=Rt("Tasks",{async enqueue(e,t,n={}){return Ea(n),fn().enqueue(Sa(e),t===void 0?null:t,n)},async cancel(e,t={}){return fn().cancel(e,t.machine)},async get(e,t={}){return fn().get(e,t.machine)}}),pn=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function Ar(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await be.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return pn(a.data,a.status===200)},async cancel(n,r){return pn((await be.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return pn((await be.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Aa=1e4,xa=36e5,Er=24*36e5,Ct=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<Er))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(Aa*2**Math.min(t.attempt-1,16),xa),_.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=Er&&this.tasks.delete(s);n==="failed"&&_.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Mt="/_palbase/test-user-templates",Ra=/^[a-z][a-z0-9_-]{0,63}$/;function Vd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Ra.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,Te))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,Te,{value:r,enumerable:!1}),se().add(s)}}function xr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Rr(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ie&&n.status===404)return!1;throw n}}var Oa="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function Or(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,Oa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var hn=20;function Pr(e,t){let n=[...t].sort(),r=n.length===0?" none":`: ${n.slice(0,hn).join(", ")}${n.length>hn?` and ${n.length-hn} more`:""}`;return`This version has no test user template ${JSON.stringify(e.slice(0,64))} \u2014 it has${r}`}var gn="/_palbase/storage/upload/authorize",Cr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Pa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fe(e){if(!Pa(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function Mr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function jr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function jt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ca=/^[a-z][a-z0-9-]{1,62}$/,Dr=1024,Ma=new Set(["userId","uploadId","filename"]);function ec(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);let r=n.bucket;if(typeof r!="string"||r==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Ca.test(r))throw new TypeError(`@Upload("${e}"): bucket "${r}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let s=ja(n.pathTemplate);if(s)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${s}`);let a={bucket:r,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(d,l,h)=>{if(typeof l!="string"||h===void 0||typeof h.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(d.constructor,He,()=>[]).push({method:"POST",subpath:e,fn:l,options:o,upload:a})}}function tc(){return pe("uploadedObject")}function ja(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Ma.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!Nr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Nr(e){if(e===""||new TextEncoder().encode(e).byteLength>Dr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Da(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Na(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Na(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function Ur(e,t){let n=Da(e,t);return Nr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Dr} bytes)`}}function Lr(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ir(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Fe(t.user);if(!o)return"user is { id?, session?, role }";let d=Mr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=Ua(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Ua(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!wn(g)||!Object.values(g).every(b=>typeof b=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...g}}}import{markData as La}from"palgres";var je=Symbol.for("palbase.backend.gateway"),Je=Symbol.for("palbase.backend.gatewayHooks"),qr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},Ia={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(qr),output:()=>structuredClone(qr)}}},Kr=Symbol.for("palbase.backend.gatewayRefusal"),Hr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Kr,{value:!0})}},qa=e=>typeof e=="object"&&e!==null&&e[Kr]===!0&&typeof e.reason=="string",We=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Ha=6e4,Ba=86400,Br=604800,zr=65536,Se=255,za=["roles:","flags:","messaging:","calls:","debug:"],Ga=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Ke=e=>new TextEncoder().encode(e).byteLength,bn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",Tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Fa(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Ke(e)>Se)return`a channel is ${Se} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=za.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Jr(e){if(typeof e!="string"||e==="")return"is a name";if(Ke(e)>Se)return`is ${Se} bytes at most`}function ic(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Fa(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&Tn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Wa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||Ga.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,b]of Object.entries(d)){let k=Jr(g);if(k)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${k}`);if(!bn(b))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=de(a,Je,$n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Ia}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ha,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&We(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!We(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);de(a,je,()=>h),se().add(a)}}function Wa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ba;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Br)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Br} (a week)`);return n}var $n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ka={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ka[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=de(n.constructor,Je,$n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var dc=ct("authorize"),cc=ct("first"),uc=ct("connect"),lc=ct("disconnect"),fc=ct("empty");function pc(e,t,n={}){let r=Jr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!bn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!bn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=de(s.constructor,Je,$n),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ja(e){return D(e,je)}function Va(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Vr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Ke(r)>Se?{problem:`a channel is ${Se} bytes at most`}:r}function Za(e,t,n){let r=Tn(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Vr(e,t):Ya(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Ya(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Qa=1e4,Xa=1e3,eo=100,_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),we=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Gr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Fr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Zr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:v,instance:E}of e){let f=Ja(v),T=a.get(f.name);if(T!==void 0&&T!==v)throw new TypeError(`@Gateway("${f.pattern}"): two gateways are named ${f.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(f.name,v);let R=s.get(Fr(f.pattern));if(R!==void 0)throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: ${n.get(R)?.cls.name}'s "${R}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Fr(f.pattern),f.pattern);for(let[z,J]of[...Object.entries(f.hooks),...Object.entries(f.messages).map(([L,N])=>[`message ${L}`,N.fn])])if(typeof E[J]!="function")throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: its ${z} is ${J}, which is no method of it`);let I={cls:v,instance:E,g:f};n.set(f.pattern,I),r.set(v,I)}let o=new Map,d=new Set,l=new Set,h=new vn(t.broadcast),g=v=>{let E=o.get(v);return E||(E=new AbortController,o.set(v,E)),E},b=(v,E)=>{E?.abort(),o.get(v)===E&&o.delete(v)},k=(v,E,f,T,R,I)=>{if(!Object.hasOwn(v.g.events,f)){_.warn(`[palbase] ${R}: emit("${f}") is not sent \u2014 ${v.cls.name} declares no event "${f}" (static events)`);return}if(v.g.chat&&f==="chat"){_.warn(`[palbase] ${R}: emit("chat") is not sent \u2014 ${v.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:f,payload:T??{},...I!==void 0?{conn_id:I}:{}},R)},B=async(v,E,f)=>{if(typeof v!="object"||v===null||typeof v.pipe!="function")throw new TypeError(`${f}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await v.pipe(E)};function U(v,E,f,T,R,I,z){let J=T?.signal??AbortSignal.abort(),L=`${v.cls.name} (${E})`;return{channel:E,params:Object.freeze({...f}),signal:J,count:R,user:I,emit:(N,G)=>k(v,E,N,G,L,z),pipe:N=>B(N,E,L),owner:{hold(N){ne.exit(async()=>{try{await N(J)}catch(G){J.aborted||_.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>b(E,T)}}}function q(v){let{room:E,channel:f}=v;if(typeof E!="string"||typeof f!="string")return we(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!We(T.g)?we(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:f,params:Va(E,f)}}let W=(v,E)=>we(400,"bad_request",`"${E}" is not a channel of the gateway "${v}"`);async function K(v,E){let f=q(v);if("status"in f)return f;let{entry:T,channel:R,params:I}=f,z={status:200,body:{subscribe:!1,publish:!1}};if(!I)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${R}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),z;let J=Fe(v.user),L=J?.id;if(!L)return z;if(T.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}};if(T.g.access==="owner")return I[Tn(T.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:z;let N=T.g.hooks.authorize;if(!N)return z;let G,Q;try{G=await t.run(J,`${T.cls.name}.${N}`,E,async()=>T.instance[N]({user:{id:L},params:Object.freeze({...I})})),Q=to(G)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return _.error(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) failed; the join is refused`,{error:te}),z}return Q==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) answered ${no(G)}, which is no grant (true, { read, write } or null); the join is refused`),z):{status:200,body:Q}}async function le(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return W(f.entry.g.pattern,f.channel);let T=Fe(v.user);if(!T?.id||typeof v.event!="string")return we(400,"bad_request","A message names its member (user) and its event");let R=Object.hasOwn(f.entry.g.messages,v.event)?f.entry.g.messages[v.event]:void 0;if(!R)return{status:200,body:{ok:!1,reason:kn(`gateway "${f.channel}" takes no message "${v.event}"`,Dt)}};let I=await R.schema["~standard"].validate(La(v.payload??{}));if(I.issues)return{status:200,body:{ok:!1,reason:Wr(I.issues)}};let z=g(f.channel),J={...U(f.entry,f.channel,f.params,z,0,{id:T.id}),payload:I.value},L=`${f.entry.cls.name}.${R.fn} (@Subscribe "${v.event}" of ${f.channel})`,N;try{N=await t.run(T,`${f.entry.cls.name}.${R.fn}`,E,async()=>f.entry.instance[R.fn](J))}catch(Q){if(t.isOutage(Q))throw Q;return qa(Q)?{status:200,body:{ok:!1,reason:kn(Q.reason,Dt)}}:(E?.aborted||_.error(`[palbase] ${L} failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(R.reply){let Q=await R.reply["~standard"].validate(N);if(Q.issues)return _.error(`[palbase] ${L} returned an ack its reply schema refuses (${Wr(Q.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=Q.value}let G;try{G=JSON.stringify(N)}catch(Q){return _.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Ke(G)>zr?(_.error(`[palbase] ${L} returned an ack of ${Ke(G)} bytes, past ${zr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(G)}}}async function he(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return W(f.entry.g.pattern,f.channel);let T=v.event;if(typeof T!="string"||!Object.hasOwn(Gr,T))return we(400,"bad_request","A gateway's moment is first, join, leave or empty");let R=typeof v.count=="number"&&Number.isInteger(v.count)&&v.count>=0?v.count:void 0;if(R===void 0)return we(400,"bad_request","A gateway's moment says its count of members");let I=T==="join"||T==="leave",z=I?Fe(v.user):void 0,J=I?v.connId:void 0;if(I&&(!z?.id||typeof J!="string"||J===""))return we(400,"bad_request",`A ${T} names its member: user and connId`);let L=`${T}\0${f.channel}\0${typeof J=="string"?J:""}`;if(I&&d.has(L))return{status:204};if(l.has(L))return we(503,"in_progress","This moment of the gateway is being handled",5);l.add(L);try{let N=f.entry.g.hooks[Gr[T]],G;if(T==="empty"?(G=o.get(f.channel),b(f.channel,G)):G=T==="leave"?o.get(f.channel):g(f.channel),N){let Q=U(f.entry,f.channel,f.params,G,R,{id:z?.id??""},T==="join"?J:void 0);try{await t.run(z,`${f.entry.cls.name}.${N}`,E,async()=>f.entry.instance[N](Q))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||_.error(`[palbase] ${f.entry.cls.name}.${N} (${T} of ${f.channel}) failed; realtime tells it again`,{error:te}),we(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return I&&(d.add(L),d.size>Qa&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(L)}}function ge(v,E){let f=r.get(v),T=`Palbase.gateways.to(${v?.name??String(v)})`;if(!f)throw new TypeError(`${T}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let R=Vr(f.g.pattern,E??{});if(typeof R!="string")throw new TypeError(`${T}: ${R.problem}`);return{entry:f,channel:R,where:T}}return{declarations:[...n.values()].map(v=>v.g),async serve(v,E,f){return _n(E)?v==="authorize"?K(E,f):v==="message"?le(E,f):v==="lifecycle"?he(E,f):we(404,"not_found",`No gateway call ${JSON.stringify(v)}`):we(400,"bad_request","A gateway's call is a JSON object")},emit(v,E,f,T){let{entry:R,channel:I,where:z}=ge(v,E);k(R,I,f,T,z)},async pipe(v,E,f){let{channel:T,where:R}=ge(v,E);await B(f,T,R)},async revalidate(v,E,f={}){let T=r.get(v),R=`Palbase.gateways.to(${v?.name??String(v)}).revalidate`;if(!T)throw new TypeError(`${R}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let I=Za(T.g.pattern,E??{},f);if("problem"in I)throw new TypeError(`${R}: ${I.problem}`);let z=ne.getStore()?.saying;if(z){z.push(()=>{t.revalidate(I).catch(J=>_.warn(`[palbase] ${R}: realtime did not decide the channel again`,{error:J}))});return}await t.revalidate(I)},close(){for(let v of o.values())v.abort();o.clear()}}}function to(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!_n(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function no(e){return Array.isArray(e)?"an array":_n(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var ro=20,Dt=256;function Wr(e){let t="";for(let n of e.slice(0,ro)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Dt)break}return kn(t,Dt)}function kn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var vn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ke(t.event)>Se){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Se} bytes`);return}try{JSON.stringify(t.payload)}catch(s){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let r=ne.getStore()?.saying;r?r.push(()=>this.queue(t,n)):this.queue(t,n)}queue(t,n){let r=this.queues.get(t.topic);if(r){r.length>=Xa?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,eo);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as En,createHmac as so,createPublicKey as es,timingSafeEqual as ao,verify as ts}from"node:crypto";function yc(e){let t=D(e,Be);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function ns(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,Be),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,g=n[d.secret.env],b;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{b=oo(d,g)}catch(U){a.push(`${h}: ${d.secret.env} ${U.message}`)}let k=t(o),B=new Map(d.events.map(({event:U,fn:q})=>[U,{name:`${o.name}.${q}`,call:(W,K)=>k[q](W,K)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:b,events:B})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
1
|
+
/*! palbase 0.76.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{c as gr,d as yr,e as nn,f as wr,g as br}from"./TGQGGUE6.js";import{a as Rt,c as ne,d as mr,e as hr,f as be,h as _,i as kr}from"./MKVIRNSJ.js";import{F as pr,a as cr,e as dt,g as St,h as ur,i as lr,j as At,k as xt,n as fr}from"./5RNXCTOO.js";import{a as Et,b as ir,n as dr}from"./A3I7H7QN.js";import{b as ie}from"./UOW74IHY.js";import"reflect-metadata";var rn=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],vr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Ot=/^\d+$/;function ka(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let g=s.slice(a+1);if(!Ot.test(g)||Number(g)<1||Number(g)>n)return;d=Number(g)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),b=o.slice(0,g),k=o.slice(g+1);if(!Ot.test(b)||!Ot.test(k)||Number(b)<t||Number(k)>n||Number(b)>Number(k))return;l=Number(b),h=Number(k)}else{if(!Ot.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let g=l;g<=h;g+=d)r.add(g)}return r}function Tr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${vr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let g=ka(t[h],rn[h].lo,rn[h].hi);if(!g)return`${vr}; its ${rn[h].name} "${t[h]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let g=r.has(l.getUTCDate()),b=a.has(l.getUTCDay());if(o||d?g&&b:g||b)return}return`"${e}" is never due: no date has that day in that month`}var qe=Symbol.for("palbase.backend.controller"),He=Symbol.for("palbase.backend.routes"),an=Symbol.for("palbase.backend.params"),on=Symbol.for("palbase.backend.injectable"),dn=Symbol.for("palbase.backend.module"),Me=Symbol.for("palbase.backend.events"),Be=Symbol.for("palbase.backend.webhook"),Ee=Symbol.for("palbase.backend.crons"),ke=Symbol.for("palbase.backend.tasks"),Te=Symbol.for("palbase.backend.testUserTemplates");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var sn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[sn]instanceof Set||(e[sn]=new Set),e[sn]}var Ge=new Set(["webhooks","_palbase"]);function gd(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&Ge.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,qe,()=>({basePath:e,options:t})),se().add(n)}}function ze(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);de(r.constructor,He,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var yd=ze("GET"),wd=ze("POST"),bd=ze("PUT"),kd=ze("PATCH"),vd=ze("DELETE"),Td=ze("QUERY");function pe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=de(n.constructor,an,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function cn(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var $d=e=>pe("body",{schema:cn("Body",e)}),_d=e=>pe("query",{schema:cn("QueryParams",e)}),Ed=e=>pe("headers",e===void 0?{}:{schema:cn("Headers",e)}),Sd=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return pe("param",{name:e})},Ad=()=>pe("user"),xd=()=>pe("optionalUser"),Rd=()=>pe("req"),Od=()=>pe("requestId"),Pd=()=>pe("client"),Cd=()=>pe("attestedDevice");function Md(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return pe("resolve",{resolver:e,options:t[0]})}function jd(){return e=>{de(e,on,()=>!0),se().add(e)}}function Dd(e){return t=>{de(t,dn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Er=/^[a-z]+(\.[a-z_]+)+$/,va=/^[a-z][a-z0-9-]{1,62}$/,un=e=>e.startsWith("file.");function Nd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!va.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!un(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);de(r.constructor,Me,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var ln=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ta=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function $r(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!Ta.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Ud(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=Tr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||$r(t.timeZone)!==void 0))throw new TypeError(`${n}: ${$r(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Ee))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Ee,{value:s,enumerable:!1}),se().add(a)}}var _r=["stripe","github","twilio","sendgrid","slack","discord","livekit"],$a=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ld(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!$a.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!_r.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${_r.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&_a(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Me)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}de(t,Be,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function _a(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Id(){return[...se()].filter(e=>D(e,qe)!==void 0)}function qd(e){return(D(e,He)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Pt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Fd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}var mn;function Ar(e){mn=e}function fn(){if(!mn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return mn}var Ea=720*3600;function Sa(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Ea))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function Aa(e){if(typeof e=="string")return e;let t=e[ke];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Wd=Rt("Tasks",{async enqueue(e,t,n={}){return Sa(n),fn().enqueue(Aa(e),t===void 0?null:t,n)},async cancel(e,t={}){return fn().cancel(e,t.machine)},async get(e,t={}){return fn().get(e,t.machine)}}),pn=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function xr(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await be.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return pn(a.data,a.status===200)},async cancel(n,r){return pn((await be.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return pn((await be.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var xa=1e4,Ra=36e5,Sr=24*36e5,Ct=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<Sr))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(xa*2**Math.min(t.attempt-1,16),Ra),_.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=Sr&&this.tasks.delete(s);n==="failed"&&_.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Mt="/_palbase/test-user-templates",Oa=/^[a-z][a-z0-9_-]{0,63}$/;function Zd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Oa.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,Te))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,Te,{value:r,enumerable:!1}),se().add(s)}}function Rr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Or(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ie&&n.status===404)return!1;throw n}}var Pa="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function Pr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,Pa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var hn=20;function Cr(e,t){let n=[...t].sort(),r=n.length===0?" none":`: ${n.slice(0,hn).join(", ")}${n.length>hn?` and ${n.length-hn} more`:""}`;return`This version has no test user template ${JSON.stringify(e.slice(0,64))} \u2014 it has${r}`}var gn="/_palbase/storage/upload/authorize",Mr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Ca=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fe(e){if(!Ca(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function jr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Dr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function jt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ma=/^[a-z][a-z0-9-]{1,62}$/,Nr=1024,ja=new Set(["userId","uploadId","filename"]);function tc(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);let r=n.bucket;if(typeof r!="string"||r==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Ma.test(r))throw new TypeError(`@Upload("${e}"): bucket "${r}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let s=Da(n.pathTemplate);if(s)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${s}`);let a={bucket:r,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(d,l,h)=>{if(typeof l!="string"||h===void 0||typeof h.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(d.constructor,He,()=>[]).push({method:"POST",subpath:e,fn:l,options:o,upload:a})}}function nc(){return pe("uploadedObject")}function Da(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!ja.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!Ur(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Ur(e){if(e===""||new TextEncoder().encode(e).byteLength>Nr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Na(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ua(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ua(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function Lr(e,t){let n=Na(e,t);return Ur(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Nr} bytes)`}}function Ir(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function qr(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Fe(t.user);if(!o)return"user is { id?, session?, role }";let d=jr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=La(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function La(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!wn(g)||!Object.values(g).every(b=>typeof b=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...g}}}import{markData as Ia}from"palgres";var je=Symbol.for("palbase.backend.gateway"),Je=Symbol.for("palbase.backend.gatewayHooks"),Hr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},qa={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(Hr),output:()=>structuredClone(Hr)}}},Jr=Symbol.for("palbase.backend.gatewayRefusal"),Br=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Jr,{value:!0})}},Ha=e=>typeof e=="object"&&e!==null&&e[Jr]===!0&&typeof e.reason=="string",We=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,bn=e=>({id:e.id??"",...e.session?{session:e.session}:{}}),Ba=6e4,Ga=86400,Gr=604800,zr=65536,Se=255,za=["roles:","flags:","messaging:","calls:","debug:"],Fa=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Ke=e=>new TextEncoder().encode(e).byteLength,kn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",$n=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Wa(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Ke(e)>Se)return`a channel is ${Se} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=za.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Vr(e){if(typeof e!="string"||e==="")return"is a name";if(Ke(e)>Se)return`is ${Se} bytes at most`}function dc(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Wa(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&$n(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Ka(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||Fa.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,b]of Object.entries(d)){let k=Vr(g);if(k)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${k}`);if(!kn(b))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=de(a,Je,_n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:qa}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ba,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&We(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!We(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);de(a,je,()=>h),se().add(a)}}function Ka(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ga;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Gr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Gr} (a week)`);return n}var _n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ja={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ja[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=de(n.constructor,Je,_n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var cc=ct("authorize"),uc=ct("first"),lc=ct("connect"),fc=ct("disconnect"),pc=ct("empty");function mc(e,t,n={}){let r=Vr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!kn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!kn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=de(s.constructor,Je,_n),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Va(e){return D(e,je)}function Za(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Zr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Ke(r)>Se?{problem:`a channel is ${Se} bytes at most`}:r}function Ya(e,t,n){let r=$n(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Zr(e,t):Qa(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Qa(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Xa=1e4,eo=1e3,to=100,En=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),we=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Fr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Wr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Yr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:v,instance:E}of e){let f=Va(v),T=a.get(f.name);if(T!==void 0&&T!==v)throw new TypeError(`@Gateway("${f.pattern}"): two gateways are named ${f.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(f.name,v);let R=s.get(Wr(f.pattern));if(R!==void 0)throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: ${n.get(R)?.cls.name}'s "${R}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Wr(f.pattern),f.pattern);for(let[G,z]of[...Object.entries(f.hooks),...Object.entries(f.messages).map(([I,N])=>[`message ${I}`,N.fn])])if(typeof E[z]!="function")throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: its ${G} is ${z}, which is no method of it`);let L={cls:v,instance:E,g:f};n.set(f.pattern,L),r.set(v,L)}let o=new Map,d=new Set,l=new Set,h=new Tn(t.broadcast),g=v=>{let E=o.get(v);return E||(E=new AbortController,o.set(v,E)),E},b=(v,E)=>{E?.abort(),o.get(v)===E&&o.delete(v)},k=(v,E,f,T,R,L)=>{if(!Object.hasOwn(v.g.events,f)){_.warn(`[palbase] ${R}: emit("${f}") is not sent \u2014 ${v.cls.name} declares no event "${f}" (static events)`);return}if(v.g.chat&&f==="chat"){_.warn(`[palbase] ${R}: emit("chat") is not sent \u2014 ${v.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:f,payload:T??{},...L!==void 0?{conn_id:L}:{}},R)},B=async(v,E,f)=>{if(typeof v!="object"||v===null||typeof v.pipe!="function")throw new TypeError(`${f}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await v.pipe(E)};function U(v,E,f,T,R,L,G){let z=T?.signal??AbortSignal.abort(),I=`${v.cls.name} (${E})`;return{channel:E,params:Object.freeze({...f}),signal:z,count:R,user:L,emit:(N,F)=>k(v,E,N,F,I,G),pipe:N=>B(N,E,I),owner:{hold(N){ne.exit(async()=>{try{await N(z)}catch(F){z.aborted||_.error(`[palbase] ${I}: a task owner.hold ran failed`,{error:F})}}).catch(()=>{})},release:()=>b(E,T)}}}function q(v){let{room:E,channel:f}=v;if(typeof E!="string"||typeof f!="string")return we(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!We(T.g)?we(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:f,params:Za(E,f)}}let K=(v,E)=>we(400,"bad_request",`"${E}" is not a channel of the gateway "${v}"`);async function J(v,E){let f=q(v);if("status"in f)return f;let{entry:T,channel:R,params:L}=f,G={status:200,body:{subscribe:!1,publish:!1}};if(!L)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${R}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),G;let z=Fe(v.user);if(!z?.id)return G;let I=z.id;if(T.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}};if(T.g.access==="owner")return L[$n(T.g.pattern)[0].slice(1,-1)]===I?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:G;let N=T.g.hooks.authorize;if(!N)return G;let F,Q;try{F=await t.run(z,`${T.cls.name}.${N}`,E,async()=>T.instance[N]({user:bn(z),params:Object.freeze({...L})})),Q=no(F)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return _.error(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) failed; the join is refused`,{error:te}),G}return Q==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) answered ${ro(F)}, which is no grant (true, { read, write } or null); the join is refused`),G):{status:200,body:Q}}async function le(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return K(f.entry.g.pattern,f.channel);let T=Fe(v.user);if(!T?.id||typeof v.event!="string")return we(400,"bad_request","A message names its member (user) and its event");let R=Object.hasOwn(f.entry.g.messages,v.event)?f.entry.g.messages[v.event]:void 0;if(!R)return{status:200,body:{ok:!1,reason:vn(`gateway "${f.channel}" takes no message "${v.event}"`,Dt)}};let L=await R.schema["~standard"].validate(Ia(v.payload??{}));if(L.issues)return{status:200,body:{ok:!1,reason:Kr(L.issues)}};let G=g(f.channel),z={...U(f.entry,f.channel,f.params,G,0,bn(T)),payload:L.value},I=`${f.entry.cls.name}.${R.fn} (@Subscribe "${v.event}" of ${f.channel})`,N;try{N=await t.run(T,`${f.entry.cls.name}.${R.fn}`,E,async()=>f.entry.instance[R.fn](z))}catch(Q){if(t.isOutage(Q))throw Q;return Ha(Q)?{status:200,body:{ok:!1,reason:vn(Q.reason,Dt)}}:(E?.aborted||_.error(`[palbase] ${I} failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(R.reply){let Q=await R.reply["~standard"].validate(N);if(Q.issues)return _.error(`[palbase] ${I} returned an ack its reply schema refuses (${Kr(Q.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=Q.value}let F;try{F=JSON.stringify(N)}catch(Q){return _.error(`[palbase] ${I} returned an ack that is not JSON; the member is told it failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return F===void 0?{status:200,body:{ok:!0}}:Ke(F)>zr?(_.error(`[palbase] ${I} returned an ack of ${Ke(F)} bytes, past ${zr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(F)}}}async function he(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return K(f.entry.g.pattern,f.channel);let T=v.event;if(typeof T!="string"||!Object.hasOwn(Fr,T))return we(400,"bad_request","A gateway's moment is first, join, leave or empty");let R=typeof v.count=="number"&&Number.isInteger(v.count)&&v.count>=0?v.count:void 0;if(R===void 0)return we(400,"bad_request","A gateway's moment says its count of members");let L=T==="join"||T==="leave",G=L?Fe(v.user):void 0,z=L?v.connId:void 0;if(L&&(!G?.id||typeof z!="string"||z===""))return we(400,"bad_request",`A ${T} names its member: user and connId`);let I=`${T}\0${f.channel}\0${typeof z=="string"?z:""}`;if(L&&d.has(I))return{status:204};if(l.has(I))return we(503,"in_progress","This moment of the gateway is being handled",5);l.add(I);try{let N=f.entry.g.hooks[Fr[T]],F;if(T==="empty"?(F=o.get(f.channel),b(f.channel,F)):F=T==="leave"?o.get(f.channel):g(f.channel),N){let Q=U(f.entry,f.channel,f.params,F,R,G?bn(G):{id:""},T==="join"?z:void 0);try{await t.run(G,`${f.entry.cls.name}.${N}`,E,async()=>f.entry.instance[N](Q))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||_.error(`[palbase] ${f.entry.cls.name}.${N} (${T} of ${f.channel}) failed; realtime tells it again`,{error:te}),we(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return L&&(d.add(I),d.size>Xa&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(I)}}function ge(v,E){let f=r.get(v),T=`Palbase.gateways.to(${v?.name??String(v)})`;if(!f)throw new TypeError(`${T}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let R=Zr(f.g.pattern,E??{});if(typeof R!="string")throw new TypeError(`${T}: ${R.problem}`);return{entry:f,channel:R,where:T}}return{declarations:[...n.values()].map(v=>v.g),async serve(v,E,f){return En(E)?v==="authorize"?J(E,f):v==="message"?le(E,f):v==="lifecycle"?he(E,f):we(404,"not_found",`No gateway call ${JSON.stringify(v)}`):we(400,"bad_request","A gateway's call is a JSON object")},emit(v,E,f,T){let{entry:R,channel:L,where:G}=ge(v,E);k(R,L,f,T,G)},async pipe(v,E,f){let{channel:T,where:R}=ge(v,E);await B(f,T,R)},async revalidate(v,E,f={}){let T=r.get(v),R=`Palbase.gateways.to(${v?.name??String(v)}).revalidate`;if(!T)throw new TypeError(`${R}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let L=Ya(T.g.pattern,E??{},f);if("problem"in L)throw new TypeError(`${R}: ${L.problem}`);let G=ne.getStore()?.saying;if(G){G.push(()=>{t.revalidate(L).catch(z=>_.warn(`[palbase] ${R}: realtime did not decide the channel again`,{error:z}))});return}await t.revalidate(L)},close(){for(let v of o.values())v.abort();o.clear()}}}function no(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!En(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function ro(e){return Array.isArray(e)?"an array":En(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var so=20,Dt=256;function Kr(e){let t="";for(let n of e.slice(0,so)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Dt)break}return vn(t,Dt)}function vn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var Tn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ke(t.event)>Se){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Se} bytes`);return}try{JSON.stringify(t.payload)}catch(s){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let r=ne.getStore()?.saying;r?r.push(()=>this.queue(t,n)):this.queue(t,n)}queue(t,n){let r=this.queues.get(t.topic);if(r){r.length>=eo?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,to);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as Sn,createHmac as ao,createPublicKey as ts,timingSafeEqual as oo,verify as ns}from"node:crypto";function wc(e){let t=D(e,Be);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function rs(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,Be),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,g=n[d.secret.env],b;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{b=io(d,g)}catch(U){a.push(`${h}: ${d.secret.env} ${U.message}`)}let k=t(o),B=new Map(d.events.map(({event:U,fn:q})=>[U,{name:`${o.name}.${q}`,call:(K,J)=>k[q](K,J)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:b,events:B})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
3
|
- ${a.join(`
|
|
4
|
-
- `)}`);return s}function
|
|
5
|
-
${o}`)}`}:{};return d?{type:
|
|
4
|
+
- `)}`);return s}function ss(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Ve=1024,Qr=1024*Ve;function io(e,t){if(e.signature)return De(void 0,e.signature.header,1/0,bo(e.signature,t));switch(e.provider){case"stripe":return De("stripe","stripe-signature",512*Ve,lo(t));case"github":return De("github","x-hub-signature-256",25*Qr,fo(t));case"slack":return De("slack","x-slack-signature",64*Ve,po(t));case"discord":return De("discord","x-signature-ed25519",64*Ve,mo(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Ve),check:go(t)};case"sendgrid":return De("sendgrid","x-twilio-email-event-webhook-signature",Qr,yo(t));case"livekit":return De("livekit","authorization",512*Ve,wo(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function De(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??as(e,s)}}function as(e,t){let n=An(t.body),r;try{r=JSON.parse(n)}catch{if(r=n,e==="slack"){let s=new URLSearchParams(n).get("payload");if(s!==null)try{r=JSON.parse(s)}catch{}}}return{type:os(e,t.headers,r),event:r,...co(e,t,r)}}function os(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=Ne(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=cs(n)?n.type:void 0;return r===1?"PING":r===2?"INTERACTION_CREATE":Number.isInteger(r)?`type_${String(r)}`:""}case"sendgrid":return"event_batch";case"twilio":return Ne(n,"EventType");case"livekit":return Ne(n,"event");default:return Ne(n,"type")}}function co(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(Ne(n,"id"));case"slack":return r(Ne(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${is(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>Ne(s,"sg_event_id")||void 0)}:{};default:return{}}}var uo=300;function lo(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let l of r.split(",")){let h=l.indexOf("=");if(h<=0)continue;let g=l.slice(0,h).trim(),b=l.slice(h+1).trim();if(g==="t"){if(s!==void 0)return"malformed_signature";s=b}else if(g==="v1"){let k=me(b,"hex");if(!k)return"malformed_signature";a.push(k)}}let o=ut(s);if(o===void 0||a.length===0)return"malformed_signature";if(lt(o,n))return"stale_timestamp";let d=Ze("sha256",e,`${s}.`,t.body);return a.some(l=>Ae(l,d))?void 0:"signature_mismatch"}}function fo(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?me(n.slice(7),"hex"):void 0;return r?Ae(r,Ze("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function po(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),a=ut(s),o=r.startsWith("v0=")?me(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":lt(a,n)?"stale_timestamp":Ae(o,Ze("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function mo(e){let t=me(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let n=ts({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let a=r.headers.get("x-signature-ed25519");if(!a)return"missing_signature";let o=r.headers.get("x-signature-timestamp")??void 0,d=ut(o),l=me(a,"hex");return d===void 0||!l||l.byteLength!==64?"malformed_signature":lt(d,s)?"stale_timestamp":ns(null,ds(o,r.body),n,l)?void 0:"signature_mismatch"}}var ho=1e3;function go(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=me(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let a=s.searchParams.get("bodySHA256"),o="",d;if(a!==null){if(!Ae(Buffer.from(a.toLowerCase()),Buffer.from(Sn("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let B=1;for(let K of t.body)if(K===38&&++B>ho)return"malformed_signature";let U=new Map;for(let[K,J]of new URLSearchParams(An(t.body))){let le=U.get(K);le||U.set(K,le=new Set),le.add(J)}let q=[];for(let K of[...U.keys()].sort()){let J=[...U.get(K)].sort();for(let le of J)o+=K+le;q.push([K,J.length===1?J[0]:J])}d=Object.fromEntries(q)}let l=s.protocol==="https:"?"443":"80",h=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,g=`${s.protocol}//${s.hostname}:${s.port||l}${s.pathname}${s.search}`;if(![h,g].some(B=>Ae(r,Ze("sha1",e,B,o))))return"signature_mismatch";let b=t.headers.get("i-twilio-idempotency-token"),k=b?{id:`${b}:${is(`${h}
|
|
5
|
+
${o}`)}`}:{};return d?{type:os("twilio",t.headers,d),event:d,...k}:{...as("twilio",t),...k}}}function yo(e){let t;try{let n=me(e,"base64");if(!n)throw new Error;t=ts({key:Buffer.from(n),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(n,r)=>{let s=n.headers.get("x-twilio-email-event-webhook-signature");if(!s)return"missing_signature";let a=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),o=ut(a),d=me(s.trim(),"base64");return o===void 0||!d?"malformed_signature":lt(o,r)?"stale_timestamp":ns("sha256",ds(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var Xr=60;function wo(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let a=es(me(s[0],"base64url")),o=me(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!Ae(o,Ze("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=es(me(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+Xr||typeof d.nbf=="number"&&n<d.nbf-Xr)return"stale_timestamp";let l=typeof d.sha256=="string"?me(d.sha256,"base64"):void 0;return l&&Ae(l,Sn("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function bo(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,a)=>{let o=s.headers.get(e.header);if(!o)return"missing_signature";if(e.prefix){if(!o.startsWith(e.prefix))return"malformed_signature";o=o.slice(e.prefix.length)}let d="";if(n.includes("{ts}")){d=s.headers.get(e.timestampHeader)?.trim()??"";let h=ut(d);if(h===void 0)return"malformed_signature";if(lt(h,a))return"stale_timestamp"}let l=me(o.trim(),e.encoding);return l?Ae(l,Ze(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var ko=new TextEncoder;function Ze(e,t,...n){let r=ao(e,t);for(let s of n)r.update(s);return r.digest()}function is(e){return Sn("sha256").update(e).digest("hex")}function ds(e,t){return Buffer.concat([ko.encode(e),t])}function Ae(e,t){return e.byteLength===t.byteLength&&oo(e,t)}var vo={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function me(e,t){return vo[t].test(e)?Buffer.from(e,t):void 0}function ut(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function lt(e,t){return Math.abs(t-e)>uo}function An(e){return new TextDecoder().decode(e)}function es(e){if(e)try{return JSON.parse(An(e))}catch{return}}function cs(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(e,t){let n=cs(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var Y=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
|
|
6
6
|
Kind: ${t}
|
|
7
7
|
Path: ${n.join(" -> ")}
|
|
8
8
|
At: ${r}
|
|
@@ -10,12 +10,12 @@ ${s}
|
|
|
10
10
|
|
|
11
11
|
Potential solutions:
|
|
12
12
|
${a.map(o=>` - ${o}`).join(`
|
|
13
|
-
`)}`),this.name="DiError",this.kind=t,this.path=n}},vo=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],To=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),Nt=class{owner=new Map;defs=new Map;instances=new Map;providers=new Set;order=[];controllers=[];eventProviders=[];webhooks=[];cronProviders=[];taskProviders=[];templateProviders=[];gateways=[];constructor(t){this.collect(t),this.validate()}collect(t){let n=(r,s)=>{if(this.defs.has(r))return;let a=D(r,dn);if(!a)throw new Y("unknown import",[...s,r.name],r.name,`${r.name} is not a @Module`,["decorate it with @Module({ \u2026 })","or list the module itself, not one of its classes"]);this.defs.set(r,a);for(let o of a.imports){if(o===r)throw new Y("unknown import",[r.name],r.name,`${r.name} imports itself`,["remove it from its own imports"]);n(o,[...s,r.name])}};for(let r of t)n(r,[]);for(let[r,s]of this.defs){for(let a of[...s.controllers,...s.providers]){let o=this.owner.get(a);if(o&&o!==r)throw new Y("duplicate ownership",[o.name,a.name,r.name],a.name,`${a.name} is listed by ${o.name} and by ${r.name}; a class has one owner`,["keep it in one module and export it from there"]);this.owner.set(a,r)}for(let a of s.providers)this.providers.add(a);for(let a of s.controllers){if(!D(a,qe))throw new Y("undeclared provider",[r.name,a.name],a.name,`${a.name} is in ${r.name}'s controllers but is not a @Controller`,["decorate it with @Controller(path)"]);if(D(a,Ee))throw new Y("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Cron: a cron is a provider's`,["give the cron a class of its own \u2014 @Cron({ name, schedule }) with run(meta) \u2014 listed in the module's providers"]);if(D(a,ke))throw new Y("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Task: a task is a provider's`,["give the task a class of its own \u2014 @Task({ name }) with run(payload, meta) \u2014 listed in the module's providers"]);if(D(a,Te))throw new Y("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @TestUserTemplate: a template is a provider's`,["give the template a class of its own \u2014 @TestUserTemplate({ name }) with seed(user, meta) \u2014 listed in the module's providers"]);if(D(a,je)||D(a,Je))throw new Y("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Gateway: a gateway is a provider's`,["give the gateway a class of its own, listed in the module's providers"]);this.controllers.push({cls:a,module:r})}}}validate(){for(let t of se())if(!this.owner.has(t))throw new Y("unowned class",[t.name],t.name,`${t.name} is declared but no module lists it: it would never be built`,["list it in a module's controllers or providers","or delete it"]);for(let[t,n]of this.defs){for(let r of n.exports)if(this.owner.get(r)!==t)throw new Y("unknown export",[t.name,r.name],t.name,`${t.name} exports ${r.name}, which it does not own`,[`list ${r.name} in ${t.name}'s providers`,"or export it from the module that owns it"]);for(let r of n.providers){if(D(r,Je)&&!D(r,je))throw new Y("undeclared provider",[t.name,r.name],r.name,`${r.name} has a gateway's methods (@Authorize, @OnFirst, @Subscribe\u2026) but is no @Gateway`,["decorate it with @Gateway(pattern, options)"]);if(!D(r,on)&&!D(r,Me)&&!D(r,je)&&!D(r,Ee)&&!D(r,ke)&&!D(r,Te)){let s=Reflect.getMetadata("design:paramtypes",r);throw r.length>0&&!s?new Y("metadata missing",[t.name,r.name],r.name,`${r.name} has constructor parameters but no emitted types`,["decorate it with @Injectable()","enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json"]):new Y("undeclared provider",[t.name,r.name],r.name,`${r.name} is in ${t.name}'s providers but is not @Injectable() (nor an @On handler, a @Gateway, a @Cron, a @Task or a @TestUserTemplate)`,["decorate it with @Injectable()"])}D(r,je)&&this.gateways.push(r),D(r,Be)?this.webhooks.push(r):D(r,Me)&&this.eventProviders.push(r),D(r,Ee)&&this.cronProviders.push(r),D(r,ke)&&this.taskProviders.push(r),D(r,Te)&&this.templateProviders.push(r)}}for(let t of this.owner.keys())for(let n of vo)if(typeof t.prototype[n]=="function")throw new Y("nest lifecycle name",[t.name],`${t.name}.${n}`,`${n} is NestJS's; it is never called here`,["use onStart() and onShutdown()"]);for(let t of this.owner.keys())this.resolve(t,[])}get(t){let n=this.instances.get(t);if(!n)throw new Error(`${t.name} is not built by this app`);return n}resolve(t,n){let r=this.instances.get(t);if(r)return r;if(n.includes(t.name))throw new Y("dependency cycle",[...n,t.name],t.name,`${[...n,t.name].join(" -> ")} goes round`,["move the shared part into a third class both depend on"]);let s=[...n,t.name],a=t.length,o=Reflect.getMetadata("design:paramtypes",t)??[];if(a>0&&o.length===0)throw new Y("metadata missing",s,t.name,`${t.name} takes ${a} constructor parameter(s) but no types were emitted`,["enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json","build with tsc, Bun or SWC (esbuild does not emit them)"]);let d=[];o.slice(0,a).forEach((h,g)=>{if(To.has(h)||typeof h!="function")throw new Y("unresolvable dependency",s,`${t.name} constructor parameter ${g}`,`parameter ${g} of ${t.name} is typed as ${h===void 0?"something with no runtime class":h.name} \u2014 an interface, union or primitive has no class to build`,["type it with the class itself"]);d.push(this.resolve(this.reachable(t,h,s),s))});let l=new t(...d);return this.instances.set(t,l),this.order.push(l),l}dependencyOf(t,n,r){let s=t;return this.resolve(this.reachable(s,n,[s.name,r]),[s.name,r])}provider(t,n){if(typeof t!="function")throw new TypeError(`${n}: inject takes a provider's class \u2014 it was given ${t===null?"null":typeof t}`);let r=t;if(!this.owner.has(r)&&![...this.owner.keys()].some(a=>a.prototype instanceof r))throw new Y("unowned class",[n,r.name],r.name,`${n} asks for ${r.name}, which no module provides: the app built none`,[`list ${r.name} in a module's providers`]);let s=this.target(r,[n]);if(!this.providers.has(s))throw new Y("undeclared provider",[n,s.name],s.name,`${s.name} is a controller: only a module's providers are given`,[`move what ${n} needs into a provider, listed in a module's providers`]);return this.get(s)}reachable(t,n,r){let s=this.owner.get(t),a=this.target(n,r),o=this.owner.get(a);if(o!==s){if(!this.defs.get(s).imports.includes(o))throw new Y("missing import",[...r,a.name],`${s.name}`,`${t.name} (in ${s.name}) needs ${a.name}, owned by ${o.name}, which ${s.name} does not import`,[`add ${o.name} to ${s.name}'s imports (imports are not transitive)`]);if(!this.defs.get(o).exports.includes(a))throw new Y("private dependency",[...r,a.name],`${o.name}`,`${a.name} is ${o.name}'s own: it is not in its exports`,[`add ${a.name} to ${o.name}'s exports`])}return a}target(t,n){if(this.owner.has(t))return t;let r=[...this.owner.keys()].filter(s=>s.prototype instanceof t);if(r.length===1)return r[0];throw r.length>1?new Y("duplicate ownership",[...n,t.name],t.name,`${t.name} has ${r.length} owned subclasses (${r.map(s=>s.name).join(", ")}): which one is meant cannot be told`,["ask for the subclass itself"]):new Y("unowned class",[...n,t.name],t.name,`${t.name} is needed but no module lists it`,[`list ${t.name} in a module's providers (and export it if another module needs it)`])}async start(){let t=[];for(let n of this.order){let r=n.onStart;if(typeof r=="function")try{await r.call(n)}catch(s){throw await this.shutdown(t),new Error(`[palbase] ${n.constructor.name}.onStart() failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}t.push(n)}}async shutdown(t=this.order){for(let n of[...t].reverse()){let r=n.onShutdown;if(typeof r=="function")try{await r.call(n)}catch(s){console.error(`[palbase] ${n.constructor.name}.onShutdown() failed`,s)}}}};import{HTTP_ERROR_BRAND as $o,HttpError as ft}from"palgres";import{z as xe}from"zod";import{BadRequest as xc,Conflict as Rc,DeadlockDetected as Oc,HttpError as Pc,NotFound as Cc,SerializationFailure as Mc,TooManyRequests as jc,UniqueViolation as Dc}from"palgres";function pt(e){if(typeof e!="object"||e===null||e[$o]!==!0)return!1;let t=e;return Number.isInteger(t.status)&&t.status>=400&&t.status<=599&&typeof t.error=="string"&&typeof t.errorDescription=="string"}var cs=class extends ft{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},us=class extends ft{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},ls=class extends ft{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function ps(e,t){let n={error:e.error,error_description:e.errorDescription,status:e.status,request_id:t};return e.data!==void 0&&(n.data=e.data),n}var _o=Symbol.for("palbase.backend.errorRegistry"),Eo={bad_request:xe.object({fields:xe.array(xe.object({field:xe.string(),message:xe.string()})),more:xe.number().int().optional()}),too_many_requests:xe.object({retryAfter:xe.number().int()})},So=new Set(["auth_unavailable","check_failed","client_closed_request","database_unavailable","duplicate_upload","email_not_verified","handler_failed","idempotency_key_in_use","idempotency_key_reused","in_progress","internal_error","invalid_idempotency_key","invalid_signature","invalid_token","job_failed","job_not_found","method_not_allowed","missing_signature","payload_too_large","service_unavailable","signature_mismatch","temporarily_unavailable","unknown_token","upload_required","webhook_secret_missing"]);function Ao(){let e=new Map;for(let[t,n,r]of[["bad_request",400,"BadRequest"],["unauthorized",401,"Unauthorized"],["forbidden",403,"Forbidden"],["not_found",404,"NotFound"],["conflict",409,"Conflict"],["unique_violation",409,"UniqueViolation"],["too_many_requests",429,"TooManyRequests"]]){let s=Eo[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function xo(){let e=globalThis;return e[_o]??=Ao()}var Ro=/^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;function Ec(e,t,n){if(typeof e!="string"||e.length>100||!Ro.test(e))throw new TypeError(`defineError(code, status): code is a wire code like room_locked or invite.notFound \u2014 a letter, then letters and digits in parts joined by . _ or - \u2014 not ${JSON.stringify(e)}`);if(!Number.isInteger(t)||t<400||t>599)throw new TypeError(`defineError("${e}", status): status is a 4xx or 5xx integer, not ${String(t)} \u2014 an error is never a success`);if(n!==void 0&&typeof n?.["~standard"]?.validate!="function")throw new TypeError(`defineError("${e}", ${t}, data): data is a Standard Schema (a zod, valibot or arktype schema)`);if(So.has(e))throw new TypeError(`defineError("${e}", ${t}): "${e}" is the framework's own answer \u2014 a client would read the framework's refusal as the project's error; give the project's its own code`);let r=xo(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&fs(s.data)!==fs(n)))throw new TypeError(`defineError("${e}", ${t}): "${e}" is already ${s.builtin?`the built-in ${s.className}`:`defined with status ${s.status}${s.status===t?" and other data":""}`} \u2014 a code is one error of the project's`);let a=e.split(/[._-]/).flatMap(k=>k.split(/(?=[A-Z])/)),o=a.map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(""),d=a.map(k=>k.toLowerCase()).join(" "),l=d.charAt(0).toUpperCase()+d.slice(1),b=n?(k=>class extends ft{static code=e;static status=t;constructor(B,U){let q=Oo(e,k,B);super(t,e,U??(typeof q=="string"?q:l),q),this.name=o}})(n):class extends ft{static code=e;static status=t;constructor(k){super(t,e,k??l),this.name=o}};return Object.defineProperty(b,"name",{value:o}),r.set(e,{code:e,status:t,className:o,builtin:!1,...n?{data:n}:{}}),b}function Oo(e,t,n){let r=t["~standard"].validate(n);if(r instanceof Promise)throw new TypeError(`${e}: its data schema validates asynchronously; an error is made at once`);if(r.issues)throw new TypeError(`${e}: its data does not fit its schema \u2014 ${r.issues.map(s=>s.message).join("; ")}`);return r.value}function fs(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}import{markData as Po}from"palgres";var ms="/_palbase/ai/tools",hs="/_palbase/ai/agents",Ye=4<<20,Co=Symbol.for("palbase.ai.tool_error");function An(e){return e instanceof Error&&e[Co]===!0}var Mo=/^[A-Za-z0-9_.:-]{1,160}$/;function gs(e){if(!An(e))return;let t=e.workspaceTree;if(!Re(t))return;let n={};return typeof t.manifestId=="string"&&Mo.test(t.manifestId)&&(n.manifest_id=t.manifestId),Number.isSafeInteger(t.seq)&&t.seq>=1&&(n.seq=t.seq),n.manifest_id===void 0&&n.seq===void 0?void 0:n}var jo=Symbol.for("palbase.ai.declared");function ys(){let e=globalThis[jo];if(!e)return{tools:new Map,clientTools:new Map,agents:new Map};let t=new Set(e.twice);for(let n of e.clientTools?.keys()??[])e.tools.has(n)&&t.add(`tool:${n}`);if(t.size>0){let n=[...t].map(r=>r.replace(":"," "));throw new TypeError(`[palbase] ${n.join(", ")}: declared twice with different values \u2014 an ai.tool's, an ai.clientTool's and an ai.agent's name is its own (an agent is given one tool of a name, and the build's contract names it once); make each once, at a module's top level`)}return{tools:new Map(e.tools),clientTools:new Map(e.clientTools??[]),agents:new Map(e.agents)}}var Re=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ws(e){let t={};if(e==null)return t;if(Re(e)){for(let[n,r]of Object.entries(e)){if(typeof r!="string")return;Object.defineProperty(t,n,{value:r,enumerable:!0,writable:!0,configurable:!0})}return t}}function bs(e){if(!Re(e))return"context is {chat_id, agent, user, metadata}";if(typeof e.chat_id!="string")return"context.chat_id is the chat (empty for a one-shot answer's call)";if(typeof e.agent!="string")return"context.agent is the agent's name";let t=null;if(e.user!==null&&e.user!==void 0){if(!Re(e.user)||typeof e.user.id!="string"||e.user.id===""||e.user.name!==void 0&&typeof e.user.name!="string")return"context.user is {id, name}, or null";t={id:e.user.id,name:typeof e.user.name=="string"?e.user.name:""}}let n=ws(e.metadata);return n===void 0?"context.metadata is an object of strings":{chatId:e.chat_id,agent:e.agent,user:t,metadata:n}}function ks(e){let t=bs(e);if(typeof t=="string")return t;let n=e;if(typeof n.turn_id!="string"||typeof n.run_id!="string")return"context.turn_id and context.run_id are the turn the call is made in and the run that made it";if(n.subagent!==null&&typeof n.subagent!="string")return"context.subagent is the subagent that made the call, or null";let r={...t,turnId:n.turn_id,runId:n.run_id,subagent:n.subagent};if(n.workspace!==void 0&&n.workspace!==null){let s=n.workspace;if(!Re(s)||typeof s.chat_id!="string"||s.chat_id===""||s.manifest_id!==void 0&&typeof s.manifest_id!="string"||s.seq!==void 0&&(!Number.isSafeInteger(s.seq)||s.seq<0))return"context.workspace is {chat_id, manifest_id, seq}: the tree of the chat's workspace the call is made at";r.workspace={chatId:s.chat_id,...typeof s.manifest_id=="string"&&s.manifest_id!==""?{manifestId:s.manifest_id}:{},...typeof s.seq=="number"&&s.seq>0?{seq:s.seq}:{}}}return r}function vs(e){let t=bs(e);if(typeof t=="string")return t;let n=e,r=null;if(n.message!==null){let a=n.message,o=Re(a)?ws(a.metadata):void 0;if(!Re(a)||typeof a.id!="string"||typeof a.client_id!="string"||a.author!==null&&typeof a.author!="string"||typeof a.author_name!="string"||typeof a.text!="string"||typeof a.delivery!="string"||o===void 0)return"message is {id, client_id, author, author_name, text, delivery, metadata}, or null";r={id:a.id,clientId:a.client_id,author:a.author,authorName:a.author_name,text:a.text,delivery:a.delivery,metadata:Po(o)}}let s=null;if(n.goal!==void 0&&n.goal!==null){if(!Re(n.goal)||typeof n.goal.objective!="string"||typeof n.goal.rubric!="string")return"goal is {objective, rubric}";s={objective:n.goal.objective,rubric:n.goal.rubric}}return{...t,message:r,goal:s}}var Do=1e3,No=256*1024,Ut=class{answers=new Map;running=new Set;answered(t){return this.answers.get(t)}isRunning(t){return this.running.has(t)}start(t){this.running.add(t)}end(t,n){this.running.delete(t),!(n===void 0||n.answer.length>No)&&(this.answers.set(t,n),this.answers.size>Do&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as ra,isEngineRaised as Wn,markData as ue}from"palgres";import{createHash as sa}from"node:crypto";import{createHash as Uo,randomInt as Lo}from"node:crypto";import{ago as xn,isRetryable as Io,now as Ts}from"palgres";import{defineSchema as qo,defineTable as Ho,index as Bo,integer as zo,jsonb as Go,raw as Fo,text as Rn,timestamp as $s}from"palgres/dsl";var Ps=new Set(["POST","PUT","PATCH","DELETE"]),_s=255,Es=35,Ss=24,As=65536,xs=1e3,Wo=64,Cn={description:"Makes the write safe to send again (at most 255 characters). A retry with the same key and the same request gets the first answer back, marked `Idempotent-Replayed: true`, and changes nothing; the same key with a different request is refused with 422, and while the first request still runs a retry gets 409 with Retry-After. Answers are kept for 24 hours.",in:"header",name:"Idempotency-Key",required:!1,schema:{maxLength:255,type:"string"}},Ko=Ho("idempotency_keys",{columns:{key:Rn().primaryKey(),fingerprint:Rn(),started_at:$s().defaultNow(),completed_at:$s().nullable(),status_code:zo().nullable(),response_headers:Go().nullable(),response_body:Rn().nullable()},indexes:e=>[Bo("idempotency_keys_started").on(e.col("started_at"))]}),Gc=qo("palbase",{tables:[Ko],raw:[Fo("idempotency_answer",`CREATE OR REPLACE FUNCTION palbase.idempotency_answer(record_key text, claimed_at timestamptz, answer_status integer, answer_headers jsonb, answer_body text) RETURNS boolean
|
|
13
|
+
`)}`),this.name="DiError",this.kind=t,this.path=n}},To=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],$o=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),Nt=class{owner=new Map;defs=new Map;instances=new Map;providers=new Set;order=[];controllers=[];eventProviders=[];webhooks=[];cronProviders=[];taskProviders=[];templateProviders=[];gateways=[];constructor(t){this.collect(t),this.validate()}collect(t){let n=(r,s)=>{if(this.defs.has(r))return;let a=D(r,dn);if(!a)throw new Y("unknown import",[...s,r.name],r.name,`${r.name} is not a @Module`,["decorate it with @Module({ \u2026 })","or list the module itself, not one of its classes"]);this.defs.set(r,a);for(let o of a.imports){if(o===r)throw new Y("unknown import",[r.name],r.name,`${r.name} imports itself`,["remove it from its own imports"]);n(o,[...s,r.name])}};for(let r of t)n(r,[]);for(let[r,s]of this.defs){for(let a of[...s.controllers,...s.providers]){let o=this.owner.get(a);if(o&&o!==r)throw new Y("duplicate ownership",[o.name,a.name,r.name],a.name,`${a.name} is listed by ${o.name} and by ${r.name}; a class has one owner`,["keep it in one module and export it from there"]);this.owner.set(a,r)}for(let a of s.providers)this.providers.add(a);for(let a of s.controllers){if(!D(a,qe))throw new Y("undeclared provider",[r.name,a.name],a.name,`${a.name} is in ${r.name}'s controllers but is not a @Controller`,["decorate it with @Controller(path)"]);if(D(a,Ee))throw new Y("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Cron: a cron is a provider's`,["give the cron a class of its own \u2014 @Cron({ name, schedule }) with run(meta) \u2014 listed in the module's providers"]);if(D(a,ke))throw new Y("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Task: a task is a provider's`,["give the task a class of its own \u2014 @Task({ name }) with run(payload, meta) \u2014 listed in the module's providers"]);if(D(a,Te))throw new Y("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @TestUserTemplate: a template is a provider's`,["give the template a class of its own \u2014 @TestUserTemplate({ name }) with seed(user, meta) \u2014 listed in the module's providers"]);if(D(a,je)||D(a,Je))throw new Y("undeclared provider",[r.name,a.name],a.name,`${a.name} is a controller and a @Gateway: a gateway is a provider's`,["give the gateway a class of its own, listed in the module's providers"]);this.controllers.push({cls:a,module:r})}}}validate(){for(let t of se())if(!this.owner.has(t))throw new Y("unowned class",[t.name],t.name,`${t.name} is declared but no module lists it: it would never be built`,["list it in a module's controllers or providers","or delete it"]);for(let[t,n]of this.defs){for(let r of n.exports)if(this.owner.get(r)!==t)throw new Y("unknown export",[t.name,r.name],t.name,`${t.name} exports ${r.name}, which it does not own`,[`list ${r.name} in ${t.name}'s providers`,"or export it from the module that owns it"]);for(let r of n.providers){if(D(r,Je)&&!D(r,je))throw new Y("undeclared provider",[t.name,r.name],r.name,`${r.name} has a gateway's methods (@Authorize, @OnFirst, @Subscribe\u2026) but is no @Gateway`,["decorate it with @Gateway(pattern, options)"]);if(!D(r,on)&&!D(r,Me)&&!D(r,je)&&!D(r,Ee)&&!D(r,ke)&&!D(r,Te)){let s=Reflect.getMetadata("design:paramtypes",r);throw r.length>0&&!s?new Y("metadata missing",[t.name,r.name],r.name,`${r.name} has constructor parameters but no emitted types`,["decorate it with @Injectable()","enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json"]):new Y("undeclared provider",[t.name,r.name],r.name,`${r.name} is in ${t.name}'s providers but is not @Injectable() (nor an @On handler, a @Gateway, a @Cron, a @Task or a @TestUserTemplate)`,["decorate it with @Injectable()"])}D(r,je)&&this.gateways.push(r),D(r,Be)?this.webhooks.push(r):D(r,Me)&&this.eventProviders.push(r),D(r,Ee)&&this.cronProviders.push(r),D(r,ke)&&this.taskProviders.push(r),D(r,Te)&&this.templateProviders.push(r)}}for(let t of this.owner.keys())for(let n of To)if(typeof t.prototype[n]=="function")throw new Y("nest lifecycle name",[t.name],`${t.name}.${n}`,`${n} is NestJS's; it is never called here`,["use onStart() and onShutdown()"]);for(let t of this.owner.keys())this.resolve(t,[])}get(t){let n=this.instances.get(t);if(!n)throw new Error(`${t.name} is not built by this app`);return n}resolve(t,n){let r=this.instances.get(t);if(r)return r;if(n.includes(t.name))throw new Y("dependency cycle",[...n,t.name],t.name,`${[...n,t.name].join(" -> ")} goes round`,["move the shared part into a third class both depend on"]);let s=[...n,t.name],a=t.length,o=Reflect.getMetadata("design:paramtypes",t)??[];if(a>0&&o.length===0)throw new Y("metadata missing",s,t.name,`${t.name} takes ${a} constructor parameter(s) but no types were emitted`,["enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json","build with tsc, Bun or SWC (esbuild does not emit them)"]);let d=[];o.slice(0,a).forEach((h,g)=>{if($o.has(h)||typeof h!="function")throw new Y("unresolvable dependency",s,`${t.name} constructor parameter ${g}`,`parameter ${g} of ${t.name} is typed as ${h===void 0?"something with no runtime class":h.name} \u2014 an interface, union or primitive has no class to build`,["type it with the class itself"]);d.push(this.resolve(this.reachable(t,h,s),s))});let l=new t(...d);return this.instances.set(t,l),this.order.push(l),l}dependencyOf(t,n,r){let s=t;return this.resolve(this.reachable(s,n,[s.name,r]),[s.name,r])}provider(t,n){if(typeof t!="function")throw new TypeError(`${n}: inject takes a provider's class \u2014 it was given ${t===null?"null":typeof t}`);let r=t;if(!this.owner.has(r)&&![...this.owner.keys()].some(a=>a.prototype instanceof r))throw new Y("unowned class",[n,r.name],r.name,`${n} asks for ${r.name}, which no module provides: the app built none`,[`list ${r.name} in a module's providers`]);let s=this.target(r,[n]);if(!this.providers.has(s))throw new Y("undeclared provider",[n,s.name],s.name,`${s.name} is a controller: only a module's providers are given`,[`move what ${n} needs into a provider, listed in a module's providers`]);return this.get(s)}reachable(t,n,r){let s=this.owner.get(t),a=this.target(n,r),o=this.owner.get(a);if(o!==s){if(!this.defs.get(s).imports.includes(o))throw new Y("missing import",[...r,a.name],`${s.name}`,`${t.name} (in ${s.name}) needs ${a.name}, owned by ${o.name}, which ${s.name} does not import`,[`add ${o.name} to ${s.name}'s imports (imports are not transitive)`]);if(!this.defs.get(o).exports.includes(a))throw new Y("private dependency",[...r,a.name],`${o.name}`,`${a.name} is ${o.name}'s own: it is not in its exports`,[`add ${a.name} to ${o.name}'s exports`])}return a}target(t,n){if(this.owner.has(t))return t;let r=[...this.owner.keys()].filter(s=>s.prototype instanceof t);if(r.length===1)return r[0];throw r.length>1?new Y("duplicate ownership",[...n,t.name],t.name,`${t.name} has ${r.length} owned subclasses (${r.map(s=>s.name).join(", ")}): which one is meant cannot be told`,["ask for the subclass itself"]):new Y("unowned class",[...n,t.name],t.name,`${t.name} is needed but no module lists it`,[`list ${t.name} in a module's providers (and export it if another module needs it)`])}async start(){let t=[];for(let n of this.order){let r=n.onStart;if(typeof r=="function")try{await r.call(n)}catch(s){throw await this.shutdown(t),new Error(`[palbase] ${n.constructor.name}.onStart() failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}t.push(n)}}async shutdown(t=this.order){for(let n of[...t].reverse()){let r=n.onShutdown;if(typeof r=="function")try{await r.call(n)}catch(s){console.error(`[palbase] ${n.constructor.name}.onShutdown() failed`,s)}}}};import{HTTP_ERROR_BRAND as _o,HttpError as ft}from"palgres";import{z as xe}from"zod";import{BadRequest as Rc,Conflict as Oc,DeadlockDetected as Pc,HttpError as Cc,NotFound as Mc,SerializationFailure as jc,TooManyRequests as Dc,UniqueViolation as Nc}from"palgres";function pt(e){if(typeof e!="object"||e===null||e[_o]!==!0)return!1;let t=e;return Number.isInteger(t.status)&&t.status>=400&&t.status<=599&&typeof t.error=="string"&&typeof t.errorDescription=="string"}var us=class extends ft{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},ls=class extends ft{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},fs=class extends ft{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function ms(e,t){let n={error:e.error,error_description:e.errorDescription,status:e.status,request_id:t};return e.data!==void 0&&(n.data=e.data),n}var Eo=Symbol.for("palbase.backend.errorRegistry"),So={bad_request:xe.object({fields:xe.array(xe.object({field:xe.string(),message:xe.string()})),more:xe.number().int().optional()}),too_many_requests:xe.object({retryAfter:xe.number().int()})},Ao=new Set(["auth_unavailable","check_failed","client_closed_request","database_unavailable","duplicate_upload","email_not_verified","handler_failed","idempotency_key_in_use","idempotency_key_reused","in_progress","internal_error","invalid_idempotency_key","invalid_signature","invalid_token","job_failed","job_not_found","method_not_allowed","missing_signature","payload_too_large","service_unavailable","signature_mismatch","temporarily_unavailable","unknown_token","upload_required","webhook_secret_missing"]);function xo(){let e=new Map;for(let[t,n,r]of[["bad_request",400,"BadRequest"],["unauthorized",401,"Unauthorized"],["forbidden",403,"Forbidden"],["not_found",404,"NotFound"],["conflict",409,"Conflict"],["unique_violation",409,"UniqueViolation"],["too_many_requests",429,"TooManyRequests"]]){let s=So[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function Ro(){let e=globalThis;return e[Eo]??=xo()}var Oo=/^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;function Sc(e,t,n){if(typeof e!="string"||e.length>100||!Oo.test(e))throw new TypeError(`defineError(code, status): code is a wire code like room_locked or invite.notFound \u2014 a letter, then letters and digits in parts joined by . _ or - \u2014 not ${JSON.stringify(e)}`);if(!Number.isInteger(t)||t<400||t>599)throw new TypeError(`defineError("${e}", status): status is a 4xx or 5xx integer, not ${String(t)} \u2014 an error is never a success`);if(n!==void 0&&typeof n?.["~standard"]?.validate!="function")throw new TypeError(`defineError("${e}", ${t}, data): data is a Standard Schema (a zod, valibot or arktype schema)`);if(Ao.has(e))throw new TypeError(`defineError("${e}", ${t}): "${e}" is the framework's own answer \u2014 a client would read the framework's refusal as the project's error; give the project's its own code`);let r=Ro(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&ps(s.data)!==ps(n)))throw new TypeError(`defineError("${e}", ${t}): "${e}" is already ${s.builtin?`the built-in ${s.className}`:`defined with status ${s.status}${s.status===t?" and other data":""}`} \u2014 a code is one error of the project's`);let a=e.split(/[._-]/).flatMap(k=>k.split(/(?=[A-Z])/)),o=a.map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(""),d=a.map(k=>k.toLowerCase()).join(" "),l=d.charAt(0).toUpperCase()+d.slice(1),b=n?(k=>class extends ft{static code=e;static status=t;constructor(B,U){let q=Po(e,k,B);super(t,e,U??(typeof q=="string"?q:l),q),this.name=o}})(n):class extends ft{static code=e;static status=t;constructor(k){super(t,e,k??l),this.name=o}};return Object.defineProperty(b,"name",{value:o}),r.set(e,{code:e,status:t,className:o,builtin:!1,...n?{data:n}:{}}),b}function Po(e,t,n){let r=t["~standard"].validate(n);if(r instanceof Promise)throw new TypeError(`${e}: its data schema validates asynchronously; an error is made at once`);if(r.issues)throw new TypeError(`${e}: its data does not fit its schema \u2014 ${r.issues.map(s=>s.message).join("; ")}`);return r.value}function ps(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}import{markData as Co}from"palgres";var hs="/_palbase/ai/tools",gs="/_palbase/ai/agents",Ye=4<<20,Mo=Symbol.for("palbase.ai.tool_error");function xn(e){return e instanceof Error&&e[Mo]===!0}var jo=/^[A-Za-z0-9_.:-]{1,160}$/;function ys(e){if(!xn(e))return;let t=e.workspaceTree;if(!Re(t))return;let n={};return typeof t.manifestId=="string"&&jo.test(t.manifestId)&&(n.manifest_id=t.manifestId),Number.isSafeInteger(t.seq)&&t.seq>=1&&(n.seq=t.seq),n.manifest_id===void 0&&n.seq===void 0?void 0:n}var Do=Symbol.for("palbase.ai.declared");function ws(){let e=globalThis[Do];if(!e)return{tools:new Map,clientTools:new Map,agents:new Map};let t=new Set(e.twice);for(let n of e.clientTools?.keys()??[])e.tools.has(n)&&t.add(`tool:${n}`);if(t.size>0){let n=[...t].map(r=>r.replace(":"," "));throw new TypeError(`[palbase] ${n.join(", ")}: declared twice with different values \u2014 an ai.tool's, an ai.clientTool's and an ai.agent's name is its own (an agent is given one tool of a name, and the build's contract names it once); make each once, at a module's top level`)}return{tools:new Map(e.tools),clientTools:new Map(e.clientTools??[]),agents:new Map(e.agents)}}var Re=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function bs(e){let t={};if(e==null)return t;if(Re(e)){for(let[n,r]of Object.entries(e)){if(typeof r!="string")return;Object.defineProperty(t,n,{value:r,enumerable:!0,writable:!0,configurable:!0})}return t}}function ks(e){if(!Re(e))return"context is {chat_id, agent, user, metadata}";if(typeof e.chat_id!="string")return"context.chat_id is the chat (empty for a one-shot answer's call)";if(typeof e.agent!="string")return"context.agent is the agent's name";let t=null;if(e.user!==null&&e.user!==void 0){if(!Re(e.user)||typeof e.user.id!="string"||e.user.id===""||e.user.name!==void 0&&typeof e.user.name!="string")return"context.user is {id, name}, or null";t={id:e.user.id,name:typeof e.user.name=="string"?e.user.name:""}}let n=bs(e.metadata);return n===void 0?"context.metadata is an object of strings":{chatId:e.chat_id,agent:e.agent,user:t,metadata:n}}function vs(e){let t=ks(e);if(typeof t=="string")return t;let n=e;if(typeof n.turn_id!="string"||typeof n.run_id!="string")return"context.turn_id and context.run_id are the turn the call is made in and the run that made it";if(n.subagent!==null&&typeof n.subagent!="string")return"context.subagent is the subagent that made the call, or null";let r={...t,turnId:n.turn_id,runId:n.run_id,subagent:n.subagent};if(n.workspace!==void 0&&n.workspace!==null){let s=n.workspace;if(!Re(s)||typeof s.chat_id!="string"||s.chat_id===""||s.manifest_id!==void 0&&typeof s.manifest_id!="string"||s.seq!==void 0&&(!Number.isSafeInteger(s.seq)||s.seq<0))return"context.workspace is {chat_id, manifest_id, seq}: the tree of the chat's workspace the call is made at";r.workspace={chatId:s.chat_id,...typeof s.manifest_id=="string"&&s.manifest_id!==""?{manifestId:s.manifest_id}:{},...typeof s.seq=="number"&&s.seq>0?{seq:s.seq}:{}}}return r}function Ts(e){let t=ks(e);if(typeof t=="string")return t;let n=e,r=null;if(n.message!==null){let a=n.message,o=Re(a)?bs(a.metadata):void 0;if(!Re(a)||typeof a.id!="string"||typeof a.client_id!="string"||a.author!==null&&typeof a.author!="string"||typeof a.author_name!="string"||typeof a.text!="string"||typeof a.delivery!="string"||o===void 0)return"message is {id, client_id, author, author_name, text, delivery, metadata}, or null";r={id:a.id,clientId:a.client_id,author:a.author,authorName:a.author_name,text:a.text,delivery:a.delivery,metadata:Co(o)}}let s=null;if(n.goal!==void 0&&n.goal!==null){if(!Re(n.goal)||typeof n.goal.objective!="string"||typeof n.goal.rubric!="string")return"goal is {objective, rubric}";s={objective:n.goal.objective,rubric:n.goal.rubric}}return{...t,message:r,goal:s}}var No=1e3,Uo=256*1024,Ut=class{answers=new Map;running=new Set;answered(t){return this.answers.get(t)}isRunning(t){return this.running.has(t)}start(t){this.running.add(t)}end(t,n){this.running.delete(t),!(n===void 0||n.answer.length>Uo)&&(this.answers.set(t,n),this.answers.size>No&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as sa,isEngineRaised as Kn,markData as ue}from"palgres";import{createHash as aa}from"node:crypto";import{createHash as Lo,randomInt as Io}from"node:crypto";import{ago as Rn,isRetryable as qo,now as $s}from"palgres";import{defineSchema as Ho,defineTable as Bo,index as Go,integer as zo,jsonb as Fo,raw as Wo,text as On,timestamp as _s}from"palgres/dsl";var Cs=new Set(["POST","PUT","PATCH","DELETE"]),Es=255,Ss=35,As=24,xs=65536,Rs=1e3,Ko=64,Mn={description:"Makes the write safe to send again (at most 255 characters). A retry with the same key and the same request gets the first answer back, marked `Idempotent-Replayed: true`, and changes nothing; the same key with a different request is refused with 422, and while the first request still runs a retry gets 409 with Retry-After. Answers are kept for 24 hours.",in:"header",name:"Idempotency-Key",required:!1,schema:{maxLength:255,type:"string"}},Jo=Bo("idempotency_keys",{columns:{key:On().primaryKey(),fingerprint:On(),started_at:_s().defaultNow(),completed_at:_s().nullable(),status_code:zo().nullable(),response_headers:Fo().nullable(),response_body:On().nullable()},indexes:e=>[Go("idempotency_keys_started").on(e.col("started_at"))]}),Fc=Ho("palbase",{tables:[Jo],raw:[Wo("idempotency_answer",`CREATE OR REPLACE FUNCTION palbase.idempotency_answer(record_key text, claimed_at timestamptz, answer_status integer, answer_headers jsonb, answer_body text) RETURNS boolean
|
|
14
14
|
LANGUAGE sql VOLATILE SECURITY DEFINER SET search_path = pg_catalog, pg_temp
|
|
15
15
|
AS $answer$
|
|
16
16
|
UPDATE palbase.idempotency_keys
|
|
17
17
|
SET completed_at = now(), status_code = answer_status, response_headers = answer_headers, response_body = answer_body
|
|
18
18
|
WHERE key = record_key AND started_at = claimed_at AND completed_at IS NULL
|
|
19
19
|
RETURNING true
|
|
20
|
-
$answer$`,{drop:"DROP FUNCTION IF EXISTS palbase.idempotency_answer(text, timestamptz, integer, jsonb, text)"})]}),Jo={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},Vo={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},Zo={status:409,code:"idempotency_key_in_use",message:"This request's Idempotency-Key was taken over by a retry; what it did is not kept",retryAfter:1},Rs={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},It=class extends Error{};function mt(e){return Ps.has(e.method)&&e.meta.upload===void 0}function Cs(e,t){if(!Ps.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function Yo(e,t){return Ms([e.role,e.uid,t]).digest("hex")}function Qo(e){return Ms([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function Ms(e){let t=Uo("sha256");for(let n of e)t.update(n).update("\0");return t}function Xo(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function On(e){return e<500&&e!==429&&e!==499}function ei(e,t){return t&&On(e)}function js(e){let t=e["~standard"].jsonSchema?.input,n;try{n=t?.({target:"draft-2020-12"})}catch{return!1}let r=n?.properties;return typeof r=="object"&&r!==null&&Object.keys(r).some(s=>s.toLowerCase()==="idempotency-key")}var ti={role:"service",claims:{}},ni={seal:e=>e,open:async e=>e},qt=class{db;answers;constructor(t,n=ni){this.db=t,this.answers=n}async serve(t,n,r){if(t.key.length>_s)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${_s} characters`});let s;try{s=await this.begin(Yo(t.caller,t.key),Qo(t))}catch(d){return _.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:d}),r.refusal(Rs)}if("kept"in s){let d;try{d=s.kept.body===null?null:await this.answers.open(s.kept.body)}catch(l){return _.warn("[palbase] the answer kept against an Idempotency-Key could not be opened; the write is not run again",{error:l}),r.refusal(Rs)}return ri({...s.kept,body:d},r.requestId)}if("refused"in s)return r.refusal(s.refused==="reused"?Jo:Vo);let a=s.claim,o;try{o=await n(d=>this.record(a,d))}catch(d){if(d instanceof It)return r.refusal(Zo);let l=r.failure(d);return ei(l.status,r.ran())&&!Io(d)?this.keep(a,l):(await this.release(a),l)}return On(o.status)||await this.release(a),o}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:xn({hours:Ss})}}}))}async begin(t,n){return Lo(Wo)===0&&await this.sweep().catch(r=>_.warn("[palbase] the expired Idempotency-Keys could not be taken away; the next sweep tries again",{error:r})),this.asService(async r=>{for(let s=0;s<3;s++){let[a]=await r.insertMany([{key:t,fingerprint:n}],{onConflict:["key"],action:"ignore"});if(a)return{claim:{key:t,started:a.started_at}};if(await r.deleteMany({where:{key:t,started_at:{lt:xn({hours:Ss})}}})>0)continue;let o=await r.findUnique({where:{key:t}});if(o===null)continue;let d=Xo(o,n);if(d==="reused")return{refused:"reused"};if(d==="replay")return{kept:{status:o.status_code,headers:o.response_headers??[],body:o.response_body}};let[l]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:xn({seconds:Es})}},set:{started_at:Ts()}});return l?{claim:{key:t,started:l.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!On(n.status))return n;let{response:r,kept:s}=await Os(n),a=ne.getStore()?.database;if(!a)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let o=s.body===null?null:this.answers.seal(s.body),[d]=await a.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,s.status,JSON.stringify(s.headers),o]);if(d?.answered!==!0)throw new It;return r}async keep(t,n){let{response:r,kept:s}=await Os(n);try{await this.asService(a=>a.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:Ts(),status_code:s.status,response_headers:s.headers,response_body:s.body===null?null:this.answers.seal(s.body)}}))}catch(a){_.warn("[palbase] a refusal could not be kept against its Idempotency-Key; a retry runs it again once the key is stale",{error:a})}return r}async release(t){if(await this.releaseOnce(t))return;let n=Date.now()+Es*1e3,r=()=>{Date.now()+xs>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},xs).unref()};r()}async releaseOnce(t){try{return await this.asService(n=>n.deleteMany({where:{key:t.key,started_at:t.started,completed_at:null}})),!0}catch{return!1}}async asService(t){let n=this.db.request(ti),r;try{r=await t(n.database.palbase.idempotency_keys)}catch(s){throw await n.rollback(s).catch(()=>{}),s}try{await n.commit()}catch(s){throw await n.rollback(s).catch(()=>{}),s}return r}};function ri(e,t){let n=new Headers(e.headers);return n.set("x-request-id",t),n.set("idempotent-replayed","true"),new Response(e.body===null?null:Buffer.from(e.body,"base64"),{status:e.status,headers:n})}var Lt=Symbol("waits"),Pn=new WeakMap;function Ht(e,t){return Pn.set(e,t),e}async function si(e){for(let t=0;t<e;t++)await Promise.resolve();return Lt}function ai(e){return Promise.race([e,si(8)])}async function Os(e){let t=[];e.headers.forEach((d,l)=>{l!=="x-request-id"&&t.push([l,d])});let n=d=>new Response(d,{status:e.status,statusText:e.statusText,headers:e.headers});if(Pn.has(e)){let d=Pn.get(e)??null;if(d===null||d.byteLength===0)return{response:n(d===null?null:Buffer.from(d)),kept:{status:e.status,headers:t,body:null}};let l=Buffer.from(d);return l.byteLength>As?{response:n(l),kept:{status:e.status,headers:t.filter(([h])=>h!=="content-length"&&h!=="content-encoding"),body:null}}:{response:n(l),kept:{status:e.status,headers:t,body:l.toString("base64")}}}if(e.body===null)return{response:n(null),kept:{status:e.status,headers:t,body:null}};let r=e.body.getReader(),s=[],a=0;for(;;){let d=r.read(),l=await ai(d);if(l!==Lt&&l.done)break;if(l!==Lt&&(s.push(l.value),a+=l.value.byteLength,a<=As))continue;let h=l===Lt?d:void 0,g=new ReadableStream({start(b){for(let k of s)b.enqueue(k)},async pull(b){let k=await(h??r.read());h=void 0,k.done?b.close():b.enqueue(k.value)},cancel:b=>r.cancel(b)});return{response:n(g),kept:{status:e.status,headers:t.filter(([b])=>b!=="content-length"&&b!=="content-encoding"),body:null}}}let o=Buffer.concat(s);return{response:n(o),kept:{status:e.status,headers:t,body:o.byteLength===0?null:o.toString("base64")}}}import{createHash as oi}from"node:crypto";var Mn="/webhooks/palbase",qs="PalbaseErrorEnvelope",Ds="PalbaseBearer",ii={$ref:`#/components/schemas/${qs}`},di={type:"object",description:"Every refusal: the framework's, a handler's HttpError, the database's.",properties:{error:{type:"string",description:"A stable code, like bad_request"},error_description:{type:"string",description:"What went wrong, for a person"},status:{type:"integer",description:"The HTTP status"},request_id:{type:"string",description:"The request's id, as the app's log has it"},data:{description:"Details, when the refusal has them: a validation's fields, a token's reason, a limit's retryAfter"}},required:["error","error_description","status","request_id"]},Ns={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Qe={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function Hs(e,t,n){let r={[qs]:di},s={},a=[],o=[],d=new Set,l=new Map;for(let f of e){let T=o.find(V=>pi(V,f));if(T){a.push({route:f.id,handler:Us(f),answeredBy:T.id});continue}o.push(f);let R=f.segments.map(V=>typeof V=="string"?V:"{}").join("/");l.has(R)||l.set(R,hi(f.segments.flatMap(V=>typeof V=="string"?[]:[V.param])));let I=l.get(R),z=0,J=`/${f.segments.map(V=>typeof V=="string"?V:`{${I[z++]}}`).join("/")}`,L=t(f),N=Bt(mi(f),d),G=f.method!=="GET"&&f.method!=="HEAD",Q=V=>{let Ue=f.params.filter(Le=>Le.kind===V&&Le.schema).map((Le,at)=>Ft(Le.schema,`${N}.${V}${at===0?"":`.${at+1}`}`,r));return Ue.length===0?void 0:Ue.length===1?Ue[0]:{allOf:Ue}},te=I.map(V=>({name:V,in:"path",required:!0,schema:{type:"string"}})),rt=Q("query");rt&&te.push(...Is(rt,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:rt}]);let vt=Q("headers");vt&&te.push(...Is(vt,"header")??[]);let ye=n.idempotency===!0&&mt(f);ye&&te.push({...Cn,schema:{...Cn.schema}});let ve=G?Q("body"):void 0,ee={operationId:N};f.controller.name!==""&&(ee.tags=[f.controller.name]),te.length>0&&(ee.parameters=te),ve&&(ee.requestBody={required:!ki(ve),content:{"application/json":{schema:ve}}});let Yt=f.params.some(V=>V.schema!==void 0),Tt=n.routes?.(f),st=Ti(N,Tt?.throws??[],n.errors);ee.responses={...vi(Tt,N,r),...Ei(L,{validates:Yt,hasPathParams:I.length>0,readsBody:G,keyed:ye}),..._i(st,N,r)},st.length>0&&(ee["x-palbase-errors"]=$i(N,st)),L.auth.required&&(ee.security=[{[Ds]:[]}]),ee["x-palbase-handler"]=Us(f);let Qt=f.params.some(V=>V.kind==="optionalUser")||n.databaseSeesCaller;ee["x-palbase-auth"]=L.auth.required?"required":Qt?"optional":"public",ee["x-palbase-verified-email"]=L.auth.verifiedEmail,L.auth.aal!=="aal1"&&(ee["x-palbase-aal"]=L.auth.aal),L.auth.maxAge!==null&&(ee["x-palbase-max-age"]=L.auth.maxAge),L.attest&&(ee["x-palbase-attest"]=!0);let $e=L.limit===!1?!1:L.limit.map(V=>({max:V.max,window:V.window}));ee["x-palbase-rate-limit"]=$e===!1?!1:$e.length===1?$e[0]:$e,f.meta.upload&&(ee["x-palbase-upload"]={bucket:f.meta.upload.bucket,pathTemplate:f.meta.upload.pathTemplate}),(s[J]??={})[f.method.toLowerCase()]=ee}for(let f of n.webhooks??[]){let T={operationId:Bt(`webhooks.${f.name}`,d)};f.cls!==""&&(T.tags=[f.cls]),T.description=f.provider?`${Ns[f.provider]??f.provider}'s deliveries: verified with ${Ns[f.provider]??f.provider}'s signature scheme under the secret in ${f.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${f.signatureHeader} header: verified under the secret in ${f.secretEnv}, then handed to the @On of their event type.`,T.responses={200:{description:"Taken: { ok: true, handled } \u2014 handled is false when no @On takes the event's type, and duplicate is true for a delivery already run; or the handler's answer: a Response as it is, text as text, anything else as JSON",content:{"application/json":{},[f.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:re("invalid_signature: the delivery is not signed with the secret \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:re("in_progress: the same delivery is being handled; the sender delivers it again",Qe),413:re("payload_too_large: the body is over what this sender sends"),500:re("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:re("service_unavailable, auth_unavailable or database_unavailable: what the handler needs of the platform did not answer \u2014 the sender delivers it again after Retry-After",Qe)},T["x-palbase-webhook"]=f.provider?{provider:f.provider,secretEnv:f.secretEnv,events:f.events}:{signatureHeader:f.signatureHeader,secretEnv:f.secretEnv,events:f.events},s[`/webhooks/${f.name}`]={post:T}}let h=[...new Set(n.platformEvents??[])].sort();if(h.length>0){let f={operationId:Bt("webhooks.palbase",d)};f.description="The project's events, delivered by the platform to the app's machine: verified under the secret in PALBASE_WEBHOOK_SECRET, then handed to the @On of their type \u2014 user.deleted first to forgetting the rows the app keeps of that user.",f.responses={204:{description:"Taken: handled, or a delivery already run"},401:re("invalid_signature: the delivery is not the platform's \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:re("in_progress: the same event is being handled; the platform delivers it again",Qe),500:re("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:re("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let T=[...new Set(n.platformEventBuckets??[])].sort();f["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:h,...T.length>0?{buckets:T}:{}},s[Mn]={post:f}}let g=n.gateways??[],b=li(g,r),k=g.length>0,B=Object.fromEntries(g.filter(We).map(f=>[f.pattern,{events:b[f.name].events,messages:Object.fromEntries(Object.entries(b[f.name].messages).map(([T,R])=>[T,R.payload])),graceMs:f.graceMs,...f.logKeepSeconds>0?{logKeepSeconds:f.logKeepSeconds}:{}}])),U=Object.keys(B).length>0,q=g.filter(f=>!We(f)).map(f=>({pattern:f.pattern,kind:f.access,publish:f.publish,state_read:!1,state_write:!1,...f.logKeepSeconds>0?{log_keep_seconds:f.logKeepSeconds}:{}})),W=q.length>0,K=ci(n.ai?.agents??[]),le=Object.keys(K).length>0,he=ui(n.ai?.tools??[]),ge=Object.keys(he).length>0,v={schemas:r,securitySchemes:{[Ds]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},E={openapi:"3.2.0",info:{title:"Palbase backend",version:oi("sha256").update(JSON.stringify({paths:s,components:v,unreachable:a,...k?{gateways:b}:{},...U?{rooms:B}:{},...W?{channels:q}:{},...le?{agents:K}:{},...ge?{aiTools:he}:{}})).digest("hex").slice(0,12),description:"The routes this app serves, as its decorators declare them, and \u2014 when its source was read as the contract was written \u2014 what each answers and the errors it throws (x-palbase-errors). Every refusal is the PalbaseErrorEnvelope; a declared error's carries its code and its data."},paths:s,components:v};return a.length>0&&(E["x-palbase-unreachable"]=a),k&&(E["x-palbase-gateways"]=b),U&&(E["x-palbase-room"]=B),W&&(E["x-palbase-channels"]=q),le&&(E["x-palbase-agents"]=K),ge&&(E["x-palbase-ai-tools"]=he),E}function ci(e){let t=new Map;for(let n of e){if(t.has(n.name))throw new Error(`ai.agent "${n.name}" is declared twice: an agent's name is its own \u2014 make each once, at a module's top level`);t.set(n.name,{...n.description!==void 0?{description:n.description}:{},...n.machine!==void 0?{machine:n.machine}:{}})}return Object.fromEntries([...t].sort(([n],[r])=>n<r?-1:n>r?1:0))}function ui(e){let t=new Map;for(let n of e){let r=t.get(n.name);if(r)throw new Error(`ai tool "${n.name}" is declared twice (${r.kind===n.kind?`two ai.${n.kind==="backend"?"tool":"clientTool"}s`:"an ai.tool and an ai.clientTool"}): an agent is given one tool of a name \u2014 rename one of them`);t.set(n.name,{kind:n.kind,description:n.description,parameters:n.parameters,...n.approval?{approval:!0}:{},...n.kind==="backend"&&n.machine!==void 0?{machine:n.machine}:{}})}return Object.fromEntries([...t].sort(([n],[r])=>n<r?-1:n>r?1:0))}function li(e,t){let n=[];for(let r of e){let s=(d,l,h,g)=>{let b=Gt(`${r.name}_${d}_${l}`),k={},B=Ft(h,b,k,g);B.$ref===void 0&&(k[b]=B),fi(r.pattern,d,l,k[b]);for(let[U,q]of Object.entries(k)){if(Object.hasOwn(t,U)&&JSON.stringify(t[U])!==JSON.stringify(q))throw new Error(`@Gateway("${r.pattern}") ${d} "${l}": its schema is the component ${U}, which another gateway's names with another schema \u2014 rename one of them`);t[U]=q}return{$ref:`#/components/schemas/${b}`}},a=Object.fromEntries(Object.entries(r.events).map(([d,l])=>[d,s("event",d,l,"answered")])),o=Object.fromEntries(Object.entries(r.messages).map(([d,l])=>[d,{payload:s("message",d,l.schema,"sent"),...l.reply?{reply:s("reply",d,l.reply,"answered")}:{}}]));n.push([r.name,{pattern:r.pattern,...r.access?{access:r.access}:{},...r.logKeepSeconds>0?{durable:r.logKeepSeconds}:{},...r.chat?{chat:!0}:{},events:a,messages:o}])}return Object.fromEntries(n)}function fi(e,t,n,r){if(!(!ae(r)||!ae(r.properties))){for(let[s,a]of Object.entries(r.properties))if(a===!0||ae(a)&&Object.keys(a).length===0)throw new Error(t==="message"?`@Gateway("${e}") message "${n}" has an untyped field "${s}". Inbound payloads reach the server \u2014 declare the shape so it can be validated.`:`@Gateway("${e}") ${t} "${n}" has an untyped field "${s}". An untyped payload makes every generated client opaque \u2014 declare its shape.`)}}function pi(e,t){return e.method===t.method&&e.segments.length===t.segments.length&&e.segments.every((n,r)=>typeof n!="string"||n===t.segments[r])}function Us(e){return`${e.controller.name}.${e.fn}`}function mi(e){let t=e.controller.name;if(t.endsWith("Controller")&&(t=t.slice(0,-10)),t!=="")return`${t[0].toLowerCase()}${t.slice(1)}.${e.fn}`;let n=r=>r.charAt(0).toUpperCase()+r.slice(1);return e.method.toLowerCase()+e.segments.map(r=>typeof r=="string"?n(r):`By${n(r.param)}`).join("")}function Bt(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function hi(e){let t=new Set;return e.map(n=>Bt(n,t))}function Ft(e,t,n,r="sent"){let s=e["~standard"],a=s.jsonSchema?.input;if(typeof a!="function")return{};let o;try{o=a({target:"draft-2020-12",libraryOptions:{unrepresentable:"any",...s.vendor==="zod"?{override:gi}:{}}})}catch{return{}}let d=Gt(t);for(;Object.keys(n).some(l=>l===d||l.startsWith(`${d}.`));)d=`${d}_`;return yi(o,d,n,r)}function gi(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function yi(e,t,n,r){let s=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},a=!1,o=h=>h==="#"?(a=!0,`#/components/schemas/${t}`):h.startsWith("#/$defs/")?`#/components/schemas/${t}.${Gt(bi(h.slice(8)))}`:h,d="all";if(r==="sent"){let h=new Set;for(let g of[e,...Object.values(s)])zt(g,h);d=h}for(let[h,g]of Object.entries(s))n[`${t}.${Gt(h)}`]=gt(ht(g,o,d));let l=gt(ht(e,o,d));return a?(n[t]=l,{$ref:`#/components/schemas/${t}`}):l}var wi=new Set(["type","enum","required","dependentRequired","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","contentEncoding","contentMediaType","minItems","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties","readOnly","writeOnly","deprecated",or]),jn=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),Dn=new Set(["anyOf","oneOf","allOf","prefixItems"]),Nn=new Set(["properties","patternProperties","dependentSchemas"]),ae=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ht(e,t,n){if(!ae(e))return typeof e=="boolean"?e:{};let r={};for(let[s,a]of Object.entries(e))s==="$ref"&&typeof a=="string"?r.$ref=t(a):s==="const"?(n==="all"||n.has(e))&&(r.const=a):wi.has(s)?r[s]=a:jn.has(s)?r[s]=ht(a,t,n):Dn.has(s)&&Array.isArray(a)?r[s]=a.map(o=>ht(o,t,n)):Nn.has(s)&&ae(a)&&(r[s]=Object.fromEntries(Object.entries(a).map(([o,d])=>[o,ht(d,t,n)])));return r}var Ls=Number.MAX_SAFE_INTEGER;function gt(e){if(!ae(e))return e;let t={};for(let[r,s]of Object.entries(e))jn.has(r)?t[r]=gt(s):Dn.has(r)&&Array.isArray(s)?t[r]=s.map(gt):Nn.has(r)&&ae(s)?t[r]=Object.fromEntries(Object.entries(s).map(([a,o])=>[a,gt(o)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-Ls&&delete t.minimum,t.maximum===Ls&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,ae(t.propertyNames)&&Object.keys(t.propertyNames).length===1&&t.propertyNames.type==="string"&&delete t.propertyNames,Array.isArray(t.type)&&t.type.filter(r=>r!=="null").length>1&&Object.keys(t).length===1)return{anyOf:t.type.map(r=>({type:r}))};let n=t.anyOf;if(Array.isArray(n)&&n.length===2&&Object.keys(t).length===1){let r=n.findIndex(a=>ae(a)&&Object.keys(a).length===1&&a.type==="null"),s=n[1-r];if(r!==-1&&ae(s)&&typeof s.type=="string")return{...s,type:[s.type,"null"]}}return t}function zt(e,t){if(ae(e)){for(let n of["anyOf","oneOf"]){let r=e[n];if(!Array.isArray(r)||r.length<2||!r.every(ae))continue;if(r.every(a=>"const"in a||Array.isArray(a.enum)))for(let a of r)t.add(a);let s=r.map(a=>ae(a.properties)?a.properties:{});for(let a of Object.keys(s[0]))if(s.every(o=>ae(o[a])&&"const"in o[a]))for(let o of s)t.add(o[a])}for(let[n,r]of Object.entries(e))if(jn.has(n))zt(r,t);else if(Dn.has(n)&&Array.isArray(r))for(let s of r)zt(s,t);else if(Nn.has(n)&&ae(r))for(let s of Object.values(r))zt(s,t)}}function bi(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Gt(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function Is(e,t){if(e.type!=="object"||typeof e.properties!="object"||e.properties===null)return;let n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([r,s])=>({name:r,in:t,required:n.has(r),schema:s}))}function ki(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function re(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:ii}}}}function vi(e,t,n){if(!e)return{200:{description:"The handler's answer, as JSON",content:{"application/json":{}}},204:{description:"The handler answered nothing (undefined or null)"}};if(e.returns.kind==="void")return{204:{description:"No Content"}};if(e.returns.kind==="raw")return{default:{description:"The handler's own Response, as it built it"}};let r=Ft(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function Ti(e,t,n){let r=new Set,s=[];for(let a of t){if(r.has(a.code))continue;r.add(a.code);let o=n?.get(a.code);if(o&&a.status!==o.status)throw new Error(`${e} throws "${a.code}" with status ${a.status}, but the code is defined with status ${o.status} \u2014 a client matches an error by its code, so one code carries one status`);s.push({...a,...o?.data?{data:o.data}:{}})}return s}function $i(e,t){let n=Object.create(null);for(let r of t){let s=r.name.charAt(0).toLowerCase()+r.name.slice(1),a=Object.hasOwn(n,s)?n[s]:void 0;if(a)throw new Error(`${e} throws "${a.code}" and "${r.code}" under one name, "${r.name}" \u2014 every client names an error case after it; give one of them its own defineError`);n[s]={status:r.status,code:r.code,hasData:r.data!==void 0,description:""}}return n}function _i(e,t,n){let r=new Map;for(let a of e)r.set(a.status,[...r.get(a.status)??[],a]);let s={};for(let a of[...r.keys()].sort((o,d)=>o-d)){let o=r.get(a),d=o.map(l=>{let h={error:{type:"string",const:l.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},g=["error","error_description","status","request_id"];return l.data&&(h.data=Ft(l.data,`${t}.${l.code}.data`,n,"answered"),g.push("data")),{type:"object",properties:h,required:g}});s[String(a)]={description:o.map(l=>l.code).join(" | "),content:{"application/json":{schema:d.length===1?d[0]:{oneOf:d}}}}}return s}function Ei(e,t){let n={},r=[t.validates&&"a parameter failed its schema (data.fields names each field, data.more how many more)",t.hasPathParams&&"the path is not valid percent-encoding"].filter(Boolean),s=[r.length>0&&`bad_request: ${r.join("; or ")}`,t.keyed&&"invalid_idempotency_key: the Idempotency-Key is over 255 characters"].filter(Boolean);s.length>0&&(n[400]=re(s.join("; ")));let a=[e.auth.required&&"unauthorized: no access token was sent; invalid_token: the token is not valid (data.reason says why), or the Authorization header is not a Bearer token",e.auth.aal!=="aal1"&&`insufficient_user_authentication: the user signed in below ${e.auth.aal} \u2014 step up and call again (WWW-Authenticate acr_values; data.acr_values)`,e.auth.maxAge!==null&&`insufficient_user_authentication: the user last signed in or stepped up more than ${e.auth.maxAge} seconds ago \u2014 step up and call again (WWW-Authenticate max_age; data.max_age)`,e.attest&&"app_attest_required: the environment asks for the device's attestation and the call's proof is missing or does not verify (data.reason: app_attest_required, assertion_invalid, assertion_stale, device_unknown; data.challenge and X-Palbase-Attest-Challenge to attest with)"].filter(Boolean);return a.length>0&&(n[401]=re(a.join("; "))),e.auth.verifiedEmail&&(n[403]=re("email_not_verified: the user's email address is not verified")),t.keyed&&(n[409]=re("idempotency_key_in_use: a request with this Idempotency-Key is still running",Qe)),t.readsBody&&(n[413]=re("payload_too_large: the body is over the app's body limit")),t.keyed&&(n[422]=re("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(n[429]=re("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Qe)),n[500]=re("internal_error: the handler failed; the app's log has it under the request id"),n[503]=re(`${e.auth.required?"auth_unavailable: sign-ins cannot be checked right now; ":""}${e.attest?"attest_unavailable: the device's attestation cannot be checked right now; ":""}service_unavailable: a platform service the request needs did not answer${t.keyed?"; temporarily_unavailable: the Idempotency-Key could not be recorded":""}`,Qe),n}var Wt=class{windows=new Map;now;maxKeys;constructor(t=Date.now,n=1e5){this.now=t,this.maxKeys=n}take(t,n){let r=this.now(),s=this.windows.get(t);if((!s||r>=s.resetAt)&&(s={count:0,resetAt:r+n.window*1e3}),this.windows.delete(t),this.windows.set(t,s),this.windows.size>this.maxKeys&&this.windows.delete(this.windows.keys().next().value),s.count++,s.count>n.max)return Math.max(1,Math.ceil((s.resetAt-r)/1e3))}takeEach(t,n){if(n.length===1)return this.take(t,n[0]);let r,s=[];if(n.forEach((a,o)=>{let d=this.reserve(`${t}\0${o}`,a);"wait"in d?r=Math.max(r??0,d.wait):s.push([`${t}\0${o}`,d.window])}),r!==void 0)for(let[a,o]of s)this.give(a,o);return r}reserve(t,n){let r=this.take(t,n);return r!==void 0?{wait:r}:{window:this.windows.get(t).resetAt}}give(t,n){let r=this.windows.get(t);r&&r.resetAt===n&&r.count>0&&r.count--}};function yt(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return Si(r??t??"unknown")}function Si(e){let t=e.replace(/^\[|\]$/g,"").replace(/%.*$/,"");if(!t.includes(":"))return e;let n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(t);if(n)return n[1];let[r,s=""]=t.split("::"),a=r?r.split(":"):[],o=s?s.split(":"):[],d=t.includes("::")?[...a,...Array(8-a.length-o.length).fill("0"),...o]:a;return d.length!==8||d.some(l=>!/^[0-9a-f]{1,4}$/i.test(l))?t:`${d.slice(0,4).map(l=>parseInt(l,16).toString(16)).join(":")}::/64`}var Un="/.well-known/palbase/attest-challenge",oe={deviceId:"x-palbase-device-id",anchor:"x-palbase-installation-anchor",challenge:"x-palbase-attest-challenge",payload:"x-palbase-attest-payload",signature:"x-palbase-attest-signature",capable:"x-palbase-attest-capable",sdkVersion:"x-palbase-sdk-version"},Ai=25e3,Kt=3e3,xi=1e4,Bs=()=>({capable:0,incapable:0,unknown:0,no_sdk:0,verified:0,refused:0}),Jt=class{constructor(t,n=Date.now){this.auth=t;this.now=n}auth;now;mode;readAt=-1/0;reading;counts=Bs();timer;shipping=Promise.resolve();async modeNow(){return this.now()-this.readAt>=Ai&&(this.reading??=this.readMode().finally(()=>{this.reading=void 0}),await this.reading),this.mode}async readMode(){try{let n=(await this.auth.adminGetAttestPolicy({signal:AbortSignal.timeout(Kt)})).data.mode;if(n!=="off"&&n!=="monitor"&&n!=="enforce")throw new Error(`auth answered an App Attest mode this version does not know: ${JSON.stringify(n)}`);this.mode=n,this.readAt=this.now()}catch(t){_.warn(`[palbase] attest: the environment's App Attest mode could not be read${this.mode?`; keeping ${this.mode}`:""}`,{error:t})}}async check(t,n,r,s){let a=await this.modeNow();if(a===void 0)return{unavailable:!0,pass:!1};if(a==="off")return{pass:!0};let o=t.headers,d=o.get(oe.deviceId)??"",l=o.get(oe.payload)??"",h=o.get(oe.signature)??"",g=d!==""&&l!==""&&h!=="",b=g&&zs(l)&&zs(h);this.declared(o,g);let k;try{k=(await this.auth.adminVerifyDeviceAssertion({body:{installation_id:o.get(oe.anchor)??"",device_id:b?d:"",challenge:o.get(oe.challenge)??"",payload:b?l:"",signature:b?h:"",method:t.method,path:s??Ri(n),body_sha256:r&&r.byteLength>0?await Oi(r):""},signal:AbortSignal.timeout(Kt)})).data}catch(q){return _.warn(`[palbase] attest: auth could not verify ${t.method} ${n.pathname}`,{error:q}),a==="enforce"?{unavailable:!0,pass:!1}:{pass:!0}}g&&this.outcome(b&&k.ok);let B=a==="enforce"&&k.ok&&k.device_id&&k.platform?{id:k.device_id,platform:k.platform}:void 0;return k.ok||a==="monitor"?{pass:!0,challenge:k.next_challenge||void 0,device:B}:{pass:!1,reason:g?b?k.reason==="assertion_stale"||k.reason==="device_unknown"||k.reason==="assertion_invalid"?k.reason:"app_attest_required":"assertion_invalid":"app_attest_required",challenge:k.next_challenge}}async challengeFor(t){let n=await this.modeNow();if(n===void 0)return{unavailable:!0};if(n==="off")return{};try{let r=await this.auth.adminVerifyDeviceAssertion({body:{installation_id:t,device_id:"",challenge:"",payload:"",signature:"",method:"GET",path:Un,body_sha256:""},signal:AbortSignal.timeout(Kt)});return r.data.next_challenge?{challenge:r.data.next_challenge}:{unavailable:!0}}catch(r){return _.warn("[palbase] attest: auth could not mint a challenge",{error:r}),{unavailable:!0}}}declared(t,n){let r=t.get(oe.capable);n||r==="yes"?this.counts.capable++:r==="no"?this.counts.incapable++:t.get(oe.sdkVersion)?this.counts.unknown++:this.counts.no_sdk++,this.schedule()}outcome(t){t?this.counts.verified++:this.counts.refused++}schedule(){this.timer||(this.timer=setInterval(()=>{this.flush()},xi),this.timer.unref?.())}async flush(){let t=this.counts;Object.values(t).every(n=>n===0)||(this.counts=Bs(),this.shipping=this.shipping.then(async()=>{try{await this.auth.adminRecordAttestObservations({body:t,signal:AbortSignal.timeout(Kt)})}catch(n){_.warn("[palbase] attest: a batch of App Attest counts was not recorded",{error:n})}}),await this.shipping)}async stop(){this.timer&&clearInterval(this.timer),this.timer=void 0,await this.flush()}};function zs(e){return e.length===0||e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e)?!1:Buffer.from(e,"base64").toString("base64")===e}function Ri(e){let t=e.href,n=t.indexOf("#");return(n===-1?t:t.slice(0,n)).slice(e.origin.length)}async function Oi(e){let t=new Uint8Array(e.byteLength);t.set(e);let n=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Buffer.from(n).toString("base64")}function Gs(e){let t=[];for(let n of e){let r=D(n,qe),s=D(n,He)??[];if(s.length===0)throw new TypeError(`@Controller ${n.name} has no routes: a controller with nothing to serve is a mistake`);let a=D(n,an)??new Map;for(let o of s){let d=`${r.basePath}${o.subpath}`||"/",l=d.split("/").filter(Boolean).map(g=>{let b=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(g)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(g);return b?{param:b[1]}:g});if(typeof l[0]=="string"&&ze.has(l[0]))throw new TypeError(`${n.name}.${o.fn}: ${o.method} ${d} \u2014 /${l[0]} is the platform's; a route is served elsewhere`);let h=[...a.get(o.fn)??[]].sort((g,b)=>g.index-b.index);for(let g of h)if(g.kind==="param"&&!l.some(b=>typeof b!="string"&&b.param===g.name))throw new TypeError(`${n.name}.${o.fn}: @Param("${g.name}") names no {${g.name}} in ${o.method} ${d}`);t.push({id:`${o.method} ${d}`,method:o.method,segments:l,controller:n,fn:o.fn,params:h,meta:o,controllerAuth:r.options.auth,controllerAttest:r.options.attest})}}return Lr(t),t}function Ln(e,t,n){let r=n.split("/").filter(Boolean);for(let s of e){if(s.method!==t||s.segments.length!==r.length)continue;let a={},o=!0;for(let d=0;d<r.length&&o;d++){let l=s.segments[d];if(typeof l=="string")o=l===r[d];else try{a[l.param]=decodeURIComponent(r[d])}catch{return{malformed:!0}}}if(o)return{route:s,params:a}}return null}function Hn(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Xe(e,t,n,r,s){return bt(e,e?Hn(e.requests,t):void 0,n,r,s)}var Vt={role:"service",claims:{}};async function bt(e,t,n,r,s){if(!e||!t)return s();let a=k=>_.warn(`[palbase] ${r}: a transaction of the request could not be given back \u2014 it wrote, locked, is an $atomic or an $attempt, ran SQL of its own, or the database keeps one snapshot for it \u2014 and sat ${k} ms with no statement running: the handler waited on something else, and a database connection waited with it. Make the outside call before the first write, or outside $atomic.`,{waitedMs:k}),o=e.app.request(t,{signal:n,heldIdle:a}),d=ne.getStore(),l=[],h=d?.saying;d&&(d.database=o.database,d.saying=l);let g=()=>{d&&(d.saying=h)},b;try{b=await s()}catch(k){throw g(),await o.rollback(k).catch(B=>_.error("[palbase] the request's transaction could not be rolled back",{error:B})),k}try{await o.commit()}catch(k){throw g(),await o.rollback(k).catch(B=>_.error("[palbase] the request's transaction could not be rolled back",{error:B})),k}g();for(let k of l)k();return b}var Ci=1024*1024,Mi=20,ji={max:300,window:60},Di={max:60,window:60},Ni=/^ins_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,et="/_palbase/crons",tt="/_palbase/tasks",Fs=50,Ws=50,Ui=4096,Li=69632,Ks=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,nt=1e4,Ii=6e4;function qi(e,t){let n=e.meta.options.auth??e.controllerAuth??t??!0;if(typeof n=="boolean")return{required:n,verifiedEmail:!1,aal:"aal1",maxAge:null};let r=n.aal??"aal1";if(r!=="aal1"&&r!=="aal2"&&r!=="aal3")throw new TypeError(`${e.id}: auth { aal } is 'aal1', 'aal2' or 'aal3', not ${JSON.stringify(r)}`);if(r!=="aal1"&&n.required===!1)throw new TypeError(`${e.id}: auth { aal: '${r}' } asks how the user signed in \u2014 the route needs a signed-in user (required: true)`);let s=n.maxAge??null;if(s!==null&&!(Number.isInteger(s)&&s>0))throw new TypeError(`${e.id}: auth { maxAge } is a whole number of seconds above 0, not ${JSON.stringify(s)}`);if(s!==null&&n.required===!1)throw new TypeError(`${e.id}: auth { maxAge } asks when the user last signed in \u2014 the route needs a signed-in user (required: true)`);return{required:n.required!==!1,verifiedEmail:n.verifiedEmail===!0,aal:r,maxAge:s}}function Js(e,t){let n=['error="insufficient_user_authentication"'];return e.aal!=="aal1"&&n.push(`acr_values="urn:nist:800-63:${e.aal}"`),e.maxAge!==null&&n.push(`max_age=${e.maxAge}`),`${t?"DPoP":"Bearer"} ${n.join(", ")}`}function Vs(e){return{...e.aal!=="aal1"?{acr_values:e.aal}:{},...e.maxAge!==null?{max_age:e.maxAge}:{}}}var Hi=60;function Bi(e,t,n){if(e===null)return!1;let r=n/1e3-e;return r>=-Hi&&r<=t}var X=class extends Error{constructor(n,r,s,a,o,d,l){super(s);this.status=n;this.code=r;this.data=a;this.retryAfter=o;this.challenge=d;this.headers=l}status;code;data;retryAfter;challenge;headers};function zi(e){if(e==="proof")return'DPoP error="invalid_dpop_proof", algs="ES256"';if(e==="bound"||e==="not_bound")return'DPoP error="invalid_token", algs="ES256"'}var Gi=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function Fi(e,t){let n=new Headers(e.headers);for(let r of Gi)n.delete(r);return e.url!==""&&(n.delete("content-encoding"),n.delete("content-length")),n.set("x-request-id",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}function Zs(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),Zt(e.headers,"Accept-Language")),e}function Zt(e,t){let n=(e.get("vary")??"").split(",").map(r=>r.trim()).filter(Boolean);n.includes("*")||n.some(r=>r.toLowerCase()===t.toLowerCase())||e.set("vary",[...n,t].join(", "))}function ce(e,t,n,r={}){let s=JSON.stringify(t);return Ht(new Response(s,{status:e,headers:{"content-type":"application/json","x-request-id":n,...r}}),Buffer.from(s,"utf8"))}function $(e,t){let n={error:e.code,error_description:e.message,status:e.status,request_id:t};e.data!==void 0&&(n.data=e.data);let r={...e.headers};return e.retryAfter!==void 0&&(r["retry-after"]=String(e.retryAfter)),e.challenge!==void 0&&(r["www-authenticate"]=e.challenge),ce(e.status,n,t,r)}function Ys(e,t){if(t===void 0)return e;try{return e.headers.set(oe.challenge,t),e}catch{let n=new Headers(e.headers);return n.set(oe.challenge,t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}}var aa=new Set([0,429,502,503,504]);function Qs(e,t,n,r){if(r?.aborted)return _.info(`[palbase] ${n}: the client left before its answer`),$({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof X)return $({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge,headers:e.headers},t);if(pt(e)){let a=e;return a.status>=500&&_.error(`[palbase] ${n} answered ${a.status} ${a.error}`,{error:e}),ce(a.status,ps(a,t),t,a.retryAfter!==void 0?{"retry-after":String(a.retryAfter)}:{})}let s=Bn(e,n);return s?$(s,t):(e instanceof ie?_.error(`[palbase] ${n}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):_.error(`[palbase] unhandled error in ${n}`,{error:e}),$({status:500,code:"internal_error",message:"The request could not be completed"},t))}function Bn(e,t){if(e instanceof xt)return _.warn(`[palbase] ${t}: sign-ins cannot be checked (${e.message})`,{error:e}),{status:503,code:"auth_unavailable",message:"Sign-ins cannot be checked right now; try again shortly",retryAfter:1};if(e instanceof ie&&aa.has(e.status))return _.warn(`[palbase] ${t}: a platform service did not answer (${e.op}: ${e.status} ${e.code})`,{error:e}),{status:503,code:"service_unavailable",message:"A service this request needs did not answer; try again shortly",retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))};let n=ra(e);if(n!==void 0)return _.warn(`[palbase] ${t}: the database connection ${n==="lost"?"was lost":"could not be opened"}`,{error:e}),{status:503,code:"database_unavailable",message:"The database is temporarily unavailable",data:{retrySafe:n==="never"},retryAfter:1}}function Wi(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return An(e)?t(e.message):pt(e)&&!Wn(e)&&!zn(e)?t(e.errorDescription):zn(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function zn(e){return e instanceof xt||e instanceof ie&&aa.has(e.status)||ra(e)!==void 0||pt(e)&&e.status===503&&Wn(e)}async function In(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,Mi).map(o=>({field:(o.path??[]).map(d=>String(typeof d=="object"&&d!==null&&"key"in d?d.key:d)).join("."),message:o.message})),a=r.issues.length-s.length;throw new X(400,"bad_request",`${n} failed validation`,a>0?{fields:s,more:a}:{fields:s})}return r.value}async function wt(e,t){let n=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(n)&&n>t)throw new X(413,"payload_too_large",`Request body exceeds ${t} bytes`);if(!e.body)return new Uint8Array(0);let r=e.body.getReader(),s=[],a=0;for(;;){let{done:l,value:h}=await r.read();if(l)break;if(a+=h.byteLength,a>t)throw await r.cancel().catch(()=>{}),new X(413,"payload_too_large",`Request body exceeds ${t} bytes`);s.push(h)}let o=new Uint8Array(a),d=0;for(let l of s)o.set(l,d),d+=l.byteLength;return o}function Ki(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return ue(t)}function Ji(e){let t=e.claims.custom_claims;return{id:e.id,email:e.email,role:e.role,emailVerified:e.emailVerified,metadata:typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},sessionId:e.sessionId,test:e.claims.test===!0,acr:Vi(e.claims.acr),amr:Array.isArray(e.claims.amr)?e.claims.amr.filter(n=>typeof n=="string"):[],authTime:typeof e.claims.auth_time=="number"&&e.claims.auth_time>0?e.claims.auth_time:null}}function Vi(e){return e==="aal1"||e==="aal2"||e==="aal3"?e:null}function Xs(e){return e==="aal3"?3:e==="aal2"?2:1}function Zi(e){return e.id?{id:e.id,email:e.email??null,role:e.role,emailVerified:e.emailVerified??!1,metadata:{},sessionId:e.session??null,test:!1,acr:null,amr:[],authTime:null}:null}var Yi=/^[A-Za-z0-9._:-]{8,128}$/,Qi=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Xi={max:20,window:60},ed=10*6e4,td=1e4,kt=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},Gn=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=sa("sha256").update(t).digest("hex"),a=(this.known.get(s)??0)>this.now(),o=`token-misses\0a:${n}`,d;if(!a){let h=this.limiter.reserve(o,Xi);if("wait"in h)throw new kt(h.wait);d=h}let l=await r();if(!l)throw this.known.delete(s),new At("unknown_token","The token is not one of the app's");return d&&this.limiter.give(o,d.window),this.known.delete(s),this.known.set(s,this.now()+ed),this.known.size>td&&this.known.delete(this.known.keys().next().value),l}};function Au(e){let t=new Nt(e.modules),n=Gs(t.controllers.map(i=>i.cls)),r=new Map(n.map(i=>[i,qi(i,e.auth)])),s=i=>i.meta.options.attest??i.controllerAttest??!1,a=n.some(s)?new Jt(e.server.auth,e.now):void 0,o=new Map;for(let i of n){let c={body:[],query:[]};for(let p of i.params){if(!p.schema)continue;let u=yr(p.schema);if(p.kind==="body")c.body.push(...nn(u,"/body",i.id));else if(p.kind==="query"){let y=nn(u,"/query",i.id),m=y.find(w=>w.split("/").length!==3);if(m)throw new TypeError(`${i.id}: ${m} \u2014 an encrypted query field is one of the query's own names`);c.query.push(...y)}else if(wr(u))throw new TypeError(`${i.id}: its ${p.kind} carry no encrypted field \u2014 its body's or its query's do`)}if(c.body.length+c.query.length!==0){if(i.meta.upload)throw new TypeError(`${i.id}: an upload's body comes through storage, which seals nothing \u2014 it carries no encrypted field`);o.set(i,c)}}async function d(i,c,p,u){let y=e.server.transit;try{return y.loaded||await y.load(),await y.request({header:p,method:u,path:ad(i),params:i.segments.flatMap(m=>typeof m=="string"?[]:[c[m.param]??""])})}catch(m){throw ta(m)}}for(let[i,c]of r){if(!c.required&&i.params.some(p=>p.kind==="user"))throw new TypeError(`${i.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(i.meta.upload&&c.verifiedEmail)throw new TypeError(`${i.id}: an @Upload route cannot ask for a verified email \u2014 storage names its caller by id and session, not by its token; read the user (Palbase.auth) in the handler to check it`);if(i.meta.upload&&c.aal!=="aal1")throw new TypeError(`${i.id}: an @Upload route cannot ask for auth { aal } \u2014 storage names its caller by id and session, not by its token`);if(i.meta.upload&&c.maxAge!==null)throw new TypeError(`${i.id}: an @Upload route cannot ask for auth { maxAge } \u2014 storage names its caller by id and session, not by its token's auth_time`);if(!s(i)&&i.params.some(p=>p.kind==="attestedDevice"))throw new TypeError(`${i.id}: @AttestedDevice() on a route that does not ask for device attestation \u2014 mark it attest: true`);if(i.meta.upload&&s(i))throw new TypeError(`${i.id}: an @Upload route cannot ask for device attestation \u2014 storage calls it, not the app's client; attest the route the app calls before the upload`)}let l=new Map;for(let i of n)for(let c of i.params)c.kind==="resolve"&&l.set(c,t.dependencyOf(i.controller,c.resolver,`${i.id} @Resolve(${c.resolver?.name})`));let h=new Map;for(let i of t.cronProviders){let c=t.get(i),p=D(i,Ee),u=h.get(p.name);if(u)throw new TypeError(`@Cron "${p.name}" is ${u.owner} and ${i.name}: a cron's name is its own \u2014 name one of them`);h.set(p.name,{declaration:p,owner:i.name,run:y=>c.run(y)})}let g=new Map;for(let i of t.taskProviders){let c=t.get(i),p=D(i,ke),u=g.get(p.name);if(u)throw new TypeError(`@Task "${p.name}" is ${u.owner} and ${i.name}: a task type's name is its own \u2014 name one of them`);g.set(p.name,{declaration:p,owner:i.name,run:(y,m)=>c.run(y,m)})}let b=new Map;for(let i of t.templateProviders){let c=t.get(i),p=D(i,Te),u=b.get(p.name);if(u)throw new TypeError(`@TestUserTemplate "${p.name}" is ${u.owner} and ${i.name}: a template's name is its own \u2014 name one of them`);b.set(p.name,{owner:i.name,seed:(y,m)=>c.seed(y,m),...typeof c.undo=="function"?{undo:(y,m)=>c.undo(y,m)}:{}})}b.size>0&&!e.platform&&_.info(`[palbase] ${b.size} @TestUserTemplate(s): the platform calls a machine for its test users; nothing does here`);let k=new Map,B=new Set,U=new Set,q=new Set;if(e.platform&&!e.platform.secret)throw new Error("[palbase] platform.secret is the key the platform signs its calls with (PALBASE_PLATFORM_SECRET)");if(h.size>Fs)throw new TypeError(`${h.size} @Cron classes: a machine runs ${Fs} crons at most`);if(g.size>Ws)throw new TypeError(`${g.size} @Task classes: a machine runs ${Ws} task types at most`);h.size>0&&!e.platform&&_.info(`[palbase] ${h.size} @Cron(s): the platform runs them on a machine; nothing calls them here`);let W=Zr(t.gateways.map(i=>({cls:i,instance:t.get(i)})),{run:(i,c,p,u)=>ne.run({requestId:ne.getStore()?.requestId??"",...i?.id?{userId:i.id}:{}},()=>bt(e.database,e.database?i?.id?Hn(e.database.requests,jt(i)):Vt:void 0,p,c,async()=>{let y=await u();if(p?.aborted)throw new Error(`realtime gave up on ${c} before it ended`);return y})),broadcast:i=>e.server.realtime.broadcast({body:{messages:i}}),revalidate:i=>e.server.realtime.revalidate({body:i}),isOutage:zn});W.declarations.length>0&&!e.platform&&_.info(`[palbase] ${W.declarations.length} @Gateway(s): realtime tells a machine of them; nothing does here`);let K=ys();(K.tools.size>0||K.agents.size>0)&&!e.platform&&_.info(`[palbase] ${K.tools.size} ai.tool(s) and ${K.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let le=i=>c=>t.provider(c,`${i} ctx.inject(${typeof c=="function"?c.name:String(c)})`),he=new Ut,ge=new Set,v=e.database!==void 0||e.contractOnly?.database===!0;if(v){for(let i of n)if(mt(i)&&i.params.some(c=>c.kind==="headers"&&c.schema!==void 0&&js(c.schema)))throw new TypeError(`${i.id}: its @Headers schema declares Idempotency-Key \u2014 the framework takes that header on every write of an app with a database and answers a retry from it; a handler reads it with @Headers() (no schema)`)}let E=e.database?new qt(e.database.app,e.database.keptAnswers):void 0,f=ld(e.cors),T=e.now??Date.now,R=new Wt(e.now),I=new Gn(R,e.now??Date.now),z=e.maxBodyBytes??Ci,J=i=>{let c=i.meta.options.rateLimit??e.rateLimit??ji;if(c===!1)return!1;let p=(Array.isArray(c)?c:[c]).filter(u=>u.max>0&&u.window>0);return p.length>0?p:!1},L=e.env??process.env,N=ns(t.webhooks,i=>t.get(i),L,{secrets:e.contractOnly===void 0}),G=N.size===0&&h.size===0&&g.size===0&&b.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(L).filter(i=>typeof i[1]=="string"&&!fr(i[0])))),Q=new Map([...N.keys()].map(i=>[i,{seen:new Set,inflight:new Set}])),te=new Map([...N.keys()].map(i=>[i,{counts:new Map,at:void 0}])),rt,vt=()=>rt??=Hs(n,i=>({auth:r.get(i),limit:J(i),attest:s(i)}),{databaseSeesCaller:v,idempotency:v,webhooks:[...N.values()].map(i=>({name:i.name,cls:i.cls.name,provider:i.provider,signatureHeader:i.signatureHeader,secretEnv:i.secretEnv,events:[...i.events.keys()]})),platformEvents:[...ye.keys()],gateways:W.declarations,ai:{agents:[...K.agents.values()].map(i=>({name:i.name,...i.description!==void 0?{description:i.description}:{},...i.machine!==void 0?{machine:i.machine}:{}})),tools:[...[...K.tools.values()].map(i=>({name:i.name,kind:"backend",description:i.description,parameters:i.parameters,approval:i.approval,...i.machine!==void 0?{machine:i.machine}:{}})),...[...K.clientTools.values()].map(i=>({name:i.name,kind:"client",description:i.description,parameters:i.parameters,approval:i.approval}))]},platformEventBuckets:rd(ye),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),ye=new Map;for(let[i,c]of Object.entries(e.events??{}))ye.set(i,c.map(p=>({name:`palbase(${i})`,call:u=>p(u)})));for(let i of t.eventProviders){let c=t.get(i);for(let{event:p,fn:u,bucket:y}of D(i,Me)??[]){if(!_r.test(p))throw new TypeError(`@On("${p}") on ${i.name}.${u}: a platform event's type is dotted lowercase words, like user.deleted \u2014 a third party's event is taken by an @On in its @Webhook class`);ye.has(p)||ye.set(p,[]),ye.get(p).push({name:`${i.name}.${u}`,bucket:y,call:async(m,w)=>c[u](m,w)})}}let ve=new Set,ee=new Set;pr(e.server),mr({to:(i,c)=>({emit:(p,u)=>W.emit(i,c,p,u),pipe:p=>W.pipe(i,c,p),revalidate:p=>W.revalidate(i,c,p)})}),Sr(e.platform?Ar(L.PALBASE_MACHINE):new Ct(new Map([...g].map(([i,c])=>[i,c.declaration])),(i,c)=>at(i,c),e.now));async function Yt(i,c){let p;try{p=await ur(i,e.webhookSecret,{now:e.now})}catch(u){if(u instanceof dt)return $({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${u.code}`},c);throw u}if(ue(p.data),ve.has(p.id))return new Response(null,{status:204,headers:{"x-request-id":c}});if(ee.has(p.id))return $({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},c);ee.add(p.id);try{let u;try{await Xe(e.database,null,void 0,`event ${p.type}`,async()=>{for(let y of ye.get(p.type)??[])if(!(y.bucket!==void 0&&nd(p)!==y.bucket))try{await y.call(p,{requestId:c})}catch(m){throw u=y.name,m}})}catch(y){return _.error(`[palbase] ${u??"the delivery"} failed on ${p.type} ${p.id}; the platform delivers it again`,{error:y}),$({status:500,code:"handler_failed",message:"The event could not be handled"},c)}return ve.add(p.id),ve.size>nt&&ve.delete(ve.values().next().value),new Response(null,{status:204,headers:{"x-request-id":c}})}finally{ee.delete(p.id)}}async function Tt(i,c={}){let p=i.headers.get("origin");if(f&&p!==null){let u=f.allows(p);if(i.method==="OPTIONS"&&i.headers.has("access-control-request-method"))return u?new Response(null,{status:204,headers:f.preflight(p,i.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let y=await Xn(i,c);if(u)for(let[m,w]of Object.entries(f.headers(p)))m==="vary"?Zt(y.headers,w):y.headers.set(m,w);else Zt(y.headers,"Origin");return y}return Xn(i,c)}async function st(i,c,p,u){if(!i.headers.get(p.scheme.header))return $e(p,"missing_signature",u);let y={headers:i.headers,body:await wt(i,p.scheme.maxBytes(z)),url:rs(i,c)},m;try{m=p.scheme.check(y,T()/1e3)}catch{return $e(p,"signature_mismatch",u,"check_failed")}if(typeof m=="string")return $e(p,m,u);let w=p.events.get(m.type);if(!w)return _.info(`[palbase] webhook ${p.name}: no @On takes "${m.type}"; acknowledged`),ce(200,{ok:!0,handled:!1},u);let A=Q.get(p.name),O=m.event,M=[];if(m.id!==void 0){if(A.seen.has(m.id))return ce(200,{ok:!0,handled:!1,duplicate:!0},u);M=[m.id]}else if(m.ids&&Array.isArray(O)){let x=m.ids,S=O.map((j,Z)=>[j,x[Z]]).filter(([,j])=>j===void 0||!A.seen.has(j));if(S.length===0)return ce(200,{ok:!0,handled:!1,duplicate:!0},u);O=S.map(([j])=>j),M=S.flatMap(([,j])=>j===void 0?[]:[j])}if(M.some(x=>A.inflight.has(x)))return $({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},u);ue(O);for(let x of M)A.inflight.add(x);let P;try{P=await Xe(e.database,null,void 0,`webhook ${p.name}`,()=>w.call(O,{env:G,requestId:u,environmentId:e.projectId??""}))}catch(x){let S=Bn(x,`webhook ${p.name}`)??od(x,p.name);return S?$(S,u):(_.error(`[palbase] ${w.name} failed on ${p.name} "${m.type}"; the sender delivers it again`,{error:x}),$({status:500,code:"handler_failed",message:"The event could not be handled"},u))}finally{for(let x of M)A.inflight.delete(x)}for(let x of M)A.seen.add(x),A.seen.size>nt&&A.seen.delete(A.seen.values().next().value);return Qt(P,p,u)}function Qt(i,c,p){if(i instanceof Response)return i;if(typeof i=="string"){let u=c.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(i,{status:200,headers:{"content-type":u,"x-request-id":p}})}return ce(200,i??{ok:!0,handled:!0},p)}function $e(i,c,p,u=c){let y=te.get(i.name);y.counts.set(u,(y.counts.get(u)??0)+1);let m=T();return(y.at===void 0||m-y.at>=Ii)&&(V(i.name),y.at=m),$({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${c}`},p)}function V(i){let c=te.get(i).counts;if(c.size===0)return;let p=[...c.values()].reduce((u,y)=>u+y,0);_.warn(`[palbase] webhook ${i}: ${p} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(c)}),c.clear()}function Ue(i){let c=i.split("/").filter(Boolean);return c.length===2&&c[0]==="webhooks"?N.get(c[1]):void 0}async function Le(i,c,p,u){let y=c.pathname===et;if(i.method!==(y?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:y?"The crons are listed with GET":"A cron is run with POST"},u);let m=y?new Uint8Array(0):await wt(i,Ui);try{await St({secret:p,signature:i.headers.get("palbase-signature"),body:m,now:e.now})}catch(H){if(H instanceof dt)return $({status:401,code:"invalid_signature",message:`The crons are the platform's to call: ${H.code}`},u);throw H}if(y){let H=[...h.values()].map(({declaration:F})=>({name:F.name,schedule:F.schedule,time_zone:F.timeZone,timeout:F.timeout,retry:F.retries}));return ce(200,{crons:H},u,{"cache-control":"no-store"})}let w=c.pathname.slice(et.length+1),A=h.get(w);if(!A)return $({status:404,code:"cron_not_found",message:`This version has no cron ${JSON.stringify(w)}`},u);let O;try{O=JSON.parse(new TextDecoder().decode(m))}catch{return $({status:400,code:"bad_request",message:"A run is the JSON {cron, run_id, scheduled_at, attempt}"},u)}let{cron:M,run_id:P,scheduled_at:x,attempt:S}=O??{};if(M!==w||typeof P!="string"||P===""||typeof x!="string"||!Ks.test(x)||Number.isNaN(Date.parse(x))||!Number.isInteger(S)||S<1)return $({status:400,code:"bad_request",message:`A run of ${w} is the JSON {cron: "${w}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},u);let j=`${P}#${String(S)}`;if(U.has(j))return new Response(null,{status:204,headers:{"x-request-id":u}});if(q.has(j))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},u);q.add(j);let Z={env:G,environmentId:e.projectId??"",cron:w,runId:P,scheduledAt:new Date(x),attempt:S};try{await bt(e.database,e.database?Vt:void 0,i.signal,`cron ${w}`,async()=>{if(await A.run(Z),i.signal.aborted)throw new Error(`the platform gave up on this attempt of ${w} before it ended`)})}catch(H){return i.signal.aborted||_.error(`[palbase] cron ${w} failed (run ${P}, attempt ${String(S)})`,{error:H}),$({status:500,code:"cron_failed",message:`The cron ${w} failed; the platform tries it again`},u)}finally{q.delete(j)}return U.add(j),U.size>nt&&U.delete(U.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}})}let at=async({task:i,id:c,attempt:p,payload:u,createdAt:y},m)=>{let w=g.get(i);if(!w)return{status:404,message:`this version has no task ${JSON.stringify(i)}`};let A=ue(u??null),O=w.declaration.payload;if(O){let P=await O["~standard"].validate(A);if(P.issues){let x=P.issues.slice(0,5).map(S=>`${(S.path??[]).map(j=>String(typeof j=="object"&&j!==null&&"key"in j?j.key:j)).join(".")||"(payload)"}: ${S.message}`).join("; ");return _.error(`[palbase] task ${i} ${c}: what it carries is not what it takes \u2014 it fails, not to be tried again: ${x}`),{status:422,message:`what it carries is not what @Task "${i}" takes: ${x}`}}A=P.value}let M={env:G,environmentId:e.projectId??"",task:i,id:c,attempt:p,createdAt:y};try{await bt(e.database,e.database?Vt:void 0,m,`task ${i}`,async()=>{if(await w.run(A,M),m.aborted)throw new Error(`the platform gave up on this attempt of ${i} before it ended`)})}catch(P){return P instanceof Pt?(_.error(`[palbase] task ${i} ${c} can never be done: ${P.message}`),{status:422,message:P.message}):(m.aborted||_.error(`[palbase] task ${i} failed (task ${c}, attempt ${String(p)})`,{error:P}),{status:500,message:`the task ${i} failed; it is tried again`})}return{status:204}};async function da(i,c,p,u){let y=c.pathname===tt;if(i.method!==(y?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:y?"The task types are listed with GET":"A task is run with POST"},u);let m=y?new Uint8Array(0):await wt(i,Li);try{await St({secret:p,signature:i.headers.get("palbase-signature"),body:m,now:e.now})}catch(H){if(H instanceof dt)return $({status:401,code:"invalid_signature",message:`The tasks are the platform's to call: ${H.code}`},u);throw H}if(y){let H=[...g.values()].map(({declaration:F})=>({name:F.name,timeout:F.timeout,retry:F.retries,concurrency:F.concurrency}));return ce(200,{tasks:H},u,{"cache-control":"no-store"})}let w=c.pathname.slice(tt.length+1),A;try{A=JSON.parse(new TextDecoder().decode(m))}catch{return $({status:400,code:"bad_request",message:"A task is the JSON {task, id, attempt, payload, created_at}"},u)}let{task:O,id:M,attempt:P,payload:x,created_at:S}=A??{};if(O!==w||typeof M!="string"||M===""||typeof S!="string"||!Ks.test(S)||Number.isNaN(Date.parse(S))||!Number.isInteger(P)||P<1)return $({status:400,code:"bad_request",message:`A task of ${w} is the JSON {task: "${w}", id, attempt (1 or more), payload, created_at (RFC 3339)}`},u);let j=`task:${M}#${String(P)}`;if(U.has(j))return new Response(null,{status:204,headers:{"x-request-id":u}});if(q.has(j))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},u);q.add(j);let Z;try{Z=await at({task:w,id:M,attempt:P,payload:x,createdAt:new Date(S)},i.signal)}finally{q.delete(j)}return Z.status===404?$({status:404,code:"task_not_found",message:Z.message??""},u):Z.status===422?$({status:422,code:"task_failure",message:Z.message??""},u):Z.status>=300?$({status:Z.status,code:"task_failed",message:Z.message??""},u):(U.add(j),U.size>nt&&U.delete(U.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}}))}async function ot(i,c,p,u){if(i.method!=="POST")return $({status:405,code:"method_not_allowed",message:`${u} is POSTed`},p);let y;try{cr({signature:i.headers.get("palbase-signature"),now:e.now}),y=await wt(i,1048576),await St({secret:c,signature:i.headers.get("palbase-signature"),body:y,now:e.now})}catch(w){if(w instanceof dt)return $({status:401,code:"invalid_signature",message:`${u} is the platform's to call: ${w.code}`},p);throw w}let m;try{m=JSON.parse(new TextDecoder().decode(y))}catch{return $({status:400,code:"bad_request",message:`${u} is JSON`},p)}return typeof m!="object"||m===null||!Object.hasOwn(m,"call")||m.call!==new URL(i.url).pathname?$({status:401,code:"invalid_signature",message:`${u} is the platform's to call: signed_for_another_call`},p):{body:m}}async function ca(i,c,p,u,y){let m=await ot(c,p,u,`An upload's ${i}`);if(m instanceof Response)return m;let w=Ir(i,m.body);if(typeof w=="string")return $({status:400,code:"bad_request",message:`An upload's ${i}: ${w}`},u);if(i==="complete"){if(ge.has(w.uploadId))return $({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},u);ge.add(w.uploadId),ge.size>nt&&ge.delete(ge.values().next().value)}let A=Ln(n,w.method,w.route);if(!A||"malformed"in A||!A.route.meta.upload)return $({status:404,code:"not_found",message:`No upload route for ${w.method} ${w.route}`},u);let{route:O,params:M}=A,P=A.route.meta.upload,x=Zi(w.user);if(x&&er(y,x.id),r.get(O).required&&!x)throw new X(401,"unauthorized","This route needs a signed-in user");if(i==="authorize"){let Z=J(O);if(Z!==!1){let F=R.takeEach(`${O.id}\0${jr(w.user,w.client)}`,Z);if(F!==void 0)throw new X(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:F},F)}let H=Ur(P.pathTemplate,{userId:x?.id??null,uploadId:w.uploadId,filename:w.filename});if("problem"in H)throw new X(400,"bad_request",H.problem);return await Xe(e.database,jt(w.user),c.signal,O.id,async()=>{let F={request:c,query:new URLSearchParams(w.query),params:M,user:x,body:w.body===void 0||w.body===null?{}:ue(w.body),requestId:u};await Qn(O,F);for(let _e of O.params)(_e.kind==="query"||_e.kind==="body"&&w.body!==void 0)&&await na(_e,F)}),ce(200,{bucket:P.bucket,path:H.path},u)}y.endpoint=O.id.slice(O.id.indexOf(" ")+1);let S=new URLSearchParams(w.query),j=w.body===null||w.body===void 0?{}:ue(w.body);return qn(await Xt(O,{request:c,query:S,params:M,user:x,body:j,requestId:u,uploadedObject:ue(w.uploadedObject)},jt(w.user)),void 0,u)}async function ua(i,c,p,u){let y=c.pathname.slice(Mt.length+1),m=y.endsWith("/undo"),w=m?y.slice(0,-5):y,A=await ot(i,p,u,"A test user template");if(A instanceof Response)return A;let O=b.get(w);if(!O)return $({status:404,code:"template_not_found",message:Pr(w,[...b.keys()])},u);if(m&&!O.undo)return $({status:404,code:"no_undo",message:`@TestUserTemplate "${w}" has no undo: the user's deletion cleans up after it`},u);let M=xr(w,A.body);if(typeof M=="string")return $({status:400,code:"bad_request",message:`A test user template's call: ${M}`},u);let P=ue(M.user),x;try{x=await Rr(e.server,P.id)}catch(H){return _.error(`[palbase] test user template ${w}: auth could not say whether ${P.id} is a test user; nothing was written`,{error:H}),$({status:503,code:"auth_unavailable",message:"Auth could not say whether the user is a test user: the template did not run",retryAfter:5},u)}if(!x)return _.warn(`[palbase] test user template ${w}${m?" undo":""}: auth does not say ${P.id} is a test user \u2014 nothing was run`),$({status:403,code:"not_a_test_user",message:"Auth does not say this user is a test user: a template writes for test users alone"},u);let S=`${P.id}\0${w}`;if(B.has(S))return $({status:409,code:"in_progress",message:`The template ${w} is being written for this user`,retryAfter:5},u);if(!m&&k.has(S))return ce(200,{rows:k.get(S)},u);B.add(S);let j={env:G,environmentId:e.projectId??"",template:w},Z=`test user template ${w}${m?" undo":""}`;try{let H={};return await bt(e.database,e.database?Vt:void 0,i.signal,Z,async()=>{if(m?await O.undo(P,j):(await O.seed(P,j),H=await Or(ne.getStore()?.database)),i.signal.aborted)throw new Error(`the platform gave up on ${Z} before it ended`)}),m?(k.delete(S),new Response(null,{status:204,headers:{"x-request-id":u}})):(k.set(S,H),k.size>nt&&k.delete(k.keys().next().value),ce(200,{rows:H},u))}catch(H){i.signal.aborted||_.error(`[palbase] ${Z} failed for ${P.id}: nothing of it was kept`,{error:H});let F=H instanceof Error&&H.message!==""?`: ${H.message.replace(/\s+/g," ").slice(0,300)}`:"";return $({status:500,code:m?"undo_failed":"template_failed",message:`${m?"The undo of":"The template"} ${w} failed${F}; nothing of it was kept`},u)}finally{B.delete(S)}}function Zn(i,c,p,u){let y=i?{sub:i.id,role:"authenticated"}:null;return ne.run({requestId:ne.getStore()?.requestId??"",...i?{userId:i.id}:{}},()=>Xe(e.database,y,p,c,async()=>{let m=await u();if(p.aborted)throw new Error(`the platform gave up on ${c} before it ended`);return m}))}let Yn=(i,c)=>new Response(i,{status:200,headers:{"content-type":"application/json","x-request-id":c}});async function la(i,c,p){let u=await ot(i,c,p,"A tool call");if(u instanceof Response)return u;let y=u.body,m=y.tool;if(typeof m!="string"||m==="")return $({status:400,code:"bad_request",message:"A tool call is {tool, call_id, input, context}: tool names it"},p);let w=K.tools.get(m);if(!w)return $({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(m.slice(0,64))}`},p);let A=y.call_id,O=ks(y.context);if(typeof A!="string"||A===""||A.length>256||typeof O=="string")return $({status:400,code:"bad_request",message:`A call of ${m} is {tool, call_id, input, context}${typeof O=="string"?`: ${O}`:""}`},p);let M=sa("sha256").update(JSON.stringify(y)).digest("hex"),P=he.answered(A);if(P!==void 0)return P.digest!==M?$({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},p):Yn(P.answer,p);if(he.isRunning(A))return $({status:409,code:"in_progress",message:"This call is running",retryAfter:2},p);he.start(A);let x;try{let S=await Zn(O.user,`ai.tool ${m}`,i.signal,()=>w.call(ue(y.input??{}),{...O,callId:A,signal:i.signal,inject:le(`ai.tool ${m}`)}));x="deferred"in S?JSON.stringify({deferred:!0,...S.expires_in_seconds!==void 0?{expires_in_seconds:S.expires_in_seconds}:{}}):JSON.stringify({output:S.output,is_error:S.is_error,...S.workspace_tree!==void 0?{workspace_tree:S.workspace_tree}:{}});let j=new TextEncoder().encode(x).byteLength;if(j>Ye){_.error(`[palbase] ai.tool ${m} answered ${j} bytes (call ${A}): a machine's answer is ${Ye} at most; the agent is told it failed`);let Z="deferred"in S?void 0:S.workspace_tree;x=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${Ye/(1<<20)} MiB it may be`}],is_error:!0,...Z!==void 0?{workspace_tree:Z}:{}})}}catch(S){if(i.signal.aborted)return he.end(A,void 0),$({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},p);_.error(`[palbase] ai.tool ${m} failed (call ${A}, chat ${O.chatId}); the agent is told`,{error:S});let j=gs(S);x=JSON.stringify({output:[{type:"text",text:Wi(S)}],is_error:!0,...j!==void 0?{workspace_tree:j}:{}})}return he.end(A,{digest:M,answer:x}),Yn(x,p)}async function fa(i,c,p){let u=await ot(i,c,p,"An agent's turn");if(u instanceof Response)return u;let y=vs(u.body);if(typeof y=="string"||y.agent==="")return $({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata, message}${typeof y=="string"?`: ${y}`:": agent names it"}`},p);let m=y.agent,w=K.agents.get(m);if(!w)return $({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(m.slice(0,64))}`},p);let A;try{A=await Zn(y.user,`ai.agent ${m}`,i.signal,()=>w.resolve({...y,signal:i.signal,inject:le(`ai.agent ${m}`)}))}catch(P){if(i.signal.aborted)return $({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},p);let x=Bn(P,`ai.agent ${m}`);return x?$(x,p):(_.error(`[palbase] ai.agent ${m} failed for chat ${y.chatId}; the turn is not started`,{error:P}),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},p))}let O=A.tools.find(P=>K.tools.get(P.name)!==P);if(O)return _.error(`[palbase] ai.agent ${m} handed out ai.tool ${JSON.stringify(O.name)}, which this app did not declare when it was made \u2014 make each ai.tool once, at a module's top level, and hand that one out`),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},p);let M=JSON.stringify(A.definition);return new TextEncoder().encode(M).byteLength>Ye?(_.error(`[palbase] ai.agent ${m}'s definition is larger than the ${Ye} bytes a machine's answer may be`),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},p)):new Response(M,{status:200,headers:{"content-type":"application/json","x-request-id":p,"cache-control":"no-store"}})}async function pa(i,c,p,u){let y=await ot(c,p,u,`A gateway's ${i}`);if(y instanceof Response)return y;let m=await W.serve(i,y.body,c.signal);return"code"in m?$({status:m.status,code:m.code,message:m.message,retryAfter:m.retryAfter},u):"body"in m?ce(200,m.body,u):new Response(null,{status:204,headers:{"x-request-id":u}})}async function Qn(i,c){let p=[],u={params:Object.freeze({...c.params}),user:ue(c.user),headers:i.meta.upload?new Headers:c.request.headers,requestId:c.requestId};for(let y of i.params)y.kind==="resolve"&&(p[y.index]=await l.get(y).resolve(u,y.options));return p}async function Xt(i,c,p,u){let y=t.get(i.controller),m=await Xe(e.database,p,c.request.signal,i.id,async()=>{let w=await Qn(i,c);for(let O of i.params)O.kind!=="resolve"&&(w[O.index]=await na(O,c));u?.ran();let A=await y[i.fn](...w);if(c.uploadedObject&&c.request.signal.aborted)throw new Error(`storage gave up on ${i.id}'s upload before it was answered`);return u?u.record(Zs(ea(A,c.requestId),ne.getStore()?.usedLocales)):A});return u?m:Zs(ea(m,c.requestId),ne.getStore()?.usedLocales)}async function Xn(i,c){let p=i.headers.get("x-request-id")??"",u=Yi.test(p)?p:`req_${crypto.randomUUID()}`,y=performance.now(),m=new URL(i.url).pathname,w={endpoint:m},A=await ma(i,c,u,w);return e.telemetry?.record({requestId:u,method:i.method,endpoint:w.endpoint,path:m,status:A.status,durationMs:performance.now()-y,userId:w.userId}),A}function er(i,c){i.userId=c;let p=ne.getStore();p&&(p.userId=c)}async function ma(i,c,p,u){let y=e.strings,m=y?{requestId:p,strings:y,locales:br(i.headers.get("accept-language"),y.source),usedLocales:[]}:{requestId:p},w=await ha(m,i,c,p,u);return y&&Zt(w.headers,"Accept-Language"),w}async function ha(i,c,p,u,y){return ne.run(i,async()=>{let m=new URL(c.url),w=`${c.method} ${m.pathname}`;try{if(m.pathname===Mn&&ye.size>0)return c.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},u):e.webhookSecret?await Yt(c,u):$({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},u);let A=Ue(m.pathname);if(A)return w=`webhook ${A.name}`,c.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},u):await st(c,m,A,u);if(e.platform&&(m.pathname===et||m.pathname.startsWith(`${et}/`)))return w=m.pathname===et?"crons":`cron ${m.pathname.slice(et.length+1)}`,await Le(c,m,e.platform.secret,u);if(e.platform&&(m.pathname===tt||m.pathname.startsWith(`${tt}/`)))return w=m.pathname===tt?"tasks":`task ${m.pathname.slice(tt.length+1)}`,await da(c,m,e.platform.secret,u);if(e.platform&&(m.pathname===gn||m.pathname===Cr)){let C=m.pathname===gn?"authorize":"complete";return w=`upload ${C}`,await ca(C,c,e.platform.secret,u,y)}if(e.platform&&m.pathname.startsWith(`${yn}/`)){let C=m.pathname.slice(yn.length+1);return w=`gateway ${C}`,await pa(C,c,e.platform.secret,u)}if(e.platform&&m.pathname===ms)return w="ai tool call",await la(c,e.platform.secret,u);if(e.platform&&m.pathname===hs)return w="ai agent's turn",await fa(c,e.platform.secret,u);if(e.platform&&m.pathname.startsWith(`${Mt}/`))return w=`test user template ${m.pathname.slice(Mt.length+1)}`,await ua(c,m,e.platform.secret,u);if(a&&m.pathname===Un){if(w="attest challenge",c.method!=="GET")return $({status:405,code:"method_not_allowed",message:"A challenge is asked for with GET"},u);let C=c.headers.get(oe.anchor)??"";if(C==="")return $({status:400,code:"installation_anchor_required",message:`A challenge is for an installation: send ${oe.anchor}`},u);if(!Ni.test(C))return $({status:400,code:"invalid_installation_anchor",message:`${oe.anchor} is the installation anchor auth issued (ins_\u2026)`},u);let fe=R.takeEach(`attest challenge\0a:${yt(c.headers,p.remoteAddress)}`,[Di]);if(fe!==void 0)return $({status:429,code:"too_many_requests",message:"Too many challenges asked for from this address",retryAfter:fe},u);let Ie=await a.challengeFor(C);if("unavailable"in Ie)return $({status:503,code:"attest_unavailable",message:"The device's attestation cannot be checked right now",retryAfter:1},u);let Ce={"cache-control":"no-store","x-request-id":u};return Ie.challenge&&(Ce[oe.challenge]=Ie.challenge),new Response(null,{status:204,headers:Ce})}if(id(m.pathname))return $({status:404,code:"not_found",message:`No route for ${c.method} ${m.pathname}`},u);let O=Ln(n,c.method,m.pathname);if(O&&"malformed"in O)return $({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},u);if(!O)return $({status:404,code:"not_found",message:`No route for ${c.method} ${m.pathname}`},u);let{route:M,params:P}=O;if(w=M.id,y.endpoint=M.id.slice(M.id.indexOf(" ")+1),M.meta.upload)throw new X(400,"upload_required",`${M.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let x=r.get(M),S=null,j=null,Z=c.headers.get("authorization")??"",H=/^(bearer|dpop)\s+(\S+)$/i.exec(Z),F=H?.[2],_e=H?.[1].toLowerCase()==="dpop";if(F)try{let C=!_e&&e.tokens&&!Qi.test(F)&&e.tokens.accepts(F)?e.tokens:void 0,fe=C?await I.ask(F,yt(c.headers,p.remoteAddress),()=>Xe(e.database,null,c.signal,"token",()=>C.resolve(F))):await e.verifier.verify(F,_e?{proof:c.headers.get("dpop"),method:c.method,url:lr(c.headers,m)}:void 0);S=Ji(fe),j=fe.claims}catch(C){if(!x.required&&(C instanceof At||C instanceof xt||C instanceof kt))S=null;else throw C instanceof kt?new X(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:C.wait},C.wait):C instanceof At?new X(401,"invalid_token","The access token is not valid",{reason:C.reason},void 0,zi(C.reason)):C}else if(Z!==""&&x.required)throw new X(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(S&&er(y,S.id),x.required&&!S)throw new X(401,"unauthorized","This route needs a signed-in user");if(x.verifiedEmail&&!S?.emailVerified)throw new X(403,"email_not_verified","This route needs a verified email address");if(S&&Xs(S.acr)<Xs(x.aal))throw new X(401,"insufficient_user_authentication",`This route needs a sign-in at ${x.aal}: step up and call again`,Vs(x),void 0,Js(x,_e));if(S&&x.maxAge!==null&&!Bi(S.authTime,x.maxAge,Date.now()))throw new X(401,"insufficient_user_authentication",`This route needs the user to have signed in or stepped up within the last ${x.maxAge} seconds: step up and call again`,Vs(x),void 0,Js(x,_e));let tr=J(M);if(tr!==!1){let C=S?`u:${S.id}`:`a:${yt(c.headers,p.remoteAddress)}`,fe=R.takeEach(`${M.id}\0${C}`,tr);if(fe!==void 0)throw new X(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:fe},fe)}let Oe=c.method==="GET"||c.method==="HEAD"?void 0:await wt(c,z),en,nr=null;if(a&&s(M)){let C=await a.check(c,m,Oe,p.target);if("unavailable"in C)throw new X(503,"attest_unavailable","The device's attestation cannot be checked right now",void 0,1);if(!C.pass)throw new X(401,"app_attest_required","This route is called by the app on a device that attests",{reason:C.reason,challenge:C.challenge},void 0,void 0,{[oe.challenge]:C.challenge});en=C.challenge,nr=C.device??null}let $t=Oe===void 0?void 0:Ki(Oe),tn=m.searchParams,Pe=o.get(M),_t=c.headers.get(Et),it=Pe!==void 0||_t!==null?await d(M,P,_t,c.method):void 0;if(it&&Pe)try{if(Pe.body.length>0&&$t!==void 0&&($t=await it.open($t,"/body",Pe.body)),Pe.query.length>0){let C=await it.open(Object.fromEntries(m.searchParams),"/query",Pe.query);tn=new URLSearchParams(m.searchParams);for(let fe of Pe.query){let Ie=ir(fe.slice(7)),Ce=C[Ie];Ce!==void 0&&tn.set(Ie,typeof Ce=="string"?Ce:JSON.stringify(Ce))}}}catch(C){throw ta(C)}let rr={request:c,query:tn,params:P,user:S,body:$t,raw:Oe,requestId:u,attested:nr},sr=E&&Oe!==void 0&&mt(M)?Cs(c.method,c.headers):void 0;if(!E||sr===void 0)return Ys(await qn(await Xt(M,rr,j),it,u),en);let ga={role:Hn(e.database.requests,j).role,uid:S?.id??`a:${yt(c.headers,p.remoteAddress)}`},ar=!1,ya=_t!==null?{uri:`${m.pathname}${m.search}`,body:sd(new TextEncoder().encode(`${_t}
|
|
21
|
-
`),Oe)}:{uri:`${m.pathname}${m.search}`,body:Oe},
|
|
20
|
+
$answer$`,{drop:"DROP FUNCTION IF EXISTS palbase.idempotency_answer(text, timestamptz, integer, jsonb, text)"})]}),Vo={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},Zo={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},Yo={status:409,code:"idempotency_key_in_use",message:"This request's Idempotency-Key was taken over by a retry; what it did is not kept",retryAfter:1},Os={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},It=class extends Error{};function mt(e){return Cs.has(e.method)&&e.meta.upload===void 0}function Ms(e,t){if(!Cs.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function Qo(e,t){return js([e.role,e.uid,t]).digest("hex")}function Xo(e){return js([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function js(e){let t=Lo("sha256");for(let n of e)t.update(n).update("\0");return t}function ei(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function Pn(e){return e<500&&e!==429&&e!==499}function ti(e,t){return t&&Pn(e)}function Ds(e){let t=e["~standard"].jsonSchema?.input,n;try{n=t?.({target:"draft-2020-12"})}catch{return!1}let r=n?.properties;return typeof r=="object"&&r!==null&&Object.keys(r).some(s=>s.toLowerCase()==="idempotency-key")}var ni={role:"service",claims:{}},ri={seal:e=>e,open:async e=>e},qt=class{db;answers;constructor(t,n=ri){this.db=t,this.answers=n}async serve(t,n,r){if(t.key.length>Es)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${Es} characters`});let s;try{s=await this.begin(Qo(t.caller,t.key),Xo(t))}catch(d){return _.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:d}),r.refusal(Os)}if("kept"in s){let d;try{d=s.kept.body===null?null:await this.answers.open(s.kept.body)}catch(l){return _.warn("[palbase] the answer kept against an Idempotency-Key could not be opened; the write is not run again",{error:l}),r.refusal(Os)}return si({...s.kept,body:d},r.requestId)}if("refused"in s)return r.refusal(s.refused==="reused"?Vo:Zo);let a=s.claim,o;try{o=await n(d=>this.record(a,d))}catch(d){if(d instanceof It)return r.refusal(Yo);let l=r.failure(d);return ti(l.status,r.ran())&&!qo(d)?this.keep(a,l):(await this.release(a),l)}return Pn(o.status)||await this.release(a),o}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:Rn({hours:As})}}}))}async begin(t,n){return Io(Ko)===0&&await this.sweep().catch(r=>_.warn("[palbase] the expired Idempotency-Keys could not be taken away; the next sweep tries again",{error:r})),this.asService(async r=>{for(let s=0;s<3;s++){let[a]=await r.insertMany([{key:t,fingerprint:n}],{onConflict:["key"],action:"ignore"});if(a)return{claim:{key:t,started:a.started_at}};if(await r.deleteMany({where:{key:t,started_at:{lt:Rn({hours:As})}}})>0)continue;let o=await r.findUnique({where:{key:t}});if(o===null)continue;let d=ei(o,n);if(d==="reused")return{refused:"reused"};if(d==="replay")return{kept:{status:o.status_code,headers:o.response_headers??[],body:o.response_body}};let[l]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:Rn({seconds:Ss})}},set:{started_at:$s()}});return l?{claim:{key:t,started:l.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!Pn(n.status))return n;let{response:r,kept:s}=await Ps(n),a=ne.getStore()?.database;if(!a)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let o=s.body===null?null:this.answers.seal(s.body),[d]=await a.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,s.status,JSON.stringify(s.headers),o]);if(d?.answered!==!0)throw new It;return r}async keep(t,n){let{response:r,kept:s}=await Ps(n);try{await this.asService(a=>a.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:$s(),status_code:s.status,response_headers:s.headers,response_body:s.body===null?null:this.answers.seal(s.body)}}))}catch(a){_.warn("[palbase] a refusal could not be kept against its Idempotency-Key; a retry runs it again once the key is stale",{error:a})}return r}async release(t){if(await this.releaseOnce(t))return;let n=Date.now()+Ss*1e3,r=()=>{Date.now()+Rs>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},Rs).unref()};r()}async releaseOnce(t){try{return await this.asService(n=>n.deleteMany({where:{key:t.key,started_at:t.started,completed_at:null}})),!0}catch{return!1}}async asService(t){let n=this.db.request(ni),r;try{r=await t(n.database.palbase.idempotency_keys)}catch(s){throw await n.rollback(s).catch(()=>{}),s}try{await n.commit()}catch(s){throw await n.rollback(s).catch(()=>{}),s}return r}};function si(e,t){let n=new Headers(e.headers);return n.set("x-request-id",t),n.set("idempotent-replayed","true"),new Response(e.body===null?null:Buffer.from(e.body,"base64"),{status:e.status,headers:n})}var Lt=Symbol("waits"),Cn=new WeakMap;function Ht(e,t){return Cn.set(e,t),e}async function ai(e){for(let t=0;t<e;t++)await Promise.resolve();return Lt}function oi(e){return Promise.race([e,ai(8)])}async function Ps(e){let t=[];e.headers.forEach((d,l)=>{l!=="x-request-id"&&t.push([l,d])});let n=d=>new Response(d,{status:e.status,statusText:e.statusText,headers:e.headers});if(Cn.has(e)){let d=Cn.get(e)??null;if(d===null||d.byteLength===0)return{response:n(d===null?null:Buffer.from(d)),kept:{status:e.status,headers:t,body:null}};let l=Buffer.from(d);return l.byteLength>xs?{response:n(l),kept:{status:e.status,headers:t.filter(([h])=>h!=="content-length"&&h!=="content-encoding"),body:null}}:{response:n(l),kept:{status:e.status,headers:t,body:l.toString("base64")}}}if(e.body===null)return{response:n(null),kept:{status:e.status,headers:t,body:null}};let r=e.body.getReader(),s=[],a=0;for(;;){let d=r.read(),l=await oi(d);if(l!==Lt&&l.done)break;if(l!==Lt&&(s.push(l.value),a+=l.value.byteLength,a<=xs))continue;let h=l===Lt?d:void 0,g=new ReadableStream({start(b){for(let k of s)b.enqueue(k)},async pull(b){let k=await(h??r.read());h=void 0,k.done?b.close():b.enqueue(k.value)},cancel:b=>r.cancel(b)});return{response:n(g),kept:{status:e.status,headers:t.filter(([b])=>b!=="content-length"&&b!=="content-encoding"),body:null}}}let o=Buffer.concat(s);return{response:n(o),kept:{status:e.status,headers:t,body:o.byteLength===0?null:o.toString("base64")}}}import{createHash as ii}from"node:crypto";var jn="/webhooks/palbase",Hs="PalbaseErrorEnvelope",Ns="PalbaseBearer",di={$ref:`#/components/schemas/${Hs}`},ci={type:"object",description:"Every refusal: the framework's, a handler's HttpError, the database's.",properties:{error:{type:"string",description:"A stable code, like bad_request"},error_description:{type:"string",description:"What went wrong, for a person"},status:{type:"integer",description:"The HTTP status"},request_id:{type:"string",description:"The request's id, as the app's log has it"},data:{description:"Details, when the refusal has them: a validation's fields, a token's reason, a limit's retryAfter"}},required:["error","error_description","status","request_id"]},Us={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Qe={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function Bs(e,t,n){let r={[Hs]:ci},s={},a=[],o=[],d=new Set,l=new Map;for(let f of e){let T=o.find(V=>mi(V,f));if(T){a.push({route:f.id,handler:Ls(f),answeredBy:T.id});continue}o.push(f);let R=f.segments.map(V=>typeof V=="string"?V:"{}").join("/");l.has(R)||l.set(R,gi(f.segments.flatMap(V=>typeof V=="string"?[]:[V.param])));let L=l.get(R),G=0,z=`/${f.segments.map(V=>typeof V=="string"?V:`{${L[G++]}}`).join("/")}`,I=t(f),N=Bt(hi(f),d),F=f.method!=="GET"&&f.method!=="HEAD",Q=V=>{let Ue=f.params.filter(Le=>Le.kind===V&&Le.schema).map((Le,at)=>Ft(Le.schema,`${N}.${V}${at===0?"":`.${at+1}`}`,r));return Ue.length===0?void 0:Ue.length===1?Ue[0]:{allOf:Ue}},te=L.map(V=>({name:V,in:"path",required:!0,schema:{type:"string"}})),rt=Q("query");rt&&te.push(...qs(rt,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:rt}]);let vt=Q("headers");vt&&te.push(...qs(vt,"header")??[]);let ye=n.idempotency===!0&&mt(f);ye&&te.push({...Mn,schema:{...Mn.schema}});let ve=F?Q("body"):void 0,ee={operationId:N};f.controller.name!==""&&(ee.tags=[f.controller.name]),te.length>0&&(ee.parameters=te),ve&&(ee.requestBody={required:!vi(ve),content:{"application/json":{schema:ve}}});let Yt=f.params.some(V=>V.schema!==void 0),Tt=n.routes?.(f),st=$i(N,Tt?.throws??[],n.errors);ee.responses={...Ti(Tt,N,r),...Si(I,{validates:Yt,hasPathParams:L.length>0,readsBody:F,keyed:ye}),...Ei(st,N,r)},st.length>0&&(ee["x-palbase-errors"]=_i(N,st)),I.auth.required&&(ee.security=[{[Ns]:[]}]),ee["x-palbase-handler"]=Ls(f);let Qt=f.params.some(V=>V.kind==="optionalUser")||n.databaseSeesCaller;ee["x-palbase-auth"]=I.auth.required?"required":Qt?"optional":"public",ee["x-palbase-verified-email"]=I.auth.verifiedEmail,I.auth.aal!=="aal1"&&(ee["x-palbase-aal"]=I.auth.aal),I.auth.maxAge!==null&&(ee["x-palbase-max-age"]=I.auth.maxAge),I.attest&&(ee["x-palbase-attest"]=!0);let $e=I.limit===!1?!1:I.limit.map(V=>({max:V.max,window:V.window}));ee["x-palbase-rate-limit"]=$e===!1?!1:$e.length===1?$e[0]:$e,f.meta.upload&&(ee["x-palbase-upload"]={bucket:f.meta.upload.bucket,pathTemplate:f.meta.upload.pathTemplate}),(s[z]??={})[f.method.toLowerCase()]=ee}for(let f of n.webhooks??[]){let T={operationId:Bt(`webhooks.${f.name}`,d)};f.cls!==""&&(T.tags=[f.cls]),T.description=f.provider?`${Us[f.provider]??f.provider}'s deliveries: verified with ${Us[f.provider]??f.provider}'s signature scheme under the secret in ${f.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${f.signatureHeader} header: verified under the secret in ${f.secretEnv}, then handed to the @On of their event type.`,T.responses={200:{description:"Taken: { ok: true, handled } \u2014 handled is false when no @On takes the event's type, and duplicate is true for a delivery already run; or the handler's answer: a Response as it is, text as text, anything else as JSON",content:{"application/json":{},[f.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:re("invalid_signature: the delivery is not signed with the secret \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:re("in_progress: the same delivery is being handled; the sender delivers it again",Qe),413:re("payload_too_large: the body is over what this sender sends"),500:re("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:re("service_unavailable, auth_unavailable or database_unavailable: what the handler needs of the platform did not answer \u2014 the sender delivers it again after Retry-After",Qe)},T["x-palbase-webhook"]=f.provider?{provider:f.provider,secretEnv:f.secretEnv,events:f.events}:{signatureHeader:f.signatureHeader,secretEnv:f.secretEnv,events:f.events},s[`/webhooks/${f.name}`]={post:T}}let h=[...new Set(n.platformEvents??[])].sort();if(h.length>0){let f={operationId:Bt("webhooks.palbase",d)};f.description="The project's events, delivered by the platform to the app's machine: verified under the secret in PALBASE_WEBHOOK_SECRET, then handed to the @On of their type \u2014 user.deleted first to forgetting the rows the app keeps of that user.",f.responses={204:{description:"Taken: handled, or a delivery already run"},401:re("invalid_signature: the delivery is not the platform's \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:re("in_progress: the same event is being handled; the platform delivers it again",Qe),500:re("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:re("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let T=[...new Set(n.platformEventBuckets??[])].sort();f["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:h,...T.length>0?{buckets:T}:{}},s[jn]={post:f}}let g=n.gateways??[],b=fi(g,r),k=g.length>0,B=Object.fromEntries(g.filter(We).map(f=>[f.pattern,{events:b[f.name].events,messages:Object.fromEntries(Object.entries(b[f.name].messages).map(([T,R])=>[T,R.payload])),graceMs:f.graceMs,...f.logKeepSeconds>0?{logKeepSeconds:f.logKeepSeconds}:{}}])),U=Object.keys(B).length>0,q=g.filter(f=>!We(f)).map(f=>({pattern:f.pattern,kind:f.access,publish:f.publish,state_read:!1,state_write:!1,...f.logKeepSeconds>0?{log_keep_seconds:f.logKeepSeconds}:{}})),K=q.length>0,J=ui(n.ai?.agents??[]),le=Object.keys(J).length>0,he=li(n.ai?.tools??[]),ge=Object.keys(he).length>0,v={schemas:r,securitySchemes:{[Ns]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},E={openapi:"3.2.0",info:{title:"Palbase backend",version:ii("sha256").update(JSON.stringify({paths:s,components:v,unreachable:a,...k?{gateways:b}:{},...U?{rooms:B}:{},...K?{channels:q}:{},...le?{agents:J}:{},...ge?{aiTools:he}:{}})).digest("hex").slice(0,12),description:"The routes this app serves, as its decorators declare them, and \u2014 when its source was read as the contract was written \u2014 what each answers and the errors it throws (x-palbase-errors). Every refusal is the PalbaseErrorEnvelope; a declared error's carries its code and its data."},paths:s,components:v};return a.length>0&&(E["x-palbase-unreachable"]=a),k&&(E["x-palbase-gateways"]=b),U&&(E["x-palbase-room"]=B),K&&(E["x-palbase-channels"]=q),le&&(E["x-palbase-agents"]=J),ge&&(E["x-palbase-ai-tools"]=he),E}function ui(e){let t=new Map;for(let n of e){if(t.has(n.name))throw new Error(`ai.agent "${n.name}" is declared twice: an agent's name is its own \u2014 make each once, at a module's top level`);t.set(n.name,{...n.description!==void 0?{description:n.description}:{},...n.machine!==void 0?{machine:n.machine}:{}})}return Object.fromEntries([...t].sort(([n],[r])=>n<r?-1:n>r?1:0))}function li(e){let t=new Map;for(let n of e){let r=t.get(n.name);if(r)throw new Error(`ai tool "${n.name}" is declared twice (${r.kind===n.kind?`two ai.${n.kind==="backend"?"tool":"clientTool"}s`:"an ai.tool and an ai.clientTool"}): an agent is given one tool of a name \u2014 rename one of them`);t.set(n.name,{kind:n.kind,description:n.description,parameters:n.parameters,...n.approval?{approval:!0}:{},...n.kind==="backend"&&n.machine!==void 0?{machine:n.machine}:{}})}return Object.fromEntries([...t].sort(([n],[r])=>n<r?-1:n>r?1:0))}function fi(e,t){let n=[];for(let r of e){let s=(d,l,h,g)=>{let b=zt(`${r.name}_${d}_${l}`),k={},B=Ft(h,b,k,g);B.$ref===void 0&&(k[b]=B),pi(r.pattern,d,l,k[b]);for(let[U,q]of Object.entries(k)){if(Object.hasOwn(t,U)&&JSON.stringify(t[U])!==JSON.stringify(q))throw new Error(`@Gateway("${r.pattern}") ${d} "${l}": its schema is the component ${U}, which another gateway's names with another schema \u2014 rename one of them`);t[U]=q}return{$ref:`#/components/schemas/${b}`}},a=Object.fromEntries(Object.entries(r.events).map(([d,l])=>[d,s("event",d,l,"answered")])),o=Object.fromEntries(Object.entries(r.messages).map(([d,l])=>[d,{payload:s("message",d,l.schema,"sent"),...l.reply?{reply:s("reply",d,l.reply,"answered")}:{}}]));n.push([r.name,{pattern:r.pattern,...r.access?{access:r.access}:{},...r.logKeepSeconds>0?{durable:r.logKeepSeconds}:{},...r.chat?{chat:!0}:{},events:a,messages:o}])}return Object.fromEntries(n)}function pi(e,t,n,r){if(!(!ae(r)||!ae(r.properties))){for(let[s,a]of Object.entries(r.properties))if(a===!0||ae(a)&&Object.keys(a).length===0)throw new Error(t==="message"?`@Gateway("${e}") message "${n}" has an untyped field "${s}". Inbound payloads reach the server \u2014 declare the shape so it can be validated.`:`@Gateway("${e}") ${t} "${n}" has an untyped field "${s}". An untyped payload makes every generated client opaque \u2014 declare its shape.`)}}function mi(e,t){return e.method===t.method&&e.segments.length===t.segments.length&&e.segments.every((n,r)=>typeof n!="string"||n===t.segments[r])}function Ls(e){return`${e.controller.name}.${e.fn}`}function hi(e){let t=e.controller.name;if(t.endsWith("Controller")&&(t=t.slice(0,-10)),t!=="")return`${t[0].toLowerCase()}${t.slice(1)}.${e.fn}`;let n=r=>r.charAt(0).toUpperCase()+r.slice(1);return e.method.toLowerCase()+e.segments.map(r=>typeof r=="string"?n(r):`By${n(r.param)}`).join("")}function Bt(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function gi(e){let t=new Set;return e.map(n=>Bt(n,t))}function Ft(e,t,n,r="sent"){let s=e["~standard"],a=s.jsonSchema?.input;if(typeof a!="function")return{};let o;try{o=a({target:"draft-2020-12",libraryOptions:{unrepresentable:"any",...s.vendor==="zod"?{override:yi}:{}}})}catch{return{}}let d=zt(t);for(;Object.keys(n).some(l=>l===d||l.startsWith(`${d}.`));)d=`${d}_`;return wi(o,d,n,r)}function yi(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function wi(e,t,n,r){let s=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},a=!1,o=h=>h==="#"?(a=!0,`#/components/schemas/${t}`):h.startsWith("#/$defs/")?`#/components/schemas/${t}.${zt(ki(h.slice(8)))}`:h,d="all";if(r==="sent"){let h=new Set;for(let g of[e,...Object.values(s)])Gt(g,h);d=h}for(let[h,g]of Object.entries(s))n[`${t}.${zt(h)}`]=gt(ht(g,o,d));let l=gt(ht(e,o,d));return a?(n[t]=l,{$ref:`#/components/schemas/${t}`}):l}var bi=new Set(["type","enum","required","dependentRequired","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","contentEncoding","contentMediaType","minItems","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties","readOnly","writeOnly","deprecated",ir]),Dn=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),Nn=new Set(["anyOf","oneOf","allOf","prefixItems"]),Un=new Set(["properties","patternProperties","dependentSchemas"]),ae=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ht(e,t,n){if(!ae(e))return typeof e=="boolean"?e:{};let r={};for(let[s,a]of Object.entries(e))s==="$ref"&&typeof a=="string"?r.$ref=t(a):s==="const"?(n==="all"||n.has(e))&&(r.const=a):bi.has(s)?r[s]=a:Dn.has(s)?r[s]=ht(a,t,n):Nn.has(s)&&Array.isArray(a)?r[s]=a.map(o=>ht(o,t,n)):Un.has(s)&&ae(a)&&(r[s]=Object.fromEntries(Object.entries(a).map(([o,d])=>[o,ht(d,t,n)])));return r}var Is=Number.MAX_SAFE_INTEGER;function gt(e){if(!ae(e))return e;let t={};for(let[r,s]of Object.entries(e))Dn.has(r)?t[r]=gt(s):Nn.has(r)&&Array.isArray(s)?t[r]=s.map(gt):Un.has(r)&&ae(s)?t[r]=Object.fromEntries(Object.entries(s).map(([a,o])=>[a,gt(o)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-Is&&delete t.minimum,t.maximum===Is&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,ae(t.propertyNames)&&Object.keys(t.propertyNames).length===1&&t.propertyNames.type==="string"&&delete t.propertyNames,Array.isArray(t.type)&&t.type.filter(r=>r!=="null").length>1&&Object.keys(t).length===1)return{anyOf:t.type.map(r=>({type:r}))};let n=t.anyOf;if(Array.isArray(n)&&n.length===2&&Object.keys(t).length===1){let r=n.findIndex(a=>ae(a)&&Object.keys(a).length===1&&a.type==="null"),s=n[1-r];if(r!==-1&&ae(s)&&typeof s.type=="string")return{...s,type:[s.type,"null"]}}return t}function Gt(e,t){if(ae(e)){for(let n of["anyOf","oneOf"]){let r=e[n];if(!Array.isArray(r)||r.length<2||!r.every(ae))continue;if(r.every(a=>"const"in a||Array.isArray(a.enum)))for(let a of r)t.add(a);let s=r.map(a=>ae(a.properties)?a.properties:{});for(let a of Object.keys(s[0]))if(s.every(o=>ae(o[a])&&"const"in o[a]))for(let o of s)t.add(o[a])}for(let[n,r]of Object.entries(e))if(Dn.has(n))Gt(r,t);else if(Nn.has(n)&&Array.isArray(r))for(let s of r)Gt(s,t);else if(Un.has(n)&&ae(r))for(let s of Object.values(r))Gt(s,t)}}function ki(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function zt(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function qs(e,t){if(e.type!=="object"||typeof e.properties!="object"||e.properties===null)return;let n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([r,s])=>({name:r,in:t,required:n.has(r),schema:s}))}function vi(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function re(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:di}}}}function Ti(e,t,n){if(!e)return{200:{description:"The handler's answer, as JSON",content:{"application/json":{}}},204:{description:"The handler answered nothing (undefined or null)"}};if(e.returns.kind==="void")return{204:{description:"No Content"}};if(e.returns.kind==="raw")return{default:{description:"The handler's own Response, as it built it"}};let r=Ft(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function $i(e,t,n){let r=new Set,s=[];for(let a of t){if(r.has(a.code))continue;r.add(a.code);let o=n?.get(a.code);if(o&&a.status!==o.status)throw new Error(`${e} throws "${a.code}" with status ${a.status}, but the code is defined with status ${o.status} \u2014 a client matches an error by its code, so one code carries one status`);s.push({...a,...o?.data?{data:o.data}:{}})}return s}function _i(e,t){let n=Object.create(null);for(let r of t){let s=r.name.charAt(0).toLowerCase()+r.name.slice(1),a=Object.hasOwn(n,s)?n[s]:void 0;if(a)throw new Error(`${e} throws "${a.code}" and "${r.code}" under one name, "${r.name}" \u2014 every client names an error case after it; give one of them its own defineError`);n[s]={status:r.status,code:r.code,hasData:r.data!==void 0,description:""}}return n}function Ei(e,t,n){let r=new Map;for(let a of e)r.set(a.status,[...r.get(a.status)??[],a]);let s={};for(let a of[...r.keys()].sort((o,d)=>o-d)){let o=r.get(a),d=o.map(l=>{let h={error:{type:"string",const:l.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},g=["error","error_description","status","request_id"];return l.data&&(h.data=Ft(l.data,`${t}.${l.code}.data`,n,"answered"),g.push("data")),{type:"object",properties:h,required:g}});s[String(a)]={description:o.map(l=>l.code).join(" | "),content:{"application/json":{schema:d.length===1?d[0]:{oneOf:d}}}}}return s}function Si(e,t){let n={},r=[t.validates&&"a parameter failed its schema (data.fields names each field, data.more how many more)",t.hasPathParams&&"the path is not valid percent-encoding"].filter(Boolean),s=[r.length>0&&`bad_request: ${r.join("; or ")}`,t.keyed&&"invalid_idempotency_key: the Idempotency-Key is over 255 characters"].filter(Boolean);s.length>0&&(n[400]=re(s.join("; ")));let a=[e.auth.required&&"unauthorized: no access token was sent; invalid_token: the token is not valid (data.reason says why), or the Authorization header is not a Bearer token",e.auth.aal!=="aal1"&&`insufficient_user_authentication: the user signed in below ${e.auth.aal} \u2014 step up and call again (WWW-Authenticate acr_values; data.acr_values)`,e.auth.maxAge!==null&&`insufficient_user_authentication: the user last signed in or stepped up more than ${e.auth.maxAge} seconds ago \u2014 step up and call again (WWW-Authenticate max_age; data.max_age)`,e.attest&&"app_attest_required: the environment asks for the device's attestation and the call's proof is missing or does not verify (data.reason: app_attest_required, assertion_invalid, assertion_stale, device_unknown; data.challenge and X-Palbase-Attest-Challenge to attest with)"].filter(Boolean);return a.length>0&&(n[401]=re(a.join("; "))),e.auth.verifiedEmail&&(n[403]=re("email_not_verified: the user's email address is not verified")),t.keyed&&(n[409]=re("idempotency_key_in_use: a request with this Idempotency-Key is still running",Qe)),t.readsBody&&(n[413]=re("payload_too_large: the body is over the app's body limit")),t.keyed&&(n[422]=re("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(n[429]=re("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Qe)),n[500]=re("internal_error: the handler failed; the app's log has it under the request id"),n[503]=re(`${e.auth.required?"auth_unavailable: sign-ins cannot be checked right now; ":""}${e.attest?"attest_unavailable: the device's attestation cannot be checked right now; ":""}service_unavailable: a platform service the request needs did not answer${t.keyed?"; temporarily_unavailable: the Idempotency-Key could not be recorded":""}`,Qe),n}var Wt=class{windows=new Map;now;maxKeys;constructor(t=Date.now,n=1e5){this.now=t,this.maxKeys=n}take(t,n){let r=this.now(),s=this.windows.get(t);if((!s||r>=s.resetAt)&&(s={count:0,resetAt:r+n.window*1e3}),this.windows.delete(t),this.windows.set(t,s),this.windows.size>this.maxKeys&&this.windows.delete(this.windows.keys().next().value),s.count++,s.count>n.max)return Math.max(1,Math.ceil((s.resetAt-r)/1e3))}takeEach(t,n){if(n.length===1)return this.take(t,n[0]);let r,s=[];if(n.forEach((a,o)=>{let d=this.reserve(`${t}\0${o}`,a);"wait"in d?r=Math.max(r??0,d.wait):s.push([`${t}\0${o}`,d.window])}),r!==void 0)for(let[a,o]of s)this.give(a,o);return r}reserve(t,n){let r=this.take(t,n);return r!==void 0?{wait:r}:{window:this.windows.get(t).resetAt}}give(t,n){let r=this.windows.get(t);r&&r.resetAt===n&&r.count>0&&r.count--}};function yt(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return Ai(r??t??"unknown")}function Ai(e){let t=e.replace(/^\[|\]$/g,"").replace(/%.*$/,"");if(!t.includes(":"))return e;let n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(t);if(n)return n[1];let[r,s=""]=t.split("::"),a=r?r.split(":"):[],o=s?s.split(":"):[],d=t.includes("::")?[...a,...Array(8-a.length-o.length).fill("0"),...o]:a;return d.length!==8||d.some(l=>!/^[0-9a-f]{1,4}$/i.test(l))?t:`${d.slice(0,4).map(l=>parseInt(l,16).toString(16)).join(":")}::/64`}var Ln="/.well-known/palbase/attest-challenge",oe={deviceId:"x-palbase-device-id",anchor:"x-palbase-installation-anchor",challenge:"x-palbase-attest-challenge",payload:"x-palbase-attest-payload",signature:"x-palbase-attest-signature",capable:"x-palbase-attest-capable",sdkVersion:"x-palbase-sdk-version"},xi=25e3,Kt=3e3,Ri=1e4,Gs=()=>({capable:0,incapable:0,unknown:0,no_sdk:0,verified:0,refused:0}),Jt=class{constructor(t,n=Date.now){this.auth=t;this.now=n}auth;now;mode;readAt=-1/0;reading;counts=Gs();timer;shipping=Promise.resolve();async modeNow(){return this.now()-this.readAt>=xi&&(this.reading??=this.readMode().finally(()=>{this.reading=void 0}),await this.reading),this.mode}async readMode(){try{let n=(await this.auth.adminGetAttestPolicy({signal:AbortSignal.timeout(Kt)})).data.mode;if(n!=="off"&&n!=="monitor"&&n!=="enforce")throw new Error(`auth answered an App Attest mode this version does not know: ${JSON.stringify(n)}`);this.mode=n,this.readAt=this.now()}catch(t){_.warn(`[palbase] attest: the environment's App Attest mode could not be read${this.mode?`; keeping ${this.mode}`:""}`,{error:t})}}async check(t,n,r,s){let a=await this.modeNow();if(a===void 0)return{unavailable:!0,pass:!1};if(a==="off")return{pass:!0};let o=t.headers,d=o.get(oe.deviceId)??"",l=o.get(oe.payload)??"",h=o.get(oe.signature)??"",g=d!==""&&l!==""&&h!=="",b=g&&zs(l)&&zs(h);this.declared(o,g);let k;try{k=(await this.auth.adminVerifyDeviceAssertion({body:{installation_id:o.get(oe.anchor)??"",device_id:b?d:"",challenge:o.get(oe.challenge)??"",payload:b?l:"",signature:b?h:"",method:t.method,path:s??Oi(n),body_sha256:r&&r.byteLength>0?await Pi(r):""},signal:AbortSignal.timeout(Kt)})).data}catch(q){return _.warn(`[palbase] attest: auth could not verify ${t.method} ${n.pathname}`,{error:q}),a==="enforce"?{unavailable:!0,pass:!1}:{pass:!0}}g&&this.outcome(b&&k.ok);let B=a==="enforce"&&k.ok&&k.device_id&&k.platform?{id:k.device_id,platform:k.platform}:void 0;return k.ok||a==="monitor"?{pass:!0,challenge:k.next_challenge||void 0,device:B}:{pass:!1,reason:g?b?k.reason==="assertion_stale"||k.reason==="device_unknown"||k.reason==="assertion_invalid"?k.reason:"app_attest_required":"assertion_invalid":"app_attest_required",challenge:k.next_challenge}}async challengeFor(t){let n=await this.modeNow();if(n===void 0)return{unavailable:!0};if(n==="off")return{};try{let r=await this.auth.adminVerifyDeviceAssertion({body:{installation_id:t,device_id:"",challenge:"",payload:"",signature:"",method:"GET",path:Ln,body_sha256:""},signal:AbortSignal.timeout(Kt)});return r.data.next_challenge?{challenge:r.data.next_challenge}:{unavailable:!0}}catch(r){return _.warn("[palbase] attest: auth could not mint a challenge",{error:r}),{unavailable:!0}}}declared(t,n){let r=t.get(oe.capable);n||r==="yes"?this.counts.capable++:r==="no"?this.counts.incapable++:t.get(oe.sdkVersion)?this.counts.unknown++:this.counts.no_sdk++,this.schedule()}outcome(t){t?this.counts.verified++:this.counts.refused++}schedule(){this.timer||(this.timer=setInterval(()=>{this.flush()},Ri),this.timer.unref?.())}async flush(){let t=this.counts;Object.values(t).every(n=>n===0)||(this.counts=Gs(),this.shipping=this.shipping.then(async()=>{try{await this.auth.adminRecordAttestObservations({body:t,signal:AbortSignal.timeout(Kt)})}catch(n){_.warn("[palbase] attest: a batch of App Attest counts was not recorded",{error:n})}}),await this.shipping)}async stop(){this.timer&&clearInterval(this.timer),this.timer=void 0,await this.flush()}};function zs(e){return e.length===0||e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e)?!1:Buffer.from(e,"base64").toString("base64")===e}function Oi(e){let t=e.href,n=t.indexOf("#");return(n===-1?t:t.slice(0,n)).slice(e.origin.length)}async function Pi(e){let t=new Uint8Array(e.byteLength);t.set(e);let n=new Uint8Array(await crypto.subtle.digest("SHA-256",t));return Buffer.from(n).toString("base64")}function Fs(e){let t=[];for(let n of e){let r=D(n,qe),s=D(n,He)??[];if(s.length===0)throw new TypeError(`@Controller ${n.name} has no routes: a controller with nothing to serve is a mistake`);let a=D(n,an)??new Map;for(let o of s){let d=`${r.basePath}${o.subpath}`||"/",l=d.split("/").filter(Boolean).map(g=>{let b=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(g)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(g);return b?{param:b[1]}:g});if(typeof l[0]=="string"&&Ge.has(l[0]))throw new TypeError(`${n.name}.${o.fn}: ${o.method} ${d} \u2014 /${l[0]} is the platform's; a route is served elsewhere`);let h=[...a.get(o.fn)??[]].sort((g,b)=>g.index-b.index);for(let g of h)if(g.kind==="param"&&!l.some(b=>typeof b!="string"&&b.param===g.name))throw new TypeError(`${n.name}.${o.fn}: @Param("${g.name}") names no {${g.name}} in ${o.method} ${d}`);t.push({id:`${o.method} ${d}`,method:o.method,segments:l,controller:n,fn:o.fn,params:h,meta:o,controllerAuth:r.options.auth,controllerAttest:r.options.attest})}}return Ir(t),t}function In(e,t,n){let r=n.split("/").filter(Boolean);for(let s of e){if(s.method!==t||s.segments.length!==r.length)continue;let a={},o=!0;for(let d=0;d<r.length&&o;d++){let l=s.segments[d];if(typeof l=="string")o=l===r[d];else try{a[l.param]=decodeURIComponent(r[d])}catch{return{malformed:!0}}}if(o)return{route:s,params:a}}return null}function Bn(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Xe(e,t,n,r,s){return bt(e,e?Bn(e.requests,t):void 0,n,r,s)}var Vt={role:"service",claims:{}};async function bt(e,t,n,r,s){if(!e||!t)return s();let a=k=>_.warn(`[palbase] ${r}: a transaction of the request could not be given back \u2014 it wrote, locked, is an $atomic or an $attempt, ran SQL of its own, or the database keeps one snapshot for it \u2014 and sat ${k} ms with no statement running: the handler waited on something else, and a database connection waited with it. Make the outside call before the first write, or outside $atomic.`,{waitedMs:k}),o=e.app.request(t,{signal:n,heldIdle:a}),d=ne.getStore(),l=[],h=d?.saying;d&&(d.database=o.database,d.saying=l);let g=()=>{d&&(d.saying=h)},b;try{b=await s()}catch(k){throw g(),await o.rollback(k).catch(B=>_.error("[palbase] the request's transaction could not be rolled back",{error:B})),k}try{await o.commit()}catch(k){throw g(),await o.rollback(k).catch(B=>_.error("[palbase] the request's transaction could not be rolled back",{error:B})),k}g();for(let k of l)k();return b}var Mi=1024*1024,ji=20,Di={max:300,window:60},Ni={max:60,window:60},Ui=/^ins_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,et="/_palbase/crons",tt="/_palbase/tasks",Ws=50,Ks=50,Li=4096,Ii=69632,Js=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,nt=1e4,qi=6e4;function Hi(e,t){let n=e.meta.options.auth??e.controllerAuth??t??!0;if(typeof n=="boolean")return{required:n,verifiedEmail:!1,aal:"aal1",maxAge:null};let r=n.aal??"aal1";if(r!=="aal1"&&r!=="aal2"&&r!=="aal3")throw new TypeError(`${e.id}: auth { aal } is 'aal1', 'aal2' or 'aal3', not ${JSON.stringify(r)}`);if(r!=="aal1"&&n.required===!1)throw new TypeError(`${e.id}: auth { aal: '${r}' } asks how the user signed in \u2014 the route needs a signed-in user (required: true)`);let s=n.maxAge??null;if(s!==null&&!(Number.isInteger(s)&&s>0))throw new TypeError(`${e.id}: auth { maxAge } is a whole number of seconds above 0, not ${JSON.stringify(s)}`);if(s!==null&&n.required===!1)throw new TypeError(`${e.id}: auth { maxAge } asks when the user last signed in \u2014 the route needs a signed-in user (required: true)`);return{required:n.required!==!1,verifiedEmail:n.verifiedEmail===!0,aal:r,maxAge:s}}function Vs(e,t){let n=['error="insufficient_user_authentication"'];return e.aal!=="aal1"&&n.push(`acr_values="urn:nist:800-63:${e.aal}"`),e.maxAge!==null&&n.push(`max_age=${e.maxAge}`),`${t?"DPoP":"Bearer"} ${n.join(", ")}`}function Zs(e){return{...e.aal!=="aal1"?{acr_values:e.aal}:{},...e.maxAge!==null?{max_age:e.maxAge}:{}}}var Bi=60;function Gi(e,t,n){if(e===null)return!1;let r=n/1e3-e;return r>=-Bi&&r<=t}var X=class extends Error{constructor(n,r,s,a,o,d,l){super(s);this.status=n;this.code=r;this.data=a;this.retryAfter=o;this.challenge=d;this.headers=l}status;code;data;retryAfter;challenge;headers};function zi(e){if(e==="proof")return'DPoP error="invalid_dpop_proof", algs="ES256"';if(e==="bound"||e==="not_bound")return'DPoP error="invalid_token", algs="ES256"'}var Fi=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function Wi(e,t){let n=new Headers(e.headers);for(let r of Fi)n.delete(r);return e.url!==""&&(n.delete("content-encoding"),n.delete("content-length")),n.set("x-request-id",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}function Ys(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),Zt(e.headers,"Accept-Language")),e}function Zt(e,t){let n=(e.get("vary")??"").split(",").map(r=>r.trim()).filter(Boolean);n.includes("*")||n.some(r=>r.toLowerCase()===t.toLowerCase())||e.set("vary",[...n,t].join(", "))}function ce(e,t,n,r={}){let s=JSON.stringify(t);return Ht(new Response(s,{status:e,headers:{"content-type":"application/json","x-request-id":n,...r}}),Buffer.from(s,"utf8"))}function $(e,t){let n={error:e.code,error_description:e.message,status:e.status,request_id:t};e.data!==void 0&&(n.data=e.data);let r={...e.headers};return e.retryAfter!==void 0&&(r["retry-after"]=String(e.retryAfter)),e.challenge!==void 0&&(r["www-authenticate"]=e.challenge),ce(e.status,n,t,r)}function Qs(e,t){if(t===void 0)return e;try{return e.headers.set(oe.challenge,t),e}catch{let n=new Headers(e.headers);return n.set(oe.challenge,t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}}var oa=new Set([0,429,502,503,504]);function Xs(e,t,n,r){if(r?.aborted)return _.info(`[palbase] ${n}: the client left before its answer`),$({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof X)return $({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge,headers:e.headers},t);if(pt(e)){let a=e;return a.status>=500&&_.error(`[palbase] ${n} answered ${a.status} ${a.error}`,{error:e}),ce(a.status,ms(a,t),t,a.retryAfter!==void 0?{"retry-after":String(a.retryAfter)}:{})}let s=Gn(e,n);return s?$(s,t):(e instanceof ie?_.error(`[palbase] ${n}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):_.error(`[palbase] unhandled error in ${n}`,{error:e}),$({status:500,code:"internal_error",message:"The request could not be completed"},t))}function Gn(e,t){if(e instanceof xt)return _.warn(`[palbase] ${t}: sign-ins cannot be checked (${e.message})`,{error:e}),{status:503,code:"auth_unavailable",message:"Sign-ins cannot be checked right now; try again shortly",retryAfter:1};if(e instanceof ie&&oa.has(e.status))return _.warn(`[palbase] ${t}: a platform service did not answer (${e.op}: ${e.status} ${e.code})`,{error:e}),{status:503,code:"service_unavailable",message:"A service this request needs did not answer; try again shortly",retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))};let n=sa(e);if(n!==void 0)return _.warn(`[palbase] ${t}: the database connection ${n==="lost"?"was lost":"could not be opened"}`,{error:e}),{status:503,code:"database_unavailable",message:"The database is temporarily unavailable",data:{retrySafe:n==="never"},retryAfter:1}}function Ki(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return xn(e)?t(e.message):pt(e)&&!Kn(e)&&!zn(e)?t(e.errorDescription):zn(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function zn(e){return e instanceof xt||e instanceof ie&&oa.has(e.status)||sa(e)!==void 0||pt(e)&&e.status===503&&Kn(e)}async function qn(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,ji).map(o=>({field:(o.path??[]).map(d=>String(typeof d=="object"&&d!==null&&"key"in d?d.key:d)).join("."),message:o.message})),a=r.issues.length-s.length;throw new X(400,"bad_request",`${n} failed validation`,a>0?{fields:s,more:a}:{fields:s})}return r.value}async function wt(e,t){let n=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(n)&&n>t)throw new X(413,"payload_too_large",`Request body exceeds ${t} bytes`);if(!e.body)return new Uint8Array(0);let r=e.body.getReader(),s=[],a=0;for(;;){let{done:l,value:h}=await r.read();if(l)break;if(a+=h.byteLength,a>t)throw await r.cancel().catch(()=>{}),new X(413,"payload_too_large",`Request body exceeds ${t} bytes`);s.push(h)}let o=new Uint8Array(a),d=0;for(let l of s)o.set(l,d),d+=l.byteLength;return o}function Ji(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return ue(t)}function Vi(e){let t=e.claims.custom_claims;return{id:e.id,email:e.email,role:e.role,emailVerified:e.emailVerified,metadata:typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},sessionId:e.sessionId,test:e.claims.test===!0,acr:Zi(e.claims.acr),amr:Array.isArray(e.claims.amr)?e.claims.amr.filter(n=>typeof n=="string"):[],authTime:typeof e.claims.auth_time=="number"&&e.claims.auth_time>0?e.claims.auth_time:null}}function Zi(e){return e==="aal1"||e==="aal2"||e==="aal3"?e:null}function ea(e){return e==="aal3"?3:e==="aal2"?2:1}function Yi(e){return e.id?{id:e.id,email:e.email??null,role:e.role,emailVerified:e.emailVerified??!1,metadata:{},sessionId:e.session??null,test:!1,acr:null,amr:[],authTime:null}:null}var Qi=/^[A-Za-z0-9._:-]{8,128}$/,Xi=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,ed={max:20,window:60},td=10*6e4,nd=1e4,kt=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},Fn=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=aa("sha256").update(t).digest("hex"),a=(this.known.get(s)??0)>this.now(),o=`token-misses\0a:${n}`,d;if(!a){let h=this.limiter.reserve(o,ed);if("wait"in h)throw new kt(h.wait);d=h}let l=await r();if(!l)throw this.known.delete(s),new At("unknown_token","The token is not one of the app's");return d&&this.limiter.give(o,d.window),this.known.delete(s),this.known.set(s,this.now()+td),this.known.size>nd&&this.known.delete(this.known.keys().next().value),l}};function xu(e){let t=new Nt(e.modules),n=Fs(t.controllers.map(i=>i.cls)),r=new Map(n.map(i=>[i,Hi(i,e.auth)])),s=i=>i.meta.options.attest??i.controllerAttest??!1,a=n.some(s)?new Jt(e.server.auth,e.now):void 0,o=new Map;for(let i of n){let c={body:[],query:[]};for(let p of i.params){if(!p.schema)continue;let u=wr(p.schema);if(p.kind==="body")c.body.push(...nn(u,"/body",i.id));else if(p.kind==="query"){let y=nn(u,"/query",i.id),m=y.find(w=>w.split("/").length!==3);if(m)throw new TypeError(`${i.id}: ${m} \u2014 an encrypted query field is one of the query's own names`);c.query.push(...y)}else if(br(u))throw new TypeError(`${i.id}: its ${p.kind} carry no encrypted field \u2014 its body's or its query's do`)}if(c.body.length+c.query.length!==0){if(i.meta.upload)throw new TypeError(`${i.id}: an upload's body comes through storage, which seals nothing \u2014 it carries no encrypted field`);o.set(i,c)}}async function d(i,c,p,u){let y=e.server.transit;try{return y.loaded||await y.load(),await y.request({header:p,method:u,path:od(i),params:i.segments.flatMap(m=>typeof m=="string"?[]:[c[m.param]??""])})}catch(m){throw na(m)}}for(let[i,c]of r){if(!c.required&&i.params.some(p=>p.kind==="user"))throw new TypeError(`${i.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(i.meta.upload&&c.verifiedEmail)throw new TypeError(`${i.id}: an @Upload route cannot ask for a verified email \u2014 storage names its caller by id and session, not by its token; read the user (Palbase.auth) in the handler to check it`);if(i.meta.upload&&c.aal!=="aal1")throw new TypeError(`${i.id}: an @Upload route cannot ask for auth { aal } \u2014 storage names its caller by id and session, not by its token`);if(i.meta.upload&&c.maxAge!==null)throw new TypeError(`${i.id}: an @Upload route cannot ask for auth { maxAge } \u2014 storage names its caller by id and session, not by its token's auth_time`);if(!s(i)&&i.params.some(p=>p.kind==="attestedDevice"))throw new TypeError(`${i.id}: @AttestedDevice() on a route that does not ask for device attestation \u2014 mark it attest: true`);if(i.meta.upload&&s(i))throw new TypeError(`${i.id}: an @Upload route cannot ask for device attestation \u2014 storage calls it, not the app's client; attest the route the app calls before the upload`)}let l=new Map;for(let i of n)for(let c of i.params)c.kind==="resolve"&&l.set(c,t.dependencyOf(i.controller,c.resolver,`${i.id} @Resolve(${c.resolver?.name})`));let h=new Map;for(let i of t.cronProviders){let c=t.get(i),p=D(i,Ee),u=h.get(p.name);if(u)throw new TypeError(`@Cron "${p.name}" is ${u.owner} and ${i.name}: a cron's name is its own \u2014 name one of them`);h.set(p.name,{declaration:p,owner:i.name,run:y=>c.run(y)})}let g=new Map;for(let i of t.taskProviders){let c=t.get(i),p=D(i,ke),u=g.get(p.name);if(u)throw new TypeError(`@Task "${p.name}" is ${u.owner} and ${i.name}: a task type's name is its own \u2014 name one of them`);g.set(p.name,{declaration:p,owner:i.name,run:(y,m)=>c.run(y,m)})}let b=new Map;for(let i of t.templateProviders){let c=t.get(i),p=D(i,Te),u=b.get(p.name);if(u)throw new TypeError(`@TestUserTemplate "${p.name}" is ${u.owner} and ${i.name}: a template's name is its own \u2014 name one of them`);b.set(p.name,{owner:i.name,seed:(y,m)=>c.seed(y,m),...typeof c.undo=="function"?{undo:(y,m)=>c.undo(y,m)}:{}})}b.size>0&&!e.platform&&_.info(`[palbase] ${b.size} @TestUserTemplate(s): the platform calls a machine for its test users; nothing does here`);let k=new Map,B=new Set,U=new Set,q=new Set;if(e.platform&&!e.platform.secret)throw new Error("[palbase] platform.secret is the key the platform signs its calls with (PALBASE_PLATFORM_SECRET)");if(h.size>Ws)throw new TypeError(`${h.size} @Cron classes: a machine runs ${Ws} crons at most`);if(g.size>Ks)throw new TypeError(`${g.size} @Task classes: a machine runs ${Ks} task types at most`);h.size>0&&!e.platform&&_.info(`[palbase] ${h.size} @Cron(s): the platform runs them on a machine; nothing calls them here`);let K=Yr(t.gateways.map(i=>({cls:i,instance:t.get(i)})),{run:(i,c,p,u)=>ne.run({requestId:ne.getStore()?.requestId??"",...i?.id?{userId:i.id}:{}},()=>bt(e.database,e.database?i?.id?Bn(e.database.requests,jt(i)):Vt:void 0,p,c,async()=>{let y=await u();if(p?.aborted)throw new Error(`realtime gave up on ${c} before it ended`);return y})),broadcast:i=>e.server.realtime.broadcast({body:{messages:i}}),revalidate:i=>e.server.realtime.revalidate({body:i}),isOutage:zn});K.declarations.length>0&&!e.platform&&_.info(`[palbase] ${K.declarations.length} @Gateway(s): realtime tells a machine of them; nothing does here`);let J=ws();(J.tools.size>0||J.agents.size>0)&&!e.platform&&_.info(`[palbase] ${J.tools.size} ai.tool(s) and ${J.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let le=i=>c=>t.provider(c,`${i} ctx.inject(${typeof c=="function"?c.name:String(c)})`),he=new Ut,ge=new Set,v=e.database!==void 0||e.contractOnly?.database===!0;if(v){for(let i of n)if(mt(i)&&i.params.some(c=>c.kind==="headers"&&c.schema!==void 0&&Ds(c.schema)))throw new TypeError(`${i.id}: its @Headers schema declares Idempotency-Key \u2014 the framework takes that header on every write of an app with a database and answers a retry from it; a handler reads it with @Headers() (no schema)`)}let E=e.database?new qt(e.database.app,e.database.keptAnswers):void 0,f=fd(e.cors),T=e.now??Date.now,R=new Wt(e.now),L=new Fn(R,e.now??Date.now),G=e.maxBodyBytes??Mi,z=i=>{let c=i.meta.options.rateLimit??e.rateLimit??Di;if(c===!1)return!1;let p=(Array.isArray(c)?c:[c]).filter(u=>u.max>0&&u.window>0);return p.length>0?p:!1},I=e.env??process.env,N=rs(t.webhooks,i=>t.get(i),I,{secrets:e.contractOnly===void 0}),F=N.size===0&&h.size===0&&g.size===0&&b.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(I).filter(i=>typeof i[1]=="string"&&!pr(i[0])))),Q=new Map([...N.keys()].map(i=>[i,{seen:new Set,inflight:new Set}])),te=new Map([...N.keys()].map(i=>[i,{counts:new Map,at:void 0}])),rt,vt=()=>rt??=Bs(n,i=>({auth:r.get(i),limit:z(i),attest:s(i)}),{databaseSeesCaller:v,idempotency:v,webhooks:[...N.values()].map(i=>({name:i.name,cls:i.cls.name,provider:i.provider,signatureHeader:i.signatureHeader,secretEnv:i.secretEnv,events:[...i.events.keys()]})),platformEvents:[...ye.keys()],gateways:K.declarations,ai:{agents:[...J.agents.values()].map(i=>({name:i.name,...i.description!==void 0?{description:i.description}:{},...i.machine!==void 0?{machine:i.machine}:{}})),tools:[...[...J.tools.values()].map(i=>({name:i.name,kind:"backend",description:i.description,parameters:i.parameters,approval:i.approval,...i.machine!==void 0?{machine:i.machine}:{}})),...[...J.clientTools.values()].map(i=>({name:i.name,kind:"client",description:i.description,parameters:i.parameters,approval:i.approval}))]},platformEventBuckets:sd(ye),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),ye=new Map;for(let[i,c]of Object.entries(e.events??{}))ye.set(i,c.map(p=>({name:`palbase(${i})`,call:u=>p(u)})));for(let i of t.eventProviders){let c=t.get(i);for(let{event:p,fn:u,bucket:y}of D(i,Me)??[]){if(!Er.test(p))throw new TypeError(`@On("${p}") on ${i.name}.${u}: a platform event's type is dotted lowercase words, like user.deleted \u2014 a third party's event is taken by an @On in its @Webhook class`);ye.has(p)||ye.set(p,[]),ye.get(p).push({name:`${i.name}.${u}`,bucket:y,call:async(m,w)=>c[u](m,w)})}}let ve=new Set,ee=new Set;mr(e.server),hr({to:(i,c)=>({emit:(p,u)=>K.emit(i,c,p,u),pipe:p=>K.pipe(i,c,p),revalidate:p=>K.revalidate(i,c,p)})}),Ar(e.platform?xr(I.PALBASE_MACHINE):new Ct(new Map([...g].map(([i,c])=>[i,c.declaration])),(i,c)=>at(i,c),e.now));async function Yt(i,c){let p;try{p=await lr(i,e.webhookSecret,{now:e.now})}catch(u){if(u instanceof dt)return $({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${u.code}`},c);throw u}if(ue(p.data),ve.has(p.id))return new Response(null,{status:204,headers:{"x-request-id":c}});if(ee.has(p.id))return $({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},c);ee.add(p.id);try{let u;try{await Xe(e.database,null,void 0,`event ${p.type}`,async()=>{for(let y of ye.get(p.type)??[])if(!(y.bucket!==void 0&&rd(p)!==y.bucket))try{await y.call(p,{requestId:c})}catch(m){throw u=y.name,m}})}catch(y){return _.error(`[palbase] ${u??"the delivery"} failed on ${p.type} ${p.id}; the platform delivers it again`,{error:y}),$({status:500,code:"handler_failed",message:"The event could not be handled"},c)}return ve.add(p.id),ve.size>nt&&ve.delete(ve.values().next().value),new Response(null,{status:204,headers:{"x-request-id":c}})}finally{ee.delete(p.id)}}async function Tt(i,c={}){let p=i.headers.get("origin");if(f&&p!==null){let u=f.allows(p);if(i.method==="OPTIONS"&&i.headers.has("access-control-request-method"))return u?new Response(null,{status:204,headers:f.preflight(p,i.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let y=await er(i,c);if(u)for(let[m,w]of Object.entries(f.headers(p)))m==="vary"?Zt(y.headers,w):y.headers.set(m,w);else Zt(y.headers,"Origin");return y}return er(i,c)}async function st(i,c,p,u){if(!i.headers.get(p.scheme.header))return $e(p,"missing_signature",u);let y={headers:i.headers,body:await wt(i,p.scheme.maxBytes(G)),url:ss(i,c)},m;try{m=p.scheme.check(y,T()/1e3)}catch{return $e(p,"signature_mismatch",u,"check_failed")}if(typeof m=="string")return $e(p,m,u);let w=p.events.get(m.type);if(!w)return _.info(`[palbase] webhook ${p.name}: no @On takes "${m.type}"; acknowledged`),ce(200,{ok:!0,handled:!1},u);let A=Q.get(p.name),O=m.event,M=[];if(m.id!==void 0){if(A.seen.has(m.id))return ce(200,{ok:!0,handled:!1,duplicate:!0},u);M=[m.id]}else if(m.ids&&Array.isArray(O)){let x=m.ids,S=O.map((j,Z)=>[j,x[Z]]).filter(([,j])=>j===void 0||!A.seen.has(j));if(S.length===0)return ce(200,{ok:!0,handled:!1,duplicate:!0},u);O=S.map(([j])=>j),M=S.flatMap(([,j])=>j===void 0?[]:[j])}if(M.some(x=>A.inflight.has(x)))return $({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},u);ue(O);for(let x of M)A.inflight.add(x);let P;try{P=await Xe(e.database,null,void 0,`webhook ${p.name}`,()=>w.call(O,{env:F,requestId:u,environmentId:e.projectId??""}))}catch(x){let S=Gn(x,`webhook ${p.name}`)??id(x,p.name);return S?$(S,u):(_.error(`[palbase] ${w.name} failed on ${p.name} "${m.type}"; the sender delivers it again`,{error:x}),$({status:500,code:"handler_failed",message:"The event could not be handled"},u))}finally{for(let x of M)A.inflight.delete(x)}for(let x of M)A.seen.add(x),A.seen.size>nt&&A.seen.delete(A.seen.values().next().value);return Qt(P,p,u)}function Qt(i,c,p){if(i instanceof Response)return i;if(typeof i=="string"){let u=c.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(i,{status:200,headers:{"content-type":u,"x-request-id":p}})}return ce(200,i??{ok:!0,handled:!0},p)}function $e(i,c,p,u=c){let y=te.get(i.name);y.counts.set(u,(y.counts.get(u)??0)+1);let m=T();return(y.at===void 0||m-y.at>=qi)&&(V(i.name),y.at=m),$({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${c}`},p)}function V(i){let c=te.get(i).counts;if(c.size===0)return;let p=[...c.values()].reduce((u,y)=>u+y,0);_.warn(`[palbase] webhook ${i}: ${p} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(c)}),c.clear()}function Ue(i){let c=i.split("/").filter(Boolean);return c.length===2&&c[0]==="webhooks"?N.get(c[1]):void 0}async function Le(i,c,p,u){let y=c.pathname===et;if(i.method!==(y?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:y?"The crons are listed with GET":"A cron is run with POST"},u);let m=y?new Uint8Array(0):await wt(i,Li);try{await St({secret:p,signature:i.headers.get("palbase-signature"),body:m,now:e.now})}catch(H){if(H instanceof dt)return $({status:401,code:"invalid_signature",message:`The crons are the platform's to call: ${H.code}`},u);throw H}if(y){let H=[...h.values()].map(({declaration:W})=>({name:W.name,schedule:W.schedule,time_zone:W.timeZone,timeout:W.timeout,retry:W.retries}));return ce(200,{crons:H},u,{"cache-control":"no-store"})}let w=c.pathname.slice(et.length+1),A=h.get(w);if(!A)return $({status:404,code:"cron_not_found",message:`This version has no cron ${JSON.stringify(w)}`},u);let O;try{O=JSON.parse(new TextDecoder().decode(m))}catch{return $({status:400,code:"bad_request",message:"A run is the JSON {cron, run_id, scheduled_at, attempt}"},u)}let{cron:M,run_id:P,scheduled_at:x,attempt:S}=O??{};if(M!==w||typeof P!="string"||P===""||typeof x!="string"||!Js.test(x)||Number.isNaN(Date.parse(x))||!Number.isInteger(S)||S<1)return $({status:400,code:"bad_request",message:`A run of ${w} is the JSON {cron: "${w}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},u);let j=`${P}#${String(S)}`;if(U.has(j))return new Response(null,{status:204,headers:{"x-request-id":u}});if(q.has(j))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},u);q.add(j);let Z={env:F,environmentId:e.projectId??"",cron:w,runId:P,scheduledAt:new Date(x),attempt:S};try{await bt(e.database,e.database?Vt:void 0,i.signal,`cron ${w}`,async()=>{if(await A.run(Z),i.signal.aborted)throw new Error(`the platform gave up on this attempt of ${w} before it ended`)})}catch(H){return i.signal.aborted||_.error(`[palbase] cron ${w} failed (run ${P}, attempt ${String(S)})`,{error:H}),$({status:500,code:"cron_failed",message:`The cron ${w} failed; the platform tries it again`},u)}finally{q.delete(j)}return U.add(j),U.size>nt&&U.delete(U.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}})}let at=async({task:i,id:c,attempt:p,payload:u,createdAt:y},m)=>{let w=g.get(i);if(!w)return{status:404,message:`this version has no task ${JSON.stringify(i)}`};let A=ue(u??null),O=w.declaration.payload;if(O){let P=await O["~standard"].validate(A);if(P.issues){let x=P.issues.slice(0,5).map(S=>`${(S.path??[]).map(j=>String(typeof j=="object"&&j!==null&&"key"in j?j.key:j)).join(".")||"(payload)"}: ${S.message}`).join("; ");return _.error(`[palbase] task ${i} ${c}: what it carries is not what it takes \u2014 it fails, not to be tried again: ${x}`),{status:422,message:`what it carries is not what @Task "${i}" takes: ${x}`}}A=P.value}let M={env:F,environmentId:e.projectId??"",task:i,id:c,attempt:p,createdAt:y};try{await bt(e.database,e.database?Vt:void 0,m,`task ${i}`,async()=>{if(await w.run(A,M),m.aborted)throw new Error(`the platform gave up on this attempt of ${i} before it ended`)})}catch(P){return P instanceof Pt?(_.error(`[palbase] task ${i} ${c} can never be done: ${P.message}`),{status:422,message:P.message}):(m.aborted||_.error(`[palbase] task ${i} failed (task ${c}, attempt ${String(p)})`,{error:P}),{status:500,message:`the task ${i} failed; it is tried again`})}return{status:204}};async function ca(i,c,p,u){let y=c.pathname===tt;if(i.method!==(y?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:y?"The task types are listed with GET":"A task is run with POST"},u);let m=y?new Uint8Array(0):await wt(i,Ii);try{await St({secret:p,signature:i.headers.get("palbase-signature"),body:m,now:e.now})}catch(H){if(H instanceof dt)return $({status:401,code:"invalid_signature",message:`The tasks are the platform's to call: ${H.code}`},u);throw H}if(y){let H=[...g.values()].map(({declaration:W})=>({name:W.name,timeout:W.timeout,retry:W.retries,concurrency:W.concurrency}));return ce(200,{tasks:H},u,{"cache-control":"no-store"})}let w=c.pathname.slice(tt.length+1),A;try{A=JSON.parse(new TextDecoder().decode(m))}catch{return $({status:400,code:"bad_request",message:"A task is the JSON {task, id, attempt, payload, created_at}"},u)}let{task:O,id:M,attempt:P,payload:x,created_at:S}=A??{};if(O!==w||typeof M!="string"||M===""||typeof S!="string"||!Js.test(S)||Number.isNaN(Date.parse(S))||!Number.isInteger(P)||P<1)return $({status:400,code:"bad_request",message:`A task of ${w} is the JSON {task: "${w}", id, attempt (1 or more), payload, created_at (RFC 3339)}`},u);let j=`task:${M}#${String(P)}`;if(U.has(j))return new Response(null,{status:204,headers:{"x-request-id":u}});if(q.has(j))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},u);q.add(j);let Z;try{Z=await at({task:w,id:M,attempt:P,payload:x,createdAt:new Date(S)},i.signal)}finally{q.delete(j)}return Z.status===404?$({status:404,code:"task_not_found",message:Z.message??""},u):Z.status===422?$({status:422,code:"task_failure",message:Z.message??""},u):Z.status>=300?$({status:Z.status,code:"task_failed",message:Z.message??""},u):(U.add(j),U.size>nt&&U.delete(U.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}}))}async function ot(i,c,p,u){if(i.method!=="POST")return $({status:405,code:"method_not_allowed",message:`${u} is POSTed`},p);let y;try{ur({signature:i.headers.get("palbase-signature"),now:e.now}),y=await wt(i,1048576),await St({secret:c,signature:i.headers.get("palbase-signature"),body:y,now:e.now})}catch(w){if(w instanceof dt)return $({status:401,code:"invalid_signature",message:`${u} is the platform's to call: ${w.code}`},p);throw w}let m;try{m=JSON.parse(new TextDecoder().decode(y))}catch{return $({status:400,code:"bad_request",message:`${u} is JSON`},p)}return typeof m!="object"||m===null||!Object.hasOwn(m,"call")||m.call!==new URL(i.url).pathname?$({status:401,code:"invalid_signature",message:`${u} is the platform's to call: signed_for_another_call`},p):{body:m}}async function ua(i,c,p,u,y){let m=await ot(c,p,u,`An upload's ${i}`);if(m instanceof Response)return m;let w=qr(i,m.body);if(typeof w=="string")return $({status:400,code:"bad_request",message:`An upload's ${i}: ${w}`},u);if(i==="complete"){if(ge.has(w.uploadId))return $({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},u);ge.add(w.uploadId),ge.size>nt&&ge.delete(ge.values().next().value)}let A=In(n,w.method,w.route);if(!A||"malformed"in A||!A.route.meta.upload)return $({status:404,code:"not_found",message:`No upload route for ${w.method} ${w.route}`},u);let{route:O,params:M}=A,P=A.route.meta.upload,x=Yi(w.user);if(x&&tr(y,x.id),r.get(O).required&&!x)throw new X(401,"unauthorized","This route needs a signed-in user");if(i==="authorize"){let Z=z(O);if(Z!==!1){let W=R.takeEach(`${O.id}\0${Dr(w.user,w.client)}`,Z);if(W!==void 0)throw new X(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:W},W)}let H=Lr(P.pathTemplate,{userId:x?.id??null,uploadId:w.uploadId,filename:w.filename});if("problem"in H)throw new X(400,"bad_request",H.problem);return await Xe(e.database,jt(w.user),c.signal,O.id,async()=>{let W={request:c,query:new URLSearchParams(w.query),params:M,user:x,body:w.body===void 0||w.body===null?{}:ue(w.body),requestId:u};await Xn(O,W);for(let _e of O.params)(_e.kind==="query"||_e.kind==="body"&&w.body!==void 0)&&await ra(_e,W)}),ce(200,{bucket:P.bucket,path:H.path},u)}y.endpoint=O.id.slice(O.id.indexOf(" ")+1);let S=new URLSearchParams(w.query),j=w.body===null||w.body===void 0?{}:ue(w.body);return Hn(await Xt(O,{request:c,query:S,params:M,user:x,body:j,requestId:u,uploadedObject:ue(w.uploadedObject)},jt(w.user)),void 0,u)}async function la(i,c,p,u){let y=c.pathname.slice(Mt.length+1),m=y.endsWith("/undo"),w=m?y.slice(0,-5):y,A=await ot(i,p,u,"A test user template");if(A instanceof Response)return A;let O=b.get(w);if(!O)return $({status:404,code:"template_not_found",message:Cr(w,[...b.keys()])},u);if(m&&!O.undo)return $({status:404,code:"no_undo",message:`@TestUserTemplate "${w}" has no undo: the user's deletion cleans up after it`},u);let M=Rr(w,A.body);if(typeof M=="string")return $({status:400,code:"bad_request",message:`A test user template's call: ${M}`},u);let P=ue(M.user),x;try{x=await Or(e.server,P.id)}catch(H){return _.error(`[palbase] test user template ${w}: auth could not say whether ${P.id} is a test user; nothing was written`,{error:H}),$({status:503,code:"auth_unavailable",message:"Auth could not say whether the user is a test user: the template did not run",retryAfter:5},u)}if(!x)return _.warn(`[palbase] test user template ${w}${m?" undo":""}: auth does not say ${P.id} is a test user \u2014 nothing was run`),$({status:403,code:"not_a_test_user",message:"Auth does not say this user is a test user: a template writes for test users alone"},u);let S=`${P.id}\0${w}`;if(B.has(S))return $({status:409,code:"in_progress",message:`The template ${w} is being written for this user`,retryAfter:5},u);if(!m&&k.has(S))return ce(200,{rows:k.get(S)},u);B.add(S);let j={env:F,environmentId:e.projectId??"",template:w},Z=`test user template ${w}${m?" undo":""}`;try{let H={};return await bt(e.database,e.database?Vt:void 0,i.signal,Z,async()=>{if(m?await O.undo(P,j):(await O.seed(P,j),H=await Pr(ne.getStore()?.database)),i.signal.aborted)throw new Error(`the platform gave up on ${Z} before it ended`)}),m?(k.delete(S),new Response(null,{status:204,headers:{"x-request-id":u}})):(k.set(S,H),k.size>nt&&k.delete(k.keys().next().value),ce(200,{rows:H},u))}catch(H){i.signal.aborted||_.error(`[palbase] ${Z} failed for ${P.id}: nothing of it was kept`,{error:H});let W=H instanceof Error&&H.message!==""?`: ${H.message.replace(/\s+/g," ").slice(0,300)}`:"";return $({status:500,code:m?"undo_failed":"template_failed",message:`${m?"The undo of":"The template"} ${w} failed${W}; nothing of it was kept`},u)}finally{B.delete(S)}}function Yn(i,c,p,u){let y=i?{sub:i.id,role:"authenticated"}:null;return ne.run({requestId:ne.getStore()?.requestId??"",...i?{userId:i.id}:{}},()=>Xe(e.database,y,p,c,async()=>{let m=await u();if(p.aborted)throw new Error(`the platform gave up on ${c} before it ended`);return m}))}let Qn=(i,c)=>new Response(i,{status:200,headers:{"content-type":"application/json","x-request-id":c}});async function fa(i,c,p){let u=await ot(i,c,p,"A tool call");if(u instanceof Response)return u;let y=u.body,m=y.tool;if(typeof m!="string"||m==="")return $({status:400,code:"bad_request",message:"A tool call is {tool, call_id, input, context}: tool names it"},p);let w=J.tools.get(m);if(!w)return $({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(m.slice(0,64))}`},p);let A=y.call_id,O=vs(y.context);if(typeof A!="string"||A===""||A.length>256||typeof O=="string")return $({status:400,code:"bad_request",message:`A call of ${m} is {tool, call_id, input, context}${typeof O=="string"?`: ${O}`:""}`},p);let M=aa("sha256").update(JSON.stringify(y)).digest("hex"),P=he.answered(A);if(P!==void 0)return P.digest!==M?$({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},p):Qn(P.answer,p);if(he.isRunning(A))return $({status:409,code:"in_progress",message:"This call is running",retryAfter:2},p);he.start(A);let x;try{let S=await Yn(O.user,`ai.tool ${m}`,i.signal,()=>w.call(ue(y.input??{}),{...O,callId:A,signal:i.signal,inject:le(`ai.tool ${m}`)}));x="deferred"in S?JSON.stringify({deferred:!0,...S.expires_in_seconds!==void 0?{expires_in_seconds:S.expires_in_seconds}:{}}):JSON.stringify({output:S.output,is_error:S.is_error,...S.workspace_tree!==void 0?{workspace_tree:S.workspace_tree}:{}});let j=new TextEncoder().encode(x).byteLength;if(j>Ye){_.error(`[palbase] ai.tool ${m} answered ${j} bytes (call ${A}): a machine's answer is ${Ye} at most; the agent is told it failed`);let Z="deferred"in S?void 0:S.workspace_tree;x=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${Ye/(1<<20)} MiB it may be`}],is_error:!0,...Z!==void 0?{workspace_tree:Z}:{}})}}catch(S){if(i.signal.aborted)return he.end(A,void 0),$({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},p);_.error(`[palbase] ai.tool ${m} failed (call ${A}, chat ${O.chatId}); the agent is told`,{error:S});let j=ys(S);x=JSON.stringify({output:[{type:"text",text:Ki(S)}],is_error:!0,...j!==void 0?{workspace_tree:j}:{}})}return he.end(A,{digest:M,answer:x}),Qn(x,p)}async function pa(i,c,p){let u=await ot(i,c,p,"An agent's turn");if(u instanceof Response)return u;let y=Ts(u.body);if(typeof y=="string"||y.agent==="")return $({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata, message}${typeof y=="string"?`: ${y}`:": agent names it"}`},p);let m=y.agent,w=J.agents.get(m);if(!w)return $({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(m.slice(0,64))}`},p);let A;try{A=await Yn(y.user,`ai.agent ${m}`,i.signal,()=>w.resolve({...y,signal:i.signal,inject:le(`ai.agent ${m}`)}))}catch(P){if(i.signal.aborted)return $({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},p);let x=Gn(P,`ai.agent ${m}`);return x?$(x,p):(_.error(`[palbase] ai.agent ${m} failed for chat ${y.chatId}; the turn is not started`,{error:P}),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},p))}let O=A.tools.find(P=>J.tools.get(P.name)!==P);if(O)return _.error(`[palbase] ai.agent ${m} handed out ai.tool ${JSON.stringify(O.name)}, which this app did not declare when it was made \u2014 make each ai.tool once, at a module's top level, and hand that one out`),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},p);let M=JSON.stringify(A.definition);return new TextEncoder().encode(M).byteLength>Ye?(_.error(`[palbase] ai.agent ${m}'s definition is larger than the ${Ye} bytes a machine's answer may be`),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},p)):new Response(M,{status:200,headers:{"content-type":"application/json","x-request-id":p,"cache-control":"no-store"}})}async function ma(i,c,p,u){let y=await ot(c,p,u,`A gateway's ${i}`);if(y instanceof Response)return y;let m=await K.serve(i,y.body,c.signal);return"code"in m?$({status:m.status,code:m.code,message:m.message,retryAfter:m.retryAfter},u):"body"in m?ce(200,m.body,u):new Response(null,{status:204,headers:{"x-request-id":u}})}async function Xn(i,c){let p=[],u={params:Object.freeze({...c.params}),user:ue(c.user),headers:i.meta.upload?new Headers:c.request.headers,requestId:c.requestId};for(let y of i.params)y.kind==="resolve"&&(p[y.index]=await l.get(y).resolve(u,y.options));return p}async function Xt(i,c,p,u){let y=t.get(i.controller),m=await Xe(e.database,p,c.request.signal,i.id,async()=>{let w=await Xn(i,c);for(let O of i.params)O.kind!=="resolve"&&(w[O.index]=await ra(O,c));u?.ran();let A=await y[i.fn](...w);if(c.uploadedObject&&c.request.signal.aborted)throw new Error(`storage gave up on ${i.id}'s upload before it was answered`);return u?u.record(Ys(ta(A,c.requestId),ne.getStore()?.usedLocales)):A});return u?m:Ys(ta(m,c.requestId),ne.getStore()?.usedLocales)}async function er(i,c){let p=i.headers.get("x-request-id")??"",u=Qi.test(p)?p:`req_${crypto.randomUUID()}`,y=performance.now(),m=new URL(i.url).pathname,w={endpoint:m},A=await ha(i,c,u,w);return e.telemetry?.record({requestId:u,method:i.method,endpoint:w.endpoint,path:m,status:A.status,durationMs:performance.now()-y,userId:w.userId}),A}function tr(i,c){i.userId=c;let p=ne.getStore();p&&(p.userId=c)}async function ha(i,c,p,u){let y=e.strings,m=y?{requestId:p,strings:y,locales:kr(i.headers.get("accept-language"),y.source),usedLocales:[]}:{requestId:p},w=await ga(m,i,c,p,u);return y&&Zt(w.headers,"Accept-Language"),w}async function ga(i,c,p,u,y){return ne.run(i,async()=>{let m=new URL(c.url),w=`${c.method} ${m.pathname}`;try{if(m.pathname===jn&&ye.size>0)return c.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},u):e.webhookSecret?await Yt(c,u):$({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},u);let A=Ue(m.pathname);if(A)return w=`webhook ${A.name}`,c.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},u):await st(c,m,A,u);if(e.platform&&(m.pathname===et||m.pathname.startsWith(`${et}/`)))return w=m.pathname===et?"crons":`cron ${m.pathname.slice(et.length+1)}`,await Le(c,m,e.platform.secret,u);if(e.platform&&(m.pathname===tt||m.pathname.startsWith(`${tt}/`)))return w=m.pathname===tt?"tasks":`task ${m.pathname.slice(tt.length+1)}`,await ca(c,m,e.platform.secret,u);if(e.platform&&(m.pathname===gn||m.pathname===Mr)){let C=m.pathname===gn?"authorize":"complete";return w=`upload ${C}`,await ua(C,c,e.platform.secret,u,y)}if(e.platform&&m.pathname.startsWith(`${yn}/`)){let C=m.pathname.slice(yn.length+1);return w=`gateway ${C}`,await ma(C,c,e.platform.secret,u)}if(e.platform&&m.pathname===hs)return w="ai tool call",await fa(c,e.platform.secret,u);if(e.platform&&m.pathname===gs)return w="ai agent's turn",await pa(c,e.platform.secret,u);if(e.platform&&m.pathname.startsWith(`${Mt}/`))return w=`test user template ${m.pathname.slice(Mt.length+1)}`,await la(c,m,e.platform.secret,u);if(a&&m.pathname===Ln){if(w="attest challenge",c.method!=="GET")return $({status:405,code:"method_not_allowed",message:"A challenge is asked for with GET"},u);let C=c.headers.get(oe.anchor)??"";if(C==="")return $({status:400,code:"installation_anchor_required",message:`A challenge is for an installation: send ${oe.anchor}`},u);if(!Ui.test(C))return $({status:400,code:"invalid_installation_anchor",message:`${oe.anchor} is the installation anchor auth issued (ins_\u2026)`},u);let fe=R.takeEach(`attest challenge\0a:${yt(c.headers,p.remoteAddress)}`,[Ni]);if(fe!==void 0)return $({status:429,code:"too_many_requests",message:"Too many challenges asked for from this address",retryAfter:fe},u);let Ie=await a.challengeFor(C);if("unavailable"in Ie)return $({status:503,code:"attest_unavailable",message:"The device's attestation cannot be checked right now",retryAfter:1},u);let Ce={"cache-control":"no-store","x-request-id":u};return Ie.challenge&&(Ce[oe.challenge]=Ie.challenge),new Response(null,{status:204,headers:Ce})}if(dd(m.pathname))return $({status:404,code:"not_found",message:`No route for ${c.method} ${m.pathname}`},u);let O=In(n,c.method,m.pathname);if(O&&"malformed"in O)return $({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},u);if(!O)return $({status:404,code:"not_found",message:`No route for ${c.method} ${m.pathname}`},u);let{route:M,params:P}=O;if(w=M.id,y.endpoint=M.id.slice(M.id.indexOf(" ")+1),M.meta.upload)throw new X(400,"upload_required",`${M.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let x=r.get(M),S=null,j=null,Z=c.headers.get("authorization")??"",H=/^(bearer|dpop)\s+(\S+)$/i.exec(Z),W=H?.[2],_e=H?.[1].toLowerCase()==="dpop";if(W)try{let C=!_e&&e.tokens&&!Xi.test(W)&&e.tokens.accepts(W)?e.tokens:void 0,fe=C?await L.ask(W,yt(c.headers,p.remoteAddress),()=>Xe(e.database,null,c.signal,"token",()=>C.resolve(W))):await e.verifier.verify(W,_e?{proof:c.headers.get("dpop"),method:c.method,url:fr(c.headers,m)}:void 0);S=Vi(fe),j=fe.claims}catch(C){if(!x.required&&(C instanceof At||C instanceof xt||C instanceof kt))S=null;else throw C instanceof kt?new X(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:C.wait},C.wait):C instanceof At?new X(401,"invalid_token","The access token is not valid",{reason:C.reason},void 0,zi(C.reason)):C}else if(Z!==""&&x.required)throw new X(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(S&&tr(y,S.id),x.required&&!S)throw new X(401,"unauthorized","This route needs a signed-in user");if(x.verifiedEmail&&!S?.emailVerified)throw new X(403,"email_not_verified","This route needs a verified email address");if(S&&ea(S.acr)<ea(x.aal))throw new X(401,"insufficient_user_authentication",`This route needs a sign-in at ${x.aal}: step up and call again`,Zs(x),void 0,Vs(x,_e));if(S&&x.maxAge!==null&&!Gi(S.authTime,x.maxAge,Date.now()))throw new X(401,"insufficient_user_authentication",`This route needs the user to have signed in or stepped up within the last ${x.maxAge} seconds: step up and call again`,Zs(x),void 0,Vs(x,_e));let nr=z(M);if(nr!==!1){let C=S?`u:${S.id}`:`a:${yt(c.headers,p.remoteAddress)}`,fe=R.takeEach(`${M.id}\0${C}`,nr);if(fe!==void 0)throw new X(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:fe},fe)}let Oe=c.method==="GET"||c.method==="HEAD"?void 0:await wt(c,G),en,rr=null;if(a&&s(M)){let C=await a.check(c,m,Oe,p.target);if("unavailable"in C)throw new X(503,"attest_unavailable","The device's attestation cannot be checked right now",void 0,1);if(!C.pass)throw new X(401,"app_attest_required","This route is called by the app on a device that attests",{reason:C.reason,challenge:C.challenge},void 0,void 0,{[oe.challenge]:C.challenge});en=C.challenge,rr=C.device??null}let $t=Oe===void 0?void 0:Ji(Oe),tn=m.searchParams,Pe=o.get(M),_t=c.headers.get(Et),it=Pe!==void 0||_t!==null?await d(M,P,_t,c.method):void 0;if(it&&Pe)try{if(Pe.body.length>0&&$t!==void 0&&($t=await it.open($t,"/body",Pe.body)),Pe.query.length>0){let C=await it.open(Object.fromEntries(m.searchParams),"/query",Pe.query);tn=new URLSearchParams(m.searchParams);for(let fe of Pe.query){let Ie=dr(fe.slice(7)),Ce=C[Ie];Ce!==void 0&&tn.set(Ie,typeof Ce=="string"?Ce:JSON.stringify(Ce))}}}catch(C){throw na(C)}let sr={request:c,query:tn,params:P,user:S,body:$t,raw:Oe,requestId:u,attested:rr},ar=E&&Oe!==void 0&&mt(M)?Ms(c.method,c.headers):void 0;if(!E||ar===void 0)return Qs(await Hn(await Xt(M,sr,j),it,u),en);let ya={role:Bn(e.database.requests,j).role,uid:S?.id??`a:${yt(c.headers,p.remoteAddress)}`},or=!1,wa=_t!==null?{uri:`${m.pathname}${m.search}`,body:ad(new TextEncoder().encode(`${_t}
|
|
21
|
+
`),Oe)}:{uri:`${m.pathname}${m.search}`,body:Oe},ba=C=>async fe=>C(await Hn(fe,it,u));return Qs(await E.serve({key:ar,caller:ya,method:c.method,...wa},C=>Xt(M,sr,j,{record:ba(C),ran:()=>{or=!0}}),{requestId:u,refusal:C=>$(C,u),failure:C=>Xs(C,u,w,c.signal),ran:()=>or}),en)}catch(A){return Xs(A,u,w,c.signal)}})}return{handle:Tt,routes:n.map(i=>i.id),contract:vt,start:()=>t.start(),stop:async()=>{K.close(),await a?.stop();for(let i of te.keys())V(i);await t.shutdown(),await e.telemetry?.flush()}}}function rd(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function sd(e){let t=new Set;for(let[n,r]of e)if(un(n))for(let s of r){if(s.bucket===void 0)return;t.add(s.bucket)}return t.size===0?void 0:[...t].sort()}function ta(e,t){if(e instanceof Response)return Wi(e,t);if(e==null)return Ht(new Response(null,{status:204,headers:{"x-request-id":t}}),null);if(gr()===0)return ce(200,e,t);let{value:n,pointers:r}=yr(e);return ce(200,n,t,r.length>0?{[Wn]:JSON.stringify(r)}:{})}var Wn="x-palbase-answer-encrypted";async function Hn(e,t,n){let r=e.headers.get(Wn);if(r===null)return e;if(!t)return await e.body?.cancel(),$({status:400,code:"encryption_required",message:`This route answers encrypted fields: the request names its key in ${Et}`,data:{field:Et}},n);let s=new Headers(e.headers);s.delete(Wn),s.delete("content-length");let a=await t.seal(await e.json(),JSON.parse(r)),o=JSON.stringify(a);return Ht(new Response(o,{status:e.status,statusText:e.statusText,headers:s}),Buffer.from(o,"utf8"))}function ad(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function na(e){return e instanceof cr?new X(e.status,e.code,e.message,e.data):e}function od(e){return`/${e.segments.map(t=>typeof t=="string"?t:"{}").join("/")}`}function id(e,t){if(!(!pt(e)||e.status!==503||!Kn(e)))return _.warn(`[palbase] webhook ${t}: the database did not answer (${e.error})`,{error:e}),{status:503,code:e.error,message:e.errorDescription,data:e.data,retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))}}function dd(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return Ge.has(decodeURIComponent(t))}catch{return Ge.has(t)}}var cd="GET, POST, PUT, PATCH, DELETE, QUERY",ud=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function ld(e){return ud.test(e)&&(!e.startsWith("http://")||/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(e))}function fd(e){if(!e)return;if(e.origins!=="*"){for(let r of e.origins)if(!ld(r))throw new TypeError(`cors origin ${JSON.stringify(r)} is https://host[:port] (http only for localhost), with no path`)}let t=e.origins==="*"?null:new Set(e.origins),n=String(e.maxAge??600);return{allows:r=>t===null||t.has(r),headers:r=>({"access-control-allow-origin":t===null?"*":r,"access-control-expose-headers":"idempotent-replayed, retry-after, x-request-id",vary:"Origin"}),preflight:(r,s)=>({"access-control-allow-origin":t===null?"*":r,"access-control-allow-methods":cd,"access-control-allow-headers":s&&/^[A-Za-z0-9-]+(\s*,\s*[A-Za-z0-9-]+)*$/.test(s)?s:"authorization, content-type","access-control-max-age":n,vary:"Origin"})}}async function ra(e,t){switch(e.kind){case"body":return qn(e.schema,t.body??{},"Request body");case"query":return qn(e.schema,ue(Object.fromEntries(t.query)),"Query parameters");case"headers":{let n={};return t.request.headers.forEach((r,s)=>n[s.toLowerCase()]=r),ue(n),e.schema?qn(e.schema,n,"Request headers"):n}case"param":return t.params[e.name];case"user":case"optionalUser":return ue(t.user);case"req":return t.raw===void 0?t.request:new Request(t.request.url,{method:t.request.method,headers:t.request.headers,body:t.raw,signal:t.request.signal});case"requestId":return t.requestId;case"resolve":throw new Error("@Resolve parameters are made by their resolver, before the others");case"uploadedObject":return t.uploadedObject;case"attestedDevice":return t.attested??null;case"client":{let n=t.request.headers;return ue({sdkVersion:n.get("x-palbase-sdk-version"),appVersion:n.get("x-palbase-client-version"),platform:n.get("x-platform"),osVersion:n.get("x-os-version")})}}}var Vn=720*3600;function Jn(e){return e instanceof ie&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function ia(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),Vn)}function da(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var Zn=class{filling=new Map;async get(t){try{let n=await be.cache.getCacheEntry({query:{key:t}});return n.data.found?n.data.value??null:null}catch(n){if(!Jn(n))throw n;return _.warn("cache: a read could not reach the cache; it is a miss",{key:t,status:n.status}),null}}async set(t,n,r){try{await be.cache.putCacheEntry({query:{key:t},body:{value:da(n),ttl:ia(r)}})}catch(s){if(!Jn(s))throw s;_.warn("cache: a write could not reach the cache; it is let go",{key:t,status:s.status})}}async del(t){await be.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await be.cache.incrementCacheEntry({query:{key:t}})).data.value}getOrSet(t,n,r){let s=this.filling.get(t);if(s)return s;let a=(async()=>{try{let o;try{o=(await be.cache.getCacheEntry({query:{key:t}})).data}catch(l){if(!Jn(l))throw l;_.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:l.status})}if(o?.found)return o.value??null;let d=await r();return await this.set(t,d,n),d}finally{this.filling.delete(t)}})();return this.filling.set(t,a),a}},Cu=Rt("Cache",new Zn);function Mu(e={}){let t=e.maxEntries??5e4,n=e.now??(()=>Date.now()),r=new Map,s=new Map,a=h=>{let g=r.get(h);if(g&&g.expiresAt<=n()){r.delete(h);return}return g},o=()=>{let h=n();for(let[b,k]of r)k.expiresAt<=h&&r.delete(b);if(r.size<t)return;let g=[...r.entries()].sort((b,k)=>b[1].expiresAt-k[1].expiresAt);for(let[b]of g.slice(0,Math.ceil(g.length/4)))r.delete(b)},d=async(h,g,b)=>{r.size>=t&&!r.has(h)&&o(),r.set(h,{value:da(g),expiresAt:n()+(ia(b)??Vn)*1e3})};return{get:async h=>{let g=a(h);return g?structuredClone(g.value):null},set:d,async del(h){r.delete(h)},async incr(h){let g=a(h),b=(typeof g?.value=="number"&&Number.isInteger(g.value)?g.value:0)+1;return r.set(h,{value:b,expiresAt:g?.expiresAt??n()+Vn*1e3}),b},getOrSet(h,g,b){let k=a(h);if(k)return Promise.resolve(structuredClone(k.value));let B=s.get(h);if(B)return B;let U=(async()=>{try{let q=await b();return await d(h,q,g),q}finally{s.delete(h)}})();return s.set(h,U),U}}}export{dn as a,Me as b,Be as c,gd as d,yd as e,wd as f,bd as g,kd as h,vd as i,Td as j,$d as k,_d as l,Ed as m,Sd as n,Ad as o,xd as p,Rd as q,Od as r,Pd as s,Cd as t,Md as u,jd as v,Dd as w,Nd as x,Ud as y,Ld as z,D as A,Id as B,qd as C,Pt as D,Fd as E,Wd as F,Zd as G,tc as H,nc as I,qa as J,Br as K,dc as L,cc as M,uc as N,lc as O,fc as P,pc as Q,mc as R,wc as S,Y as T,us as U,ls as V,fs as W,Ro as X,Sc as Y,Rc as Z,Oc as _,Pc as $,Cc as aa,Mc as ba,jc as ca,Dc as da,Nc as ea,Fc as fa,Mi as ga,xu as ha,ld as ia,Vn as ja,Cu as ka,Mu as la};
|