palbase 0.8.0 → 0.8.1

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.
Files changed (41) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +3 -3
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/5M3HV3X4.js +2 -0
  8. package/dist/chunks/{WEI32SAJ.js → 5RTSNQ4X.js} +2 -2
  9. package/dist/chunks/{BRBCWPR3.js → 6RXVXPHC.js} +1 -1
  10. package/dist/chunks/{JSJVV43D.js → 73R33XMD.js} +1 -1
  11. package/dist/chunks/{TUGRIOFX.js → 7XVI5JLP.js} +2 -2
  12. package/dist/chunks/{KDWDPSL2.js → CA4VJGGG.js} +1 -1
  13. package/dist/chunks/{RO5Y5YU4.js → KHHJRNAO.js} +1 -1
  14. package/dist/chunks/{5VTGMNPL.js → KJWHR5BP.js} +6 -6
  15. package/dist/chunks/{PDOHT46N.js → KYJJJUEU.js} +2 -2
  16. package/dist/chunks/{K6RRNI23.js → M4XLAPDF.js} +2 -2
  17. package/dist/chunks/{RBA6V3UO.js → MAYLG7WE.js} +2 -2
  18. package/dist/chunks/NSQAN2ME.js +6 -0
  19. package/dist/chunks/{WINBISC2.js → Q4XTWEAW.js} +3 -3
  20. package/dist/chunks/{BO5KR2EQ.js → RYI2OB52.js} +2 -2
  21. package/dist/chunks/{P4Z5E6ZI.js → RZ525VLP.js} +2 -2
  22. package/dist/chunks/{PGPQGKH2.js → T2Q5CKLL.js} +2 -2
  23. package/dist/chunks/{EGNEXFTZ.js → Y6AQWQBE.js} +2 -2
  24. package/dist/chunks/{Z5JVQNAZ.js → ZSKMWUIQ.js} +2 -2
  25. package/dist/cli.js +101 -101
  26. package/dist/refuse/ai.js +1 -1
  27. package/dist/refuse/backend.js +1 -1
  28. package/dist/refuse/server.js +1 -1
  29. package/dist/server/index.js +2 -2
  30. package/dist/server/testing.js +2 -2
  31. package/dist/web/index.js +2 -2
  32. package/dist/web/palbe.js +2 -2
  33. package/dist/web/paywall.js +2 -2
  34. package/dist/web/ssr.js +2 -2
  35. package/dist/web/vite.js +2 -2
  36. package/package.json +4 -2
  37. package/types/internal/src/modules/purchases.d.ts +109 -1
  38. package/types/web/src/index.d.ts +1 -1
  39. package/types/web/src/purchases.d.ts +48 -5
  40. package/dist/chunks/DB3SIBKB.js +0 -2
  41. package/dist/chunks/FZ3MQOVA.js +0 -6
@@ -1,8 +1,8 @@
1
- /*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
2
- import{a as mt,c as se,d as Un,e as Ln,f as ge,h as _,i as In}from"./K6RRNI23.js";import{b as Ze,d as lt,e as jn,f as Mn,g as ft,h as pt,k as Dn,q as Nn}from"./Z5JVQNAZ.js";import{b as pe}from"./PDOHT46N.js";import"reflect-metadata";var Ut=[{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}],zn="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)",ht=/^\d+$/;function Es(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),i=1;if(a!==-1){let g=s.slice(a+1);if(!ht.test(g)||Number(g)<1||Number(g)>n)return;i=Number(g)}let u=t,p=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),k=o.slice(0,g),x=o.slice(g+1);if(!ht.test(k)||!ht.test(x)||Number(k)<t||Number(x)>n||Number(k)>Number(x))return;u=Number(k),p=Number(x)}else{if(!ht.test(o)||Number(o)<t||Number(o)>n)return;u=Number(o),p=a===-1?u:n}for(let g=u;g<=p;g+=i)r.add(g)}return r}function Gn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${zn}; "${e}" is not`;let n=[];for(let p=0;p<5;p++){let g=Es(t[p],Ut[p].lo,Ut[p].hi);if(!g)return`${zn}; its ${Ut[p].name} "${t[p]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),i=t[4].startsWith("*"),u=new Date(Date.UTC(2e3,0,1));for(let p=0;p<366*8+2;p++,u.setUTCDate(u.getUTCDate()+1)){if(!s.has(u.getUTCMonth()+1))continue;let g=r.has(u.getUTCDate()),k=a.has(u.getUTCDay());if(o||i?g&&k:g||k)return}return`"${e}" is never due: no date has that day in that month`}var Pe=Symbol.for("palbase.backend.controller"),Ce=Symbol.for("palbase.backend.routes"),It=Symbol.for("palbase.backend.params"),zt=Symbol.for("palbase.backend.injectable"),Gt=Symbol.for("palbase.backend.module"),Se=Symbol.for("palbase.backend.events"),je=Symbol.for("palbase.backend.webhook"),we=Symbol.for("palbase.backend.crons"),ye=Symbol.for("palbase.backend.tasks");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 Lt=Symbol.for("palbase.backend.declared");function ce(){let e=globalThis;return e[Lt]instanceof Set||(e[Lt]=new Set),e[Lt]}var Me=new Set(["webhooks","_palbase"]);function ii(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&&Me.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,Pe,()=>({basePath:e,options:t})),ce().add(n)}}function De(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,Ce,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var di=De("GET"),ci=De("POST"),ui=De("PUT"),li=De("PATCH"),fi=De("DELETE"),pi=De("QUERY");function ue(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,It,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function Ht(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 mi=e=>ue("body",{schema:Ht("Body",e)}),hi=e=>ue("query",{schema:Ht("QueryParams",e)}),gi=e=>ue("headers",e===void 0?{}:{schema:Ht("Headers",e)}),yi=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},wi=()=>ue("user"),bi=()=>ue("optionalUser"),ki=()=>ue("req"),vi=()=>ue("requestId"),$i=()=>ue("requestId"),Ti=()=>ue("client");function Si(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 ue("resolve",{resolver:e,options:t[0]})}function Ei(){return e=>{de(e,zt,()=>!0),ce().add(e)}}function _i(e){return t=>{de(t,Gt,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Fn=/^[a-z]+(\.[a-z_]+)+$/,_s=/^[a-z][a-z0-9-]{1,62}$/,qt=e=>e.startsWith("file.");function xi(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"||!_s.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(!qt(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,Se,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),ce().add(r.constructor)}}var Ft=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,xs=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Hn(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(!xs.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 Oi(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Ft.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=Gn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Hn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Hn(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,we))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,we,{value:s,enumerable:!1}),ce().add(a)}}var qn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Os=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ri(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(!Os.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&&!qn.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${qn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&Rs(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=U(t,Se)??[];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:i}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${i}" }) \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,je,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:i})=>({event:o,fn:i}))})),ce().add(t)}}function Rs(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 U(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ai(){return[...ce()].filter(e=>U(e,Pe)!==void 0)}function Pi(e){return(U(e,Ce)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var gt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Ni(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Ft.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,ye))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ye,{value:r,enumerable:!1}),ce().add(s)}}var Jt;function Kn(e){Jt=e}function Bt(){if(!Jt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return Jt}var As=720*3600;function Ps(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>As))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 Cs(e){if(typeof e=="string")return e;let t=e[ye];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Ui=mt("Tasks",{async enqueue(e,t,n={}){return Ps(n),Bt().enqueue(Cs(e),t===void 0?null:t,n)},async cancel(e,t={}){return Bt().cancel(e,t.machine)},async get(e,t={}){return Bt().get(e,t.machine)}}),Kt=(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 Jn(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 ge.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 Kt(a.data,a.status===200)},async cancel(n,r){return Kt((await ge.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return Kt((await ge.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var js=1e4,Ms=36e5,Bn=24*36e5,yt=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 pe({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 pe({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 pe({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 u of this.tasks.values())if(u.task===t&&u.key===r.key&&(u.finishedAt===void 0||this.now()-u.finishedAt<Bn))return this.view(u,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,i={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(i.id,i),this.schedule(i),this.view(i,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new pe({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 pe({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(i){a={status:500,message:i.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(js*2**Math.min(t.attempt-1,16),Ms),_.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>=Bn&&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 Wt="/_palbase/storage/upload/authorize",Wn="/_palbase/storage/upload/complete",Vt="/_palbase/realtime/rooms";var Ds=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ne(e){if(!Ds(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 Vn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Zn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function wt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ns=/^[a-z][a-z0-9-]{1,62}$/,Qn=1024,Us=new Set(["userId","uploadId","filename"]);function Hi(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`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Ns.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" 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 r=Ls(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,i,u)=>{if(typeof i!="string"||u===void 0||typeof u.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(o.constructor,Ce,()=>[]).push({method:"POST",subpath:e,fn:i,options:a,upload:s})}}function qi(){return ue("uploadedObject")}function Ls(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Us.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(!Yn(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Yn(e){if(e===""||new TextEncoder().encode(e).byteLength>Qn)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 Is(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>zs(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function zs(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 Xn(e,t){let n=Is(e,t);return Yn(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Qn} bytes)`}}function er(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 Zt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function tr(e,t){if(!Zt(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=Ne(t.user);if(!o)return"user is { id?, session?, role }";let i=Vn(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,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let u=Gs(t.uploadedObject);return u?u.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...i?{client:i}:{},filename:"",uploadedObject:u,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Gs(e){if(!Zt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:i,height:u,thumbhash:p,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)&&!(i!==void 0&&typeof i!="number"||u!==void 0&&typeof u!="number"||p!==void 0&&typeof p!="string")&&!(!Zt(g)||!Object.values(g).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...i!==void 0?{width:i}:{},...u!==void 0?{height:u}:{},...p!==void 0?{thumbhash:p}:{},variants:{...g}}}import{markData as Hs}from"palgres";var Ee=Symbol.for("palbase.backend.gateway"),Ie=Symbol.for("palbase.backend.gatewayHooks"),nr={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"]},qs={"~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(nr),output:()=>structuredClone(nr)}}},cr=Symbol.for("palbase.backend.gatewayRefusal"),rr=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,cr,{value:!0})}},Fs=e=>typeof e=="object"&&e!==null&&e[cr]===!0&&typeof e.reason=="string",Ue=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Bs=6e4,Ks=86400,sr=604800,ar=65536,be=255,Js=["roles:","flags:","messaging:","debug:"],Ws=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(" ")),Le=e=>new TextEncoder().encode(e).byteLength,Qt=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",en=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Vs(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(Le(e)>be)return`a channel is ${be} 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=Js.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 ur(e){if(typeof e!="string"||e==="")return"is a name";if(Le(e)>be)return`is ${be} bytes at most`}function Vi(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Vs(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"&&en(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=Zs(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)||Ws.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 i=a.events??{};if(typeof i!="object"||i===null||Array.isArray(i))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(i,"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,k]of Object.entries(i)){let x=ur(g);if(x)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${x}`);if(!Qt(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let u=de(a,Ie,tn),p={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...i,chat:qs}:{...i},chat:r.chat===!0,graceMs:r.graceMs??Bs,hooks:{...u.hooks},messages:Object.assign(Object.create(null),u.messages)};if(p.access===void 0&&p.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(p.access!==void 0&&p.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${p.access}' and @Authorize both say who may join \u2014 keep one`);if(p.publish&&Ue(p))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(p.publish&&p.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(p.chat&&!Ue(p))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,Ee,()=>p),ce().add(a)}}function Zs(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ks;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>sr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${sr} (a week)`);return n}var tn=()=>({hooks:Object.create(null),messages:Object.create(null)}),Qs={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function Qe(e){let t=Qs[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,Ie,tn),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,ce().add(n.constructor)}}var Zi=Qe("authorize"),Qi=Qe("first"),Yi=Qe("connect"),Xi=Qe("disconnect"),ed=Qe("empty");function td(e,t,n={}){let r=ur(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!Qt(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!Qt(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 i=de(s.constructor,Ie,tn),u=i.messages[e];if(u!==void 0&&u.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${u.fn} and ${a}).`);i.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},ce().add(s.constructor)}}function Ys(e){return U(e,Ee)}function Xs(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 lr(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 Le(r)>be?{problem:`a channel is ${be} bytes at most`}:r}function ea(e,t,n){let r=en(e).map(i=>i.slice(1,-1));for(let i of Object.keys(t))if(!r.includes(i))return{problem:`{${i}} 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(i=>Object.hasOwn(t,i))?lr(e,t):ta(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(i=>`{${i}}`).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 ta(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 na=1e4,ra=1e3,sa=100,nn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),me=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),or={first:"first",join:"connect",leave:"disconnect",empty:"empty"},ir=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function fr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:E}of e){let w=Ys(b),T=a.get(w.name);if(T!==void 0&&T!==b)throw new TypeError(`@Gateway("${w.pattern}"): two gateways are named ${w.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(w.name,b);let O=s.get(ir(w.pattern));if(O!==void 0)throw new TypeError(`@Gateway("${w.pattern}") on ${b.name}: ${n.get(O)?.cls.name}'s "${O}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(ir(w.pattern),w.pattern);for(let[q,J]of[...Object.entries(w.hooks),...Object.entries(w.messages).map(([I,j])=>[`message ${I}`,j.fn])])if(typeof E[J]!="function")throw new TypeError(`@Gateway("${w.pattern}") on ${b.name}: its ${q} is ${J}, which is no method of it`);let N={cls:b,instance:E,g:w};n.set(w.pattern,N),r.set(b,N)}let o=new Map,i=new Set,u=new Set,p=new Xt(t.broadcast),g=b=>{let E=o.get(b);return E||(E=new AbortController,o.set(b,E)),E},k=(b,E)=>{E?.abort(),o.get(b)===E&&o.delete(b)},x=(b,E,w,T,O,N)=>{if(!Object.hasOwn(b.g.events,w)){_.warn(`[palbase] ${O}: emit("${w}") is not sent \u2014 ${b.cls.name} declares no event "${w}" (static events)`);return}if(b.g.chat&&w==="chat"){_.warn(`[palbase] ${O}: emit("chat") is not sent \u2014 ${b.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}p.send({topic:E,event:w,payload:T??{},...N!==void 0?{conn_id:N}:{}},O)},W=async(b,E,w)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${w}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(E)};function L(b,E,w,T,O,N,q){let J=T?.signal??AbortSignal.abort(),I=`${b.cls.name} (${E})`;return{channel:E,params:Object.freeze({...w}),signal:J,count:O,user:N,emit:(j,G)=>x(b,E,j,G,I,q),pipe:j=>W(j,E,I),owner:{hold(j){se.exit(async()=>{try{await j(J)}catch(G){J.aborted||_.error(`[palbase] ${I}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(E,T)}}}function z(b){let{room:E,channel:w}=b;if(typeof E!="string"||typeof w!="string")return me(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!Ue(T.g)?me(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:w,params:Xs(E,w)}}let Z=(b,E)=>me(400,"bad_request",`"${E}" is not a channel of the gateway "${b}"`);async function Y(b,E){let w=z(b);if("status"in w)return w;let{entry:T,channel:O,params:N}=w,q={status:200,body:{subscribe:!1,publish:!1}};if(!N)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${O}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),q;let J=Ne(b.user),I=J?.id;if(!I)return q;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 N[en(T.g.pattern)[0].slice(1,-1)]===I?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:q;let j=T.g.hooks.authorize;if(!j)return q;let G,F;try{G=await t.run(J,`${T.cls.name}.${j}`,E,async()=>T.instance[j]({user:{id:I},params:Object.freeze({...N})})),F=aa(G)}catch(oe){if(t.isOutage(oe)||E?.aborted)throw oe;return _.error(`[palbase] ${T.cls.name}.${j} (@Authorize of ${O}) failed; the join is refused`,{error:oe}),q}return F==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${j} (@Authorize of ${O}) answered ${oa(G)}, which is no grant (true, { read, write } or null); the join is refused`),q):{status:200,body:F}}async function ne(b,E){let w=z(b);if("status"in w)return w;if(!w.params)return Z(w.entry.g.pattern,w.channel);let T=Ne(b.user);if(!T?.id||typeof b.event!="string")return me(400,"bad_request","A message names its member (user) and its event");let O=Object.hasOwn(w.entry.g.messages,b.event)?w.entry.g.messages[b.event]:void 0;if(!O)return{status:200,body:{ok:!1,reason:Yt(`gateway "${w.channel}" takes no message "${b.event}"`,bt)}};let N=await O.schema["~standard"].validate(Hs(b.payload??{}));if(N.issues)return{status:200,body:{ok:!1,reason:dr(N.issues)}};let q=g(w.channel),J={...L(w.entry,w.channel,w.params,q,0,{id:T.id}),payload:N.value},I=`${w.entry.cls.name}.${O.fn} (@Subscribe "${b.event}" of ${w.channel})`,j;try{j=await t.run(T,`${w.entry.cls.name}.${O.fn}`,E,async()=>w.entry.instance[O.fn](J))}catch(F){if(t.isOutage(F))throw F;return Fs(F)?{status:200,body:{ok:!1,reason:Yt(F.reason,bt)}}:(E?.aborted||_.error(`[palbase] ${I} failed`,{error:F}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(j===void 0)return{status:200,body:{ok:!0}};if(O.reply){let F=await O.reply["~standard"].validate(j);if(F.issues)return _.error(`[palbase] ${I} returned an ack its reply schema refuses (${dr(F.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};j=F.value}let G;try{G=JSON.stringify(j)}catch(F){return _.error(`[palbase] ${I} returned an ack that is not JSON; the member is told it failed`,{error:F}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Le(G)>ar?(_.error(`[palbase] ${I} returned an ack of ${Le(G)} bytes, past ${ar}; 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 v(b,E){let w=z(b);if("status"in w)return w;if(!w.params)return Z(w.entry.g.pattern,w.channel);let T=b.event;if(typeof T!="string"||!Object.hasOwn(or,T))return me(400,"bad_request","A gateway's moment is first, join, leave or empty");let O=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(O===void 0)return me(400,"bad_request","A gateway's moment says its count of members");let N=T==="join"||T==="leave",q=N?Ne(b.user):void 0,J=N?b.connId:void 0;if(N&&(!q?.id||typeof J!="string"||J===""))return me(400,"bad_request",`A ${T} names its member: user and connId`);let I=`${T}\0${w.channel}\0${typeof J=="string"?J:""}`;if(N&&i.has(I))return{status:204};if(u.has(I))return me(503,"in_progress","This moment of the gateway is being handled",5);u.add(I);try{let j=w.entry.g.hooks[or[T]],G;if(T==="empty"?(G=o.get(w.channel),k(w.channel,G)):G=T==="leave"?o.get(w.channel):g(w.channel),j){let F=L(w.entry,w.channel,w.params,G,O,{id:q?.id??""},T==="join"?J:void 0);try{await t.run(q,`${w.entry.cls.name}.${j}`,E,async()=>w.entry.instance[j](F))}catch(oe){if(t.isOutage(oe))throw oe;return E?.aborted||_.error(`[palbase] ${w.entry.cls.name}.${j} (${T} of ${w.channel}) failed; realtime tells it again`,{error:oe}),me(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return N&&(i.add(I),i.size>na&&i.delete(i.values().next().value)),{status:204}}finally{u.delete(I)}}function X(b,E){let w=r.get(b),T=`Palbase.gateways.to(${b?.name??String(b)})`;if(!w)throw new TypeError(`${T}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let O=lr(w.g.pattern,E??{});if(typeof O!="string")throw new TypeError(`${T}: ${O.problem}`);return{entry:w,channel:O,where:T}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,E,w){return nn(E)?b==="authorize"?Y(E,w):b==="message"?ne(E,w):b==="lifecycle"?v(E,w):me(404,"not_found",`No gateway call ${JSON.stringify(b)}`):me(400,"bad_request","A gateway's call is a JSON object")},emit(b,E,w,T){let{entry:O,channel:N,where:q}=X(b,E);x(O,N,w,T,q)},async pipe(b,E,w){let{channel:T,where:O}=X(b,E);await W(w,T,O)},async revalidate(b,E,w={}){let T=r.get(b),O=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!T)throw new TypeError(`${O}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let N=ea(T.g.pattern,E??{},w);if("problem"in N)throw new TypeError(`${O}: ${N.problem}`);await t.revalidate(N)},close(){for(let b of o.values())b.abort();o.clear()}}}function aa(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!nn(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 oa(e){return Array.isArray(e)?"an array":nn(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 ia=20,bt=256;function dr(e){let t="";for(let n of e.slice(0,ia)){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)>=bt)break}return Yt(t,bt)}function Yt(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 Xt=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Le(t.event)>be){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${be} bytes`);return}try{JSON.stringify(t.payload)}catch(a){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=ra?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),se.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,sa);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 rn,createHmac as da,createPublicKey as gr,timingSafeEqual as ca,verify as yr}from"node:crypto";function ad(e){let t=U(e,je);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 wr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let i=U(o,je),u=s.get(i.name);if(u)throw new TypeError(`@Webhook "${i.name}" is declared by ${u.cls.name} and by ${o.name}: /webhooks/${i.name} is one endpoint`);let p=`@Webhook "${i.name}" (${o.name})`,g=n[i.secret.env],k;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${p} reads its signing secret from ${i.secret.env}, which is not set`);else try{k=ua(i,g)}catch(L){a.push(`${p}: ${i.secret.env} ${L.message}`)}let x=t(o),W=new Map(i.events.map(({event:L,fn:z})=>[L,{name:`${o.name}.${z}`,call:(Z,Y)=>x[z](Z,Y)}]));s.set(i.name,{name:i.name,cls:o,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:k,events:W})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
1
+ /*! palbase 0.8.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as ht,c as se,d as Un,e as Ln,f as ge,h as _,i as In}from"./M4XLAPDF.js";import{b as Ze,d as ft,e as jn,f as Mn,g as pt,h as mt,k as Dn,q as Nn}from"./ZSKMWUIQ.js";import{b as pe}from"./KYJJJUEU.js";import"reflect-metadata";var Lt=[{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}],zn="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)",gt=/^\d+$/;function Es(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),i=1;if(a!==-1){let g=s.slice(a+1);if(!gt.test(g)||Number(g)<1||Number(g)>n)return;i=Number(g)}let u=t,p=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),k=o.slice(0,g),x=o.slice(g+1);if(!gt.test(k)||!gt.test(x)||Number(k)<t||Number(x)>n||Number(k)>Number(x))return;u=Number(k),p=Number(x)}else{if(!gt.test(o)||Number(o)<t||Number(o)>n)return;u=Number(o),p=a===-1?u:n}for(let g=u;g<=p;g+=i)r.add(g)}return r}function Gn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${zn}; "${e}" is not`;let n=[];for(let p=0;p<5;p++){let g=Es(t[p],Lt[p].lo,Lt[p].hi);if(!g)return`${zn}; its ${Lt[p].name} "${t[p]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),i=t[4].startsWith("*"),u=new Date(Date.UTC(2e3,0,1));for(let p=0;p<366*8+2;p++,u.setUTCDate(u.getUTCDate()+1)){if(!s.has(u.getUTCMonth()+1))continue;let g=r.has(u.getUTCDate()),k=a.has(u.getUTCDay());if(o||i?g&&k:g||k)return}return`"${e}" is never due: no date has that day in that month`}var Pe=Symbol.for("palbase.backend.controller"),Ce=Symbol.for("palbase.backend.routes"),zt=Symbol.for("palbase.backend.params"),Gt=Symbol.for("palbase.backend.injectable"),Ht=Symbol.for("palbase.backend.module"),Se=Symbol.for("palbase.backend.events"),je=Symbol.for("palbase.backend.webhook"),we=Symbol.for("palbase.backend.crons"),ye=Symbol.for("palbase.backend.tasks");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 It=Symbol.for("palbase.backend.declared");function ce(){let e=globalThis;return e[It]instanceof Set||(e[It]=new Set),e[It]}var Me=new Set(["webhooks","_palbase"]);function ii(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&&Me.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,Pe,()=>({basePath:e,options:t})),ce().add(n)}}function De(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,Ce,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var di=De("GET"),ci=De("POST"),ui=De("PUT"),li=De("PATCH"),fi=De("DELETE"),pi=De("QUERY");function ue(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,zt,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function qt(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 mi=e=>ue("body",{schema:qt("Body",e)}),hi=e=>ue("query",{schema:qt("QueryParams",e)}),gi=e=>ue("headers",e===void 0?{}:{schema:qt("Headers",e)}),yi=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},wi=()=>ue("user"),bi=()=>ue("optionalUser"),ki=()=>ue("req"),vi=()=>ue("requestId"),$i=()=>ue("requestId"),Ti=()=>ue("client");function Si(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 ue("resolve",{resolver:e,options:t[0]})}function Ei(){return e=>{de(e,Gt,()=>!0),ce().add(e)}}function _i(e){return t=>{de(t,Ht,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Fn=/^[a-z]+(\.[a-z_]+)+$/,_s=/^[a-z][a-z0-9-]{1,62}$/,Ft=e=>e.startsWith("file.");function xi(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"||!_s.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(!Ft(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,Se,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),ce().add(r.constructor)}}var Bt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,xs=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Hn(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(!xs.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 Oi(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Bt.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=Gn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Hn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Hn(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,we))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,we,{value:s,enumerable:!1}),ce().add(a)}}var qn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Os=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ri(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(!Os.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&&!qn.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${qn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&Rs(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=U(t,Se)??[];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:i}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${i}" }) \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,je,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:i})=>({event:o,fn:i}))})),ce().add(t)}}function Rs(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 U(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ai(){return[...ce()].filter(e=>U(e,Pe)!==void 0)}function Pi(e){return(U(e,Ce)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var yt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Ni(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Bt.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,ye))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ye,{value:r,enumerable:!1}),ce().add(s)}}var Wt;function Kn(e){Wt=e}function Kt(){if(!Wt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return Wt}var As=720*3600;function Ps(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>As))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 Cs(e){if(typeof e=="string")return e;let t=e[ye];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Ui=ht("Tasks",{async enqueue(e,t,n={}){return Ps(n),Kt().enqueue(Cs(e),t===void 0?null:t,n)},async cancel(e,t={}){return Kt().cancel(e,t.machine)},async get(e,t={}){return Kt().get(e,t.machine)}}),Jt=(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 Jn(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 ge.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 Jt(a.data,a.status===200)},async cancel(n,r){return Jt((await ge.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return Jt((await ge.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var js=1e4,Ms=36e5,Bn=24*36e5,wt=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 pe({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 pe({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 pe({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 u of this.tasks.values())if(u.task===t&&u.key===r.key&&(u.finishedAt===void 0||this.now()-u.finishedAt<Bn))return this.view(u,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,i={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(i.id,i),this.schedule(i),this.view(i,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new pe({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 pe({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(i){a={status:500,message:i.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(js*2**Math.min(t.attempt-1,16),Ms),_.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>=Bn&&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 Vt="/_palbase/storage/upload/authorize",Wn="/_palbase/storage/upload/complete",Zt="/_palbase/realtime/rooms";var Ds=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ne(e){if(!Ds(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 Vn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Zn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function bt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ns=/^[a-z][a-z0-9-]{1,62}$/,Qn=1024,Us=new Set(["userId","uploadId","filename"]);function Hi(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`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Ns.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" 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 r=Ls(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,i,u)=>{if(typeof i!="string"||u===void 0||typeof u.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(o.constructor,Ce,()=>[]).push({method:"POST",subpath:e,fn:i,options:a,upload:s})}}function qi(){return ue("uploadedObject")}function Ls(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Us.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(!Yn(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Yn(e){if(e===""||new TextEncoder().encode(e).byteLength>Qn)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 Is(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>zs(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function zs(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 Xn(e,t){let n=Is(e,t);return Yn(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Qn} bytes)`}}function er(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 Qt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function tr(e,t){if(!Qt(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=Ne(t.user);if(!o)return"user is { id?, session?, role }";let i=Vn(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,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let u=Gs(t.uploadedObject);return u?u.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...i?{client:i}:{},filename:"",uploadedObject:u,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Gs(e){if(!Qt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:i,height:u,thumbhash:p,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)&&!(i!==void 0&&typeof i!="number"||u!==void 0&&typeof u!="number"||p!==void 0&&typeof p!="string")&&!(!Qt(g)||!Object.values(g).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...i!==void 0?{width:i}:{},...u!==void 0?{height:u}:{},...p!==void 0?{thumbhash:p}:{},variants:{...g}}}import{markData as Hs}from"palgres";var Ee=Symbol.for("palbase.backend.gateway"),Ie=Symbol.for("palbase.backend.gatewayHooks"),nr={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"]},qs={"~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(nr),output:()=>structuredClone(nr)}}},cr=Symbol.for("palbase.backend.gatewayRefusal"),rr=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,cr,{value:!0})}},Fs=e=>typeof e=="object"&&e!==null&&e[cr]===!0&&typeof e.reason=="string",Ue=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Bs=6e4,Ks=86400,sr=604800,ar=65536,be=255,Js=["roles:","flags:","messaging:","debug:"],Ws=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(" ")),Le=e=>new TextEncoder().encode(e).byteLength,Yt=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Vs(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(Le(e)>be)return`a channel is ${be} 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=Js.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 ur(e){if(typeof e!="string"||e==="")return"is a name";if(Le(e)>be)return`is ${be} bytes at most`}function Vi(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Vs(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=Zs(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)||Ws.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 i=a.events??{};if(typeof i!="object"||i===null||Array.isArray(i))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(i,"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,k]of Object.entries(i)){let x=ur(g);if(x)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${x}`);if(!Yt(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let u=de(a,Ie,nn),p={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...i,chat:qs}:{...i},chat:r.chat===!0,graceMs:r.graceMs??Bs,hooks:{...u.hooks},messages:Object.assign(Object.create(null),u.messages)};if(p.access===void 0&&p.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(p.access!==void 0&&p.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${p.access}' and @Authorize both say who may join \u2014 keep one`);if(p.publish&&Ue(p))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(p.publish&&p.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(p.chat&&!Ue(p))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,Ee,()=>p),ce().add(a)}}function Zs(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ks;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>sr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${sr} (a week)`);return n}var nn=()=>({hooks:Object.create(null),messages:Object.create(null)}),Qs={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function Qe(e){let t=Qs[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,Ie,nn),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,ce().add(n.constructor)}}var Zi=Qe("authorize"),Qi=Qe("first"),Yi=Qe("connect"),Xi=Qe("disconnect"),ed=Qe("empty");function td(e,t,n={}){let r=ur(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!Yt(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!Yt(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 i=de(s.constructor,Ie,nn),u=i.messages[e];if(u!==void 0&&u.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${u.fn} and ${a}).`);i.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},ce().add(s.constructor)}}function Ys(e){return U(e,Ee)}function Xs(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 lr(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 Le(r)>be?{problem:`a channel is ${be} bytes at most`}:r}function ea(e,t,n){let r=tn(e).map(i=>i.slice(1,-1));for(let i of Object.keys(t))if(!r.includes(i))return{problem:`{${i}} 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(i=>Object.hasOwn(t,i))?lr(e,t):ta(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(i=>`{${i}}`).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 ta(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 na=1e4,ra=1e3,sa=100,rn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),me=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),or={first:"first",join:"connect",leave:"disconnect",empty:"empty"},ir=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function fr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:E}of e){let w=Ys(b),T=a.get(w.name);if(T!==void 0&&T!==b)throw new TypeError(`@Gateway("${w.pattern}"): two gateways are named ${w.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(w.name,b);let O=s.get(ir(w.pattern));if(O!==void 0)throw new TypeError(`@Gateway("${w.pattern}") on ${b.name}: ${n.get(O)?.cls.name}'s "${O}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(ir(w.pattern),w.pattern);for(let[q,J]of[...Object.entries(w.hooks),...Object.entries(w.messages).map(([I,j])=>[`message ${I}`,j.fn])])if(typeof E[J]!="function")throw new TypeError(`@Gateway("${w.pattern}") on ${b.name}: its ${q} is ${J}, which is no method of it`);let N={cls:b,instance:E,g:w};n.set(w.pattern,N),r.set(b,N)}let o=new Map,i=new Set,u=new Set,p=new en(t.broadcast),g=b=>{let E=o.get(b);return E||(E=new AbortController,o.set(b,E)),E},k=(b,E)=>{E?.abort(),o.get(b)===E&&o.delete(b)},x=(b,E,w,T,O,N)=>{if(!Object.hasOwn(b.g.events,w)){_.warn(`[palbase] ${O}: emit("${w}") is not sent \u2014 ${b.cls.name} declares no event "${w}" (static events)`);return}if(b.g.chat&&w==="chat"){_.warn(`[palbase] ${O}: emit("chat") is not sent \u2014 ${b.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}p.send({topic:E,event:w,payload:T??{},...N!==void 0?{conn_id:N}:{}},O)},W=async(b,E,w)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${w}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(E)};function L(b,E,w,T,O,N,q){let J=T?.signal??AbortSignal.abort(),I=`${b.cls.name} (${E})`;return{channel:E,params:Object.freeze({...w}),signal:J,count:O,user:N,emit:(j,G)=>x(b,E,j,G,I,q),pipe:j=>W(j,E,I),owner:{hold(j){se.exit(async()=>{try{await j(J)}catch(G){J.aborted||_.error(`[palbase] ${I}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(E,T)}}}function z(b){let{room:E,channel:w}=b;if(typeof E!="string"||typeof w!="string")return me(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!Ue(T.g)?me(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:w,params:Xs(E,w)}}let Z=(b,E)=>me(400,"bad_request",`"${E}" is not a channel of the gateway "${b}"`);async function Y(b,E){let w=z(b);if("status"in w)return w;let{entry:T,channel:O,params:N}=w,q={status:200,body:{subscribe:!1,publish:!1}};if(!N)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${O}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),q;let J=Ne(b.user),I=J?.id;if(!I)return q;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 N[tn(T.g.pattern)[0].slice(1,-1)]===I?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:q;let j=T.g.hooks.authorize;if(!j)return q;let G,F;try{G=await t.run(J,`${T.cls.name}.${j}`,E,async()=>T.instance[j]({user:{id:I},params:Object.freeze({...N})})),F=aa(G)}catch(oe){if(t.isOutage(oe)||E?.aborted)throw oe;return _.error(`[palbase] ${T.cls.name}.${j} (@Authorize of ${O}) failed; the join is refused`,{error:oe}),q}return F==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${j} (@Authorize of ${O}) answered ${oa(G)}, which is no grant (true, { read, write } or null); the join is refused`),q):{status:200,body:F}}async function ne(b,E){let w=z(b);if("status"in w)return w;if(!w.params)return Z(w.entry.g.pattern,w.channel);let T=Ne(b.user);if(!T?.id||typeof b.event!="string")return me(400,"bad_request","A message names its member (user) and its event");let O=Object.hasOwn(w.entry.g.messages,b.event)?w.entry.g.messages[b.event]:void 0;if(!O)return{status:200,body:{ok:!1,reason:Xt(`gateway "${w.channel}" takes no message "${b.event}"`,kt)}};let N=await O.schema["~standard"].validate(Hs(b.payload??{}));if(N.issues)return{status:200,body:{ok:!1,reason:dr(N.issues)}};let q=g(w.channel),J={...L(w.entry,w.channel,w.params,q,0,{id:T.id}),payload:N.value},I=`${w.entry.cls.name}.${O.fn} (@Subscribe "${b.event}" of ${w.channel})`,j;try{j=await t.run(T,`${w.entry.cls.name}.${O.fn}`,E,async()=>w.entry.instance[O.fn](J))}catch(F){if(t.isOutage(F))throw F;return Fs(F)?{status:200,body:{ok:!1,reason:Xt(F.reason,kt)}}:(E?.aborted||_.error(`[palbase] ${I} failed`,{error:F}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(j===void 0)return{status:200,body:{ok:!0}};if(O.reply){let F=await O.reply["~standard"].validate(j);if(F.issues)return _.error(`[palbase] ${I} returned an ack its reply schema refuses (${dr(F.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};j=F.value}let G;try{G=JSON.stringify(j)}catch(F){return _.error(`[palbase] ${I} returned an ack that is not JSON; the member is told it failed`,{error:F}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Le(G)>ar?(_.error(`[palbase] ${I} returned an ack of ${Le(G)} bytes, past ${ar}; 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 v(b,E){let w=z(b);if("status"in w)return w;if(!w.params)return Z(w.entry.g.pattern,w.channel);let T=b.event;if(typeof T!="string"||!Object.hasOwn(or,T))return me(400,"bad_request","A gateway's moment is first, join, leave or empty");let O=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(O===void 0)return me(400,"bad_request","A gateway's moment says its count of members");let N=T==="join"||T==="leave",q=N?Ne(b.user):void 0,J=N?b.connId:void 0;if(N&&(!q?.id||typeof J!="string"||J===""))return me(400,"bad_request",`A ${T} names its member: user and connId`);let I=`${T}\0${w.channel}\0${typeof J=="string"?J:""}`;if(N&&i.has(I))return{status:204};if(u.has(I))return me(503,"in_progress","This moment of the gateway is being handled",5);u.add(I);try{let j=w.entry.g.hooks[or[T]],G;if(T==="empty"?(G=o.get(w.channel),k(w.channel,G)):G=T==="leave"?o.get(w.channel):g(w.channel),j){let F=L(w.entry,w.channel,w.params,G,O,{id:q?.id??""},T==="join"?J:void 0);try{await t.run(q,`${w.entry.cls.name}.${j}`,E,async()=>w.entry.instance[j](F))}catch(oe){if(t.isOutage(oe))throw oe;return E?.aborted||_.error(`[palbase] ${w.entry.cls.name}.${j} (${T} of ${w.channel}) failed; realtime tells it again`,{error:oe}),me(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return N&&(i.add(I),i.size>na&&i.delete(i.values().next().value)),{status:204}}finally{u.delete(I)}}function X(b,E){let w=r.get(b),T=`Palbase.gateways.to(${b?.name??String(b)})`;if(!w)throw new TypeError(`${T}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let O=lr(w.g.pattern,E??{});if(typeof O!="string")throw new TypeError(`${T}: ${O.problem}`);return{entry:w,channel:O,where:T}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,E,w){return rn(E)?b==="authorize"?Y(E,w):b==="message"?ne(E,w):b==="lifecycle"?v(E,w):me(404,"not_found",`No gateway call ${JSON.stringify(b)}`):me(400,"bad_request","A gateway's call is a JSON object")},emit(b,E,w,T){let{entry:O,channel:N,where:q}=X(b,E);x(O,N,w,T,q)},async pipe(b,E,w){let{channel:T,where:O}=X(b,E);await W(w,T,O)},async revalidate(b,E,w={}){let T=r.get(b),O=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!T)throw new TypeError(`${O}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let N=ea(T.g.pattern,E??{},w);if("problem"in N)throw new TypeError(`${O}: ${N.problem}`);await t.revalidate(N)},close(){for(let b of o.values())b.abort();o.clear()}}}function aa(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!rn(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 oa(e){return Array.isArray(e)?"an array":rn(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 ia=20,kt=256;function dr(e){let t="";for(let n of e.slice(0,ia)){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)>=kt)break}return Xt(t,kt)}function Xt(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 en=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Le(t.event)>be){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${be} bytes`);return}try{JSON.stringify(t.payload)}catch(a){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=ra?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),se.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,sa);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 da,createPublicKey as gr,timingSafeEqual as ca,verify as yr}from"node:crypto";function ad(e){let t=U(e,je);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 wr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let i=U(o,je),u=s.get(i.name);if(u)throw new TypeError(`@Webhook "${i.name}" is declared by ${u.cls.name} and by ${o.name}: /webhooks/${i.name} is one endpoint`);let p=`@Webhook "${i.name}" (${o.name})`,g=n[i.secret.env],k;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${p} reads its signing secret from ${i.secret.env}, which is not set`);else try{k=ua(i,g)}catch(L){a.push(`${p}: ${i.secret.env} ${L.message}`)}let x=t(o),W=new Map(i.events.map(({event:L,fn:z})=>[L,{name:`${o.name}.${z}`,call:(Z,Y)=>x[z](Z,Y)}]));s.set(i.name,{name:i.name,cls:o,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:k,events:W})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
3
3
  - ${a.join(`
4
- - `)}`);return s}function br(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var ze=1024,pr=1024*ze;function ua(e,t){if(e.signature)return _e(void 0,e.signature.header,1/0,va(e.signature,t));switch(e.provider){case"stripe":return _e("stripe","stripe-signature",512*ze,pa(t));case"github":return _e("github","x-hub-signature-256",25*pr,ma(t));case"slack":return _e("slack","x-slack-signature",64*ze,ha(t));case"discord":return _e("discord","x-signature-ed25519",64*ze,ga(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*ze),check:wa(t)};case"sendgrid":return _e("sendgrid","x-twilio-email-event-webhook-signature",pr,ba(t));case"livekit":return _e("livekit","authorization",512*ze,ka(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function _e(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??kr(e,s)}}function kr(e,t){let n=sn(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:vr(e,t.headers,r),event:r,...la(e,t,r)}}function vr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=xe(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=Sr(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 xe(n,"EventType");case"livekit":return xe(n,"event");default:return xe(n,"type")}}function la(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(xe(n,"id"));case"slack":return r(xe(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${$r(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>xe(s,"sg_event_id")||void 0)}:{};default:return{}}}var fa=300;function pa(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let u of r.split(",")){let p=u.indexOf("=");if(p<=0)continue;let g=u.slice(0,p).trim(),k=u.slice(p+1).trim();if(g==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(g==="v1"){let x=le(k,"hex");if(!x)return"malformed_signature";a.push(x)}}let o=Ye(s);if(o===void 0||a.length===0)return"malformed_signature";if(Xe(o,n))return"stale_timestamp";let i=Ge("sha256",e,`${s}.`,t.body);return a.some(u=>ke(u,i))?void 0:"signature_mismatch"}}function ma(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?le(n.slice(7),"hex"):void 0;return r?ke(r,Ge("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function ha(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=Ye(s),o=r.startsWith("v0=")?le(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":Xe(a,n)?"stale_timestamp":ke(o,Ge("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function ga(e){let t=le(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=gr({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,i=Ye(o),u=le(a,"hex");return i===void 0||!u||u.byteLength!==64?"malformed_signature":Xe(i,s)?"stale_timestamp":yr(null,Tr(o,r.body),n,u)?void 0:"signature_mismatch"}}var ya=1e3;function wa(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=le(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="",i;if(a!==null){if(!ke(Buffer.from(a.toLowerCase()),Buffer.from(rn("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let W=1;for(let Z of t.body)if(Z===38&&++W>ya)return"malformed_signature";let L=new Map;for(let[Z,Y]of new URLSearchParams(sn(t.body))){let ne=L.get(Z);ne||L.set(Z,ne=new Set),ne.add(Y)}let z=[];for(let Z of[...L.keys()].sort()){let Y=[...L.get(Z)].sort();for(let ne of Y)o+=Z+ne;z.push([Z,Y.length===1?Y[0]:Y])}i=Object.fromEntries(z)}let u=s.protocol==="https:"?"443":"80",p=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,g=`${s.protocol}//${s.hostname}:${s.port||u}${s.pathname}${s.search}`;if(![p,g].some(W=>ke(r,Ge("sha1",e,W,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),x=k?{id:`${k}:${$r(`${p}
5
- ${o}`)}`}:{};return i?{type:vr("twilio",t.headers,i),event:i,...x}:{...kr("twilio",t),...x}}}function ba(e){let t;try{let n=le(e,"base64");if(!n)throw new Error;t=gr({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=Ye(a),i=le(s.trim(),"base64");return o===void 0||!i?"malformed_signature":Xe(o,r)?"stale_timestamp":yr("sha256",Tr(a,n.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var mr=60;function ka(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=hr(le(s[0],"base64url")),o=le(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!ke(o,Ge("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let i=hr(le(s[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(n>i.exp+mr||typeof i.nbf=="number"&&n<i.nbf-mr)return"stale_timestamp";let u=typeof i.sha256=="string"?le(i.sha256,"base64"):void 0;return u&&ke(u,rn("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function va(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 i="";if(n.includes("{ts}")){i=s.headers.get(e.timestampHeader)?.trim()??"";let p=Ye(i);if(p===void 0)return"malformed_signature";if(Xe(p,a))return"stale_timestamp"}let u=le(o.trim(),e.encoding);return u?ke(u,Ge(r,t,...n.map(p=>p==="{body}"?s.body:p==="{ts}"?i:p)))?void 0:"signature_mismatch":"malformed_signature"}}var $a=new TextEncoder;function Ge(e,t,...n){let r=da(e,t);for(let s of n)r.update(s);return r.digest()}function $r(e){return rn("sha256").update(e).digest("hex")}function Tr(e,t){return Buffer.concat([$a.encode(e),t])}function ke(e,t){return e.byteLength===t.byteLength&&ca(e,t)}var Ta={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 le(e,t){return Ta[t].test(e)?Buffer.from(e,t):void 0}function Ye(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function Xe(e,t){return Math.abs(t-e)>fa}function sn(e){return new TextDecoder().decode(e)}function hr(e){if(e)try{return JSON.parse(sn(e))}catch{return}}function Sr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xe(e,t){let n=Sr(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var K=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
4
+ - `)}`);return s}function br(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var ze=1024,pr=1024*ze;function ua(e,t){if(e.signature)return _e(void 0,e.signature.header,1/0,va(e.signature,t));switch(e.provider){case"stripe":return _e("stripe","stripe-signature",512*ze,pa(t));case"github":return _e("github","x-hub-signature-256",25*pr,ma(t));case"slack":return _e("slack","x-slack-signature",64*ze,ha(t));case"discord":return _e("discord","x-signature-ed25519",64*ze,ga(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*ze),check:wa(t)};case"sendgrid":return _e("sendgrid","x-twilio-email-event-webhook-signature",pr,ba(t));case"livekit":return _e("livekit","authorization",512*ze,ka(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function _e(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??kr(e,s)}}function kr(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:vr(e,t.headers,r),event:r,...la(e,t,r)}}function vr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=xe(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=Sr(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 xe(n,"EventType");case"livekit":return xe(n,"event");default:return xe(n,"type")}}function la(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(xe(n,"id"));case"slack":return r(xe(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${$r(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>xe(s,"sg_event_id")||void 0)}:{};default:return{}}}var fa=300;function pa(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let u of r.split(",")){let p=u.indexOf("=");if(p<=0)continue;let g=u.slice(0,p).trim(),k=u.slice(p+1).trim();if(g==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(g==="v1"){let x=le(k,"hex");if(!x)return"malformed_signature";a.push(x)}}let o=Ye(s);if(o===void 0||a.length===0)return"malformed_signature";if(Xe(o,n))return"stale_timestamp";let i=Ge("sha256",e,`${s}.`,t.body);return a.some(u=>ke(u,i))?void 0:"signature_mismatch"}}function ma(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?le(n.slice(7),"hex"):void 0;return r?ke(r,Ge("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function ha(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=Ye(s),o=r.startsWith("v0=")?le(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":Xe(a,n)?"stale_timestamp":ke(o,Ge("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function ga(e){let t=le(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=gr({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,i=Ye(o),u=le(a,"hex");return i===void 0||!u||u.byteLength!==64?"malformed_signature":Xe(i,s)?"stale_timestamp":yr(null,Tr(o,r.body),n,u)?void 0:"signature_mismatch"}}var ya=1e3;function wa(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=le(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="",i;if(a!==null){if(!ke(Buffer.from(a.toLowerCase()),Buffer.from(sn("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let W=1;for(let Z of t.body)if(Z===38&&++W>ya)return"malformed_signature";let L=new Map;for(let[Z,Y]of new URLSearchParams(an(t.body))){let ne=L.get(Z);ne||L.set(Z,ne=new Set),ne.add(Y)}let z=[];for(let Z of[...L.keys()].sort()){let Y=[...L.get(Z)].sort();for(let ne of Y)o+=Z+ne;z.push([Z,Y.length===1?Y[0]:Y])}i=Object.fromEntries(z)}let u=s.protocol==="https:"?"443":"80",p=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,g=`${s.protocol}//${s.hostname}:${s.port||u}${s.pathname}${s.search}`;if(![p,g].some(W=>ke(r,Ge("sha1",e,W,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),x=k?{id:`${k}:${$r(`${p}
5
+ ${o}`)}`}:{};return i?{type:vr("twilio",t.headers,i),event:i,...x}:{...kr("twilio",t),...x}}}function ba(e){let t;try{let n=le(e,"base64");if(!n)throw new Error;t=gr({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=Ye(a),i=le(s.trim(),"base64");return o===void 0||!i?"malformed_signature":Xe(o,r)?"stale_timestamp":yr("sha256",Tr(a,n.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var mr=60;function ka(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=hr(le(s[0],"base64url")),o=le(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!ke(o,Ge("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let i=hr(le(s[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(n>i.exp+mr||typeof i.nbf=="number"&&n<i.nbf-mr)return"stale_timestamp";let u=typeof i.sha256=="string"?le(i.sha256,"base64"):void 0;return u&&ke(u,sn("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function va(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 i="";if(n.includes("{ts}")){i=s.headers.get(e.timestampHeader)?.trim()??"";let p=Ye(i);if(p===void 0)return"malformed_signature";if(Xe(p,a))return"stale_timestamp"}let u=le(o.trim(),e.encoding);return u?ke(u,Ge(r,t,...n.map(p=>p==="{body}"?s.body:p==="{ts}"?i:p)))?void 0:"signature_mismatch":"malformed_signature"}}var $a=new TextEncoder;function Ge(e,t,...n){let r=da(e,t);for(let s of n)r.update(s);return r.digest()}function $r(e){return sn("sha256").update(e).digest("hex")}function Tr(e,t){return Buffer.concat([$a.encode(e),t])}function ke(e,t){return e.byteLength===t.byteLength&&ca(e,t)}var Ta={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 le(e,t){return Ta[t].test(e)?Buffer.from(e,t):void 0}function Ye(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function Xe(e,t){return Math.abs(t-e)>fa}function an(e){return new TextDecoder().decode(e)}function hr(e){if(e)try{return JSON.parse(an(e))}catch{return}}function Sr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xe(e,t){let n=Sr(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var K=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,11 +10,11 @@ ${s}
10
10
 
11
11
  Potential solutions:
12
12
  ${a.map(o=>` - ${o}`).join(`
13
- `)}`),this.name="DiError",this.kind=t,this.path=n}},Sa=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],Ea=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),kt=class{owner=new Map;defs=new Map;instances=new Map;providers=new Set;order=[];controllers=[];eventProviders=[];webhooks=[];cronProviders=[];taskProviders=[];gateways=[];constructor(t){this.collect(t),this.validate()}collect(t){let n=(r,s)=>{if(this.defs.has(r))return;let a=U(r,Gt);if(!a)throw new K("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 K("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 K("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(!U(a,Pe))throw new K("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(U(a,we))throw new K("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(U(a,ye))throw new K("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(U(a,Ee)||U(a,Ie))throw new K("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 ce())if(!this.owner.has(t))throw new K("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 K("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(U(r,Ie)&&!U(r,Ee))throw new K("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(!U(r,zt)&&!U(r,Se)&&!U(r,Ee)&&!U(r,we)&&!U(r,ye)){let s=Reflect.getMetadata("design:paramtypes",r);throw r.length>0&&!s?new K("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 K("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 or a @Task)`,["decorate it with @Injectable()"])}U(r,Ee)&&this.gateways.push(r),U(r,je)?this.webhooks.push(r):U(r,Se)&&this.eventProviders.push(r),U(r,we)&&this.cronProviders.push(r),U(r,ye)&&this.taskProviders.push(r)}}for(let t of this.owner.keys())for(let n of Sa)if(typeof t.prototype[n]=="function")throw new K("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 K("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 K("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 i=[];o.slice(0,a).forEach((p,g)=>{if(Ea.has(p)||typeof p!="function")throw new K("unresolvable dependency",s,`${t.name} constructor parameter ${g}`,`parameter ${g} of ${t.name} is typed as ${p===void 0?"something with no runtime class":p.name} \u2014 an interface, union or primitive has no class to build`,["type it with the class itself"]);i.push(this.resolve(this.reachable(t,p,s),s))});let u=new t(...i);return this.instances.set(t,u),this.order.push(u),u}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 K("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 K("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 K("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 K("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 K("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 K("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 _a,HttpError as et}from"palgres";import{z as ve}from"zod";import{BadRequest as gd,Conflict as yd,DeadlockDetected as wd,HttpError as bd,NotFound as kd,SerializationFailure as vd,TooManyRequests as $d,UniqueViolation as Td}from"palgres";function tt(e){if(typeof e!="object"||e===null||e[_a]!==!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 Er=class extends et{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},_r=class extends et{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},xr=class extends et{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function Rr(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 xa=Symbol.for("palbase.backend.errorRegistry"),Oa={bad_request:ve.object({fields:ve.array(ve.object({field:ve.string(),message:ve.string()})),more:ve.number().int().optional()}),too_many_requests:ve.object({retryAfter:ve.number().int()})},Ra=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 Aa(){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=Oa[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function Pa(){let e=globalThis;return e[xa]??=Aa()}var Ca=/^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;function pd(e,t,n){if(typeof e!="string"||e.length>100||!Ca.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(Ra.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=Pa(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&Or(s.data)!==Or(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(x=>x.split(/(?=[A-Z])/)),o=a.map(x=>x.charAt(0).toUpperCase()+x.slice(1)).join(""),i=a.map(x=>x.toLowerCase()).join(" "),u=i.charAt(0).toUpperCase()+i.slice(1),k=n?(x=>class extends et{static code=e;static status=t;constructor(W,L){let z=ja(e,x,W);super(t,e,L??(typeof z=="string"?z:u),z),this.name=o}})(n):class extends et{static code=e;static status=t;constructor(x){super(t,e,x??u),this.name=o}};return Object.defineProperty(k,"name",{value:o}),r.set(e,{code:e,status:t,className:o,builtin:!1,...n?{data:n}:{}}),k}function ja(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 Or(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}import{markData as Ma}from"palgres";var Ar="/_palbase/ai/tools",Pr="/_palbase/ai/agents",Cr="/_palbase/ai/repos",qe=4<<20,Da=Symbol.for("palbase.ai.tool_error");function jr(e){return e instanceof Error&&e[Da]===!0}var Na=Symbol.for("palbase.ai.declared");function Mr(){let e=globalThis[Na];if(!e)return{tools:new Map,agents:new Map,repos:new Map,repoTokens:void 0};if(e.twice.size>0){let t=[...e.twice].map(n=>n.replace(":"," "));throw new TypeError(`[palbase] ${t.join(", ")}: declared twice with different values \u2014 an ai.tool's and an ai.agent's name is its own, and ai.repoTokens is given once; make each once, at a module's top level`)}return{tools:new Map(e.tools),agents:new Map(e.agents),repos:new Map(e.repos??[]),repoTokens:e.repoTokens}}var He=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Dr(e){let t={};if(e==null)return t;if(He(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 Nr(e){if(!He(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(!He(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=Dr(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 Ur(e){let t=Nr(e);if(typeof t=="string")return t;let n=e;return typeof n.turn_id!="string"||typeof n.run_id!="string"?"context.turn_id and context.run_id are the turn the call is made in and the run that made it":n.subagent!==null&&typeof n.subagent!="string"?"context.subagent is the subagent that made the call, or null":{...t,turnId:n.turn_id,runId:n.run_id,subagent:n.subagent}}function Lr(e){let t=Nr(e);if(typeof t=="string")return t;let n=e,r=null;if(n.message!==null){let a=n.message,o=He(a)?Dr(a.metadata):void 0;if(!He(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:Ma(o)}}let s=null;if(n.goal!==void 0&&n.goal!==null){if(!He(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 Ua=1e4,La=10*6e4,vt=class{constructor(t=Date.now){this.now=t}now;seen=new Map;take(t){let n=this.now();for(let[r,s]of this.seen){if(n-s<=La&&this.seen.size<=Ua)break;this.seen.delete(r)}return this.seen.has(t)?!1:(this.seen.set(t,n),!0)}},Ia=1e3,za=256*1024,$t=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>za)&&(this.answers.set(t,n),this.answers.size>Ia&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as ls,isEngineRaised as kn,markData as fe}from"palgres";import{createHash as fs}from"node:crypto";import{createHash as Ga,randomInt as Ha}from"node:crypto";import{ago as an,isRetryable as qa,now as Ir}from"palgres";import{defineSchema as Fa,defineTable as Ba,index as Ka,integer as Ja,jsonb as Wa,raw as Va,text as on,timestamp as zr}from"palgres/dsl";var Kr=new Set(["POST","PUT","PATCH","DELETE"]),Gr=255,Hr=35,qr=24,Za=65536,Fr=1e3,Qa=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"}},Ya=Ba("idempotency_keys",{columns:{key:on().primaryKey(),fingerprint:on(),started_at:zr().defaultNow(),completed_at:zr().nullable(),status_code:Ja().nullable(),response_headers:Wa().nullable(),response_body:on().nullable()},indexes:e=>[Ka("idempotency_keys_started").on(e.col("started_at"))]}),Cd=Fa("palbase",{tables:[Ya],raw:[Va("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}},Sa=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],Ea=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),vt=class{owner=new Map;defs=new Map;instances=new Map;providers=new Set;order=[];controllers=[];eventProviders=[];webhooks=[];cronProviders=[];taskProviders=[];gateways=[];constructor(t){this.collect(t),this.validate()}collect(t){let n=(r,s)=>{if(this.defs.has(r))return;let a=U(r,Ht);if(!a)throw new K("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 K("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 K("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(!U(a,Pe))throw new K("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(U(a,we))throw new K("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(U(a,ye))throw new K("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(U(a,Ee)||U(a,Ie))throw new K("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 ce())if(!this.owner.has(t))throw new K("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 K("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(U(r,Ie)&&!U(r,Ee))throw new K("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(!U(r,Gt)&&!U(r,Se)&&!U(r,Ee)&&!U(r,we)&&!U(r,ye)){let s=Reflect.getMetadata("design:paramtypes",r);throw r.length>0&&!s?new K("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 K("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 or a @Task)`,["decorate it with @Injectable()"])}U(r,Ee)&&this.gateways.push(r),U(r,je)?this.webhooks.push(r):U(r,Se)&&this.eventProviders.push(r),U(r,we)&&this.cronProviders.push(r),U(r,ye)&&this.taskProviders.push(r)}}for(let t of this.owner.keys())for(let n of Sa)if(typeof t.prototype[n]=="function")throw new K("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 K("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 K("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 i=[];o.slice(0,a).forEach((p,g)=>{if(Ea.has(p)||typeof p!="function")throw new K("unresolvable dependency",s,`${t.name} constructor parameter ${g}`,`parameter ${g} of ${t.name} is typed as ${p===void 0?"something with no runtime class":p.name} \u2014 an interface, union or primitive has no class to build`,["type it with the class itself"]);i.push(this.resolve(this.reachable(t,p,s),s))});let u=new t(...i);return this.instances.set(t,u),this.order.push(u),u}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 K("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 K("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 K("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 K("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 K("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 K("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 _a,HttpError as et}from"palgres";import{z as ve}from"zod";import{BadRequest as gd,Conflict as yd,DeadlockDetected as wd,HttpError as bd,NotFound as kd,SerializationFailure as vd,TooManyRequests as $d,UniqueViolation as Td}from"palgres";function tt(e){if(typeof e!="object"||e===null||e[_a]!==!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 Er=class extends et{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},_r=class extends et{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},xr=class extends et{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function Rr(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 xa=Symbol.for("palbase.backend.errorRegistry"),Oa={bad_request:ve.object({fields:ve.array(ve.object({field:ve.string(),message:ve.string()})),more:ve.number().int().optional()}),too_many_requests:ve.object({retryAfter:ve.number().int()})},Ra=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 Aa(){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=Oa[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function Pa(){let e=globalThis;return e[xa]??=Aa()}var Ca=/^[a-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;function pd(e,t,n){if(typeof e!="string"||e.length>100||!Ca.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(Ra.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=Pa(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&Or(s.data)!==Or(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(x=>x.split(/(?=[A-Z])/)),o=a.map(x=>x.charAt(0).toUpperCase()+x.slice(1)).join(""),i=a.map(x=>x.toLowerCase()).join(" "),u=i.charAt(0).toUpperCase()+i.slice(1),k=n?(x=>class extends et{static code=e;static status=t;constructor(W,L){let z=ja(e,x,W);super(t,e,L??(typeof z=="string"?z:u),z),this.name=o}})(n):class extends et{static code=e;static status=t;constructor(x){super(t,e,x??u),this.name=o}};return Object.defineProperty(k,"name",{value:o}),r.set(e,{code:e,status:t,className:o,builtin:!1,...n?{data:n}:{}}),k}function ja(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 Or(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}import{markData as Ma}from"palgres";var Ar="/_palbase/ai/tools",Pr="/_palbase/ai/agents",Cr="/_palbase/ai/repos",qe=4<<20,Da=Symbol.for("palbase.ai.tool_error");function jr(e){return e instanceof Error&&e[Da]===!0}var Na=Symbol.for("palbase.ai.declared");function Mr(){let e=globalThis[Na];if(!e)return{tools:new Map,agents:new Map,repos:new Map,repoTokens:void 0};if(e.twice.size>0){let t=[...e.twice].map(n=>n.replace(":"," "));throw new TypeError(`[palbase] ${t.join(", ")}: declared twice with different values \u2014 an ai.tool's and an ai.agent's name is its own, and ai.repoTokens is given once; make each once, at a module's top level`)}return{tools:new Map(e.tools),agents:new Map(e.agents),repos:new Map(e.repos??[]),repoTokens:e.repoTokens}}var He=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Dr(e){let t={};if(e==null)return t;if(He(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 Nr(e){if(!He(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(!He(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=Dr(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 Ur(e){let t=Nr(e);if(typeof t=="string")return t;let n=e;return typeof n.turn_id!="string"||typeof n.run_id!="string"?"context.turn_id and context.run_id are the turn the call is made in and the run that made it":n.subagent!==null&&typeof n.subagent!="string"?"context.subagent is the subagent that made the call, or null":{...t,turnId:n.turn_id,runId:n.run_id,subagent:n.subagent}}function Lr(e){let t=Nr(e);if(typeof t=="string")return t;let n=e,r=null;if(n.message!==null){let a=n.message,o=He(a)?Dr(a.metadata):void 0;if(!He(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:Ma(o)}}let s=null;if(n.goal!==void 0&&n.goal!==null){if(!He(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 Ua=1e4,La=10*6e4,$t=class{constructor(t=Date.now){this.now=t}now;seen=new Map;take(t){let n=this.now();for(let[r,s]of this.seen){if(n-s<=La&&this.seen.size<=Ua)break;this.seen.delete(r)}return this.seen.has(t)?!1:(this.seen.set(t,n),!0)}},Ia=1e3,za=256*1024,Tt=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>za)&&(this.answers.set(t,n),this.answers.size>Ia&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as ls,isEngineRaised as kn,markData as fe}from"palgres";import{createHash as fs}from"node:crypto";import{createHash as Ga,randomInt as Ha}from"node:crypto";import{ago as on,isRetryable as qa,now as Ir}from"palgres";import{defineSchema as Fa,defineTable as Ba,index as Ka,integer as Ja,jsonb as Wa,raw as Va,text as dn,timestamp as zr}from"palgres/dsl";var Kr=new Set(["POST","PUT","PATCH","DELETE"]),Gr=255,Hr=35,qr=24,Za=65536,Fr=1e3,Qa=64,un={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"}},Ya=Ba("idempotency_keys",{columns:{key:dn().primaryKey(),fingerprint:dn(),started_at:zr().defaultNow(),completed_at:zr().nullable(),status_code:Ja().nullable(),response_headers:Wa().nullable(),response_body:dn().nullable()},indexes:e=>[Ka("idempotency_keys_started").on(e.col("started_at"))]}),Cd=Fa("palbase",{tables:[Ya],raw:[Va("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)"})]}),Xa={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},eo={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},to={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},no={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},St=class extends Error{};function nt(e){return Kr.has(e.method)&&e.meta.upload===void 0}function Jr(e,t){if(!Kr.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function ro(e,t){return Wr([e.role,e.uid,t]).digest("hex")}function so(e){return Wr([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function Wr(e){let t=Ga("sha256");for(let n of e)t.update(n).update("\0");return t}function ao(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function dn(e){return e<500&&e!==429&&e!==499}function oo(e,t){return t&&dn(e)}function Vr(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 io={role:"service",claims:{}},Et=class{constructor(t){this.db=t}db;async serve(t,n,r){if(t.key.length>Gr)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${Gr} characters`});let s;try{s=await this.begin(ro(t.caller,t.key),so(t))}catch(i){return _.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:i}),r.refusal(no)}if("kept"in s)return co(s.kept,r.requestId);if("refused"in s)return r.refusal(s.refused==="reused"?Xa:eo);let a=s.claim,o;try{o=await n(i=>this.record(a,i))}catch(i){if(i instanceof St)return r.refusal(to);let u=r.failure(i);return oo(u.status,r.ran())&&!qa(i)?this.keep(a,u):(await this.release(a),u)}return dn(o.status)||await this.release(a),o}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:an({hours:qr})}}}))}async begin(t,n){return Ha(Qa)===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:an({hours:qr})}}})>0)continue;let o=await r.findUnique({where:{key:t}});if(o===null)continue;let i=ao(o,n);if(i==="reused")return{refused:"reused"};if(i==="replay")return{kept:{status:o.status_code,headers:o.response_headers??[],body:o.response_body}};let[u]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:an({seconds:Hr})}},set:{started_at:Ir()}});return u?{claim:{key:t,started:u.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!dn(n.status))return n;let{response:r,kept:s}=await Br(n),a=se.getStore()?.database;if(!a)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let[o]=await a.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,s.status,JSON.stringify(s.headers),s.body]);if(o?.answered!==!0)throw new St;return r}async keep(t,n){let{response:r,kept:s}=await Br(n);try{await this.asService(a=>a.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:Ir(),status_code:s.status,response_headers:s.headers,response_body: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()+Hr*1e3,r=()=>{Date.now()+Fr>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},Fr).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(io),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 co(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 Tt=Symbol("waits");function uo(e){return new Promise((t,n)=>{let r=setImmediate(()=>t(Tt));e.then(s=>{clearImmediate(r),t(s)},s=>{clearImmediate(r),n(s)})})}async function Br(e){let t=[];e.headers.forEach((i,u)=>{u!=="x-request-id"&&t.push([u,i])});let n=i=>new Response(i,{status:e.status,statusText:e.statusText,headers:e.headers});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 i=r.read(),u=await uo(i);if(u!==Tt&&u.done)break;if(u!==Tt&&(s.push(u.value),a+=u.value.byteLength,a<=Za))continue;let p=u===Tt?i:void 0,g=new ReadableStream({start(k){for(let x of s)k.enqueue(x)},async pull(k){let x=await(p??r.read());p=void 0,x.done?k.close():k.enqueue(x.value)},cancel:k=>r.cancel(k)});return{response:n(g),kept:{status:e.status,headers:t.filter(([k])=>k!=="content-length"&&k!=="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 lo}from"node:crypto";var un="/webhooks/palbase",ts="PalbaseErrorEnvelope",Zr="PalbaseBearer",fo={$ref:`#/components/schemas/${ts}`},po={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"]},Qr={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Fe={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function ns(e,t,n){let r={[ts]:po},s={},a=[],o=[],i=new Set,u=new Map;for(let v of e){let X=o.find(V=>go(V,v));if(X){a.push({route:v.id,handler:Yr(v),answeredBy:X.id});continue}o.push(v);let b=v.segments.map(V=>typeof V=="string"?V:"{}").join("/");u.has(b)||u.set(b,wo(v.segments.flatMap(V=>typeof V=="string"?[]:[V.param])));let E=u.get(b),w=0,T=`/${v.segments.map(V=>typeof V=="string"?V:`{${E[w++]}}`).join("/")}`,O=t(v),N=_t(yo(v),i),q=v.method!=="GET"&&v.method!=="HEAD",J=V=>{let Oe=v.params.filter(Te=>Te.kind===V&&Te.schema).map((Te,ut)=>Rt(Te.schema,`${N}.${V}${ut===0?"":`.${ut+1}`}`,r));return Oe.length===0?void 0:Oe.length===1?Oe[0]:{allOf:Oe}},I=E.map(V=>({name:V,in:"path",required:!0,schema:{type:"string"}})),j=J("query");j&&I.push(...es(j,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:j}]);let G=J("headers");G&&I.push(...es(G,"header")??[]);let F=n.idempotency===!0&&nt(v);F&&I.push({...cn,schema:{...cn.schema}});let oe=q?J("body"):void 0,ie={operationId:N};v.controller.name!==""&&(ie.tags=[v.controller.name]),I.length>0&&(ie.parameters=I),oe&&(ie.requestBody={required:!To(oe),content:{"application/json":{schema:oe}}});let Dt=v.params.some(V=>V.schema!==void 0),dt=n.routes?.(v),$e=Eo(N,dt?.throws??[],n.errors);ie.responses={...So(dt,N,r),...Oo(O,{validates:Dt,hasPathParams:E.length>0,readsBody:q,keyed:F}),...xo($e,N,r)},$e.length>0&&(ie["x-palbase-errors"]=_o(N,$e)),O.auth.required&&(ie.security=[{[Zr]:[]}]),ie["x-palbase-handler"]=Yr(v);let ct=v.params.some(V=>V.kind==="optionalUser")||n.databaseSeesCaller;ie["x-palbase-auth"]=O.auth.required?"required":ct?"optional":"public",ie["x-palbase-verified-email"]=O.auth.verifiedEmail,ie["x-palbase-rate-limit"]=O.limit===!1?!1:{max:O.limit.max,window:O.limit.window},v.meta.upload&&(ie["x-palbase-upload"]={bucket:v.meta.upload.bucket,pathTemplate:v.meta.upload.pathTemplate}),(s[T]??={})[v.method.toLowerCase()]=ie}for(let v of n.webhooks??[]){let X={operationId:_t(`webhooks.${v.name}`,i)};v.cls!==""&&(X.tags=[v.cls]),X.description=v.provider?`${Qr[v.provider]??v.provider}'s deliveries: verified with ${Qr[v.provider]??v.provider}'s signature scheme under the secret in ${v.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${v.signatureHeader} header: verified under the secret in ${v.secretEnv}, then handed to the @On of their event type.`,X.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":{},[v.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:te("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:te("in_progress: the same delivery is being handled; the sender delivers it again",Fe),413:te("payload_too_large: the body is over what this sender sends"),500:te("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:te("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",Fe)},X["x-palbase-webhook"]=v.provider?{provider:v.provider,secretEnv:v.secretEnv,events:v.events}:{signatureHeader:v.signatureHeader,secretEnv:v.secretEnv,events:v.events},s[`/webhooks/${v.name}`]={post:X}}let p=[...new Set(n.platformEvents??[])].sort();if(p.length>0){let v={operationId:_t("webhooks.palbase",i)};v.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.",v.responses={204:{description:"Taken: handled, or a delivery already run"},401:te("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:te("in_progress: the same event is being handled; the platform delivers it again",Fe),500:te("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:te("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let X=[...new Set(n.platformEventBuckets??[])].sort();v["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:p,...X.length>0?{buckets:X}:{}},s[un]={post:v}}let g=n.gateways??[],k=mo(g,r),x=g.length>0,W=Object.fromEntries(g.filter(Ue).map(v=>[v.pattern,{events:k[v.name].events,messages:Object.fromEntries(Object.entries(k[v.name].messages).map(([X,b])=>[X,b.payload])),graceMs:v.graceMs,...v.logKeepSeconds>0?{logKeepSeconds:v.logKeepSeconds}:{}}])),L=Object.keys(W).length>0,z=g.filter(v=>!Ue(v)).map(v=>({pattern:v.pattern,kind:v.access,publish:v.publish,state_read:!1,state_write:!1,...v.logKeepSeconds>0?{log_keep_seconds:v.logKeepSeconds}:{}})),Z=z.length>0,Y={schemas:r,securitySchemes:{[Zr]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},ne={openapi:"3.2.0",info:{title:"Palbase backend",version:lo("sha256").update(JSON.stringify({paths:s,components:Y,unreachable:a,...x?{gateways:k}:{},...L?{rooms:W}:{},...Z?{channels:z}:{}})).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:Y};return a.length>0&&(ne["x-palbase-unreachable"]=a),x&&(ne["x-palbase-gateways"]=k),L&&(ne["x-palbase-room"]=W),Z&&(ne["x-palbase-channels"]=z),ne}function mo(e,t){let n=[];for(let r of e){let s=(i,u,p,g)=>{let k=Ot(`${r.name}_${i}_${u}`),x={},W=Rt(p,k,x,g);W.$ref===void 0&&(x[k]=W),ho(r.pattern,i,u,x[k]);for(let[L,z]of Object.entries(x)){if(Object.hasOwn(t,L)&&JSON.stringify(t[L])!==JSON.stringify(z))throw new Error(`@Gateway("${r.pattern}") ${i} "${u}": its schema is the component ${L}, which another gateway's names with another schema \u2014 rename one of them`);t[L]=z}return{$ref:`#/components/schemas/${k}`}},a=Object.fromEntries(Object.entries(r.events).map(([i,u])=>[i,s("event",i,u,"answered")])),o=Object.fromEntries(Object.entries(r.messages).map(([i,u])=>[i,{payload:s("message",i,u.schema,"sent"),...u.reply?{reply:s("reply",i,u.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 ho(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 go(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 Yr(e){return`${e.controller.name}.${e.fn}`}function yo(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 _t(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function wo(e){let t=new Set;return e.map(n=>_t(n,t))}function Rt(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:bo}:{}}})}catch{return{}}let i=Ot(t);for(;Object.keys(n).some(u=>u===i||u.startsWith(`${i}.`));)i=`${i}_`;return ko(o,i,n,r)}function bo(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function ko(e,t,n,r){let s=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},a=!1,o=p=>p==="#"?(a=!0,`#/components/schemas/${t}`):p.startsWith("#/$defs/")?`#/components/schemas/${t}.${Ot($o(p.slice(8)))}`:p,i="all";if(r==="sent"){let p=new Set;for(let g of[e,...Object.values(s)])xt(g,p);i=p}for(let[p,g]of Object.entries(s))n[`${t}.${Ot(p)}`]=st(rt(g,o,i));let u=st(rt(e,o,i));return a?(n[t]=u,{$ref:`#/components/schemas/${t}`}):u}var vo=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"]),ln=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),fn=new Set(["anyOf","oneOf","allOf","prefixItems"]),pn=new Set(["properties","patternProperties","dependentSchemas"]),ae=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function rt(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):vo.has(s)?r[s]=a:ln.has(s)?r[s]=rt(a,t,n):fn.has(s)&&Array.isArray(a)?r[s]=a.map(o=>rt(o,t,n)):pn.has(s)&&ae(a)&&(r[s]=Object.fromEntries(Object.entries(a).map(([o,i])=>[o,rt(i,t,n)])));return r}var Xr=Number.MAX_SAFE_INTEGER;function st(e){if(!ae(e))return e;let t={};for(let[r,s]of Object.entries(e))ln.has(r)?t[r]=st(s):fn.has(r)&&Array.isArray(s)?t[r]=s.map(st):pn.has(r)&&ae(s)?t[r]=Object.fromEntries(Object.entries(s).map(([a,o])=>[a,st(o)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-Xr&&delete t.minimum,t.maximum===Xr&&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 xt(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(ln.has(n))xt(r,t);else if(fn.has(n)&&Array.isArray(r))for(let s of r)xt(s,t);else if(pn.has(n)&&ae(r))for(let s of Object.values(r))xt(s,t)}}function $o(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Ot(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function es(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 To(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function te(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:fo}}}}function So(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=Rt(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function Eo(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 _o(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 xo(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,i)=>o-i)){let o=r.get(a),i=o.map(u=>{let p={error:{type:"string",const:u.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},g=["error","error_description","status","request_id"];return u.data&&(p.data=Rt(u.data,`${t}.${u.code}.data`,n,"answered"),g.push("data")),{type:"object",properties:p,required:g}});s[String(a)]={description:o.map(u=>u.code).join(" | "),content:{"application/json":{schema:i.length===1?i[0]:{oneOf:i}}}}}return s}function Oo(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);return s.length>0&&(n[400]=te(s.join("; "))),e.auth.required&&(n[401]=te("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.verifiedEmail&&(n[403]=te("email_not_verified: the user's email address is not verified")),t.keyed&&(n[409]=te("idempotency_key_in_use: a request with this Idempotency-Key is still running",Fe)),t.readsBody&&(n[413]=te("payload_too_large: the body is over the app's body limit")),t.keyed&&(n[422]=te("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(n[429]=te("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Fe)),n[500]=te("internal_error: the handler failed; the app's log has it under the request id"),n[503]=te(`${e.auth.required?"auth_unavailable: sign-ins 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":""}`,Fe),n}var At=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))}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 Pt(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return Ro(r??t??"unknown")}function Ro(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(":"):[],i=t.includes("::")?[...a,...Array(8-a.length-o.length).fill("0"),...o]:a;return i.length!==8||i.some(u=>!/^[0-9a-f]{1,4}$/i.test(u))?t:`${i.slice(0,4).map(u=>parseInt(u,16).toString(16)).join(":")}::/64`}function rs(e){let t=[];for(let n of e){let r=U(n,Pe),s=U(n,Ce)??[];if(s.length===0)throw new TypeError(`@Controller ${n.name} has no routes: a controller with nothing to serve is a mistake`);let a=U(n,It)??new Map;for(let o of s){let i=`${r.basePath}${o.subpath}`||"/",u=i.split("/").filter(Boolean).map(g=>{let k=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(g)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(g);return k?{param:k[1]}:g});if(typeof u[0]=="string"&&Me.has(u[0]))throw new TypeError(`${n.name}.${o.fn}: ${o.method} ${i} \u2014 /${u[0]} is the platform's; a route is served elsewhere`);let p=[...a.get(o.fn)??[]].sort((g,k)=>g.index-k.index);for(let g of p)if(g.kind==="param"&&!u.some(k=>typeof k!="string"&&k.param===g.name))throw new TypeError(`${n.name}.${o.fn}: @Param("${g.name}") names no {${g.name}} in ${o.method} ${i}`);t.push({id:`${o.method} ${i}`,method:o.method,segments:u,controller:n,fn:o.fn,params:p,meta:o,controllerAuth:r.options.auth})}}return er(t),t}function mn(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 i=0;i<r.length&&o;i++){let u=s.segments[i];if(typeof u=="string")o=u===r[i];else try{a[u.param]=decodeURIComponent(r[i])}catch{return{malformed:!0}}}if(o)return{route:s,params:a}}return null}function yn(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Be(e,t,n,r,s){return Ct(e,e?yn(e.requests,t):void 0,n,r,s)}var hn={role:"service",claims:{}};async function Ct(e,t,n,r,s){if(!e||!t)return s();let a=p=>_.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 ${p} 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:p}),o=e.app.request(t,{signal:n,heldIdle:a}),i=se.getStore();i&&(i.database=o.database);let u;try{u=await s()}catch(p){throw await o.rollback(p).catch(g=>_.error("[palbase] the request's transaction could not be rolled back",{error:g})),p}try{await o.commit()}catch(p){throw await o.rollback(p).catch(g=>_.error("[palbase] the request's transaction could not be rolled back",{error:g})),p}return u}var Po=1024*1024,Co=20,jo={max:300,window:60},Ke="/_palbase/crons",Je="/_palbase/tasks",ss=50,as=50,Mo=4096,Do=69632,os=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,at=1e4,No=6e4;function Uo(e,t){let n=e.meta.options.auth??e.controllerAuth??t??!0;if(typeof n=="boolean")return{required:n,verifiedEmail:!1};if((n.role??"").trim()!==""||(n.permission??"").trim()!=="")throw new TypeError(`${e.id}: auth { role, permission } were checked against v2's database; v3 has none yet \u2014 check the role in the service`);return{required:n.required!==!1,verifiedEmail:n.verifiedEmail===!0}}var re=class extends Error{constructor(n,r,s,a,o,i){super(s);this.status=n;this.code=r;this.data=a;this.retryAfter=o;this.challenge=i}status;code;data;retryAfter;challenge};function Lo(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 Io=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function zo(e,t){let n=new Headers(e.headers);for(let r of Io)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 is(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),jt(e.headers,"Accept-Language")),e}function jt(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 he(e,t,n,r={}){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json","x-request-id":n,...r}})}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={};return e.retryAfter!==void 0&&(r["retry-after"]=String(e.retryAfter)),e.challenge!==void 0&&(r["www-authenticate"]=e.challenge),he(e.status,n,t,r)}var ps=new Set([0,429,502,503,504]);function ds(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 re)return $({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(tt(e)){let a=e;return a.status>=500&&_.error(`[palbase] ${n} answered ${a.status} ${a.error}`,{error:e}),he(a.status,Rr(a,t),t,a.retryAfter!==void 0?{"retry-after":String(a.retryAfter)}:{})}let s=Mt(e,n);return s?$(s,t):(e instanceof pe?_.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 Mt(e,t){if(e instanceof pt)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 pe&&ps.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=ls(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 Go(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return jr(e)?t(e.message):tt(e)&&!kn(e)&&!wn(e)?t(e.errorDescription):wn(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function wn(e){return e instanceof pt||e instanceof pe&&ps.has(e.status)||ls(e)!==void 0||tt(e)&&e.status===503&&kn(e)}async function gn(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,Co).map(o=>({field:(o.path??[]).map(i=>String(typeof i=="object"&&i!==null&&"key"in i?i.key:i)).join("."),message:o.message})),a=r.issues.length-s.length;throw new re(400,"bad_request",`${n} failed validation`,a>0?{fields:s,more:a}:{fields:s})}return r.value}async function ot(e,t){let n=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(n)&&n>t)throw new re(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:u,value:p}=await r.read();if(u)break;if(a+=p.byteLength,a>t)throw await r.cancel().catch(()=>{}),new re(413,"payload_too_large",`Request body exceeds ${t} bytes`);s.push(p)}let o=new Uint8Array(a),i=0;for(let u of s)o.set(u,i),i+=u.byteLength;return o}function Ho(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return fe(t)}function qo(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}}function Fo(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}:null}var Bo=/^[A-Za-z0-9._:-]{8,128}$/,Ko=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Jo={max:20,window:60},Wo=10*6e4,Vo=1e4,it=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},bn=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=fs("sha256").update(t).digest("hex"),a=(this.known.get(s)??0)>this.now(),o=`token-misses\0a:${n}`,i;if(!a){let p=this.limiter.reserve(o,Jo);if("wait"in p)throw new it(p.wait);i=p}let u=await r();if(!u)throw this.known.delete(s),new ft("unknown_token","The token is not one of the app's");return i&&this.limiter.give(o,i.window),this.known.delete(s),this.known.set(s,this.now()+Wo),this.known.size>Vo&&this.known.delete(this.known.keys().next().value),u}};function ic(e){let t=new kt(e.modules),n=rs(t.controllers.map(d=>d.cls)),r=new Map(n.map(d=>[d,Uo(d,e.auth)]));for(let[d,c]of r){if(!c.required&&d.params.some(l=>l.kind==="user"))throw new TypeError(`${d.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(d.meta.upload&&c.verifiedEmail)throw new TypeError(`${d.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`)}let s=new Map;for(let d of n)for(let c of d.params)c.kind==="resolve"&&s.set(c,t.dependencyOf(d.controller,c.resolver,`${d.id} @Resolve(${c.resolver?.name})`));let a=new Map;for(let d of t.cronProviders){let c=t.get(d),l=U(d,we),f=a.get(l.name);if(f)throw new TypeError(`@Cron "${l.name}" is ${f.owner} and ${d.name}: a cron's name is its own \u2014 name one of them`);a.set(l.name,{declaration:l,owner:d.name,run:h=>c.run(h)})}let o=new Map;for(let d of t.taskProviders){let c=t.get(d),l=U(d,ye),f=o.get(l.name);if(f)throw new TypeError(`@Task "${l.name}" is ${f.owner} and ${d.name}: a task type's name is its own \u2014 name one of them`);o.set(l.name,{declaration:l,owner:d.name,run:(h,m)=>c.run(h,m)})}let i=new Set,u=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(a.size>ss)throw new TypeError(`${a.size} @Cron classes: a machine runs ${ss} crons at most`);if(o.size>as)throw new TypeError(`${o.size} @Task classes: a machine runs ${as} task types at most`);a.size>0&&!e.platform&&_.info(`[palbase] ${a.size} @Cron(s): the platform runs them on a machine; nothing calls them here`);let p=fr(t.gateways.map(d=>({cls:d,instance:t.get(d)})),{run:(d,c,l,f)=>se.run({requestId:se.getStore()?.requestId??"",...d?.id?{userId:d.id}:{}},()=>Ct(e.database,e.database?d?.id?yn(e.database.requests,wt(d)):hn:void 0,l,c,async()=>{let h=await f();if(l?.aborted)throw new Error(`realtime gave up on ${c} before it ended`);return h})),broadcast:d=>e.server.realtime.broadcast({body:{messages:d}}),revalidate:d=>e.server.realtime.revalidate({body:d}),isOutage:wn});p.declarations.length>0&&!e.platform&&_.info(`[palbase] ${p.declarations.length} @Gateway(s): realtime tells a machine of them; nothing does here`);let g=Mr();(g.tools.size>0||g.agents.size>0)&&!e.platform&&_.info(`[palbase] ${g.tools.size} ai.tool(s) and ${g.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let k=d=>c=>t.provider(c,`${d} ctx.inject(${typeof c=="function"?c.name:String(c)})`),x=new $t,W=new vt(e.now??Date.now),L=new Set,z=e.database!==void 0||e.contractOnly?.database===!0;if(z){for(let d of n)if(nt(d)&&d.params.some(c=>c.kind==="headers"&&c.schema!==void 0&&Vr(c.schema)))throw new TypeError(`${d.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 Z=e.database?new Et(e.database.app):void 0,Y=ri(e.cors),ne=e.now??Date.now,v=new At(e.now),X=new bn(v,e.now??Date.now),b=e.maxBodyBytes??Po,E=d=>{let c=d.meta.options.rateLimit??e.rateLimit??jo;return c!==!1&&c.max>0&&c.window>0?c:!1},w=e.env??process.env,T=wr(t.webhooks,d=>t.get(d),w,{secrets:e.contractOnly===void 0}),O=T.size===0&&a.size===0&&o.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(w).filter(d=>typeof d[1]=="string"&&!Nn(d[0])))),N=new Map([...T.keys()].map(d=>[d,{seen:new Set,inflight:new Set}])),q=new Map([...T.keys()].map(d=>[d,{counts:new Map,at:void 0}])),J,I=()=>J??=ns(n,d=>({auth:r.get(d),limit:E(d)}),{databaseSeesCaller:z,idempotency:z,webhooks:[...T.values()].map(d=>({name:d.name,cls:d.cls.name,provider:d.provider,signatureHeader:d.signatureHeader,secretEnv:d.secretEnv,events:[...d.events.keys()]})),platformEvents:[...j.keys()],gateways:p.declarations,platformEventBuckets:Qo(j),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),j=new Map;for(let[d,c]of Object.entries(e.events??{}))j.set(d,c.map(l=>({name:`palbase(${d})`,call:f=>l(f)})));for(let d of t.eventProviders){let c=t.get(d);for(let{event:l,fn:f,bucket:h}of U(d,Se)??[]){if(!Fn.test(l))throw new TypeError(`@On("${l}") on ${d.name}.${f}: 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`);j.has(l)||j.set(l,[]),j.get(l).push({name:`${d.name}.${f}`,bucket:h,call:async(m,y)=>c[f](m,y)})}}let G=new Set,F=new Set;Un(e.server),Ln({to:(d,c)=>({emit:(l,f)=>p.emit(d,c,l,f),pipe:l=>p.pipe(d,c,l),revalidate:l=>p.revalidate(d,c,l)})}),Kn(e.platform?Jn(w.PALBASE_MACHINE):new yt(new Map([...o].map(([d,c])=>[d,c.declaration])),(d,c)=>Te(d,c),e.now));async function oe(d,c){let l;try{l=await Mn(d,e.webhookSecret,{now:e.now})}catch(f){if(f instanceof Ze)return $({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${f.code}`},c);throw f}if(fe(l.data),G.has(l.id))return new Response(null,{status:204,headers:{"x-request-id":c}});if(F.has(l.id))return $({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},c);F.add(l.id);try{let f;try{await Be(e.database,null,void 0,`event ${l.type}`,async()=>{for(let h of j.get(l.type)??[])if(!(h.bucket!==void 0&&Zo(l)!==h.bucket))try{await h.call(l,{requestId:c})}catch(m){throw f=h.name,m}})}catch(h){return _.error(`[palbase] ${f??"the delivery"} failed on ${l.type} ${l.id}; the platform delivers it again`,{error:h}),$({status:500,code:"handler_failed",message:"The event could not be handled"},c)}return G.add(l.id),G.size>at&&G.delete(G.values().next().value),new Response(null,{status:204,headers:{"x-request-id":c}})}finally{F.delete(l.id)}}async function ie(d,c={}){let l=d.headers.get("origin");if(Y&&l!==null){let f=Y.allows(l);if(d.method==="OPTIONS"&&d.headers.has("access-control-request-method"))return f?new Response(null,{status:204,headers:Y.preflight(l,d.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let h=await xn(d,c);if(f)for(let[m,y]of Object.entries(Y.headers(l)))m==="vary"?jt(h.headers,y):h.headers.set(m,y);else jt(h.headers,"Origin");return h}return xn(d,c)}async function Dt(d,c,l,f){if(!d.headers.get(l.scheme.header))return $e(l,"missing_signature",f);let h={headers:d.headers,body:await ot(d,l.scheme.maxBytes(b)),url:br(d,c)},m;try{m=l.scheme.check(h,ne()/1e3)}catch{return $e(l,"signature_mismatch",f,"check_failed")}if(typeof m=="string")return $e(l,m,f);let y=l.events.get(m.type);if(!y)return _.info(`[palbase] webhook ${l.name}: no @On takes "${m.type}"; acknowledged`),he(200,{ok:!0,handled:!1},f);let S=N.get(l.name),R=m.event,C=[];if(m.id!==void 0){if(S.seen.has(m.id))return he(200,{ok:!0,handled:!1,duplicate:!0},f);C=[m.id]}else if(m.ids&&Array.isArray(R)){let A=m.ids,P=R.map((D,ee)=>[D,A[ee]]).filter(([,D])=>D===void 0||!S.seen.has(D));if(P.length===0)return he(200,{ok:!0,handled:!1,duplicate:!0},f);R=P.map(([D])=>D),C=P.flatMap(([,D])=>D===void 0?[]:[D])}if(C.some(A=>S.inflight.has(A)))return $({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},f);fe(R);for(let A of C)S.inflight.add(A);let M;try{M=await Be(e.database,null,void 0,`webhook ${l.name}`,()=>y.call(R,{env:O,requestId:f,environmentId:e.projectId??""}))}catch(A){let P=Mt(A,`webhook ${l.name}`)??Yo(A,l.name);return P?$(P,f):(_.error(`[palbase] ${y.name} failed on ${l.name} "${m.type}"; the sender delivers it again`,{error:A}),$({status:500,code:"handler_failed",message:"The event could not be handled"},f))}finally{for(let A of C)S.inflight.delete(A)}for(let A of C)S.seen.add(A),S.seen.size>at&&S.seen.delete(S.seen.values().next().value);return dt(M,l,f)}function dt(d,c,l){if(d instanceof Response)return d;if(typeof d=="string"){let f=c.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(d,{status:200,headers:{"content-type":f,"x-request-id":l}})}return he(200,d??{ok:!0,handled:!0},l)}function $e(d,c,l,f=c){let h=q.get(d.name);h.counts.set(f,(h.counts.get(f)??0)+1);let m=ne();return(h.at===void 0||m-h.at>=No)&&(ct(d.name),h.at=m),$({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${c}`},l)}function ct(d){let c=q.get(d).counts;if(c.size===0)return;let l=[...c.values()].reduce((f,h)=>f+h,0);_.warn(`[palbase] webhook ${d}: ${l} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(c)}),c.clear()}function V(d){let c=d.split("/").filter(Boolean);return c.length===2&&c[0]==="webhooks"?T.get(c[1]):void 0}async function Oe(d,c,l,f){let h=c.pathname===Ke;if(d.method!==(h?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:h?"The crons are listed with GET":"A cron is run with POST"},f);let m=h?new Uint8Array(0):await ot(d,Mo);try{await lt({secret:l,signature:d.headers.get("palbase-signature"),body:m,now:e.now})}catch(Q){if(Q instanceof Ze)return $({status:401,code:"invalid_signature",message:`The crons are the platform's to call: ${Q.code}`},f);throw Q}if(h){let Q=[...a.values()].map(({declaration:B})=>({name:B.name,schedule:B.schedule,time_zone:B.timeZone,timeout:B.timeout,retry:B.retries}));return he(200,{crons:Q},f,{"cache-control":"no-store"})}let y=c.pathname.slice(Ke.length+1),S=a.get(y);if(!S)return $({status:404,code:"cron_not_found",message:`This version has no cron ${JSON.stringify(y)}`},f);let R;try{R=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}"},f)}let{cron:C,run_id:M,scheduled_at:A,attempt:P}=R??{};if(C!==y||typeof M!="string"||M===""||typeof A!="string"||!os.test(A)||Number.isNaN(Date.parse(A))||!Number.isInteger(P)||P<1)return $({status:400,code:"bad_request",message:`A run of ${y} is the JSON {cron: "${y}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},f);let D=`${M}#${String(P)}`;if(i.has(D))return new Response(null,{status:204,headers:{"x-request-id":f}});if(u.has(D))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},f);u.add(D);let ee={env:O,environmentId:e.projectId??"",cron:y,runId:M,scheduledAt:new Date(A),attempt:P};try{await Ct(e.database,e.database?hn:void 0,d.signal,`cron ${y}`,async()=>{if(await S.run(ee),d.signal.aborted)throw new Error(`the platform gave up on this attempt of ${y} before it ended`)})}catch(Q){return d.signal.aborted||_.error(`[palbase] cron ${y} failed (run ${M}, attempt ${String(P)})`,{error:Q}),$({status:500,code:"cron_failed",message:`The cron ${y} failed; the platform tries it again`},f)}finally{u.delete(D)}return i.add(D),i.size>at&&i.delete(i.values().next().value),new Response(null,{status:204,headers:{"x-request-id":f}})}let Te=async({task:d,id:c,attempt:l,payload:f,createdAt:h},m)=>{let y=o.get(d);if(!y)return{status:404,message:`this version has no task ${JSON.stringify(d)}`};let S=fe(f??null),R=y.declaration.payload;if(R){let M=await R["~standard"].validate(S);if(M.issues){let A=M.issues.slice(0,5).map(P=>`${(P.path??[]).map(D=>String(typeof D=="object"&&D!==null&&"key"in D?D.key:D)).join(".")||"(payload)"}: ${P.message}`).join("; ");return _.error(`[palbase] task ${d} ${c}: what it carries is not what it takes \u2014 it fails, not to be tried again: ${A}`),{status:422,message:`what it carries is not what @Task "${d}" takes: ${A}`}}S=M.value}let C={env:O,environmentId:e.projectId??"",task:d,id:c,attempt:l,createdAt:h};try{await Ct(e.database,e.database?hn:void 0,m,`task ${d}`,async()=>{if(await y.run(S,C),m.aborted)throw new Error(`the platform gave up on this attempt of ${d} before it ended`)})}catch(M){return M instanceof gt?(_.error(`[palbase] task ${d} ${c} can never be done: ${M.message}`),{status:422,message:M.message}):(m.aborted||_.error(`[palbase] task ${d} failed (task ${c}, attempt ${String(l)})`,{error:M}),{status:500,message:`the task ${d} failed; it is tried again`})}return{status:204}};async function ut(d,c,l,f){let h=c.pathname===Je;if(d.method!==(h?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:h?"The task types are listed with GET":"A task is run with POST"},f);let m=h?new Uint8Array(0):await ot(d,Do);try{await lt({secret:l,signature:d.headers.get("palbase-signature"),body:m,now:e.now})}catch(Q){if(Q instanceof Ze)return $({status:401,code:"invalid_signature",message:`The tasks are the platform's to call: ${Q.code}`},f);throw Q}if(h){let Q=[...o.values()].map(({declaration:B})=>({name:B.name,timeout:B.timeout,retry:B.retries,concurrency:B.concurrency}));return he(200,{tasks:Q},f,{"cache-control":"no-store"})}let y=c.pathname.slice(Je.length+1),S;try{S=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}"},f)}let{task:R,id:C,attempt:M,payload:A,created_at:P}=S??{};if(R!==y||typeof C!="string"||C===""||typeof P!="string"||!os.test(P)||Number.isNaN(Date.parse(P))||!Number.isInteger(M)||M<1)return $({status:400,code:"bad_request",message:`A task of ${y} is the JSON {task: "${y}", id, attempt (1 or more), payload, created_at (RFC 3339)}`},f);let D=`task:${C}#${String(M)}`;if(i.has(D))return new Response(null,{status:204,headers:{"x-request-id":f}});if(u.has(D))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},f);u.add(D);let ee;try{ee=await Te({task:y,id:C,attempt:M,payload:A,createdAt:new Date(P)},d.signal)}finally{u.delete(D)}return ee.status===404?$({status:404,code:"task_not_found",message:ee.message??""},f):ee.status===422?$({status:422,code:"task_failure",message:ee.message??""},f):ee.status>=300?$({status:ee.status,code:"task_failed",message:ee.message??""},f):(i.add(D),i.size>at&&i.delete(i.values().next().value),new Response(null,{status:204,headers:{"x-request-id":f}}))}async function We(d,c,l,f){if(d.method!=="POST")return $({status:405,code:"method_not_allowed",message:`${f} is POSTed`},l);let h;try{jn({signature:d.headers.get("palbase-signature"),now:e.now}),h=await ot(d,1048576),await lt({secret:c,signature:d.headers.get("palbase-signature"),body:h,now:e.now})}catch(y){if(y instanceof Ze)return $({status:401,code:"invalid_signature",message:`${f} is the platform's to call: ${y.code}`},l);throw y}let m;try{m=JSON.parse(new TextDecoder().decode(h))}catch{return $({status:400,code:"bad_request",message:`${f} is JSON`},l)}return typeof m!="object"||m===null||!Object.hasOwn(m,"call")||m.call!==new URL(d.url).pathname?$({status:401,code:"invalid_signature",message:`${f} is the platform's to call: signed_for_another_call`},l):{body:m}}async function gs(d,c,l,f,h){let m=await We(c,l,f,`An upload's ${d}`);if(m instanceof Response)return m;let y=tr(d,m.body);if(typeof y=="string")return $({status:400,code:"bad_request",message:`An upload's ${d}: ${y}`},f);if(d==="complete"){if(L.has(y.uploadId))return $({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},f);L.add(y.uploadId),L.size>at&&L.delete(L.values().next().value)}let S=mn(n,y.method,y.route);if(!S||"malformed"in S||!S.route.meta.upload)return $({status:404,code:"not_found",message:`No upload route for ${y.method} ${y.route}`},f);let{route:R,params:C}=S,M=S.route.meta.upload,A=Fo(y.user);if(A&&On(h,A.id),r.get(R).required&&!A)throw new re(401,"unauthorized","This route needs a signed-in user");if(d==="authorize"){let ee=E(R);if(ee!==!1){let B=v.take(`${R.id}\0${Zn(y.user,y.client)}`,ee);if(B!==void 0)throw new re(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:B},B)}let Q=Xn(M.pathTemplate,{userId:A?.id??null,uploadId:y.uploadId,filename:y.filename});if("problem"in Q)throw new re(400,"bad_request",Q.problem);return await Be(e.database,wt(y.user),c.signal,R.id,async()=>{let B={request:c,query:new URLSearchParams(y.query),params:C,user:A,body:y.body===void 0||y.body===null?{}:fe(y.body),requestId:f};await _n(R,B);for(let Re of R.params)(Re.kind==="query"||Re.kind==="body"&&y.body!==void 0)&&await us(Re,B)}),he(200,{bucket:M.bucket,path:Q.path},f)}h.endpoint=R.id.slice(R.id.indexOf(" ")+1);let P=new URLSearchParams(y.query),D=y.body===null||y.body===void 0?{}:fe(y.body);return Nt(R,{request:c,query:P,params:C,user:A,body:D,requestId:f,uploadedObject:fe(y.uploadedObject)},wt(y.user))}function Sn(d,c,l,f){let h=d?{sub:d.id,role:"authenticated"}:null;return se.run({requestId:se.getStore()?.requestId??"",...d?{userId:d.id}:{}},()=>Be(e.database,h,l,c,async()=>{let m=await f();if(l.aborted)throw new Error(`the platform gave up on ${c} before it ended`);return m}))}let En=(d,c)=>new Response(d,{status:200,headers:{"content-type":"application/json","x-request-id":c}});async function ys(d,c,l){let f=await We(d,c,l,"A tool call");if(f instanceof Response)return f;let h=f.body,m=h.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"},l);let y=g.tools.get(m);if(!y)return $({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(m.slice(0,64))}`},l);let S=h.call_id,R=Ur(h.context);if(typeof S!="string"||S===""||S.length>256||typeof R=="string")return $({status:400,code:"bad_request",message:`A call of ${m} is {tool, call_id, input, context}${typeof R=="string"?`: ${R}`:""}`},l);let C=fs("sha256").update(JSON.stringify(h)).digest("hex"),M=x.answered(S);if(M!==void 0)return M.digest!==C?$({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},l):En(M.answer,l);if(x.isRunning(S))return $({status:409,code:"in_progress",message:"This call is running",retryAfter:2},l);x.start(S);let A;try{let P=await Sn(R.user,`ai.tool ${m}`,d.signal,()=>y.call(fe(h.input??{}),{...R,callId:S,signal:d.signal,inject:k(`ai.tool ${m}`)}));A="deferred"in P?JSON.stringify({deferred:!0,...P.expires_in_seconds!==void 0?{expires_in_seconds:P.expires_in_seconds}:{}}):JSON.stringify({output:P.output,is_error:P.is_error});let D=new TextEncoder().encode(A).byteLength;D>qe&&(_.error(`[palbase] ai.tool ${m} answered ${D} bytes (call ${S}): a machine's answer is ${qe} at most; the agent is told it failed`),A=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${qe/(1<<20)} MiB it may be`}],is_error:!0}))}catch(P){if(d.signal.aborted)return x.end(S,void 0),$({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);_.error(`[palbase] ai.tool ${m} failed (call ${S}, chat ${R.chatId}); the agent is told`,{error:P}),A=JSON.stringify({output:[{type:"text",text:Go(P)}],is_error:!0})}return x.end(S,{digest:C,answer:A}),En(A,l)}async function ws(d,c,l){let f=await We(d,c,l,"An agent's turn");if(f instanceof Response)return f;let h=Lr(f.body);if(typeof h=="string"||h.agent==="")return $({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata, message}${typeof h=="string"?`: ${h}`:": agent names it"}`},l);let m=h.agent,y=g.agents.get(m);if(!y)return $({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(m.slice(0,64))}`},l);let S;try{S=await Sn(h.user,`ai.agent ${m}`,d.signal,()=>y.resolve({...h,signal:d.signal,inject:k(`ai.agent ${m}`)}))}catch(M){if(d.signal.aborted)return $({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);let A=Mt(M,`ai.agent ${m}`);return A?$(A,l):(_.error(`[palbase] ai.agent ${m} failed for chat ${h.chatId}; the turn is not started`,{error:M}),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},l))}let R=S.tools.find(M=>g.tools.get(M.name)!==M);if(R)return _.error(`[palbase] ai.agent ${m} handed out ai.tool ${JSON.stringify(R.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`},l);let C=JSON.stringify(S.definition);return new TextEncoder().encode(C).byteLength>qe?(_.error(`[palbase] ai.agent ${m}'s definition is larger than the ${qe} bytes a machine's answer may be`),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},l)):new Response(C,{status:200,headers:{"content-type":"application/json","x-request-id":l,"cache-control":"no-store"}})}async function bs(d,c,l){let f=await We(d,c,l,"A repository's token");if(f instanceof Response)return f;let h=f.body;if(typeof h.repo!="string"||h.repo===""||typeof h.repository!="string"||typeof h.call_id!="string"||h.call_id===""||h.call_id.length>256)return $({status:400,code:"bad_request",message:"A repository's token is asked as {call_id, repo, repository}"},l);if(!W.take(h.call_id))return $({status:409,code:"call_id_reused",message:"This token ask was answered already"},l);let m=g.repos.get(h.repo),y=m?R=>m.token(R):g.repoTokens;if(!y)return $({status:404,code:"repo_not_found",message:`This version has no ai.repo ${JSON.stringify(h.repo.slice(0,64))}, and no ai.repoTokens`},l);let S;try{S=await y({repo:h.repo,repository:h.repository,signal:d.signal,inject:k(m?`ai.repo ${h.repo}`:`ai.repoTokens for ${h.repo}`)})}catch(R){if(d.signal.aborted)return $({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);let C=Mt(R,`ai.repo ${h.repo}`);return C?$(C,l):(_.error(`[palbase] ai.repo ${h.repo} gave no token; the workspace's clone or push is refused`,{error:R}),$({status:500,code:"token_failed",message:`The repository ${h.repo} gave no token`},l))}return!m&&S==null?$({status:404,code:"repo_not_found",message:`ai.repoTokens gives no token for ${JSON.stringify(h.repo.slice(0,64))}`},l):typeof S!="string"||S.trim()===""?(_.error(`[palbase] ai.repo ${h.repo}'s token function answered no token`),$({status:500,code:"token_failed",message:`The repository ${h.repo} gave no token`},l)):new Response(JSON.stringify({token:S}),{status:200,headers:{"content-type":"application/json","x-request-id":l,"cache-control":"no-store"}})}async function ks(d,c,l,f){let h=await We(c,l,f,`A gateway's ${d}`);if(h instanceof Response)return h;let m=await p.serve(d,h.body,c.signal);return"code"in m?$({status:m.status,code:m.code,message:m.message,retryAfter:m.retryAfter},f):"body"in m?he(200,m.body,f):new Response(null,{status:204,headers:{"x-request-id":f}})}async function _n(d,c){let l=[],f={params:Object.freeze({...c.params}),user:fe(c.user),headers:d.meta.upload?new Headers:c.request.headers,requestId:c.requestId};for(let h of d.params)h.kind==="resolve"&&(l[h.index]=await s.get(h).resolve(f,h.options));return l}async function Nt(d,c,l,f){let h=t.get(d.controller),m=await Be(e.database,l,c.request.signal,d.id,async()=>{let y=await _n(d,c);for(let R of d.params)R.kind!=="resolve"&&(y[R.index]=await us(R,c));f?.ran();let S=await h[d.fn](...y);if(c.uploadedObject&&c.request.signal.aborted)throw new Error(`storage gave up on ${d.id}'s upload before it was answered`);return f?f.record(is(cs(S,c.requestId),se.getStore()?.usedLocales)):S});return f?m:is(cs(m,c.requestId),se.getStore()?.usedLocales)}async function xn(d,c){let l=d.headers.get("x-request-id")??"",f=Bo.test(l)?l:`req_${crypto.randomUUID()}`,h=performance.now(),m=new URL(d.url).pathname,y={endpoint:m},S=await vs(d,c,f,y);return e.telemetry?.record({requestId:f,method:d.method,endpoint:y.endpoint,path:m,status:S.status,durationMs:performance.now()-h,userId:y.userId}),S}function On(d,c){d.userId=c;let l=se.getStore();l&&(l.userId=c)}async function vs(d,c,l,f){let h=e.strings,m=h?{requestId:l,strings:h,locales:In(d.headers.get("accept-language"),h.source),usedLocales:[]}:{requestId:l},y=await $s(m,d,c,l,f);return h&&jt(y.headers,"Accept-Language"),y}async function $s(d,c,l,f,h){return se.run(d,async()=>{let m=new URL(c.url),y=`${c.method} ${m.pathname}`;try{if(m.pathname===un&&j.size>0)return c.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},f):e.webhookSecret?await oe(c,f):$({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},f);let S=V(m.pathname);if(S)return y=`webhook ${S.name}`,c.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},f):await Dt(c,m,S,f);if(e.platform&&(m.pathname===Ke||m.pathname.startsWith(`${Ke}/`)))return y=m.pathname===Ke?"crons":`cron ${m.pathname.slice(Ke.length+1)}`,await Oe(c,m,e.platform.secret,f);if(e.platform&&(m.pathname===Je||m.pathname.startsWith(`${Je}/`)))return y=m.pathname===Je?"tasks":`task ${m.pathname.slice(Je.length+1)}`,await ut(c,m,e.platform.secret,f);if(e.platform&&(m.pathname===Wt||m.pathname===Wn)){let H=m.pathname===Wt?"authorize":"complete";return y=`upload ${H}`,await gs(H,c,e.platform.secret,f,h)}if(e.platform&&m.pathname.startsWith(`${Vt}/`)){let H=m.pathname.slice(Vt.length+1);return y=`gateway ${H}`,await ks(H,c,e.platform.secret,f)}if(e.platform&&m.pathname===Ar)return y="ai tool call",await ys(c,e.platform.secret,f);if(e.platform&&m.pathname===Pr)return y="ai agent's turn",await ws(c,e.platform.secret,f);if(e.platform&&m.pathname===Cr)return y="ai repository's token",await bs(c,e.platform.secret,f);if(Xo(m.pathname))return $({status:404,code:"not_found",message:`No route for ${c.method} ${m.pathname}`},f);let R=mn(n,c.method,m.pathname);if(R&&"malformed"in R)return $({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},f);if(!R)return $({status:404,code:"not_found",message:`No route for ${c.method} ${m.pathname}`},f);let{route:C,params:M}=R;if(y=C.id,h.endpoint=C.id.slice(C.id.indexOf(" ")+1),C.meta.upload)throw new re(400,"upload_required",`${C.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let A=r.get(C),P=null,D=null,ee=c.headers.get("authorization")??"",Q=/^(bearer|dpop)\s+(\S+)$/i.exec(ee),B=Q?.[2],Re=Q?.[1].toLowerCase()==="dpop";if(B)try{let H=!Re&&e.tokens&&!Ko.test(B)&&e.tokens.accepts(B)?e.tokens:void 0,Ae=H?await X.ask(B,Pt(c.headers,l.remoteAddress),()=>Be(e.database,null,c.signal,"token",()=>H.resolve(B))):await e.verifier.verify(B,Re?{proof:c.headers.get("dpop"),method:c.method,url:Dn(c.headers,m)}:void 0);P=qo(Ae),D=Ae.claims}catch(H){if(!A.required&&(H instanceof ft||H instanceof pt||H instanceof it))P=null;else throw H instanceof it?new re(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:H.wait},H.wait):H instanceof ft?new re(401,"invalid_token","The access token is not valid",{reason:H.reason},void 0,Lo(H.reason)):H}else if(ee!==""&&A.required)throw new re(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(P&&On(h,P.id),A.required&&!P)throw new re(401,"unauthorized","This route needs a signed-in user");if(A.verifiedEmail&&!P?.emailVerified)throw new re(403,"email_not_verified","This route needs a verified email address");let Rn=E(C);if(Rn!==!1){let H=P?`u:${P.id}`:`a:${Pt(c.headers,l.remoteAddress)}`,Ae=v.take(`${C.id}\0${H}`,Rn);if(Ae!==void 0)throw new re(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:Ae},Ae)}let Ve=c.method==="GET"||c.method==="HEAD"?void 0:await ot(c,b),Ts=Ve===void 0?void 0:Ho(Ve),An={request:c,query:m.searchParams,params:M,user:P,body:Ts,raw:Ve,requestId:f},Pn=Z&&Ve!==void 0&&nt(C)?Jr(c.method,c.headers):void 0;if(!Z||Pn===void 0)return await Nt(C,An,D);let Ss={role:yn(e.database.requests,D).role,uid:P?.id??`a:${Pt(c.headers,l.remoteAddress)}`},Cn=!1;return await Z.serve({key:Pn,caller:Ss,method:c.method,uri:`${m.pathname}${m.search}`,body:Ve},H=>Nt(C,An,D,{record:H,ran:()=>{Cn=!0}}),{requestId:f,refusal:H=>$(H,f),failure:H=>ds(H,f,y,c.signal),ran:()=>Cn})}catch(S){return ds(S,f,y,c.signal)}})}return{handle:ie,routes:n.map(d=>d.id),contract:I,start:()=>t.start(),stop:async()=>{p.close();for(let d of q.keys())ct(d);await t.shutdown(),await e.telemetry?.flush()}}}function Zo(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function Qo(e){let t=new Set;for(let[n,r]of e)if(qt(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 cs(e,t){return e instanceof Response?zo(e,t):e==null?new Response(null,{status:204,headers:{"x-request-id":t}}):he(200,e,t)}function Yo(e,t){if(!(!tt(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 Xo(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return Me.has(decodeURIComponent(t))}catch{return Me.has(t)}}var ei="GET, POST, PUT, PATCH, DELETE, QUERY",ti=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function ni(e){return ti.test(e)&&(!e.startsWith("http://")||/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(e))}function ri(e){if(!e)return;if(e.origins!=="*"){for(let r of e.origins)if(!ni(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":ei,"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 us(e,t){switch(e.kind){case"body":return gn(e.schema,t.body??{},"Request body");case"query":return gn(e.schema,fe(Object.fromEntries(t.query)),"Query parameters");case"headers":{let n={};return t.request.headers.forEach((r,s)=>n[s.toLowerCase()]=r),fe(n),e.schema?gn(e.schema,n,"Request headers"):n}case"param":return t.params[e.name];case"user":case"optionalUser":return fe(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"client":{let n=t.request.headers;return fe({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 $n=720*3600;function vn(e){return e instanceof pe&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function ms(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),$n)}function hs(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var Tn=class{filling=new Map;async get(t){try{let n=await ge.cache.getCacheEntry({query:{key:t}});return n.data.found?n.data.value??null:null}catch(n){if(!vn(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 ge.cache.putCacheEntry({query:{key:t},body:{value:hs(n),ttl:ms(r)}})}catch(s){if(!vn(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 ge.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await ge.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 ge.cache.getCacheEntry({query:{key:t}})).data}catch(u){if(!vn(u))throw u;_.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:u.status})}if(o?.found)return o.value??null;let i=await r();return await this.set(t,i,n),i}finally{this.filling.delete(t)}})();return this.filling.set(t,a),a}},lc=mt("Cache",new Tn);function fc(e={}){let t=e.maxEntries??5e4,n=e.now??(()=>Date.now()),r=new Map,s=new Map,a=p=>{let g=r.get(p);if(g&&g.expiresAt<=n()){r.delete(p);return}return g},o=()=>{let p=n();for(let[k,x]of r)x.expiresAt<=p&&r.delete(k);if(r.size<t)return;let g=[...r.entries()].sort((k,x)=>k[1].expiresAt-x[1].expiresAt);for(let[k]of g.slice(0,Math.ceil(g.length/4)))r.delete(k)},i=async(p,g,k)=>{r.size>=t&&!r.has(p)&&o(),r.set(p,{value:hs(g),expiresAt:n()+(ms(k)??$n)*1e3})};return{get:async p=>{let g=a(p);return g?structuredClone(g.value):null},set:i,async del(p){r.delete(p)},async incr(p){let g=a(p),k=(typeof g?.value=="number"&&Number.isInteger(g.value)?g.value:0)+1;return r.set(p,{value:k,expiresAt:g?.expiresAt??n()+$n*1e3}),k},getOrSet(p,g,k){let x=a(p);if(x)return Promise.resolve(structuredClone(x.value));let W=s.get(p);if(W)return W;let L=(async()=>{try{let z=await k();return await i(p,z,g),z}finally{s.delete(p)}})();return s.set(p,L),L}}}export{Gt as a,Se as b,je as c,ii as d,di as e,ci as f,ui as g,li as h,fi as i,pi as j,mi as k,hi as l,gi as m,yi as n,wi as o,bi as p,ki as q,vi as r,$i as s,Ti as t,Si as u,Ei as v,_i as w,xi as x,Oi as y,Ri as z,U as A,Ai as B,Pi as C,gt as D,Ni as E,Ui as F,Hi as G,qi as H,qs as I,rr as J,Vi as K,Zi as L,Qi as M,Yi as N,Xi as O,ed as P,td as Q,ad as R,K as S,Er as T,_r as U,xr as V,Pa as W,pd as X,gd as Y,yd as Z,wd as _,bd as $,kd as aa,vd as ba,$d as ca,Td as da,Cd as ea,Po as fa,ic as ga,ni as ha,$n as ia,lc as ja,fc as ka};
20
+ $answer$`,{drop:"DROP FUNCTION IF EXISTS palbase.idempotency_answer(text, timestamptz, integer, jsonb, text)"})]}),Xa={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},eo={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},to={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},no={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},Et=class extends Error{};function nt(e){return Kr.has(e.method)&&e.meta.upload===void 0}function Jr(e,t){if(!Kr.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function ro(e,t){return Wr([e.role,e.uid,t]).digest("hex")}function so(e){return Wr([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function Wr(e){let t=Ga("sha256");for(let n of e)t.update(n).update("\0");return t}function ao(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function cn(e){return e<500&&e!==429&&e!==499}function oo(e,t){return t&&cn(e)}function Vr(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 io={role:"service",claims:{}},_t=class{constructor(t){this.db=t}db;async serve(t,n,r){if(t.key.length>Gr)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${Gr} characters`});let s;try{s=await this.begin(ro(t.caller,t.key),so(t))}catch(i){return _.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:i}),r.refusal(no)}if("kept"in s)return co(s.kept,r.requestId);if("refused"in s)return r.refusal(s.refused==="reused"?Xa:eo);let a=s.claim,o;try{o=await n(i=>this.record(a,i))}catch(i){if(i instanceof Et)return r.refusal(to);let u=r.failure(i);return oo(u.status,r.ran())&&!qa(i)?this.keep(a,u):(await this.release(a),u)}return cn(o.status)||await this.release(a),o}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:on({hours:qr})}}}))}async begin(t,n){return Ha(Qa)===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:on({hours:qr})}}})>0)continue;let o=await r.findUnique({where:{key:t}});if(o===null)continue;let i=ao(o,n);if(i==="reused")return{refused:"reused"};if(i==="replay")return{kept:{status:o.status_code,headers:o.response_headers??[],body:o.response_body}};let[u]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:on({seconds:Hr})}},set:{started_at:Ir()}});return u?{claim:{key:t,started:u.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!cn(n.status))return n;let{response:r,kept:s}=await Br(n),a=se.getStore()?.database;if(!a)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let[o]=await a.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,s.status,JSON.stringify(s.headers),s.body]);if(o?.answered!==!0)throw new Et;return r}async keep(t,n){let{response:r,kept:s}=await Br(n);try{await this.asService(a=>a.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:Ir(),status_code:s.status,response_headers:s.headers,response_body: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()+Hr*1e3,r=()=>{Date.now()+Fr>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},Fr).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(io),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 co(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 St=Symbol("waits");function uo(e){return new Promise((t,n)=>{let r=setImmediate(()=>t(St));e.then(s=>{clearImmediate(r),t(s)},s=>{clearImmediate(r),n(s)})})}async function Br(e){let t=[];e.headers.forEach((i,u)=>{u!=="x-request-id"&&t.push([u,i])});let n=i=>new Response(i,{status:e.status,statusText:e.statusText,headers:e.headers});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 i=r.read(),u=await uo(i);if(u!==St&&u.done)break;if(u!==St&&(s.push(u.value),a+=u.value.byteLength,a<=Za))continue;let p=u===St?i:void 0,g=new ReadableStream({start(k){for(let x of s)k.enqueue(x)},async pull(k){let x=await(p??r.read());p=void 0,x.done?k.close():k.enqueue(x.value)},cancel:k=>r.cancel(k)});return{response:n(g),kept:{status:e.status,headers:t.filter(([k])=>k!=="content-length"&&k!=="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 lo}from"node:crypto";var ln="/webhooks/palbase",ts="PalbaseErrorEnvelope",Zr="PalbaseBearer",fo={$ref:`#/components/schemas/${ts}`},po={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"]},Qr={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Fe={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function ns(e,t,n){let r={[ts]:po},s={},a=[],o=[],i=new Set,u=new Map;for(let v of e){let X=o.find(V=>go(V,v));if(X){a.push({route:v.id,handler:Yr(v),answeredBy:X.id});continue}o.push(v);let b=v.segments.map(V=>typeof V=="string"?V:"{}").join("/");u.has(b)||u.set(b,wo(v.segments.flatMap(V=>typeof V=="string"?[]:[V.param])));let E=u.get(b),w=0,T=`/${v.segments.map(V=>typeof V=="string"?V:`{${E[w++]}}`).join("/")}`,O=t(v),N=xt(yo(v),i),q=v.method!=="GET"&&v.method!=="HEAD",J=V=>{let Oe=v.params.filter(Te=>Te.kind===V&&Te.schema).map((Te,lt)=>At(Te.schema,`${N}.${V}${lt===0?"":`.${lt+1}`}`,r));return Oe.length===0?void 0:Oe.length===1?Oe[0]:{allOf:Oe}},I=E.map(V=>({name:V,in:"path",required:!0,schema:{type:"string"}})),j=J("query");j&&I.push(...es(j,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:j}]);let G=J("headers");G&&I.push(...es(G,"header")??[]);let F=n.idempotency===!0&&nt(v);F&&I.push({...un,schema:{...un.schema}});let oe=q?J("body"):void 0,ie={operationId:N};v.controller.name!==""&&(ie.tags=[v.controller.name]),I.length>0&&(ie.parameters=I),oe&&(ie.requestBody={required:!To(oe),content:{"application/json":{schema:oe}}});let Nt=v.params.some(V=>V.schema!==void 0),ct=n.routes?.(v),$e=Eo(N,ct?.throws??[],n.errors);ie.responses={...So(ct,N,r),...Oo(O,{validates:Nt,hasPathParams:E.length>0,readsBody:q,keyed:F}),...xo($e,N,r)},$e.length>0&&(ie["x-palbase-errors"]=_o(N,$e)),O.auth.required&&(ie.security=[{[Zr]:[]}]),ie["x-palbase-handler"]=Yr(v);let ut=v.params.some(V=>V.kind==="optionalUser")||n.databaseSeesCaller;ie["x-palbase-auth"]=O.auth.required?"required":ut?"optional":"public",ie["x-palbase-verified-email"]=O.auth.verifiedEmail,ie["x-palbase-rate-limit"]=O.limit===!1?!1:{max:O.limit.max,window:O.limit.window},v.meta.upload&&(ie["x-palbase-upload"]={bucket:v.meta.upload.bucket,pathTemplate:v.meta.upload.pathTemplate}),(s[T]??={})[v.method.toLowerCase()]=ie}for(let v of n.webhooks??[]){let X={operationId:xt(`webhooks.${v.name}`,i)};v.cls!==""&&(X.tags=[v.cls]),X.description=v.provider?`${Qr[v.provider]??v.provider}'s deliveries: verified with ${Qr[v.provider]??v.provider}'s signature scheme under the secret in ${v.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${v.signatureHeader} header: verified under the secret in ${v.secretEnv}, then handed to the @On of their event type.`,X.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":{},[v.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:te("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:te("in_progress: the same delivery is being handled; the sender delivers it again",Fe),413:te("payload_too_large: the body is over what this sender sends"),500:te("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:te("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",Fe)},X["x-palbase-webhook"]=v.provider?{provider:v.provider,secretEnv:v.secretEnv,events:v.events}:{signatureHeader:v.signatureHeader,secretEnv:v.secretEnv,events:v.events},s[`/webhooks/${v.name}`]={post:X}}let p=[...new Set(n.platformEvents??[])].sort();if(p.length>0){let v={operationId:xt("webhooks.palbase",i)};v.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.",v.responses={204:{description:"Taken: handled, or a delivery already run"},401:te("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:te("in_progress: the same event is being handled; the platform delivers it again",Fe),500:te("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:te("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let X=[...new Set(n.platformEventBuckets??[])].sort();v["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:p,...X.length>0?{buckets:X}:{}},s[ln]={post:v}}let g=n.gateways??[],k=mo(g,r),x=g.length>0,W=Object.fromEntries(g.filter(Ue).map(v=>[v.pattern,{events:k[v.name].events,messages:Object.fromEntries(Object.entries(k[v.name].messages).map(([X,b])=>[X,b.payload])),graceMs:v.graceMs,...v.logKeepSeconds>0?{logKeepSeconds:v.logKeepSeconds}:{}}])),L=Object.keys(W).length>0,z=g.filter(v=>!Ue(v)).map(v=>({pattern:v.pattern,kind:v.access,publish:v.publish,state_read:!1,state_write:!1,...v.logKeepSeconds>0?{log_keep_seconds:v.logKeepSeconds}:{}})),Z=z.length>0,Y={schemas:r,securitySchemes:{[Zr]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},ne={openapi:"3.2.0",info:{title:"Palbase backend",version:lo("sha256").update(JSON.stringify({paths:s,components:Y,unreachable:a,...x?{gateways:k}:{},...L?{rooms:W}:{},...Z?{channels:z}:{}})).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:Y};return a.length>0&&(ne["x-palbase-unreachable"]=a),x&&(ne["x-palbase-gateways"]=k),L&&(ne["x-palbase-room"]=W),Z&&(ne["x-palbase-channels"]=z),ne}function mo(e,t){let n=[];for(let r of e){let s=(i,u,p,g)=>{let k=Rt(`${r.name}_${i}_${u}`),x={},W=At(p,k,x,g);W.$ref===void 0&&(x[k]=W),ho(r.pattern,i,u,x[k]);for(let[L,z]of Object.entries(x)){if(Object.hasOwn(t,L)&&JSON.stringify(t[L])!==JSON.stringify(z))throw new Error(`@Gateway("${r.pattern}") ${i} "${u}": its schema is the component ${L}, which another gateway's names with another schema \u2014 rename one of them`);t[L]=z}return{$ref:`#/components/schemas/${k}`}},a=Object.fromEntries(Object.entries(r.events).map(([i,u])=>[i,s("event",i,u,"answered")])),o=Object.fromEntries(Object.entries(r.messages).map(([i,u])=>[i,{payload:s("message",i,u.schema,"sent"),...u.reply?{reply:s("reply",i,u.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 ho(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 go(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 Yr(e){return`${e.controller.name}.${e.fn}`}function yo(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 xt(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function wo(e){let t=new Set;return e.map(n=>xt(n,t))}function At(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:bo}:{}}})}catch{return{}}let i=Rt(t);for(;Object.keys(n).some(u=>u===i||u.startsWith(`${i}.`));)i=`${i}_`;return ko(o,i,n,r)}function bo(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function ko(e,t,n,r){let s=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},a=!1,o=p=>p==="#"?(a=!0,`#/components/schemas/${t}`):p.startsWith("#/$defs/")?`#/components/schemas/${t}.${Rt($o(p.slice(8)))}`:p,i="all";if(r==="sent"){let p=new Set;for(let g of[e,...Object.values(s)])Ot(g,p);i=p}for(let[p,g]of Object.entries(s))n[`${t}.${Rt(p)}`]=st(rt(g,o,i));let u=st(rt(e,o,i));return a?(n[t]=u,{$ref:`#/components/schemas/${t}`}):u}var vo=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"]),fn=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),pn=new Set(["anyOf","oneOf","allOf","prefixItems"]),mn=new Set(["properties","patternProperties","dependentSchemas"]),ae=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function rt(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):vo.has(s)?r[s]=a:fn.has(s)?r[s]=rt(a,t,n):pn.has(s)&&Array.isArray(a)?r[s]=a.map(o=>rt(o,t,n)):mn.has(s)&&ae(a)&&(r[s]=Object.fromEntries(Object.entries(a).map(([o,i])=>[o,rt(i,t,n)])));return r}var Xr=Number.MAX_SAFE_INTEGER;function st(e){if(!ae(e))return e;let t={};for(let[r,s]of Object.entries(e))fn.has(r)?t[r]=st(s):pn.has(r)&&Array.isArray(s)?t[r]=s.map(st):mn.has(r)&&ae(s)?t[r]=Object.fromEntries(Object.entries(s).map(([a,o])=>[a,st(o)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-Xr&&delete t.minimum,t.maximum===Xr&&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 Ot(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(fn.has(n))Ot(r,t);else if(pn.has(n)&&Array.isArray(r))for(let s of r)Ot(s,t);else if(mn.has(n)&&ae(r))for(let s of Object.values(r))Ot(s,t)}}function $o(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function Rt(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function es(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 To(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function te(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:fo}}}}function So(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=At(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function Eo(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 _o(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 xo(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,i)=>o-i)){let o=r.get(a),i=o.map(u=>{let p={error:{type:"string",const:u.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},g=["error","error_description","status","request_id"];return u.data&&(p.data=At(u.data,`${t}.${u.code}.data`,n,"answered"),g.push("data")),{type:"object",properties:p,required:g}});s[String(a)]={description:o.map(u=>u.code).join(" | "),content:{"application/json":{schema:i.length===1?i[0]:{oneOf:i}}}}}return s}function Oo(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);return s.length>0&&(n[400]=te(s.join("; "))),e.auth.required&&(n[401]=te("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.verifiedEmail&&(n[403]=te("email_not_verified: the user's email address is not verified")),t.keyed&&(n[409]=te("idempotency_key_in_use: a request with this Idempotency-Key is still running",Fe)),t.readsBody&&(n[413]=te("payload_too_large: the body is over the app's body limit")),t.keyed&&(n[422]=te("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(n[429]=te("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Fe)),n[500]=te("internal_error: the handler failed; the app's log has it under the request id"),n[503]=te(`${e.auth.required?"auth_unavailable: sign-ins 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":""}`,Fe),n}var Pt=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))}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 Ct(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return Ro(r??t??"unknown")}function Ro(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(":"):[],i=t.includes("::")?[...a,...Array(8-a.length-o.length).fill("0"),...o]:a;return i.length!==8||i.some(u=>!/^[0-9a-f]{1,4}$/i.test(u))?t:`${i.slice(0,4).map(u=>parseInt(u,16).toString(16)).join(":")}::/64`}function rs(e){let t=[];for(let n of e){let r=U(n,Pe),s=U(n,Ce)??[];if(s.length===0)throw new TypeError(`@Controller ${n.name} has no routes: a controller with nothing to serve is a mistake`);let a=U(n,zt)??new Map;for(let o of s){let i=`${r.basePath}${o.subpath}`||"/",u=i.split("/").filter(Boolean).map(g=>{let k=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(g)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(g);return k?{param:k[1]}:g});if(typeof u[0]=="string"&&Me.has(u[0]))throw new TypeError(`${n.name}.${o.fn}: ${o.method} ${i} \u2014 /${u[0]} is the platform's; a route is served elsewhere`);let p=[...a.get(o.fn)??[]].sort((g,k)=>g.index-k.index);for(let g of p)if(g.kind==="param"&&!u.some(k=>typeof k!="string"&&k.param===g.name))throw new TypeError(`${n.name}.${o.fn}: @Param("${g.name}") names no {${g.name}} in ${o.method} ${i}`);t.push({id:`${o.method} ${i}`,method:o.method,segments:u,controller:n,fn:o.fn,params:p,meta:o,controllerAuth:r.options.auth})}}return er(t),t}function hn(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 i=0;i<r.length&&o;i++){let u=s.segments[i];if(typeof u=="string")o=u===r[i];else try{a[u.param]=decodeURIComponent(r[i])}catch{return{malformed:!0}}}if(o)return{route:s,params:a}}return null}function yn(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Be(e,t,n,r,s){return it(e,e?yn(e.requests,t):void 0,n,r,s)}var jt={role:"service",claims:{}};async function it(e,t,n,r,s){if(!e||!t)return s();let a=p=>_.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 ${p} 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:p}),o=e.app.request(t,{signal:n,heldIdle:a}),i=se.getStore();i&&(i.database=o.database);let u;try{u=await s()}catch(p){throw await o.rollback(p).catch(g=>_.error("[palbase] the request's transaction could not be rolled back",{error:g})),p}try{await o.commit()}catch(p){throw await o.rollback(p).catch(g=>_.error("[palbase] the request's transaction could not be rolled back",{error:g})),p}return u}var Po=1024*1024,Co=20,jo={max:300,window:60},Ke="/_palbase/crons",Je="/_palbase/tasks",ss=50,as=50,Mo=4096,Do=69632,os=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,at=1e4,No=6e4;function Uo(e,t){let n=e.meta.options.auth??e.controllerAuth??t??!0;if(typeof n=="boolean")return{required:n,verifiedEmail:!1};if((n.role??"").trim()!==""||(n.permission??"").trim()!=="")throw new TypeError(`${e.id}: auth { role, permission } were checked against v2's database; v3 has none yet \u2014 check the role in the service`);return{required:n.required!==!1,verifiedEmail:n.verifiedEmail===!0}}var re=class extends Error{constructor(n,r,s,a,o,i){super(s);this.status=n;this.code=r;this.data=a;this.retryAfter=o;this.challenge=i}status;code;data;retryAfter;challenge};function Lo(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 Io=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function zo(e,t){let n=new Headers(e.headers);for(let r of Io)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 is(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),Mt(e.headers,"Accept-Language")),e}function Mt(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 he(e,t,n,r={}){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json","x-request-id":n,...r}})}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={};return e.retryAfter!==void 0&&(r["retry-after"]=String(e.retryAfter)),e.challenge!==void 0&&(r["www-authenticate"]=e.challenge),he(e.status,n,t,r)}var ps=new Set([0,429,502,503,504]);function ds(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 re)return $({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(tt(e)){let a=e;return a.status>=500&&_.error(`[palbase] ${n} answered ${a.status} ${a.error}`,{error:e}),he(a.status,Rr(a,t),t,a.retryAfter!==void 0?{"retry-after":String(a.retryAfter)}:{})}let s=Dt(e,n);return s?$(s,t):(e instanceof pe?_.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 Dt(e,t){if(e instanceof mt)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 pe&&ps.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=ls(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 Go(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return jr(e)?t(e.message):tt(e)&&!kn(e)&&!wn(e)?t(e.errorDescription):wn(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function wn(e){return e instanceof mt||e instanceof pe&&ps.has(e.status)||ls(e)!==void 0||tt(e)&&e.status===503&&kn(e)}async function gn(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,Co).map(o=>({field:(o.path??[]).map(i=>String(typeof i=="object"&&i!==null&&"key"in i?i.key:i)).join("."),message:o.message})),a=r.issues.length-s.length;throw new re(400,"bad_request",`${n} failed validation`,a>0?{fields:s,more:a}:{fields:s})}return r.value}async function ot(e,t){let n=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(n)&&n>t)throw new re(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:u,value:p}=await r.read();if(u)break;if(a+=p.byteLength,a>t)throw await r.cancel().catch(()=>{}),new re(413,"payload_too_large",`Request body exceeds ${t} bytes`);s.push(p)}let o=new Uint8Array(a),i=0;for(let u of s)o.set(u,i),i+=u.byteLength;return o}function Ho(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return fe(t)}function qo(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}}function Fo(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}:null}var Bo=/^[A-Za-z0-9._:-]{8,128}$/,Ko=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Jo={max:20,window:60},Wo=10*6e4,Vo=1e4,dt=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},bn=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=fs("sha256").update(t).digest("hex"),a=(this.known.get(s)??0)>this.now(),o=`token-misses\0a:${n}`,i;if(!a){let p=this.limiter.reserve(o,Jo);if("wait"in p)throw new dt(p.wait);i=p}let u=await r();if(!u)throw this.known.delete(s),new pt("unknown_token","The token is not one of the app's");return i&&this.limiter.give(o,i.window),this.known.delete(s),this.known.set(s,this.now()+Wo),this.known.size>Vo&&this.known.delete(this.known.keys().next().value),u}};function ic(e){let t=new vt(e.modules),n=rs(t.controllers.map(d=>d.cls)),r=new Map(n.map(d=>[d,Uo(d,e.auth)]));for(let[d,c]of r){if(!c.required&&d.params.some(l=>l.kind==="user"))throw new TypeError(`${d.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(d.meta.upload&&c.verifiedEmail)throw new TypeError(`${d.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`)}let s=new Map;for(let d of n)for(let c of d.params)c.kind==="resolve"&&s.set(c,t.dependencyOf(d.controller,c.resolver,`${d.id} @Resolve(${c.resolver?.name})`));let a=new Map;for(let d of t.cronProviders){let c=t.get(d),l=U(d,we),f=a.get(l.name);if(f)throw new TypeError(`@Cron "${l.name}" is ${f.owner} and ${d.name}: a cron's name is its own \u2014 name one of them`);a.set(l.name,{declaration:l,owner:d.name,run:h=>c.run(h)})}let o=new Map;for(let d of t.taskProviders){let c=t.get(d),l=U(d,ye),f=o.get(l.name);if(f)throw new TypeError(`@Task "${l.name}" is ${f.owner} and ${d.name}: a task type's name is its own \u2014 name one of them`);o.set(l.name,{declaration:l,owner:d.name,run:(h,m)=>c.run(h,m)})}let i=new Set,u=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(a.size>ss)throw new TypeError(`${a.size} @Cron classes: a machine runs ${ss} crons at most`);if(o.size>as)throw new TypeError(`${o.size} @Task classes: a machine runs ${as} task types at most`);a.size>0&&!e.platform&&_.info(`[palbase] ${a.size} @Cron(s): the platform runs them on a machine; nothing calls them here`);let p=fr(t.gateways.map(d=>({cls:d,instance:t.get(d)})),{run:(d,c,l,f)=>se.run({requestId:se.getStore()?.requestId??"",...d?.id?{userId:d.id}:{}},()=>it(e.database,e.database?d?.id?yn(e.database.requests,bt(d)):jt:void 0,l,c,async()=>{let h=await f();if(l?.aborted)throw new Error(`realtime gave up on ${c} before it ended`);return h})),broadcast:d=>e.server.realtime.broadcast({body:{messages:d}}),revalidate:d=>e.server.realtime.revalidate({body:d}),isOutage:wn});p.declarations.length>0&&!e.platform&&_.info(`[palbase] ${p.declarations.length} @Gateway(s): realtime tells a machine of them; nothing does here`);let g=Mr();(g.tools.size>0||g.agents.size>0)&&!e.platform&&_.info(`[palbase] ${g.tools.size} ai.tool(s) and ${g.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let k=d=>c=>t.provider(c,`${d} ctx.inject(${typeof c=="function"?c.name:String(c)})`),x=new Tt,W=new $t(e.now??Date.now),L=new Set,z=e.database!==void 0||e.contractOnly?.database===!0;if(z){for(let d of n)if(nt(d)&&d.params.some(c=>c.kind==="headers"&&c.schema!==void 0&&Vr(c.schema)))throw new TypeError(`${d.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 Z=e.database?new _t(e.database.app):void 0,Y=ri(e.cors),ne=e.now??Date.now,v=new Pt(e.now),X=new bn(v,e.now??Date.now),b=e.maxBodyBytes??Po,E=d=>{let c=d.meta.options.rateLimit??e.rateLimit??jo;return c!==!1&&c.max>0&&c.window>0?c:!1},w=e.env??process.env,T=wr(t.webhooks,d=>t.get(d),w,{secrets:e.contractOnly===void 0}),O=T.size===0&&a.size===0&&o.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(w).filter(d=>typeof d[1]=="string"&&!Nn(d[0])))),N=new Map([...T.keys()].map(d=>[d,{seen:new Set,inflight:new Set}])),q=new Map([...T.keys()].map(d=>[d,{counts:new Map,at:void 0}])),J,I=()=>J??=ns(n,d=>({auth:r.get(d),limit:E(d)}),{databaseSeesCaller:z,idempotency:z,webhooks:[...T.values()].map(d=>({name:d.name,cls:d.cls.name,provider:d.provider,signatureHeader:d.signatureHeader,secretEnv:d.secretEnv,events:[...d.events.keys()]})),platformEvents:[...j.keys()],gateways:p.declarations,platformEventBuckets:Qo(j),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),j=new Map;for(let[d,c]of Object.entries(e.events??{}))j.set(d,c.map(l=>({name:`palbase(${d})`,call:f=>l(f)})));for(let d of t.eventProviders){let c=t.get(d);for(let{event:l,fn:f,bucket:h}of U(d,Se)??[]){if(!Fn.test(l))throw new TypeError(`@On("${l}") on ${d.name}.${f}: 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`);j.has(l)||j.set(l,[]),j.get(l).push({name:`${d.name}.${f}`,bucket:h,call:async(m,y)=>c[f](m,y)})}}let G=new Set,F=new Set;Un(e.server),Ln({to:(d,c)=>({emit:(l,f)=>p.emit(d,c,l,f),pipe:l=>p.pipe(d,c,l),revalidate:l=>p.revalidate(d,c,l)})}),Kn(e.platform?Jn(w.PALBASE_MACHINE):new wt(new Map([...o].map(([d,c])=>[d,c.declaration])),(d,c)=>Te(d,c),e.now));async function oe(d,c){let l;try{l=await Mn(d,e.webhookSecret,{now:e.now})}catch(f){if(f instanceof Ze)return $({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${f.code}`},c);throw f}if(fe(l.data),G.has(l.id))return new Response(null,{status:204,headers:{"x-request-id":c}});if(F.has(l.id))return $({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},c);F.add(l.id);try{let f;try{await Be(e.database,null,void 0,`event ${l.type}`,async()=>{for(let h of j.get(l.type)??[])if(!(h.bucket!==void 0&&Zo(l)!==h.bucket))try{await h.call(l,{requestId:c})}catch(m){throw f=h.name,m}})}catch(h){return _.error(`[palbase] ${f??"the delivery"} failed on ${l.type} ${l.id}; the platform delivers it again`,{error:h}),$({status:500,code:"handler_failed",message:"The event could not be handled"},c)}return G.add(l.id),G.size>at&&G.delete(G.values().next().value),new Response(null,{status:204,headers:{"x-request-id":c}})}finally{F.delete(l.id)}}async function ie(d,c={}){let l=d.headers.get("origin");if(Y&&l!==null){let f=Y.allows(l);if(d.method==="OPTIONS"&&d.headers.has("access-control-request-method"))return f?new Response(null,{status:204,headers:Y.preflight(l,d.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let h=await xn(d,c);if(f)for(let[m,y]of Object.entries(Y.headers(l)))m==="vary"?Mt(h.headers,y):h.headers.set(m,y);else Mt(h.headers,"Origin");return h}return xn(d,c)}async function Nt(d,c,l,f){if(!d.headers.get(l.scheme.header))return $e(l,"missing_signature",f);let h={headers:d.headers,body:await ot(d,l.scheme.maxBytes(b)),url:br(d,c)},m;try{m=l.scheme.check(h,ne()/1e3)}catch{return $e(l,"signature_mismatch",f,"check_failed")}if(typeof m=="string")return $e(l,m,f);let y=l.events.get(m.type);if(!y)return _.info(`[palbase] webhook ${l.name}: no @On takes "${m.type}"; acknowledged`),he(200,{ok:!0,handled:!1},f);let S=N.get(l.name),R=m.event,C=[];if(m.id!==void 0){if(S.seen.has(m.id))return he(200,{ok:!0,handled:!1,duplicate:!0},f);C=[m.id]}else if(m.ids&&Array.isArray(R)){let A=m.ids,P=R.map((D,ee)=>[D,A[ee]]).filter(([,D])=>D===void 0||!S.seen.has(D));if(P.length===0)return he(200,{ok:!0,handled:!1,duplicate:!0},f);R=P.map(([D])=>D),C=P.flatMap(([,D])=>D===void 0?[]:[D])}if(C.some(A=>S.inflight.has(A)))return $({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},f);fe(R);for(let A of C)S.inflight.add(A);let M;try{M=await Be(e.database,null,void 0,`webhook ${l.name}`,()=>y.call(R,{env:O,requestId:f,environmentId:e.projectId??""}))}catch(A){let P=Dt(A,`webhook ${l.name}`)??Yo(A,l.name);return P?$(P,f):(_.error(`[palbase] ${y.name} failed on ${l.name} "${m.type}"; the sender delivers it again`,{error:A}),$({status:500,code:"handler_failed",message:"The event could not be handled"},f))}finally{for(let A of C)S.inflight.delete(A)}for(let A of C)S.seen.add(A),S.seen.size>at&&S.seen.delete(S.seen.values().next().value);return ct(M,l,f)}function ct(d,c,l){if(d instanceof Response)return d;if(typeof d=="string"){let f=c.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(d,{status:200,headers:{"content-type":f,"x-request-id":l}})}return he(200,d??{ok:!0,handled:!0},l)}function $e(d,c,l,f=c){let h=q.get(d.name);h.counts.set(f,(h.counts.get(f)??0)+1);let m=ne();return(h.at===void 0||m-h.at>=No)&&(ut(d.name),h.at=m),$({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${c}`},l)}function ut(d){let c=q.get(d).counts;if(c.size===0)return;let l=[...c.values()].reduce((f,h)=>f+h,0);_.warn(`[palbase] webhook ${d}: ${l} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(c)}),c.clear()}function V(d){let c=d.split("/").filter(Boolean);return c.length===2&&c[0]==="webhooks"?T.get(c[1]):void 0}async function Oe(d,c,l,f){let h=c.pathname===Ke;if(d.method!==(h?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:h?"The crons are listed with GET":"A cron is run with POST"},f);let m=h?new Uint8Array(0):await ot(d,Mo);try{await ft({secret:l,signature:d.headers.get("palbase-signature"),body:m,now:e.now})}catch(Q){if(Q instanceof Ze)return $({status:401,code:"invalid_signature",message:`The crons are the platform's to call: ${Q.code}`},f);throw Q}if(h){let Q=[...a.values()].map(({declaration:B})=>({name:B.name,schedule:B.schedule,time_zone:B.timeZone,timeout:B.timeout,retry:B.retries}));return he(200,{crons:Q},f,{"cache-control":"no-store"})}let y=c.pathname.slice(Ke.length+1),S=a.get(y);if(!S)return $({status:404,code:"cron_not_found",message:`This version has no cron ${JSON.stringify(y)}`},f);let R;try{R=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}"},f)}let{cron:C,run_id:M,scheduled_at:A,attempt:P}=R??{};if(C!==y||typeof M!="string"||M===""||typeof A!="string"||!os.test(A)||Number.isNaN(Date.parse(A))||!Number.isInteger(P)||P<1)return $({status:400,code:"bad_request",message:`A run of ${y} is the JSON {cron: "${y}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},f);let D=`${M}#${String(P)}`;if(i.has(D))return new Response(null,{status:204,headers:{"x-request-id":f}});if(u.has(D))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},f);u.add(D);let ee={env:O,environmentId:e.projectId??"",cron:y,runId:M,scheduledAt:new Date(A),attempt:P};try{await it(e.database,e.database?jt:void 0,d.signal,`cron ${y}`,async()=>{if(await S.run(ee),d.signal.aborted)throw new Error(`the platform gave up on this attempt of ${y} before it ended`)})}catch(Q){return d.signal.aborted||_.error(`[palbase] cron ${y} failed (run ${M}, attempt ${String(P)})`,{error:Q}),$({status:500,code:"cron_failed",message:`The cron ${y} failed; the platform tries it again`},f)}finally{u.delete(D)}return i.add(D),i.size>at&&i.delete(i.values().next().value),new Response(null,{status:204,headers:{"x-request-id":f}})}let Te=async({task:d,id:c,attempt:l,payload:f,createdAt:h},m)=>{let y=o.get(d);if(!y)return{status:404,message:`this version has no task ${JSON.stringify(d)}`};let S=fe(f??null),R=y.declaration.payload;if(R){let M=await R["~standard"].validate(S);if(M.issues){let A=M.issues.slice(0,5).map(P=>`${(P.path??[]).map(D=>String(typeof D=="object"&&D!==null&&"key"in D?D.key:D)).join(".")||"(payload)"}: ${P.message}`).join("; ");return _.error(`[palbase] task ${d} ${c}: what it carries is not what it takes \u2014 it fails, not to be tried again: ${A}`),{status:422,message:`what it carries is not what @Task "${d}" takes: ${A}`}}S=M.value}let C={env:O,environmentId:e.projectId??"",task:d,id:c,attempt:l,createdAt:h};try{await it(e.database,e.database?jt:void 0,m,`task ${d}`,async()=>{if(await y.run(S,C),m.aborted)throw new Error(`the platform gave up on this attempt of ${d} before it ended`)})}catch(M){return M instanceof yt?(_.error(`[palbase] task ${d} ${c} can never be done: ${M.message}`),{status:422,message:M.message}):(m.aborted||_.error(`[palbase] task ${d} failed (task ${c}, attempt ${String(l)})`,{error:M}),{status:500,message:`the task ${d} failed; it is tried again`})}return{status:204}};async function lt(d,c,l,f){let h=c.pathname===Je;if(d.method!==(h?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:h?"The task types are listed with GET":"A task is run with POST"},f);let m=h?new Uint8Array(0):await ot(d,Do);try{await ft({secret:l,signature:d.headers.get("palbase-signature"),body:m,now:e.now})}catch(Q){if(Q instanceof Ze)return $({status:401,code:"invalid_signature",message:`The tasks are the platform's to call: ${Q.code}`},f);throw Q}if(h){let Q=[...o.values()].map(({declaration:B})=>({name:B.name,timeout:B.timeout,retry:B.retries,concurrency:B.concurrency}));return he(200,{tasks:Q},f,{"cache-control":"no-store"})}let y=c.pathname.slice(Je.length+1),S;try{S=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}"},f)}let{task:R,id:C,attempt:M,payload:A,created_at:P}=S??{};if(R!==y||typeof C!="string"||C===""||typeof P!="string"||!os.test(P)||Number.isNaN(Date.parse(P))||!Number.isInteger(M)||M<1)return $({status:400,code:"bad_request",message:`A task of ${y} is the JSON {task: "${y}", id, attempt (1 or more), payload, created_at (RFC 3339)}`},f);let D=`task:${C}#${String(M)}`;if(i.has(D))return new Response(null,{status:204,headers:{"x-request-id":f}});if(u.has(D))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},f);u.add(D);let ee;try{ee=await Te({task:y,id:C,attempt:M,payload:A,createdAt:new Date(P)},d.signal)}finally{u.delete(D)}return ee.status===404?$({status:404,code:"task_not_found",message:ee.message??""},f):ee.status===422?$({status:422,code:"task_failure",message:ee.message??""},f):ee.status>=300?$({status:ee.status,code:"task_failed",message:ee.message??""},f):(i.add(D),i.size>at&&i.delete(i.values().next().value),new Response(null,{status:204,headers:{"x-request-id":f}}))}async function We(d,c,l,f){if(d.method!=="POST")return $({status:405,code:"method_not_allowed",message:`${f} is POSTed`},l);let h;try{jn({signature:d.headers.get("palbase-signature"),now:e.now}),h=await ot(d,1048576),await ft({secret:c,signature:d.headers.get("palbase-signature"),body:h,now:e.now})}catch(y){if(y instanceof Ze)return $({status:401,code:"invalid_signature",message:`${f} is the platform's to call: ${y.code}`},l);throw y}let m;try{m=JSON.parse(new TextDecoder().decode(h))}catch{return $({status:400,code:"bad_request",message:`${f} is JSON`},l)}return typeof m!="object"||m===null||!Object.hasOwn(m,"call")||m.call!==new URL(d.url).pathname?$({status:401,code:"invalid_signature",message:`${f} is the platform's to call: signed_for_another_call`},l):{body:m}}async function gs(d,c,l,f,h){let m=await We(c,l,f,`An upload's ${d}`);if(m instanceof Response)return m;let y=tr(d,m.body);if(typeof y=="string")return $({status:400,code:"bad_request",message:`An upload's ${d}: ${y}`},f);if(d==="complete"){if(L.has(y.uploadId))return $({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},f);L.add(y.uploadId),L.size>at&&L.delete(L.values().next().value)}let S=hn(n,y.method,y.route);if(!S||"malformed"in S||!S.route.meta.upload)return $({status:404,code:"not_found",message:`No upload route for ${y.method} ${y.route}`},f);let{route:R,params:C}=S,M=S.route.meta.upload,A=Fo(y.user);if(A&&On(h,A.id),r.get(R).required&&!A)throw new re(401,"unauthorized","This route needs a signed-in user");if(d==="authorize"){let ee=E(R);if(ee!==!1){let B=v.take(`${R.id}\0${Zn(y.user,y.client)}`,ee);if(B!==void 0)throw new re(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:B},B)}let Q=Xn(M.pathTemplate,{userId:A?.id??null,uploadId:y.uploadId,filename:y.filename});if("problem"in Q)throw new re(400,"bad_request",Q.problem);return await Be(e.database,bt(y.user),c.signal,R.id,async()=>{let B={request:c,query:new URLSearchParams(y.query),params:C,user:A,body:y.body===void 0||y.body===null?{}:fe(y.body),requestId:f};await _n(R,B);for(let Re of R.params)(Re.kind==="query"||Re.kind==="body"&&y.body!==void 0)&&await us(Re,B)}),he(200,{bucket:M.bucket,path:Q.path},f)}h.endpoint=R.id.slice(R.id.indexOf(" ")+1);let P=new URLSearchParams(y.query),D=y.body===null||y.body===void 0?{}:fe(y.body);return Ut(R,{request:c,query:P,params:C,user:A,body:D,requestId:f,uploadedObject:fe(y.uploadedObject)},bt(y.user))}function Sn(d,c,l,f){let h=d?{sub:d.id,role:"authenticated"}:null;return se.run({requestId:se.getStore()?.requestId??"",...d?{userId:d.id}:{}},()=>Be(e.database,h,l,c,async()=>{let m=await f();if(l.aborted)throw new Error(`the platform gave up on ${c} before it ended`);return m}))}let En=(d,c)=>new Response(d,{status:200,headers:{"content-type":"application/json","x-request-id":c}});async function ys(d,c,l){let f=await We(d,c,l,"A tool call");if(f instanceof Response)return f;let h=f.body,m=h.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"},l);let y=g.tools.get(m);if(!y)return $({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(m.slice(0,64))}`},l);let S=h.call_id,R=Ur(h.context);if(typeof S!="string"||S===""||S.length>256||typeof R=="string")return $({status:400,code:"bad_request",message:`A call of ${m} is {tool, call_id, input, context}${typeof R=="string"?`: ${R}`:""}`},l);let C=fs("sha256").update(JSON.stringify(h)).digest("hex"),M=x.answered(S);if(M!==void 0)return M.digest!==C?$({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},l):En(M.answer,l);if(x.isRunning(S))return $({status:409,code:"in_progress",message:"This call is running",retryAfter:2},l);x.start(S);let A;try{let P=await Sn(R.user,`ai.tool ${m}`,d.signal,()=>y.call(fe(h.input??{}),{...R,callId:S,signal:d.signal,inject:k(`ai.tool ${m}`)}));A="deferred"in P?JSON.stringify({deferred:!0,...P.expires_in_seconds!==void 0?{expires_in_seconds:P.expires_in_seconds}:{}}):JSON.stringify({output:P.output,is_error:P.is_error});let D=new TextEncoder().encode(A).byteLength;D>qe&&(_.error(`[palbase] ai.tool ${m} answered ${D} bytes (call ${S}): a machine's answer is ${qe} at most; the agent is told it failed`),A=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${qe/(1<<20)} MiB it may be`}],is_error:!0}))}catch(P){if(d.signal.aborted)return x.end(S,void 0),$({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);_.error(`[palbase] ai.tool ${m} failed (call ${S}, chat ${R.chatId}); the agent is told`,{error:P}),A=JSON.stringify({output:[{type:"text",text:Go(P)}],is_error:!0})}return x.end(S,{digest:C,answer:A}),En(A,l)}async function ws(d,c,l){let f=await We(d,c,l,"An agent's turn");if(f instanceof Response)return f;let h=Lr(f.body);if(typeof h=="string"||h.agent==="")return $({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata, message}${typeof h=="string"?`: ${h}`:": agent names it"}`},l);let m=h.agent,y=g.agents.get(m);if(!y)return $({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(m.slice(0,64))}`},l);let S;try{S=await Sn(h.user,`ai.agent ${m}`,d.signal,()=>y.resolve({...h,signal:d.signal,inject:k(`ai.agent ${m}`)}))}catch(M){if(d.signal.aborted)return $({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);let A=Dt(M,`ai.agent ${m}`);return A?$(A,l):(_.error(`[palbase] ai.agent ${m} failed for chat ${h.chatId}; the turn is not started`,{error:M}),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},l))}let R=S.tools.find(M=>g.tools.get(M.name)!==M);if(R)return _.error(`[palbase] ai.agent ${m} handed out ai.tool ${JSON.stringify(R.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`},l);let C=JSON.stringify(S.definition);return new TextEncoder().encode(C).byteLength>qe?(_.error(`[palbase] ai.agent ${m}'s definition is larger than the ${qe} bytes a machine's answer may be`),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},l)):new Response(C,{status:200,headers:{"content-type":"application/json","x-request-id":l,"cache-control":"no-store"}})}async function bs(d,c,l){let f=await We(d,c,l,"A repository's token");if(f instanceof Response)return f;let h=f.body;if(typeof h.repo!="string"||h.repo===""||typeof h.repository!="string"||typeof h.call_id!="string"||h.call_id===""||h.call_id.length>256)return $({status:400,code:"bad_request",message:"A repository's token is asked as {call_id, repo, repository}"},l);if(!W.take(h.call_id))return $({status:409,code:"call_id_reused",message:"This token ask was answered already"},l);let m=g.repos.get(h.repo),y=m?R=>m.token(R):g.repoTokens;if(!y)return $({status:404,code:"repo_not_found",message:`This version has no ai.repo ${JSON.stringify(h.repo.slice(0,64))}, and no ai.repoTokens`},l);let S;try{S=await it(e.database,e.database?jt:void 0,d.signal,`ai.repo ${h.repo}`,async()=>y({repo:h.repo,repository:h.repository,signal:d.signal,inject:k(m?`ai.repo ${h.repo}`:`ai.repoTokens for ${h.repo}`)}))}catch(R){if(d.signal.aborted)return $({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},l);let C=Dt(R,`ai.repo ${h.repo}`);return C?$(C,l):(_.error(`[palbase] ai.repo ${h.repo} gave no token; the workspace's clone or push is refused`,{error:R}),$({status:500,code:"token_failed",message:`The repository ${h.repo} gave no token`},l))}return!m&&S==null?$({status:404,code:"repo_not_found",message:`ai.repoTokens gives no token for ${JSON.stringify(h.repo.slice(0,64))}`},l):typeof S!="string"||S.trim()===""?(_.error(`[palbase] ai.repo ${h.repo}'s token function answered no token`),$({status:500,code:"token_failed",message:`The repository ${h.repo} gave no token`},l)):new Response(JSON.stringify({token:S}),{status:200,headers:{"content-type":"application/json","x-request-id":l,"cache-control":"no-store"}})}async function ks(d,c,l,f){let h=await We(c,l,f,`A gateway's ${d}`);if(h instanceof Response)return h;let m=await p.serve(d,h.body,c.signal);return"code"in m?$({status:m.status,code:m.code,message:m.message,retryAfter:m.retryAfter},f):"body"in m?he(200,m.body,f):new Response(null,{status:204,headers:{"x-request-id":f}})}async function _n(d,c){let l=[],f={params:Object.freeze({...c.params}),user:fe(c.user),headers:d.meta.upload?new Headers:c.request.headers,requestId:c.requestId};for(let h of d.params)h.kind==="resolve"&&(l[h.index]=await s.get(h).resolve(f,h.options));return l}async function Ut(d,c,l,f){let h=t.get(d.controller),m=await Be(e.database,l,c.request.signal,d.id,async()=>{let y=await _n(d,c);for(let R of d.params)R.kind!=="resolve"&&(y[R.index]=await us(R,c));f?.ran();let S=await h[d.fn](...y);if(c.uploadedObject&&c.request.signal.aborted)throw new Error(`storage gave up on ${d.id}'s upload before it was answered`);return f?f.record(is(cs(S,c.requestId),se.getStore()?.usedLocales)):S});return f?m:is(cs(m,c.requestId),se.getStore()?.usedLocales)}async function xn(d,c){let l=d.headers.get("x-request-id")??"",f=Bo.test(l)?l:`req_${crypto.randomUUID()}`,h=performance.now(),m=new URL(d.url).pathname,y={endpoint:m},S=await vs(d,c,f,y);return e.telemetry?.record({requestId:f,method:d.method,endpoint:y.endpoint,path:m,status:S.status,durationMs:performance.now()-h,userId:y.userId}),S}function On(d,c){d.userId=c;let l=se.getStore();l&&(l.userId=c)}async function vs(d,c,l,f){let h=e.strings,m=h?{requestId:l,strings:h,locales:In(d.headers.get("accept-language"),h.source),usedLocales:[]}:{requestId:l},y=await $s(m,d,c,l,f);return h&&Mt(y.headers,"Accept-Language"),y}async function $s(d,c,l,f,h){return se.run(d,async()=>{let m=new URL(c.url),y=`${c.method} ${m.pathname}`;try{if(m.pathname===ln&&j.size>0)return c.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},f):e.webhookSecret?await oe(c,f):$({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},f);let S=V(m.pathname);if(S)return y=`webhook ${S.name}`,c.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},f):await Nt(c,m,S,f);if(e.platform&&(m.pathname===Ke||m.pathname.startsWith(`${Ke}/`)))return y=m.pathname===Ke?"crons":`cron ${m.pathname.slice(Ke.length+1)}`,await Oe(c,m,e.platform.secret,f);if(e.platform&&(m.pathname===Je||m.pathname.startsWith(`${Je}/`)))return y=m.pathname===Je?"tasks":`task ${m.pathname.slice(Je.length+1)}`,await lt(c,m,e.platform.secret,f);if(e.platform&&(m.pathname===Vt||m.pathname===Wn)){let H=m.pathname===Vt?"authorize":"complete";return y=`upload ${H}`,await gs(H,c,e.platform.secret,f,h)}if(e.platform&&m.pathname.startsWith(`${Zt}/`)){let H=m.pathname.slice(Zt.length+1);return y=`gateway ${H}`,await ks(H,c,e.platform.secret,f)}if(e.platform&&m.pathname===Ar)return y="ai tool call",await ys(c,e.platform.secret,f);if(e.platform&&m.pathname===Pr)return y="ai agent's turn",await ws(c,e.platform.secret,f);if(e.platform&&m.pathname===Cr)return y="ai repository's token",await bs(c,e.platform.secret,f);if(Xo(m.pathname))return $({status:404,code:"not_found",message:`No route for ${c.method} ${m.pathname}`},f);let R=hn(n,c.method,m.pathname);if(R&&"malformed"in R)return $({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},f);if(!R)return $({status:404,code:"not_found",message:`No route for ${c.method} ${m.pathname}`},f);let{route:C,params:M}=R;if(y=C.id,h.endpoint=C.id.slice(C.id.indexOf(" ")+1),C.meta.upload)throw new re(400,"upload_required",`${C.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let A=r.get(C),P=null,D=null,ee=c.headers.get("authorization")??"",Q=/^(bearer|dpop)\s+(\S+)$/i.exec(ee),B=Q?.[2],Re=Q?.[1].toLowerCase()==="dpop";if(B)try{let H=!Re&&e.tokens&&!Ko.test(B)&&e.tokens.accepts(B)?e.tokens:void 0,Ae=H?await X.ask(B,Ct(c.headers,l.remoteAddress),()=>Be(e.database,null,c.signal,"token",()=>H.resolve(B))):await e.verifier.verify(B,Re?{proof:c.headers.get("dpop"),method:c.method,url:Dn(c.headers,m)}:void 0);P=qo(Ae),D=Ae.claims}catch(H){if(!A.required&&(H instanceof pt||H instanceof mt||H instanceof dt))P=null;else throw H instanceof dt?new re(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:H.wait},H.wait):H instanceof pt?new re(401,"invalid_token","The access token is not valid",{reason:H.reason},void 0,Lo(H.reason)):H}else if(ee!==""&&A.required)throw new re(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(P&&On(h,P.id),A.required&&!P)throw new re(401,"unauthorized","This route needs a signed-in user");if(A.verifiedEmail&&!P?.emailVerified)throw new re(403,"email_not_verified","This route needs a verified email address");let Rn=E(C);if(Rn!==!1){let H=P?`u:${P.id}`:`a:${Ct(c.headers,l.remoteAddress)}`,Ae=v.take(`${C.id}\0${H}`,Rn);if(Ae!==void 0)throw new re(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:Ae},Ae)}let Ve=c.method==="GET"||c.method==="HEAD"?void 0:await ot(c,b),Ts=Ve===void 0?void 0:Ho(Ve),An={request:c,query:m.searchParams,params:M,user:P,body:Ts,raw:Ve,requestId:f},Pn=Z&&Ve!==void 0&&nt(C)?Jr(c.method,c.headers):void 0;if(!Z||Pn===void 0)return await Ut(C,An,D);let Ss={role:yn(e.database.requests,D).role,uid:P?.id??`a:${Ct(c.headers,l.remoteAddress)}`},Cn=!1;return await Z.serve({key:Pn,caller:Ss,method:c.method,uri:`${m.pathname}${m.search}`,body:Ve},H=>Ut(C,An,D,{record:H,ran:()=>{Cn=!0}}),{requestId:f,refusal:H=>$(H,f),failure:H=>ds(H,f,y,c.signal),ran:()=>Cn})}catch(S){return ds(S,f,y,c.signal)}})}return{handle:ie,routes:n.map(d=>d.id),contract:I,start:()=>t.start(),stop:async()=>{p.close();for(let d of q.keys())ut(d);await t.shutdown(),await e.telemetry?.flush()}}}function Zo(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function Qo(e){let t=new Set;for(let[n,r]of e)if(Ft(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 cs(e,t){return e instanceof Response?zo(e,t):e==null?new Response(null,{status:204,headers:{"x-request-id":t}}):he(200,e,t)}function Yo(e,t){if(!(!tt(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 Xo(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return Me.has(decodeURIComponent(t))}catch{return Me.has(t)}}var ei="GET, POST, PUT, PATCH, DELETE, QUERY",ti=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function ni(e){return ti.test(e)&&(!e.startsWith("http://")||/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(e))}function ri(e){if(!e)return;if(e.origins!=="*"){for(let r of e.origins)if(!ni(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":ei,"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 us(e,t){switch(e.kind){case"body":return gn(e.schema,t.body??{},"Request body");case"query":return gn(e.schema,fe(Object.fromEntries(t.query)),"Query parameters");case"headers":{let n={};return t.request.headers.forEach((r,s)=>n[s.toLowerCase()]=r),fe(n),e.schema?gn(e.schema,n,"Request headers"):n}case"param":return t.params[e.name];case"user":case"optionalUser":return fe(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"client":{let n=t.request.headers;return fe({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 $n=720*3600;function vn(e){return e instanceof pe&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function ms(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),$n)}function hs(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var Tn=class{filling=new Map;async get(t){try{let n=await ge.cache.getCacheEntry({query:{key:t}});return n.data.found?n.data.value??null:null}catch(n){if(!vn(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 ge.cache.putCacheEntry({query:{key:t},body:{value:hs(n),ttl:ms(r)}})}catch(s){if(!vn(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 ge.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await ge.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 ge.cache.getCacheEntry({query:{key:t}})).data}catch(u){if(!vn(u))throw u;_.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:u.status})}if(o?.found)return o.value??null;let i=await r();return await this.set(t,i,n),i}finally{this.filling.delete(t)}})();return this.filling.set(t,a),a}},lc=ht("Cache",new Tn);function fc(e={}){let t=e.maxEntries??5e4,n=e.now??(()=>Date.now()),r=new Map,s=new Map,a=p=>{let g=r.get(p);if(g&&g.expiresAt<=n()){r.delete(p);return}return g},o=()=>{let p=n();for(let[k,x]of r)x.expiresAt<=p&&r.delete(k);if(r.size<t)return;let g=[...r.entries()].sort((k,x)=>k[1].expiresAt-x[1].expiresAt);for(let[k]of g.slice(0,Math.ceil(g.length/4)))r.delete(k)},i=async(p,g,k)=>{r.size>=t&&!r.has(p)&&o(),r.set(p,{value:hs(g),expiresAt:n()+(ms(k)??$n)*1e3})};return{get:async p=>{let g=a(p);return g?structuredClone(g.value):null},set:i,async del(p){r.delete(p)},async incr(p){let g=a(p),k=(typeof g?.value=="number"&&Number.isInteger(g.value)?g.value:0)+1;return r.set(p,{value:k,expiresAt:g?.expiresAt??n()+$n*1e3}),k},getOrSet(p,g,k){let x=a(p);if(x)return Promise.resolve(structuredClone(x.value));let W=s.get(p);if(W)return W;let L=(async()=>{try{let z=await k();return await i(p,z,g),z}finally{s.delete(p)}})();return s.set(p,L),L}}}export{Ht as a,Se as b,je as c,ii as d,di as e,ci as f,ui as g,li as h,fi as i,pi as j,mi as k,hi as l,gi as m,yi as n,wi as o,bi as p,ki as q,vi as r,$i as s,Ti as t,Si as u,Ei as v,_i as w,xi as x,Oi as y,Ri as z,U as A,Ai as B,Pi as C,yt as D,Ni as E,Ui as F,Hi as G,qi as H,qs as I,rr as J,Vi as K,Zi as L,Qi as M,Yi as N,Xi as O,ed as P,td as Q,ad as R,K as S,Er as T,_r as U,xr as V,Pa as W,pd as X,gd as Y,yd as Z,wd as _,bd as $,kd as aa,vd as ba,$d as ca,Td as da,Cd as ea,Po as fa,ic as ga,ni as ha,$n as ia,lc as ja,fc as ka};