palbase 0.69.1 → 0.71.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.
Files changed (50) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai-sdk/index.js +2 -2
  3. package/dist/backend/engine.js +2 -2
  4. package/dist/backend/env.js +1 -1
  5. package/dist/backend/index.js +9 -9
  6. package/dist/backend/stack.js +1 -1
  7. package/dist/backend/test.js +2 -2
  8. package/dist/chunks/{D6ZVNWQ2.js → 4RTYKYU6.js} +2 -2
  9. package/dist/chunks/{LQF6CVJR.js → 5EP5JREH.js} +1 -1
  10. package/dist/chunks/{CE6XFRSZ.js → 6DOVOQD7.js} +2 -2
  11. package/dist/chunks/{CPTZEOT3.js → 6G26LJYB.js} +1 -1
  12. package/dist/chunks/{XK7JQGKM.js → 6I2XBWUM.js} +2 -2
  13. package/dist/chunks/AVLXOKYL.js +2 -0
  14. package/dist/chunks/{OZM5TI3D.js → AYPODLGK.js} +2 -2
  15. package/dist/chunks/{KOX5W2ID.js → C7I5HJWB.js} +1 -1
  16. package/dist/chunks/{JFVOERVR.js → E3JCXDTW.js} +2 -2
  17. package/dist/chunks/{EZW67SHF.js → F5D2WPY6.js} +2 -2
  18. package/dist/chunks/{OE772CLE.js → FHSOCZK5.js} +3 -3
  19. package/dist/chunks/{CRK2KWFW.js → KWAJFRHM.js} +2 -2
  20. package/dist/chunks/{BZYYDYLF.js → LCZZSEYY.js} +2 -2
  21. package/dist/chunks/{FQEGZTR3.js → NNFT2MAJ.js} +1 -1
  22. package/dist/chunks/{37KUGTKN.js → NWKQOVQV.js} +2 -2
  23. package/dist/chunks/{BCSBO6QR.js → P2PPTVZS.js} +2 -2
  24. package/dist/chunks/{ICNSKNUT.js → P2ZR3LIZ.js} +2 -2
  25. package/dist/chunks/{CD2TYINV.js → PZEHNKUJ.js} +1 -1
  26. package/dist/chunks/{OA2EJLJ2.js → S6FTHDCG.js} +2 -2
  27. package/dist/chunks/{PM3BWYB5.js → STC7LMPR.js} +1 -1
  28. package/dist/chunks/{YGIYMCYC.js → WDNAIUED.js} +1 -1
  29. package/dist/chunks/{TXOMPE5N.js → WL7Z55QJ.js} +2 -2
  30. package/dist/chunks/{F7WQUODK.js → WMXNVSHQ.js} +2 -2
  31. package/dist/chunks/{P234HHKR.js → WYZDZ7QZ.js} +2 -2
  32. package/dist/cli.js +4 -4
  33. package/dist/cloud/index.js +2 -2
  34. package/dist/refuse/ai-sdk.js +1 -1
  35. package/dist/refuse/ai.js +1 -1
  36. package/dist/refuse/backend.js +1 -1
  37. package/dist/refuse/cloud.js +1 -1
  38. package/dist/refuse/server.js +1 -1
  39. package/dist/server/index.js +2 -2
  40. package/dist/server/testing.js +2 -2
  41. package/dist/web/index.js +2 -2
  42. package/dist/web/message.js +2 -2
  43. package/dist/web/palbe.js +2 -2
  44. package/dist/web/payments-ui.js +2 -2
  45. package/dist/web/paywall.js +2 -2
  46. package/dist/web/push-sw.js +1 -1
  47. package/dist/web/ssr.js +2 -2
  48. package/dist/web/vite.js +2 -2
  49. package/package.json +3 -3
  50. package/dist/chunks/Y4FKEIZV.js +0 -2
@@ -1,5 +1,5 @@
1
- /*! palbase 0.69.1 — Palbase SDK License (see LICENSE) */
2
- import{c as hr,d as gr,e as nn,f as yr,g as wr}from"./XK7JQGKM.js";import{a as Rt,c as ne,d as pr,e as mr,f as be,h as _,i as br}from"./EZW67SHF.js";import{a as dr,e as dt,g as St,h as cr,i as ur,j as At,k as xt,n as lr,y as fr}from"./JFVOERVR.js";import{a as Et,b as or,n as ir}from"./LQF6CVJR.js";import{b as ie}from"./ICNSKNUT.js";import"reflect-metadata";var rn=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],kr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Ot=/^\d+$/;function ba(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let g=s.slice(a+1);if(!Ot.test(g)||Number(g)<1||Number(g)>n)return;d=Number(g)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),b=o.slice(0,g),k=o.slice(g+1);if(!Ot.test(b)||!Ot.test(k)||Number(b)<t||Number(k)>n||Number(b)>Number(k))return;l=Number(b),h=Number(k)}else{if(!Ot.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let g=l;g<=h;g+=d)r.add(g)}return r}function vr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${kr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let g=ba(t[h],rn[h].lo,rn[h].hi);if(!g)return`${kr}; its ${rn[h].name} "${t[h]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let g=r.has(l.getUTCDate()),b=a.has(l.getUTCDay());if(o||d?g&&b:g||b)return}return`"${e}" is never due: no date has that day in that month`}var qe=Symbol.for("palbase.backend.controller"),He=Symbol.for("palbase.backend.routes"),an=Symbol.for("palbase.backend.params"),on=Symbol.for("palbase.backend.injectable"),dn=Symbol.for("palbase.backend.module"),Me=Symbol.for("palbase.backend.events"),Be=Symbol.for("palbase.backend.webhook"),Ee=Symbol.for("palbase.backend.crons"),ke=Symbol.for("palbase.backend.tasks"),Te=Symbol.for("palbase.backend.testUserTemplates");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var sn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[sn]instanceof Set||(e[sn]=new Set),e[sn]}var ze=new Set(["webhooks","_palbase"]);function hd(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&ze.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,qe,()=>({basePath:e,options:t})),se().add(n)}}function Ge(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);de(r.constructor,He,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var gd=Ge("GET"),yd=Ge("POST"),wd=Ge("PUT"),bd=Ge("PATCH"),kd=Ge("DELETE"),vd=Ge("QUERY");function pe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=de(n.constructor,an,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function cn(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var Td=e=>pe("body",{schema:cn("Body",e)}),$d=e=>pe("query",{schema:cn("QueryParams",e)}),_d=e=>pe("headers",e===void 0?{}:{schema:cn("Headers",e)}),Ed=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return pe("param",{name:e})},Sd=()=>pe("user"),Ad=()=>pe("optionalUser"),xd=()=>pe("req"),Rd=()=>pe("requestId"),Od=()=>pe("client"),Pd=()=>pe("attestedDevice");function Cd(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return pe("resolve",{resolver:e,options:t[0]})}function Md(){return e=>{de(e,on,()=>!0),se().add(e)}}function jd(e){return t=>{de(t,dn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var _r=/^[a-z]+(\.[a-z_]+)+$/,ka=/^[a-z][a-z0-9-]{1,62}$/,un=e=>e.startsWith("file.");function Dd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!ka.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!un(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);de(r.constructor,Me,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var ln=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,va=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Tr(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!va.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Nd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=vr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Tr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Tr(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Ee))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Ee,{value:s,enumerable:!1}),se().add(a)}}var $r=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Ta=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ud(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!Ta.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!$r.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${$r.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&$a(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Me)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}de(t,Be,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function $a(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ld(){return[...se()].filter(e=>D(e,qe)!==void 0)}function Id(e){return(D(e,He)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Pt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Gd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}var mn;function Sr(e){mn=e}function fn(){if(!mn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return mn}var _a=720*3600;function Ea(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>_a))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function Sa(e){if(typeof e=="string")return e;let t=e[ke];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Fd=Rt("Tasks",{async enqueue(e,t,n={}){return Ea(n),fn().enqueue(Sa(e),t===void 0?null:t,n)},async cancel(e,t={}){return fn().cancel(e,t.machine)},async get(e,t={}){return fn().get(e,t.machine)}}),pn=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function Ar(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await be.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return pn(a.data,a.status===200)},async cancel(n,r){return pn((await be.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return pn((await be.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Aa=1e4,xa=36e5,Er=24*36e5,Ct=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<Er))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(Aa*2**Math.min(t.attempt-1,16),xa),_.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=Er&&this.tasks.delete(s);n==="failed"&&_.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Mt="/_palbase/test-user-templates",Ra=/^[a-z][a-z0-9_-]{0,63}$/;function Vd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Ra.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,Te))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,Te,{value:r,enumerable:!1}),se().add(s)}}function xr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Rr(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ie&&n.status===404)return!1;throw n}}var Oa="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function Or(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,Oa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var hn=20;function Pr(e,t){let n=[...t].sort(),r=n.length===0?" none":`: ${n.slice(0,hn).join(", ")}${n.length>hn?` and ${n.length-hn} more`:""}`;return`This version has no test user template ${JSON.stringify(e.slice(0,64))} \u2014 it has${r}`}var gn="/_palbase/storage/upload/authorize",Cr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Pa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fe(e){if(!Pa(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function Mr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function jr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function jt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ca=/^[a-z][a-z0-9-]{1,62}$/,Dr=1024,Ma=new Set(["userId","uploadId","filename"]);function ec(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);let r=n.bucket;if(typeof r!="string"||r==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Ca.test(r))throw new TypeError(`@Upload("${e}"): bucket "${r}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let s=ja(n.pathTemplate);if(s)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${s}`);let a={bucket:r,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(d,l,h)=>{if(typeof l!="string"||h===void 0||typeof h.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(d.constructor,He,()=>[]).push({method:"POST",subpath:e,fn:l,options:o,upload:a})}}function tc(){return pe("uploadedObject")}function ja(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Ma.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!Nr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Nr(e){if(e===""||new TextEncoder().encode(e).byteLength>Dr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Da(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Na(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Na(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function Ur(e,t){let n=Da(e,t);return Nr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Dr} bytes)`}}function Lr(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ir(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Fe(t.user);if(!o)return"user is { id?, session?, role }";let d=Mr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=Ua(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Ua(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!wn(g)||!Object.values(g).every(b=>typeof b=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...g}}}import{markData as La}from"palgres";var je=Symbol.for("palbase.backend.gateway"),Je=Symbol.for("palbase.backend.gatewayHooks"),qr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},Ia={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(qr),output:()=>structuredClone(qr)}}},Kr=Symbol.for("palbase.backend.gatewayRefusal"),Hr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Kr,{value:!0})}},qa=e=>typeof e=="object"&&e!==null&&e[Kr]===!0&&typeof e.reason=="string",We=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Ha=6e4,Ba=86400,Br=604800,zr=65536,Se=255,za=["roles:","flags:","messaging:","calls:","debug:"],Ga=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Ke=e=>new TextEncoder().encode(e).byteLength,bn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",Tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Fa(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Ke(e)>Se)return`a channel is ${Se} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=za.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Jr(e){if(typeof e!="string"||e==="")return"is a name";if(Ke(e)>Se)return`is ${Se} bytes at most`}function ic(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Fa(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&Tn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Wa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||Ga.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,b]of Object.entries(d)){let k=Jr(g);if(k)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${k}`);if(!bn(b))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=de(a,Je,$n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Ia}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ha,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&We(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!We(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);de(a,je,()=>h),se().add(a)}}function Wa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ba;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Br)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Br} (a week)`);return n}var $n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ka={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ka[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=de(n.constructor,Je,$n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var dc=ct("authorize"),cc=ct("first"),uc=ct("connect"),lc=ct("disconnect"),fc=ct("empty");function pc(e,t,n={}){let r=Jr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!bn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!bn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=de(s.constructor,Je,$n),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ja(e){return D(e,je)}function Va(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Vr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Ke(r)>Se?{problem:`a channel is ${Se} bytes at most`}:r}function Za(e,t,n){let r=Tn(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Vr(e,t):Ya(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Ya(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Qa=1e4,Xa=1e3,eo=100,_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),we=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Gr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Fr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Zr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:v,instance:E}of e){let f=Ja(v),T=a.get(f.name);if(T!==void 0&&T!==v)throw new TypeError(`@Gateway("${f.pattern}"): two gateways are named ${f.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(f.name,v);let R=s.get(Fr(f.pattern));if(R!==void 0)throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: ${n.get(R)?.cls.name}'s "${R}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Fr(f.pattern),f.pattern);for(let[z,J]of[...Object.entries(f.hooks),...Object.entries(f.messages).map(([L,N])=>[`message ${L}`,N.fn])])if(typeof E[J]!="function")throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: its ${z} is ${J}, which is no method of it`);let I={cls:v,instance:E,g:f};n.set(f.pattern,I),r.set(v,I)}let o=new Map,d=new Set,l=new Set,h=new vn(t.broadcast),g=v=>{let E=o.get(v);return E||(E=new AbortController,o.set(v,E)),E},b=(v,E)=>{E?.abort(),o.get(v)===E&&o.delete(v)},k=(v,E,f,T,R,I)=>{if(!Object.hasOwn(v.g.events,f)){_.warn(`[palbase] ${R}: emit("${f}") is not sent \u2014 ${v.cls.name} declares no event "${f}" (static events)`);return}if(v.g.chat&&f==="chat"){_.warn(`[palbase] ${R}: emit("chat") is not sent \u2014 ${v.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:f,payload:T??{},...I!==void 0?{conn_id:I}:{}},R)},B=async(v,E,f)=>{if(typeof v!="object"||v===null||typeof v.pipe!="function")throw new TypeError(`${f}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await v.pipe(E)};function U(v,E,f,T,R,I,z){let J=T?.signal??AbortSignal.abort(),L=`${v.cls.name} (${E})`;return{channel:E,params:Object.freeze({...f}),signal:J,count:R,user:I,emit:(N,G)=>k(v,E,N,G,L,z),pipe:N=>B(N,E,L),owner:{hold(N){ne.exit(async()=>{try{await N(J)}catch(G){J.aborted||_.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>b(E,T)}}}function q(v){let{room:E,channel:f}=v;if(typeof E!="string"||typeof f!="string")return we(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!We(T.g)?we(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:f,params:Va(E,f)}}let W=(v,E)=>we(400,"bad_request",`"${E}" is not a channel of the gateway "${v}"`);async function K(v,E){let f=q(v);if("status"in f)return f;let{entry:T,channel:R,params:I}=f,z={status:200,body:{subscribe:!1,publish:!1}};if(!I)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${R}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),z;let J=Fe(v.user),L=J?.id;if(!L)return z;if(T.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}};if(T.g.access==="owner")return I[Tn(T.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:z;let N=T.g.hooks.authorize;if(!N)return z;let G,Q;try{G=await t.run(J,`${T.cls.name}.${N}`,E,async()=>T.instance[N]({user:{id:L},params:Object.freeze({...I})})),Q=to(G)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return _.error(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) failed; the join is refused`,{error:te}),z}return Q==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) answered ${no(G)}, which is no grant (true, { read, write } or null); the join is refused`),z):{status:200,body:Q}}async function le(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return W(f.entry.g.pattern,f.channel);let T=Fe(v.user);if(!T?.id||typeof v.event!="string")return we(400,"bad_request","A message names its member (user) and its event");let R=Object.hasOwn(f.entry.g.messages,v.event)?f.entry.g.messages[v.event]:void 0;if(!R)return{status:200,body:{ok:!1,reason:kn(`gateway "${f.channel}" takes no message "${v.event}"`,Dt)}};let I=await R.schema["~standard"].validate(La(v.payload??{}));if(I.issues)return{status:200,body:{ok:!1,reason:Wr(I.issues)}};let z=g(f.channel),J={...U(f.entry,f.channel,f.params,z,0,{id:T.id}),payload:I.value},L=`${f.entry.cls.name}.${R.fn} (@Subscribe "${v.event}" of ${f.channel})`,N;try{N=await t.run(T,`${f.entry.cls.name}.${R.fn}`,E,async()=>f.entry.instance[R.fn](J))}catch(Q){if(t.isOutage(Q))throw Q;return qa(Q)?{status:200,body:{ok:!1,reason:kn(Q.reason,Dt)}}:(E?.aborted||_.error(`[palbase] ${L} failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(R.reply){let Q=await R.reply["~standard"].validate(N);if(Q.issues)return _.error(`[palbase] ${L} returned an ack its reply schema refuses (${Wr(Q.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=Q.value}let G;try{G=JSON.stringify(N)}catch(Q){return _.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Ke(G)>zr?(_.error(`[palbase] ${L} returned an ack of ${Ke(G)} bytes, past ${zr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(G)}}}async function he(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return W(f.entry.g.pattern,f.channel);let T=v.event;if(typeof T!="string"||!Object.hasOwn(Gr,T))return we(400,"bad_request","A gateway's moment is first, join, leave or empty");let R=typeof v.count=="number"&&Number.isInteger(v.count)&&v.count>=0?v.count:void 0;if(R===void 0)return we(400,"bad_request","A gateway's moment says its count of members");let I=T==="join"||T==="leave",z=I?Fe(v.user):void 0,J=I?v.connId:void 0;if(I&&(!z?.id||typeof J!="string"||J===""))return we(400,"bad_request",`A ${T} names its member: user and connId`);let L=`${T}\0${f.channel}\0${typeof J=="string"?J:""}`;if(I&&d.has(L))return{status:204};if(l.has(L))return we(503,"in_progress","This moment of the gateway is being handled",5);l.add(L);try{let N=f.entry.g.hooks[Gr[T]],G;if(T==="empty"?(G=o.get(f.channel),b(f.channel,G)):G=T==="leave"?o.get(f.channel):g(f.channel),N){let Q=U(f.entry,f.channel,f.params,G,R,{id:z?.id??""},T==="join"?J:void 0);try{await t.run(z,`${f.entry.cls.name}.${N}`,E,async()=>f.entry.instance[N](Q))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||_.error(`[palbase] ${f.entry.cls.name}.${N} (${T} of ${f.channel}) failed; realtime tells it again`,{error:te}),we(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return I&&(d.add(L),d.size>Qa&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(L)}}function ge(v,E){let f=r.get(v),T=`Palbase.gateways.to(${v?.name??String(v)})`;if(!f)throw new TypeError(`${T}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let R=Vr(f.g.pattern,E??{});if(typeof R!="string")throw new TypeError(`${T}: ${R.problem}`);return{entry:f,channel:R,where:T}}return{declarations:[...n.values()].map(v=>v.g),async serve(v,E,f){return _n(E)?v==="authorize"?K(E,f):v==="message"?le(E,f):v==="lifecycle"?he(E,f):we(404,"not_found",`No gateway call ${JSON.stringify(v)}`):we(400,"bad_request","A gateway's call is a JSON object")},emit(v,E,f,T){let{entry:R,channel:I,where:z}=ge(v,E);k(R,I,f,T,z)},async pipe(v,E,f){let{channel:T,where:R}=ge(v,E);await B(f,T,R)},async revalidate(v,E,f={}){let T=r.get(v),R=`Palbase.gateways.to(${v?.name??String(v)}).revalidate`;if(!T)throw new TypeError(`${R}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let I=Za(T.g.pattern,E??{},f);if("problem"in I)throw new TypeError(`${R}: ${I.problem}`);let z=ne.getStore()?.saying;if(z){z.push(()=>{t.revalidate(I).catch(J=>_.warn(`[palbase] ${R}: realtime did not decide the channel again`,{error:J}))});return}await t.revalidate(I)},close(){for(let v of o.values())v.abort();o.clear()}}}function to(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!_n(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function no(e){return Array.isArray(e)?"an array":_n(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var ro=20,Dt=256;function Wr(e){let t="";for(let n of e.slice(0,ro)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Dt)break}return kn(t,Dt)}function kn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var vn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ke(t.event)>Se){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Se} bytes`);return}try{JSON.stringify(t.payload)}catch(s){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let r=ne.getStore()?.saying;r?r.push(()=>this.queue(t,n)):this.queue(t,n)}queue(t,n){let r=this.queues.get(t.topic);if(r){r.length>=Xa?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,eo);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as En,createHmac as so,createPublicKey as es,timingSafeEqual as ao,verify as ts}from"node:crypto";function yc(e){let t=D(e,Be);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function ns(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,Be),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,g=n[d.secret.env],b;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{b=oo(d,g)}catch(U){a.push(`${h}: ${d.secret.env} ${U.message}`)}let k=t(o),B=new Map(d.events.map(({event:U,fn:q})=>[U,{name:`${o.name}.${q}`,call:(W,K)=>k[q](W,K)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:b,events:B})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
1
+ /*! palbase 0.71.0 — Palbase SDK License (see LICENSE) */
2
+ import{c as hr,d as gr,e as nn,f as yr,g as wr}from"./6I2XBWUM.js";import{a as Rt,c as ne,d as pr,e as mr,f as be,h as _,i as br}from"./F5D2WPY6.js";import{a as dr,e as dt,g as St,h as cr,i as ur,j as At,k as xt,n as lr,y as fr}from"./E3JCXDTW.js";import{a as Et,b as or,n as ir}from"./5EP5JREH.js";import{b as ie}from"./P2ZR3LIZ.js";import"reflect-metadata";var rn=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],kr="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",Ot=/^\d+$/;function ba(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let g=s.slice(a+1);if(!Ot.test(g)||Number(g)<1||Number(g)>n)return;d=Number(g)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let g=o.indexOf("-"),b=o.slice(0,g),k=o.slice(g+1);if(!Ot.test(b)||!Ot.test(k)||Number(b)<t||Number(k)>n||Number(b)>Number(k))return;l=Number(b),h=Number(k)}else{if(!Ot.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let g=l;g<=h;g+=d)r.add(g)}return r}function vr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${kr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let g=ba(t[h],rn[h].lo,rn[h].hi);if(!g)return`${kr}; its ${rn[h].name} "${t[h]}" is not one`;n.push(g)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let g=r.has(l.getUTCDate()),b=a.has(l.getUTCDay());if(o||d?g&&b:g||b)return}return`"${e}" is never due: no date has that day in that month`}var qe=Symbol.for("palbase.backend.controller"),He=Symbol.for("palbase.backend.routes"),an=Symbol.for("palbase.backend.params"),on=Symbol.for("palbase.backend.injectable"),dn=Symbol.for("palbase.backend.module"),Me=Symbol.for("palbase.backend.events"),Be=Symbol.for("palbase.backend.webhook"),Ee=Symbol.for("palbase.backend.crons"),ke=Symbol.for("palbase.backend.tasks"),Te=Symbol.for("palbase.backend.testUserTemplates");function de(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var sn=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[sn]instanceof Set||(e[sn]=new Set),e[sn]}var ze=new Set(["webhooks","_palbase"]);function hd(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&ze.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);de(n,qe,()=>({basePath:e,options:t})),se().add(n)}}function Ge(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);de(r.constructor,He,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var gd=Ge("GET"),yd=Ge("POST"),wd=Ge("PUT"),bd=Ge("PATCH"),kd=Ge("DELETE"),vd=Ge("QUERY");function pe(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=de(n.constructor,an,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function cn(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var Td=e=>pe("body",{schema:cn("Body",e)}),$d=e=>pe("query",{schema:cn("QueryParams",e)}),_d=e=>pe("headers",e===void 0?{}:{schema:cn("Headers",e)}),Ed=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return pe("param",{name:e})},Sd=()=>pe("user"),Ad=()=>pe("optionalUser"),xd=()=>pe("req"),Rd=()=>pe("requestId"),Od=()=>pe("client"),Pd=()=>pe("attestedDevice");function Cd(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return pe("resolve",{resolver:e,options:t[0]})}function Md(){return e=>{de(e,on,()=>!0),se().add(e)}}function jd(e){return t=>{de(t,dn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var _r=/^[a-z]+(\.[a-z_]+)+$/,ka=/^[a-z][a-z0-9-]{1,62}$/,un=e=>e.startsWith("file.");function Dd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!ka.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!un(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);de(r.constructor,Me,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var ln=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,va=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function Tr(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!va.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Nd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=vr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||Tr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${Tr(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Ee))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Ee,{value:s,enumerable:!1}),se().add(a)}}var $r=["stripe","github","twilio","sendgrid","slack","discord","livekit"],Ta=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ud(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!Ta.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!$r.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${$r.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&$a(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Me)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}de(t,Be,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function $a(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ld(){return[...se()].filter(e=>D(e,qe)!==void 0)}function Id(e){return(D(e,He)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Pt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Gd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!ln.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}var mn;function Sr(e){mn=e}function fn(){if(!mn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return mn}var _a=720*3600;function Ea(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>_a))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function Sa(e){if(typeof e=="string")return e;let t=e[ke];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Fd=Rt("Tasks",{async enqueue(e,t,n={}){return Ea(n),fn().enqueue(Sa(e),t===void 0?null:t,n)},async cancel(e,t={}){return fn().cancel(e,t.machine)},async get(e,t={}){return fn().get(e,t.machine)}}),pn=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function Ar(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await be.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return pn(a.data,a.status===200)},async cancel(n,r){return pn((await be.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return pn((await be.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Aa=1e4,xa=36e5,Er=24*36e5,Ct=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<Er))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(Aa*2**Math.min(t.attempt-1,16),xa),_.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=Er&&this.tasks.delete(s);n==="failed"&&_.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Mt="/_palbase/test-user-templates",Ra=/^[a-z][a-z0-9_-]{0,63}$/;function Vd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Ra.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,Te))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,Te,{value:r,enumerable:!1}),se().add(s)}}function xr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Rr(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof ie&&n.status===404)return!1;throw n}}var Oa="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function Or(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,Oa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var hn=20;function Pr(e,t){let n=[...t].sort(),r=n.length===0?" none":`: ${n.slice(0,hn).join(", ")}${n.length>hn?` and ${n.length-hn} more`:""}`;return`This version has no test user template ${JSON.stringify(e.slice(0,64))} \u2014 it has${r}`}var gn="/_palbase/storage/upload/authorize",Cr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Pa=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fe(e){if(!Pa(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function Mr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function jr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function jt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Ca=/^[a-z][a-z0-9-]{1,62}$/,Dr=1024,Ma=new Set(["userId","uploadId","filename"]);function ec(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);let r=n.bucket;if(typeof r!="string"||r==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Ca.test(r))throw new TypeError(`@Upload("${e}"): bucket "${r}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let s=ja(n.pathTemplate);if(s)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${s}`);let a={bucket:r,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(d,l,h)=>{if(typeof l!="string"||h===void 0||typeof h.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);de(d.constructor,He,()=>[]).push({method:"POST",subpath:e,fn:l,options:o,upload:a})}}function tc(){return pe("uploadedObject")}function ja(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Ma.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!Nr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Nr(e){if(e===""||new TextEncoder().encode(e).byteLength>Dr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Da(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Na(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Na(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function Ur(e,t){let n=Da(e,t);return Nr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Dr} bytes)`}}function Lr(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ir(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Fe(t.user);if(!o)return"user is { id?, session?, role }";let d=Mr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=Ua(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Ua(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:g}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!wn(g)||!Object.values(g).every(b=>typeof b=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...g}}}import{markData as La}from"palgres";var je=Symbol.for("palbase.backend.gateway"),Je=Symbol.for("palbase.backend.gatewayHooks"),qr={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},Ia={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(qr),output:()=>structuredClone(qr)}}},Kr=Symbol.for("palbase.backend.gatewayRefusal"),Hr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Kr,{value:!0})}},qa=e=>typeof e=="object"&&e!==null&&e[Kr]===!0&&typeof e.reason=="string",We=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Ha=6e4,Ba=86400,Br=604800,zr=65536,Se=255,za=["roles:","flags:","messaging:","calls:","debug:"],Ga=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Ke=e=>new TextEncoder().encode(e).byteLength,bn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",Tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Fa(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Ke(e)>Se)return`a channel is ${Se} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=za.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Jr(e){if(typeof e!="string"||e==="")return"is a name";if(Ke(e)>Se)return`is ${Se} bytes at most`}function ic(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Fa(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&Tn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Wa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||Ga.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[g,b]of Object.entries(d)){let k=Jr(g);if(k)throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" ${k}`);if(!bn(b))throw new TypeError(`@Gateway("${e}") on ${o}: event "${g}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=de(a,Je,$n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Ia}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ha,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&We(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!We(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);de(a,je,()=>h),se().add(a)}}function Wa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ba;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Br)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Br} (a week)`);return n}var $n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ka={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ka[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=de(n.constructor,Je,$n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var dc=ct("authorize"),cc=ct("first"),uc=ct("connect"),lc=ct("disconnect"),fc=ct("empty");function pc(e,t,n={}){let r=Jr(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!bn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!bn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=de(s.constructor,Je,$n),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ja(e){return D(e,je)}function Va(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Vr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Ke(r)>Se?{problem:`a channel is ${Se} bytes at most`}:r}function Za(e,t,n){let r=Tn(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Vr(e,t):Ya(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Ya(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Qa=1e4,Xa=1e3,eo=100,_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),we=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Gr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Fr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Zr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:v,instance:E}of e){let f=Ja(v),T=a.get(f.name);if(T!==void 0&&T!==v)throw new TypeError(`@Gateway("${f.pattern}"): two gateways are named ${f.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(f.name,v);let R=s.get(Fr(f.pattern));if(R!==void 0)throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: ${n.get(R)?.cls.name}'s "${R}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Fr(f.pattern),f.pattern);for(let[z,J]of[...Object.entries(f.hooks),...Object.entries(f.messages).map(([L,N])=>[`message ${L}`,N.fn])])if(typeof E[J]!="function")throw new TypeError(`@Gateway("${f.pattern}") on ${v.name}: its ${z} is ${J}, which is no method of it`);let I={cls:v,instance:E,g:f};n.set(f.pattern,I),r.set(v,I)}let o=new Map,d=new Set,l=new Set,h=new vn(t.broadcast),g=v=>{let E=o.get(v);return E||(E=new AbortController,o.set(v,E)),E},b=(v,E)=>{E?.abort(),o.get(v)===E&&o.delete(v)},k=(v,E,f,T,R,I)=>{if(!Object.hasOwn(v.g.events,f)){_.warn(`[palbase] ${R}: emit("${f}") is not sent \u2014 ${v.cls.name} declares no event "${f}" (static events)`);return}if(v.g.chat&&f==="chat"){_.warn(`[palbase] ${R}: emit("chat") is not sent \u2014 ${v.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:E,event:f,payload:T??{},...I!==void 0?{conn_id:I}:{}},R)},B=async(v,E,f)=>{if(typeof v!="object"||v===null||typeof v.pipe!="function")throw new TypeError(`${f}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await v.pipe(E)};function U(v,E,f,T,R,I,z){let J=T?.signal??AbortSignal.abort(),L=`${v.cls.name} (${E})`;return{channel:E,params:Object.freeze({...f}),signal:J,count:R,user:I,emit:(N,G)=>k(v,E,N,G,L,z),pipe:N=>B(N,E,L),owner:{hold(N){ne.exit(async()=>{try{await N(J)}catch(G){J.aborted||_.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>b(E,T)}}}function q(v){let{room:E,channel:f}=v;if(typeof E!="string"||typeof f!="string")return we(400,"bad_request","A gateway's call names its pattern (room) and its channel");let T=n.get(E);return!T||!We(T.g)?we(404,"not_found",`This app serves no gateway "${E}"`):{entry:T,channel:f,params:Va(E,f)}}let W=(v,E)=>we(400,"bad_request",`"${E}" is not a channel of the gateway "${v}"`);async function K(v,E){let f=q(v);if("status"in f)return f;let{entry:T,channel:R,params:I}=f,z={status:200,body:{subscribe:!1,publish:!1}};if(!I)return _.warn(`[palbase] ${T.cls.name}: realtime asked about "${R}", which is not a channel of the gateway "${T.g.pattern}"; the join is refused`),z;let J=Fe(v.user),L=J?.id;if(!L)return z;if(T.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}};if(T.g.access==="owner")return I[Tn(T.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys(T.g.messages).length>0}}:z;let N=T.g.hooks.authorize;if(!N)return z;let G,Q;try{G=await t.run(J,`${T.cls.name}.${N}`,E,async()=>T.instance[N]({user:{id:L},params:Object.freeze({...I})})),Q=to(G)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return _.error(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) failed; the join is refused`,{error:te}),z}return Q==="malformed"?(_.warn(`[palbase] ${T.cls.name}.${N} (@Authorize of ${R}) answered ${no(G)}, which is no grant (true, { read, write } or null); the join is refused`),z):{status:200,body:Q}}async function le(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return W(f.entry.g.pattern,f.channel);let T=Fe(v.user);if(!T?.id||typeof v.event!="string")return we(400,"bad_request","A message names its member (user) and its event");let R=Object.hasOwn(f.entry.g.messages,v.event)?f.entry.g.messages[v.event]:void 0;if(!R)return{status:200,body:{ok:!1,reason:kn(`gateway "${f.channel}" takes no message "${v.event}"`,Dt)}};let I=await R.schema["~standard"].validate(La(v.payload??{}));if(I.issues)return{status:200,body:{ok:!1,reason:Wr(I.issues)}};let z=g(f.channel),J={...U(f.entry,f.channel,f.params,z,0,{id:T.id}),payload:I.value},L=`${f.entry.cls.name}.${R.fn} (@Subscribe "${v.event}" of ${f.channel})`,N;try{N=await t.run(T,`${f.entry.cls.name}.${R.fn}`,E,async()=>f.entry.instance[R.fn](J))}catch(Q){if(t.isOutage(Q))throw Q;return qa(Q)?{status:200,body:{ok:!1,reason:kn(Q.reason,Dt)}}:(E?.aborted||_.error(`[palbase] ${L} failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(R.reply){let Q=await R.reply["~standard"].validate(N);if(Q.issues)return _.error(`[palbase] ${L} returned an ack its reply schema refuses (${Wr(Q.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=Q.value}let G;try{G=JSON.stringify(N)}catch(Q){return _.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:Q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Ke(G)>zr?(_.error(`[palbase] ${L} returned an ack of ${Ke(G)} bytes, past ${zr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(G)}}}async function he(v,E){let f=q(v);if("status"in f)return f;if(!f.params)return W(f.entry.g.pattern,f.channel);let T=v.event;if(typeof T!="string"||!Object.hasOwn(Gr,T))return we(400,"bad_request","A gateway's moment is first, join, leave or empty");let R=typeof v.count=="number"&&Number.isInteger(v.count)&&v.count>=0?v.count:void 0;if(R===void 0)return we(400,"bad_request","A gateway's moment says its count of members");let I=T==="join"||T==="leave",z=I?Fe(v.user):void 0,J=I?v.connId:void 0;if(I&&(!z?.id||typeof J!="string"||J===""))return we(400,"bad_request",`A ${T} names its member: user and connId`);let L=`${T}\0${f.channel}\0${typeof J=="string"?J:""}`;if(I&&d.has(L))return{status:204};if(l.has(L))return we(503,"in_progress","This moment of the gateway is being handled",5);l.add(L);try{let N=f.entry.g.hooks[Gr[T]],G;if(T==="empty"?(G=o.get(f.channel),b(f.channel,G)):G=T==="leave"?o.get(f.channel):g(f.channel),N){let Q=U(f.entry,f.channel,f.params,G,R,{id:z?.id??""},T==="join"?J:void 0);try{await t.run(z,`${f.entry.cls.name}.${N}`,E,async()=>f.entry.instance[N](Q))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||_.error(`[palbase] ${f.entry.cls.name}.${N} (${T} of ${f.channel}) failed; realtime tells it again`,{error:te}),we(500,"handler_failed",`The gateway's ${T} could not be handled`)}}return I&&(d.add(L),d.size>Qa&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(L)}}function ge(v,E){let f=r.get(v),T=`Palbase.gateways.to(${v?.name??String(v)})`;if(!f)throw new TypeError(`${T}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let R=Vr(f.g.pattern,E??{});if(typeof R!="string")throw new TypeError(`${T}: ${R.problem}`);return{entry:f,channel:R,where:T}}return{declarations:[...n.values()].map(v=>v.g),async serve(v,E,f){return _n(E)?v==="authorize"?K(E,f):v==="message"?le(E,f):v==="lifecycle"?he(E,f):we(404,"not_found",`No gateway call ${JSON.stringify(v)}`):we(400,"bad_request","A gateway's call is a JSON object")},emit(v,E,f,T){let{entry:R,channel:I,where:z}=ge(v,E);k(R,I,f,T,z)},async pipe(v,E,f){let{channel:T,where:R}=ge(v,E);await B(f,T,R)},async revalidate(v,E,f={}){let T=r.get(v),R=`Palbase.gateways.to(${v?.name??String(v)}).revalidate`;if(!T)throw new TypeError(`${R}: ${v?.name??String(v)} is no @Gateway this app serves \u2014 list it in a module's providers`);let I=Za(T.g.pattern,E??{},f);if("problem"in I)throw new TypeError(`${R}: ${I.problem}`);let z=ne.getStore()?.saying;if(z){z.push(()=>{t.revalidate(I).catch(J=>_.warn(`[palbase] ${R}: realtime did not decide the channel again`,{error:J}))});return}await t.revalidate(I)},close(){for(let v of o.values())v.abort();o.clear()}}}function to(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!_n(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function no(e){return Array.isArray(e)?"an array":_n(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var ro=20,Dt=256;function Wr(e){let t="";for(let n of e.slice(0,ro)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Dt)break}return kn(t,Dt)}function kn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var vn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ke(t.event)>Se){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Se} bytes`);return}try{JSON.stringify(t.payload)}catch(s){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:s});return}let r=ne.getStore()?.saying;r?r.push(()=>this.queue(t,n)):this.queue(t,n)}queue(t,n){let r=this.queues.get(t.topic);if(r){r.length>=Xa?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,eo);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as En,createHmac as so,createPublicKey as es,timingSafeEqual as ao,verify as ts}from"node:crypto";function yc(e){let t=D(e,Be);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function ns(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,Be),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,g=n[d.secret.env],b;if(r.secrets!==!1)if(g===void 0||g==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{b=oo(d,g)}catch(U){a.push(`${h}: ${d.secret.env} ${U.message}`)}let k=t(o),B=new Map(d.events.map(({event:U,fn:q})=>[U,{name:`${o.name}.${q}`,call:(W,K)=>k[q](W,K)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:b,events:B})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
3
3
  - ${a.join(`
4
4
  - `)}`);return s}function rs(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Ve=1024,Yr=1024*Ve;function oo(e,t){if(e.signature)return De(void 0,e.signature.header,1/0,wo(e.signature,t));switch(e.provider){case"stripe":return De("stripe","stripe-signature",512*Ve,uo(t));case"github":return De("github","x-hub-signature-256",25*Yr,lo(t));case"slack":return De("slack","x-slack-signature",64*Ve,fo(t));case"discord":return De("discord","x-signature-ed25519",64*Ve,po(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Ve),check:ho(t)};case"sendgrid":return De("sendgrid","x-twilio-email-event-webhook-signature",Yr,go(t));case"livekit":return De("livekit","authorization",512*Ve,yo(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function De(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??ss(e,s)}}function ss(e,t){let n=Sn(t.body),r;try{r=JSON.parse(n)}catch{if(r=n,e==="slack"){let s=new URLSearchParams(n).get("payload");if(s!==null)try{r=JSON.parse(s)}catch{}}}return{type:as(e,t.headers,r),event:r,...io(e,t,r)}}function as(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=Ne(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=ds(n)?n.type:void 0;return r===1?"PING":r===2?"INTERACTION_CREATE":Number.isInteger(r)?`type_${String(r)}`:""}case"sendgrid":return"event_batch";case"twilio":return Ne(n,"EventType");case"livekit":return Ne(n,"event");default:return Ne(n,"type")}}function io(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(Ne(n,"id"));case"slack":return r(Ne(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${os(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>Ne(s,"sg_event_id")||void 0)}:{};default:return{}}}var co=300;function uo(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let l of r.split(",")){let h=l.indexOf("=");if(h<=0)continue;let g=l.slice(0,h).trim(),b=l.slice(h+1).trim();if(g==="t"){if(s!==void 0)return"malformed_signature";s=b}else if(g==="v1"){let k=me(b,"hex");if(!k)return"malformed_signature";a.push(k)}}let o=ut(s);if(o===void 0||a.length===0)return"malformed_signature";if(lt(o,n))return"stale_timestamp";let d=Ze("sha256",e,`${s}.`,t.body);return a.some(l=>Ae(l,d))?void 0:"signature_mismatch"}}function lo(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?me(n.slice(7),"hex"):void 0;return r?Ae(r,Ze("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function fo(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),a=ut(s),o=r.startsWith("v0=")?me(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":lt(a,n)?"stale_timestamp":Ae(o,Ze("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function po(e){let t=me(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let n=es({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let a=r.headers.get("x-signature-ed25519");if(!a)return"missing_signature";let o=r.headers.get("x-signature-timestamp")??void 0,d=ut(o),l=me(a,"hex");return d===void 0||!l||l.byteLength!==64?"malformed_signature":lt(d,s)?"stale_timestamp":ts(null,is(o,r.body),n,l)?void 0:"signature_mismatch"}}var mo=1e3;function ho(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=me(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let a=s.searchParams.get("bodySHA256"),o="",d;if(a!==null){if(!Ae(Buffer.from(a.toLowerCase()),Buffer.from(En("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let B=1;for(let W of t.body)if(W===38&&++B>mo)return"malformed_signature";let U=new Map;for(let[W,K]of new URLSearchParams(Sn(t.body))){let le=U.get(W);le||U.set(W,le=new Set),le.add(K)}let q=[];for(let W of[...U.keys()].sort()){let K=[...U.get(W)].sort();for(let le of K)o+=W+le;q.push([W,K.length===1?K[0]:K])}d=Object.fromEntries(q)}let l=s.protocol==="https:"?"443":"80",h=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,g=`${s.protocol}//${s.hostname}:${s.port||l}${s.pathname}${s.search}`;if(![h,g].some(B=>Ae(r,Ze("sha1",e,B,o))))return"signature_mismatch";let b=t.headers.get("i-twilio-idempotency-token"),k=b?{id:`${b}:${os(`${h}
5
5
  ${o}`)}`}:{};return d?{type:as("twilio",t.headers,d),event:d,...k}:{...ss("twilio",t),...k}}}function go(e){let t;try{let n=me(e,"base64");if(!n)throw new Error;t=es({key:Buffer.from(n),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(n,r)=>{let s=n.headers.get("x-twilio-email-event-webhook-signature");if(!s)return"missing_signature";let a=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),o=ut(a),d=me(s.trim(),"base64");return o===void 0||!d?"malformed_signature":lt(o,r)?"stale_timestamp":ts("sha256",is(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var Qr=60;function yo(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let a=Xr(me(s[0],"base64url")),o=me(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!Ae(o,Ze("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=Xr(me(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+Qr||typeof d.nbf=="number"&&n<d.nbf-Qr)return"stale_timestamp";let l=typeof d.sha256=="string"?me(d.sha256,"base64"):void 0;return l&&Ae(l,En("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function wo(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,a)=>{let o=s.headers.get(e.header);if(!o)return"missing_signature";if(e.prefix){if(!o.startsWith(e.prefix))return"malformed_signature";o=o.slice(e.prefix.length)}let d="";if(n.includes("{ts}")){d=s.headers.get(e.timestampHeader)?.trim()??"";let h=ut(d);if(h===void 0)return"malformed_signature";if(lt(h,a))return"stale_timestamp"}let l=me(o.trim(),e.encoding);return l?Ae(l,Ze(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var bo=new TextEncoder;function Ze(e,t,...n){let r=so(e,t);for(let s of n)r.update(s);return r.digest()}function os(e){return En("sha256").update(e).digest("hex")}function is(e,t){return Buffer.concat([bo.encode(e),t])}function Ae(e,t){return e.byteLength===t.byteLength&&ao(e,t)}var ko={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function me(e,t){return ko[t].test(e)?Buffer.from(e,t):void 0}function ut(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function lt(e,t){return Math.abs(t-e)>co}function Sn(e){return new TextDecoder().decode(e)}function Xr(e){if(e)try{return JSON.parse(Sn(e))}catch{return}}function ds(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(e,t){let n=ds(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var Y=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- /*! palbase 0.69.1 — Palbase SDK License (see LICENSE) */
2
+ /*! palbase 0.71.0 — Palbase SDK License (see LICENSE) */
3
3
  var G0=Object.defineProperty;var jt=(e,t)=>{for(var n in t)G0(e,n,{get:t[n],enumerable:!0})};import{parseArgs as A$}from"node:util";var K0=Symbol.for("palbase.data"),U0=globalThis,Su=U0[K0]??=new WeakSet;function F0(e){return e instanceof Date||ArrayBuffer.isView(e)||e instanceof ArrayBuffer}function Fo(e){let t=[e];for(;t.length>0;){let n=t.pop();if(!(typeof n!="object"||n===null||Su.has(n)||F0(n))){Su.add(n);for(let s of Array.isArray(n)?n:Object.values(n))t.push(s)}}return e}var W0="X-PoW-Challenge-ID",B0="X-PoW-Nonce";function Au(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:s,difficulty:a}=t.challenge;return typeof n!="string"||typeof s!="string"||typeof a!="number"||!Number.isInteger(a)||a<0?null:{id:n,prefix:s,difficulty:a}}function J0(e){return 8*2**e}var Ca;async function H0(){if(Ca)return Ca;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let s=(await import("node:crypto")).createHash;if(typeof s=="function")return Ca=a=>new Uint8Array(s("sha256").update(a).digest()),Ca}catch{}let t=new TextEncoder;return Ca=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),Ca}function V0(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var X0=4096,Y0=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function Pu(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 H0(),s=J0(e.difficulty),a=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<s;i++){if(i%X0===0&&i>0){if(await Y0(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>a)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let o=n(e.prefix+i),r=o instanceof Uint8Array?o:await o;if(V0(r)>=e.difficulty)return{[W0]:e.id,[B0]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${s} attempts`)}var q=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="PalbaseError",this.op=t.op,this.status=t.status,this.code=t.code,this.requestId=t.requestId,this.retryAfter=t.retryAfter,this.body=t.body}};function u(e,t,n){let s=String(n);if(s===""||s==="."||s==="..")throw new q({op:e,status:0,code:"invalid_path_parameter",message:`${e}: ${t} cannot be ${s===""?"empty":JSON.stringify(s)}`});return encodeURIComponent(s)}var Z0=new Set(["apikey","authorization"]),Q0=64*1024;function sp(e){let t=Wo(e.baseUrl),n=e.fetch??globalThis.fetch,s=e.solveProofOfWork??!0,a=async(i,o)=>{let r=n$(t,i),l=new Headers;for(let[y,b]of Object.entries(i.headers??{}))b!=null&&!Z0.has(y.toLowerCase())&&l.set(y,String(b));for(let[y,b]of Object.entries(o))l.set(y,b);await s$(i,e.credentials,l),l.has("accept")||l.set("accept","application/json");let p={method:i.method,headers:l,redirect:"manual",signal:i.signal,...i.keepalive?{keepalive:!0}:{}};i.body&&i.body.value!==void 0&&(l.set("content-type",i.body.contentType),p.body=a$(i.body.kind,i.body.value),Oa(p.body)||(p.duplex="half"));let d;try{d=i.onUploadProgress&&e.xmlHttpRequest?await e$(e.xmlHttpRequest,i.op,r,p,i.onUploadProgress):await n(r,p)}catch(y){throw i.signal?.aborted||y instanceof q?y:new q({op:i.op,status:0,code:"network_error",message:`${i.op}: the request did not reach ${t.origin}`,cause:y})}let c=i.answers[d.status]??(i.ownResponse&&d.status>=200&&d.status<300?"raw":void 0);if(c===void 0)throw d.status>=200&&d.status<300?(await d.body?.cancel(),new q({op:i.op,status:d.status,code:"undeclared_answer",message:`${i.op}: the server answered ${d.status}, which its contract does not declare; the request may have taken effect`})):await o$(i.op,d);let m;switch(c){case"json":try{m=Fo(await d.json())}catch(y){throw new q({op:i.op,status:d.status,code:"invalid_json",message:`${i.op}: the answer is not JSON`,cause:y})}break;case"raw":m=d;break;default:await d.body?.cancel(),m=void 0}return{status:d.status,data:m,headers:d.headers}};return{async send(i){try{return await a(i,{})}catch(o){let r=s&&o instanceof q&&o.status===403?Au(o.body):null,l=i.body?.value;if(!r||i.body?.kind==="raw"&&!Oa(l))throw o;let p=o,d;try{d=await Pu(r,{signal:i.signal})}catch(c){throw i.signal?.aborted?c:new q({op:i.op,status:403,code:"pow_unsolved",message:`${i.op}: ${c instanceof Error?c.message:String(c)}`,requestId:p.requestId,body:p.body,cause:c})}return a(i,d)}}}}function e$(e,t,n,s,a){return new Promise((i,o)=>{let r=s.signal;if(r?.aborted)return o(r.reason);let l=new e,p=()=>l.abort();r?.addEventListener("abort",p,{once:!0});let d=c=>{r?.removeEventListener("abort",p),c()};l.open(s.method??"GET",n.href),l.responseType="arraybuffer",new Headers(s.headers).forEach((c,m)=>l.setRequestHeader(m,c)),l.upload&&(l.upload.onprogress=c=>{c.lengthComputable&&a(c.loaded,c.total)}),l.onload=()=>d(()=>{if(l.responseURL!==""&&l.responseURL!==n.href){o(new q({op:t,status:0,code:"undeclared_redirect",message:`${t}: the server redirected; the answer is another address's, and was not read`}));return}if(l.status<200||l.status>599)return o(new TypeError(`${t}: answered ${l.status}`));let c=l.status===204||l.status===205||l.status===304;i(new Response(c?null:l.response,{status:l.status,statusText:l.statusText,headers:t$(l.getAllResponseHeaders())}))}),l.onerror=()=>d(()=>o(new TypeError(`${t}: the request failed`))),l.onabort=()=>d(()=>o(r?.reason??new DOMException("The request was aborted","AbortError"))),l.send(s.body)})}function t$(e){let t=new Headers;for(let n of e.split(/\r?\n/)){let s=n.indexOf(":");if(!(s<=0))try{t.append(n.slice(0,s).trim(),n.slice(s+1).trim())}catch{}}return t}function Wo(e){let t;try{t=new URL(e)}catch{throw new TypeError(`baseUrl ${JSON.stringify(e)} is not an absolute URL`)}let n=t.hostname==="localhost"||t.hostname.endsWith(".localhost")||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${t.origin}`);if(t.username||t.password||t.search||t.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(t.pathname!=="/"&&t.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return t}function n$(e,t){if(!t.path.startsWith("/")||t.path.startsWith("//"))throw new q({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path ${JSON.stringify(t.path)} is not absolute`});let n=new URL(t.path+i$(t.query),e);if(n.origin!==e.origin)throw new q({op:t.op,status:0,code:"invalid_path",message:`${t.op}: path leaves the project's origin`});return n}async function s$(e,t,n){if(e.auth.length===0)return;let s=e.auth.some(o=>o.includes("userJWT"))?await t.accessToken?.():void 0,a=o=>{switch(o){case"ApiKeyAuth":return!!(t.publishableKey??t.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(t.secretKey??t.token);case"PalbaseBearer":return!!t.token;case"userJWT":return!!s&&!t.token;default:return!1}},i=e.auth.filter(o=>o.every(a)).reduce((o,r)=>o===void 0||r.length>o.length?r:o,void 0);if(!i)throw new q({op:e.op,status:0,code:"missing_credential",message:`${e.op} needs one of: ${e.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of i)o==="ApiKeyAuth"?n.set("apikey",t.publishableKey??t.secretKey):(o==="SecretKeyAuth"||o==="AdminAuth"||o==="PalbaseBearer")&&t.token?n.set("authorization",`Bearer ${t.token}`):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",t.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${s}`)}function a$(e,t){switch(e){case"json":return JSON.stringify(t);case"form":{let n=new URLSearchParams;for(let[s,a]of Object.entries(t))ap(n,s,a);return n}case"raw":return t}}function Oa(e){return!!(e==null||typeof e=="string"||e instanceof URLSearchParams||e instanceof Blob||e instanceof FormData||e instanceof ArrayBuffer||ArrayBuffer.isView(e))}function i$(e){if(!e)return"";let t=new URLSearchParams;for(let[s,a]of Object.entries(e))ap(t,s,a);let n=t.toString();return n===""?"":`?${n}`}function ap(e,t,n){if(n!=null){if(Array.isArray(n)){for(let s of n)ap(e,t,s);return}if(n instanceof Date){e.append(t,n.toISOString());return}e.append(t,typeof n=="object"?JSON.stringify(n):String(n))}}async function o$(e,t){let n=await r$(t,Q0).catch(()=>""),s;try{s=n===""?void 0:JSON.parse(n)}catch{s=n}let a=l$(s)?s:void 0,i=Number(t.headers.get("retry-after")),o=t.status>=300&&t.status<400;return new q({op:e,status:t.status,code:a?.error??(o?"undeclared_redirect":`http_${t.status}`),message:a?.error_description??(o?`${e}: the server redirected (${t.status}); the request was not followed, its credentials stay here`:`${e}: ${t.status} ${t.statusText}`.trim()),requestId:a?.request_id??t.headers.get("x-request-id")??void 0,retryAfter:a?.retry_after??(Number.isFinite(i)&&i>0?i:void 0),body:s})}async function r$(e,t){if(!e.body)return"";let n=e.body.getReader(),s=[],a=0;for(;a<t;){let{done:r,value:l}=await n.read();if(r)break;s.push(l),a+=l.byteLength}await n.cancel().catch(()=>{});let i=new Uint8Array(Math.min(a,t)),o=0;for(let r of s){let l=Math.min(r.byteLength,i.byteLength-o);if(i.set(r.subarray(0,l),o),o+=l,o>=i.byteLength)break}return new TextDecoder().decode(i)}function l$(e){return typeof e=="object"&&e!==null&&typeof e.error=="string"}var Bo={project:{type:"string",short:"P",value:"project",description:"the project (name or id; org/project when the name is in two organizations)"},env:{type:"string",short:"E",value:"env",description:"the project's environment (slug or ref)"},json:{type:"boolean",description:"print the answer as JSON"},"non-interactive":{type:"boolean",description:"never ask: refuse what would need a question"},yes:{type:"boolean",short:"y",description:"confirm a change to a production environment without asking"},debug:{type:"boolean",description:"print each request the command sends"},help:{type:"boolean",short:"h",description:"show help"}};var f=class extends Error{exitCode;hint;code;reported;constructor(t,n,s={}){super(n),this.name="CliError",this.code=t,this.hint=s.hint,this.exitCode=s.exitCode??1,this.reported=s.reported??!1}};function h(e,t){return new f("usage",e,{hint:t,exitCode:2})}var Jo=class{io;json;constructor(t,n){this.io=t,this.json=n}result(t,n){this.json?this.io.stdout(`${JSON.stringify(t,null,2)}
4
4
  `):n()}line(t=""){this.io.stdout(`${le(t)}
5
5
  `)}note(t){this.io.stderr(`${le(t)}
@@ -9,7 +9,7 @@ var G0=Object.defineProperty;var jt=(e,t)=>{for(var n in t)G0(e,n,{get:t[n],enum
9
9
  `);let o;try{o=await this.io.fetch(t,{method:n.method,headers:{...n.headers,...a},body:n.body,signal:n.signal,...s?{}:{duplex:"half"},redirect:"manual"})}catch(l){throw n.signal?.aborted?l:new f("network_error",`${new URL(t).origin} could not be reached: ${l instanceof Error?l.message:String(l)}`)}if(this.debug&&this.io.stderr(`< ${o.status} ${o.headers.get("x-request-id")??""}
10
10
  `),o.status!==503||!s||i>=_$||!k$.has(await lp(o)??""))return o;await o.body?.cancel();let r=Number(o.headers.get("retry-after")??"");await this.io.sleep((Number.isFinite(r)&&r>0?Math.min(r,30):1)*1e3)}}async exchange(t,n,s){let a=await this.token(),i=await this.send(t,n,s,a.value);if(i.status===401&&a.renewable){let o=await this.renew(await this.currentSession());i=await this.send(t,n,s,o.access_token)}return{res:i,renewable:a.renewable}}async answered(t,n,s,a){if(s.status===204)return;let i=await s.text(),o=i===""?void 0:$$(i);if(s.ok)return o;let r=o??{};throw s.status===401?r.error==="token_not_for_machines"?Gu(new URL(this.cloud.studioApi).host):a?xa():this.tokenRefused("Studio"):new q({op:`${t} ${n}`,status:s.status,code:r.error??`http_${s.status}`,message:r.error_description??`Studio answered ${s.status}`,requestId:r.request_id??s.headers.get("x-request-id")??void 0,body:o})}tokenRefused(t){return(this.io.env.PALBASE_TOKEN??"").startsWith("pbe_")?new f("token_refused",`${t} refused PALBASE_TOKEN, an environment's token: it ended (a few hours at most), it was revoked, or what minted it no longer holds`,{hint:"mint another: palbase env:tokens:create --scope <scope> (an admin), or with the environment's secret key (Studio's POST /environments/{ref}/tokens)"}):(this.io.env.PALBASE_TOKEN??"").startsWith("pbu_")?new f("token_refused",`${t} refused PALBASE_TOKEN, an account token: it was revoked, it ended, or, in this organization, the one who made it left it`,{hint:"its maker makes a new one: palbase account:tokens:create <name>"}):new f("token_refused",`${t} refused PALBASE_TOKEN: it was revoked, it ended, or the one who made it no longer holds its role`,{hint:"an admin makes a new one: palbase tokens:create <name>"})}async token(){let t=this.io.env.PALBASE_TOKEN;return t&&t!==""?{value:t,renewable:!1}:{value:(await this.currentSession()).access_token,renewable:!0}}async renew(t){let n=await Du(this.io,this.cloud,t);return await this.state.writeSession(n),this.session=n,n}async send(t,n,s,a){let i=`${this.cloud.studioApi}${v$}${n}`;this.debug&&this.io.stderr(`> ${t} ${i}
11
11
  `);try{let o=await this.io.fetch(i,{method:t,headers:{...a===void 0?{}:{authorization:`Bearer ${a}`},accept:"application/json",...s===void 0?{}:{"content-type":"application/json"}},body:s===void 0?void 0:JSON.stringify(s),redirect:"manual"});return this.debug&&this.io.stderr(`< ${o.status} ${o.headers.get("x-request-id")??""}
12
- `),o}catch(o){throw new f("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${o instanceof Error?o.message:String(o)}`)}}};function Gu(e){return new f("token_not_for_machines",`the platform's edge refused PALBASE_TOKEN at ${e}, taking it for a machine's address (token_not_for_machines): the token itself was not refused`,{hint:"nothing is wrong with the token: run this again in a few minutes, and tell Palbase if it lasts"})}async function lp(e){let t=await e.clone().json().catch(()=>null),n=t&&typeof t=="object"?t.error:void 0;return typeof n=="string"&&/^(console|token|edge)_/.test(n)?n:void 0}function $$(e){try{return JSON.parse(e)}catch{return e}}var Ku={version:"0.69.1"};var Zo=Ku.version;async function Ju(e,t,n,s){let a=new Map(n.map(r=>[r.name,r])),i=e.includes("--json"),o=e.includes("--debug");try{let{name:r,at:l}=P$(e);if(r===void 0)return e.includes("--version")?(t.stdout(`palbase ${Zo}
12
+ `),o}catch(o){throw new f("network_error",`Studio (${this.cloud.studioApi}) could not be reached: ${o instanceof Error?o.message:String(o)}`)}}};function Gu(e){return new f("token_not_for_machines",`the platform's edge refused PALBASE_TOKEN at ${e}, taking it for a machine's address (token_not_for_machines): the token itself was not refused`,{hint:"nothing is wrong with the token: run this again in a few minutes, and tell Palbase if it lasts"})}async function lp(e){let t=await e.clone().json().catch(()=>null),n=t&&typeof t=="object"?t.error:void 0;return typeof n=="string"&&/^(console|token|edge)_/.test(n)?n:void 0}function $$(e){try{return JSON.parse(e)}catch{return e}}var Ku={version:"0.71.0"};var Zo=Ku.version;async function Ju(e,t,n,s){let a=new Map(n.map(r=>[r.name,r])),i=e.includes("--json"),o=e.includes("--debug");try{let{name:r,at:l}=P$(e);if(r===void 0)return e.includes("--version")?(t.stdout(`palbase ${Zo}
13
13
  `),0):(t.stdout(Bu(n)),e.length===0||e.includes("--help")||e.includes("-h")?0:2);if(r==="help"){let T=e[l+1],C=T===void 0?void 0:a.get(T);if(T!==void 0&&!C)throw Uu(T,n);return t.stdout(C?Wu(C):Bu(n)),0}let p=a.get(r);if(!p)throw Uu(r,n);let d=[...e.slice(0,l),...e.slice(l+1)],c=d.includes("--")?d.slice(0,d.indexOf("--")):d;if(c.includes("--help")||c.includes("-h"))return t.stdout(Wu(p)),0;let{flags:m,positionals:y}=R$(p,d),b=p.args??{min:0,max:0};if(y.length<b.min)throw h(`${p.name} needs ${b.min===1?"an argument":`${b.min} arguments`}`,dp(p));if(y.length>b.max)throw h(`${p.name} takes ${b.max===0?"no argument":`at most ${b.max}`}: ${JSON.stringify(y.slice(b.max))} is left over`,dp(p));let v={project:m.project,env:m.env,json:m.json===!0,nonInteractive:m["non-interactive"]===!0,yes:m.yes===!0,debug:m.debug===!0},R=Ou(t.env),A=new Vo(Nu(t.configDir,R)),j={io:t,state:A,out:new Jo(t,v.json),global:v,args:y,flags:m,interactive:t.interactive&&!v.nonInteractive,cloud:R,studio:new Yo(t,R,A,v.debug,s?.callPlatform)};return await p.run(j)??0}catch(r){return E$(r,t,i,o)}}function P$(e){let t=new Set;for(let[n,s]of Object.entries(Bo))s.type==="string"&&(t.add(`--${n}`),s.short&&t.add(`-${s.short}`));for(let n=0;n<e.length;n++){let s=e[n];if(s==="--")return{at:-1};if(t.has(s)){n++;continue}if(!s.startsWith("-"))return{name:s,at:n}}return{at:-1}}function R$(e,t){let n={...Bo,...e.flags??{}},s={};for(let[a,i]of Object.entries(n))s[a]={type:i.type,...i.short?{short:i.short}:{},...i.multiple?{multiple:!0}:{}};try{let{values:a,positionals:i}=A$({args:t,options:s,strict:!0,allowPositionals:!0});return{flags:a,positionals:i}}catch(a){throw h(a instanceof Error?a.message.replace(/^.*?: /,""):String(a),`palbase help ${e.name}`)}}function E$(e,t,n,s){let a="error",i,o,r=1,l;return e instanceof f?(a=e.code,i=e.message,o=e.hint,r=e.exitCode):e instanceof q?(a=e.code,i=e.message,l=e.requestId,e.code==="token_out_of_scope"&&t.env.PALBASE_TOKEN&&(i=`${e.op} refused PALBASE_TOKEN: ${e.message}`,o="this is the token's reach, fixed when it was minted: a person's yes does not change it \u2014 mint a token whose scopes name this call, or have a person run it signed in")):i=e instanceof Error?e.message:String(e),n&&e instanceof f&&e.reported||(n&&t.stdout(`${JSON.stringify({error:a,message:i,...o?{hint:o}:{},...l?{request_id:l}:{}},null,2)}
14
14
  `),t.stderr(`error: ${le(i)}${l?` (request ${le(l)})`:""}
15
15
  `),o&&t.stderr(` ${le(o)}
@@ -11831,7 +11831,7 @@ ${t}}`}var us=e=>["",e.toUpperCase(),"-".repeat(e.length)],EO=[{title:"One packa
11831
11831
  "include": ["src/**/*.ts", "tests/**/*.ts", "palbase/*.d.ts"]
11832
11832
  }
11833
11833
  `,hq=`# The backend as a machine builds it: its dependencies, then its source, run by Bun.
11834
- FROM oven/bun:1.4.2-alpine
11834
+ FROM oven/bun:1.4.5-alpine
11835
11835
  WORKDIR /app
11836
11836
  COPY package.json bun.lock* ./
11837
11837
  RUN bun install --production
@@ -11997,7 +11997,7 @@ export class NotesController {
11997
11997
  return Database.public.notes.findMany({ orderBy: { column: "created_at", direction: "desc" }, limit: 20 });
11998
11998
  }
11999
11999
  }
12000
- `;function Aq(e){let t=uq(e).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[._-]+|[._-]+$/g,"");return t===""?"backend":t.slice(0,214)}function Pq(e){let t=Ga(void 0,Np({secrets:[],flags:[],buckets:[]}));return e?Ga(t,$q,qo):t}function Rq(e,t){let n={name:e,private:!0,type:"module",scripts:{dev:"bun --watch run src/main.ts",start:"bun run src/main.ts",test:"bun test ./tests"},dependencies:{palbase:`^${Zo}`},devDependencies:{"@types/bun":"^1.4.2"}};return{"package.json":`${JSON.stringify(n,null,2)}
12000
+ `;function Aq(e){let t=uq(e).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[._-]+|[._-]+$/g,"");return t===""?"backend":t.slice(0,214)}function Pq(e){let t=Ga(void 0,Np({secrets:[],flags:[],buckets:[]}));return e?Ga(t,$q,qo):t}function Rq(e,t){let n={name:e,private:!0,type:"module",scripts:{dev:"bun --watch run src/main.ts",start:"bun run src/main.ts",test:"bun test ./tests"},dependencies:{palbase:`^${Zo}`},devDependencies:{"@types/bun":"^1.4.5"}};return{"package.json":`${JSON.stringify(n,null,2)}
12001
12001
  `,"tsconfig.json":gq,Dockerfile:hq,"palbase/palbase-env.d.ts":Pq(t),".gitignore":yq,"src/main.ts":kq(t),"src/app.module.ts":vq(t),"src/health.controller.ts":fq,"tests/health.test.ts":bq,...t?{"src/db/public.ts":_q,"src/notes/notes.controller.ts":Sq,"tests/notes.test.ts":wq}:{}}}async function Eq(e){try{return await dq(e),!0}catch{return!1}}var C0={name:"init",summary:"start a backend on palbase/backend here (or in <dir>): a health route, its module, its tests, a Dockerfile; --db adds a schema, its routes and their test",usage:"[dir] [--db] [--print]",details:["Nothing already there is written over: a file init would write that exists stops it, naming the file.","--db's table is typed in palbase/palbase-env.d.ts by the block palbase db:types writes of the schema: run db:types again when you change it.","--print writes nothing: it prints the files as JSON ({ name, db, version, files: { <path>: <text> } }), for a program that seeds a repository with this release's starter (bunx palbase@<version> init --print <name> --db).","Then: bun install, palbase use <project>/<environment>, palbase env:pull, bun dev.",`Its tests: bun test (here, no app); palbase test --users alice,bob --base-url http://localhost:8080 -- bun test ./tests (against the app you started, as test users made for the run \u2014 with an environment's token, against the deployed machine: --base-url https://<ref>.app.palbase.studio); on the platform, palbase machines:update <name> --test-command "bun test ./tests" --test-users alice,bob runs them against each new build before it takes traffic.`],args:{min:0,max:1},flags:{db:{type:"boolean",description:"with a database: a schema file (a table each user reads alone) and its routes"},print:{type:"boolean",description:"print the files as JSON, write nothing ([dir] names the package)"}},scope:"none",async run(e){let t=mq(e.io.cwd,e.args[0]??"."),n=e.flags.db===!0,s=Aq(t),a=Rq(s,n);if(e.flags.print===!0){e.io.stdout(`${JSON.stringify({name:s,db:n,version:Zo,files:a},null,2)}
12002
12002
  `);return}let i=[];for(let r of Object.keys(a))await Eq(vu(t,r))&&i.push(r);if(i.length>0)throw new f("already_there",`${i.join(", ")} ${i.length===1?"is":"are"} already in ${t}: init starts a backend, it writes over nothing`,{hint:"run it in an empty directory, or palbase init <new-dir>"});for(let[r,l]of Object.entries(a))await pq(vu(t,r,".."),{recursive:!0}),await cq(vu(t,r),l,{flag:"wx"});let o=["bun install","palbase use <project>/<environment>","palbase env:pull",...n?["palbase db:push --url <your Postgres> (or palbase databases:create, then db:push)","set PALBASE_DB_URL in .env.local (palbase db:url prints it)"]:[],"bun dev","palbase test --users alice,bob --base-url http://localhost:8080 -- bun test ./tests"];e.out.result({dir:t,files:Object.keys(a),db:n},()=>{e.out.line(`Started a backend in ${t}: ${Object.keys(a).join(", ")}.`),e.out.line(`Next: ${o.join(" \u2192 ")}.`)})}};function jq(e){return[cp(e?.ownerLogin),Hu,Vu,Nh,Ih,Lh,C0,jm,Sm,_0,Tm,Nm,wh,vh,kh,_h,$h,Ah,Sh,Ph,Rh,...Xu,...h_,Eh,jh,Th,Ch,Oh,xh,Dh,Mh,zh,...r_,...bh,...Hb,...Xb,Fk,...i_,...sm,...Zb,...pw,...cw,...Pw,...jw,...Rw,...Ov,...Kk,...Gk,...sv,Xv,Yv,...nk,...uk,...ik,...wk,...Rk,Ib,Lb,Db,Mb,zb,qb,Gb,Kb,Fb,Ub,lf,pf,df,cf,ry,py,yf,cy,by,wy,dy,vy,_y,$y,Sy,Ay,Ry,Ty,...Py,Cy,Ey,Oy,xy,...jy,Ny,Iy,Ly,Dy,My,zy,qy,Gy,Ky,Uy,Fy,Wy,By,Jy,Hy,Vy,uf,...Jm,ly,Xy,Yy,ef,tf,nf,sf,Zy,af,of,rf,Hh,Vh,Xh,Yh,Qh,S0,P0,R0,E0,j0,T0,A0,...i0]}var O0=jq();import{spawn as N0}from"node:child_process";import{constants as xq,homedir as Nq}from"node:os";import{createInterface as Iq}from"node:readline/promises";var Tq=new Set(["UND_ERR_CONNECT_TIMEOUT","ECONNREFUSED","ENOTFOUND","EAI_AGAIN","ENETUNREACH","EHOSTUNREACH","ENETDOWN"]),Cq=new Set(["ECONNRESET","UND_ERR_SOCKET","EPIPE","UND_ERR_CLOSED"]);function Oq(e){let t=e?.cause,n=t?.code??t?.errors?.[0]?.code;return typeof n=="string"?n:""}function x0(e,t,n=3){return(async(s,a={})=>{let i=(a.method??"GET").toUpperCase(),o=a.body instanceof ReadableStream;for(let r=1;;r++)try{return await e(s,a)}catch(l){let p=Oq(l);if(!(Tq.has(p)||Cq.has(p)&&(i==="GET"||i==="HEAD"))||o||r>=n||a.signal?.aborted)throw l;await t(300*r)}})}function I0(){let e=process.env;return{stdout:t=>{process.stdout.write(t)},stderr:t=>{process.stderr.write(t)},async readStdin(){if(process.stdin.isTTY)return Gq();let t=[];for await(let n of process.stdin)t.push(n);return Buffer.concat(t).toString("utf8")},async readStdinBytes(t){let n=[],s=0;for await(let a of process.stdin){if(s+=a.byteLength,s>t)return process.stdin.destroy(),null;n.push(a)}return new Uint8Array(Buffer.concat(n,s))},async prompt(t){let n=Iq({input:process.stdin,output:process.stderr});try{return await n.question(t)}finally{n.close()}},openBrowser:t=>qq(t,e),env:e,cwd:process.cwd(),interactive:!!(process.stdin.isTTY&&process.stderr.isTTY)&&e.CI===void 0,configDir:Tu(e,Nq()),fetch:x0(globalThis.fetch.bind(globalThis),t=>new Promise(n=>setTimeout(n,t))),run:(t,n,s={})=>new Promise(a=>{let i=N0(t,n,{cwd:s.cwd,env:{...s.envOnly?zq(process.env):process.env,...s.env??{}},stdio:s.inherit?"inherit":["ignore","pipe","pipe"]}),o="",r="",l=s.inherit?Dq(i,process.stdin.isTTY===!0):()=>{};i.stdout?.setEncoding("utf8"),i.stderr?.setEncoding("utf8"),i.stdout?.on("data",p=>o+=p),i.stderr?.on("data",p=>r+=p),i.once("error",p=>{l(),a({code:p.code==="ENOENT"?127:1,stdout:o,stderr:p.message})}),i.once("close",(p,d)=>{l(),a({code:p??(d?128+(xq.signals[d]??0):1),stdout:o,stderr:r})})}),now:()=>Date.now(),sleep:t=>new Promise(n=>setTimeout(n,t))}}var Lq=["SIGHUP","SIGINT","SIGTERM"];function Dq(e,t){let n=Lq.map(s=>{let a=()=>{s==="SIGINT"&&t?void 0:e.kill(s)};return process.on(s,a),[s,a]});return()=>{for(let[s,a]of n)process.off(s,a)}}var Mq=["PATH","Path","PATHEXT","HOME","USERPROFILE","TMPDIR","TEMP","TMP","SystemRoot","LANG","LC_ALL"];function zq(e){return Object.fromEntries(Mq.flatMap(t=>e[t]===void 0?[]:[[t,e[t]]]))}function qq(e,t){if(t.PALBASE_NO_BROWSER||t.CI!==void 0)return Promise.resolve(!1);let[n,s]=process.platform==="darwin"?["open",[e]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",e]]:["xdg-open",[e]];return new Promise(a=>{try{let i=N0(n,s,{stdio:"ignore",detached:!0});i.once("error",()=>a(!1)),i.once("spawn",()=>{i.unref(),a(!0)})}catch{a(!1)}})}function Gq(){let e=process.stdin;return new Promise((t,n)=>{let s="",a=o=>{e.off("data",i),e.setRawMode(!1),e.pause(),process.stderr.write(`
12003
12003
  `),o()},i=o=>{for(let r of o.toString("utf8")){if(r==="")return a(()=>t(s));if(r==="")return a(()=>n(new Error("cancelled: nothing was read")));r==="\r"||r===`