palbase 0.4.0 → 0.5.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.
- package/dist/ai/index.js +10 -10
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +8 -8
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{TRHIZOIS.js → 32RCJNOH.js} +3 -3
- package/dist/chunks/{BJL2FT5W.js → 3AUBDHV2.js} +1 -1
- package/dist/chunks/{IVDNNHII.js → 7BA7LGEM.js} +2 -2
- package/dist/chunks/A7EL6JKQ.js +20 -0
- package/dist/chunks/AWHTWL65.js +2 -0
- package/dist/chunks/{2AT72FFB.js → B45UFKBR.js} +2 -2
- package/dist/chunks/{ST2NZ4TZ.js → DNHDO6AJ.js} +1 -1
- package/dist/chunks/{BHT2IHBE.js → EHJKMDP3.js} +2 -2
- package/dist/chunks/{3OIKIBMG.js → FSXD7MN3.js} +2 -2
- package/dist/chunks/{SUNHFMDO.js → KSJ6AMCG.js} +2 -2
- package/dist/chunks/PALOWH6U.js +6 -0
- package/dist/chunks/{RKNVSAGY.js → PFSUOVTB.js} +1 -1
- package/dist/chunks/{6JO3UVPT.js → QIN2NQPN.js} +2 -2
- package/dist/chunks/{FS222NNP.js → R43DXJZE.js} +2 -2
- package/dist/chunks/{ODFLUINN.js → TTZRGQWF.js} +1 -1
- package/dist/chunks/{UNTTPATW.js → ZXYDN6NA.js} +1 -1
- package/dist/cli.js +133 -129
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/ai.d.ts +20 -2
- package/types/ai/src/chats.d.ts +75 -1
- package/types/ai/src/index.d.ts +2 -2
- package/types/ai/src/tools.d.ts +35 -0
- package/types/backend/src/channels.d.ts +81 -0
- package/types/backend/src/container.d.ts +4 -2
- package/types/backend/src/decorators.d.ts +32 -17
- package/types/backend/src/engine.d.ts +12 -4
- package/types/backend/src/env.d.ts +1 -1
- package/types/backend/src/index.d.ts +4 -2
- package/types/backend/src/openapi.d.ts +3 -0
- package/types/backend/src/rooms.d.ts +10 -0
- package/types/backend/src/tasks.d.ts +168 -0
- package/types/internal/src/chat.d.ts +17 -1
- package/types/internal/src/modules/ai.d.ts +314 -0
- package/types/internal/src/modules/auth.d.ts +64 -47
- package/types/internal/src/modules/machines.d.ts +320 -79
- package/types/internal/src/modules/notify.d.ts +3 -3
- package/types/internal/src/modules/purchases.d.ts +562 -3
- package/types/internal/src/modules/storage.d.ts +32 -3
- package/types/web/src/ai.d.ts +25 -2
- package/types/web/src/client.d.ts +7 -0
- package/types/web/src/index.d.ts +1 -1
- package/types/web/src/paywall/placement.d.ts +2 -0
- package/types/web/src/purchases.d.ts +3 -1
- package/dist/chunks/CY6B75KF.js +0 -6
- package/dist/chunks/EGRDFD5C.js +0 -20
- package/dist/chunks/ZFX4BFQR.js +0 -2
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/*! palbase 0.5.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as dt,c as ee,d as Un,e as le,g as E,h as Ln}from"./DNHDO6AJ.js";import{b as Ke,d as ot,e as Mn,f as Dn,g as at,h as it,k as jn,q as Nn}from"./KSJ6AMCG.js";import{b as ie}from"./B45UFKBR.js";import"reflect-metadata";var Pt=[{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}],In="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)",ct=/^\d+$/;function bs(e,t,n){let r=new Set;for(let s of e.split(",")){let o=s.indexOf("/"),a=o===-1?s:s.slice(0,o),i=1;if(o!==-1){let y=s.slice(o+1);if(!ct.test(y)||Number(y)<1||Number(y)>n)return;i=Number(y)}let c=t,p=n;if(a!=="*")if(a.includes("-")){let y=a.indexOf("-"),k=a.slice(0,y),R=a.slice(y+1);if(!ct.test(k)||!ct.test(R)||Number(k)<t||Number(R)>n||Number(k)>Number(R))return;c=Number(k),p=Number(R)}else{if(!ct.test(a)||Number(a)<t||Number(a)>n)return;c=Number(a),p=o===-1?c:n}for(let y=c;y<=p;y+=i)r.add(y)}return r}function zn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${In}; "${e}" is not`;let n=[];for(let p=0;p<5;p++){let y=bs(t[p],Pt[p].lo,Pt[p].hi);if(!y)return`${In}; its ${Pt[p].name} "${t[p]}" is not one`;n.push(y)}let[,,r,s,o]=n;o.has(7)&&o.add(0);let a=t[2].startsWith("*"),i=t[4].startsWith("*"),c=new Date(Date.UTC(2e3,0,1));for(let p=0;p<366*8+2;p++,c.setUTCDate(c.getUTCDate()+1)){if(!s.has(c.getUTCMonth()+1))continue;let y=r.has(c.getUTCDate()),k=o.has(c.getUTCDay());if(a||i?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var _e=Symbol.for("palbase.backend.controller"),Se=Symbol.for("palbase.backend.routes"),Mt=Symbol.for("palbase.backend.params"),Dt=Symbol.for("palbase.backend.injectable"),jt=Symbol.for("palbase.backend.module"),be=Symbol.for("palbase.backend.events"),Oe=Symbol.for("palbase.backend.webhook"),he=Symbol.for("palbase.backend.crons"),fe=Symbol.for("palbase.backend.tasks");function Y(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var Ct=Symbol.for("palbase.backend.declared");function re(){let e=globalThis;return e[Ct]instanceof Set||(e[Ct]=new Set),e[Ct]}var xe=new Set(["webhooks","_palbase"]);function Ka(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&&xe.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);Y(n,_e,()=>({basePath:e,options:t})),re().add(n)}}function Ae(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,o)=>{if(typeof s!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);Y(r.constructor,Se,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var Ja=Ae("GET"),Wa=Ae("POST"),Va=Ae("PUT"),Za=Ae("PATCH"),Qa=Ae("DELETE"),Ga=Ae("QUERY");function se(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let o=Y(n.constructor,Mt,()=>new Map);o.has(r)||o.set(r,[]),o.get(r).push({index:s,kind:e,...t})}}function Nt(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 Ya=e=>se("body",{schema:Nt("Body",e)}),Xa=e=>se("query",{schema:Nt("QueryParams",e)}),ei=e=>se("headers",e===void 0?{}:{schema:Nt("Headers",e)}),ti=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return se("param",{name:e})},ni=()=>se("user"),ri=()=>se("optionalUser"),si=()=>se("req"),oi=()=>se("requestId"),ai=()=>se("requestId"),ii=()=>se("client");function di(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 se("resolve",{resolver:e,options:t[0]})}function ci(){return e=>{Y(e,Dt,()=>!0),re().add(e)}}function ui(e){return t=>{Y(t,jt,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Bn=/^[a-z]+(\.[a-z_]+)+$/,ks=/^[a-z][a-z0-9-]{1,62}$/,Ut=e=>e.startsWith("file.");function li(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"||!ks.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(!Ut(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,o)=>{if(typeof s!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@On("${e}") goes on a method`);Y(r.constructor,be,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),re().add(r.constructor)}}var Lt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,vs=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function qn(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(!vs.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 fi(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Lt.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=zn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||qn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${qn(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 o=>{if(typeof o.prototype.run!="function")throw new TypeError(`${n} on ${o.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(o,he))throw new TypeError(`${n} on ${o.name}: a class is one cron`);Object.defineProperty(o,he,{value:s,enumerable:!1}),re().add(o)}}var Hn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],$s=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function pi(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(!$s.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&&!Hn.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${Hn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&Ts(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=M(t,be)??[];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 o=new Set;for(let{event:a,bucket:i}of s){if(o.has(a))throw new TypeError(`${n}: @On("${a}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${n}: @On("${a}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);o.add(a)}Y(t,Oe,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:a,fn:i})=>({event:a,fn:i}))})),re().add(t)}}function Ts(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 M(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function mi(){return[...re()].filter(e=>M(e,_e)!==void 0)}function hi(e){return(M(e,Se)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var ut=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function ki(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Lt.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,fe))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,fe,{value:r,enumerable:!1}),re().add(s)}}var qt;function Kn(e){qt=e}function It(){if(!qt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return qt}var Es=720*3600;function Rs(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Es))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 _s(e){if(typeof e=="string")return e;let t=e[fe];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var vi=dt("Tasks",{async enqueue(e,t,n={}){return Rs(n),It().enqueue(_s(e),t===void 0?null:t,n)},async cancel(e,t={}){return It().cancel(e,t.machine)},async get(e,t={}){return It().get(e,t.machine)}}),zt=(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 o=await le.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 zt(o.data,o.status===200)},async cancel(n,r){return zt((await le.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return zt((await le.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ss=1e4,Os=36e5,Fn=24*36e5,lt=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let c of this.tasks.values())if(c.task===t&&c.key===r.key&&(c.finishedAt===void 0||this.now()-c.finishedAt<Fn))return this.view(c,!0)}let o=this.now(),a=r.delay!==void 0?o+r.delay*1e3:r.runAt?Math.max(o,r.runAt.getTime()):o,i={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:a,createdAt:new Date(o)};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 ie({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),o;try{o=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(o={status:504,message:`it did not end in ${n.timeout} s`})}catch(i){o={status:500,message:i.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let a=`${o.status}${o.message?`: ${o.message}`:""}`;o.status>=200&&o.status<300?this.finish(t,"succeeded"):o.status===422?this.finish(t,"failed",`the app said it can never be done: ${a}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${a}`):(t.state="waiting",t.reason=`the app answered ${a}`,t.runAt=this.now()+Math.min(Ss*2**Math.min(t.attempt-1,16),Os),E.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,o]of this.tasks)o.finishedAt!==void 0&&this.now()-o.finishedAt>=Fn&&this.tasks.delete(s);n==="failed"&&E.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()}}};import{markData as As}from"palgres";var Ht="/_palbase/storage/upload/authorize",Wn="/_palbase/storage/upload/complete",Bt="/_palbase/realtime/rooms";var xs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Pe(e){if(!xs(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 ft(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var pe=Symbol.for("palbase.backend.room"),Me=Symbol.for("palbase.backend.roomHooks"),Jt=6e4,Ce=255,Ps=["roles:","flags:","messaging:","debug:"],Wt=e=>new TextEncoder().encode(e).byteLength,Qn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function";function Vt(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(Wt(e)>Ce)return`a channel is ${Ce} 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=Ps.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 Gn(e){if(typeof e!="string"||e==="")return"is a name";if(Wt(e)>Ce)return`is ${Ce} bytes at most`}function Oi(e,t){if(typeof e!="string"||e==="")throw new TypeError('@Room(pattern, { events }): pattern is the channels it is, like "ai:{sessionId}"');let n=Vt(e);if(n)throw new TypeError(`@Room("${e}"): ${n}`);let r=t??{};if(typeof r.events!="object"||r.events===null||Array.isArray(r.events))throw new TypeError(`@Room("${e}"): events is required \u2014 what the room sends, by name, each its payload's schema ({} for none)`);for(let[a,i]of Object.entries(r.events)){let c=Gn(a);if(c)throw new TypeError(`@Room("${e}"): event "${a}" ${c}`);if(!Qn(i))throw new TypeError(`@Room("${e}"): event "${a}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Room("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);let s={...r.events},o=r.graceMs??Jt;return a=>{let i=Y(a,Me,Zt);Y(a,pe,()=>({pattern:e,events:s,graceMs:o,hooks:{...i.hooks},messages:Object.assign(Object.create(null),i.messages)})),re().add(a)}}var Zt=()=>({hooks:Object.create(null),messages:Object.create(null)});function Je(e){let t=`On${e[0].toUpperCase()}${e.slice(1)}`;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 room's methods are its instance's`);let o=Y(n.constructor,Me,Zt),a=o.hooks[e];if(a!==void 0&&a!==r)throw new TypeError(`@${t}() is declared twice in one room (${a} and ${r}). A room has one of each hook.`);o.hooks[e]=r,re().add(n.constructor)}}var xi=Je("authorize"),Ai=Je("first"),Pi=Je("join"),Ci=Je("leave"),Mi=Je("empty");function Di(e,t){let n=Gn(e);if(n)throw new TypeError(`@OnMessage(name, schema): name ${n}`);if(!Qn(t))throw new TypeError(`@OnMessage("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return(r,s,o)=>{if(typeof s!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@OnMessage("${e}") goes on a method`);if(typeof r=="function")throw new TypeError(`@OnMessage("${e}") on static ${r.name}.${s}: a room's methods are its instance's`);let a=Y(r.constructor,Me,Zt),i=a.messages[e];if(i!==void 0&&i.fn!==s)throw new TypeError(`@OnMessage("${e}") is declared twice in one room (${i.fn} and ${s}).`);a.messages[e]={fn:s,schema:t},re().add(r.constructor)}}function Qt(e){return M(e,pe)}function Cs(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let o=0;o<n.length;o++){let a=n[o];if(a.length>=2&&a.startsWith("{")&&a.endsWith("}")){if(r[o]==="")return;s.push([a.slice(1,-1),r[o]])}else if(a!==r[o])return}return Object.fromEntries(s)}var Ms=1e4,Ds=1e3,js=100,Gt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ce=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Ns=new Set(["first","join","leave","empty"]);function Yn(e,t){let n=new Map,r=new Map;for(let{cls:h,instance:v}of e){let b=Qt(h),O=b.pattern.split(":").map(F=>F.startsWith("{")?"{}":F).join(":"),z=r.get(O);if(z!==void 0)throw new TypeError(`@Room("${b.pattern}") on ${h.name}: ${n.get(z)?.cls.name}'s "${z}" is the same channels \u2014 one room is told of them; keep one`);r.set(O,b.pattern);for(let[F,D]of[...Object.entries(b.hooks),...Object.entries(b.messages).map(([j,q])=>[`message ${j}`,q.fn])])if(typeof v[D]!="function")throw new TypeError(`@Room("${b.pattern}") on ${h.name}: its ${F} is ${D}, which is no method of it`);n.set(b.pattern,{cls:h,instance:v,room:b})}let s=new Map,o=new Set,a=new Set,i=new Kt(t.broadcast),c=h=>{let v=s.get(h);return v||(v=new AbortController,s.set(h,v)),v},p=(h,v)=>{v?.abort(),s.get(h)===v&&s.delete(h)};function y(h,v,b,O,z,F,D){let j=O?.signal??AbortSignal.abort(),q=`${h.cls.name} (${v})`;return{room:v,params:Object.freeze({...b}),signal:j,count:z,user:F,emit:(H,K)=>i.send({topic:v,event:H,payload:K??{},...D!==void 0?{conn_id:D}:{}},q),owner:{hold(H){ee.exit(async()=>{try{await H(j)}catch(K){j.aborted||E.error(`[palbase] ${q}: a task owner.hold ran failed`,{error:K})}}).catch(()=>{})},release:()=>p(v,O)}}}function k(h){let{room:v,channel:b}=h;if(typeof v!="string"||typeof b!="string")return ce(400,"bad_request","A room's call names its room (the pattern) and its channel");let O=n.get(v);return O?{entry:O,channel:b,params:Cs(v,b)}:ce(404,"not_found",`This app declares no room "${v}"`)}let R=(h,v)=>ce(400,"bad_request",`"${v}" is not a channel of the room "${h}"`);async function U(h,v){let b=k(h);if("status"in b)return b;let{entry:O,channel:z,params:F}=b,D={status:200,body:{subscribe:!1,publish:!1}};if(!F)return E.warn(`[palbase] ${O.cls.name}: realtime asked about "${z}", which is not a channel of the room "${O.room.pattern}"; the join is refused`),D;let j=Pe(h.user),q=j?.id;if(!q)return D;let H=O.room.hooks.authorize;if(!H)return D;let K,de;try{K=await t.run(j,`${O.cls.name}.${H}`,v,async()=>O.instance[H]({user:{id:q},params:Object.freeze({...F})})),de=Us(K)}catch(ne){if(t.isOutage(ne)||v?.aborted)throw ne;return E.error(`[palbase] ${O.cls.name}.${H} (@OnAuthorize of ${z}) failed; the join is refused`,{error:ne}),D}return de==="malformed"?(E.warn(`[palbase] ${O.cls.name}.${H} (@OnAuthorize of ${z}) answered ${Ls(K)}, which is no grant (true, { read, write } or null); the join is refused`),D):{status:200,body:de}}async function I(h,v){let b=k(h);if("status"in b)return b;if(!b.params)return R(b.entry.room.pattern,b.channel);let O=Pe(h.user);if(!O?.id||typeof h.event!="string")return ce(400,"bad_request","A message names its member (user) and its event");let z=Object.hasOwn(b.entry.room.messages,h.event)?b.entry.room.messages[h.event]:void 0;if(!z)return{status:200,body:{ok:!1,reason:Xn(`room "${b.channel}" declares no message "${h.event}"`,Ft)}};let F=await z.schema["~standard"].validate(As(h.payload??{}));if(F.issues)return{status:200,body:{ok:!1,reason:zs(F.issues)}};let D=c(b.channel),j={...y(b.entry,b.channel,b.params,D,0,{id:O.id}),payload:F.value};try{await t.run(O,`${b.entry.cls.name}.${z.fn}`,v,async()=>b.entry.instance[z.fn](j))}catch(q){if(t.isOutage(q))throw q;return v?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${z.fn} (@OnMessage "${h.event}" of ${b.channel}) failed`,{error:q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return{status:200,body:{ok:!0}}}async function L(h,v){let b=k(h);if("status"in b)return b;if(!b.params)return R(b.entry.room.pattern,b.channel);let O=h.event;if(typeof O!="string"||!Ns.has(O))return ce(400,"bad_request","A room's moment is first, join, leave or empty");let z=typeof h.count=="number"&&Number.isInteger(h.count)&&h.count>=0?h.count:void 0;if(z===void 0)return ce(400,"bad_request","A room's moment says its count of members");let F=O==="join"||O==="leave",D=F?Pe(h.user):void 0,j=F?h.connId:void 0;if(F&&(!D?.id||typeof j!="string"||j===""))return ce(400,"bad_request",`A ${O} names its member: user and connId`);let q=`${O}\0${b.channel}\0${typeof j=="string"?j:""}`;if(F&&o.has(q))return{status:204};if(a.has(q))return ce(503,"in_progress","This moment of the room is being handled",5);a.add(q);try{let H=b.entry.room.hooks[O],K;if(O==="empty"?(K=s.get(b.channel),p(b.channel,K)):K=O==="leave"?s.get(b.channel):c(b.channel),H){let de=y(b.entry,b.channel,b.params,K,z,{id:D?.id??""},O==="join"?j:void 0);try{await t.run(D,`${b.entry.cls.name}.${H}`,v,async()=>b.entry.instance[H](de))}catch(ne){if(t.isOutage(ne))throw ne;return v?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${H} (${O} of ${b.channel}) failed; realtime tells it again`,{error:ne}),ce(500,"handler_failed",`The room's ${O} could not be handled`)}}return F&&(o.add(q),o.size>Ms&&o.delete(o.values().next().value)),{status:204}}finally{a.delete(q)}}return{declarations:[...n.values()].map(h=>h.room),async serve(h,v,b){return Gt(v)?h==="authorize"?U(v,b):h==="message"?I(v,b):h==="lifecycle"?L(v,b):ce(404,"not_found",`No room call ${JSON.stringify(h)}`):ce(400,"bad_request","A room's call is a JSON object")},close(){for(let h of s.values())h.abort();s.clear()}}}function Us(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!Gt(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,o=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:o!==!1}}function Ls(e){return Array.isArray(e)?"an array":Gt(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 Is=20,Ft=256;function zs(e){let t="";for(let n of e.slice(0,Is)){let r=(n.path??[]).slice(0,8).map(o=>String(typeof o=="object"&&o!==null&&"key"in o?o.key:o).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Ft)break}return Xn(t,Ft)}function Xn(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 Kt=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Wt(t.event)>Ce){E.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Ce} bytes`);return}try{JSON.stringify(t.payload)}catch(o){E.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:o});return}let r=this.queues.get(t.topic);if(r){r.length>=Ds?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),ee.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,js);try{await this.broadcast(s)}catch(a){E.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:a})}let o=this.dropped.get(t);o&&(this.dropped.delete(t),E.warn(`[palbase] ${r}: ${o} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};var Yt=Symbol.for("palbase.backend.channels");function Ii(){return{kind:"owner"}}function zi(e={}){return{kind:"public",publish:e.publish??!1,state:e.state}}var qs=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}")).length,pt=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function qi(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("defineChannels({ pattern: entry }): an object of channel patterns");let t=[],n=[],r=new Map;for(let[i,c]of Object.entries(e)){let p=Vt(i);if(p)throw new TypeError(`defineChannels: "${i}": ${p}`);let y=r.get(pt(i));if(y!==void 0)throw new TypeError(`defineChannels: "${i}" and "${y}" are the same channels \u2014 keep one`);if(r.set(pt(i),i),typeof c!="object"||c===null)throw new TypeError(`defineChannels: "${i}": an entry is ownerOnly(), publicChannel() or { authorize }`);if("handler"in c)throw new TypeError(`defineChannels: "${i}": a handler is a room's in v3 \u2014 write @Room("${i}", { events }) with @OnAuthorize and @OnMessage, and leave it out of channels`);if("kind"in c&&c.kind==="owner"){if(qs(i)!==1)throw new TypeError(`defineChannels: ownerOnly() pattern "${i}" must carry exactly one {param} (its value is compared to the signed-in user's id)`);t.push({pattern:i,kind:"owner",publish:!1,state_read:!1,state_write:!1})}else if("kind"in c&&c.kind==="public")t.push({pattern:i,kind:"public",publish:c.publish??!1,state_read:c.state?.read??!1,state_write:c.state?.write??!1});else if("authorize"in c&&typeof c.authorize=="function")n.push({pattern:i,authorize:c.authorize});else throw new TypeError(`defineChannels: "${i}": an entry is ownerOnly(), publicChannel() or { authorize(ctx) }`)}let s={rows:t,custom:n},o=globalThis,a=o[Yt];if(a&&!Hs(a,s))throw new Error(`defineChannels: channels were already declared (${[...a.rows,...a.custom].map(i=>i.pattern).join(", ")}). A project declares its channels once \u2014 a second call would overwrite the first, and channels nobody declared are refused.`);return o[Yt]=s,s}function Hs(e,t){let n=r=>JSON.stringify([r.rows,r.custom.map(s=>[s.pattern,s.authorize.toString()])]);return n(e)===n(t)}function er(){return globalThis[Yt]??{rows:[],custom:[]}}function tr(e){let t=!1;return e.custom.map(({pattern:n,authorize:r})=>{let s={[`channel ${n}`]:class{}}[`channel ${n}`];return Y(s,pe,()=>({pattern:n,events:{},graceMs:Jt,hooks:{authorize:"authorize"},messages:Object.create(null)})),{cls:s,instance:{async authorize(a){let i=await r(a);return i==null||i.subscribe!==!0?null:(i.state&&!t&&(t=!0,E.warn(`[palbase] channel "${n}": its authorize answered state rights; a channel an authorize function decides is a room, which has none \u2014 the user hears${i.publish?" and sends":""}`)),{read:!0,write:i.publish===!0})}}}})}function nr(e,t){let n=new Map(t.map(r=>[pt(r.pattern),r.pattern]));for(let r of[...e.rows,...e.custom]){let s=n.get(pt(r.pattern));if(s!==void 0)return`channel "${r.pattern}" and @Room("${s}") are the same channels \u2014 a channel is declared in defineChannels or by a @Room, not both`}}var Bs=/^[a-z][a-z0-9-]{1,62}$/,rr=1024,Fs=new Set(["userId","uploadId","filename"]);function Ji(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(!Bs.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=Ks(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(a,i,c)=>{if(typeof i!="string"||c===void 0||typeof c.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);Y(a.constructor,Se,()=>[]).push({method:"POST",subpath:e,fn:i,options:o,upload:s})}}function Wi(){return se("uploadedObject")}function Ks(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Fs.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(!sr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function sr(e){if(e===""||new TextEncoder().encode(e).byteLength>rr)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 Js(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ws(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ws(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 or(e,t){let n=Js(e,t);return sr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${rr} bytes)`}}function ar(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(o=>o.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(o=>o.kind==="headers"||o.kind==="req"||o.kind==="client");if(s){let o=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${o}() 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 Xt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ir(e,t){if(!Xt(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:o}=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 o!="string"||o==="")return"uploadId is the upload's id";let a=Pe(t.user);if(!a)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:o,user:a,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let c=Vs(t.uploadedObject);return c?c.uploadId!==o?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:o,user:a,...i?{client:i}:{},filename:"",uploadedObject:c,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Vs(e){if(!Xt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:o,checksum:a,width:i,height:c,thumbhash:p,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof a!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(i!==void 0&&typeof i!="number"||c!==void 0&&typeof c!="number"||p!==void 0&&typeof p!="string")&&!(!Xt(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:o,checksum:a,...i!==void 0?{width:i}:{},...c!==void 0?{height:c}:{},...p!==void 0?{thumbhash:p}:{},variants:{...y}}}import{createHash as en,createHmac as Zs,createPublicKey as lr,timingSafeEqual as Qs,verify as fr}from"node:crypto";function Gi(e){let t=M(e,Oe);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 pr(e,t,n,r={}){let s=new Map,o=[];for(let a of e){let i=M(a,Oe),c=s.get(i.name);if(c)throw new TypeError(`@Webhook "${i.name}" is declared by ${c.cls.name} and by ${a.name}: /webhooks/${i.name} is one endpoint`);let p=`@Webhook "${i.name}" (${a.name})`,y=n[i.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")o.push(`${p} reads its signing secret from ${i.secret.env}, which is not set`);else try{k=Gs(i,y)}catch(I){o.push(`${p}: ${i.secret.env} ${I.message}`)}let R=t(a),U=new Map(i.events.map(({event:I,fn:L})=>[I,{name:`${a.name}.${L}`,call:(h,v)=>R[L](h,v)}]));s.set(i.name,{name:i.name,cls:a,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:k,events:U})}if(o.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
|
+
- ${o.join(`
|
|
4
|
+
- `)}`);return s}function mr(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var De=1024,dr=1024*De;function Gs(e,t){if(e.signature)return ke(void 0,e.signature.header,1/0,co(e.signature,t));switch(e.provider){case"stripe":return ke("stripe","stripe-signature",512*De,eo(t));case"github":return ke("github","x-hub-signature-256",25*dr,to(t));case"slack":return ke("slack","x-slack-signature",64*De,no(t));case"discord":return ke("discord","x-signature-ed25519",64*De,ro(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*De),check:oo(t)};case"sendgrid":return ke("sendgrid","x-twilio-email-event-webhook-signature",dr,ao(t));case"livekit":return ke("livekit","authorization",512*De,io(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function ke(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,o)=>r(s,o)??hr(e,s)}}function hr(e,t){let n=tn(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:gr(e,t.headers,r),event:r,...Ys(e,t,r)}}function gr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=ve(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=br(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 ve(n,"EventType");case"livekit":return ve(n,"event");default:return ve(n,"type")}}function Ys(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(ve(n,"id"));case"slack":return r(ve(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${yr(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>ve(s,"sg_event_id")||void 0)}:{};default:return{}}}var Xs=300;function eo(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,o=[];for(let c of r.split(",")){let p=c.indexOf("=");if(p<=0)continue;let y=c.slice(0,p).trim(),k=c.slice(p+1).trim();if(y==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(y==="v1"){let R=oe(k,"hex");if(!R)return"malformed_signature";o.push(R)}}let a=We(s);if(a===void 0||o.length===0)return"malformed_signature";if(Ve(a,n))return"stale_timestamp";let i=je("sha256",e,`${s}.`,t.body);return o.some(c=>ge(c,i))?void 0:"signature_mismatch"}}function to(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?oe(n.slice(7),"hex"):void 0;return r?ge(r,je("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function no(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(),o=We(s),a=r.startsWith("v0=")?oe(r.slice(3),"hex"):void 0;return o===void 0||!a?"malformed_signature":Ve(o,n)?"stale_timestamp":ge(a,je("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function ro(e){let t=oe(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=lr({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let o=r.headers.get("x-signature-ed25519");if(!o)return"missing_signature";let a=r.headers.get("x-signature-timestamp")??void 0,i=We(a),c=oe(o,"hex");return i===void 0||!c||c.byteLength!==64?"malformed_signature":Ve(i,s)?"stale_timestamp":fr(null,wr(a,r.body),n,c)?void 0:"signature_mismatch"}}var so=1e3;function oo(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=oe(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let o=s.searchParams.get("bodySHA256"),a="",i;if(o!==null){if(!ge(Buffer.from(o.toLowerCase()),Buffer.from(en("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let U=1;for(let h of t.body)if(h===38&&++U>so)return"malformed_signature";let I=new Map;for(let[h,v]of new URLSearchParams(tn(t.body))){let b=I.get(h);b||I.set(h,b=new Set),b.add(v)}let L=[];for(let h of[...I.keys()].sort()){let v=[...I.get(h)].sort();for(let b of v)a+=h+b;L.push([h,v.length===1?v[0]:v])}i=Object.fromEntries(L)}let c=s.protocol==="https:"?"443":"80",p=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,y=`${s.protocol}//${s.hostname}:${s.port||c}${s.pathname}${s.search}`;if(![p,y].some(U=>ge(r,je("sha1",e,U,a))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),R=k?{id:`${k}:${yr(`${p}
|
|
5
|
+
${a}`)}`}:{};return i?{type:gr("twilio",t.headers,i),event:i,...R}:{...hr("twilio",t),...R}}}function ao(e){let t;try{let n=oe(e,"base64");if(!n)throw new Error;t=lr({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 o=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),a=We(o),i=oe(s.trim(),"base64");return a===void 0||!i?"malformed_signature":Ve(a,r)?"stale_timestamp":fr("sha256",wr(o,n.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var cr=60;function io(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 o=ur(oe(s[0],"base64url")),a=oe(s[2],"base64url");if(o?.alg!=="HS256"||!a)return"malformed_signature";if(!ge(a,je("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let i=ur(oe(s[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(n>i.exp+cr||typeof i.nbf=="number"&&n<i.nbf-cr)return"stale_timestamp";let c=typeof i.sha256=="string"?oe(i.sha256,"base64"):void 0;return c&&ge(c,en("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function co(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,o)=>{let a=s.headers.get(e.header);if(!a)return"missing_signature";if(e.prefix){if(!a.startsWith(e.prefix))return"malformed_signature";a=a.slice(e.prefix.length)}let i="";if(n.includes("{ts}")){i=s.headers.get(e.timestampHeader)?.trim()??"";let p=We(i);if(p===void 0)return"malformed_signature";if(Ve(p,o))return"stale_timestamp"}let c=oe(a.trim(),e.encoding);return c?ge(c,je(r,t,...n.map(p=>p==="{body}"?s.body:p==="{ts}"?i:p)))?void 0:"signature_mismatch":"malformed_signature"}}var uo=new TextEncoder;function je(e,t,...n){let r=Zs(e,t);for(let s of n)r.update(s);return r.digest()}function yr(e){return en("sha256").update(e).digest("hex")}function wr(e,t){return Buffer.concat([uo.encode(e),t])}function ge(e,t){return e.byteLength===t.byteLength&&Qs(e,t)}var lo={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 oe(e,t){return lo[t].test(e)?Buffer.from(e,t):void 0}function We(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function Ve(e,t){return Math.abs(t-e)>Xs}function tn(e){return new TextDecoder().decode(e)}function ur(e){if(e)try{return JSON.parse(tn(e))}catch{return}}function br(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ve(e,t){let n=br(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var J=class extends Error{kind;path;constructor(t,n,r,s,o){super(`
|
|
6
|
+
Kind: ${t}
|
|
7
|
+
Path: ${n.join(" -> ")}
|
|
8
|
+
At: ${r}
|
|
9
|
+
${s}
|
|
10
|
+
|
|
11
|
+
Potential solutions:
|
|
12
|
+
${o.map(a=>` - ${a}`).join(`
|
|
13
|
+
`)}`),this.name="DiError",this.kind=t,this.path=n}},fo=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],po=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),mt=class{owner=new Map;defs=new Map;instances=new Map;order=[];controllers=[];eventProviders=[];webhooks=[];cronProviders=[];taskProviders=[];rooms=[];constructor(t){this.collect(t),this.validate()}collect(t){let n=(r,s)=>{if(this.defs.has(r))return;let o=M(r,jt);if(!o)throw new J("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,o);for(let a of o.imports){if(a===r)throw new J("unknown import",[r.name],r.name,`${r.name} imports itself`,["remove it from its own imports"]);n(a,[...s,r.name])}};for(let r of t)n(r,[]);for(let[r,s]of this.defs){for(let o of[...s.controllers,...s.providers]){let a=this.owner.get(o);if(a&&a!==r)throw new J("duplicate ownership",[a.name,o.name,r.name],o.name,`${o.name} is listed by ${a.name} and by ${r.name}; a class has one owner`,["keep it in one module and export it from there"]);this.owner.set(o,r)}for(let o of s.controllers){if(!M(o,_e))throw new J("undeclared provider",[r.name,o.name],o.name,`${o.name} is in ${r.name}'s controllers but is not a @Controller`,["decorate it with @Controller(path)"]);if(M(o,he))throw new J("undeclared provider",[r.name,o.name],o.name,`${o.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(M(o,fe))throw new J("undeclared provider",[r.name,o.name],o.name,`${o.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(M(o,pe)||M(o,Me))throw new J("undeclared provider",[r.name,o.name],o.name,`${o.name} is a controller and a @Room: a room is a provider's`,["give the room a class of its own, listed in the module's providers"]);this.controllers.push({cls:o,module:r})}}}validate(){for(let t of re())if(!this.owner.has(t))throw new J("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 J("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(M(r,Me)&&!M(r,pe))throw new J("undeclared provider",[t.name,r.name],r.name,`${r.name} has a room's methods (@OnAuthorize, @OnFirst, @OnMessage\u2026) but is no @Room`,["decorate it with @Room(pattern, { events })"]);if(!M(r,Dt)&&!M(r,be)&&!M(r,pe)&&!M(r,he)&&!M(r,fe)){let s=Reflect.getMetadata("design:paramtypes",r);throw r.length>0&&!s?new J("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 J("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 @Room, a @Cron or a @Task)`,["decorate it with @Injectable()"])}M(r,pe)&&this.rooms.push(r),M(r,Oe)?this.webhooks.push(r):M(r,be)&&this.eventProviders.push(r),M(r,he)&&this.cronProviders.push(r),M(r,fe)&&this.taskProviders.push(r)}}for(let t of this.owner.keys())for(let n of fo)if(typeof t.prototype[n]=="function")throw new J("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 J("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],o=t.length,a=Reflect.getMetadata("design:paramtypes",t)??[];if(o>0&&a.length===0)throw new J("metadata missing",s,t.name,`${t.name} takes ${o} 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=[];a.slice(0,o).forEach((p,y)=>{if(po.has(p)||typeof p!="function")throw new J("unresolvable dependency",s,`${t.name} constructor parameter ${y}`,`parameter ${y} 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 c=new t(...i);return this.instances.set(t,c),this.order.push(c),c}dependencyOf(t,n,r){let s=t;return this.resolve(this.reachable(s,n,[s.name,r]),[s.name,r])}reachable(t,n,r){let s=this.owner.get(t),o=this.target(n,r),a=this.owner.get(o);if(a!==s){if(!this.defs.get(s).imports.includes(a))throw new J("missing import",[...r,o.name],`${s.name}`,`${t.name} (in ${s.name}) needs ${o.name}, owned by ${a.name}, which ${s.name} does not import`,[`add ${a.name} to ${s.name}'s imports (imports are not transitive)`]);if(!this.defs.get(a).exports.includes(o))throw new J("private dependency",[...r,o.name],`${a.name}`,`${o.name} is ${a.name}'s own: it is not in its exports`,[`add ${o.name} to ${a.name}'s exports`])}return o}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 J("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 J("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 mo,HttpError as Ze}from"palgres";import{z as ye}from"zod";import{BadRequest as dd,Conflict as cd,DeadlockDetected as ud,HttpError as ld,NotFound as fd,SerializationFailure as pd,TooManyRequests as md,UniqueViolation as hd}from"palgres";function Qe(e){if(typeof e!="object"||e===null||e[mo]!==!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 kr=class extends Ze{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},vr=class extends Ze{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},$r=class extends Ze{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function Er(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 ho=Symbol.for("palbase.backend.errorRegistry"),go={bad_request:ye.object({fields:ye.array(ye.object({field:ye.string(),message:ye.string()})),more:ye.number().int().optional()}),too_many_requests:ye.object({retryAfter:ye.number().int()})},yo=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 wo(){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=go[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function bo(){let e=globalThis;return e[ho]??=wo()}function od(e,t,n){if(typeof e!="string"||!/^[a-z][a-z0-9_]*$/.test(e))throw new TypeError(`defineError(code, status): code is a lowercase wire code like room_locked, 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(yo.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=bo(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&Tr(s.data)!==Tr(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 o=e.split("_").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(""),a=e.replace(/_/g," "),i=a.charAt(0).toUpperCase()+a.slice(1),y=n?(k=>class extends Ze{static code=e;static status=t;constructor(R,U){let I=ko(e,k,R);super(t,e,U??(typeof I=="string"?I:i),I),this.name=o}})(n):class extends Ze{static code=e;static status=t;constructor(k){super(t,e,k??i),this.name=o}};return Object.defineProperty(y,"name",{value:o}),r.set(e,{code:e,status:t,className:o,builtin:!1,...n?{data:n}:{}}),y}function ko(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 Tr(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}var Rr="/_palbase/ai/tools",_r="/_palbase/ai/agents",Sr="/_palbase/ai/repos";var vo=Symbol.for("palbase.ai.tool_error");function Or(e){return e instanceof Error&&e[vo]===!0}var $o=Symbol.for("palbase.ai.declared");function xr(){let e=globalThis[$o];if(!e)return{tools:new Map,agents:new Map,repos:new Map};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; 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??[])}}var nn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function rn(e){if(!nn(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(!nn(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={};if(e.metadata!==void 0&&e.metadata!==null){if(!nn(e.metadata))return"context.metadata is an object of strings";for(let[r,s]of Object.entries(e.metadata)){if(typeof s!="string")return"context.metadata is an object of strings";Object.defineProperty(n,r,{value:s,enumerable:!0,writable:!0,configurable:!0})}}return{chatId:e.chat_id,agent:e.agent,user:t,metadata:n}}var To=1e4,Eo=10*6e4,ht=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<=Eo&&this.seen.size<=To)break;this.seen.delete(r)}return this.seen.has(t)?!1:(this.seen.set(t,n),!0)}},Ro=1e3,_o=256*1024,gt=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>_o)&&(this.answers.set(t,n),this.answers.size>Ro&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as ns,isEngineRaised as bn,markData as ae}from"palgres";import{createHash as rs}from"node:crypto";import{createHash as So,randomInt as Oo}from"node:crypto";import{ago as sn,isRetryable as xo,now as Ar}from"palgres";import{defineSchema as Ao,defineTable as Po,index as Co,integer as Mo,jsonb as Do,raw as jo,text as on,timestamp as Pr}from"palgres/dsl";var Ur=new Set(["POST","PUT","PATCH","DELETE"]),Cr=255,Mr=35,Dr=24,No=65536,jr=1e3,Uo=64,dn={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"}},Lo=Po("idempotency_keys",{columns:{key:on().primaryKey(),fingerprint:on(),started_at:Pr().defaultNow(),completed_at:Pr().nullable(),status_code:Mo().nullable(),response_headers:Do().nullable(),response_body:on().nullable()},indexes:e=>[Co("idempotency_keys_started").on(e.col("started_at"))]}),Td=Ao("palbase",{tables:[Lo],raw:[jo("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
|
+
LANGUAGE sql VOLATILE SECURITY DEFINER SET search_path = pg_catalog, pg_temp
|
|
15
|
+
AS $answer$
|
|
16
|
+
UPDATE palbase.idempotency_keys
|
|
17
|
+
SET completed_at = now(), status_code = answer_status, response_headers = answer_headers, response_body = answer_body
|
|
18
|
+
WHERE key = record_key AND started_at = claimed_at AND completed_at IS NULL
|
|
19
|
+
RETURNING true
|
|
20
|
+
$answer$`,{drop:"DROP FUNCTION IF EXISTS palbase.idempotency_answer(text, timestamptz, integer, jsonb, text)"})]}),Io={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},zo={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},qo={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},Ho={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},wt=class extends Error{};function Ge(e){return Ur.has(e.method)&&e.meta.upload===void 0}function Lr(e,t){if(!Ur.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function Bo(e,t){return Ir([e.role,e.uid,t]).digest("hex")}function Fo(e){return Ir([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function Ir(e){let t=So("sha256");for(let n of e)t.update(n).update("\0");return t}function Ko(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function an(e){return e<500&&e!==429&&e!==499}function Jo(e,t){return t&&an(e)}function zr(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 Wo={role:"service",claims:{}},bt=class{constructor(t){this.db=t}db;async serve(t,n,r){if(t.key.length>Cr)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${Cr} characters`});let s;try{s=await this.begin(Bo(t.caller,t.key),Fo(t))}catch(i){return E.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:i}),r.refusal(Ho)}if("kept"in s)return Vo(s.kept,r.requestId);if("refused"in s)return r.refusal(s.refused==="reused"?Io:zo);let o=s.claim,a;try{a=await n(i=>this.record(o,i))}catch(i){if(i instanceof wt)return r.refusal(qo);let c=r.failure(i);return Jo(c.status,r.ran())&&!xo(i)?this.keep(o,c):(await this.release(o),c)}return an(a.status)||await this.release(o),a}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:sn({hours:Dr})}}}))}async begin(t,n){return Oo(Uo)===0&&await this.sweep().catch(r=>E.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[o]=await r.insertMany([{key:t,fingerprint:n}],{onConflict:["key"],action:"ignore"});if(o)return{claim:{key:t,started:o.started_at}};if(await r.deleteMany({where:{key:t,started_at:{lt:sn({hours:Dr})}}})>0)continue;let a=await r.findUnique({where:{key:t}});if(a===null)continue;let i=Ko(a,n);if(i==="reused")return{refused:"reused"};if(i==="replay")return{kept:{status:a.status_code,headers:a.response_headers??[],body:a.response_body}};let[c]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:sn({seconds:Mr})}},set:{started_at:Ar()}});return c?{claim:{key:t,started:c.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!an(n.status))return n;let{response:r,kept:s}=await Nr(n),o=ee.getStore()?.database;if(!o)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let[a]=await o.$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(a?.answered!==!0)throw new wt;return r}async keep(t,n){let{response:r,kept:s}=await Nr(n);try{await this.asService(o=>o.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:Ar(),status_code:s.status,response_headers:s.headers,response_body:s.body}}))}catch(o){E.warn("[palbase] a refusal could not be kept against its Idempotency-Key; a retry runs it again once the key is stale",{error:o})}return r}async release(t){if(await this.releaseOnce(t))return;let n=Date.now()+Mr*1e3,r=()=>{Date.now()+jr>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},jr).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(Wo),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 Vo(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 yt=Symbol("waits");function Zo(e){return new Promise((t,n)=>{let r=setImmediate(()=>t(yt));e.then(s=>{clearImmediate(r),t(s)},s=>{clearImmediate(r),n(s)})})}async function Nr(e){let t=[];e.headers.forEach((i,c)=>{c!=="x-request-id"&&t.push([c,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=[],o=0;for(;;){let i=r.read(),c=await Zo(i);if(c!==yt&&c.done)break;if(c!==yt&&(s.push(c.value),o+=c.value.byteLength,o<=No))continue;let p=c===yt?i:void 0,y=new ReadableStream({start(k){for(let R of s)k.enqueue(R)},async pull(k){let R=await(p??r.read());p=void 0,R.done?k.close():k.enqueue(R.value)},cancel:k=>r.cancel(k)});return{response:n(y),kept:{status:e.status,headers:t.filter(([k])=>k!=="content-length"&&k!=="content-encoding"),body:null}}}let a=Buffer.concat(s);return{response:n(a),kept:{status:e.status,headers:t,body:a.byteLength===0?null:a.toString("base64")}}}import{createHash as Qo}from"node:crypto";var cn="/webhooks/palbase",Jr="PalbaseErrorEnvelope",qr="PalbaseBearer",Go={$ref:`#/components/schemas/${Jr}`},Yo={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"]},Hr={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Ne={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function Wr(e,t,n){let r={[Jr]:Yo},s={},o=[],a=[],i=new Set,c=new Map;for(let h of e){let v=a.find(V=>ta(V,h));if(v){o.push({route:h.id,handler:Br(h),answeredBy:v.id});continue}a.push(h);let b=h.segments.map(V=>typeof V=="string"?V:"{}").join("/");c.has(b)||c.set(b,ra(h.segments.flatMap(V=>typeof V=="string"?[]:[V.param])));let O=c.get(b),z=0,F=`/${h.segments.map(V=>typeof V=="string"?V:`{${O[z++]}}`).join("/")}`,D=t(h),j=kt(na(h),i),q=h.method!=="GET"&&h.method!=="HEAD",H=V=>{let Te=h.params.filter(me=>me.kind===V&&me.schema).map((me,He)=>Tt(me.schema,`${j}.${V}${He===0?"":`.${He+1}`}`,r));return Te.length===0?void 0:Te.length===1?Te[0]:{allOf:Te}},K=O.map(V=>({name:V,in:"path",required:!0,schema:{type:"string"}})),de=H("query");de&&K.push(...Kr(de,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:de}]);let ne=H("headers");ne&&K.push(...Kr(ne,"header")??[]);let st=n.idempotency===!0&&Ge(h);st&&K.push({...dn,schema:{...dn.schema}});let ze=q?H("body"):void 0,W={operationId:j};h.controller.name!==""&&(W.tags=[h.controller.name]),K.length>0&&(W.parameters=K),ze&&(W.requestBody={required:!da(ze),content:{"application/json":{schema:ze}}});let we=h.params.some(V=>V.schema!==void 0),$e=n.routes?.(h),qe=ua(j,$e?.throws??[],n.errors);W.responses={...ca($e,j,r),...pa(D,{validates:we,hasPathParams:O.length>0,readsBody:q,keyed:st}),...fa(qe,j,r)},qe.length>0&&(W["x-palbase-errors"]=la(j,qe)),D.auth.required&&(W.security=[{[qr]:[]}]),W["x-palbase-handler"]=Br(h);let xt=h.params.some(V=>V.kind==="optionalUser")||n.databaseSeesCaller;W["x-palbase-auth"]=D.auth.required?"required":xt?"optional":"public",W["x-palbase-verified-email"]=D.auth.verifiedEmail,W["x-palbase-rate-limit"]=D.limit===!1?!1:{max:D.limit.max,window:D.limit.window},h.meta.upload&&(W["x-palbase-upload"]={bucket:h.meta.upload.bucket,pathTemplate:h.meta.upload.pathTemplate}),(s[F]??={})[h.method.toLowerCase()]=W}for(let h of n.webhooks??[]){let v={operationId:kt(`webhooks.${h.name}`,i)};h.cls!==""&&(v.tags=[h.cls]),v.description=h.provider?`${Hr[h.provider]??h.provider}'s deliveries: verified with ${Hr[h.provider]??h.provider}'s signature scheme under the secret in ${h.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${h.signatureHeader} header: verified under the secret in ${h.secretEnv}, then handed to the @On of their event type.`,v.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":{},[h.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:G("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:G("in_progress: the same delivery is being handled; the sender delivers it again",Ne),413:G("payload_too_large: the body is over what this sender sends"),500:G("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:G("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",Ne)},v["x-palbase-webhook"]=h.provider?{provider:h.provider,secretEnv:h.secretEnv,events:h.events}:{signatureHeader:h.signatureHeader,secretEnv:h.secretEnv,events:h.events},s[`/webhooks/${h.name}`]={post:v}}let p=[...new Set(n.platformEvents??[])].sort();if(p.length>0){let h={operationId:kt("webhooks.palbase",i)};h.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.",h.responses={204:{description:"Taken: handled, or a delivery already run"},401:G("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:G("in_progress: the same event is being handled; the platform delivers it again",Ne),500:G("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:G("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let v=[...new Set(n.platformEventBuckets??[])].sort();h["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:p,...v.length>0?{buckets:v}:{}},s[cn]={post:h}}let y=Xo(n.rooms??[],r),k=Object.keys(y).length>0,R=n.channels??[],U=R.length>0,I={schemas:r,securitySchemes:{[qr]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},L={openapi:"3.2.0",info:{title:"Palbase backend",version:Qo("sha256").update(JSON.stringify({paths:s,components:I,unreachable:o,...k?{rooms:y}:{},...U?{channels:R}:{}})).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:I};return o.length>0&&(L["x-palbase-unreachable"]=o),k&&(L["x-palbase-room"]=y),U&&(L["x-palbase-channels"]=R.map(h=>({...h}))),L}function Xo(e,t){let n=[];for(let r of e){let s=r.pattern.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_|_$/g,""),o=(c,p,y,k)=>{let R=$t(`Room_${s}_${p}`),U={},I=Tt(y,R,U,k);I.$ref===void 0&&(U[R]=I),ea(r.pattern,c,p,U[R]);for(let[L,h]of Object.entries(U)){if(Object.hasOwn(t,L)&&JSON.stringify(t[L])!==JSON.stringify(h))throw new Error(`@Room("${r.pattern}") ${c} "${p}": its schema is the component ${L}, which another room's event or message names with another schema \u2014 rename one of them`);t[L]=h}return{$ref:`#/components/schemas/${R}`}},a=Object.fromEntries(Object.entries(r.events).map(([c,p])=>[c,o("event",c,p,"answered")])),i=Object.fromEntries(Object.entries(r.messages).map(([c,p])=>[c,o("message",c,p.schema,"sent")]));n.push([r.pattern,{events:a,messages:i,graceMs:r.graceMs}])}return Object.fromEntries(n)}function ea(e,t,n,r){if(!(!te(r)||!te(r.properties))){for(let[s,o]of Object.entries(r.properties))if(o===!0||te(o)&&Object.keys(o).length===0)throw new Error(t==="event"?`@Room("${e}") event "${n}" has an untyped field "${s}". An untyped payload makes every generated client opaque \u2014 declare its shape.`:`@Room("${e}") message "${n}" has an untyped field "${s}". Inbound payloads reach the server \u2014 declare the shape so it can be validated.`)}}function ta(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 Br(e){return`${e.controller.name}.${e.fn}`}function na(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 kt(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function ra(e){let t=new Set;return e.map(n=>kt(n,t))}function Tt(e,t,n,r="sent"){let s=e["~standard"],o=s.jsonSchema?.input;if(typeof o!="function")return{};let a;try{a=o({target:"draft-2020-12",libraryOptions:{unrepresentable:"any",...s.vendor==="zod"?{override:sa}:{}}})}catch{return{}}let i=$t(t);for(;Object.keys(n).some(c=>c===i||c.startsWith(`${i}.`));)i=`${i}_`;return oa(a,i,n,r)}function sa(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function oa(e,t,n,r){let s=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},o=!1,a=p=>p==="#"?(o=!0,`#/components/schemas/${t}`):p.startsWith("#/$defs/")?`#/components/schemas/${t}.${$t(ia(p.slice(8)))}`:p,i="all";if(r==="sent"){let p=new Set;for(let y of[e,...Object.values(s)])vt(y,p);i=p}for(let[p,y]of Object.entries(s))n[`${t}.${$t(p)}`]=Xe(Ye(y,a,i));let c=Xe(Ye(e,a,i));return o?(n[t]=c,{$ref:`#/components/schemas/${t}`}):c}var aa=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"]),un=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),ln=new Set(["anyOf","oneOf","allOf","prefixItems"]),fn=new Set(["properties","patternProperties","dependentSchemas"]),te=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ye(e,t,n){if(!te(e))return typeof e=="boolean"?e:{};let r={};for(let[s,o]of Object.entries(e))s==="$ref"&&typeof o=="string"?r.$ref=t(o):s==="const"?(n==="all"||n.has(e))&&(r.const=o):aa.has(s)?r[s]=o:un.has(s)?r[s]=Ye(o,t,n):ln.has(s)&&Array.isArray(o)?r[s]=o.map(a=>Ye(a,t,n)):fn.has(s)&&te(o)&&(r[s]=Object.fromEntries(Object.entries(o).map(([a,i])=>[a,Ye(i,t,n)])));return r}var Fr=Number.MAX_SAFE_INTEGER;function Xe(e){if(!te(e))return e;let t={};for(let[r,s]of Object.entries(e))un.has(r)?t[r]=Xe(s):ln.has(r)&&Array.isArray(s)?t[r]=s.map(Xe):fn.has(r)&&te(s)?t[r]=Object.fromEntries(Object.entries(s).map(([o,a])=>[o,Xe(a)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-Fr&&delete t.minimum,t.maximum===Fr&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,te(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(o=>te(o)&&Object.keys(o).length===1&&o.type==="null"),s=n[1-r];if(r!==-1&&te(s)&&typeof s.type=="string")return{...s,type:[s.type,"null"]}}return t}function vt(e,t){if(te(e)){for(let n of["anyOf","oneOf"]){let r=e[n];if(!Array.isArray(r)||r.length<2||!r.every(te))continue;if(r.every(o=>"const"in o||Array.isArray(o.enum)))for(let o of r)t.add(o);let s=r.map(o=>te(o.properties)?o.properties:{});for(let o of Object.keys(s[0]))if(s.every(a=>te(a[o])&&"const"in a[o]))for(let a of s)t.add(a[o])}for(let[n,r]of Object.entries(e))if(un.has(n))vt(r,t);else if(ln.has(n)&&Array.isArray(r))for(let s of r)vt(s,t);else if(fn.has(n)&&te(r))for(let s of Object.values(r))vt(s,t)}}function ia(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function $t(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function Kr(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 da(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function G(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:Go}}}}function ca(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=Tt(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function ua(e,t,n){let r=new Set,s=[];for(let o of t){if(r.has(o.code))continue;r.add(o.code);let a=n?.get(o.code);if(a&&o.status!==a.status)throw new Error(`${e} throws "${o.code}" with status ${o.status}, but the code is defined with status ${a.status} \u2014 a client matches an error by its code, so one code carries one status`);s.push({...o,...a?.data?{data:a.data}:{}})}return s}function la(e,t){let n=Object.create(null);for(let r of t){let s=r.name.charAt(0).toLowerCase()+r.name.slice(1),o=Object.hasOwn(n,s)?n[s]:void 0;if(o)throw new Error(`${e} throws "${o.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 fa(e,t,n){let r=new Map;for(let o of e)r.set(o.status,[...r.get(o.status)??[],o]);let s={};for(let o of[...r.keys()].sort((a,i)=>a-i)){let a=r.get(o),i=a.map(c=>{let p={error:{type:"string",const:c.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},y=["error","error_description","status","request_id"];return c.data&&(p.data=Tt(c.data,`${t}.${c.code}.data`,n,"answered"),y.push("data")),{type:"object",properties:p,required:y}});s[String(o)]={description:a.map(c=>c.code).join(" | "),content:{"application/json":{schema:i.length===1?i[0]:{oneOf:i}}}}}return s}function pa(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]=G(s.join("; "))),e.auth.required&&(n[401]=G("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]=G("email_not_verified: the user's email address is not verified")),t.keyed&&(n[409]=G("idempotency_key_in_use: a request with this Idempotency-Key is still running",Ne)),t.readsBody&&(n[413]=G("payload_too_large: the body is over the app's body limit")),t.keyed&&(n[422]=G("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(n[429]=G("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Ne)),n[500]=G("internal_error: the handler failed; the app's log has it under the request id"),n[503]=G(`${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":""}`,Ne),n}var Et=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 Rt(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return ma(r??t??"unknown")}function ma(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("::"),o=r?r.split(":"):[],a=s?s.split(":"):[],i=t.includes("::")?[...o,...Array(8-o.length-a.length).fill("0"),...a]:o;return i.length!==8||i.some(c=>!/^[0-9a-f]{1,4}$/i.test(c))?t:`${i.slice(0,4).map(c=>parseInt(c,16).toString(16)).join(":")}::/64`}function Vr(e){let t=[];for(let n of e){let r=M(n,_e),s=M(n,Se)??[];if(s.length===0)throw new TypeError(`@Controller ${n.name} has no routes: a controller with nothing to serve is a mistake`);let o=M(n,Mt)??new Map;for(let a of s){let i=`${r.basePath}${a.subpath}`||"/",c=i.split("/").filter(Boolean).map(y=>{let k=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(y)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(y);return k?{param:k[1]}:y});if(typeof c[0]=="string"&&xe.has(c[0]))throw new TypeError(`${n.name}.${a.fn}: ${a.method} ${i} \u2014 /${c[0]} is the platform's; a route is served elsewhere`);let p=[...o.get(a.fn)??[]].sort((y,k)=>y.index-k.index);for(let y of p)if(y.kind==="param"&&!c.some(k=>typeof k!="string"&&k.param===y.name))throw new TypeError(`${n.name}.${a.fn}: @Param("${y.name}") names no {${y.name}} in ${a.method} ${i}`);t.push({id:`${a.method} ${i}`,method:a.method,segments:c,controller:n,fn:a.fn,params:p,meta:a,controllerAuth:r.options.auth})}}return ar(t),t}function pn(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 o={},a=!0;for(let i=0;i<r.length&&a;i++){let c=s.segments[i];if(typeof c=="string")a=c===r[i];else try{o[c.param]=decodeURIComponent(r[i])}catch{return{malformed:!0}}}if(a)return{route:s,params:o}}return null}function gn(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Ue(e,t,n,r,s){return _t(e,e?gn(e.requests,t):void 0,n,r,s)}var mn={role:"service",claims:{}};async function _t(e,t,n,r,s){if(!e||!t)return s();let o=p=>E.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}),a=e.app.request(t,{signal:n,heldIdle:o}),i=ee.getStore();i&&(i.database=a.database);let c;try{c=await s()}catch(p){throw await a.rollback(p).catch(y=>E.error("[palbase] the request's transaction could not be rolled back",{error:y})),p}try{await a.commit()}catch(p){throw await a.rollback(p).catch(y=>E.error("[palbase] the request's transaction could not be rolled back",{error:y})),p}return c}var ga=1024*1024,ya=20,wa={max:300,window:60},Le="/_palbase/crons",Ie="/_palbase/tasks",Zr=50,Qr=50,ba=4096,ka=69632,Gr=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,tt=1e4,va=6e4;function $a(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 X=class extends Error{constructor(n,r,s,o,a,i){super(s);this.status=n;this.code=r;this.data=o;this.retryAfter=a;this.challenge=i}status;code;data;retryAfter;challenge};function Ta(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 Ea=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function Ra(e,t){let n=new Headers(e.headers);for(let r of Ea)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 Yr(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),St(e.headers,"Accept-Language")),e}function St(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 ue(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),ue(e.status,n,t,r)}var ss=new Set([0,429,502,503,504]);function Xr(e,t,n,r){if(r?.aborted)return E.info(`[palbase] ${n}: the client left before its answer`),$({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof X)return $({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(Qe(e)){let o=e;return o.status>=500&&E.error(`[palbase] ${n} answered ${o.status} ${o.error}`,{error:e}),ue(o.status,Er(o,t),t,o.retryAfter!==void 0?{"retry-after":String(o.retryAfter)}:{})}let s=Ot(e,n);return s?$(s,t):(e instanceof ie?E.error(`[palbase] ${n}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):E.error(`[palbase] unhandled error in ${n}`,{error:e}),$({status:500,code:"internal_error",message:"The request could not be completed"},t))}function Ot(e,t){if(e instanceof it)return E.warn(`[palbase] ${t}: sign-ins cannot be checked (${e.message})`,{error:e}),{status:503,code:"auth_unavailable",message:"Sign-ins cannot be checked right now; try again shortly",retryAfter:1};if(e instanceof ie&&ss.has(e.status))return E.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=ns(e);if(n!==void 0)return E.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 _a(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return Or(e)?t(e.message):Qe(e)&&!bn(e)&&!yn(e)?t(e.errorDescription):yn(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function yn(e){return e instanceof it||e instanceof ie&&ss.has(e.status)||ns(e)!==void 0||Qe(e)&&e.status===503&&bn(e)}async function hn(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,ya).map(a=>({field:(a.path??[]).map(i=>String(typeof i=="object"&&i!==null&&"key"in i?i.key:i)).join("."),message:a.message})),o=r.issues.length-s.length;throw new X(400,"bad_request",`${n} failed validation`,o>0?{fields:s,more:o}:{fields:s})}return r.value}async function nt(e,t){let n=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(n)&&n>t)throw new X(413,"payload_too_large",`Request body exceeds ${t} bytes`);if(!e.body)return new Uint8Array(0);let r=e.body.getReader(),s=[],o=0;for(;;){let{done:c,value:p}=await r.read();if(c)break;if(o+=p.byteLength,o>t)throw await r.cancel().catch(()=>{}),new X(413,"payload_too_large",`Request body exceeds ${t} bytes`);s.push(p)}let a=new Uint8Array(o),i=0;for(let c of s)a.set(c,i),i+=c.byteLength;return a}function Sa(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return ae(t)}function Oa(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 xa(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 Aa=/^[A-Za-z0-9._:-]{8,128}$/,Pa=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Ca={max:20,window:60},Ma=10*6e4,Da=1e4,rt=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},wn=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=rs("sha256").update(t).digest("hex"),o=(this.known.get(s)??0)>this.now(),a=`token-misses\0a:${n}`,i;if(!o){let p=this.limiter.reserve(a,Ca);if("wait"in p)throw new rt(p.wait);i=p}let c=await r();if(!c)throw this.known.delete(s),new at("unknown_token","The token is not one of the app's");return i&&this.limiter.give(a,i.window),this.known.delete(s),this.known.set(s,this.now()+Ma),this.known.size>Da&&this.known.delete(this.known.keys().next().value),c}};function Yd(e){let t=new mt(e.modules),n=Vr(t.controllers.map(d=>d.cls)),r=new Map(n.map(d=>[d,$a(d,e.auth)]));for(let[d,u]of r){if(!u.required&&d.params.some(f=>f.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&&u.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 u of d.params)u.kind==="resolve"&&s.set(u,t.dependencyOf(d.controller,u.resolver,`${d.id} @Resolve(${u.resolver?.name})`));let o=new Map;for(let d of t.cronProviders){let u=t.get(d),f=M(d,he),l=o.get(f.name);if(l)throw new TypeError(`@Cron "${f.name}" is ${l.owner} and ${d.name}: a cron's name is its own \u2014 name one of them`);o.set(f.name,{declaration:f,owner:d.name,run:g=>u.run(g)})}let a=new Map;for(let d of t.taskProviders){let u=t.get(d),f=M(d,fe),l=a.get(f.name);if(l)throw new TypeError(`@Task "${f.name}" is ${l.owner} and ${d.name}: a task type's name is its own \u2014 name one of them`);a.set(f.name,{declaration:f,owner:d.name,run:(g,m)=>u.run(g,m)})}let i=new Set,c=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(o.size>Zr)throw new TypeError(`${o.size} @Cron classes: a machine runs ${Zr} crons at most`);if(a.size>Qr)throw new TypeError(`${a.size} @Task classes: a machine runs ${Qr} task types at most`);o.size>0&&!e.platform&&E.info(`[palbase] ${o.size} @Cron(s): the platform runs them on a machine; nothing calls them here`);let p=e.channels??er(),y=nr(p,t.rooms.map(d=>Qt(d)));if(y)throw new TypeError(y);let k=Yn([...t.rooms.map(d=>({cls:d,instance:t.get(d)})),...tr(p)],{run:(d,u,f,l)=>ee.run({requestId:ee.getStore()?.requestId??"",...d?.id?{userId:d.id}:{}},()=>_t(e.database,e.database?d?.id?gn(e.database.requests,ft(d)):mn:void 0,f,u,async()=>{let g=await l();if(f?.aborted)throw new Error(`realtime gave up on ${u} before it ended`);return g})),broadcast:d=>e.server.realtime.broadcast({body:{messages:d}}),isOutage:yn});k.declarations.length>0&&!e.platform&&E.info(`[palbase] ${k.declarations.length} @Room(s): realtime tells a machine of them; nothing does here`);let R=xr();(R.tools.size>0||R.agents.size>0)&&!e.platform&&E.info(`[palbase] ${R.tools.size} ai.tool(s) and ${R.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let U=new gt,I=new ht(e.now??Date.now),L=new Set,h=e.database!==void 0||e.contractOnly?.database===!0;if(h){for(let d of n)if(Ge(d)&&d.params.some(u=>u.kind==="headers"&&u.schema!==void 0&&zr(u.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 v=e.database?new bt(e.database.app):void 0,b=qa(e.cors),O=e.now??Date.now,z=new Et(e.now),F=new wn(z,e.now??Date.now),D=e.maxBodyBytes??ga,j=d=>{let u=d.meta.options.rateLimit??e.rateLimit??wa;return u!==!1&&u.max>0&&u.window>0?u:!1},q=e.env??process.env,H=pr(t.webhooks,d=>t.get(d),q,{secrets:e.contractOnly===void 0}),K=H.size===0&&o.size===0&&a.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(q).filter(d=>typeof d[1]=="string"&&!Nn(d[0])))),de=new Map([...H.keys()].map(d=>[d,{seen:new Set,inflight:new Set}])),ne=new Map([...H.keys()].map(d=>[d,{counts:new Map,at:void 0}])),st,ze=()=>st??=Wr(n,d=>({auth:r.get(d),limit:j(d)}),{databaseSeesCaller:h,idempotency:h,webhooks:[...H.values()].map(d=>({name:d.name,cls:d.cls.name,provider:d.provider,signatureHeader:d.signatureHeader,secretEnv:d.secretEnv,events:[...d.events.keys()]})),platformEvents:[...W.keys()],rooms:k.declarations,channels:p.rows,platformEventBuckets:Na(W),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),W=new Map;for(let[d,u]of Object.entries(e.events??{}))W.set(d,u.map(f=>({name:`palbase(${d})`,call:l=>f(l)})));for(let d of t.eventProviders){let u=t.get(d);for(let{event:f,fn:l,bucket:g}of M(d,be)??[]){if(!Bn.test(f))throw new TypeError(`@On("${f}") on ${d.name}.${l}: 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`);W.has(f)||W.set(f,[]),W.get(f).push({name:`${d.name}.${l}`,bucket:g,call:async(m,w)=>u[l](m,w)})}}let we=new Set,$e=new Set;Un(e.server),Kn(e.platform?Jn(q.PALBASE_MACHINE):new lt(new Map([...a].map(([d,u])=>[d,u.declaration])),(d,u)=>Tn(d,u),e.now));async function qe(d,u){let f;try{f=await Dn(d,e.webhookSecret,{now:e.now})}catch(l){if(l instanceof Ke)return $({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${l.code}`},u);throw l}if(ae(f.data),we.has(f.id))return new Response(null,{status:204,headers:{"x-request-id":u}});if($e.has(f.id))return $({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},u);$e.add(f.id);try{let l;try{await Ue(e.database,null,void 0,`event ${f.type}`,async()=>{for(let g of W.get(f.type)??[])if(!(g.bucket!==void 0&&ja(f)!==g.bucket))try{await g.call(f,{requestId:u})}catch(m){throw l=g.name,m}})}catch(g){return E.error(`[palbase] ${l??"the delivery"} failed on ${f.type} ${f.id}; the platform delivers it again`,{error:g}),$({status:500,code:"handler_failed",message:"The event could not be handled"},u)}return we.add(f.id),we.size>tt&&we.delete(we.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}})}finally{$e.delete(f.id)}}async function xt(d,u={}){let f=d.headers.get("origin");if(b&&f!==null){let l=b.allows(f);if(d.method==="OPTIONS"&&d.headers.has("access-control-request-method"))return l?new Response(null,{status:204,headers:b.preflight(f,d.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let g=await Sn(d,u);if(l)for(let[m,w]of Object.entries(b.headers(f)))m==="vary"?St(g.headers,w):g.headers.set(m,w);else St(g.headers,"Origin");return g}return Sn(d,u)}async function V(d,u,f,l){if(!d.headers.get(f.scheme.header))return me(f,"missing_signature",l);let g={headers:d.headers,body:await nt(d,f.scheme.maxBytes(D)),url:mr(d,u)},m;try{m=f.scheme.check(g,O()/1e3)}catch{return me(f,"signature_mismatch",l,"check_failed")}if(typeof m=="string")return me(f,m,l);let w=f.events.get(m.type);if(!w)return E.info(`[palbase] webhook ${f.name}: no @On takes "${m.type}"; acknowledged`),ue(200,{ok:!0,handled:!1},l);let T=de.get(f.name),_=m.event,C=[];if(m.id!==void 0){if(T.seen.has(m.id))return ue(200,{ok:!0,handled:!1,duplicate:!0},l);C=[m.id]}else if(m.ids&&Array.isArray(_)){let S=m.ids,x=_.map((P,Q)=>[P,S[Q]]).filter(([,P])=>P===void 0||!T.seen.has(P));if(x.length===0)return ue(200,{ok:!0,handled:!1,duplicate:!0},l);_=x.map(([P])=>P),C=x.flatMap(([,P])=>P===void 0?[]:[P])}if(C.some(S=>T.inflight.has(S)))return $({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},l);ae(_);for(let S of C)T.inflight.add(S);let A;try{A=await Ue(e.database,null,void 0,`webhook ${f.name}`,()=>w.call(_,{env:K,requestId:l,environmentId:e.projectId??""}))}catch(S){let x=Ot(S,`webhook ${f.name}`)??Ua(S,f.name);return x?$(x,l):(E.error(`[palbase] ${w.name} failed on ${f.name} "${m.type}"; the sender delivers it again`,{error:S}),$({status:500,code:"handler_failed",message:"The event could not be handled"},l))}finally{for(let S of C)T.inflight.delete(S)}for(let S of C)T.seen.add(S),T.seen.size>tt&&T.seen.delete(T.seen.values().next().value);return Te(A,f,l)}function Te(d,u,f){if(d instanceof Response)return d;if(typeof d=="string"){let l=u.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(d,{status:200,headers:{"content-type":l,"x-request-id":f}})}return ue(200,d??{ok:!0,handled:!0},f)}function me(d,u,f,l=u){let g=ne.get(d.name);g.counts.set(l,(g.counts.get(l)??0)+1);let m=O();return(g.at===void 0||m-g.at>=va)&&(He(d.name),g.at=m),$({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${u}`},f)}function He(d){let u=ne.get(d).counts;if(u.size===0)return;let f=[...u.values()].reduce((l,g)=>l+g,0);E.warn(`[palbase] webhook ${d}: ${f} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(u)}),u.clear()}function is(d){let u=d.split("/").filter(Boolean);return u.length===2&&u[0]==="webhooks"?H.get(u[1]):void 0}async function ds(d,u,f,l){let g=u.pathname===Le;if(d.method!==(g?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:g?"The crons are listed with GET":"A cron is run with POST"},l);let m=g?new Uint8Array(0):await nt(d,ba);try{await ot({secret:f,signature:d.headers.get("palbase-signature"),body:m,now:e.now})}catch(Z){if(Z instanceof Ke)return $({status:401,code:"invalid_signature",message:`The crons are the platform's to call: ${Z.code}`},l);throw Z}if(g){let Z=[...o.values()].map(({declaration:B})=>({name:B.name,schedule:B.schedule,time_zone:B.timeZone,timeout:B.timeout,retry:B.retries}));return ue(200,{crons:Z},l,{"cache-control":"no-store"})}let w=u.pathname.slice(Le.length+1),T=o.get(w);if(!T)return $({status:404,code:"cron_not_found",message:`This version has no cron ${JSON.stringify(w)}`},l);let _;try{_=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}"},l)}let{cron:C,run_id:A,scheduled_at:S,attempt:x}=_??{};if(C!==w||typeof A!="string"||A===""||typeof S!="string"||!Gr.test(S)||Number.isNaN(Date.parse(S))||!Number.isInteger(x)||x<1)return $({status:400,code:"bad_request",message:`A run of ${w} is the JSON {cron: "${w}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},l);let P=`${A}#${String(x)}`;if(i.has(P))return new Response(null,{status:204,headers:{"x-request-id":l}});if(c.has(P))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},l);c.add(P);let Q={env:K,environmentId:e.projectId??"",cron:w,runId:A,scheduledAt:new Date(S),attempt:x};try{await _t(e.database,e.database?mn:void 0,d.signal,`cron ${w}`,async()=>{if(await T.run(Q),d.signal.aborted)throw new Error(`the platform gave up on this attempt of ${w} before it ended`)})}catch(Z){return d.signal.aborted||E.error(`[palbase] cron ${w} failed (run ${A}, attempt ${String(x)})`,{error:Z}),$({status:500,code:"cron_failed",message:`The cron ${w} failed; the platform tries it again`},l)}finally{c.delete(P)}return i.add(P),i.size>tt&&i.delete(i.values().next().value),new Response(null,{status:204,headers:{"x-request-id":l}})}let Tn=async({task:d,id:u,attempt:f,payload:l,createdAt:g},m)=>{let w=a.get(d);if(!w)return{status:404,message:`this version has no task ${JSON.stringify(d)}`};let T=ae(l??null),_=w.declaration.payload;if(_){let A=await _["~standard"].validate(T);if(A.issues){let S=A.issues.slice(0,5).map(x=>`${(x.path??[]).map(P=>String(typeof P=="object"&&P!==null&&"key"in P?P.key:P)).join(".")||"(payload)"}: ${x.message}`).join("; ");return E.error(`[palbase] task ${d} ${u}: what it carries is not what it takes \u2014 it fails, not to be tried again: ${S}`),{status:422,message:`what it carries is not what @Task "${d}" takes: ${S}`}}T=A.value}let C={env:K,environmentId:e.projectId??"",task:d,id:u,attempt:f,createdAt:g};try{await _t(e.database,e.database?mn:void 0,m,`task ${d}`,async()=>{if(await w.run(T,C),m.aborted)throw new Error(`the platform gave up on this attempt of ${d} before it ended`)})}catch(A){return A instanceof ut?(E.error(`[palbase] task ${d} ${u} can never be done: ${A.message}`),{status:422,message:A.message}):(m.aborted||E.error(`[palbase] task ${d} failed (task ${u}, attempt ${String(f)})`,{error:A}),{status:500,message:`the task ${d} failed; it is tried again`})}return{status:204}};async function cs(d,u,f,l){let g=u.pathname===Ie;if(d.method!==(g?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:g?"The task types are listed with GET":"A task is run with POST"},l);let m=g?new Uint8Array(0):await nt(d,ka);try{await ot({secret:f,signature:d.headers.get("palbase-signature"),body:m,now:e.now})}catch(Z){if(Z instanceof Ke)return $({status:401,code:"invalid_signature",message:`The tasks are the platform's to call: ${Z.code}`},l);throw Z}if(g){let Z=[...a.values()].map(({declaration:B})=>({name:B.name,timeout:B.timeout,retry:B.retries,concurrency:B.concurrency}));return ue(200,{tasks:Z},l,{"cache-control":"no-store"})}let w=u.pathname.slice(Ie.length+1),T;try{T=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}"},l)}let{task:_,id:C,attempt:A,payload:S,created_at:x}=T??{};if(_!==w||typeof C!="string"||C===""||typeof x!="string"||!Gr.test(x)||Number.isNaN(Date.parse(x))||!Number.isInteger(A)||A<1)return $({status:400,code:"bad_request",message:`A task of ${w} is the JSON {task: "${w}", id, attempt (1 or more), payload, created_at (RFC 3339)}`},l);let P=`task:${C}#${String(A)}`;if(i.has(P))return new Response(null,{status:204,headers:{"x-request-id":l}});if(c.has(P))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},l);c.add(P);let Q;try{Q=await Tn({task:w,id:C,attempt:A,payload:S,createdAt:new Date(x)},d.signal)}finally{c.delete(P)}return Q.status===404?$({status:404,code:"task_not_found",message:Q.message??""},l):Q.status===422?$({status:422,code:"task_failure",message:Q.message??""},l):Q.status>=300?$({status:Q.status,code:"task_failed",message:Q.message??""},l):(i.add(P),i.size>tt&&i.delete(i.values().next().value),new Response(null,{status:204,headers:{"x-request-id":l}}))}async function Be(d,u,f,l){if(d.method!=="POST")return $({status:405,code:"method_not_allowed",message:`${l} is POSTed`},f);let g;try{Mn({signature:d.headers.get("palbase-signature"),now:e.now}),g=await nt(d,1048576),await ot({secret:u,signature:d.headers.get("palbase-signature"),body:g,now:e.now})}catch(w){if(w instanceof Ke)return $({status:401,code:"invalid_signature",message:`${l} is the platform's to call: ${w.code}`},f);throw w}let m;try{m=JSON.parse(new TextDecoder().decode(g))}catch{return $({status:400,code:"bad_request",message:`${l} is JSON`},f)}return typeof m!="object"||m===null||!Object.hasOwn(m,"call")||m.call!==new URL(d.url).pathname?$({status:401,code:"invalid_signature",message:`${l} is the platform's to call: signed_for_another_call`},f):{body:m}}async function us(d,u,f,l,g){let m=await Be(u,f,l,`An upload's ${d}`);if(m instanceof Response)return m;let w=ir(d,m.body);if(typeof w=="string")return $({status:400,code:"bad_request",message:`An upload's ${d}: ${w}`},l);if(d==="complete"){if(L.has(w.uploadId))return $({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},l);L.add(w.uploadId),L.size>tt&&L.delete(L.values().next().value)}let T=pn(n,w.method,w.route);if(!T||"malformed"in T||!T.route.meta.upload)return $({status:404,code:"not_found",message:`No upload route for ${w.method} ${w.route}`},l);let{route:_,params:C}=T,A=T.route.meta.upload,S=xa(w.user);if(S&&On(g,S.id),r.get(_).required&&!S)throw new X(401,"unauthorized","This route needs a signed-in user");if(d==="authorize"){let Q=j(_);if(Q!==!1){let B=z.take(`${_.id}\0${Zn(w.user,w.client)}`,Q);if(B!==void 0)throw new X(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:B},B)}let Z=or(A.pathTemplate,{userId:S?.id??null,uploadId:w.uploadId,filename:w.filename});if("problem"in Z)throw new X(400,"bad_request",Z.problem);return await Ue(e.database,ft(w.user),u.signal,_.id,async()=>{let B={request:u,query:new URLSearchParams(w.query),params:C,user:S,body:w.body===void 0||w.body===null?{}:ae(w.body),requestId:l};await _n(_,B);for(let Ee of _.params)(Ee.kind==="query"||Ee.kind==="body"&&w.body!==void 0)&&await ts(Ee,B)}),ue(200,{bucket:A.bucket,path:Z.path},l)}g.endpoint=_.id.slice(_.id.indexOf(" ")+1);let x=new URLSearchParams(w.query),P=w.body===null||w.body===void 0?{}:ae(w.body);return At(_,{request:u,query:x,params:C,user:S,body:P,requestId:l,uploadedObject:ae(w.uploadedObject)},ft(w.user))}function En(d,u,f,l){let g=d?{sub:d.id,role:"authenticated"}:null;return ee.run({requestId:ee.getStore()?.requestId??"",...d?{userId:d.id}:{}},()=>Ue(e.database,g,f,u,async()=>{let m=await l();if(f.aborted)throw new Error(`the platform gave up on ${u} before it ended`);return m}))}let Rn=(d,u)=>new Response(d,{status:200,headers:{"content-type":"application/json","x-request-id":u}});async function ls(d,u,f){let l=await Be(d,u,f,"A tool call");if(l instanceof Response)return l;let g=l.body,m=g.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"},f);let w=R.tools.get(m);if(!w)return $({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(m.slice(0,64))}`},f);let T=g.call_id,_=rn(g.context);if(typeof T!="string"||T===""||T.length>256||typeof _=="string")return $({status:400,code:"bad_request",message:`A call of ${m} is {tool, call_id, input, context}${typeof _=="string"?`: ${_}`:""}`},f);let C=rs("sha256").update(JSON.stringify(g)).digest("hex"),A=U.answered(T);if(A!==void 0)return A.digest!==C?$({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},f):Rn(A.answer,f);if(U.isRunning(T))return $({status:409,code:"in_progress",message:"This call is running",retryAfter:2},f);U.start(T);let S;try{let x=await En(_.user,`ai.tool ${m}`,d.signal,()=>w.call(ae(g.input??{}),{..._,callId:T,signal:d.signal}));S=JSON.stringify({output:x.output,is_error:x.is_error});let P=new TextEncoder().encode(S).byteLength;P>4194304&&(E.error(`[palbase] ai.tool ${m} answered ${P} bytes (call ${T}): a machine's answer is ${4194304} at most; the agent is told it failed`),S=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${4194304/(1<<20)} MiB it may be`}],is_error:!0}))}catch(x){if(d.signal.aborted)return U.end(T,void 0),$({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);E.error(`[palbase] ai.tool ${m} failed (call ${T}, chat ${_.chatId}); the agent is told`,{error:x}),S=JSON.stringify({output:[{type:"text",text:_a(x)}],is_error:!0})}return U.end(T,{digest:C,answer:S}),Rn(S,f)}async function fs(d,u,f){let l=await Be(d,u,f,"An agent's turn");if(l instanceof Response)return l;let g=rn(l.body);if(typeof g=="string"||g.agent==="")return $({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata}${typeof g=="string"?`: ${g}`:": agent names it"}`},f);let m=g.agent,w=R.agents.get(m);if(!w)return $({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(m.slice(0,64))}`},f);let T;try{T=await En(g.user,`ai.agent ${m}`,d.signal,()=>w.resolve({...g,signal:d.signal}))}catch(A){if(d.signal.aborted)return $({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let S=Ot(A,`ai.agent ${m}`);return S?$(S,f):(E.error(`[palbase] ai.agent ${m} failed for chat ${g.chatId}; the turn is not started`,{error:A}),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},f))}let _=T.tools.find(A=>R.tools.get(A.name)!==A);if(_)return E.error(`[palbase] ai.agent ${m} handed out ai.tool ${JSON.stringify(_.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`},f);let C=JSON.stringify(T.definition);return new TextEncoder().encode(C).byteLength>4194304?(E.error(`[palbase] ai.agent ${m}'s definition is larger than the ${4194304} bytes a machine's answer may be`),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},f)):new Response(C,{status:200,headers:{"content-type":"application/json","x-request-id":f,"cache-control":"no-store"}})}async function ps(d,u,f){let l=await Be(d,u,f,"A repository's token");if(l instanceof Response)return l;let g=l.body;if(typeof g.repo!="string"||g.repo===""||typeof g.repository!="string"||typeof g.call_id!="string"||g.call_id===""||g.call_id.length>256)return $({status:400,code:"bad_request",message:"A repository's token is asked as {call_id, repo, repository}"},f);if(!I.take(g.call_id))return $({status:409,code:"call_id_reused",message:"This token ask was answered already"},f);let m=R.repos.get(g.repo);if(!m)return $({status:404,code:"repo_not_found",message:`This version has no ai.repo ${JSON.stringify(g.repo.slice(0,64))}`},f);let w;try{w=await m.token({repo:g.repo,repository:g.repository,signal:d.signal})}catch(T){if(d.signal.aborted)return $({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let _=Ot(T,`ai.repo ${g.repo}`);return _?$(_,f):(E.error(`[palbase] ai.repo ${g.repo} gave no token; the workspace's clone or push is refused`,{error:T}),$({status:500,code:"token_failed",message:`The repository ${g.repo} gave no token`},f))}return typeof w!="string"||w.trim()===""?(E.error(`[palbase] ai.repo ${g.repo}'s token function answered no token`),$({status:500,code:"token_failed",message:`The repository ${g.repo} gave no token`},f)):new Response(JSON.stringify({token:w}),{status:200,headers:{"content-type":"application/json","x-request-id":f,"cache-control":"no-store"}})}async function ms(d,u,f,l){let g=await Be(u,f,l,`A room's ${d}`);if(g instanceof Response)return g;let m=await k.serve(d,g.body,u.signal);return"code"in m?$({status:m.status,code:m.code,message:m.message,retryAfter:m.retryAfter},l):"body"in m?ue(200,m.body,l):new Response(null,{status:204,headers:{"x-request-id":l}})}async function _n(d,u){let f=[],l={params:Object.freeze({...u.params}),user:ae(u.user),headers:d.meta.upload?new Headers:u.request.headers,requestId:u.requestId};for(let g of d.params)g.kind==="resolve"&&(f[g.index]=await s.get(g).resolve(l,g.options));return f}async function At(d,u,f,l){let g=t.get(d.controller),m=await Ue(e.database,f,u.request.signal,d.id,async()=>{let w=await _n(d,u);for(let _ of d.params)_.kind!=="resolve"&&(w[_.index]=await ts(_,u));l?.ran();let T=await g[d.fn](...w);if(u.uploadedObject&&u.request.signal.aborted)throw new Error(`storage gave up on ${d.id}'s upload before it was answered`);return l?l.record(Yr(es(T,u.requestId),ee.getStore()?.usedLocales)):T});return l?m:Yr(es(m,u.requestId),ee.getStore()?.usedLocales)}async function Sn(d,u){let f=d.headers.get("x-request-id")??"",l=Aa.test(f)?f:`req_${crypto.randomUUID()}`,g=performance.now(),m=new URL(d.url).pathname,w={endpoint:m},T=await hs(d,u,l,w);return e.telemetry?.record({requestId:l,method:d.method,endpoint:w.endpoint,path:m,status:T.status,durationMs:performance.now()-g,userId:w.userId}),T}function On(d,u){d.userId=u;let f=ee.getStore();f&&(f.userId=u)}async function hs(d,u,f,l){let g=e.strings,m=g?{requestId:f,strings:g,locales:Ln(d.headers.get("accept-language"),g.source),usedLocales:[]}:{requestId:f},w=await gs(m,d,u,f,l);return g&&St(w.headers,"Accept-Language"),w}async function gs(d,u,f,l,g){return ee.run(d,async()=>{let m=new URL(u.url),w=`${u.method} ${m.pathname}`;try{if(m.pathname===cn&&W.size>0)return u.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},l):e.webhookSecret?await qe(u,l):$({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},l);let T=is(m.pathname);if(T)return w=`webhook ${T.name}`,u.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},l):await V(u,m,T,l);if(e.platform&&(m.pathname===Le||m.pathname.startsWith(`${Le}/`)))return w=m.pathname===Le?"crons":`cron ${m.pathname.slice(Le.length+1)}`,await ds(u,m,e.platform.secret,l);if(e.platform&&(m.pathname===Ie||m.pathname.startsWith(`${Ie}/`)))return w=m.pathname===Ie?"tasks":`task ${m.pathname.slice(Ie.length+1)}`,await cs(u,m,e.platform.secret,l);if(e.platform&&(m.pathname===Ht||m.pathname===Wn)){let N=m.pathname===Ht?"authorize":"complete";return w=`upload ${N}`,await us(N,u,e.platform.secret,l,g)}if(e.platform&&m.pathname.startsWith(`${Bt}/`)){let N=m.pathname.slice(Bt.length+1);return w=`room ${N}`,await ms(N,u,e.platform.secret,l)}if(e.platform&&m.pathname===Rr)return w="ai tool call",await ls(u,e.platform.secret,l);if(e.platform&&m.pathname===_r)return w="ai agent's turn",await fs(u,e.platform.secret,l);if(e.platform&&m.pathname===Sr)return w="ai repository's token",await ps(u,e.platform.secret,l);if(La(m.pathname))return $({status:404,code:"not_found",message:`No route for ${u.method} ${m.pathname}`},l);let _=pn(n,u.method,m.pathname);if(_&&"malformed"in _)return $({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},l);if(!_)return $({status:404,code:"not_found",message:`No route for ${u.method} ${m.pathname}`},l);let{route:C,params:A}=_;if(w=C.id,g.endpoint=C.id.slice(C.id.indexOf(" ")+1),C.meta.upload)throw new X(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 S=r.get(C),x=null,P=null,Q=u.headers.get("authorization")??"",Z=/^(bearer|dpop)\s+(\S+)$/i.exec(Q),B=Z?.[2],Ee=Z?.[1].toLowerCase()==="dpop";if(B)try{let N=!Ee&&e.tokens&&!Pa.test(B)&&e.tokens.accepts(B)?e.tokens:void 0,Re=N?await F.ask(B,Rt(u.headers,f.remoteAddress),()=>Ue(e.database,null,u.signal,"token",()=>N.resolve(B))):await e.verifier.verify(B,Ee?{proof:u.headers.get("dpop"),method:u.method,url:jn(u.headers,m)}:void 0);x=Oa(Re),P=Re.claims}catch(N){if(!S.required&&(N instanceof at||N instanceof it||N instanceof rt))x=null;else throw N instanceof rt?new X(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:N.wait},N.wait):N instanceof at?new X(401,"invalid_token","The access token is not valid",{reason:N.reason},void 0,Ta(N.reason)):N}else if(Q!==""&&S.required)throw new X(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(x&&On(g,x.id),S.required&&!x)throw new X(401,"unauthorized","This route needs a signed-in user");if(S.verifiedEmail&&!x?.emailVerified)throw new X(403,"email_not_verified","This route needs a verified email address");let xn=j(C);if(xn!==!1){let N=x?`u:${x.id}`:`a:${Rt(u.headers,f.remoteAddress)}`,Re=z.take(`${C.id}\0${N}`,xn);if(Re!==void 0)throw new X(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:Re},Re)}let Fe=u.method==="GET"||u.method==="HEAD"?void 0:await nt(u,D),ys=Fe===void 0?void 0:Sa(Fe),An={request:u,query:m.searchParams,params:A,user:x,body:ys,raw:Fe,requestId:l},Pn=v&&Fe!==void 0&&Ge(C)?Lr(u.method,u.headers):void 0;if(!v||Pn===void 0)return await At(C,An,P);let ws={role:gn(e.database.requests,P).role,uid:x?.id??`a:${Rt(u.headers,f.remoteAddress)}`},Cn=!1;return await v.serve({key:Pn,caller:ws,method:u.method,uri:`${m.pathname}${m.search}`,body:Fe},N=>At(C,An,P,{record:N,ran:()=>{Cn=!0}}),{requestId:l,refusal:N=>$(N,l),failure:N=>Xr(N,l,w,u.signal),ran:()=>Cn})}catch(T){return Xr(T,l,w,u.signal)}})}return{handle:xt,routes:n.map(d=>d.id),contract:ze,start:()=>t.start(),stop:async()=>{k.close();for(let d of ne.keys())He(d);await t.shutdown(),await e.telemetry?.flush()}}}function ja(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function Na(e){let t=new Set;for(let[n,r]of e)if(Ut(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 es(e,t){return e instanceof Response?Ra(e,t):e==null?new Response(null,{status:204,headers:{"x-request-id":t}}):ue(200,e,t)}function Ua(e,t){if(!(!Qe(e)||e.status!==503||!bn(e)))return E.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 La(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return xe.has(decodeURIComponent(t))}catch{return xe.has(t)}}var Ia="GET, POST, PUT, PATCH, DELETE, QUERY",za=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function qa(e){if(!e)return;if(e.origins!=="*"){for(let r of e.origins)if(!za.test(r)||r.startsWith("http://")&&!/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(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":Ia,"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 ts(e,t){switch(e.kind){case"body":return hn(e.schema,t.body??{},"Request body");case"query":return hn(e.schema,ae(Object.fromEntries(t.query)),"Query parameters");case"headers":{let n={};return t.request.headers.forEach((r,s)=>n[s.toLowerCase()]=r),ae(n),e.schema?hn(e.schema,n,"Request headers"):n}case"param":return t.params[e.name];case"user":case"optionalUser":return ae(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 ae({sdkVersion:n.get("x-palbase-sdk-version"),appVersion:n.get("x-palbase-client-version"),platform:n.get("x-platform"),osVersion:n.get("x-os-version")})}}}var vn=720*3600;function kn(e){return e instanceof ie&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function os(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),vn)}function as(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var $n=class{filling=new Map;async get(t){try{let n=await le.cache.getCacheEntry({query:{key:t}});return n.data.found?n.data.value??null:null}catch(n){if(!kn(n))throw n;return E.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 le.cache.putCacheEntry({query:{key:t},body:{value:as(n),ttl:os(r)}})}catch(s){if(!kn(s))throw s;E.warn("cache: a write could not reach the cache; it is let go",{key:t,status:s.status})}}async del(t){await le.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await le.cache.incrementCacheEntry({query:{key:t}})).data.value}getOrSet(t,n,r){let s=this.filling.get(t);if(s)return s;let o=(async()=>{try{let a;try{a=(await le.cache.getCacheEntry({query:{key:t}})).data}catch(c){if(!kn(c))throw c;E.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:c.status})}if(a?.found)return a.value??null;let i=await r();return await this.set(t,i,n),i}finally{this.filling.delete(t)}})();return this.filling.set(t,o),o}},nc=dt("Cache",new $n);function rc(e={}){let t=e.maxEntries??5e4,n=e.now??(()=>Date.now()),r=new Map,s=new Map,o=p=>{let y=r.get(p);if(y&&y.expiresAt<=n()){r.delete(p);return}return y},a=()=>{let p=n();for(let[k,R]of r)R.expiresAt<=p&&r.delete(k);if(r.size<t)return;let y=[...r.entries()].sort((k,R)=>k[1].expiresAt-R[1].expiresAt);for(let[k]of y.slice(0,Math.ceil(y.length/4)))r.delete(k)},i=async(p,y,k)=>{r.size>=t&&!r.has(p)&&a(),r.set(p,{value:as(y),expiresAt:n()+(os(k)??vn)*1e3})};return{get:async p=>{let y=o(p);return y?structuredClone(y.value):null},set:i,async del(p){r.delete(p)},async incr(p){let y=o(p),k=(typeof y?.value=="number"&&Number.isInteger(y.value)?y.value:0)+1;return r.set(p,{value:k,expiresAt:y?.expiresAt??n()+vn*1e3}),k},getOrSet(p,y,k){let R=o(p);if(R)return Promise.resolve(structuredClone(R.value));let U=s.get(p);if(U)return U;let I=(async()=>{try{let L=await k();return await i(p,L,y),L}finally{s.delete(p)}})();return s.set(p,I),I}}}export{jt as a,be as b,Oe as c,Ka as d,Ja as e,Wa as f,Va as g,Za as h,Qa as i,Ga as j,Ya as k,Xa as l,ei as m,ti as n,ni as o,ri as p,si as q,oi as r,ai as s,ii as t,di as u,ci as v,ui as w,li as x,fi as y,pi as z,M as A,mi as B,hi as C,ut as D,ki as E,vi as F,Oi as G,xi as H,Ai as I,Pi as J,Ci as K,Mi as L,Di as M,Ii as N,zi as O,qi as P,Ji as Q,Wi as R,Gi as S,J as T,kr as U,vr as V,$r as W,bo as X,od as Y,dd as Z,cd as _,ud as $,ld as aa,fd as ba,pd as ca,md as da,hd as ea,Td as fa,ga,Yd as ha,vn as ia,nc as ja,rc as ka};
|