palbase 0.3.2 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +10 -13
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +9 -9
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{HHSKJTI6.js → 2AT72FFB.js} +2 -2
- package/dist/chunks/{TTKDWRP5.js → 3OIKIBMG.js} +2 -2
- package/dist/chunks/{JFWH2INT.js → 6JO3UVPT.js} +2 -2
- package/dist/chunks/{XUG2RG4F.js → BHT2IHBE.js} +2 -2
- package/dist/chunks/BJL2FT5W.js +2 -0
- package/dist/chunks/CY6B75KF.js +6 -0
- package/dist/chunks/EGRDFD5C.js +20 -0
- package/dist/chunks/{RHQ2NBCI.js → FS222NNP.js} +2 -2
- package/dist/chunks/{ZEFNZ6DZ.js → IVDNNHII.js} +2 -2
- package/dist/chunks/{YSZ2RSTS.js → ODFLUINN.js} +1 -1
- package/dist/chunks/{HJVB6KIR.js → RKNVSAGY.js} +1 -1
- package/dist/chunks/ST2NZ4TZ.js +4 -0
- package/dist/chunks/{33DZIPGE.js → SUNHFMDO.js} +2 -2
- package/dist/chunks/{44SLUFBO.js → TRHIZOIS.js} +3 -3
- package/dist/chunks/{32BPNFZX.js → UNTTPATW.js} +1 -1
- package/dist/chunks/{CNRFJ7AK.js → ZFX4BFQR.js} +2 -2
- package/dist/cli.js +131 -128
- 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 +63 -2
- package/types/ai/src/chats.d.ts +147 -0
- package/types/ai/src/index.d.ts +6 -1
- package/types/ai/src/tools.d.ts +167 -0
- package/types/backend/src/engine.d.ts +12 -1
- package/types/backend/src/i18n.d.ts +8 -7
- package/types/backend/src/strings-files.d.ts +28 -1
- package/types/internal/src/chat.d.ts +117 -0
- package/types/internal/src/tool-output.d.ts +20 -0
- package/types/web/src/ai.d.ts +201 -0
- package/types/web/src/client.d.ts +3 -0
- package/types/web/src/index.d.ts +1 -0
- package/dist/chunks/QA3GIZMI.js +0 -4
- package/dist/chunks/QD5XLRIJ.js +0 -2
- package/dist/chunks/QRWBXKEM.js +0 -20
package/dist/chunks/QRWBXKEM.js
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.3.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{a as sn,c as se,d as an,e as Ee,g as S}from"./QA3GIZMI.js";import{b as Ye,d as ht,e as tn,f as nn,g as Ge,h as Ze,k as rn,q as on}from"./33DZIPGE.js";import{b as $e}from"./HHSKJTI6.js";import"reflect-metadata";var gt=[{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}],dn="a schedule is five fields \u2014 minute hour day-of-month month day-of-week, in UTC \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Xe=/^\d+$/;function $r(e,t,r){let n=new Set;for(let o of e.split(",")){let s=o.indexOf("/"),a=s===-1?o:o.slice(0,s),i=1;if(s!==-1){let f=o.slice(s+1);if(!Xe.test(f)||Number(f)<1||Number(f)>r)return;i=Number(f)}let c=t,u=r;if(a!=="*")if(a.includes("-")){let f=a.indexOf("-"),y=a.slice(0,f),E=a.slice(f+1);if(!Xe.test(y)||!Xe.test(E)||Number(y)<t||Number(E)>r||Number(y)>Number(E))return;c=Number(y),u=Number(E)}else{if(!Xe.test(a)||Number(a)<t||Number(a)>r)return;c=Number(a),u=s===-1?c:r}for(let f=c;f<=u;f+=i)n.add(f)}return n}function cn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${dn}; "${e}" is not`;let r=[];for(let u=0;u<5;u++){let f=$r(t[u],gt[u].lo,gt[u].hi);if(!f)return`${dn}; its ${gt[u].name} "${t[u]}" is not one`;r.push(f)}let[,,n,o,s]=r;s.has(7)&&s.add(0);let a=t[2].startsWith("*"),i=t[4].startsWith("*"),c=new Date(Date.UTC(2e3,0,1));for(let u=0;u<366*8+2;u++,c.setUTCDate(c.getUTCDate()+1)){if(!o.has(c.getUTCMonth()+1))continue;let f=n.has(c.getUTCDate()),y=s.has(c.getUTCDay());if(a||i?f&&y:f||y)return}return`"${e}" is never due: no date has that day in that month`}var Re=Symbol.for("palbase.backend.controller"),Se=Symbol.for("palbase.backend.routes"),wt=Symbol.for("palbase.backend.params"),bt=Symbol.for("palbase.backend.injectable"),vt=Symbol.for("palbase.backend.module"),he=Symbol.for("palbase.backend.events"),Oe=Symbol.for("palbase.backend.webhook"),ue=Symbol.for("palbase.backend.jobs");function X(e,t,r){let n=e;return Object.prototype.hasOwnProperty.call(n,t)||Object.defineProperty(n,t,{value:r(),enumerable:!1}),n[t]}var yt=Symbol.for("palbase.backend.declared");function oe(){let e=globalThis;return e[yt]instanceof Set||(e[yt]=new Set),e[yt]}var _e=new Set(["webhooks","_palbase"]);function Ls(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return r=>{let n=e.split("/").filter(Boolean)[0];if(n!==void 0&&_e.has(n))throw new TypeError(`@Controller("${e}") on ${r.name}: /${n} is the platform's; a controller is served elsewhere`);X(r,Re,()=>({basePath:e,options:t})),oe().add(r)}}function xe(e){return(t,r={})=>{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(n,o,s)=>{if(typeof o!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);X(n.constructor,Se,()=>[]).push({method:e,subpath:t,fn:o,options:r})}}}var qs=xe("GET"),Hs=xe("POST"),Js=xe("PUT"),Bs=xe("PATCH"),zs=xe("DELETE"),Fs=xe("QUERY");function te(e,t={}){return(r,n,o)=>{if(typeof n!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let s=X(r.constructor,wt,()=>new Map);s.has(n)||s.set(n,[]),s.get(n).push({index:o,kind:e,...t})}}function kt(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 Ks=e=>te("body",{schema:kt("Body",e)}),Ws=e=>te("query",{schema:kt("QueryParams",e)}),Vs=e=>te("headers",e===void 0?{}:{schema:kt("Headers",e)}),Ys=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return te("param",{name:e})},Gs=()=>te("user"),Zs=()=>te("optionalUser"),Xs=()=>te("req"),Qs=()=>te("requestId"),ea=()=>te("requestId"),ta=()=>te("client");function na(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 te("resolve",{resolver:e,options:t[0]})}function ra(){return e=>{X(e,bt,()=>!0),oe().add(e)}}function oa(e){return t=>{X(t,vt,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var ln=/^[a-z]+(\.[a-z_]+)+$/,Er=/^[a-z][a-z0-9-]{1,62}$/,$t=e=>e.startsWith("file.");function sa(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let r=t?.bucket;if(r!==void 0){if(typeof r!="string"||!Er.test(r))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(r)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!$t(e))throw new TypeError(`@On("${e}", { bucket: "${r}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(n,o,s)=>{if(typeof o!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@On("${e}") goes on a method`);X(n.constructor,he,()=>[]).push(r===void 0?{event:e,fn:o}:{event:e,fn:o,bucket:r}),oe().add(n.constructor)}}var Rr=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function aa(e){let t=e??{},r=`@Job(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Rr.test(t.name))throw new TypeError(`${r}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${r}: schedule is five fields of cron's, like "0 3 * * *"`);let n=cn(t.schedule);if(n)throw new TypeError(`${r}: ${n}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>300))throw new TypeError(`${r}: timeout is whole seconds, 1 to 300 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${r}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let o={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeout:t.timeout??30,retries:t.retry??5};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${r} on ${s.name}: a job is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(s,ue))throw new TypeError(`${r} on ${s.name}: a class is one job`);Object.defineProperty(s,ue,{value:o,enumerable:!1}),oe().add(s)}}var un=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Sr=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function ia(e){return t=>{let r=`@Webhook on ${t.name}`,n=e??{};if(typeof n.name!="string"||n.name==="")throw new TypeError(`${r}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!Sr.test(n.name))throw new TypeError(`${r}: name "${n.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(n.name==="palbase")throw new TypeError(`${r}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(n.provider===void 0&&n.signature===void 0)throw new TypeError(`${r}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(n.provider!==void 0&&n.signature!==void 0)throw new TypeError(`${r}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(n.provider!==void 0&&!un.includes(n.provider))throw new TypeError(`${r}: provider "${String(n.provider)}" is not one of ${un.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(n.signature!==void 0&&Or(n.signature,r),typeof n.secret?.env!="string"||n.secret.env==="")throw new TypeError(`${r}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let o=T(t,he)??[];if(o.length===0)throw new TypeError(`${r}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let s=new Set;for(let{event:a,bucket:i}of o){if(s.has(a))throw new TypeError(`${r}: @On("${a}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${r}: @On("${a}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${n.name}'s are a third party's`);s.add(a)}X(t,Oe,()=>({name:n.name,provider:n.provider,signature:n.signature&&{...n.signature},secret:{env:n.secret.env},events:o.map(({event:a,fn:i})=>({event:a,fn:i}))})),oe().add(t)}}function Or(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 T(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function da(){return[...oe()].filter(e=>T(e,Re)!==void 0)}function ca(e){return(T(e,Se)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Et="/_palbase/storage/upload/authorize",fn="/_palbase/storage/upload/complete",Rt="/_palbase/realtime/rooms";var _r=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Te(e){if(!_r(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 mn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function pn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Qe(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var xr=/^[a-z][a-z0-9-]{1,62}$/,hn=1024,Tr=new Set(["userId","uploadId","filename"]);function pa(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let r=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 r.bucket!="string"||r.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!xr.test(r.bucket))throw new TypeError(`@Upload("${e}"): bucket "${r.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof r.pathTemplate!="string"||r.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let n=Ar(r.pathTemplate);if(n)throw new TypeError(`@Upload("${e}"): pathTemplate "${r.pathTemplate}" ${n}`);let o={bucket:r.bucket,pathTemplate:r.pathTemplate},s={...r.auth!==void 0?{auth:r.auth}:{},...r.rateLimit!==void 0?{rateLimit:r.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`);X(a.constructor,Se,()=>[]).push({method:"POST",subpath:e,fn:i,options:s,upload:o})}}function ha(){return te("uploadedObject")}function Ar(e){for(let r of e.matchAll(/\{([^{}]*)\}/g))if(!Tr.has(r[1]))return`names {${r[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(!gn(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function gn(e){if(e===""||new TextEncoder().encode(e).byteLength>hn)return!1;for(let t=0;t<e.length;t++){let r=e.charCodeAt(t);if(r<32||r===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Pr(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(r,n)=>jr(n==="userId"?t.userId??"anonymous":n==="uploadId"?t.uploadId:t.filename??"file"))}function jr(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 yn(e,t){let r=Pr(e,t);return gn(r)?{path:r}:{problem:`the file's name makes its path longer than storage keeps (${hn} bytes)`}}function wn(e){let t=new Map;for(let r of e)r.meta.upload&&t.set(r.controller,(t.get(r.controller)??new Set).add(r.fn));for(let r of e){let n=`${r.controller.name}.${r.fn}`;if(!r.meta.upload){if(t.get(r.controller)?.has(r.fn))throw new TypeError(`${n}: @Upload and @${r.method[0]}${r.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(r.params.some(s=>s.kind==="uploadedObject"))throw new TypeError(`${n}: @UploadedObject() on ${r.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let o=r.params.find(s=>s.kind==="headers"||s.kind==="req"||s.kind==="client");if(o){let s=o.kind==="headers"?"Headers":o.kind==="req"?"Req":"Client";throw new TypeError(`${n}: @${s}() 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 St=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function bn(e,t){if(!St(t))return"a call is a JSON object";let{route:r,method:n,query:o,uploadId:s}=t;if(typeof r!="string"||!r.startsWith("/"))return"route is the upload route's path";if(typeof n!="string"||n==="")return"method is the route's";if(typeof o!="string")return'query is the query string, "" for none';if(typeof s!="string"||s==="")return"uploadId is the upload's id";let a=Te(t.user);if(!a)return"user is { id?, session?, role }";let i=mn(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:r,method:n,query:o,uploadId:s,user:a,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let c=Cr(t.uploadedObject);return c?c.uploadId!==s?"uploadedObject is another upload's":{route:r,method:n,query:o,uploadId:s,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 Cr(e){if(!St(e))return;let{uploadId:t,path:r,bucket:n,size:o,contentType:s,checksum:a,width:i,height:c,thumbhash:u,variants:f}=e;if(!(typeof t!="string"||typeof r!="string"||typeof n!="string"||typeof s!="string"||typeof a!="string")&&!(typeof o!="number"||!Number.isInteger(o)||o<0)&&!(i!==void 0&&typeof i!="number"||c!==void 0&&typeof c!="number"||u!==void 0&&typeof u!="string")&&!(!St(f)||!Object.values(f).every(y=>typeof y=="string")))return{uploadId:t,path:r,bucket:n,size:o,contentType:s,checksum:a,...i!==void 0?{width:i}:{},...c!==void 0?{height:c}:{},...u!==void 0?{thumbhash:u}:{},variants:{...f}}}import{markData as Mr}from"palgres";var ge=Symbol.for("palbase.backend.room"),Pe=Symbol.for("palbase.backend.roomHooks"),Dr=6e4,Ae=255,Ur=["roles:","flags:","messaging:","debug:"],xt=e=>new TextEncoder().encode(e).byteLength,vn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function";function Nr(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(xt(e)>Ae)return`a channel is ${Ae} 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=Ur.find(n=>e.startsWith(n));if(t)return`${t} channels are the platform's`;let r=new Set;for(let n of e.split(":")){if(n==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(n)){if(n==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(n))return`"${n}" \u2014 a parameter is a whole segment, {name}`;if(r.has(n))return`parameter "${n}" appears twice.`;r.add(n)}}}function kn(e){if(typeof e!="string"||e==="")return"is a name";if(xt(e)>Ae)return`is ${Ae} bytes at most`}function ka(e,t){if(typeof e!="string"||e==="")throw new TypeError('@Room(pattern, { events }): pattern is the channels it is, like "ai:{sessionId}"');let r=Nr(e);if(r)throw new TypeError(`@Room("${e}"): ${r}`);let n=t??{};if(typeof n.events!="object"||n.events===null||Array.isArray(n.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(n.events)){let c=kn(a);if(c)throw new TypeError(`@Room("${e}"): event "${a}" ${c}`);if(!vn(i))throw new TypeError(`@Room("${e}"): event "${a}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}if(n.graceMs!==void 0&&(!Number.isSafeInteger(n.graceMs)||n.graceMs<=0))throw new TypeError(`@Room("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(n.graceMs)})`);let o={...n.events},s=n.graceMs??Dr;return a=>{let i=X(a,Pe,Tt);X(a,ge,()=>({pattern:e,events:o,graceMs:s,hooks:{...i.hooks},messages:Object.assign(Object.create(null),i.messages)})),oe().add(a)}}var Tt=()=>({hooks:Object.create(null),messages:Object.create(null)});function Ue(e){let t=`On${e[0].toUpperCase()}${e.slice(1)}`;return()=>(r,n,o)=>{if(typeof n!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof r=="function")throw new TypeError(`@${t}() on static ${r.name}.${n}: a room's methods are its instance's`);let s=X(r.constructor,Pe,Tt),a=s.hooks[e];if(a!==void 0&&a!==n)throw new TypeError(`@${t}() is declared twice in one room (${a} and ${n}). A room has one of each hook.`);s.hooks[e]=n,oe().add(r.constructor)}}var $a=Ue("authorize"),Ea=Ue("first"),Ra=Ue("join"),Sa=Ue("leave"),Oa=Ue("empty");function _a(e,t){let r=kn(e);if(r)throw new TypeError(`@OnMessage(name, schema): name ${r}`);if(!vn(t))throw new TypeError(`@OnMessage("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return(n,o,s)=>{if(typeof o!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@OnMessage("${e}") goes on a method`);if(typeof n=="function")throw new TypeError(`@OnMessage("${e}") on static ${n.name}.${o}: a room's methods are its instance's`);let a=X(n.constructor,Pe,Tt),i=a.messages[e];if(i!==void 0&&i.fn!==o)throw new TypeError(`@OnMessage("${e}") is declared twice in one room (${i.fn} and ${o}).`);a.messages[e]={fn:o,schema:t},oe().add(n.constructor)}}function Ir(e){return T(e,ge)}function Lr(e,t){let r=e.split(":"),n=t.split(":");if(r.length!==n.length)return;let o=[];for(let s=0;s<r.length;s++){let a=r[s];if(a.length>=2&&a.startsWith("{")&&a.endsWith("}")){if(n[s]==="")return;o.push([a.slice(1,-1),n[s]])}else if(a!==n[s])return}return Object.fromEntries(o)}var qr=1e4,Hr=1e3,Jr=100,At=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ae=(e,t,r,n)=>({status:e,code:t,message:r,...n!==void 0?{retryAfter:n}:{}}),Br=new Set(["first","join","leave","empty"]);function $n(e,t){let r=new Map,n=new Map;for(let{cls:b,instance:$}of e){let w=Ir(b),R=w.pattern.split(":").map(C=>C.startsWith("{")?"{}":C).join(":"),P=n.get(R);if(P!==void 0)throw new TypeError(`@Room("${w.pattern}") on ${b.name}: ${r.get(P)?.cls.name}'s "${P}" is the same channels \u2014 one room is told of them; keep one`);n.set(R,w.pattern);for(let[C,I]of[...Object.entries(w.hooks),...Object.entries(w.messages).map(([L,U])=>[`message ${L}`,U.fn])])if(typeof $[I]!="function")throw new TypeError(`@Room("${w.pattern}") on ${b.name}: its ${C} is ${I}, which is no method of it`);r.set(w.pattern,{cls:b,instance:$,room:w})}let o=new Map,s=new Set,a=new Set,i=new _t(t.broadcast),c=b=>{let $=o.get(b);return $||($=new AbortController,o.set(b,$)),$},u=(b,$)=>{$?.abort(),o.get(b)===$&&o.delete(b)};function f(b,$,w,R,P,C,I){let L=R?.signal??AbortSignal.abort(),U=`${b.cls.name} (${$})`;return{room:$,params:Object.freeze({...w}),signal:L,count:P,user:C,emit:(M,q)=>i.send({topic:$,event:M,payload:q??{},...I!==void 0?{conn_id:I}:{}},U),owner:{hold(M){se.exit(async()=>{try{await M(L)}catch(q){L.aborted||S.error(`[palbase] ${U}: a task owner.hold ran failed`,{error:q})}}).catch(()=>{})},release:()=>u($,R)}}}function y(b){let{room:$,channel:w}=b;if(typeof $!="string"||typeof w!="string")return ae(400,"bad_request","A room's call names its room (the pattern) and its channel");let R=r.get($);return R?{entry:R,channel:w,params:Lr($,w)}:ae(404,"not_found",`This app declares no room "${$}"`)}let E=(b,$)=>ae(400,"bad_request",`"${$}" is not a channel of the room "${b}"`);async function N(b,$){let w=y(b);if("status"in w)return w;let{entry:R,channel:P,params:C}=w,I={status:200,body:{subscribe:!1,publish:!1}};if(!C)return S.warn(`[palbase] ${R.cls.name}: realtime asked about "${P}", which is not a channel of the room "${R.room.pattern}"; the join is refused`),I;let L=Te(b.user),U=L?.id;if(!U)return I;let M=R.room.hooks.authorize;if(!M)return I;let q,re;try{q=await t.run(L,`${R.cls.name}.${M}`,$,async()=>R.instance[M]({user:{id:U},params:Object.freeze({...C})})),re=zr(q)}catch(Q){if(t.isOutage(Q)||$?.aborted)throw Q;return S.error(`[palbase] ${R.cls.name}.${M} (@OnAuthorize of ${P}) failed; the join is refused`,{error:Q}),I}return re==="malformed"?(S.warn(`[palbase] ${R.cls.name}.${M} (@OnAuthorize of ${P}) answered ${Fr(q)}, which is no grant (true, { read, write } or null); the join is refused`),I):{status:200,body:re}}async function g(b,$){let w=y(b);if("status"in w)return w;if(!w.params)return E(w.entry.room.pattern,w.channel);let R=Te(b.user);if(!R?.id||typeof b.event!="string")return ae(400,"bad_request","A message names its member (user) and its event");let P=Object.hasOwn(w.entry.room.messages,b.event)?w.entry.room.messages[b.event]:void 0;if(!P)return{status:200,body:{ok:!1,reason:En(`room "${w.channel}" declares no message "${b.event}"`,Ot)}};let C=await P.schema["~standard"].validate(Mr(b.payload??{}));if(C.issues)return{status:200,body:{ok:!1,reason:Wr(C.issues)}};let I=c(w.channel),L={...f(w.entry,w.channel,w.params,I,0,{id:R.id}),payload:C.value};try{await t.run(R,`${w.entry.cls.name}.${P.fn}`,$,async()=>w.entry.instance[P.fn](L))}catch(U){if(t.isOutage(U))throw U;return $?.aborted||S.error(`[palbase] ${w.entry.cls.name}.${P.fn} (@OnMessage "${b.event}" of ${w.channel}) failed`,{error:U}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return{status:200,body:{ok:!0}}}async function A(b,$){let w=y(b);if("status"in w)return w;if(!w.params)return E(w.entry.room.pattern,w.channel);let R=b.event;if(typeof R!="string"||!Br.has(R))return ae(400,"bad_request","A room's moment is first, join, leave or empty");let P=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(P===void 0)return ae(400,"bad_request","A room's moment says its count of members");let C=R==="join"||R==="leave",I=C?Te(b.user):void 0,L=C?b.connId:void 0;if(C&&(!I?.id||typeof L!="string"||L===""))return ae(400,"bad_request",`A ${R} names its member: user and connId`);let U=`${R}\0${w.channel}\0${typeof L=="string"?L:""}`;if(C&&s.has(U))return{status:204};if(a.has(U))return ae(503,"in_progress","This moment of the room is being handled",5);a.add(U);try{let M=w.entry.room.hooks[R],q;if(R==="empty"?(q=o.get(w.channel),u(w.channel,q)):q=R==="leave"?o.get(w.channel):c(w.channel),M){let re=f(w.entry,w.channel,w.params,q,P,{id:I?.id??""},R==="join"?L:void 0);try{await t.run(I,`${w.entry.cls.name}.${M}`,$,async()=>w.entry.instance[M](re))}catch(Q){if(t.isOutage(Q))throw Q;return $?.aborted||S.error(`[palbase] ${w.entry.cls.name}.${M} (${R} of ${w.channel}) failed; realtime tells it again`,{error:Q}),ae(500,"handler_failed",`The room's ${R} could not be handled`)}}return C&&(s.add(U),s.size>qr&&s.delete(s.values().next().value)),{status:204}}finally{a.delete(U)}}return{declarations:[...r.values()].map(b=>b.room),async serve(b,$,w){return At($)?b==="authorize"?N($,w):b==="message"?g($,w):b==="lifecycle"?A($,w):ae(404,"not_found",`No room call ${JSON.stringify(b)}`):ae(400,"bad_request","A room's call is a JSON object")},close(){for(let b of o.values())b.abort();o.clear()}}}function zr(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!At(e))return"malformed";let r=Object.hasOwn(e,"read"),n=Object.hasOwn(e,"write");if(r&&typeof e.read!="boolean"||n&&typeof e.write!="boolean"||!r&&!n)return"malformed";let o=r?e.read:void 0,s=n?e.write:void 0;return o===!1?t:{subscribe:!0,publish:s!==!1}}function Fr(e){return Array.isArray(e)?"an array":At(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 Kr=20,Ot=256;function Wr(e){let t="";for(let r of e.slice(0,Kr)){let n=(r.path??[]).slice(0,8).map(s=>String(typeof s=="object"&&s!==null&&"key"in s?s.key:s).slice(0,64)).join("."),o=n===""?r.message:`${n}: ${r.message}`;if(t=t===""?o:`${t}; ${o}`,Buffer.byteLength(t)>=Ot)break}return En(t,Ot)}function En(e,t){if(Buffer.byteLength(e)<=t)return e;let r="";for(let n of e){if(Buffer.byteLength(r+n)>t-3)break;r+=n}return`${r}\u2026`}var _t=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,r){if(typeof t.event!="string"||t.event===""||xt(t.event)>Ae){S.warn(`[palbase] ${r}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Ae} bytes`);return}try{JSON.stringify(t.payload)}catch(s){S.warn(`[palbase] ${r}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let n=this.queues.get(t.topic);if(n){n.length>=Hr?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):n.push(t);return}let o=[t];this.queues.set(t.topic,o),se.exit(()=>this.drain(t.topic,o,r))}async drain(t,r,n){for(;;){if(r.length===0){this.queues.delete(t);return}let o=r.splice(0,Jr);try{await this.broadcast(o)}catch(a){S.warn(`[palbase] ${n}: ${o.length} event(s) to ${t} were not sent`,{error:a})}let s=this.dropped.get(t);s&&(this.dropped.delete(t),S.warn(`[palbase] ${n}: ${s} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as Pt,createHmac as Vr,createPublicKey as _n,timingSafeEqual as Yr,verify as xn}from"node:crypto";function Pa(e){let t=T(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(r=>r.event)}}function Tn(e,t,r,n={}){let o=new Map,s=[];for(let a of e){let i=T(a,Oe),c=o.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 u=`@Webhook "${i.name}" (${a.name})`,f=r[i.secret.env],y;if(n.secrets!==!1)if(f===void 0||f==="")s.push(`${u} reads its signing secret from ${i.secret.env}, which is not set`);else try{y=Gr(i,f)}catch(g){s.push(`${u}: ${i.secret.env} ${g.message}`)}let E=t(a),N=new Map(i.events.map(({event:g,fn:A})=>[g,{name:`${a.name}.${A}`,call:(b,$)=>E[A](b,$)}]));o.set(i.name,{name:i.name,cls:a,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:y,events:N})}if(s.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
|
-
- ${s.join(`
|
|
4
|
-
- `)}`);return o}function An(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var je=1024,Rn=1024*je;function Gr(e,t){if(e.signature)return ye(void 0,e.signature.header,1/0,io(e.signature,t));switch(e.provider){case"stripe":return ye("stripe","stripe-signature",512*je,Qr(t));case"github":return ye("github","x-hub-signature-256",25*Rn,eo(t));case"slack":return ye("slack","x-slack-signature",64*je,to(t));case"discord":return ye("discord","x-signature-ed25519",64*je,no(t));case"twilio":return{header:"x-twilio-signature",maxBytes:r=>Math.min(r,64*je),check:oo(t)};case"sendgrid":return ye("sendgrid","x-twilio-email-event-webhook-signature",Rn,so(t));case"livekit":return ye("livekit","authorization",512*je,ao(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function ye(e,t,r,n){return{header:t,maxBytes:o=>Math.min(o,r),check:(o,s)=>n(o,s)??Pn(e,o)}}function Pn(e,t){let r=jt(t.body),n;try{n=JSON.parse(r)}catch{if(n=r,e==="slack"){let o=new URLSearchParams(r).get("payload");if(o!==null)try{n=JSON.parse(o)}catch{}}}return{type:jn(e,t.headers,n),event:n,...Zr(e,t,n)}}function jn(e,t,r){switch(e){case"github":{let n=t.get("x-github-event")??"",o=we(r,"action");return n!==""&&o!==""?`${n}.${o}`:n}case"discord":{let n=Dn(r)?r.type:void 0;return n===1?"PING":n===2?"INTERACTION_CREATE":Number.isInteger(n)?`type_${String(n)}`:""}case"sendgrid":return"event_batch";case"twilio":return we(r,"EventType");case"livekit":return we(r,"event");default:return we(r,"type")}}function Zr(e,t,r){let n=o=>o?{id:o}:{};switch(e){case"stripe":case"discord":case"livekit":return n(we(r,"id"));case"slack":return n(we(r,"event_id"));case"github":{let o=t.headers.get("x-github-delivery");return o?{id:`${o}:${Cn(t.body)}`}:{}}case"sendgrid":return Array.isArray(r)?{ids:r.map(o=>we(o,"sg_event_id")||void 0)}:{};default:return{}}}var Xr=300;function Qr(e){return(t,r)=>{let n=t.headers.get("stripe-signature");if(!n)return"missing_signature";let o,s=[];for(let c of n.split(",")){let u=c.indexOf("=");if(u<=0)continue;let f=c.slice(0,u).trim(),y=c.slice(u+1).trim();if(f==="t"){if(o!==void 0)return"malformed_signature";o=y}else if(f==="v1"){let E=ne(y,"hex");if(!E)return"malformed_signature";s.push(E)}}let a=Ne(o);if(a===void 0||s.length===0)return"malformed_signature";if(Ie(a,r))return"stale_timestamp";let i=Ce("sha256",e,`${o}.`,t.body);return s.some(c=>le(c,i))?void 0:"signature_mismatch"}}function eo(e){return t=>{let r=t.headers.get("x-hub-signature-256");if(!r)return"missing_signature";let n=r.startsWith("sha256=")?ne(r.slice(7),"hex"):void 0;return n?le(n,Ce("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function to(e){return(t,r)=>{let n=t.headers.get("x-slack-signature");if(!n)return"missing_signature";let o=t.headers.get("x-slack-request-timestamp")?.trim(),s=Ne(o),a=n.startsWith("v0=")?ne(n.slice(3),"hex"):void 0;return s===void 0||!a?"malformed_signature":Ie(s,r)?"stale_timestamp":le(a,Ce("sha256",e,`v0:${o}:`,t.body))?void 0:"signature_mismatch"}}function no(e){let t=ne(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 r=_n({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(n,o)=>{let s=n.headers.get("x-signature-ed25519");if(!s)return"missing_signature";let a=n.headers.get("x-signature-timestamp")??void 0,i=Ne(a),c=ne(s,"hex");return i===void 0||!c||c.byteLength!==64?"malformed_signature":Ie(i,o)?"stale_timestamp":xn(null,Mn(a,n.body),r,c)?void 0:"signature_mismatch"}}var ro=1e3;function oo(e){return t=>{let r=t.headers.get("x-twilio-signature");if(!r)return"missing_signature";let n=ne(r.trim(),"base64");if(!n||n.byteLength!==20)return"malformed_signature";let o;try{o=new URL(t.url)}catch{return"signature_mismatch"}let s=o.searchParams.get("bodySHA256"),a="",i;if(s!==null){if(!le(Buffer.from(s.toLowerCase()),Buffer.from(Pt("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let N=1;for(let b of t.body)if(b===38&&++N>ro)return"malformed_signature";let g=new Map;for(let[b,$]of new URLSearchParams(jt(t.body))){let w=g.get(b);w||g.set(b,w=new Set),w.add($)}let A=[];for(let b of[...g.keys()].sort()){let $=[...g.get(b)].sort();for(let w of $)a+=b+w;A.push([b,$.length===1?$[0]:$])}i=Object.fromEntries(A)}let c=o.protocol==="https:"?"443":"80",u=`${o.protocol}//${o.hostname}${o.pathname}${o.search}`,f=`${o.protocol}//${o.hostname}:${o.port||c}${o.pathname}${o.search}`;if(![u,f].some(N=>le(n,Ce("sha1",e,N,a))))return"signature_mismatch";let y=t.headers.get("i-twilio-idempotency-token"),E=y?{id:`${y}:${Cn(`${u}
|
|
5
|
-
${a}`)}`}:{};return i?{type:jn("twilio",t.headers,i),event:i,...E}:{...Pn("twilio",t),...E}}}function so(e){let t;try{let r=ne(e,"base64");if(!r)throw new Error;t=_n({key:Buffer.from(r),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(r,n)=>{let o=r.headers.get("x-twilio-email-event-webhook-signature");if(!o)return"missing_signature";let s=r.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),a=Ne(s),i=ne(o.trim(),"base64");return a===void 0||!i?"malformed_signature":Ie(a,n)?"stale_timestamp":xn("sha256",Mn(s,r.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var Sn=60;function ao(e){return(t,r)=>{let n=t.headers.get("authorization");if(!n)return"missing_signature";let o=n.split(".");if(o.length!==3)return"malformed_signature";let s=On(ne(o[0],"base64url")),a=ne(o[2],"base64url");if(s?.alg!=="HS256"||!a)return"malformed_signature";if(!le(a,Ce("sha256",e,`${o[0]}.${o[1]}`)))return"signature_mismatch";let i=On(ne(o[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(r>i.exp+Sn||typeof i.nbf=="number"&&r<i.nbf-Sn)return"stale_timestamp";let c=typeof i.sha256=="string"?ne(i.sha256,"base64"):void 0;return c&&le(c,Pt("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function io(e,t){let r=e.signs.split(/(\{body\}|\{ts\})/),n=e.algo==="hmac-sha1"?"sha1":"sha256";return(o,s)=>{let a=o.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(r.includes("{ts}")){i=o.headers.get(e.timestampHeader)?.trim()??"";let u=Ne(i);if(u===void 0)return"malformed_signature";if(Ie(u,s))return"stale_timestamp"}let c=ne(a.trim(),e.encoding);return c?le(c,Ce(n,t,...r.map(u=>u==="{body}"?o.body:u==="{ts}"?i:u)))?void 0:"signature_mismatch":"malformed_signature"}}var co=new TextEncoder;function Ce(e,t,...r){let n=Vr(e,t);for(let o of r)n.update(o);return n.digest()}function Cn(e){return Pt("sha256").update(e).digest("hex")}function Mn(e,t){return Buffer.concat([co.encode(e),t])}function le(e,t){return e.byteLength===t.byteLength&&Yr(e,t)}var uo={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 ne(e,t){return uo[t].test(e)?Buffer.from(e,t):void 0}function Ne(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function Ie(e,t){return Math.abs(t-e)>Xr}function jt(e){return new TextDecoder().decode(e)}function On(e){if(e)try{return JSON.parse(jt(e))}catch{return}}function Dn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function we(e,t){let r=Dn(e)?e[t]:void 0;return typeof r=="string"?r:""}import"reflect-metadata";var J=class extends Error{kind;path;constructor(t,r,n,o,s){super(`
|
|
6
|
-
Kind: ${t}
|
|
7
|
-
Path: ${r.join(" -> ")}
|
|
8
|
-
At: ${n}
|
|
9
|
-
${o}
|
|
10
|
-
|
|
11
|
-
Potential solutions:
|
|
12
|
-
${s.map(a=>` - ${a}`).join(`
|
|
13
|
-
`)}`),this.name="DiError",this.kind=t,this.path=r}},lo=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],fo=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),et=class{owner=new Map;defs=new Map;instances=new Map;order=[];controllers=[];eventProviders=[];webhooks=[];jobProviders=[];rooms=[];constructor(t){this.collect(t),this.validate()}collect(t){let r=(n,o)=>{if(this.defs.has(n))return;let s=T(n,vt);if(!s)throw new J("unknown import",[...o,n.name],n.name,`${n.name} is not a @Module`,["decorate it with @Module({ \u2026 })","or list the module itself, not one of its classes"]);this.defs.set(n,s);for(let a of s.imports){if(a===n)throw new J("unknown import",[n.name],n.name,`${n.name} imports itself`,["remove it from its own imports"]);r(a,[...o,n.name])}};for(let n of t)r(n,[]);for(let[n,o]of this.defs){for(let s of[...o.controllers,...o.providers]){let a=this.owner.get(s);if(a&&a!==n)throw new J("duplicate ownership",[a.name,s.name,n.name],s.name,`${s.name} is listed by ${a.name} and by ${n.name}; a class has one owner`,["keep it in one module and export it from there"]);this.owner.set(s,n)}for(let s of o.controllers){if(!T(s,Re))throw new J("undeclared provider",[n.name,s.name],s.name,`${s.name} is in ${n.name}'s controllers but is not a @Controller`,["decorate it with @Controller(path)"]);if(T(s,ue))throw new J("undeclared provider",[n.name,s.name],s.name,`${s.name} is a controller and a @Job: a job is a provider's`,["give the job a class of its own \u2014 @Injectable() @Job({ name, schedule }) with run(meta) \u2014 listed in the module's providers"]);if(T(s,ge)||T(s,Pe))throw new J("undeclared provider",[n.name,s.name],s.name,`${s.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:s,module:n})}}}validate(){for(let t of oe())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,r]of this.defs){for(let n of r.exports)if(this.owner.get(n)!==t)throw new J("unknown export",[t.name,n.name],t.name,`${t.name} exports ${n.name}, which it does not own`,[`list ${n.name} in ${t.name}'s providers`,"or export it from the module that owns it"]);for(let n of r.providers){if(T(n,Pe)&&!T(n,ge))throw new J("undeclared provider",[t.name,n.name],n.name,`${n.name} has a room's methods (@OnAuthorize, @OnFirst, @OnMessage\u2026) but is no @Room`,["decorate it with @Room(pattern, { events })"]);if(!T(n,bt)&&!T(n,he)&&!T(n,ge)&&!T(n,ue)){let o=Reflect.getMetadata("design:paramtypes",n);throw n.length>0&&!o?new J("metadata missing",[t.name,n.name],n.name,`${n.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,n.name],n.name,`${n.name} is in ${t.name}'s providers but is not @Injectable() (nor an @On handler, a @Room or a @Job)`,["decorate it with @Injectable()"])}T(n,ge)&&this.rooms.push(n),T(n,Oe)?this.webhooks.push(n):T(n,he)&&this.eventProviders.push(n),T(n,ue)&&this.jobProviders.push(n)}}for(let t of this.owner.keys())for(let r of lo)if(typeof t.prototype[r]=="function")throw new J("nest lifecycle name",[t.name],`${t.name}.${r}`,`${r} 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 r=this.instances.get(t);if(!r)throw new Error(`${t.name} is not built by this app`);return r}resolve(t,r){let n=this.instances.get(t);if(n)return n;if(r.includes(t.name))throw new J("dependency cycle",[...r,t.name],t.name,`${[...r,t.name].join(" -> ")} goes round`,["move the shared part into a third class both depend on"]);let o=[...r,t.name],s=t.length,a=Reflect.getMetadata("design:paramtypes",t)??[];if(s>0&&a.length===0)throw new J("metadata missing",o,t.name,`${t.name} takes ${s} 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,s).forEach((u,f)=>{if(fo.has(u)||typeof u!="function")throw new J("unresolvable dependency",o,`${t.name} constructor parameter ${f}`,`parameter ${f} of ${t.name} is typed as ${u===void 0?"something with no runtime class":u.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,u,o),o))});let c=new t(...i);return this.instances.set(t,c),this.order.push(c),c}dependencyOf(t,r,n){let o=t;return this.resolve(this.reachable(o,r,[o.name,n]),[o.name,n])}reachable(t,r,n){let o=this.owner.get(t),s=this.target(r,n),a=this.owner.get(s);if(a!==o){if(!this.defs.get(o).imports.includes(a))throw new J("missing import",[...n,s.name],`${o.name}`,`${t.name} (in ${o.name}) needs ${s.name}, owned by ${a.name}, which ${o.name} does not import`,[`add ${a.name} to ${o.name}'s imports (imports are not transitive)`]);if(!this.defs.get(a).exports.includes(s))throw new J("private dependency",[...n,s.name],`${a.name}`,`${s.name} is ${a.name}'s own: it is not in its exports`,[`add ${s.name} to ${a.name}'s exports`])}return s}target(t,r){if(this.owner.has(t))return t;let n=[...this.owner.keys()].filter(o=>o.prototype instanceof t);if(n.length===1)return n[0];throw n.length>1?new J("duplicate ownership",[...r,t.name],t.name,`${t.name} has ${n.length} owned subclasses (${n.map(o=>o.name).join(", ")}): which one is meant cannot be told`,["ask for the subclass itself"]):new J("unowned class",[...r,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 r of this.order){let n=r.onStart;if(typeof n=="function")try{await n.call(r)}catch(o){throw await this.shutdown(t),new Error(`[palbase] ${r.constructor.name}.onStart() failed: ${o instanceof Error?o.message:String(o)}`,{cause:o})}t.push(r)}}async shutdown(t=this.order){for(let r of[...t].reverse()){let n=r.onShutdown;if(typeof n=="function")try{await n.call(r)}catch(o){console.error(`[palbase] ${r.constructor.name}.onShutdown() failed`,o)}}}};import{HTTP_ERROR_BRAND as mo,HttpError as Le}from"palgres";import{z as fe}from"zod";import{BadRequest as Ja,Conflict as Ba,DeadlockDetected as za,HttpError as Fa,NotFound as Ka,SerializationFailure as Wa,TooManyRequests as Va,UniqueViolation as Ya}from"palgres";function tt(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 Un=class extends Le{constructor(t,r,n,o){super(t,r,n,o),this.name=new.target.name}},Nn=class extends Le{constructor(t="Unauthorized",r="unauthorized",n){super(401,r,t,n),this.name="Unauthorized"}},In=class extends Le{constructor(t="Forbidden",r="forbidden",n){super(403,r,t,n),this.name="Forbidden"}};function qn(e,t){let r={error:e.error,error_description:e.errorDescription,status:e.status,request_id:t};return e.data!==void 0&&(r.data=e.data),r}var po=Symbol.for("palbase.backend.errorRegistry"),ho={bad_request:fe.object({fields:fe.array(fe.object({field:fe.string(),message:fe.string()})),more:fe.number().int().optional()}),too_many_requests:fe.object({retryAfter:fe.number().int()})},go=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 yo(){let e=new Map;for(let[t,r,n]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 o=ho[t];e.set(t,{code:t,status:r,className:n,builtin:!0,...o?{data:o}:{}})}return e}function wo(){let e=globalThis;return e[po]??=yo()}function La(e,t,r){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(r!==void 0&&typeof r?.["~standard"]?.validate!="function")throw new TypeError(`defineError("${e}", ${t}, data): data is a Standard Schema (a zod, valibot or arktype schema)`);if(go.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 n=wo(),o=n.get(e);if(o&&(o.builtin||o.status!==t||o.data===void 0!=(r===void 0)||r!==void 0&&o.data!==r&&Ln(o.data)!==Ln(r)))throw new TypeError(`defineError("${e}", ${t}): "${e}" is already ${o.builtin?`the built-in ${o.className}`:`defined with status ${o.status}${o.status===t?" and other data":""}`} \u2014 a code is one error of the project's`);let s=e.split("_").map(y=>y.charAt(0).toUpperCase()+y.slice(1)).join(""),a=e.replace(/_/g," "),i=a.charAt(0).toUpperCase()+a.slice(1),f=r?(y=>class extends Le{static code=e;static status=t;constructor(E,N){let g=bo(e,y,E);super(t,e,N??(typeof g=="string"?g:i),g),this.name=s}})(r):class extends Le{static code=e;static status=t;constructor(y){super(t,e,y??i),this.name=s}};return Object.defineProperty(f,"name",{value:s}),n.set(e,{code:e,status:t,className:s,builtin:!1,...r?{data:r}:{}}),f}function bo(e,t,r){let n=t["~standard"].validate(r);if(n instanceof Promise)throw new TypeError(`${e}: its data schema validates asynchronously; an error is made at once`);if(n.issues)throw new TypeError(`${e}: its data does not fit its schema \u2014 ${n.issues.map(o=>o.message).join("; ")}`);return n.value}function Ln(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}import{connectionFailure as fr,isEngineRaised as mr,markData as ie}from"palgres";import{createHash as cs}from"node:crypto";import{createHash as vo,randomInt as ko}from"node:crypto";import{ago as Ct,isRetryable as $o,now as Hn}from"palgres";import{defineSchema as Eo,defineTable as Ro,index as So,integer as Oo,jsonb as _o,raw as xo,text as Mt,timestamp as Jn}from"palgres/dsl";var Vn=new Set(["POST","PUT","PATCH","DELETE"]),Bn=255,zn=35,Fn=24,To=65536,Kn=1e3,Ao=64,Ut={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"}},Po=Ro("idempotency_keys",{columns:{key:Mt().primaryKey(),fingerprint:Mt(),started_at:Jn().defaultNow(),completed_at:Jn().nullable(),status_code:Oo().nullable(),response_headers:_o().nullable(),response_body:Mt().nullable()},indexes:e=>[So("idempotency_keys_started").on(e.col("started_at"))]}),ni=Eo("palbase",{tables:[Po],raw:[xo("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)"})]}),jo={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},Co={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},Mo={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},Do={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},rt=class extends Error{};function qe(e){return Vn.has(e.method)&&e.meta.upload===void 0}function Yn(e,t){if(!Vn.has(e))return;let r=t.get("idempotency-key");return r===null||r===""?void 0:r}function Uo(e,t){return Gn([e.role,e.uid,t]).digest("hex")}function No(e){return Gn([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function Gn(e){let t=vo("sha256");for(let r of e)t.update(r).update("\0");return t}function Io(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function Dt(e){return e<500&&e!==429&&e!==499}function Lo(e,t){return t&&Dt(e)}function Zn(e){let t=e["~standard"].jsonSchema?.input,r;try{r=t?.({target:"draft-2020-12"})}catch{return!1}let n=r?.properties;return typeof n=="object"&&n!==null&&Object.keys(n).some(o=>o.toLowerCase()==="idempotency-key")}var qo={role:"service",claims:{}},ot=class{constructor(t){this.db=t}db;async serve(t,r,n){if(t.key.length>Bn)return n.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${Bn} characters`});let o;try{o=await this.begin(Uo(t.caller,t.key),No(t))}catch(i){return S.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:i}),n.refusal(Do)}if("kept"in o)return Ho(o.kept,n.requestId);if("refused"in o)return n.refusal(o.refused==="reused"?jo:Co);let s=o.claim,a;try{a=await r(i=>this.record(s,i))}catch(i){if(i instanceof rt)return n.refusal(Mo);let c=n.failure(i);return Lo(c.status,n.ran())&&!$o(i)?this.keep(s,c):(await this.release(s),c)}return Dt(a.status)||await this.release(s),a}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:Ct({hours:Fn})}}}))}async begin(t,r){return ko(Ao)===0&&await this.sweep().catch(n=>S.warn("[palbase] the expired Idempotency-Keys could not be taken away; the next sweep tries again",{error:n})),this.asService(async n=>{for(let o=0;o<3;o++){let[s]=await n.insertMany([{key:t,fingerprint:r}],{onConflict:["key"],action:"ignore"});if(s)return{claim:{key:t,started:s.started_at}};if(await n.deleteMany({where:{key:t,started_at:{lt:Ct({hours:Fn})}}})>0)continue;let a=await n.findUnique({where:{key:t}});if(a===null)continue;let i=Io(a,r);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 n.updateMany({where:{key:t,completed_at:null,started_at:{lt:Ct({seconds:zn})}},set:{started_at:Hn()}});return c?{claim:{key:t,started:c.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,r){if(!Dt(r.status))return r;let{response:n,kept:o}=await Wn(r),s=se.getStore()?.database;if(!s)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let[a]=await s.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,o.status,JSON.stringify(o.headers),o.body]);if(a?.answered!==!0)throw new rt;return n}async keep(t,r){let{response:n,kept:o}=await Wn(r);try{await this.asService(s=>s.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:Hn(),status_code:o.status,response_headers:o.headers,response_body:o.body}}))}catch(s){S.warn("[palbase] a refusal could not be kept against its Idempotency-Key; a retry runs it again once the key is stale",{error:s})}return n}async release(t){if(await this.releaseOnce(t))return;let r=Date.now()+zn*1e3,n=()=>{Date.now()+Kn>=r||setTimeout(()=>{this.releaseOnce(t).then(o=>o||n())},Kn).unref()};n()}async releaseOnce(t){try{return await this.asService(r=>r.deleteMany({where:{key:t.key,started_at:t.started,completed_at:null}})),!0}catch{return!1}}async asService(t){let r=this.db.request(qo),n;try{n=await t(r.database.palbase.idempotency_keys)}catch(o){throw await r.rollback(o).catch(()=>{}),o}try{await r.commit()}catch(o){throw await r.rollback(o).catch(()=>{}),o}return n}};function Ho(e,t){let r=new Headers(e.headers);return r.set("x-request-id",t),r.set("idempotent-replayed","true"),new Response(e.body===null?null:Buffer.from(e.body,"base64"),{status:e.status,headers:r})}var nt=Symbol("waits");function Jo(e){return new Promise((t,r)=>{let n=setImmediate(()=>t(nt));e.then(o=>{clearImmediate(n),t(o)},o=>{clearImmediate(n),r(o)})})}async function Wn(e){let t=[];e.headers.forEach((i,c)=>{c!=="x-request-id"&&t.push([c,i])});let r=i=>new Response(i,{status:e.status,statusText:e.statusText,headers:e.headers});if(e.body===null)return{response:r(null),kept:{status:e.status,headers:t,body:null}};let n=e.body.getReader(),o=[],s=0;for(;;){let i=n.read(),c=await Jo(i);if(c!==nt&&c.done)break;if(c!==nt&&(o.push(c.value),s+=c.value.byteLength,s<=To))continue;let u=c===nt?i:void 0,f=new ReadableStream({start(y){for(let E of o)y.enqueue(E)},async pull(y){let E=await(u??n.read());u=void 0,E.done?y.close():y.enqueue(E.value)},cancel:y=>n.cancel(y)});return{response:r(f),kept:{status:e.status,headers:t.filter(([y])=>y!=="content-length"&&y!=="content-encoding"),body:null}}}let a=Buffer.concat(o);return{response:r(a),kept:{status:e.status,headers:t,body:a.byteLength===0?null:a.toString("base64")}}}import{createHash as Bo}from"node:crypto";var Nt="/webhooks/palbase",rr="PalbaseErrorEnvelope",Xn="PalbaseBearer",zo={$ref:`#/components/schemas/${rr}`},Fo={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"]},Qn={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Me={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function or(e,t,r){let n={[rr]:Fo},o={},s=[],a=[],i=new Set,c=new Map;for(let g of e){let A=a.find(H=>Vo(H,g));if(A){s.push({route:g.id,handler:er(g),answeredBy:A.id});continue}a.push(g);let b=g.segments.map(H=>typeof H=="string"?H:"{}").join("/");c.has(b)||c.set(b,Go(g.segments.flatMap(H=>typeof H=="string"?[]:[H.param])));let $=c.get(b),w=0,R=`/${g.segments.map(H=>typeof H=="string"?H:`{${$[w++]}}`).join("/")}`,P=t(g),C=st(Yo(g),i),I=g.method!=="GET"&&g.method!=="HEAD",L=H=>{let be=g.params.filter(pe=>pe.kind===H&&pe.schema).map((pe,We)=>dt(pe.schema,`${C}.${H}${We===0?"":`.${We+1}`}`,n));return be.length===0?void 0:be.length===1?be[0]:{allOf:be}},U=$.map(H=>({name:H,in:"path",required:!0,schema:{type:"string"}})),M=L("query");M&&U.push(...nr(M,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:M}]);let q=L("headers");q&&U.push(...nr(q,"header")??[]);let re=r.idempotency===!0&&qe(g);re&&U.push({...Ut,schema:{...Ut.schema}});let Q=I?L("body"):void 0,G={operationId:C};g.controller.name!==""&&(G.tags=[g.controller.name]),U.length>0&&(G.parameters=U),Q&&(G.requestBody={required:!ts(Q),content:{"application/json":{schema:Q}}});let mt=g.params.some(H=>H.schema!==void 0),Fe=r.routes?.(g),me=rs(C,Fe?.throws??[],r.errors);G.responses={...ns(Fe,C,n),...as(P,{validates:mt,hasPathParams:$.length>0,readsBody:I,keyed:re}),...ss(me,C,n)},me.length>0&&(G["x-palbase-errors"]=os(C,me)),P.auth.required&&(G.security=[{[Xn]:[]}]),G["x-palbase-handler"]=er(g);let Ke=g.params.some(H=>H.kind==="optionalUser")||r.databaseSeesCaller;G["x-palbase-auth"]=P.auth.required?"required":Ke?"optional":"public",G["x-palbase-verified-email"]=P.auth.verifiedEmail,G["x-palbase-rate-limit"]=P.limit===!1?!1:{max:P.limit.max,window:P.limit.window},g.meta.upload&&(G["x-palbase-upload"]={bucket:g.meta.upload.bucket,pathTemplate:g.meta.upload.pathTemplate}),(o[R]??={})[g.method.toLowerCase()]=G}for(let g of r.webhooks??[]){let A={operationId:st(`webhooks.${g.name}`,i)};g.cls!==""&&(A.tags=[g.cls]),A.description=g.provider?`${Qn[g.provider]??g.provider}'s deliveries: verified with ${Qn[g.provider]??g.provider}'s signature scheme under the secret in ${g.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${g.signatureHeader} header: verified under the secret in ${g.secretEnv}, then handed to the @On of their event type.`,A.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":{},[g.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:K("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:K("in_progress: the same delivery is being handled; the sender delivers it again",Me),413:K("payload_too_large: the body is over what this sender sends"),500:K("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:K("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",Me)},A["x-palbase-webhook"]=g.provider?{provider:g.provider,secretEnv:g.secretEnv,events:g.events}:{signatureHeader:g.signatureHeader,secretEnv:g.secretEnv,events:g.events},o[`/webhooks/${g.name}`]={post:A}}let u=[...new Set(r.platformEvents??[])].sort();if(u.length>0){let g={operationId:st("webhooks.palbase",i)};g.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.",g.responses={204:{description:"Taken: handled, or a delivery already run"},401:K("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:K("in_progress: the same event is being handled; the platform delivers it again",Me),500:K("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:K("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let A=[...new Set(r.platformEventBuckets??[])].sort();g["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:u,...A.length>0?{buckets:A}:{}},o[Nt]={post:g}}let f=Ko(r.rooms??[],n),y=Object.keys(f).length>0,E={schemas:n,securitySchemes:{[Xn]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},N={openapi:"3.2.0",info:{title:"Palbase backend",version:Bo("sha256").update(JSON.stringify({paths:o,components:E,unreachable:s,...y?{rooms:f}:{}})).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:o,components:E};return s.length>0&&(N["x-palbase-unreachable"]=s),y&&(N["x-palbase-room"]=f),N}function Ko(e,t){let r=[];for(let n of e){let o=n.pattern.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_|_$/g,""),s=(c,u,f,y)=>{let E=it(`Room_${o}_${u}`),N={},g=dt(f,E,N,y);g.$ref===void 0&&(N[E]=g),Wo(n.pattern,c,u,N[E]);for(let[A,b]of Object.entries(N)){if(Object.hasOwn(t,A)&&JSON.stringify(t[A])!==JSON.stringify(b))throw new Error(`@Room("${n.pattern}") ${c} "${u}": its schema is the component ${A}, which another room's event or message names with another schema \u2014 rename one of them`);t[A]=b}return{$ref:`#/components/schemas/${E}`}},a=Object.fromEntries(Object.entries(n.events).map(([c,u])=>[c,s("event",c,u,"answered")])),i=Object.fromEntries(Object.entries(n.messages).map(([c,u])=>[c,s("message",c,u.schema,"sent")]));r.push([n.pattern,{events:a,messages:i,graceMs:n.graceMs}])}return Object.fromEntries(r)}function Wo(e,t,r,n){if(!(!Y(n)||!Y(n.properties))){for(let[o,s]of Object.entries(n.properties))if(s===!0||Y(s)&&Object.keys(s).length===0)throw new Error(t==="event"?`@Room("${e}") event "${r}" has an untyped field "${o}". An untyped payload makes every generated client opaque \u2014 declare its shape.`:`@Room("${e}") message "${r}" has an untyped field "${o}". Inbound payloads reach the server \u2014 declare the shape so it can be validated.`)}}function Vo(e,t){return e.method===t.method&&e.segments.length===t.segments.length&&e.segments.every((r,n)=>typeof r!="string"||r===t.segments[n])}function er(e){return`${e.controller.name}.${e.fn}`}function Yo(e){let t=e.controller.name;if(t.endsWith("Controller")&&(t=t.slice(0,-10)),t!=="")return`${t[0].toLowerCase()}${t.slice(1)}.${e.fn}`;let r=n=>n.charAt(0).toUpperCase()+n.slice(1);return e.method.toLowerCase()+e.segments.map(n=>typeof n=="string"?r(n):`By${r(n.param)}`).join("")}function st(e,t){let r=e;for(let n=2;t.has(r);n++)r=`${e}_${n}`;return t.add(r),r}function Go(e){let t=new Set;return e.map(r=>st(r,t))}function dt(e,t,r,n="sent"){let o=e["~standard"],s=o.jsonSchema?.input;if(typeof s!="function")return{};let a;try{a=s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any",...o.vendor==="zod"?{override:Zo}:{}}})}catch{return{}}let i=it(t);for(;Object.keys(r).some(c=>c===i||c.startsWith(`${i}.`));)i=`${i}_`;return Xo(a,i,r,n)}function Zo(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function Xo(e,t,r,n){let o=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},s=!1,a=u=>u==="#"?(s=!0,`#/components/schemas/${t}`):u.startsWith("#/$defs/")?`#/components/schemas/${t}.${it(es(u.slice(8)))}`:u,i="all";if(n==="sent"){let u=new Set;for(let f of[e,...Object.values(o)])at(f,u);i=u}for(let[u,f]of Object.entries(o))r[`${t}.${it(u)}`]=Je(He(f,a,i));let c=Je(He(e,a,i));return s?(r[t]=c,{$ref:`#/components/schemas/${t}`}):c}var Qo=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"]),It=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),Lt=new Set(["anyOf","oneOf","allOf","prefixItems"]),qt=new Set(["properties","patternProperties","dependentSchemas"]),Y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function He(e,t,r){if(!Y(e))return typeof e=="boolean"?e:{};let n={};for(let[o,s]of Object.entries(e))o==="$ref"&&typeof s=="string"?n.$ref=t(s):o==="const"?(r==="all"||r.has(e))&&(n.const=s):Qo.has(o)?n[o]=s:It.has(o)?n[o]=He(s,t,r):Lt.has(o)&&Array.isArray(s)?n[o]=s.map(a=>He(a,t,r)):qt.has(o)&&Y(s)&&(n[o]=Object.fromEntries(Object.entries(s).map(([a,i])=>[a,He(i,t,r)])));return n}var tr=Number.MAX_SAFE_INTEGER;function Je(e){if(!Y(e))return e;let t={};for(let[n,o]of Object.entries(e))It.has(n)?t[n]=Je(o):Lt.has(n)&&Array.isArray(o)?t[n]=o.map(Je):qt.has(n)&&Y(o)?t[n]=Object.fromEntries(Object.entries(o).map(([s,a])=>[s,Je(a)])):t[n]=o;if("const"in t){let{const:n,...o}=t;t={...o,enum:[n]}}if(t.type==="integer"&&(t.minimum===-tr&&delete t.minimum,t.maximum===tr&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,Y(t.propertyNames)&&Object.keys(t.propertyNames).length===1&&t.propertyNames.type==="string"&&delete t.propertyNames,Array.isArray(t.type)&&t.type.filter(n=>n!=="null").length>1&&Object.keys(t).length===1)return{anyOf:t.type.map(n=>({type:n}))};let r=t.anyOf;if(Array.isArray(r)&&r.length===2&&Object.keys(t).length===1){let n=r.findIndex(s=>Y(s)&&Object.keys(s).length===1&&s.type==="null"),o=r[1-n];if(n!==-1&&Y(o)&&typeof o.type=="string")return{...o,type:[o.type,"null"]}}return t}function at(e,t){if(Y(e)){for(let r of["anyOf","oneOf"]){let n=e[r];if(!Array.isArray(n)||n.length<2||!n.every(Y))continue;if(n.every(s=>"const"in s||Array.isArray(s.enum)))for(let s of n)t.add(s);let o=n.map(s=>Y(s.properties)?s.properties:{});for(let s of Object.keys(o[0]))if(o.every(a=>Y(a[s])&&"const"in a[s]))for(let a of o)t.add(a[s])}for(let[r,n]of Object.entries(e))if(It.has(r))at(n,t);else if(Lt.has(r)&&Array.isArray(n))for(let o of n)at(o,t);else if(qt.has(r)&&Y(n))for(let o of Object.values(n))at(o,t)}}function es(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function it(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function nr(e,t){if(e.type!=="object"||typeof e.properties!="object"||e.properties===null)return;let r=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([n,o])=>({name:n,in:t,required:r.has(n),schema:o}))}function ts(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function K(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:zo}}}}function ns(e,t,r){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 n=dt(e.returns.schema,`${t}.response`,r,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:n}:n}}}}}function rs(e,t,r){let n=new Set,o=[];for(let s of t){if(n.has(s.code))continue;n.add(s.code);let a=r?.get(s.code);if(a&&s.status!==a.status)throw new Error(`${e} throws "${s.code}" with status ${s.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`);o.push({...s,...a?.data?{data:a.data}:{}})}return o}function os(e,t){let r=Object.create(null);for(let n of t){let o=n.name.charAt(0).toLowerCase()+n.name.slice(1),s=Object.hasOwn(r,o)?r[o]:void 0;if(s)throw new Error(`${e} throws "${s.code}" and "${n.code}" under one name, "${n.name}" \u2014 every client names an error case after it; give one of them its own defineError`);r[o]={status:n.status,code:n.code,hasData:n.data!==void 0,description:""}}return r}function ss(e,t,r){let n=new Map;for(let s of e)n.set(s.status,[...n.get(s.status)??[],s]);let o={};for(let s of[...n.keys()].sort((a,i)=>a-i)){let a=n.get(s),i=a.map(c=>{let u={error:{type:"string",const:c.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},f=["error","error_description","status","request_id"];return c.data&&(u.data=dt(c.data,`${t}.${c.code}.data`,r,"answered"),f.push("data")),{type:"object",properties:u,required:f}});o[String(s)]={description:a.map(c=>c.code).join(" | "),content:{"application/json":{schema:i.length===1?i[0]:{oneOf:i}}}}}return o}function as(e,t){let r={},n=[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),o=[n.length>0&&`bad_request: ${n.join("; or ")}`,t.keyed&&"invalid_idempotency_key: the Idempotency-Key is over 255 characters"].filter(Boolean);return o.length>0&&(r[400]=K(o.join("; "))),e.auth.required&&(r[401]=K("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&&(r[403]=K("email_not_verified: the user's email address is not verified")),t.keyed&&(r[409]=K("idempotency_key_in_use: a request with this Idempotency-Key is still running",Me)),t.readsBody&&(r[413]=K("payload_too_large: the body is over the app's body limit")),t.keyed&&(r[422]=K("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(r[429]=K("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Me)),r[500]=K("internal_error: the handler failed; the app's log has it under the request id"),r[503]=K(`${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":""}`,Me),r}var ct=class{windows=new Map;now;maxKeys;constructor(t=Date.now,r=1e5){this.now=t,this.maxKeys=r}take(t,r){let n=this.now(),o=this.windows.get(t);if((!o||n>=o.resetAt)&&(o={count:0,resetAt:n+r.window*1e3}),this.windows.delete(t),this.windows.set(t,o),this.windows.size>this.maxKeys&&this.windows.delete(this.windows.keys().next().value),o.count++,o.count>r.max)return Math.max(1,Math.ceil((o.resetAt-n)/1e3))}reserve(t,r){let n=this.take(t,r);return n!==void 0?{wait:n}:{window:this.windows.get(t).resetAt}}give(t,r){let n=this.windows.get(t);n&&n.resetAt===r&&n.count>0&&n.count--}};function ut(e,t){let n=e.get("x-forwarded-for")?.split(",").map(o=>o.trim()).filter(Boolean).at(-1);return is(n??t??"unknown")}function is(e){let t=e.replace(/^\[|\]$/g,"").replace(/%.*$/,"");if(!t.includes(":"))return e;let r=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(t);if(r)return r[1];let[n,o=""]=t.split("::"),s=n?n.split(":"):[],a=o?o.split(":"):[],i=t.includes("::")?[...s,...Array(8-s.length-a.length).fill("0"),...a]:s;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 sr(e){let t=[];for(let r of e){let n=T(r,Re),o=T(r,Se)??[];if(o.length===0)throw new TypeError(`@Controller ${r.name} has no routes: a controller with nothing to serve is a mistake`);let s=T(r,wt)??new Map;for(let a of o){let i=`${n.basePath}${a.subpath}`||"/",c=i.split("/").filter(Boolean).map(f=>{let y=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(f)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(f);return y?{param:y[1]}:f});if(typeof c[0]=="string"&&_e.has(c[0]))throw new TypeError(`${r.name}.${a.fn}: ${a.method} ${i} \u2014 /${c[0]} is the platform's; a route is served elsewhere`);let u=[...s.get(a.fn)??[]].sort((f,y)=>f.index-y.index);for(let f of u)if(f.kind==="param"&&!c.some(y=>typeof y!="string"&&y.param===f.name))throw new TypeError(`${r.name}.${a.fn}: @Param("${f.name}") names no {${f.name}} in ${a.method} ${i}`);t.push({id:`${a.method} ${i}`,method:a.method,segments:c,controller:r,fn:a.fn,params:u,meta:a,controllerAuth:n.options.auth})}}return wn(t),t}function Ht(e,t,r){let n=r.split("/").filter(Boolean);for(let o of e){if(o.method!==t||o.segments.length!==n.length)continue;let s={},a=!0;for(let i=0;i<n.length&&a;i++){let c=o.segments[i];if(typeof c=="string")a=c===n[i];else try{s[c.param]=decodeURIComponent(n[i])}catch{return{malformed:!0}}}if(a)return{route:o,params:s}}return null}function Bt(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Be(e,t,r,n,o){return zt(e,e?Bt(e.requests,t):void 0,r,n,o)}var ar={role:"service",claims:{}};async function zt(e,t,r,n,o){if(!e||!t)return o();let s=u=>S.warn(`[palbase] ${n}: 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 ${u} 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:u}),a=e.app.request(t,{signal:r,heldIdle:s}),i=se.getStore();i&&(i.database=a.database);let c;try{c=await o()}catch(u){throw await a.rollback(u).catch(f=>S.error("[palbase] the request's transaction could not be rolled back",{error:f})),u}try{await a.commit()}catch(u){throw await a.rollback(u).catch(f=>S.error("[palbase] the request's transaction could not be rolled back",{error:f})),u}return c}var us=1024*1024,ls=20,fs={max:300,window:60},De="/_palbase/jobs",ir=50,ms=4096,ps=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,lt=1e4,hs=6e4;function gs(e,t){let r=e.meta.options.auth??e.controllerAuth??t??!0;if(typeof r=="boolean")return{required:r,verifiedEmail:!1};if((r.role??"").trim()!==""||(r.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:r.required!==!1,verifiedEmail:r.verifiedEmail===!0}}var V=class extends Error{constructor(r,n,o,s,a,i){super(o);this.status=r;this.code=n;this.data=s;this.retryAfter=a;this.challenge=i}status;code;data;retryAfter;challenge};function ys(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 ws=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function bs(e,t){let r=new Headers(e.headers);for(let n of ws)r.delete(n);return e.url!==""&&(r.delete("content-encoding"),r.delete("content-length")),r.set("x-request-id",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:r})}function dr(e,t){let r=(e.get("vary")??"").split(",").map(n=>n.trim()).filter(Boolean);r.includes("*")||r.some(n=>n.toLowerCase()===t.toLowerCase())||e.set("vary",[...r,t].join(", "))}function de(e,t,r,n={}){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json","x-request-id":r,...n}})}function x(e,t){let r={error:e.code,error_description:e.message,status:e.status,request_id:t};e.data!==void 0&&(r.data=e.data);let n={};return e.retryAfter!==void 0&&(n["retry-after"]=String(e.retryAfter)),e.challenge!==void 0&&(n["www-authenticate"]=e.challenge),de(e.status,r,t,n)}var pr=new Set([0,429,502,503,504]);function cr(e,t,r,n){if(n?.aborted)return S.info(`[palbase] ${r}: the client left before its answer`),x({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof V)return x({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(tt(e)){let s=e;return s.status>=500&&S.error(`[palbase] ${r} answered ${s.status} ${s.error}`,{error:e}),de(s.status,qn(s,t),t,s.retryAfter!==void 0?{"retry-after":String(s.retryAfter)}:{})}let o=hr(e,r);return o?x(o,t):(e instanceof $e?S.error(`[palbase] ${r}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):S.error(`[palbase] unhandled error in ${r}`,{error:e}),x({status:500,code:"internal_error",message:"The request could not be completed"},t))}function hr(e,t){if(e instanceof Ze)return S.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 $e&&pr.has(e.status))return S.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 r=fr(e);if(r!==void 0)return S.warn(`[palbase] ${t}: the database connection ${r==="lost"?"was lost":"could not be opened"}`,{error:e}),{status:503,code:"database_unavailable",message:"The database is temporarily unavailable",data:{retrySafe:r==="never"},retryAfter:1}}function vs(e){return e instanceof Ze||e instanceof $e&&pr.has(e.status)||fr(e)!==void 0||tt(e)&&e.status===503&&mr(e)}async function Jt(e,t,r){let n=await e["~standard"].validate(t);if(n.issues){let o=n.issues.slice(0,ls).map(a=>({field:(a.path??[]).map(i=>String(typeof i=="object"&&i!==null&&"key"in i?i.key:i)).join("."),message:a.message})),s=n.issues.length-o.length;throw new V(400,"bad_request",`${r} failed validation`,s>0?{fields:o,more:s}:{fields:o})}return n.value}async function ft(e,t){let r=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>t)throw new V(413,"payload_too_large",`Request body exceeds ${t} bytes`);if(!e.body)return new Uint8Array(0);let n=e.body.getReader(),o=[],s=0;for(;;){let{done:c,value:u}=await n.read();if(c)break;if(s+=u.byteLength,s>t)throw await n.cancel().catch(()=>{}),new V(413,"payload_too_large",`Request body exceeds ${t} bytes`);o.push(u)}let a=new Uint8Array(s),i=0;for(let c of o)a.set(c,i),i+=c.byteLength;return a}function ks(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return ie(t)}function $s(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 Es(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 Rs=/^[A-Za-z0-9._:-]{8,128}$/,Ss=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Os={max:20,window:60},_s=10*6e4,xs=1e4,ze=class extends Error{constructor(r){super("too many unknown tokens from this address");this.wait=r}wait},Ft=class{constructor(t,r){this.limiter=t;this.now=r}limiter;now;known=new Map;async ask(t,r,n){let o=cs("sha256").update(t).digest("hex"),s=(this.known.get(o)??0)>this.now(),a=`token-misses\0a:${r}`,i;if(!s){let u=this.limiter.reserve(a,Os);if("wait"in u)throw new ze(u.wait);i=u}let c=await n();if(!c)throw this.known.delete(o),new Ge("unknown_token","The token is not one of the app's");return i&&this.limiter.give(a,i.window),this.known.delete(o),this.known.set(o,this.now()+_s),this.known.size>xs&&this.known.delete(this.known.keys().next().value),c}};function _i(e){let t=new et(e.modules),r=sr(t.controllers.map(d=>d.cls)),n=new Map(r.map(d=>[d,gs(d,e.auth)]));for(let[d,m]of n){if(!m.required&&d.params.some(l=>l.kind==="user"))throw new TypeError(`${d.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(d.meta.upload&&m.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 o=new Map;for(let d of r)for(let m of d.params)m.kind==="resolve"&&o.set(m,t.dependencyOf(d.controller,m.resolver,`${d.id} @Resolve(${m.resolver?.name})`));let s=new Map;for(let d of t.jobProviders){let m=t.get(d),l=T(d,ue),p=s.get(l.name);if(p)throw new TypeError(`@Job "${l.name}" is ${p.owner} and ${d.name}: a job's name is its own \u2014 name one of them`);s.set(l.name,{declaration:l,owner:d.name,run:h=>m.run(h)})}let a=new Set,i=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(s.size>ir)throw new TypeError(`${s.size} @Job classes: a machine runs ${ir} jobs at most`);s.size>0&&!e.platform&&S.info(`[palbase] ${s.size} @Job(s): the platform runs them on a machine; nothing calls them here`);let c=$n(t.rooms.map(d=>({cls:d,instance:t.get(d)})),{run:(d,m,l,p)=>se.run({requestId:se.getStore()?.requestId??"",...d?.id?{userId:d.id}:{}},()=>zt(e.database,e.database?d?.id?Bt(e.database.requests,Qe(d)):ar:void 0,l,m,async()=>{let h=await p();if(l?.aborted)throw new Error(`realtime gave up on ${m} before it ended`);return h})),broadcast:d=>e.server.realtime.broadcast({body:{messages:d}}),isOutage:vs});c.declarations.length>0&&!e.platform&&S.info(`[palbase] ${c.declarations.length} @Room(s): realtime tells a machine of them; nothing does here`);let u=new Set,f=e.database!==void 0||e.contractOnly?.database===!0;if(f){for(let d of r)if(qe(d)&&d.params.some(m=>m.kind==="headers"&&m.schema!==void 0&&Zn(m.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 y=e.database?new ot(e.database.app):void 0,E=Ds(e.cors),N=e.now??Date.now,g=new ct(e.now),A=new Ft(g,e.now??Date.now),b=e.maxBodyBytes??us,$=d=>{let m=d.meta.options.rateLimit??e.rateLimit??fs;return m!==!1&&m.max>0&&m.window>0?m:!1},w=e.env??process.env,R=Tn(t.webhooks,d=>t.get(d),w,{secrets:e.contractOnly===void 0}),P=R.size===0&&s.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(w).filter(d=>typeof d[1]=="string"&&!on(d[0])))),C=new Map([...R.keys()].map(d=>[d,{seen:new Set,inflight:new Set}])),I=new Map([...R.keys()].map(d=>[d,{counts:new Map,at:void 0}])),L,U=()=>L??=or(r,d=>({auth:n.get(d),limit:$(d)}),{databaseSeesCaller:f,idempotency:f,webhooks:[...R.values()].map(d=>({name:d.name,cls:d.cls.name,provider:d.provider,signatureHeader:d.signatureHeader,secretEnv:d.secretEnv,events:[...d.events.keys()]})),platformEvents:[...M.keys()],rooms:c.declarations,platformEventBuckets:As(M),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),M=new Map;for(let[d,m]of Object.entries(e.events??{}))M.set(d,m.map(l=>({name:`palbase(${d})`,call:p=>l(p)})));for(let d of t.eventProviders){let m=t.get(d);for(let{event:l,fn:p,bucket:h}of T(d,he)??[]){if(!ln.test(l))throw new TypeError(`@On("${l}") on ${d.name}.${p}: 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`);M.has(l)||M.set(l,[]),M.get(l).push({name:`${d.name}.${p}`,bucket:h,call:async(k,v)=>m[p](k,v)})}}let q=new Set,re=new Set;an(e.server);async function Q(d,m){let l;try{l=await nn(d,e.webhookSecret,{now:e.now})}catch(p){if(p instanceof Ye)return x({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${p.code}`},m);throw p}if(ie(l.data),q.has(l.id))return new Response(null,{status:204,headers:{"x-request-id":m}});if(re.has(l.id))return x({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},m);re.add(l.id);try{let p;try{await Be(e.database,null,void 0,`event ${l.type}`,async()=>{for(let h of M.get(l.type)??[])if(!(h.bucket!==void 0&&Ts(l)!==h.bucket))try{await h.call(l,{requestId:m})}catch(k){throw p=h.name,k}})}catch(h){return S.error(`[palbase] ${p??"the delivery"} failed on ${l.type} ${l.id}; the platform delivers it again`,{error:h}),x({status:500,code:"handler_failed",message:"The event could not be handled"},m)}return q.add(l.id),q.size>lt&&q.delete(q.values().next().value),new Response(null,{status:204,headers:{"x-request-id":m}})}finally{re.delete(l.id)}}async function G(d,m={}){let l=d.headers.get("origin");if(E&&l!==null){let p=E.allows(l);if(d.method==="OPTIONS"&&d.headers.has("access-control-request-method"))return p?new Response(null,{status:204,headers:E.preflight(l,d.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let h=await Gt(d,m);if(p)for(let[k,v]of Object.entries(E.headers(l)))k==="vary"?dr(h.headers,v):h.headers.set(k,v);else dr(h.headers,"Origin");return h}return Gt(d,m)}async function mt(d,m,l,p){if(!d.headers.get(l.scheme.header))return me(l,"missing_signature",p);let h={headers:d.headers,body:await ft(d,l.scheme.maxBytes(b)),url:An(d,m)},k;try{k=l.scheme.check(h,N()/1e3)}catch{return me(l,"signature_mismatch",p,"check_failed")}if(typeof k=="string")return me(l,k,p);let v=l.events.get(k.type);if(!v)return S.info(`[palbase] webhook ${l.name}: no @On takes "${k.type}"; acknowledged`),de(200,{ok:!0,handled:!1},p);let j=C.get(l.name),_=k.event,ee=[];if(k.id!==void 0){if(j.seen.has(k.id))return de(200,{ok:!0,handled:!1,duplicate:!0},p);ee=[k.id]}else if(k.ids&&Array.isArray(_)){let O=k.ids,z=_.map((B,ce)=>[B,O[ce]]).filter(([,B])=>B===void 0||!j.seen.has(B));if(z.length===0)return de(200,{ok:!0,handled:!1,duplicate:!0},p);_=z.map(([B])=>B),ee=z.flatMap(([,B])=>B===void 0?[]:[B])}if(ee.some(O=>j.inflight.has(O)))return x({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},p);ie(_);for(let O of ee)j.inflight.add(O);let W;try{W=await Be(e.database,null,void 0,`webhook ${l.name}`,()=>v.call(_,{env:P,requestId:p,environmentId:e.projectId??""}))}catch(O){let z=hr(O,`webhook ${l.name}`)??Ps(O,l.name);return z?x(z,p):(S.error(`[palbase] ${v.name} failed on ${l.name} "${k.type}"; the sender delivers it again`,{error:O}),x({status:500,code:"handler_failed",message:"The event could not be handled"},p))}finally{for(let O of ee)j.inflight.delete(O)}for(let O of ee)j.seen.add(O),j.seen.size>lt&&j.seen.delete(j.seen.values().next().value);return Fe(W,l,p)}function Fe(d,m,l){if(d instanceof Response)return d;if(typeof d=="string"){let p=m.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(d,{status:200,headers:{"content-type":p,"x-request-id":l}})}return de(200,d??{ok:!0,handled:!0},l)}function me(d,m,l,p=m){let h=I.get(d.name);h.counts.set(p,(h.counts.get(p)??0)+1);let k=N();return(h.at===void 0||k-h.at>=hs)&&(Ke(d.name),h.at=k),x({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${m}`},l)}function Ke(d){let m=I.get(d).counts;if(m.size===0)return;let l=[...m.values()].reduce((p,h)=>p+h,0);S.warn(`[palbase] webhook ${d}: ${l} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(m)}),m.clear()}function H(d){let m=d.split("/").filter(Boolean);return m.length===2&&m[0]==="webhooks"?R.get(m[1]):void 0}async function be(d,m,l,p){let h=m.pathname===De;if(d.method!==(h?"GET":"POST"))return x({status:405,code:"method_not_allowed",message:h?"The jobs are listed with GET":"A job is run with POST"},p);let k=h?new Uint8Array(0):await ft(d,ms);try{await ht({secret:l,signature:d.headers.get("palbase-signature"),body:k,now:e.now})}catch(F){if(F instanceof Ye)return x({status:401,code:"invalid_signature",message:`The jobs are the platform's to call: ${F.code}`},p);throw F}if(h){let F=[...s.values()].map(({declaration:Z})=>({name:Z.name,schedule:Z.schedule,timeout:Z.timeout,retry:Z.retries}));return de(200,{jobs:F},p,{"cache-control":"no-store"})}let v=m.pathname.slice(De.length+1),j=s.get(v);if(!j)return x({status:404,code:"job_not_found",message:`This version has no job ${JSON.stringify(v)}`},p);let _;try{_=JSON.parse(new TextDecoder().decode(k))}catch{return x({status:400,code:"bad_request",message:"A run is the JSON {job, run_id, scheduled_at, attempt}"},p)}let{job:ee,run_id:W,scheduled_at:O,attempt:z}=_??{};if(ee!==v||typeof W!="string"||W===""||typeof O!="string"||!ps.test(O)||Number.isNaN(Date.parse(O))||!Number.isInteger(z)||z<1)return x({status:400,code:"bad_request",message:`A run of ${v} is the JSON {job: "${v}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},p);let B=`${W}#${String(z)}`;if(a.has(B))return new Response(null,{status:204,headers:{"x-request-id":p}});if(i.has(B))return x({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},p);i.add(B);let ce={env:P,environmentId:e.projectId??"",job:v,runId:W,scheduledAt:new Date(O),attempt:z};try{await zt(e.database,e.database?ar:void 0,d.signal,`job ${v}`,async()=>{if(await j.run(ce),d.signal.aborted)throw new Error(`the platform gave up on this attempt of ${v} before it ended`)})}catch(F){return d.signal.aborted||S.error(`[palbase] job ${v} failed (run ${W}, attempt ${String(z)})`,{error:F}),x({status:500,code:"job_failed",message:`The job ${v} failed; the platform tries it again`},p)}finally{i.delete(B)}return a.add(B),a.size>lt&&a.delete(a.values().next().value),new Response(null,{status:204,headers:{"x-request-id":p}})}async function pe(d,m,l,p){if(d.method!=="POST")return x({status:405,code:"method_not_allowed",message:`${p} is POSTed`},l);let h;try{tn({signature:d.headers.get("palbase-signature"),now:e.now}),h=await ft(d,1048576),await ht({secret:m,signature:d.headers.get("palbase-signature"),body:h,now:e.now})}catch(v){if(v instanceof Ye)return x({status:401,code:"invalid_signature",message:`${p} is the platform's to call: ${v.code}`},l);throw v}let k;try{k=JSON.parse(new TextDecoder().decode(h))}catch{return x({status:400,code:"bad_request",message:`${p} is JSON`},l)}return typeof k!="object"||k===null||!Object.hasOwn(k,"call")||k.call!==new URL(d.url).pathname?x({status:401,code:"invalid_signature",message:`${p} is the platform's to call: signed_for_another_call`},l):{body:k}}async function We(d,m,l,p,h){let k=await pe(m,l,p,`An upload's ${d}`);if(k instanceof Response)return k;let v=bn(d,k.body);if(typeof v=="string")return x({status:400,code:"bad_request",message:`An upload's ${d}: ${v}`},p);if(d==="complete"){if(u.has(v.uploadId))return x({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},p);u.add(v.uploadId),u.size>lt&&u.delete(u.values().next().value)}let j=Ht(r,v.method,v.route);if(!j||"malformed"in j||!j.route.meta.upload)return x({status:404,code:"not_found",message:`No upload route for ${v.method} ${v.route}`},p);let{route:_,params:ee}=j,W=j.route.meta.upload,O=Es(v.user);if(O&&Zt(h,O.id),n.get(_).required&&!O)throw new V(401,"unauthorized","This route needs a signed-in user");if(d==="authorize"){let ce=$(_);if(ce!==!1){let Z=g.take(`${_.id}\0${pn(v.user,v.client)}`,ce);if(Z!==void 0)throw new V(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:Z},Z)}let F=yn(W.pathTemplate,{userId:O?.id??null,uploadId:v.uploadId,filename:v.filename});if("problem"in F)throw new V(400,"bad_request",F.problem);return await Be(e.database,Qe(v.user),m.signal,_.id,async()=>{let Z={request:m,query:new URLSearchParams(v.query),params:ee,user:O,body:v.body===void 0||v.body===null?{}:ie(v.body),requestId:p};await Yt(_,Z);for(let ve of _.params)(ve.kind==="query"||ve.kind==="body"&&v.body!==void 0)&&await lr(ve,Z)}),de(200,{bucket:W.bucket,path:F.path},p)}h.endpoint=_.id.slice(_.id.indexOf(" ")+1);let z=new URLSearchParams(v.query),B=v.body===null||v.body===void 0?{}:ie(v.body);return pt(_,{request:m,query:z,params:ee,user:O,body:B,requestId:p,uploadedObject:ie(v.uploadedObject)},Qe(v.user))}async function wr(d,m,l,p){let h=await pe(m,l,p,`A room's ${d}`);if(h instanceof Response)return h;let k=await c.serve(d,h.body,m.signal);return"code"in k?x({status:k.status,code:k.code,message:k.message,retryAfter:k.retryAfter},p):"body"in k?de(200,k.body,p):new Response(null,{status:204,headers:{"x-request-id":p}})}async function Yt(d,m){let l=[],p={params:Object.freeze({...m.params}),user:ie(m.user),headers:d.meta.upload?new Headers:m.request.headers,requestId:m.requestId};for(let h of d.params)h.kind==="resolve"&&(l[h.index]=await o.get(h).resolve(p,h.options));return l}async function pt(d,m,l,p){let h=t.get(d.controller),k=await Be(e.database,l,m.request.signal,d.id,async()=>{let v=await Yt(d,m);for(let _ of d.params)_.kind!=="resolve"&&(v[_.index]=await lr(_,m));p?.ran();let j=await h[d.fn](...v);if(m.uploadedObject&&m.request.signal.aborted)throw new Error(`storage gave up on ${d.id}'s upload before it was answered`);return p?p.record(ur(j,m.requestId)):j});return p?k:ur(k,m.requestId)}async function Gt(d,m){let l=d.headers.get("x-request-id")??"",p=Rs.test(l)?l:`req_${crypto.randomUUID()}`,h=performance.now(),k=new URL(d.url).pathname,v={endpoint:k},j=await br(d,m,p,v);return e.telemetry?.record({requestId:p,method:d.method,endpoint:v.endpoint,path:k,status:j.status,durationMs:performance.now()-h,userId:v.userId}),j}function Zt(d,m){d.userId=m;let l=se.getStore();l&&(l.userId=m)}async function br(d,m,l,p){return se.run({requestId:l},async()=>{let h=new URL(d.url),k=`${d.method} ${h.pathname}`;try{if(h.pathname===Nt&&M.size>0)return d.method!=="POST"?x({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},l):e.webhookSecret?await Q(d,l):x({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},l);let v=H(h.pathname);if(v)return k=`webhook ${v.name}`,d.method!=="POST"?x({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},l):await mt(d,h,v,l);if(e.platform&&(h.pathname===De||h.pathname.startsWith(`${De}/`)))return k=h.pathname===De?"jobs":`job ${h.pathname.slice(De.length+1)}`,await be(d,h,e.platform.secret,l);if(e.platform&&(h.pathname===Et||h.pathname===fn)){let D=h.pathname===Et?"authorize":"complete";return k=`upload ${D}`,await We(D,d,e.platform.secret,l,p)}if(e.platform&&h.pathname.startsWith(`${Rt}/`)){let D=h.pathname.slice(Rt.length+1);return k=`room ${D}`,await wr(D,d,e.platform.secret,l)}if(js(h.pathname))return x({status:404,code:"not_found",message:`No route for ${d.method} ${h.pathname}`},l);let j=Ht(r,d.method,h.pathname);if(j&&"malformed"in j)return x({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},l);if(!j)return x({status:404,code:"not_found",message:`No route for ${d.method} ${h.pathname}`},l);let{route:_,params:ee}=j;if(k=_.id,p.endpoint=_.id.slice(_.id.indexOf(" ")+1),_.meta.upload)throw new V(400,"upload_required",`${_.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let W=n.get(_),O=null,z=null,B=d.headers.get("authorization")??"",ce=/^(bearer|dpop)\s+(\S+)$/i.exec(B),F=ce?.[2],Z=ce?.[1].toLowerCase()==="dpop";if(F)try{let D=!Z&&e.tokens&&!Ss.test(F)&&e.tokens.accepts(F)?e.tokens:void 0,ke=D?await A.ask(F,ut(d.headers,m.remoteAddress),()=>Be(e.database,null,d.signal,"token",()=>D.resolve(F))):await e.verifier.verify(F,Z?{proof:d.headers.get("dpop"),method:d.method,url:rn(d.headers,h)}:void 0);O=$s(ke),z=ke.claims}catch(D){if(!W.required&&(D instanceof Ge||D instanceof Ze||D instanceof ze))O=null;else throw D instanceof ze?new V(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:D.wait},D.wait):D instanceof Ge?new V(401,"invalid_token","The access token is not valid",{reason:D.reason},void 0,ys(D.reason)):D}else if(B!==""&&W.required)throw new V(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(O&&Zt(p,O.id),W.required&&!O)throw new V(401,"unauthorized","This route needs a signed-in user");if(W.verifiedEmail&&!O?.emailVerified)throw new V(403,"email_not_verified","This route needs a verified email address");let ve=$(_);if(ve!==!1){let D=O?`u:${O.id}`:`a:${ut(d.headers,m.remoteAddress)}`,ke=g.take(`${_.id}\0${D}`,ve);if(ke!==void 0)throw new V(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:ke},ke)}let Ve=d.method==="GET"||d.method==="HEAD"?void 0:await ft(d,b),vr=Ve===void 0?void 0:ks(Ve),Xt={request:d,query:h.searchParams,params:ee,user:O,body:vr,requestId:l},Qt=y&&Ve!==void 0&&qe(_)?Yn(d.method,d.headers):void 0;if(!y||Qt===void 0)return await pt(_,Xt,z);let kr={role:Bt(e.database.requests,z).role,uid:O?.id??`a:${ut(d.headers,m.remoteAddress)}`},en=!1;return await y.serve({key:Qt,caller:kr,method:d.method,uri:`${h.pathname}${h.search}`,body:Ve},D=>pt(_,Xt,z,{record:D,ran:()=>{en=!0}}),{requestId:l,refusal:D=>x(D,l),failure:D=>cr(D,l,k,d.signal),ran:()=>en})}catch(v){return cr(v,l,k,d.signal)}})}return{handle:G,routes:r.map(d=>d.id),contract:U,start:()=>t.start(),stop:async()=>{c.close();for(let d of I.keys())Ke(d);await t.shutdown(),await e.telemetry?.flush()}}}function Ts(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function As(e){let t=new Set;for(let[r,n]of e)if($t(r))for(let o of n){if(o.bucket===void 0)return;t.add(o.bucket)}return t.size===0?void 0:[...t].sort()}function ur(e,t){return e instanceof Response?bs(e,t):e==null?new Response(null,{status:204,headers:{"x-request-id":t}}):de(200,e,t)}function Ps(e,t){if(!(!tt(e)||e.status!==503||!mr(e)))return S.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 js(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return _e.has(decodeURIComponent(t))}catch{return _e.has(t)}}var Cs="GET, POST, PUT, PATCH, DELETE, QUERY",Ms=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function Ds(e){if(!e)return;if(e.origins!=="*"){for(let n of e.origins)if(!Ms.test(n)||n.startsWith("http://")&&!/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(n))throw new TypeError(`cors origin ${JSON.stringify(n)} is https://host[:port] (http only for localhost), with no path`)}let t=e.origins==="*"?null:new Set(e.origins),r=String(e.maxAge??600);return{allows:n=>t===null||t.has(n),headers:n=>({"access-control-allow-origin":t===null?"*":n,"access-control-expose-headers":"idempotent-replayed, retry-after, x-request-id",vary:"Origin"}),preflight:(n,o)=>({"access-control-allow-origin":t===null?"*":n,"access-control-allow-methods":Cs,"access-control-allow-headers":o&&/^[A-Za-z0-9-]+(\s*,\s*[A-Za-z0-9-]+)*$/.test(o)?o:"authorization, content-type","access-control-max-age":r,vary:"Origin"})}}async function lr(e,t){switch(e.kind){case"body":return Jt(e.schema,t.body??{},"Request body");case"query":return Jt(e.schema,ie(Object.fromEntries(t.query)),"Query parameters");case"headers":{let r={};return t.request.headers.forEach((n,o)=>r[o.toLowerCase()]=n),ie(r),e.schema?Jt(e.schema,r,"Request headers"):r}case"param":return t.params[e.name];case"user":case"optionalUser":return ie(t.user);case"req":return t.request;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 r=t.request.headers;return ie({sdkVersion:r.get("x-palbase-sdk-version"),appVersion:r.get("x-palbase-client-version"),platform:r.get("x-platform"),osVersion:r.get("x-os-version")})}}}var Wt=720*3600;function Kt(e){return e instanceof $e&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function gr(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),Wt)}function yr(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var Vt=class{filling=new Map;async get(t){try{let r=await Ee.cache.getCacheEntry({query:{key:t}});return r.data.found?r.data.value??null:null}catch(r){if(!Kt(r))throw r;return S.warn("cache: a read could not reach the cache; it is a miss",{key:t,status:r.status}),null}}async set(t,r,n){try{await Ee.cache.putCacheEntry({query:{key:t},body:{value:yr(r),ttl:gr(n)}})}catch(o){if(!Kt(o))throw o;S.warn("cache: a write could not reach the cache; it is let go",{key:t,status:o.status})}}async del(t){await Ee.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await Ee.cache.incrementCacheEntry({query:{key:t}})).data.value}getOrSet(t,r,n){let o=this.filling.get(t);if(o)return o;let s=(async()=>{try{let a;try{a=(await Ee.cache.getCacheEntry({query:{key:t}})).data}catch(c){if(!Kt(c))throw c;S.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 n();return await this.set(t,i,r),i}finally{this.filling.delete(t)}})();return this.filling.set(t,s),s}},Pi=sn("Cache",new Vt);function ji(e={}){let t=e.maxEntries??5e4,r=e.now??(()=>Date.now()),n=new Map,o=new Map,s=u=>{let f=n.get(u);if(f&&f.expiresAt<=r()){n.delete(u);return}return f},a=()=>{let u=r();for(let[y,E]of n)E.expiresAt<=u&&n.delete(y);if(n.size<t)return;let f=[...n.entries()].sort((y,E)=>y[1].expiresAt-E[1].expiresAt);for(let[y]of f.slice(0,Math.ceil(f.length/4)))n.delete(y)},i=async(u,f,y)=>{n.size>=t&&!n.has(u)&&a(),n.set(u,{value:yr(f),expiresAt:r()+(gr(y)??Wt)*1e3})};return{get:async u=>{let f=s(u);return f?structuredClone(f.value):null},set:i,async del(u){n.delete(u)},async incr(u){let f=s(u),y=(typeof f?.value=="number"&&Number.isInteger(f.value)?f.value:0)+1;return n.set(u,{value:y,expiresAt:f?.expiresAt??r()+Wt*1e3}),y},getOrSet(u,f,y){let E=s(u);if(E)return Promise.resolve(structuredClone(E.value));let N=o.get(u);if(N)return N;let g=(async()=>{try{let A=await y();return await i(u,A,f),A}finally{o.delete(u)}})();return o.set(u,g),g}}}export{vt as a,he as b,Oe as c,Ls as d,qs as e,Hs as f,Js as g,Bs as h,zs as i,Fs as j,Ks as k,Ws as l,Vs as m,Ys as n,Gs as o,Zs as p,Xs as q,Qs as r,ea as s,ta as t,na as u,ra as v,oa as w,sa as x,aa as y,ia as z,T as A,da as B,ca as C,pa as D,ha as E,ka as F,$a as G,Ea as H,Ra as I,Sa as J,Oa as K,_a as L,Pa as M,J as N,Un as O,Nn as P,In as Q,wo as R,La as S,Ja as T,Ba as U,za as V,Fa as W,Ka as X,Wa as Y,Va as Z,Ya as _,ni as $,us as aa,_i as ba,Wt as ca,Pi as da,ji as ea};
|