palbase 0.3.3 → 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/{UXRIXHHY.js → 2AT72FFB.js} +2 -2
- package/dist/chunks/{IXHR57QC.js → 3OIKIBMG.js} +2 -2
- package/dist/chunks/{YWOS5WH2.js → 6JO3UVPT.js} +2 -2
- package/dist/chunks/{P5JIZEPB.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/{47V66C2X.js → FS222NNP.js} +2 -2
- package/dist/chunks/{4AQYBTIN.js → IVDNNHII.js} +2 -2
- package/dist/chunks/{PRM2UXWG.js → ODFLUINN.js} +1 -1
- package/dist/chunks/{OKZJIY6F.js → RKNVSAGY.js} +1 -1
- package/dist/chunks/ST2NZ4TZ.js +4 -0
- package/dist/chunks/{PB7UKHCY.js → SUNHFMDO.js} +2 -2
- package/dist/chunks/{TJ5SQTW5.js → TRHIZOIS.js} +3 -3
- package/dist/chunks/{4YD2XCGF.js → UNTTPATW.js} +1 -1
- package/dist/chunks/{NK54UVDI.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/CJCMQ73A.js +0 -20
- package/dist/chunks/CZQ7KIRM.js +0 -2
- package/dist/chunks/M5B52IE6.js +0 -4
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as wn,c as Q,d as bn,e as $e,g as _,h as vn}from"./ST2NZ4TZ.js";import{b as Ze,d as bt,e as mn,f as hn,g as Xe,h as Qe,k as gn,q as yn}from"./SUNHFMDO.js";import{b as ke}from"./2AT72FFB.js";import"reflect-metadata";var vt=[{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}],kn="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)",et=/^\d+$/;function qr(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 h=o.slice(s+1);if(!et.test(h)||Number(h)<1||Number(h)>r)return;i=Number(h)}let c=t,l=r;if(a!=="*")if(a.includes("-")){let h=a.indexOf("-"),b=a.slice(0,h),S=a.slice(h+1);if(!et.test(b)||!et.test(S)||Number(b)<t||Number(S)>r||Number(b)>Number(S))return;c=Number(b),l=Number(S)}else{if(!et.test(a)||Number(a)<t||Number(a)>r)return;c=Number(a),l=s===-1?c:r}for(let h=c;h<=l;h+=i)n.add(h)}return n}function $n(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${kn}; "${e}" is not`;let r=[];for(let l=0;l<5;l++){let h=qr(t[l],vt[l].lo,vt[l].hi);if(!h)return`${kn}; its ${vt[l].name} "${t[l]}" is not one`;r.push(h)}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 l=0;l<366*8+2;l++,c.setUTCDate(c.getUTCDate()+1)){if(!o.has(c.getUTCMonth()+1))continue;let h=n.has(c.getUTCDate()),b=s.has(c.getUTCDay());if(a||i?h&&b:h||b)return}return`"${e}" is never due: no date has that day in that month`}var Re=Symbol.for("palbase.backend.controller"),Ee=Symbol.for("palbase.backend.routes"),$t=Symbol.for("palbase.backend.params"),Rt=Symbol.for("palbase.backend.injectable"),Et=Symbol.for("palbase.backend.module"),me=Symbol.for("palbase.backend.events"),_e=Symbol.for("palbase.backend.webhook"),ue=Symbol.for("palbase.backend.jobs");function ne(e,t,r){let n=e;return Object.prototype.hasOwnProperty.call(n,t)||Object.defineProperty(n,t,{value:r(),enumerable:!1}),n[t]}var kt=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[kt]instanceof Set||(e[kt]=new Set),e[kt]}var Se=new Set(["webhooks","_palbase"]);function da(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&&Se.has(n))throw new TypeError(`@Controller("${e}") on ${r.name}: /${n} is the platform's; a controller is served elsewhere`);ne(r,Re,()=>({basePath:e,options:t})),se().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`);ne(n.constructor,Ee,()=>[]).push({method:e,subpath:t,fn:o,options:r})}}}var ca=xe("GET"),ua=xe("POST"),la=xe("PUT"),fa=xe("PATCH"),pa=xe("DELETE"),ma=xe("QUERY");function re(e,t={}){return(r,n,o)=>{if(typeof n!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let s=ne(r.constructor,$t,()=>new Map);s.has(n)||s.set(n,[]),s.get(n).push({index:o,kind:e,...t})}}function _t(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 ha=e=>re("body",{schema:_t("Body",e)}),ga=e=>re("query",{schema:_t("QueryParams",e)}),ya=e=>re("headers",e===void 0?{}:{schema:_t("Headers",e)}),wa=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return re("param",{name:e})},ba=()=>re("user"),va=()=>re("optionalUser"),ka=()=>re("req"),$a=()=>re("requestId"),Ra=()=>re("requestId"),Ea=()=>re("client");function _a(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 re("resolve",{resolver:e,options:t[0]})}function Sa(){return e=>{ne(e,Rt,()=>!0),se().add(e)}}function xa(e){return t=>{ne(t,Et,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var En=/^[a-z]+(\.[a-z_]+)+$/,Br=/^[a-z][a-z0-9-]{1,62}$/,St=e=>e.startsWith("file.");function Oa(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"||!Br.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(!St(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`);ne(n.constructor,me,()=>[]).push(r===void 0?{event:e,fn:o}:{event:e,fn:o,bucket:r}),se().add(n.constructor)}}var zr=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;function Ta(e){let t=e??{},r=`@Job(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!zr.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=$n(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}),se().add(s)}}var Rn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Fr=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Aa(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(!Fr.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&&!Rn.includes(n.provider))throw new TypeError(`${r}: provider "${String(n.provider)}" is not one of ${Rn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(n.signature!==void 0&&Wr(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=j(t,me)??[];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)}ne(t,_e,()=>({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}))})),se().add(t)}}function Wr(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 j(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Pa(){return[...se()].filter(e=>j(e,Re)!==void 0)}function ja(e){return(j(e,Ee)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var xt="/_palbase/storage/upload/authorize",_n="/_palbase/storage/upload/complete",Ot="/_palbase/realtime/rooms";var Kr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Oe(e){if(!Kr(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 Sn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function xn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function tt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Vr=/^[a-z][a-z0-9-]{1,62}$/,On=1024,Yr=new Set(["userId","uploadId","filename"]);function Na(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(!Vr.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=Gr(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`);ne(a.constructor,Ee,()=>[]).push({method:"POST",subpath:e,fn:i,options:s,upload:o})}}function Ia(){return re("uploadedObject")}function Gr(e){for(let r of e.matchAll(/\{([^{}]*)\}/g))if(!Yr.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(!Tn(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Tn(e){if(e===""||new TextEncoder().encode(e).byteLength>On)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 Zr(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(r,n)=>Xr(n==="userId"?t.userId??"anonymous":n==="uploadId"?t.uploadId:t.filename??"file"))}function Xr(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 An(e,t){let r=Zr(e,t);return Tn(r)?{path:r}:{problem:`the file's name makes its path longer than storage keeps (${On} bytes)`}}function Pn(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 Tt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function jn(e,t){if(!Tt(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=Oe(t.user);if(!a)return"user is { id?, session?, role }";let i=Sn(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=Qr(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 Qr(e){if(!Tt(e))return;let{uploadId:t,path:r,bucket:n,size:o,contentType:s,checksum:a,width:i,height:c,thumbhash:l,variants:h}=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"||l!==void 0&&typeof l!="string")&&!(!Tt(h)||!Object.values(h).every(b=>typeof b=="string")))return{uploadId:t,path:r,bucket:n,size:o,contentType:s,checksum:a,...i!==void 0?{width:i}:{},...c!==void 0?{height:c}:{},...l!==void 0?{thumbhash:l}:{},variants:{...h}}}import{markData as eo}from"palgres";var he=Symbol.for("palbase.backend.room"),Ae=Symbol.for("palbase.backend.roomHooks"),to=6e4,Te=255,no=["roles:","flags:","messaging:","debug:"],jt=e=>new TextEncoder().encode(e).byteLength,Cn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function";function ro(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(jt(e)>Te)return`a channel is ${Te} 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=no.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 Mn(e){if(typeof e!="string"||e==="")return"is a name";if(jt(e)>Te)return`is ${Te} bytes at most`}function za(e,t){if(typeof e!="string"||e==="")throw new TypeError('@Room(pattern, { events }): pattern is the channels it is, like "ai:{sessionId}"');let r=ro(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=Mn(a);if(c)throw new TypeError(`@Room("${e}"): event "${a}" ${c}`);if(!Cn(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??to;return a=>{let i=ne(a,Ae,Ct);ne(a,he,()=>({pattern:e,events:o,graceMs:s,hooks:{...i.hooks},messages:Object.assign(Object.create(null),i.messages)})),se().add(a)}}var Ct=()=>({hooks:Object.create(null),messages:Object.create(null)});function Ie(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=ne(r.constructor,Ae,Ct),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,se().add(r.constructor)}}var Fa=Ie("authorize"),Wa=Ie("first"),Ka=Ie("join"),Va=Ie("leave"),Ya=Ie("empty");function Ga(e,t){let r=Mn(e);if(r)throw new TypeError(`@OnMessage(name, schema): name ${r}`);if(!Cn(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=ne(n.constructor,Ae,Ct),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},se().add(n.constructor)}}function oo(e){return j(e,he)}function so(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 ao=1e4,io=1e3,co=100,Mt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ie=(e,t,r,n)=>({status:e,code:t,message:r,...n!==void 0?{retryAfter:n}:{}}),uo=new Set(["first","join","leave","empty"]);function Dn(e,t){let r=new Map,n=new Map;for(let{cls:k,instance:$}of e){let v=oo(k),O=v.pattern.split(":").map(A=>A.startsWith("{")?"{}":A).join(":"),M=n.get(O);if(M!==void 0)throw new TypeError(`@Room("${v.pattern}") on ${k.name}: ${r.get(M)?.cls.name}'s "${M}" is the same channels \u2014 one room is told of them; keep one`);n.set(O,v.pattern);for(let[A,J]of[...Object.entries(v.hooks),...Object.entries(v.messages).map(([B,U])=>[`message ${B}`,U.fn])])if(typeof $[J]!="function")throw new TypeError(`@Room("${v.pattern}") on ${k.name}: its ${A} is ${J}, which is no method of it`);r.set(v.pattern,{cls:k,instance:$,room:v})}let o=new Map,s=new Set,a=new Set,i=new Pt(t.broadcast),c=k=>{let $=o.get(k);return $||($=new AbortController,o.set(k,$)),$},l=(k,$)=>{$?.abort(),o.get(k)===$&&o.delete(k)};function h(k,$,v,O,M,A,J){let B=O?.signal??AbortSignal.abort(),U=`${k.cls.name} (${$})`;return{room:$,params:Object.freeze({...v}),signal:B,count:M,user:A,emit:(F,V)=>i.send({topic:$,event:F,payload:V??{},...J!==void 0?{conn_id:J}:{}},U),owner:{hold(F){Q.exit(async()=>{try{await F(B)}catch(V){B.aborted||_.error(`[palbase] ${U}: a task owner.hold ran failed`,{error:V})}}).catch(()=>{})},release:()=>l($,O)}}}function b(k){let{room:$,channel:v}=k;if(typeof $!="string"||typeof v!="string")return ie(400,"bad_request","A room's call names its room (the pattern) and its channel");let O=r.get($);return O?{entry:O,channel:v,params:so($,v)}:ie(404,"not_found",`This app declares no room "${$}"`)}let S=(k,$)=>ie(400,"bad_request",`"${$}" is not a channel of the room "${k}"`);async function I(k,$){let v=b(k);if("status"in v)return v;let{entry:O,channel:M,params:A}=v,J={status:200,body:{subscribe:!1,publish:!1}};if(!A)return _.warn(`[palbase] ${O.cls.name}: realtime asked about "${M}", which is not a channel of the room "${O.room.pattern}"; the join is refused`),J;let B=Oe(k.user),U=B?.id;if(!U)return J;let F=O.room.hooks.authorize;if(!F)return J;let V,Y;try{V=await t.run(B,`${O.cls.name}.${F}`,$,async()=>O.instance[F]({user:{id:U},params:Object.freeze({...A})})),Y=lo(V)}catch(G){if(t.isOutage(G)||$?.aborted)throw G;return _.error(`[palbase] ${O.cls.name}.${F} (@OnAuthorize of ${M}) failed; the join is refused`,{error:G}),J}return Y==="malformed"?(_.warn(`[palbase] ${O.cls.name}.${F} (@OnAuthorize of ${M}) answered ${fo(V)}, which is no grant (true, { read, write } or null); the join is refused`),J):{status:200,body:Y}}async function y(k,$){let v=b(k);if("status"in v)return v;if(!v.params)return S(v.entry.room.pattern,v.channel);let O=Oe(k.user);if(!O?.id||typeof k.event!="string")return ie(400,"bad_request","A message names its member (user) and its event");let M=Object.hasOwn(v.entry.room.messages,k.event)?v.entry.room.messages[k.event]:void 0;if(!M)return{status:200,body:{ok:!1,reason:Un(`room "${v.channel}" declares no message "${k.event}"`,At)}};let A=await M.schema["~standard"].validate(eo(k.payload??{}));if(A.issues)return{status:200,body:{ok:!1,reason:mo(A.issues)}};let J=c(v.channel),B={...h(v.entry,v.channel,v.params,J,0,{id:O.id}),payload:A.value};try{await t.run(O,`${v.entry.cls.name}.${M.fn}`,$,async()=>v.entry.instance[M.fn](B))}catch(U){if(t.isOutage(U))throw U;return $?.aborted||_.error(`[palbase] ${v.entry.cls.name}.${M.fn} (@OnMessage "${k.event}" of ${v.channel}) failed`,{error:U}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return{status:200,body:{ok:!0}}}async function C(k,$){let v=b(k);if("status"in v)return v;if(!v.params)return S(v.entry.room.pattern,v.channel);let O=k.event;if(typeof O!="string"||!uo.has(O))return ie(400,"bad_request","A room's moment is first, join, leave or empty");let M=typeof k.count=="number"&&Number.isInteger(k.count)&&k.count>=0?k.count:void 0;if(M===void 0)return ie(400,"bad_request","A room's moment says its count of members");let A=O==="join"||O==="leave",J=A?Oe(k.user):void 0,B=A?k.connId:void 0;if(A&&(!J?.id||typeof B!="string"||B===""))return ie(400,"bad_request",`A ${O} names its member: user and connId`);let U=`${O}\0${v.channel}\0${typeof B=="string"?B:""}`;if(A&&s.has(U))return{status:204};if(a.has(U))return ie(503,"in_progress","This moment of the room is being handled",5);a.add(U);try{let F=v.entry.room.hooks[O],V;if(O==="empty"?(V=o.get(v.channel),l(v.channel,V)):V=O==="leave"?o.get(v.channel):c(v.channel),F){let Y=h(v.entry,v.channel,v.params,V,M,{id:J?.id??""},O==="join"?B:void 0);try{await t.run(J,`${v.entry.cls.name}.${F}`,$,async()=>v.entry.instance[F](Y))}catch(G){if(t.isOutage(G))throw G;return $?.aborted||_.error(`[palbase] ${v.entry.cls.name}.${F} (${O} of ${v.channel}) failed; realtime tells it again`,{error:G}),ie(500,"handler_failed",`The room's ${O} could not be handled`)}}return A&&(s.add(U),s.size>ao&&s.delete(s.values().next().value)),{status:204}}finally{a.delete(U)}}return{declarations:[...r.values()].map(k=>k.room),async serve(k,$,v){return Mt($)?k==="authorize"?I($,v):k==="message"?y($,v):k==="lifecycle"?C($,v):ie(404,"not_found",`No room call ${JSON.stringify(k)}`):ie(400,"bad_request","A room's call is a JSON object")},close(){for(let k of o.values())k.abort();o.clear()}}}function lo(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!Mt(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 fo(e){return Array.isArray(e)?"an array":Mt(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 po=20,At=256;function mo(e){let t="";for(let r of e.slice(0,po)){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)>=At)break}return Un(t,At)}function Un(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 Pt=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,r){if(typeof t.event!="string"||t.event===""||jt(t.event)>Te){_.warn(`[palbase] ${r}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Te} bytes`);return}try{JSON.stringify(t.payload)}catch(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>=io?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),Q.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,co);try{await this.broadcast(o)}catch(a){_.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),_.warn(`[palbase] ${n}: ${s} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as Dt,createHmac as ho,createPublicKey as Jn,timingSafeEqual as go,verify as Hn}from"node:crypto";function ei(e){let t=j(e,_e);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 qn(e,t,r,n={}){let o=new Map,s=[];for(let a of e){let i=j(a,_e),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 l=`@Webhook "${i.name}" (${a.name})`,h=r[i.secret.env],b;if(n.secrets!==!1)if(h===void 0||h==="")s.push(`${l} reads its signing secret from ${i.secret.env}, which is not set`);else try{b=yo(i,h)}catch(y){s.push(`${l}: ${i.secret.env} ${y.message}`)}let S=t(a),I=new Map(i.events.map(({event:y,fn:C})=>[y,{name:`${a.name}.${C}`,call:(k,$)=>S[C](k,$)}]));o.set(i.name,{name:i.name,cls:a,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:b,events:I})}if(s.length>0)throw new Error(`[palbase] the app cannot start:
|
|
3
|
+
- ${s.join(`
|
|
4
|
+
- `)}`);return o}function Bn(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Pe=1024,Nn=1024*Pe;function yo(e,t){if(e.signature)return ge(void 0,e.signature.header,1/0,Oo(e.signature,t));switch(e.provider){case"stripe":return ge("stripe","stripe-signature",512*Pe,vo(t));case"github":return ge("github","x-hub-signature-256",25*Nn,ko(t));case"slack":return ge("slack","x-slack-signature",64*Pe,$o(t));case"discord":return ge("discord","x-signature-ed25519",64*Pe,Ro(t));case"twilio":return{header:"x-twilio-signature",maxBytes:r=>Math.min(r,64*Pe),check:_o(t)};case"sendgrid":return ge("sendgrid","x-twilio-email-event-webhook-signature",Nn,So(t));case"livekit":return ge("livekit","authorization",512*Pe,xo(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function ge(e,t,r,n){return{header:t,maxBytes:o=>Math.min(o,r),check:(o,s)=>n(o,s)??zn(e,o)}}function zn(e,t){let r=Ut(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:Fn(e,t.headers,n),event:n,...wo(e,t,n)}}function Fn(e,t,r){switch(e){case"github":{let n=t.get("x-github-event")??"",o=ye(r,"action");return n!==""&&o!==""?`${n}.${o}`:n}case"discord":{let n=Vn(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 ye(r,"EventType");case"livekit":return ye(r,"event");default:return ye(r,"type")}}function wo(e,t,r){let n=o=>o?{id:o}:{};switch(e){case"stripe":case"discord":case"livekit":return n(ye(r,"id"));case"slack":return n(ye(r,"event_id"));case"github":{let o=t.headers.get("x-github-delivery");return o?{id:`${o}:${Wn(t.body)}`}:{}}case"sendgrid":return Array.isArray(r)?{ids:r.map(o=>ye(o,"sg_event_id")||void 0)}:{};default:return{}}}var bo=300;function vo(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 l=c.indexOf("=");if(l<=0)continue;let h=c.slice(0,l).trim(),b=c.slice(l+1).trim();if(h==="t"){if(o!==void 0)return"malformed_signature";o=b}else if(h==="v1"){let S=oe(b,"hex");if(!S)return"malformed_signature";s.push(S)}}let a=Le(o);if(a===void 0||s.length===0)return"malformed_signature";if(Je(a,r))return"stale_timestamp";let i=je("sha256",e,`${o}.`,t.body);return s.some(c=>le(c,i))?void 0:"signature_mismatch"}}function ko(e){return t=>{let r=t.headers.get("x-hub-signature-256");if(!r)return"missing_signature";let n=r.startsWith("sha256=")?oe(r.slice(7),"hex"):void 0;return n?le(n,je("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function $o(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=Le(o),a=n.startsWith("v0=")?oe(n.slice(3),"hex"):void 0;return s===void 0||!a?"malformed_signature":Je(s,r)?"stale_timestamp":le(a,je("sha256",e,`v0:${o}:`,t.body))?void 0:"signature_mismatch"}}function Ro(e){let t=oe(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let r=Jn({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=Le(a),c=oe(s,"hex");return i===void 0||!c||c.byteLength!==64?"malformed_signature":Je(i,o)?"stale_timestamp":Hn(null,Kn(a,n.body),r,c)?void 0:"signature_mismatch"}}var Eo=1e3;function _o(e){return t=>{let r=t.headers.get("x-twilio-signature");if(!r)return"missing_signature";let n=oe(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(Dt("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let I=1;for(let k of t.body)if(k===38&&++I>Eo)return"malformed_signature";let y=new Map;for(let[k,$]of new URLSearchParams(Ut(t.body))){let v=y.get(k);v||y.set(k,v=new Set),v.add($)}let C=[];for(let k of[...y.keys()].sort()){let $=[...y.get(k)].sort();for(let v of $)a+=k+v;C.push([k,$.length===1?$[0]:$])}i=Object.fromEntries(C)}let c=o.protocol==="https:"?"443":"80",l=`${o.protocol}//${o.hostname}${o.pathname}${o.search}`,h=`${o.protocol}//${o.hostname}:${o.port||c}${o.pathname}${o.search}`;if(![l,h].some(I=>le(n,je("sha1",e,I,a))))return"signature_mismatch";let b=t.headers.get("i-twilio-idempotency-token"),S=b?{id:`${b}:${Wn(`${l}
|
|
5
|
+
${a}`)}`}:{};return i?{type:Fn("twilio",t.headers,i),event:i,...S}:{...zn("twilio",t),...S}}}function So(e){let t;try{let r=oe(e,"base64");if(!r)throw new Error;t=Jn({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=Le(s),i=oe(o.trim(),"base64");return a===void 0||!i?"malformed_signature":Je(a,n)?"stale_timestamp":Hn("sha256",Kn(s,r.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var In=60;function xo(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=Ln(oe(o[0],"base64url")),a=oe(o[2],"base64url");if(s?.alg!=="HS256"||!a)return"malformed_signature";if(!le(a,je("sha256",e,`${o[0]}.${o[1]}`)))return"signature_mismatch";let i=Ln(oe(o[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(r>i.exp+In||typeof i.nbf=="number"&&r<i.nbf-In)return"stale_timestamp";let c=typeof i.sha256=="string"?oe(i.sha256,"base64"):void 0;return c&&le(c,Dt("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function Oo(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 l=Le(i);if(l===void 0)return"malformed_signature";if(Je(l,s))return"stale_timestamp"}let c=oe(a.trim(),e.encoding);return c?le(c,je(n,t,...r.map(l=>l==="{body}"?o.body:l==="{ts}"?i:l)))?void 0:"signature_mismatch":"malformed_signature"}}var To=new TextEncoder;function je(e,t,...r){let n=ho(e,t);for(let o of r)n.update(o);return n.digest()}function Wn(e){return Dt("sha256").update(e).digest("hex")}function Kn(e,t){return Buffer.concat([To.encode(e),t])}function le(e,t){return e.byteLength===t.byteLength&&go(e,t)}var Ao={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function oe(e,t){return Ao[t].test(e)?Buffer.from(e,t):void 0}function Le(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function Je(e,t){return Math.abs(t-e)>bo}function Ut(e){return new TextDecoder().decode(e)}function Ln(e){if(e)try{return JSON.parse(Ut(e))}catch{return}}function Vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ye(e,t){let r=Vn(e)?e[t]:void 0;return typeof r=="string"?r:""}import"reflect-metadata";var z=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}},Po=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],jo=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),nt=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=j(n,Et);if(!s)throw new z("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 z("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 z("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(!j(s,Re))throw new z("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(j(s,ue))throw new z("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(j(s,he)||j(s,Ae))throw new z("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 se())if(!this.owner.has(t))throw new z("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 z("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(j(n,Ae)&&!j(n,he))throw new z("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(!j(n,Rt)&&!j(n,me)&&!j(n,he)&&!j(n,ue)){let o=Reflect.getMetadata("design:paramtypes",n);throw n.length>0&&!o?new z("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 z("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()"])}j(n,he)&&this.rooms.push(n),j(n,_e)?this.webhooks.push(n):j(n,me)&&this.eventProviders.push(n),j(n,ue)&&this.jobProviders.push(n)}}for(let t of this.owner.keys())for(let r of Po)if(typeof t.prototype[r]=="function")throw new z("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 z("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 z("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((l,h)=>{if(jo.has(l)||typeof l!="function")throw new z("unresolvable dependency",o,`${t.name} constructor parameter ${h}`,`parameter ${h} of ${t.name} is typed as ${l===void 0?"something with no runtime class":l.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,l,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 z("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 z("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 z("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 z("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 Co,HttpError as He}from"palgres";import{z as fe}from"zod";import{BadRequest as li,Conflict as fi,DeadlockDetected as pi,HttpError as mi,NotFound as hi,SerializationFailure as gi,TooManyRequests as yi,UniqueViolation as wi}from"palgres";function qe(e){if(typeof e!="object"||e===null||e[Co]!==!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 Yn=class extends He{constructor(t,r,n,o){super(t,r,n,o),this.name=new.target.name}},Gn=class extends He{constructor(t="Unauthorized",r="unauthorized",n){super(401,r,t,n),this.name="Unauthorized"}},Zn=class extends He{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 Mo=Symbol.for("palbase.backend.errorRegistry"),Do={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()})},Uo=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 No(){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=Do[t];e.set(t,{code:t,status:r,className:n,builtin:!0,...o?{data:o}:{}})}return e}function Io(){let e=globalThis;return e[Mo]??=No()}function di(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(Uo.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=Io(),o=n.get(e);if(o&&(o.builtin||o.status!==t||o.data===void 0!=(r===void 0)||r!==void 0&&o.data!==r&&Xn(o.data)!==Xn(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(b=>b.charAt(0).toUpperCase()+b.slice(1)).join(""),a=e.replace(/_/g," "),i=a.charAt(0).toUpperCase()+a.slice(1),h=r?(b=>class extends He{static code=e;static status=t;constructor(S,I){let y=Lo(e,b,S);super(t,e,I??(typeof y=="string"?y:i),y),this.name=s}})(r):class extends He{static code=e;static status=t;constructor(b){super(t,e,b??i),this.name=s}};return Object.defineProperty(h,"name",{value:s}),n.set(e,{code:e,status:t,className:s,builtin:!1,...r?{data:r}:{}}),h}function Lo(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 Xn(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}var er="/_palbase/ai/tools",tr="/_palbase/ai/agents";var Jo=Symbol.for("palbase.ai.tool_error");function nr(e){return e instanceof Error&&e[Jo]===!0}var Ho=Symbol.for("palbase.ai.declared");function rr(){let e=globalThis[Ho];if(!e)return{tools:new Map,agents:new Map};if(e.twice.size>0){let t=[...e.twice].map(r=>r.replace(":"," "));throw new TypeError(`[palbase] ${t.join(", ")}: declared twice with different values \u2014 an ai.tool's and an ai.agent's name is its own; make each once, at a module's top level`)}return{tools:new Map(e.tools),agents:new Map(e.agents)}}var Nt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function It(e){if(!Nt(e))return"context is {chat_id, agent, user, metadata}";if(typeof e.chat_id!="string")return"context.chat_id is the chat (empty for a one-shot answer's call)";if(typeof e.agent!="string")return"context.agent is the agent's name";let t=null;if(e.user!==null&&e.user!==void 0){if(!Nt(e.user)||typeof e.user.id!="string"||e.user.id===""||e.user.name!==void 0&&typeof e.user.name!="string")return"context.user is {id, name}, or null";t={id:e.user.id,name:typeof e.user.name=="string"?e.user.name:""}}let r={};if(e.metadata!==void 0&&e.metadata!==null){if(!Nt(e.metadata))return"context.metadata is an object of strings";for(let[n,o]of Object.entries(e.metadata)){if(typeof o!="string")return"context.metadata is an object of strings";Object.defineProperty(r,n,{value:o,enumerable:!0,writable:!0,configurable:!0})}}return{chatId:e.chat_id,agent:e.agent,user:t,metadata:r}}var qo=1e3,Bo=256*1024,rt=class{answers=new Map;running=new Set;answered(t){return this.answers.get(t)}isRunning(t){return this.running.has(t)}start(t){this.running.add(t)}end(t,r){this.running.delete(t),!(r===void 0||r.answer.length>Bo)&&(this.answers.set(t,r),this.answers.size>qo&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as Tr,isEngineRaised as en,markData as ae}from"palgres";import{createHash as Ar}from"node:crypto";import{createHash as zo,randomInt as Fo}from"node:crypto";import{ago as Lt,isRetryable as Wo,now as or}from"palgres";import{defineSchema as Ko,defineTable as Vo,index as Yo,integer as Go,jsonb as Zo,raw as Xo,text as Jt,timestamp as sr}from"palgres/dsl";var lr=new Set(["POST","PUT","PATCH","DELETE"]),ar=255,ir=35,dr=24,Qo=65536,cr=1e3,es=64,qt={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"}},ts=Vo("idempotency_keys",{columns:{key:Jt().primaryKey(),fingerprint:Jt(),started_at:sr().defaultNow(),completed_at:sr().nullable(),status_code:Go().nullable(),response_headers:Zo().nullable(),response_body:Jt().nullable()},indexes:e=>[Yo("idempotency_keys_started").on(e.col("started_at"))]}),Si=Ko("palbase",{tables:[ts],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)"})]}),ns={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},rs={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},os={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},ss={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},st=class extends Error{};function Be(e){return lr.has(e.method)&&e.meta.upload===void 0}function fr(e,t){if(!lr.has(e))return;let r=t.get("idempotency-key");return r===null||r===""?void 0:r}function as(e,t){return pr([e.role,e.uid,t]).digest("hex")}function is(e){return pr([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function pr(e){let t=zo("sha256");for(let r of e)t.update(r).update("\0");return t}function ds(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function Ht(e){return e<500&&e!==429&&e!==499}function cs(e,t){return t&&Ht(e)}function mr(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 us={role:"service",claims:{}},at=class{constructor(t){this.db=t}db;async serve(t,r,n){if(t.key.length>ar)return n.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${ar} characters`});let o;try{o=await this.begin(as(t.caller,t.key),is(t))}catch(i){return _.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:i}),n.refusal(ss)}if("kept"in o)return ls(o.kept,n.requestId);if("refused"in o)return n.refusal(o.refused==="reused"?ns:rs);let s=o.claim,a;try{a=await r(i=>this.record(s,i))}catch(i){if(i instanceof st)return n.refusal(os);let c=n.failure(i);return cs(c.status,n.ran())&&!Wo(i)?this.keep(s,c):(await this.release(s),c)}return Ht(a.status)||await this.release(s),a}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:Lt({hours:dr})}}}))}async begin(t,r){return Fo(es)===0&&await this.sweep().catch(n=>_.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:Lt({hours:dr})}}})>0)continue;let a=await n.findUnique({where:{key:t}});if(a===null)continue;let i=ds(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:Lt({seconds:ir})}},set:{started_at:or()}});return c?{claim:{key:t,started:c.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,r){if(!Ht(r.status))return r;let{response:n,kept:o}=await ur(r),s=Q.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 st;return n}async keep(t,r){let{response:n,kept:o}=await ur(r);try{await this.asService(s=>s.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:or(),status_code:o.status,response_headers:o.headers,response_body:o.body}}))}catch(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()+ir*1e3,n=()=>{Date.now()+cr>=r||setTimeout(()=>{this.releaseOnce(t).then(o=>o||n())},cr).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(us),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 ls(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 ot=Symbol("waits");function fs(e){return new Promise((t,r)=>{let n=setImmediate(()=>t(ot));e.then(o=>{clearImmediate(n),t(o)},o=>{clearImmediate(n),r(o)})})}async function ur(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 fs(i);if(c!==ot&&c.done)break;if(c!==ot&&(o.push(c.value),s+=c.value.byteLength,s<=Qo))continue;let l=c===ot?i:void 0,h=new ReadableStream({start(b){for(let S of o)b.enqueue(S)},async pull(b){let S=await(l??n.read());l=void 0,S.done?b.close():b.enqueue(S.value)},cancel:b=>n.cancel(b)});return{response:r(h),kept:{status:e.status,headers:t.filter(([b])=>b!=="content-length"&&b!=="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 ps}from"node:crypto";var Bt="/webhooks/palbase",vr="PalbaseErrorEnvelope",hr="PalbaseBearer",ms={$ref:`#/components/schemas/${vr}`},hs={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"]},gr={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Ce={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function kr(e,t,r){let n={[vr]:hs},o={},s=[],a=[],i=new Set,c=new Map;for(let y of e){let C=a.find(H=>ws(H,y));if(C){s.push({route:y.id,handler:yr(y),answeredBy:C.id});continue}a.push(y);let k=y.segments.map(H=>typeof H=="string"?H:"{}").join("/");c.has(k)||c.set(k,vs(y.segments.flatMap(H=>typeof H=="string"?[]:[H.param])));let $=c.get(k),v=0,O=`/${y.segments.map(H=>typeof H=="string"?H:`{${$[v++]}}`).join("/")}`,M=t(y),A=it(bs(y),i),J=y.method!=="GET"&&y.method!=="HEAD",B=H=>{let pe=y.params.filter(we=>we.kind===H&&we.schema).map((we,Ye)=>ut(we.schema,`${A}.${H}${Ye===0?"":`.${Ye+1}`}`,n));return pe.length===0?void 0:pe.length===1?pe[0]:{allOf:pe}},U=$.map(H=>({name:H,in:"path",required:!0,schema:{type:"string"}})),F=B("query");F&&U.push(...br(F,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:F}]);let V=B("headers");V&&U.push(...br(V,"header")??[]);let Y=r.idempotency===!0&&Be(y);Y&&U.push({...qt,schema:{...qt.schema}});let G=J?B("body"):void 0,Z={operationId:A};y.controller.name!==""&&(Z.tags=[y.controller.name]),U.length>0&&(Z.parameters=U),G&&(Z.requestBody={required:!_s(G),content:{"application/json":{schema:G}}});let gt=y.params.some(H=>H.schema!==void 0),Ve=r.routes?.(y),Ue=xs(A,Ve?.throws??[],r.errors);Z.responses={...Ss(Ve,A,n),...As(M,{validates:gt,hasPathParams:$.length>0,readsBody:J,keyed:Y}),...Ts(Ue,A,n)},Ue.length>0&&(Z["x-palbase-errors"]=Os(A,Ue)),M.auth.required&&(Z.security=[{[hr]:[]}]),Z["x-palbase-handler"]=yr(y);let yt=y.params.some(H=>H.kind==="optionalUser")||r.databaseSeesCaller;Z["x-palbase-auth"]=M.auth.required?"required":yt?"optional":"public",Z["x-palbase-verified-email"]=M.auth.verifiedEmail,Z["x-palbase-rate-limit"]=M.limit===!1?!1:{max:M.limit.max,window:M.limit.window},y.meta.upload&&(Z["x-palbase-upload"]={bucket:y.meta.upload.bucket,pathTemplate:y.meta.upload.pathTemplate}),(o[O]??={})[y.method.toLowerCase()]=Z}for(let y of r.webhooks??[]){let C={operationId:it(`webhooks.${y.name}`,i)};y.cls!==""&&(C.tags=[y.cls]),C.description=y.provider?`${gr[y.provider]??y.provider}'s deliveries: verified with ${gr[y.provider]??y.provider}'s signature scheme under the secret in ${y.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${y.signatureHeader} header: verified under the secret in ${y.secretEnv}, then handed to the @On of their event type.`,C.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":{},[y.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",Ce),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",Ce)},C["x-palbase-webhook"]=y.provider?{provider:y.provider,secretEnv:y.secretEnv,events:y.events}:{signatureHeader:y.signatureHeader,secretEnv:y.secretEnv,events:y.events},o[`/webhooks/${y.name}`]={post:C}}let l=[...new Set(r.platformEvents??[])].sort();if(l.length>0){let y={operationId:it("webhooks.palbase",i)};y.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.",y.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",Ce),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 C=[...new Set(r.platformEventBuckets??[])].sort();y["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:l,...C.length>0?{buckets:C}:{}},o[Bt]={post:y}}let h=gs(r.rooms??[],n),b=Object.keys(h).length>0,S={schemas:n,securitySchemes:{[hr]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},I={openapi:"3.2.0",info:{title:"Palbase backend",version:ps("sha256").update(JSON.stringify({paths:o,components:S,unreachable:s,...b?{rooms:h}:{}})).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:S};return s.length>0&&(I["x-palbase-unreachable"]=s),b&&(I["x-palbase-room"]=h),I}function gs(e,t){let r=[];for(let n of e){let o=n.pattern.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_|_$/g,""),s=(c,l,h,b)=>{let S=ct(`Room_${o}_${l}`),I={},y=ut(h,S,I,b);y.$ref===void 0&&(I[S]=y),ys(n.pattern,c,l,I[S]);for(let[C,k]of Object.entries(I)){if(Object.hasOwn(t,C)&&JSON.stringify(t[C])!==JSON.stringify(k))throw new Error(`@Room("${n.pattern}") ${c} "${l}": its schema is the component ${C}, which another room's event or message names with another schema \u2014 rename one of them`);t[C]=k}return{$ref:`#/components/schemas/${S}`}},a=Object.fromEntries(Object.entries(n.events).map(([c,l])=>[c,s("event",c,l,"answered")])),i=Object.fromEntries(Object.entries(n.messages).map(([c,l])=>[c,s("message",c,l.schema,"sent")]));r.push([n.pattern,{events:a,messages:i,graceMs:n.graceMs}])}return Object.fromEntries(r)}function ys(e,t,r,n){if(!(!ee(n)||!ee(n.properties))){for(let[o,s]of Object.entries(n.properties))if(s===!0||ee(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 ws(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 yr(e){return`${e.controller.name}.${e.fn}`}function bs(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 it(e,t){let r=e;for(let n=2;t.has(r);n++)r=`${e}_${n}`;return t.add(r),r}function vs(e){let t=new Set;return e.map(r=>it(r,t))}function ut(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:ks}:{}}})}catch{return{}}let i=ct(t);for(;Object.keys(r).some(c=>c===i||c.startsWith(`${i}.`));)i=`${i}_`;return $s(a,i,r,n)}function ks(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function $s(e,t,r,n){let o=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},s=!1,a=l=>l==="#"?(s=!0,`#/components/schemas/${t}`):l.startsWith("#/$defs/")?`#/components/schemas/${t}.${ct(Es(l.slice(8)))}`:l,i="all";if(n==="sent"){let l=new Set;for(let h of[e,...Object.values(o)])dt(h,l);i=l}for(let[l,h]of Object.entries(o))r[`${t}.${ct(l)}`]=Fe(ze(h,a,i));let c=Fe(ze(e,a,i));return s?(r[t]=c,{$ref:`#/components/schemas/${t}`}):c}var Rs=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"]),zt=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),Ft=new Set(["anyOf","oneOf","allOf","prefixItems"]),Wt=new Set(["properties","patternProperties","dependentSchemas"]),ee=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ze(e,t,r){if(!ee(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):Rs.has(o)?n[o]=s:zt.has(o)?n[o]=ze(s,t,r):Ft.has(o)&&Array.isArray(s)?n[o]=s.map(a=>ze(a,t,r)):Wt.has(o)&&ee(s)&&(n[o]=Object.fromEntries(Object.entries(s).map(([a,i])=>[a,ze(i,t,r)])));return n}var wr=Number.MAX_SAFE_INTEGER;function Fe(e){if(!ee(e))return e;let t={};for(let[n,o]of Object.entries(e))zt.has(n)?t[n]=Fe(o):Ft.has(n)&&Array.isArray(o)?t[n]=o.map(Fe):Wt.has(n)&&ee(o)?t[n]=Object.fromEntries(Object.entries(o).map(([s,a])=>[s,Fe(a)])):t[n]=o;if("const"in t){let{const:n,...o}=t;t={...o,enum:[n]}}if(t.type==="integer"&&(t.minimum===-wr&&delete t.minimum,t.maximum===wr&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,ee(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=>ee(s)&&Object.keys(s).length===1&&s.type==="null"),o=r[1-n];if(n!==-1&&ee(o)&&typeof o.type=="string")return{...o,type:[o.type,"null"]}}return t}function dt(e,t){if(ee(e)){for(let r of["anyOf","oneOf"]){let n=e[r];if(!Array.isArray(n)||n.length<2||!n.every(ee))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=>ee(s.properties)?s.properties:{});for(let s of Object.keys(o[0]))if(o.every(a=>ee(a[s])&&"const"in a[s]))for(let a of o)t.add(a[s])}for(let[r,n]of Object.entries(e))if(zt.has(r))dt(n,t);else if(Ft.has(r)&&Array.isArray(n))for(let o of n)dt(o,t);else if(Wt.has(r)&&ee(n))for(let o of Object.values(n))dt(o,t)}}function Es(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function ct(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function br(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 _s(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:ms}}}}function Ss(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=ut(e.returns.schema,`${t}.response`,r,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:n}:n}}}}}function xs(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 Ts(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 l={error:{type:"string",const:c.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},h=["error","error_description","status","request_id"];return c.data&&(l.data=ut(c.data,`${t}.${c.code}.data`,r,"answered"),h.push("data")),{type:"object",properties:l,required:h}});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",Ce)),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)",Ce)),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":""}`,Ce),r}var lt=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 ft(e,t){let n=e.get("x-forwarded-for")?.split(",").map(o=>o.trim()).filter(Boolean).at(-1);return Ps(n??t??"unknown")}function Ps(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 $r(e){let t=[];for(let r of e){let n=j(r,Re),o=j(r,Ee)??[];if(o.length===0)throw new TypeError(`@Controller ${r.name} has no routes: a controller with nothing to serve is a mistake`);let s=j(r,$t)??new Map;for(let a of o){let i=`${n.basePath}${a.subpath}`||"/",c=i.split("/").filter(Boolean).map(h=>{let b=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(h)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(h);return b?{param:b[1]}:h});if(typeof c[0]=="string"&&Se.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 l=[...s.get(a.fn)??[]].sort((h,b)=>h.index-b.index);for(let h of l)if(h.kind==="param"&&!c.some(b=>typeof b!="string"&&b.param===h.name))throw new TypeError(`${r.name}.${a.fn}: @Param("${h.name}") names no {${h.name}} in ${a.method} ${i}`);t.push({id:`${a.method} ${i}`,method:a.method,segments:c,controller:r,fn:a.fn,params:l,meta:a,controllerAuth:n.options.auth})}}return Pn(t),t}function Kt(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 Yt(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Me(e,t,r,n,o){return Gt(e,e?Yt(e.requests,t):void 0,r,n,o)}var Rr={role:"service",claims:{}};async function Gt(e,t,r,n,o){if(!e||!t)return o();let s=l=>_.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 ${l} 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:l}),a=e.app.request(t,{signal:r,heldIdle:s}),i=Q.getStore();i&&(i.database=a.database);let c;try{c=await o()}catch(l){throw await a.rollback(l).catch(h=>_.error("[palbase] the request's transaction could not be rolled back",{error:h})),l}try{await a.commit()}catch(l){throw await a.rollback(l).catch(h=>_.error("[palbase] the request's transaction could not be rolled back",{error:h})),l}return c}var Cs=1024*1024,Ms=20,Ds={max:300,window:60},De="/_palbase/jobs",Er=50,Us=4096,Ns=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,pt=1e4,Is=6e4;function Ls(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 X=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 Js(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 Hs=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function qs(e,t){let r=new Headers(e.headers);for(let n of Hs)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 _r(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),ht(e.headers,"Accept-Language")),e}function ht(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 E(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 Sr(e,t,r,n){if(n?.aborted)return _.info(`[palbase] ${r}: the client left before its answer`),E({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof X)return E({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(qe(e)){let s=e;return s.status>=500&&_.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=Zt(e,r);return o?E(o,t):(e instanceof ke?_.error(`[palbase] ${r}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):_.error(`[palbase] unhandled error in ${r}`,{error:e}),E({status:500,code:"internal_error",message:"The request could not be completed"},t))}function Zt(e,t){if(e instanceof Qe)return _.warn(`[palbase] ${t}: sign-ins cannot be checked (${e.message})`,{error:e}),{status:503,code:"auth_unavailable",message:"Sign-ins cannot be checked right now; try again shortly",retryAfter:1};if(e instanceof ke&&Pr.has(e.status))return _.warn(`[palbase] ${t}: a platform service did not answer (${e.op}: ${e.status} ${e.code})`,{error:e}),{status:503,code:"service_unavailable",message:"A service this request needs did not answer; try again shortly",retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))};let r=Tr(e);if(r!==void 0)return _.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 Bs(e){let t=r=>(r.length>1e3?`${r.slice(0,1e3)}\u2026`:r)||"The tool failed";return nr(e)?t(e.message):qe(e)&&!en(e)&&!Xt(e)?t(e.errorDescription):Xt(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function Xt(e){return e instanceof Qe||e instanceof ke&&Pr.has(e.status)||Tr(e)!==void 0||qe(e)&&e.status===503&&en(e)}async function Vt(e,t,r){let n=await e["~standard"].validate(t);if(n.issues){let o=n.issues.slice(0,Ms).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 X(400,"bad_request",`${r} failed validation`,s>0?{fields:o,more:s}:{fields:o})}return n.value}async function mt(e,t){let r=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>t)throw new X(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:l}=await n.read();if(c)break;if(s+=l.byteLength,s>t)throw await n.cancel().catch(()=>{}),new X(413,"payload_too_large",`Request body exceeds ${t} bytes`);o.push(l)}let a=new Uint8Array(s),i=0;for(let c of o)a.set(c,i),i+=c.byteLength;return a}function zs(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return ae(t)}function Fs(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 Ws(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 Ks=/^[A-Za-z0-9._:-]{8,128}$/,Vs=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Ys={max:20,window:60},Gs=10*6e4,Zs=1e4,Ke=class extends Error{constructor(r){super("too many unknown tokens from this address");this.wait=r}wait},Qt=class{constructor(t,r){this.limiter=t;this.now=r}limiter;now;known=new Map;async ask(t,r,n){let o=Ar("sha256").update(t).digest("hex"),s=(this.known.get(o)??0)>this.now(),a=`token-misses\0a:${r}`,i;if(!s){let l=this.limiter.reserve(a,Ys);if("wait"in l)throw new Ke(l.wait);i=l}let c=await n();if(!c)throw this.known.delete(o),new Xe("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()+Gs),this.known.size>Zs&&this.known.delete(this.known.keys().next().value),c}};function Qi(e){let t=new nt(e.modules),r=$r(t.controllers.map(d=>d.cls)),n=new Map(r.map(d=>[d,Ls(d,e.auth)]));for(let[d,u]of n){if(!u.required&&d.params.some(f=>f.kind==="user"))throw new TypeError(`${d.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(d.meta.upload&&u.verifiedEmail)throw new TypeError(`${d.id}: an @Upload route cannot ask for a verified email \u2014 storage names its caller by id and session, not by its token; read the user (Palbase.auth) in the handler to check it`)}let o=new Map;for(let d of r)for(let u of d.params)u.kind==="resolve"&&o.set(u,t.dependencyOf(d.controller,u.resolver,`${d.id} @Resolve(${u.resolver?.name})`));let s=new Map;for(let d of t.jobProviders){let u=t.get(d),f=j(d,ue),p=s.get(f.name);if(p)throw new TypeError(`@Job "${f.name}" is ${p.owner} and ${d.name}: a job's name is its own \u2014 name one of them`);s.set(f.name,{declaration:f,owner:d.name,run:g=>u.run(g)})}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>Er)throw new TypeError(`${s.size} @Job classes: a machine runs ${Er} jobs at most`);s.size>0&&!e.platform&&_.info(`[palbase] ${s.size} @Job(s): the platform runs them on a machine; nothing calls them here`);let c=Dn(t.rooms.map(d=>({cls:d,instance:t.get(d)})),{run:(d,u,f,p)=>Q.run({requestId:Q.getStore()?.requestId??"",...d?.id?{userId:d.id}:{}},()=>Gt(e.database,e.database?d?.id?Yt(e.database.requests,tt(d)):Rr:void 0,f,u,async()=>{let g=await p();if(f?.aborted)throw new Error(`realtime gave up on ${u} before it ended`);return g})),broadcast:d=>e.server.realtime.broadcast({body:{messages:d}}),isOutage:Xt});c.declarations.length>0&&!e.platform&&_.info(`[palbase] ${c.declarations.length} @Room(s): realtime tells a machine of them; nothing does here`);let l=rr();(l.tools.size>0||l.agents.size>0)&&!e.platform&&_.info(`[palbase] ${l.tools.size} ai.tool(s) and ${l.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let h=new rt,b=new Set,S=e.database!==void 0||e.contractOnly?.database===!0;if(S){for(let d of r)if(Be(d)&&d.params.some(u=>u.kind==="headers"&&u.schema!==void 0&&mr(u.schema)))throw new TypeError(`${d.id}: its @Headers schema declares Idempotency-Key \u2014 the framework takes that header on every write of an app with a database and answers a retry from it; a handler reads it with @Headers() (no schema)`)}let I=e.database?new at(e.database.app):void 0,y=oa(e.cors),C=e.now??Date.now,k=new lt(e.now),$=new Qt(k,e.now??Date.now),v=e.maxBodyBytes??Cs,O=d=>{let u=d.meta.options.rateLimit??e.rateLimit??Ds;return u!==!1&&u.max>0&&u.window>0?u:!1},M=e.env??process.env,A=qn(t.webhooks,d=>t.get(d),M,{secrets:e.contractOnly===void 0}),J=A.size===0&&s.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(M).filter(d=>typeof d[1]=="string"&&!yn(d[0])))),B=new Map([...A.keys()].map(d=>[d,{seen:new Set,inflight:new Set}])),U=new Map([...A.keys()].map(d=>[d,{counts:new Map,at:void 0}])),F,V=()=>F??=kr(r,d=>({auth:n.get(d),limit:O(d)}),{databaseSeesCaller:S,idempotency:S,webhooks:[...A.values()].map(d=>({name:d.name,cls:d.cls.name,provider:d.provider,signatureHeader:d.signatureHeader,secretEnv:d.secretEnv,events:[...d.events.keys()]})),platformEvents:[...Y.keys()],rooms:c.declarations,platformEventBuckets:Qs(Y),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),Y=new Map;for(let[d,u]of Object.entries(e.events??{}))Y.set(d,u.map(f=>({name:`palbase(${d})`,call:p=>f(p)})));for(let d of t.eventProviders){let u=t.get(d);for(let{event:f,fn:p,bucket:g}of j(d,me)??[]){if(!En.test(f))throw new TypeError(`@On("${f}") 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`);Y.has(f)||Y.set(f,[]),Y.get(f).push({name:`${d.name}.${p}`,bucket:g,call:async(m,w)=>u[p](m,w)})}}let G=new Set,Z=new Set;bn(e.server);async function gt(d,u){let f;try{f=await hn(d,e.webhookSecret,{now:e.now})}catch(p){if(p instanceof Ze)return E({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${p.code}`},u);throw p}if(ae(f.data),G.has(f.id))return new Response(null,{status:204,headers:{"x-request-id":u}});if(Z.has(f.id))return E({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},u);Z.add(f.id);try{let p;try{await Me(e.database,null,void 0,`event ${f.type}`,async()=>{for(let g of Y.get(f.type)??[])if(!(g.bucket!==void 0&&Xs(f)!==g.bucket))try{await g.call(f,{requestId:u})}catch(m){throw p=g.name,m}})}catch(g){return _.error(`[palbase] ${p??"the delivery"} failed on ${f.type} ${f.id}; the platform delivers it again`,{error:g}),E({status:500,code:"handler_failed",message:"The event could not be handled"},u)}return G.add(f.id),G.size>pt&&G.delete(G.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}})}finally{Z.delete(f.id)}}async function Ve(d,u={}){let f=d.headers.get("origin");if(y&&f!==null){let p=y.allows(f);if(d.method==="OPTIONS"&&d.headers.has("access-control-request-method"))return p?new Response(null,{status:204,headers:y.preflight(f,d.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let g=await dn(d,u);if(p)for(let[m,w]of Object.entries(y.headers(f)))m==="vary"?ht(g.headers,w):g.headers.set(m,w);else ht(g.headers,"Origin");return g}return dn(d,u)}async function Ue(d,u,f,p){if(!d.headers.get(f.scheme.header))return H(f,"missing_signature",p);let g={headers:d.headers,body:await mt(d,f.scheme.maxBytes(v)),url:Bn(d,u)},m;try{m=f.scheme.check(g,C()/1e3)}catch{return H(f,"signature_mismatch",p,"check_failed")}if(typeof m=="string")return H(f,m,p);let w=f.events.get(m.type);if(!w)return _.info(`[palbase] webhook ${f.name}: no @On takes "${m.type}"; acknowledged`),de(200,{ok:!0,handled:!1},p);let R=B.get(f.name),T=m.event,D=[];if(m.id!==void 0){if(R.seen.has(m.id))return de(200,{ok:!0,handled:!1,duplicate:!0},p);D=[m.id]}else if(m.ids&&Array.isArray(T)){let x=m.ids,P=T.map((L,ce)=>[L,x[ce]]).filter(([,L])=>L===void 0||!R.seen.has(L));if(P.length===0)return de(200,{ok:!0,handled:!1,duplicate:!0},p);T=P.map(([L])=>L),D=P.flatMap(([,L])=>L===void 0?[]:[L])}if(D.some(x=>R.inflight.has(x)))return E({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},p);ae(T);for(let x of D)R.inflight.add(x);let q;try{q=await Me(e.database,null,void 0,`webhook ${f.name}`,()=>w.call(T,{env:J,requestId:p,environmentId:e.projectId??""}))}catch(x){let P=Zt(x,`webhook ${f.name}`)??ea(x,f.name);return P?E(P,p):(_.error(`[palbase] ${w.name} failed on ${f.name} "${m.type}"; the sender delivers it again`,{error:x}),E({status:500,code:"handler_failed",message:"The event could not be handled"},p))}finally{for(let x of D)R.inflight.delete(x)}for(let x of D)R.seen.add(x),R.seen.size>pt&&R.seen.delete(R.seen.values().next().value);return yt(q,f,p)}function yt(d,u,f){if(d instanceof Response)return d;if(typeof d=="string"){let p=u.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":f}})}return de(200,d??{ok:!0,handled:!0},f)}function H(d,u,f,p=u){let g=U.get(d.name);g.counts.set(p,(g.counts.get(p)??0)+1);let m=C();return(g.at===void 0||m-g.at>=Is)&&(pe(d.name),g.at=m),E({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${u}`},f)}function pe(d){let u=U.get(d).counts;if(u.size===0)return;let f=[...u.values()].reduce((p,g)=>p+g,0);_.warn(`[palbase] webhook ${d}: ${f} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(u)}),u.clear()}function we(d){let u=d.split("/").filter(Boolean);return u.length===2&&u[0]==="webhooks"?A.get(u[1]):void 0}async function Ye(d,u,f,p){let g=u.pathname===De;if(d.method!==(g?"GET":"POST"))return E({status:405,code:"method_not_allowed",message:g?"The jobs are listed with GET":"A job is run with POST"},p);let m=g?new Uint8Array(0):await mt(d,Us);try{await bt({secret:f,signature:d.headers.get("palbase-signature"),body:m,now:e.now})}catch(te){if(te instanceof Ze)return E({status:401,code:"invalid_signature",message:`The jobs are the platform's to call: ${te.code}`},p);throw te}if(g){let te=[...s.values()].map(({declaration:W})=>({name:W.name,schedule:W.schedule,timeout:W.timeout,retry:W.retries}));return de(200,{jobs:te},p,{"cache-control":"no-store"})}let w=u.pathname.slice(De.length+1),R=s.get(w);if(!R)return E({status:404,code:"job_not_found",message:`This version has no job ${JSON.stringify(w)}`},p);let T;try{T=JSON.parse(new TextDecoder().decode(m))}catch{return E({status:400,code:"bad_request",message:"A run is the JSON {job, run_id, scheduled_at, attempt}"},p)}let{job:D,run_id:q,scheduled_at:x,attempt:P}=T??{};if(D!==w||typeof q!="string"||q===""||typeof x!="string"||!Ns.test(x)||Number.isNaN(Date.parse(x))||!Number.isInteger(P)||P<1)return E({status:400,code:"bad_request",message:`A run of ${w} is the JSON {job: "${w}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},p);let L=`${q}#${String(P)}`;if(a.has(L))return new Response(null,{status:204,headers:{"x-request-id":p}});if(i.has(L))return E({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},p);i.add(L);let ce={env:J,environmentId:e.projectId??"",job:w,runId:q,scheduledAt:new Date(x),attempt:P};try{await Gt(e.database,e.database?Rr:void 0,d.signal,`job ${w}`,async()=>{if(await R.run(ce),d.signal.aborted)throw new Error(`the platform gave up on this attempt of ${w} before it ended`)})}catch(te){return d.signal.aborted||_.error(`[palbase] job ${w} failed (run ${q}, attempt ${String(P)})`,{error:te}),E({status:500,code:"job_failed",message:`The job ${w} failed; the platform tries it again`},p)}finally{i.delete(L)}return a.add(L),a.size>pt&&a.delete(a.values().next().value),new Response(null,{status:204,headers:{"x-request-id":p}})}async function Ge(d,u,f,p){if(d.method!=="POST")return E({status:405,code:"method_not_allowed",message:`${p} is POSTed`},f);let g;try{mn({signature:d.headers.get("palbase-signature"),now:e.now}),g=await mt(d,1048576),await bt({secret:u,signature:d.headers.get("palbase-signature"),body:g,now:e.now})}catch(w){if(w instanceof Ze)return E({status:401,code:"invalid_signature",message:`${p} is the platform's to call: ${w.code}`},f);throw w}let m;try{m=JSON.parse(new TextDecoder().decode(g))}catch{return E({status:400,code:"bad_request",message:`${p} is JSON`},f)}return typeof m!="object"||m===null||!Object.hasOwn(m,"call")||m.call!==new URL(d.url).pathname?E({status:401,code:"invalid_signature",message:`${p} is the platform's to call: signed_for_another_call`},f):{body:m}}async function Mr(d,u,f,p,g){let m=await Ge(u,f,p,`An upload's ${d}`);if(m instanceof Response)return m;let w=jn(d,m.body);if(typeof w=="string")return E({status:400,code:"bad_request",message:`An upload's ${d}: ${w}`},p);if(d==="complete"){if(b.has(w.uploadId))return E({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},p);b.add(w.uploadId),b.size>pt&&b.delete(b.values().next().value)}let R=Kt(r,w.method,w.route);if(!R||"malformed"in R||!R.route.meta.upload)return E({status:404,code:"not_found",message:`No upload route for ${w.method} ${w.route}`},p);let{route:T,params:D}=R,q=R.route.meta.upload,x=Ws(w.user);if(x&&cn(g,x.id),n.get(T).required&&!x)throw new X(401,"unauthorized","This route needs a signed-in user");if(d==="authorize"){let ce=O(T);if(ce!==!1){let W=k.take(`${T.id}\0${xn(w.user,w.client)}`,ce);if(W!==void 0)throw new X(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:W},W)}let te=An(q.pathTemplate,{userId:x?.id??null,uploadId:w.uploadId,filename:w.filename});if("problem"in te)throw new X(400,"bad_request",te.problem);return await Me(e.database,tt(w.user),u.signal,T.id,async()=>{let W={request:u,query:new URLSearchParams(w.query),params:D,user:x,body:w.body===void 0||w.body===null?{}:ae(w.body),requestId:p};await an(T,W);for(let be of T.params)(be.kind==="query"||be.kind==="body"&&w.body!==void 0)&&await Or(be,W)}),de(200,{bucket:q.bucket,path:te.path},p)}g.endpoint=T.id.slice(T.id.indexOf(" ")+1);let P=new URLSearchParams(w.query),L=w.body===null||w.body===void 0?{}:ae(w.body);return wt(T,{request:u,query:P,params:D,user:x,body:L,requestId:p,uploadedObject:ae(w.uploadedObject)},tt(w.user))}function on(d,u,f,p){let g=d?{sub:d.id,role:"authenticated"}:null;return Q.run({requestId:Q.getStore()?.requestId??"",...d?{userId:d.id}:{}},()=>Me(e.database,g,f,u,async()=>{let m=await p();if(f.aborted)throw new Error(`the platform gave up on ${u} before it ended`);return m}))}let sn=(d,u)=>new Response(d,{status:200,headers:{"content-type":"application/json","x-request-id":u}});async function Dr(d,u,f){let p=await Ge(d,u,f,"A tool call");if(p instanceof Response)return p;let g=p.body,m=g.tool;if(typeof m!="string"||m==="")return E({status:400,code:"bad_request",message:"A tool call is {tool, call_id, input, context}: tool names it"},f);let w=l.tools.get(m);if(!w)return E({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(m.slice(0,64))}`},f);let R=g.call_id,T=It(g.context);if(typeof R!="string"||R===""||R.length>256||typeof T=="string")return E({status:400,code:"bad_request",message:`A call of ${m} is {tool, call_id, input, context}${typeof T=="string"?`: ${T}`:""}`},f);let D=Ar("sha256").update(JSON.stringify(g)).digest("hex"),q=h.answered(R);if(q!==void 0)return q.digest!==D?E({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},f):sn(q.answer,f);if(h.isRunning(R))return E({status:409,code:"in_progress",message:"This call is running",retryAfter:2},f);h.start(R);let x;try{let P=await on(T.user,`ai.tool ${m}`,d.signal,()=>w.call(ae(g.input??{}),{...T,callId:R,signal:d.signal}));x=JSON.stringify({output:P.output,is_error:P.is_error});let L=new TextEncoder().encode(x).byteLength;L>4194304&&(_.error(`[palbase] ai.tool ${m} answered ${L} bytes (call ${R}): a machine's answer is ${4194304} at most; the agent is told it failed`),x=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${4194304/(1<<20)} MiB it may be`}],is_error:!0}))}catch(P){if(d.signal.aborted)return h.end(R,void 0),E({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);_.error(`[palbase] ai.tool ${m} failed (call ${R}, chat ${T.chatId}); the agent is told`,{error:P}),x=JSON.stringify({output:[{type:"text",text:Bs(P)}],is_error:!0})}return h.end(R,{digest:D,answer:x}),sn(x,f)}async function Ur(d,u,f){let p=await Ge(d,u,f,"An agent's turn");if(p instanceof Response)return p;let g=It(p.body);if(typeof g=="string"||g.agent==="")return E({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata}${typeof g=="string"?`: ${g}`:": agent names it"}`},f);let m=g.agent,w=l.agents.get(m);if(!w)return E({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(m.slice(0,64))}`},f);let R;try{R=await on(g.user,`ai.agent ${m}`,d.signal,()=>w.resolve({...g,signal:d.signal}))}catch(q){if(d.signal.aborted)return E({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let x=Zt(q,`ai.agent ${m}`);return x?E(x,f):(_.error(`[palbase] ai.agent ${m} failed for chat ${g.chatId}; the turn is not started`,{error:q}),E({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},f))}let T=R.tools.find(q=>l.tools.get(q.name)!==q);if(T)return _.error(`[palbase] ai.agent ${m} handed out ai.tool ${JSON.stringify(T.name)}, which this app did not declare when it was made \u2014 make each ai.tool once, at a module's top level, and hand that one out`),E({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},f);let D=JSON.stringify(R.definition);return new TextEncoder().encode(D).byteLength>4194304?(_.error(`[palbase] ai.agent ${m}'s definition is larger than the ${4194304} bytes a machine's answer may be`),E({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},f)):new Response(D,{status:200,headers:{"content-type":"application/json","x-request-id":f,"cache-control":"no-store"}})}async function Nr(d,u,f,p){let g=await Ge(u,f,p,`A room's ${d}`);if(g instanceof Response)return g;let m=await c.serve(d,g.body,u.signal);return"code"in m?E({status:m.status,code:m.code,message:m.message,retryAfter:m.retryAfter},p):"body"in m?de(200,m.body,p):new Response(null,{status:204,headers:{"x-request-id":p}})}async function an(d,u){let f=[],p={params:Object.freeze({...u.params}),user:ae(u.user),headers:d.meta.upload?new Headers:u.request.headers,requestId:u.requestId};for(let g of d.params)g.kind==="resolve"&&(f[g.index]=await o.get(g).resolve(p,g.options));return f}async function wt(d,u,f,p){let g=t.get(d.controller),m=await Me(e.database,f,u.request.signal,d.id,async()=>{let w=await an(d,u);for(let T of d.params)T.kind!=="resolve"&&(w[T.index]=await Or(T,u));p?.ran();let R=await g[d.fn](...w);if(u.uploadedObject&&u.request.signal.aborted)throw new Error(`storage gave up on ${d.id}'s upload before it was answered`);return p?p.record(_r(xr(R,u.requestId),Q.getStore()?.usedLocales)):R});return p?m:_r(xr(m,u.requestId),Q.getStore()?.usedLocales)}async function dn(d,u){let f=d.headers.get("x-request-id")??"",p=Ks.test(f)?f:`req_${crypto.randomUUID()}`,g=performance.now(),m=new URL(d.url).pathname,w={endpoint:m},R=await Ir(d,u,p,w);return e.telemetry?.record({requestId:p,method:d.method,endpoint:w.endpoint,path:m,status:R.status,durationMs:performance.now()-g,userId:w.userId}),R}function cn(d,u){d.userId=u;let f=Q.getStore();f&&(f.userId=u)}async function Ir(d,u,f,p){let g=e.strings,m=g?{requestId:f,strings:g,locales:vn(d.headers.get("accept-language"),g.source),usedLocales:[]}:{requestId:f},w=await Lr(m,d,u,f,p);return g&&ht(w.headers,"Accept-Language"),w}async function Lr(d,u,f,p,g){return Q.run(d,async()=>{let m=new URL(u.url),w=`${u.method} ${m.pathname}`;try{if(m.pathname===Bt&&Y.size>0)return u.method!=="POST"?E({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},p):e.webhookSecret?await gt(u,p):E({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},p);let R=we(m.pathname);if(R)return w=`webhook ${R.name}`,u.method!=="POST"?E({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},p):await Ue(u,m,R,p);if(e.platform&&(m.pathname===De||m.pathname.startsWith(`${De}/`)))return w=m.pathname===De?"jobs":`job ${m.pathname.slice(De.length+1)}`,await Ye(u,m,e.platform.secret,p);if(e.platform&&(m.pathname===xt||m.pathname===_n)){let N=m.pathname===xt?"authorize":"complete";return w=`upload ${N}`,await Mr(N,u,e.platform.secret,p,g)}if(e.platform&&m.pathname.startsWith(`${Ot}/`)){let N=m.pathname.slice(Ot.length+1);return w=`room ${N}`,await Nr(N,u,e.platform.secret,p)}if(e.platform&&m.pathname===er)return w="ai tool call",await Dr(u,e.platform.secret,p);if(e.platform&&m.pathname===tr)return w="ai agent's turn",await Ur(u,e.platform.secret,p);if(ta(m.pathname))return E({status:404,code:"not_found",message:`No route for ${u.method} ${m.pathname}`},p);let T=Kt(r,u.method,m.pathname);if(T&&"malformed"in T)return E({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},p);if(!T)return E({status:404,code:"not_found",message:`No route for ${u.method} ${m.pathname}`},p);let{route:D,params:q}=T;if(w=D.id,g.endpoint=D.id.slice(D.id.indexOf(" ")+1),D.meta.upload)throw new X(400,"upload_required",`${D.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let x=n.get(D),P=null,L=null,ce=u.headers.get("authorization")??"",te=/^(bearer|dpop)\s+(\S+)$/i.exec(ce),W=te?.[2],be=te?.[1].toLowerCase()==="dpop";if(W)try{let N=!be&&e.tokens&&!Vs.test(W)&&e.tokens.accepts(W)?e.tokens:void 0,ve=N?await $.ask(W,ft(u.headers,f.remoteAddress),()=>Me(e.database,null,u.signal,"token",()=>N.resolve(W))):await e.verifier.verify(W,be?{proof:u.headers.get("dpop"),method:u.method,url:gn(u.headers,m)}:void 0);P=Fs(ve),L=ve.claims}catch(N){if(!x.required&&(N instanceof Xe||N instanceof Qe||N instanceof Ke))P=null;else throw N instanceof Ke?new X(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:N.wait},N.wait):N instanceof Xe?new X(401,"invalid_token","The access token is not valid",{reason:N.reason},void 0,Js(N.reason)):N}else if(ce!==""&&x.required)throw new X(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(P&&cn(g,P.id),x.required&&!P)throw new X(401,"unauthorized","This route needs a signed-in user");if(x.verifiedEmail&&!P?.emailVerified)throw new X(403,"email_not_verified","This route needs a verified email address");let un=O(D);if(un!==!1){let N=P?`u:${P.id}`:`a:${ft(u.headers,f.remoteAddress)}`,ve=k.take(`${D.id}\0${N}`,un);if(ve!==void 0)throw new X(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:ve},ve)}let Ne=u.method==="GET"||u.method==="HEAD"?void 0:await mt(u,v),Jr=Ne===void 0?void 0:zs(Ne),ln={request:u,query:m.searchParams,params:q,user:P,body:Jr,raw:Ne,requestId:p},fn=I&&Ne!==void 0&&Be(D)?fr(u.method,u.headers):void 0;if(!I||fn===void 0)return await wt(D,ln,L);let Hr={role:Yt(e.database.requests,L).role,uid:P?.id??`a:${ft(u.headers,f.remoteAddress)}`},pn=!1;return await I.serve({key:fn,caller:Hr,method:u.method,uri:`${m.pathname}${m.search}`,body:Ne},N=>wt(D,ln,L,{record:N,ran:()=>{pn=!0}}),{requestId:p,refusal:N=>E(N,p),failure:N=>Sr(N,p,w,u.signal),ran:()=>pn})}catch(R){return Sr(R,p,w,u.signal)}})}return{handle:Ve,routes:r.map(d=>d.id),contract:V,start:()=>t.start(),stop:async()=>{c.close();for(let d of U.keys())pe(d);await t.shutdown(),await e.telemetry?.flush()}}}function Xs(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function Qs(e){let t=new Set;for(let[r,n]of e)if(St(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 xr(e,t){return e instanceof Response?qs(e,t):e==null?new Response(null,{status:204,headers:{"x-request-id":t}}):de(200,e,t)}function ea(e,t){if(!(!qe(e)||e.status!==503||!en(e)))return _.warn(`[palbase] webhook ${t}: the database did not answer (${e.error})`,{error:e}),{status:503,code:e.error,message:e.errorDescription,data:e.data,retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))}}function ta(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return Se.has(decodeURIComponent(t))}catch{return Se.has(t)}}var na="GET, POST, PUT, PATCH, DELETE, QUERY",ra=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function oa(e){if(!e)return;if(e.origins!=="*"){for(let n of e.origins)if(!ra.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":na,"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 Or(e,t){switch(e.kind){case"body":return Vt(e.schema,t.body??{},"Request body");case"query":return Vt(e.schema,ae(Object.fromEntries(t.query)),"Query parameters");case"headers":{let r={};return t.request.headers.forEach((n,o)=>r[o.toLowerCase()]=n),ae(r),e.schema?Vt(e.schema,r,"Request headers"):r}case"param":return t.params[e.name];case"user":case"optionalUser":return ae(t.user);case"req":return t.raw===void 0?t.request:new Request(t.request.url,{method:t.request.method,headers:t.request.headers,body:t.raw,signal:t.request.signal});case"requestId":return t.requestId;case"resolve":throw new Error("@Resolve parameters are made by their resolver, before the others");case"uploadedObject":return t.uploadedObject;case"client":{let r=t.request.headers;return ae({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 nn=720*3600;function tn(e){return e instanceof ke&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function jr(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),nn)}function Cr(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var rn=class{filling=new Map;async get(t){try{let r=await $e.cache.getCacheEntry({query:{key:t}});return r.data.found?r.data.value??null:null}catch(r){if(!tn(r))throw r;return _.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 $e.cache.putCacheEntry({query:{key:t},body:{value:Cr(r),ttl:jr(n)}})}catch(o){if(!tn(o))throw o;_.warn("cache: a write could not reach the cache; it is let go",{key:t,status:o.status})}}async del(t){await $e.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await $e.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 $e.cache.getCacheEntry({query:{key:t}})).data}catch(c){if(!tn(c))throw c;_.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}},rd=wn("Cache",new rn);function od(e={}){let t=e.maxEntries??5e4,r=e.now??(()=>Date.now()),n=new Map,o=new Map,s=l=>{let h=n.get(l);if(h&&h.expiresAt<=r()){n.delete(l);return}return h},a=()=>{let l=r();for(let[b,S]of n)S.expiresAt<=l&&n.delete(b);if(n.size<t)return;let h=[...n.entries()].sort((b,S)=>b[1].expiresAt-S[1].expiresAt);for(let[b]of h.slice(0,Math.ceil(h.length/4)))n.delete(b)},i=async(l,h,b)=>{n.size>=t&&!n.has(l)&&a(),n.set(l,{value:Cr(h),expiresAt:r()+(jr(b)??nn)*1e3})};return{get:async l=>{let h=s(l);return h?structuredClone(h.value):null},set:i,async del(l){n.delete(l)},async incr(l){let h=s(l),b=(typeof h?.value=="number"&&Number.isInteger(h.value)?h.value:0)+1;return n.set(l,{value:b,expiresAt:h?.expiresAt??r()+nn*1e3}),b},getOrSet(l,h,b){let S=s(l);if(S)return Promise.resolve(structuredClone(S.value));let I=o.get(l);if(I)return I;let y=(async()=>{try{let C=await b();return await i(l,C,h),C}finally{o.delete(l)}})();return o.set(l,y),y}}}export{Et as a,me as b,_e as c,da as d,ca as e,ua as f,la as g,fa as h,pa as i,ma as j,ha as k,ga as l,ya as m,wa as n,ba as o,va as p,ka as q,$a as r,Ra as s,Ea as t,_a as u,Sa as v,xa as w,Oa as x,Ta as y,Aa as z,j as A,Pa as B,ja as C,Na as D,Ia as E,za as F,Fa as G,Wa as H,Ka as I,Va as J,Ya as K,Ga as L,ei as M,z as N,Yn as O,Gn as P,Zn as Q,Io as R,di as S,li as T,fi as U,pi as V,mi as W,hi as X,gi as Y,yi as Z,wi as _,Si as $,Cs as aa,Qi as ba,nn as ca,rd as da,od as ea};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import"./
|
|
1
|
+
/*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import"./ODFLUINN.js";import{pathToFileURL as i}from"node:url";import{z as c}from"zod";async function f(e){let n=new Map,t=new Map;for(let r of e){let a=`${r.className}.${r.method}`,o=t.get(r.className);if(o!==void 0&&o!==r.file)throw new Error(`two controllers are named ${r.className} (${o}, ${r.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(r.className,r.file),n.set(a,{returns:await u(r),throws:r.throws})}return r=>n.get(`${r.controller.name}.${r.fn}`)}async function u(e){let n=`${e.file} \u2014 ${e.className}.${e.method}`;switch(e.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let r=(await import(i(e.returns.file).href))[e.returns.exportName];if(!s(r))throw new Error(`${n}: its return type names ${e.returns.exportName}, which ${e.returns.file} exports as no schema (a zod, valibot or arktype schema)`);return{kind:"json",schema:r,array:e.returns.array}}case"expression":{let t=new Function("z",`return (${e.returns.expression});`)(c);if(!s(t))throw new Error(`${n}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function s(e){return typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function"}export{f as routeContracts};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{
|
|
1
|
+
/*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{d as O}from"./3OIKIBMG.js";import{a as E,b as T,e as _}from"./2AT72FFB.js";var a=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(n,t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="BackendError",this.kind=n,this.code=t.code,this.status=t.status??0,this.requestId=t.requestId,this.fields=t.fields,this.retryAfter=t.retryAfter,this.data=t.data}};function D(e){return e instanceof a||typeof e=="object"&&e!==null&&e.name==="BackendError"&&typeof e.kind=="string"}function $(e){let n=e.body,t={code:e.code,message:e.message,status:e.status,requestId:e.requestId??se(n,"request_id"),data:b(n,"data"),cause:e};if(e.code==="network_error")return new a("network",t);if(e.status===401)return new a("unauthorized",t);if(e.status===429)return new a("rateLimited",{...t,retryAfter:oe(n)??e.retryAfter});let r=re(n);return e.status===400&&r?new a("validation",{...t,fields:r}):new a("server",t)}function P(e){return e instanceof T||e instanceof Error&&e.name==="PalbaseError"}function j(e){return Array.isArray(e)&&e.length>0&&e.every(n=>typeof n=="object"&&n!==null&&typeof n.field=="string"&&typeof n.message=="string")}function re(e){let n=b(b(e,"data"),"fields");if(j(n))return n;let t=b(e,"fields");return j(t)?t:void 0}function oe(e){return N(e,"retry_after")??N(b(e,"data"),"retryAfter")}function b(e,n){if(typeof e=="object"&&e!==null)return e[n]}function N(e,n){let t=b(e,n);return typeof t=="number"?t:void 0}function se(e,n){let t=b(e,n);return typeof t=="string"?t:void 0}var ie=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ae=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),ce=new Set(ae),de=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function S(e){return e==="then"||e==="toJSON"||de.has(e)}function A(e){return e==="call"||e==="join"||S(e)}function C(e){return typeof e=="string"&&ie.test(e)&&!ce.has(e)&&!S(e)}function B(e){return typeof e=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(e)}function I(e){_(e)}function J(e){return _(e).origin}var R=class extends Error{reason;constructor(n,t){super(n),this.name="RoomError",this.reason=t}},q=new WeakMap;async function U(e,n,t){let{pattern:r,events:o,messages:s}=pe(n),i=ue(r,t),c=q.get(e);c||q.set(e,c=new Map);let p=c;p.set(i,(p.get(i)??0)+1);let u=e.channel(i),l=()=>{let d=(p.get(i)??1)-1;d>0?p.set(i,d):(p.delete(i),u.leave())};try{await u.join()}catch{let d=u.state==="refused"?K(u.refusal,"unavailable"):"socket closed";throw l(),new R(`room ${JSON.stringify(i)} was not joined: ${d}`,d)}let m=!1,w=new Set,k=()=>{if(!m){m=!0,h();for(let d of[...w])d();l()}},h=u.onClosed(k),y=d=>{if(m)return()=>{};let v=u.on("broadcast",f=>{typeof f.event=="string"&&o.has(f.event)&&d(f.event,E(f.payload))}),g=()=>{w.delete(g),v()};return w.add(g),g};return{topic:i,on(d,v){if(typeof d=="function")return y((g,f)=>d({event:g,payload:f}));if(!o.has(d))throw new TypeError(`room ${JSON.stringify(r)} declares no event ${JSON.stringify(String(d))}`);if(typeof v!="function")throw new TypeError(`room ${JSON.stringify(r)}: on(${JSON.stringify(d)}, \u2026) takes the function the event is handed to`);return y((g,f)=>{g===d&&v(f)})},off(d){w.has(d)&&d()},async send(d,v){if(!s.has(d))throw new TypeError(`room ${JSON.stringify(r)} declares no message ${JSON.stringify(String(d))}`);let g=m?{status:"error",response:{reason:"not joined"}}:await u.push("broadcast",{type:"broadcast",event:d,payload:v});if(g.status==="ok")return;let f=K(g.response,"unavailable");throw new R(`room ${JSON.stringify(i)} did not take ${JSON.stringify(d)}: ${f}`,f)},leave:k}}function pe(e){let n=typeof e=="object"&&e!==null?e:{},t=r=>Array.isArray(r)&&r.every(o=>typeof o=="string");if(typeof n.pattern!="string"||n.pattern===""||!t(n.events)||!t(n.messages))throw new TypeError("join takes a room of the backend's generated module: its pattern, its events and its messages");return{pattern:n.pattern,events:new Set(n.events),messages:new Set(n.messages)}}function ue(e,n){let t=typeof n=="object"&&n!==null?n:{};return e.split(":").map(r=>{if(!(r.startsWith("{")&&r.endsWith("}")&&r.length>2))return r;let o=r.slice(1,-1),s=Object.hasOwn(t,o)?t[o]:void 0;if(typeof s!="string"||s==="")throw new TypeError(`room ${JSON.stringify(e)} needs a value for ${JSON.stringify(o)}`);if(s.includes(":"))throw new TypeError(`room ${JSON.stringify(e)}: the value of ${JSON.stringify(o)} is one segment of the channel's name and cannot hold ":"`);return s}).join(":")}function K(e,n){let t=e?.reason;return typeof t=="string"&&t!==""?t:n}var x=class{pending="";dataLines=[];eventName;consume(n){this.pending+=n.replace(/\r\n/g,`
|
|
3
3
|
`);let t=[],r=this.pending.indexOf(`
|
|
4
4
|
`);for(;r!==-1;){let o=this.pending.slice(0,r);this.pending=this.pending.slice(r+1);let s=o.endsWith("\r")?o.slice(0,-1):o;if(s==="")this.dataLines.length>0&&t.push({event:this.eventName,payload:this.dataLines.join(`
|
|
5
5
|
`)}),this.dataLines=[],this.eventName=void 0;else if(!s.startsWith(":")){if(s.startsWith("data:")){let i=s.slice(5);this.dataLines.push(i.startsWith(" ")?i.slice(1):i)}else if(s.startsWith("event:")){let i=s.slice(6);this.eventName=i.startsWith(" ")?i.slice(1):i}}r=this.pending.indexOf(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
1
|
+
/*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
|
|
2
2
|
var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{AsyncLocalStorage as v}from"node:async_hooks";function x(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var A=Symbol.for("palbase.backend.requestScope"),c=globalThis[A]??=new v,b;function I(n){b=n}var N=new Proxy({},{get(n,e){if(!b)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return b[e]}}),C=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function g(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=O(t);n==="error"||n==="warn"?process.stderr.write(`${o}
|
|
3
|
+
`):process.stdout.write(`${o}
|
|
4
|
+
`)}function O(n){try{return JSON.stringify(n)}catch{let e=new WeakSet;try{return JSON.stringify(n,(s,t)=>{if(typeof t=="bigint")return t.toString();if(typeof t=="object"&&t!==null){if(e.has(t))return"[circular]";e.add(t)}return t})}catch{return JSON.stringify({time:n.time,level:n.level,msg:n.msg,request_id:n.request_id,unwritable:"a field of this line could not be written"})}}}var m=x("Log",{debug:(n,e)=>g("debug",n,e),info:(n,e)=>g("info",n,e),warn:(n,e)=>g("warn",n,e),error:(n,e)=>g("error",n,e)});var T=512,k=8,L=64,E=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,h={"i-klingon":"tlh","en-gb-oed":"en-GB-oxendict","sgn-be-fr":"sfb","zh-cmn-hans":"cmn-Hans","zh-yue":"yue","hy-arevela":"hy-arevela"};function P(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function _(n){let e=n.split("-"),s=(e[0]??"").toLowerCase();return s==="mo"&&e.length===1?"ro-MD":s==="tl"?(e[0]="fil",e.join("-")):s==="sh"?(e[0]="sr",e.length>1&&/^[A-Za-z]{4}$/.test(e[1]??"")||e.splice(1,0,"Latn"),e.join("-")):n}function q(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>L)return;let s=e.toLowerCase(),t=Object.hasOwn(h,s)?h[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales(_(e))[0]}catch{return}if(t===void 0)return}let i=P(t);if(!(i===""||i==="und"||i==="mul"))return t}function D(n){let e=n.split("-"),s=e.findIndex((r,a)=>a>0&&r.length===1),t=s>0?e.slice(0,s):e,i=[],o=r=>{i.includes(r)||i.push(r)};for(let r=t.length;r>1||r===t.length;r--)o(t.slice(0,r).join("-"));if(!t.slice(1).some(r=>/^[A-Za-z]{4}$/.test(r)))try{let r=new Intl.Locale(t.join("-")).maximize().script;r&&o(`${t[0]}-${r}`)}catch{}return o(t[0]),i}function G(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=T){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,l=r.indexOf(";");if(l>=0){let y=r.slice(l+1);r=r.slice(0,l).trim();for(let f of y.split(";")){let p=f.indexOf("=");if(p<0||f.slice(0,p).trim().toLowerCase()!=="q")continue;let w=f.slice(p+1).trim(),d=E.test(w)?Number(w):Number.NaN;a=Number.isFinite(d)&&d>=0&&d<=1?d:0}}a>0&&i.push({tag:r,q:a,at:i.length})}i.sort((o,r)=>r.q-o.q||o.at-r.at);for(let{tag:o}of i.slice(0,k)){let r=q(o);if(r!==void 0)for(let a of D(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function $(n,e,s){let t=n.strings??{},i=Object.hasOwn(t,e)?t[e]:null;for(let o of s){if(o===n.source)break;let r=i!=null&&Object.hasOwn(i,o)?i[o]:void 0;if(typeof r=="string"&&r!=="")return{text:r,locale:o}}return{text:e,locale:n.source}}var j=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function S(n,e){return n.replace(j,(s,t,i,o)=>{if(o[i-1]==="{"||o[i+s.length]==="}")return s;let r=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return r==null?"":String(r)})}var u;function K(n){u=n===void 0?void 0:{root:n,said:!1}}function Z(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,m.warn(`[palbase] t(): the app has no palbase/strings (looked in ${u.root}) \u2014 every sentence is said as it is written. \`npx palbase strings\` starts the table; an image takes it with COPY palbase ./palbase`)),S(n,e);let{text:i,locale:o}=$(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),S(i,e)}export{x as a,R as b,c,I as d,N as e,C as f,m as g,G as h,K as i,Z as j};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palbase 0.
|
|
2
|
-
import{a as D}from"./4YD2XCGF.js";import{a as A,b as R,c as b,d as x,e as O,f as j,g as M,h as U,i as C,j as L,k as K,l as $}from"./NK54UVDI.js";import{a as N,b as I}from"./IXHR57QC.js";import{b as v,d as w}from"./UXRIXHHY.js";var ae=/^pb_[a-z0-9]+_s/;function E(n){if(D())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!ae.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=I(w({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??N);return{ai:A.client(e),analytics:R.client(e),auth:b.client(e),cache:x.client(e),flags:O.client(e),machines:j.client(e),notify:M.client(e),purchases:U.client(e),realtime:C.client(e),secrets:L.client(e),storage:K.client(e),stores:$.client(e),transport:e,url:new URL(n.url).origin}}var f=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},ue=300,de=/^[0-9]{1,12}$/,le=/^[0-9a-f]{64}$/,W=8,fe=/^whsec_[0-9A-Za-z]{32,}$/,he=1024*1024;async function B(n){if(typeof n.secret!="string"||!fe.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await F(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(z(n.body)))}catch{throw new f("invalid_body","the signed body is not JSON")}if(!be(e))throw new f("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function F(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=z(n.body),{t,v1:r}=H(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign("HMAC",s,we(new TextEncoder().encode(`${t}.`),e))),a=!1;for(let u of r)me(o,ge(u))&&(a=!0);if(!a)throw new f("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function H(n){let e=n.toleranceSeconds??ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new f("missing_signature","the request carries no Palbase-Signature header");let s,o=[];for(let a of r.split(",")){let u=a.indexOf("=");if(u<=0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=a.slice(0,u).trim(),i=a.slice(u+1).trim();if(c==="t"){if(s!==void 0||!de.test(i))throw new f("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=i}else if(c==="v1"){if(!le.test(i))throw new f("malformed_signature","a v1 is 64 lowercase hex characters");if(o.length===W)throw new f("malformed_signature",`Palbase-Signature carries at most ${W} v1`);o.push(i)}}if(s===void 0||o.length===0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new f("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:o}}async function pe(n,e,t={}){let r=await ye(n,t.maxBytes??he);return B({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function ye(n,e){let t=()=>new f("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),o=[],a=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;if(a+=l.byteLength,a>e)throw await s.cancel().catch(()=>{}),t();o.push(l)}let u=new Uint8Array(a),c=0;for(let i of o)u.set(i,c),c+=i.byteLength;return u}function z(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function ge(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function me(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function we(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function be(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var V=60,ke=60,Se=8*1024,ve=1e5;function _(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Y(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function J(n){let e=Y(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var k=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=ve){this.max=e}spend(e,t){if(t>=e.until)throw new d("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new d("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,o]of t){if(o>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[o,a]of s)a>e||(s.delete(o),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function Ee(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return _(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function q(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function G(n,e,t,r){let s=ie=>{throw new d("proof",`the DPoP proof is not taken: ${ie}`)},o=t.proof;if(!o)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(o.length>Se)return s("it is too long");let a=o.split(".");if(a.length!==3)return s("it is not a JWS of three parts");let u=J(a[0]),c=J(a[1]);if(!u||!c)return s("its header or claims are not base64url JSON");if(u.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(u.alg!=="ES256")return s(`it is signed with ${String(u.alg)}; only ES256 is taken`);let i=u.jwk;if(!i||typeof i!="object"||i.kty!=="EC"||i.crv!=="P-256"||typeof i.x!="string"||typeof i.y!="string")return s("its header carries no P-256 public key");if("d"in i)return s("its header carries a private key");if(await Ee(i.x,i.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:i.x,y:i.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let p=Y(a[2]);if(!p||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,p,new TextEncoder().encode(`${a[0]}.${a[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let h=typeof c.htu=="string"?q(c.htu):void 0,y=q(t.url);if(!h||!y||h!==y)return s(`it is for ${String(c.htu)}, not ${y??t.url}`);let re=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-re)>V)return s("it was not made within a minute of now");let se=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let oe=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:oe,until:(c.iat+V+ke)*1e3+1}}var d=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},g=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}};function _e(n){return async e=>{let t=b.client(w({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch}));try{return await t.verifyTokenUser(),!0}catch(r){if(r instanceof v&&r.status===401)return!1;throw r}}}var T={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},X=60,Te=16*1024,Pe=10*6e4,Ae=5e4,Z=n=>typeof n=="string"&&Object.hasOwn(T,n),P=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new k;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>Te)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let s=Q(r[0]),o=Q(r[1]);if(!s||!o)throw new d("malformed","the token header or claims are not base64url JSON");let a=s.alg;if(!Z(a))throw new d("algorithm",`the token is signed with ${String(a)}; only ES256 and PS256 are taken`);let u=s.kid;if(typeof u!="string"||u==="")throw new d("malformed","the token header names no kid");let c=await this.key(u);if(!c)throw new d("unknown_key",`no key ${u} in the project's key set`);if(c.alg!==a)throw new d("algorithm",`key ${u} is ${c.alg}, the token says ${a}`);let i=te(r[2]);if(!i)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(T[c.alg].verify,c.key,i,l).catch(()=>!1))throw new d("signature","the signature does not verify");let m=this.check(o),h=o.cnf,y;if(h!==void 0){if(!t)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof h!="object"||h===null||typeof h.jkt!="string"||h.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");y=await G(e,h.jkt,t,this.now())}else if(t)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,m.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return y&&this.seenProofs.spend(y,this.now()),m}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:xe(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let o=s[1].toLowerCase()==="dpop",a=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],o?{proof:t.get("dpop"),method:e.method,url:ee(t,a)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let o=this.asking.get(t);o||(o=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,o));let a;try{a=await o}catch(c){let i=this.standings.get(t),l=this.now();if(i&&l<i.at+this.standingStaleMs)return i.until=Math.min(l+this.standingTtlMs,i.at+this.standingStaleMs),i.live;throw new g("a session's standing cannot be read now",{cause:c})}let u=this.now();return this.standings.delete(t),this.standings.set(t,{live:a,at:u,until:u+this.standingTtlMs}),this.standings.size>Ae&&this.standings.delete(this.standings.keys().next().value),a}check(e){if(e.iss!==this.issuer)throw new d("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+X<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-X>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new d("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Pe;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new g("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(o){if(!s)throw o}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(o){throw this.lastFailure=o,new g("the project's key set cannot be read now",{cause:o})}this.lastFailure=void 0;let r=new Map;for(let o of Array.isArray(e.keys)?e.keys:[]){let a=o.alg;if(typeof o.kid!="string"||!Z(a))continue;let u=T[a];if(o.kty!==u.kty||o.use!==void 0&&o.use!=="sig")continue;let{d:c,...i}=o;try{r.set(o.kid,{alg:a,key:await crypto.subtle.importKey("jwk",i,u.import,!1,["verify"])})}catch{}}this.keys=r;let s=Oe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function ee(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Re.test(s)?`${r}://${s}${e.pathname}`:""}var Re=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function xe(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Oe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function te(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Q(n){let e=te(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function je(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var S=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Me(n,e,t,r){let{idempotencyKey:s,amount:o,ttlSeconds:a,metadata:u}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:o,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...a!==void 0?{ttl_seconds:a}:{},...u!==void 0?{metadata:u}:{}},i=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(i.status!=="held")throw new S(i);let l={customer_id:i.customer,spend_id:i.id},p;try{p=await r(i)}catch(m){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),m}return await n.purchases.commitSpend({path:l}),p}async function*Ue(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var Ce=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Le=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function ne(n){return!Ce.test(n)||Le.test(n)||/_PROXY$/i.test(n)}var Ke=/^(PORT|PALBASE_(URL|PROJECT_ID|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function $e(n){return Ke.test(n)}async function Ne(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let o=E({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:a}=await o.secrets.getEnvironmentValues({path:{environment:t}}),u=[],c=[],i=[];for(let[l,p]of Object.entries(a.values)){if(ne(l)){i.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=p,u.push(l)}return{set:t,loaded:u.sort(),kept:c.sort(),refused:i.sort()}}export{E as a,f as b,B as c,F as d,H as e,pe as f,d as g,g as h,_e as i,P as j,ee as k,je as l,S as m,Me as n,Ue as o,ne as p,$e as q,Ne as r};
|
|
1
|
+
/*! palbase 0.4.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as D}from"./UNTTPATW.js";import{a as A,b as R,c as b,d as x,e as O,f as j,g as M,h as U,i as C,j as L,k as K,l as $}from"./ZFX4BFQR.js";import{a as N,b as I}from"./3OIKIBMG.js";import{b as v,d as w}from"./2AT72FFB.js";var ae=/^pb_[a-z0-9]+_s/;function E(n){if(D())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!ae.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=I(w({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??N);return{ai:A.client(e),analytics:R.client(e),auth:b.client(e),cache:x.client(e),flags:O.client(e),machines:j.client(e),notify:M.client(e),purchases:U.client(e),realtime:C.client(e),secrets:L.client(e),storage:K.client(e),stores:$.client(e),transport:e,url:new URL(n.url).origin}}var f=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},ue=300,de=/^[0-9]{1,12}$/,le=/^[0-9a-f]{64}$/,W=8,fe=/^whsec_[0-9A-Za-z]{32,}$/,he=1024*1024;async function B(n){if(typeof n.secret!="string"||!fe.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await F(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(z(n.body)))}catch{throw new f("invalid_body","the signed body is not JSON")}if(!be(e))throw new f("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function F(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=z(n.body),{t,v1:r}=H(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign("HMAC",s,we(new TextEncoder().encode(`${t}.`),e))),a=!1;for(let u of r)me(o,ge(u))&&(a=!0);if(!a)throw new f("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function H(n){let e=n.toleranceSeconds??ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new f("missing_signature","the request carries no Palbase-Signature header");let s,o=[];for(let a of r.split(",")){let u=a.indexOf("=");if(u<=0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=a.slice(0,u).trim(),i=a.slice(u+1).trim();if(c==="t"){if(s!==void 0||!de.test(i))throw new f("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=i}else if(c==="v1"){if(!le.test(i))throw new f("malformed_signature","a v1 is 64 lowercase hex characters");if(o.length===W)throw new f("malformed_signature",`Palbase-Signature carries at most ${W} v1`);o.push(i)}}if(s===void 0||o.length===0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new f("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:o}}async function pe(n,e,t={}){let r=await ye(n,t.maxBytes??he);return B({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function ye(n,e){let t=()=>new f("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),o=[],a=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;if(a+=l.byteLength,a>e)throw await s.cancel().catch(()=>{}),t();o.push(l)}let u=new Uint8Array(a),c=0;for(let i of o)u.set(i,c),c+=i.byteLength;return u}function z(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function ge(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function me(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function we(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function be(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var V=60,ke=60,Se=8*1024,ve=1e5;function _(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Y(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function J(n){let e=Y(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var k=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=ve){this.max=e}spend(e,t){if(t>=e.until)throw new d("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new d("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,o]of t){if(o>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[o,a]of s)a>e||(s.delete(o),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function Ee(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return _(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function q(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function G(n,e,t,r){let s=ie=>{throw new d("proof",`the DPoP proof is not taken: ${ie}`)},o=t.proof;if(!o)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(o.length>Se)return s("it is too long");let a=o.split(".");if(a.length!==3)return s("it is not a JWS of three parts");let u=J(a[0]),c=J(a[1]);if(!u||!c)return s("its header or claims are not base64url JSON");if(u.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(u.alg!=="ES256")return s(`it is signed with ${String(u.alg)}; only ES256 is taken`);let i=u.jwk;if(!i||typeof i!="object"||i.kty!=="EC"||i.crv!=="P-256"||typeof i.x!="string"||typeof i.y!="string")return s("its header carries no P-256 public key");if("d"in i)return s("its header carries a private key");if(await Ee(i.x,i.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:i.x,y:i.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let p=Y(a[2]);if(!p||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,p,new TextEncoder().encode(`${a[0]}.${a[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let h=typeof c.htu=="string"?q(c.htu):void 0,y=q(t.url);if(!h||!y||h!==y)return s(`it is for ${String(c.htu)}, not ${y??t.url}`);let re=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-re)>V)return s("it was not made within a minute of now");let se=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let oe=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:oe,until:(c.iat+V+ke)*1e3+1}}var d=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},g=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}};function _e(n){return async e=>{let t=b.client(w({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch}));try{return await t.verifyTokenUser(),!0}catch(r){if(r instanceof v&&r.status===401)return!1;throw r}}}var T={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},X=60,Te=16*1024,Pe=10*6e4,Ae=5e4,Z=n=>typeof n=="string"&&Object.hasOwn(T,n),P=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new k;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>Te)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let s=Q(r[0]),o=Q(r[1]);if(!s||!o)throw new d("malformed","the token header or claims are not base64url JSON");let a=s.alg;if(!Z(a))throw new d("algorithm",`the token is signed with ${String(a)}; only ES256 and PS256 are taken`);let u=s.kid;if(typeof u!="string"||u==="")throw new d("malformed","the token header names no kid");let c=await this.key(u);if(!c)throw new d("unknown_key",`no key ${u} in the project's key set`);if(c.alg!==a)throw new d("algorithm",`key ${u} is ${c.alg}, the token says ${a}`);let i=te(r[2]);if(!i)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(T[c.alg].verify,c.key,i,l).catch(()=>!1))throw new d("signature","the signature does not verify");let m=this.check(o),h=o.cnf,y;if(h!==void 0){if(!t)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof h!="object"||h===null||typeof h.jkt!="string"||h.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");y=await G(e,h.jkt,t,this.now())}else if(t)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,m.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return y&&this.seenProofs.spend(y,this.now()),m}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:xe(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let o=s[1].toLowerCase()==="dpop",a=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],o?{proof:t.get("dpop"),method:e.method,url:ee(t,a)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let o=this.asking.get(t);o||(o=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,o));let a;try{a=await o}catch(c){let i=this.standings.get(t),l=this.now();if(i&&l<i.at+this.standingStaleMs)return i.until=Math.min(l+this.standingTtlMs,i.at+this.standingStaleMs),i.live;throw new g("a session's standing cannot be read now",{cause:c})}let u=this.now();return this.standings.delete(t),this.standings.set(t,{live:a,at:u,until:u+this.standingTtlMs}),this.standings.size>Ae&&this.standings.delete(this.standings.keys().next().value),a}check(e){if(e.iss!==this.issuer)throw new d("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+X<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-X>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new d("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Pe;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new g("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(o){if(!s)throw o}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(o){throw this.lastFailure=o,new g("the project's key set cannot be read now",{cause:o})}this.lastFailure=void 0;let r=new Map;for(let o of Array.isArray(e.keys)?e.keys:[]){let a=o.alg;if(typeof o.kid!="string"||!Z(a))continue;let u=T[a];if(o.kty!==u.kty||o.use!==void 0&&o.use!=="sig")continue;let{d:c,...i}=o;try{r.set(o.kid,{alg:a,key:await crypto.subtle.importKey("jwk",i,u.import,!1,["verify"])})}catch{}}this.keys=r;let s=Oe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function ee(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Re.test(s)?`${r}://${s}${e.pathname}`:""}var Re=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function xe(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Oe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function te(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Q(n){let e=te(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function je(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var S=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Me(n,e,t,r){let{idempotencyKey:s,amount:o,ttlSeconds:a,metadata:u}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:o,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...a!==void 0?{ttl_seconds:a}:{},...u!==void 0?{metadata:u}:{}},i=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(i.status!=="held")throw new S(i);let l={customer_id:i.customer,spend_id:i.id},p;try{p=await r(i)}catch(m){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),m}return await n.purchases.commitSpend({path:l}),p}async function*Ue(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var Ce=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Le=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function ne(n){return!Ce.test(n)||Le.test(n)||/_PROXY$/i.test(n)}var Ke=/^(PORT|PALBASE_(URL|PROJECT_ID|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function $e(n){return Ke.test(n)}async function Ne(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let o=E({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:a}=await o.secrets.getEnvironmentValues({path:{environment:t}}),u=[],c=[],i=[];for(let[l,p]of Object.entries(a.values)){if(ne(l)){i.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=p,u.push(l)}return{set:t,loaded:u.sort(),kept:c.sort(),refused:i.sort()}}export{E as a,f as b,B as c,F as d,H as e,pe as f,d as g,g as h,_e as i,P as j,ee as k,je as l,S as m,Me as n,Ue as o,ne as p,$e as q,Ne as r};
|