palbase 0.5.2 → 0.6.2

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 (39) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +7 -7
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{QHPZF7VM.js → 2RG3I7LX.js} +2 -2
  8. package/dist/chunks/{LHLMCQKI.js → 53FS342F.js} +2 -2
  9. package/dist/chunks/{MYNCDAKM.js → A3CDCPXX.js} +1 -1
  10. package/dist/chunks/{QHJ4OPPI.js → A76UZBAF.js} +2 -2
  11. package/dist/chunks/{FNUO6DSY.js → AD5LBZAB.js} +1 -1
  12. package/dist/chunks/{4ZVJ62A3.js → AYY4J3B2.js} +1 -1
  13. package/dist/chunks/{K2LVOEW3.js → DRGYTL6T.js} +2 -2
  14. package/dist/chunks/{ZJOO2XZ2.js → DRTZ33XF.js} +2 -2
  15. package/dist/chunks/{6I6CETZY.js → GVFZM4BI.js} +3 -3
  16. package/dist/chunks/{JHQDWDV3.js → IVEAUFGE.js} +2 -2
  17. package/dist/chunks/{HLYQRT7O.js → IYCW6PWG.js} +2 -2
  18. package/dist/chunks/KL7FIRII.js +2 -0
  19. package/dist/chunks/{TPBWIRHS.js → KLANM6M6.js} +1 -1
  20. package/dist/chunks/{NQA7ZLGD.js → SUX2BJG4.js} +1 -1
  21. package/dist/chunks/{5G3URQAW.js → SXH5AIQX.js} +2 -2
  22. package/dist/chunks/{XRW7YOUQ.js → U4OZ4HOF.js} +2 -2
  23. package/dist/chunks/{EDVRVUCJ.js → VP7V7YRH.js} +2 -2
  24. package/dist/cli.js +2 -2
  25. package/dist/refuse/ai.js +1 -1
  26. package/dist/refuse/backend.js +1 -1
  27. package/dist/refuse/server.js +1 -1
  28. package/dist/server/index.js +2 -2
  29. package/dist/server/testing.js +2 -2
  30. package/dist/web/index.js +2 -2
  31. package/dist/web/palbe.js +2 -2
  32. package/dist/web/paywall.js +2 -2
  33. package/dist/web/ssr.js +2 -0
  34. package/dist/web/vite.js +2 -2
  35. package/package.json +6 -2
  36. package/types/web/src/client.d.ts +3 -1
  37. package/types/web/src/index.d.ts +1 -1
  38. package/types/web/src/session.d.ts +11 -0
  39. package/types/web/src/ssr.d.ts +86 -0
@@ -1,4 +1,4 @@
1
- /*! palbase 0.5.2 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.6.2 — Palbase SDK License (see LICENSE) */
2
2
  import{AsyncLocalStorage as v}from"node:async_hooks";function x(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var A=Symbol.for("palbase.backend.requestScope"),c=globalThis[A]??=new v,b;function I(n){b=n}var N=new Proxy({},{get(n,e){if(!b)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return b[e]}}),C=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function g(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=O(t);n==="error"||n==="warn"?process.stderr.write(`${o}
3
3
  `):process.stdout.write(`${o}
4
4
  `)}function O(n){try{return JSON.stringify(n)}catch{let e=new WeakSet;try{return JSON.stringify(n,(s,t)=>{if(typeof t=="bigint")return t.toString();if(typeof t=="object"&&t!==null){if(e.has(t))return"[circular]";e.add(t)}return t})}catch{return JSON.stringify({time:n.time,level:n.level,msg:n.msg,request_id:n.request_id,unwritable:"a field of this line could not be written"})}}}var m=x("Log",{debug:(n,e)=>g("debug",n,e),info:(n,e)=>g("info",n,e),warn:(n,e)=>g("warn",n,e),error:(n,e)=>g("error",n,e)});var T=512,k=8,L=64,E=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,h={"i-klingon":"tlh","en-gb-oed":"en-GB-oxendict","sgn-be-fr":"sfb","zh-cmn-hans":"cmn-Hans","zh-yue":"yue","hy-arevela":"hy-arevela"};function P(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function _(n){let e=n.split("-"),s=(e[0]??"").toLowerCase();return s==="mo"&&e.length===1?"ro-MD":s==="tl"?(e[0]="fil",e.join("-")):s==="sh"?(e[0]="sr",e.length>1&&/^[A-Za-z]{4}$/.test(e[1]??"")||e.splice(1,0,"Latn"),e.join("-")):n}function q(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>L)return;let s=e.toLowerCase(),t=Object.hasOwn(h,s)?h[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales(_(e))[0]}catch{return}if(t===void 0)return}let i=P(t);if(!(i===""||i==="und"||i==="mul"))return t}function D(n){let e=n.split("-"),s=e.findIndex((r,a)=>a>0&&r.length===1),t=s>0?e.slice(0,s):e,i=[],o=r=>{i.includes(r)||i.push(r)};for(let r=t.length;r>1||r===t.length;r--)o(t.slice(0,r).join("-"));if(!t.slice(1).some(r=>/^[A-Za-z]{4}$/.test(r)))try{let r=new Intl.Locale(t.join("-")).maximize().script;r&&o(`${t[0]}-${r}`)}catch{}return o(t[0]),i}function G(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=T){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,l=r.indexOf(";");if(l>=0){let y=r.slice(l+1);r=r.slice(0,l).trim();for(let f of y.split(";")){let p=f.indexOf("=");if(p<0||f.slice(0,p).trim().toLowerCase()!=="q")continue;let w=f.slice(p+1).trim(),d=E.test(w)?Number(w):Number.NaN;a=Number.isFinite(d)&&d>=0&&d<=1?d:0}}a>0&&i.push({tag:r,q:a,at:i.length})}i.sort((o,r)=>r.q-o.q||o.at-r.at);for(let{tag:o}of i.slice(0,k)){let r=q(o);if(r!==void 0)for(let a of D(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function $(n,e,s){let t=n.strings??{},i=Object.hasOwn(t,e)?t[e]:null;for(let o of s){if(o===n.source)break;let r=i!=null&&Object.hasOwn(i,o)?i[o]:void 0;if(typeof r=="string"&&r!=="")return{text:r,locale:o}}return{text:e,locale:n.source}}var j=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function S(n,e){return n.replace(j,(s,t,i,o)=>{if(o[i-1]==="{"||o[i+s.length]==="}")return s;let r=e!==void 0&&Object.hasOwn(e,t)?e[t]:void 0;return r==null?"":String(r)})}var u;function K(n){u=n===void 0?void 0:{root:n,said:!1}}function Z(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,m.warn(`[palbase] t(): the app has no palbase/strings (looked in ${u.root}) \u2014 every sentence is said as it is written. \`npx palbase strings\` starts the table; an image takes it with COPY palbase ./palbase`)),S(n,e);let{text:i,locale:o}=$(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),S(i,e)}export{x as a,R as b,c,I as d,N as e,C as f,m as g,G as h,K as i,Z as j};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.5.2 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.6.2 — Palbase SDK License (see LICENSE) */
2
2
  import{lstat as j,mkdir as F,readdir as M,readFile as N,rename as J,rm as T,writeFile as v}from"node:fs/promises";import{join as E}from"node:path";var o="palbase/strings",f="_meta.json",p=3,y=2,$=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function m(r){try{return Intl.getCanonicalLocales(r)[0]}catch{return}}function b(r,n){try{return JSON.parse(r)}catch(t){throw new Error(`${n} is not JSON: ${t.message}`)}}async function x(r){let n=E(r,o);try{if(!(await j(n)).isDirectory())throw new Error(`${o} is not a directory: the strings live in a directory of their own`)}catch(e){if(e.code==="ENOENT")return;throw e}let t=new Map;for(let e of await M(n,{withFileTypes:!0}))if(!(e.name.startsWith(".")||!e.name.endsWith(".json"))){if(!e.isFile())throw new Error(`${o}/${e.name} is not a regular file`);t.set(e.name,await N(E(n,e.name),"utf8"))}return t.size===0?void 0:t}async function R(r,n=[p,y]){let t=await x(r);if(t===void 0)return;let e=t.get(f);if(e===void 0)throw new Error(`${o}/${f} is missing: it names the source language, and without it the language files are not a table`);let u=b(e,`${o}/${f}`);if(!$(u))throw new Error(`${o}/${f}: not a JSON object`);let s=u.version;if(s===y&&!n.includes(y))throw new Error(`${o}/${f}: version 2 is the earlier format ({"value", "state"} for each sentence) \u2014 run \`npx palbase strings\` once, and it writes the table as version ${p}`);if(typeof s!="number"||!n.includes(s))throw new Error(`${o}/${f}: version ${JSON.stringify(s)} is not one this reads (${n.join(" or ")})`);let a=u.source;if(typeof a!="string"||m(a)!==a)throw new Error(`${o}/${f}: source ${JSON.stringify(a)} is not a language tag as it is written (${m(String(a))??"en, en-US, zh-Hans"})`);let S=new Map;for(let w of[...t.keys()].sort()){if(w===f)continue;let i=w.slice(0,-5),g=`${o}/${w}`,d=m(i);if(d===void 0)throw new Error(`${g}: ${JSON.stringify(i)} is not a language tag`);if(d!==i)throw new Error(`${g}: the language is written ${d} \u2014 name the file ${d}.json`);if(i===a)throw new Error(`${g}: ${i} is the source language \u2014 its text is the key itself, and it has no file`);if(i==="und"||i==="root"||i.startsWith("x-"))throw new Error(`${g}: ${i} is no language a request names \u2014 name the file for one (en, de, pt-BR)`);let O=b(t.get(w),g);if(!$(O))throw new Error(`${g}: not a JSON object of "sentence": "translation"`);let h=new Map;for(let[l,c]of Object.entries(O))if(s===p){if(typeof c!="string")throw new Error(`${g}: the translation of ${JSON.stringify(l)} is not a string`);h.set(l,c)}else if(typeof c=="string")h.set(l,c);else{if(!$(c)||typeof c.value!="string")throw new Error(`${g}: key ${JSON.stringify(l)} is not {"value": string, "state": string}`);h.set(l,c.state==="missing"?"":c.value)}S.set(i,h)}return{format:s,source:a,languages:S}}async function A(r){let n=await R(r,[p]);if(n===void 0)return;let t={};Object.setPrototypeOf(t,null);for(let[e,u]of n.languages)for(let[s,a]of u)Object.hasOwn(t,s)||(t[s]={},Object.setPrototypeOf(t[s],null)),t[s][e]=a;return{source:n.source,locales:[n.source,...n.languages.keys()],strings:t}}export{A as a};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.5.2 — Palbase SDK License (see LICENSE) */
2
- import{a as dt,c as ee,d as Un,e as le,g as E,h as Ln}from"./FNUO6DSY.js";import{b as Ke,d as ot,e as Mn,f as Dn,g as at,h as it,k as jn,q as Nn}from"./XRW7YOUQ.js";import{b as ie}from"./HLYQRT7O.js";import"reflect-metadata";var Pt=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],In="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",ct=/^\d+$/;function bs(e,t,n){let r=new Set;for(let s of e.split(",")){let o=s.indexOf("/"),a=o===-1?s:s.slice(0,o),i=1;if(o!==-1){let y=s.slice(o+1);if(!ct.test(y)||Number(y)<1||Number(y)>n)return;i=Number(y)}let c=t,p=n;if(a!=="*")if(a.includes("-")){let y=a.indexOf("-"),k=a.slice(0,y),R=a.slice(y+1);if(!ct.test(k)||!ct.test(R)||Number(k)<t||Number(R)>n||Number(k)>Number(R))return;c=Number(k),p=Number(R)}else{if(!ct.test(a)||Number(a)<t||Number(a)>n)return;c=Number(a),p=o===-1?c:n}for(let y=c;y<=p;y+=i)r.add(y)}return r}function zn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${In}; "${e}" is not`;let n=[];for(let p=0;p<5;p++){let y=bs(t[p],Pt[p].lo,Pt[p].hi);if(!y)return`${In}; its ${Pt[p].name} "${t[p]}" is not one`;n.push(y)}let[,,r,s,o]=n;o.has(7)&&o.add(0);let a=t[2].startsWith("*"),i=t[4].startsWith("*"),c=new Date(Date.UTC(2e3,0,1));for(let p=0;p<366*8+2;p++,c.setUTCDate(c.getUTCDate()+1)){if(!s.has(c.getUTCMonth()+1))continue;let y=r.has(c.getUTCDate()),k=o.has(c.getUTCDay());if(a||i?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var _e=Symbol.for("palbase.backend.controller"),Se=Symbol.for("palbase.backend.routes"),Mt=Symbol.for("palbase.backend.params"),Dt=Symbol.for("palbase.backend.injectable"),jt=Symbol.for("palbase.backend.module"),be=Symbol.for("palbase.backend.events"),Oe=Symbol.for("palbase.backend.webhook"),he=Symbol.for("palbase.backend.crons"),fe=Symbol.for("palbase.backend.tasks");function Y(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var Ct=Symbol.for("palbase.backend.declared");function re(){let e=globalThis;return e[Ct]instanceof Set||(e[Ct]=new Set),e[Ct]}var xe=new Set(["webhooks","_palbase"]);function Ka(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&xe.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);Y(n,_e,()=>({basePath:e,options:t})),re().add(n)}}function Ae(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,o)=>{if(typeof s!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);Y(r.constructor,Se,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var Ja=Ae("GET"),Wa=Ae("POST"),Va=Ae("PUT"),Za=Ae("PATCH"),Qa=Ae("DELETE"),Ga=Ae("QUERY");function se(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let o=Y(n.constructor,Mt,()=>new Map);o.has(r)||o.set(r,[]),o.get(r).push({index:s,kind:e,...t})}}function Nt(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var Ya=e=>se("body",{schema:Nt("Body",e)}),Xa=e=>se("query",{schema:Nt("QueryParams",e)}),ei=e=>se("headers",e===void 0?{}:{schema:Nt("Headers",e)}),ti=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return se("param",{name:e})},ni=()=>se("user"),ri=()=>se("optionalUser"),si=()=>se("req"),oi=()=>se("requestId"),ai=()=>se("requestId"),ii=()=>se("client");function di(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return se("resolve",{resolver:e,options:t[0]})}function ci(){return e=>{Y(e,Dt,()=>!0),re().add(e)}}function ui(e){return t=>{Y(t,jt,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Bn=/^[a-z]+(\.[a-z_]+)+$/,ks=/^[a-z][a-z0-9-]{1,62}$/,Ut=e=>e.startsWith("file.");function li(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!ks.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!Ut(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,o)=>{if(typeof s!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@On("${e}") goes on a method`);Y(r.constructor,be,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),re().add(r.constructor)}}var Lt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,vs=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function qn(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!vs.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function fi(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Lt.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=zn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||qn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${qn(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return o=>{if(typeof o.prototype.run!="function")throw new TypeError(`${n} on ${o.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(o,he))throw new TypeError(`${n} on ${o.name}: a class is one cron`);Object.defineProperty(o,he,{value:s,enumerable:!1}),re().add(o)}}var Hn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],$s=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function pi(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!$s.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!Hn.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${Hn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&Ts(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=M(t,be)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let o=new Set;for(let{event:a,bucket:i}of s){if(o.has(a))throw new TypeError(`${n}: @On("${a}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${n}: @On("${a}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);o.add(a)}Y(t,Oe,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:a,fn:i})=>({event:a,fn:i}))})),re().add(t)}}function Ts(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function mi(){return[...re()].filter(e=>M(e,_e)!==void 0)}function hi(e){return(M(e,Se)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var ut=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function ki(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Lt.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,fe))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,fe,{value:r,enumerable:!1}),re().add(s)}}var qt;function Kn(e){qt=e}function It(){if(!qt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return qt}var Es=720*3600;function Rs(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Es))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function _s(e){if(typeof e=="string")return e;let t=e[fe];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var vi=dt("Tasks",{async enqueue(e,t,n={}){return Rs(n),It().enqueue(_s(e),t===void 0?null:t,n)},async cancel(e,t={}){return It().cancel(e,t.machine)},async get(e,t={}){return It().get(e,t.machine)}}),zt=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function Jn(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let o=await le.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return zt(o.data,o.status===200)},async cancel(n,r){return zt((await le.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return zt((await le.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ss=1e4,Os=36e5,Fn=24*36e5,lt=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let c of this.tasks.values())if(c.task===t&&c.key===r.key&&(c.finishedAt===void 0||this.now()-c.finishedAt<Fn))return this.view(c,!0)}let o=this.now(),a=r.delay!==void 0?o+r.delay*1e3:r.runAt?Math.max(o,r.runAt.getTime()):o,i={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:a,createdAt:new Date(o)};return this.tasks.set(i.id,i),this.schedule(i),this.view(i,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),o;try{o=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(o={status:504,message:`it did not end in ${n.timeout} s`})}catch(i){o={status:500,message:i.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let a=`${o.status}${o.message?`: ${o.message}`:""}`;o.status>=200&&o.status<300?this.finish(t,"succeeded"):o.status===422?this.finish(t,"failed",`the app said it can never be done: ${a}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${a}`):(t.state="waiting",t.reason=`the app answered ${a}`,t.runAt=this.now()+Math.min(Ss*2**Math.min(t.attempt-1,16),Os),E.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,o]of this.tasks)o.finishedAt!==void 0&&this.now()-o.finishedAt>=Fn&&this.tasks.delete(s);n==="failed"&&E.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};import{markData as As}from"palgres";var Ht="/_palbase/storage/upload/authorize",Wn="/_palbase/storage/upload/complete",Bt="/_palbase/realtime/rooms";var xs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Pe(e){if(!xs(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function Vn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Zn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function ft(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var pe=Symbol.for("palbase.backend.room"),Me=Symbol.for("palbase.backend.roomHooks"),Jt=6e4,Ce=255,Ps=["roles:","flags:","messaging:","debug:"],Wt=e=>new TextEncoder().encode(e).byteLength,Qn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function";function Vt(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Wt(e)>Ce)return`a channel is ${Ce} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=Ps.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Gn(e){if(typeof e!="string"||e==="")return"is a name";if(Wt(e)>Ce)return`is ${Ce} bytes at most`}function Oi(e,t){if(typeof e!="string"||e==="")throw new TypeError('@Room(pattern, { events }): pattern is the channels it is, like "ai:{sessionId}"');let n=Vt(e);if(n)throw new TypeError(`@Room("${e}"): ${n}`);let r=t??{};if(typeof r.events!="object"||r.events===null||Array.isArray(r.events))throw new TypeError(`@Room("${e}"): events is required \u2014 what the room sends, by name, each its payload's schema ({} for none)`);for(let[a,i]of Object.entries(r.events)){let c=Gn(a);if(c)throw new TypeError(`@Room("${e}"): event "${a}" ${c}`);if(!Qn(i))throw new TypeError(`@Room("${e}"): event "${a}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Room("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);let s={...r.events},o=r.graceMs??Jt;return a=>{let i=Y(a,Me,Zt);Y(a,pe,()=>({pattern:e,events:s,graceMs:o,hooks:{...i.hooks},messages:Object.assign(Object.create(null),i.messages)})),re().add(a)}}var Zt=()=>({hooks:Object.create(null),messages:Object.create(null)});function Je(e){let t=`On${e[0].toUpperCase()}${e.slice(1)}`;return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a room's methods are its instance's`);let o=Y(n.constructor,Me,Zt),a=o.hooks[e];if(a!==void 0&&a!==r)throw new TypeError(`@${t}() is declared twice in one room (${a} and ${r}). A room has one of each hook.`);o.hooks[e]=r,re().add(n.constructor)}}var xi=Je("authorize"),Ai=Je("first"),Pi=Je("join"),Ci=Je("leave"),Mi=Je("empty");function Di(e,t){let n=Gn(e);if(n)throw new TypeError(`@OnMessage(name, schema): name ${n}`);if(!Qn(t))throw new TypeError(`@OnMessage("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return(r,s,o)=>{if(typeof s!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@OnMessage("${e}") goes on a method`);if(typeof r=="function")throw new TypeError(`@OnMessage("${e}") on static ${r.name}.${s}: a room's methods are its instance's`);let a=Y(r.constructor,Me,Zt),i=a.messages[e];if(i!==void 0&&i.fn!==s)throw new TypeError(`@OnMessage("${e}") is declared twice in one room (${i.fn} and ${s}).`);a.messages[e]={fn:s,schema:t},re().add(r.constructor)}}function Qt(e){return M(e,pe)}function Cs(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let o=0;o<n.length;o++){let a=n[o];if(a.length>=2&&a.startsWith("{")&&a.endsWith("}")){if(r[o]==="")return;s.push([a.slice(1,-1),r[o]])}else if(a!==r[o])return}return Object.fromEntries(s)}var Ms=1e4,Ds=1e3,js=100,Gt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ce=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Ns=new Set(["first","join","leave","empty"]);function Yn(e,t){let n=new Map,r=new Map;for(let{cls:h,instance:v}of e){let b=Qt(h),O=b.pattern.split(":").map(F=>F.startsWith("{")?"{}":F).join(":"),z=r.get(O);if(z!==void 0)throw new TypeError(`@Room("${b.pattern}") on ${h.name}: ${n.get(z)?.cls.name}'s "${z}" is the same channels \u2014 one room is told of them; keep one`);r.set(O,b.pattern);for(let[F,D]of[...Object.entries(b.hooks),...Object.entries(b.messages).map(([j,q])=>[`message ${j}`,q.fn])])if(typeof v[D]!="function")throw new TypeError(`@Room("${b.pattern}") on ${h.name}: its ${F} is ${D}, which is no method of it`);n.set(b.pattern,{cls:h,instance:v,room:b})}let s=new Map,o=new Set,a=new Set,i=new Kt(t.broadcast),c=h=>{let v=s.get(h);return v||(v=new AbortController,s.set(h,v)),v},p=(h,v)=>{v?.abort(),s.get(h)===v&&s.delete(h)};function y(h,v,b,O,z,F,D){let j=O?.signal??AbortSignal.abort(),q=`${h.cls.name} (${v})`;return{room:v,params:Object.freeze({...b}),signal:j,count:z,user:F,emit:(H,K)=>i.send({topic:v,event:H,payload:K??{},...D!==void 0?{conn_id:D}:{}},q),owner:{hold(H){ee.exit(async()=>{try{await H(j)}catch(K){j.aborted||E.error(`[palbase] ${q}: a task owner.hold ran failed`,{error:K})}}).catch(()=>{})},release:()=>p(v,O)}}}function k(h){let{room:v,channel:b}=h;if(typeof v!="string"||typeof b!="string")return ce(400,"bad_request","A room's call names its room (the pattern) and its channel");let O=n.get(v);return O?{entry:O,channel:b,params:Cs(v,b)}:ce(404,"not_found",`This app declares no room "${v}"`)}let R=(h,v)=>ce(400,"bad_request",`"${v}" is not a channel of the room "${h}"`);async function U(h,v){let b=k(h);if("status"in b)return b;let{entry:O,channel:z,params:F}=b,D={status:200,body:{subscribe:!1,publish:!1}};if(!F)return E.warn(`[palbase] ${O.cls.name}: realtime asked about "${z}", which is not a channel of the room "${O.room.pattern}"; the join is refused`),D;let j=Pe(h.user),q=j?.id;if(!q)return D;let H=O.room.hooks.authorize;if(!H)return D;let K,de;try{K=await t.run(j,`${O.cls.name}.${H}`,v,async()=>O.instance[H]({user:{id:q},params:Object.freeze({...F})})),de=Us(K)}catch(ne){if(t.isOutage(ne)||v?.aborted)throw ne;return E.error(`[palbase] ${O.cls.name}.${H} (@OnAuthorize of ${z}) failed; the join is refused`,{error:ne}),D}return de==="malformed"?(E.warn(`[palbase] ${O.cls.name}.${H} (@OnAuthorize of ${z}) answered ${Ls(K)}, which is no grant (true, { read, write } or null); the join is refused`),D):{status:200,body:de}}async function I(h,v){let b=k(h);if("status"in b)return b;if(!b.params)return R(b.entry.room.pattern,b.channel);let O=Pe(h.user);if(!O?.id||typeof h.event!="string")return ce(400,"bad_request","A message names its member (user) and its event");let z=Object.hasOwn(b.entry.room.messages,h.event)?b.entry.room.messages[h.event]:void 0;if(!z)return{status:200,body:{ok:!1,reason:Xn(`room "${b.channel}" declares no message "${h.event}"`,Ft)}};let F=await z.schema["~standard"].validate(As(h.payload??{}));if(F.issues)return{status:200,body:{ok:!1,reason:zs(F.issues)}};let D=c(b.channel),j={...y(b.entry,b.channel,b.params,D,0,{id:O.id}),payload:F.value};try{await t.run(O,`${b.entry.cls.name}.${z.fn}`,v,async()=>b.entry.instance[z.fn](j))}catch(q){if(t.isOutage(q))throw q;return v?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${z.fn} (@OnMessage "${h.event}" of ${b.channel}) failed`,{error:q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return{status:200,body:{ok:!0}}}async function L(h,v){let b=k(h);if("status"in b)return b;if(!b.params)return R(b.entry.room.pattern,b.channel);let O=h.event;if(typeof O!="string"||!Ns.has(O))return ce(400,"bad_request","A room's moment is first, join, leave or empty");let z=typeof h.count=="number"&&Number.isInteger(h.count)&&h.count>=0?h.count:void 0;if(z===void 0)return ce(400,"bad_request","A room's moment says its count of members");let F=O==="join"||O==="leave",D=F?Pe(h.user):void 0,j=F?h.connId:void 0;if(F&&(!D?.id||typeof j!="string"||j===""))return ce(400,"bad_request",`A ${O} names its member: user and connId`);let q=`${O}\0${b.channel}\0${typeof j=="string"?j:""}`;if(F&&o.has(q))return{status:204};if(a.has(q))return ce(503,"in_progress","This moment of the room is being handled",5);a.add(q);try{let H=b.entry.room.hooks[O],K;if(O==="empty"?(K=s.get(b.channel),p(b.channel,K)):K=O==="leave"?s.get(b.channel):c(b.channel),H){let de=y(b.entry,b.channel,b.params,K,z,{id:D?.id??""},O==="join"?j:void 0);try{await t.run(D,`${b.entry.cls.name}.${H}`,v,async()=>b.entry.instance[H](de))}catch(ne){if(t.isOutage(ne))throw ne;return v?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${H} (${O} of ${b.channel}) failed; realtime tells it again`,{error:ne}),ce(500,"handler_failed",`The room's ${O} could not be handled`)}}return F&&(o.add(q),o.size>Ms&&o.delete(o.values().next().value)),{status:204}}finally{a.delete(q)}}return{declarations:[...n.values()].map(h=>h.room),async serve(h,v,b){return Gt(v)?h==="authorize"?U(v,b):h==="message"?I(v,b):h==="lifecycle"?L(v,b):ce(404,"not_found",`No room call ${JSON.stringify(h)}`):ce(400,"bad_request","A room's call is a JSON object")},close(){for(let h of s.values())h.abort();s.clear()}}}function Us(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!Gt(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,o=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:o!==!1}}function Ls(e){return Array.isArray(e)?"an array":Gt(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var Is=20,Ft=256;function zs(e){let t="";for(let n of e.slice(0,Is)){let r=(n.path??[]).slice(0,8).map(o=>String(typeof o=="object"&&o!==null&&"key"in o?o.key:o).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Ft)break}return Xn(t,Ft)}function Xn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var Kt=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Wt(t.event)>Ce){E.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Ce} bytes`);return}try{JSON.stringify(t.payload)}catch(o){E.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:o});return}let r=this.queues.get(t.topic);if(r){r.length>=Ds?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ee.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,js);try{await this.broadcast(s)}catch(a){E.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:a})}let o=this.dropped.get(t);o&&(this.dropped.delete(t),E.warn(`[palbase] ${r}: ${o} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};var Yt=Symbol.for("palbase.backend.channels");function Ii(){return{kind:"owner"}}function zi(e={}){return{kind:"public",publish:e.publish??!1,state:e.state}}var qs=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}")).length,pt=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function qi(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("defineChannels({ pattern: entry }): an object of channel patterns");let t=[],n=[],r=new Map;for(let[i,c]of Object.entries(e)){let p=Vt(i);if(p)throw new TypeError(`defineChannels: "${i}": ${p}`);let y=r.get(pt(i));if(y!==void 0)throw new TypeError(`defineChannels: "${i}" and "${y}" are the same channels \u2014 keep one`);if(r.set(pt(i),i),typeof c!="object"||c===null)throw new TypeError(`defineChannels: "${i}": an entry is ownerOnly(), publicChannel() or { authorize }`);if("handler"in c)throw new TypeError(`defineChannels: "${i}": a handler is a room's in v3 \u2014 write @Room("${i}", { events }) with @OnAuthorize and @OnMessage, and leave it out of channels`);if("kind"in c&&c.kind==="owner"){if(qs(i)!==1)throw new TypeError(`defineChannels: ownerOnly() pattern "${i}" must carry exactly one {param} (its value is compared to the signed-in user's id)`);t.push({pattern:i,kind:"owner",publish:!1,state_read:!1,state_write:!1})}else if("kind"in c&&c.kind==="public")t.push({pattern:i,kind:"public",publish:c.publish??!1,state_read:c.state?.read??!1,state_write:c.state?.write??!1});else if("authorize"in c&&typeof c.authorize=="function")n.push({pattern:i,authorize:c.authorize});else throw new TypeError(`defineChannels: "${i}": an entry is ownerOnly(), publicChannel() or { authorize(ctx) }`)}let s={rows:t,custom:n},o=globalThis,a=o[Yt];if(a&&!Hs(a,s))throw new Error(`defineChannels: channels were already declared (${[...a.rows,...a.custom].map(i=>i.pattern).join(", ")}). A project declares its channels once \u2014 a second call would overwrite the first, and channels nobody declared are refused.`);return o[Yt]=s,s}function Hs(e,t){let n=r=>JSON.stringify([r.rows,r.custom.map(s=>[s.pattern,s.authorize.toString()])]);return n(e)===n(t)}function er(){return globalThis[Yt]??{rows:[],custom:[]}}function tr(e){let t=!1;return e.custom.map(({pattern:n,authorize:r})=>{let s={[`channel ${n}`]:class{}}[`channel ${n}`];return Y(s,pe,()=>({pattern:n,events:{},graceMs:Jt,hooks:{authorize:"authorize"},messages:Object.create(null)})),{cls:s,instance:{async authorize(a){let i=await r(a);return i==null||i.subscribe!==!0?null:(i.state&&!t&&(t=!0,E.warn(`[palbase] channel "${n}": its authorize answered state rights; a channel an authorize function decides is a room, which has none \u2014 the user hears${i.publish?" and sends":""}`)),{read:!0,write:i.publish===!0})}}}})}function nr(e,t){let n=new Map(t.map(r=>[pt(r.pattern),r.pattern]));for(let r of[...e.rows,...e.custom]){let s=n.get(pt(r.pattern));if(s!==void 0)return`channel "${r.pattern}" and @Room("${s}") are the same channels \u2014 a channel is declared in defineChannels or by a @Room, not both`}}var Bs=/^[a-z][a-z0-9-]{1,62}$/,rr=1024,Fs=new Set(["userId","uploadId","filename"]);function Ji(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Bs.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let r=Ks(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(a,i,c)=>{if(typeof i!="string"||c===void 0||typeof c.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);Y(a.constructor,Se,()=>[]).push({method:"POST",subpath:e,fn:i,options:o,upload:s})}}function Wi(){return se("uploadedObject")}function Ks(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Fs.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!sr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function sr(e){if(e===""||new TextEncoder().encode(e).byteLength>rr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Js(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ws(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ws(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function or(e,t){let n=Js(e,t);return sr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${rr} bytes)`}}function ar(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(o=>o.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(o=>o.kind==="headers"||o.kind==="req"||o.kind==="client");if(s){let o=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${o}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var Xt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ir(e,t){if(!Xt(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:o}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof o!="string"||o==="")return"uploadId is the upload's id";let a=Pe(t.user);if(!a)return"user is { id?, session?, role }";let i=Vn(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:o,user:a,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let c=Vs(t.uploadedObject);return c?c.uploadId!==o?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:o,user:a,...i?{client:i}:{},filename:"",uploadedObject:c,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Vs(e){if(!Xt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:o,checksum:a,width:i,height:c,thumbhash:p,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof a!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(i!==void 0&&typeof i!="number"||c!==void 0&&typeof c!="number"||p!==void 0&&typeof p!="string")&&!(!Xt(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:o,checksum:a,...i!==void 0?{width:i}:{},...c!==void 0?{height:c}:{},...p!==void 0?{thumbhash:p}:{},variants:{...y}}}import{createHash as en,createHmac as Zs,createPublicKey as lr,timingSafeEqual as Qs,verify as fr}from"node:crypto";function Gi(e){let t=M(e,Oe);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function pr(e,t,n,r={}){let s=new Map,o=[];for(let a of e){let i=M(a,Oe),c=s.get(i.name);if(c)throw new TypeError(`@Webhook "${i.name}" is declared by ${c.cls.name} and by ${a.name}: /webhooks/${i.name} is one endpoint`);let p=`@Webhook "${i.name}" (${a.name})`,y=n[i.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")o.push(`${p} reads its signing secret from ${i.secret.env}, which is not set`);else try{k=Gs(i,y)}catch(I){o.push(`${p}: ${i.secret.env} ${I.message}`)}let R=t(a),U=new Map(i.events.map(({event:I,fn:L})=>[I,{name:`${a.name}.${L}`,call:(h,v)=>R[L](h,v)}]));s.set(i.name,{name:i.name,cls:a,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:k,events:U})}if(o.length>0)throw new Error(`[palbase] the app cannot start:
1
+ /*! palbase 0.6.2 — Palbase SDK License (see LICENSE) */
2
+ import{a as dt,c as ee,d as Un,e as le,g as E,h as Ln}from"./AD5LBZAB.js";import{b as Ke,d as ot,e as Mn,f as Dn,g as at,h as it,k as jn,q as Nn}from"./U4OZ4HOF.js";import{b as ie}from"./IYCW6PWG.js";import"reflect-metadata";var Pt=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],In="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",ct=/^\d+$/;function bs(e,t,n){let r=new Set;for(let s of e.split(",")){let o=s.indexOf("/"),a=o===-1?s:s.slice(0,o),i=1;if(o!==-1){let y=s.slice(o+1);if(!ct.test(y)||Number(y)<1||Number(y)>n)return;i=Number(y)}let c=t,p=n;if(a!=="*")if(a.includes("-")){let y=a.indexOf("-"),k=a.slice(0,y),R=a.slice(y+1);if(!ct.test(k)||!ct.test(R)||Number(k)<t||Number(R)>n||Number(k)>Number(R))return;c=Number(k),p=Number(R)}else{if(!ct.test(a)||Number(a)<t||Number(a)>n)return;c=Number(a),p=o===-1?c:n}for(let y=c;y<=p;y+=i)r.add(y)}return r}function zn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${In}; "${e}" is not`;let n=[];for(let p=0;p<5;p++){let y=bs(t[p],Pt[p].lo,Pt[p].hi);if(!y)return`${In}; its ${Pt[p].name} "${t[p]}" is not one`;n.push(y)}let[,,r,s,o]=n;o.has(7)&&o.add(0);let a=t[2].startsWith("*"),i=t[4].startsWith("*"),c=new Date(Date.UTC(2e3,0,1));for(let p=0;p<366*8+2;p++,c.setUTCDate(c.getUTCDate()+1)){if(!s.has(c.getUTCMonth()+1))continue;let y=r.has(c.getUTCDate()),k=o.has(c.getUTCDay());if(a||i?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var _e=Symbol.for("palbase.backend.controller"),Se=Symbol.for("palbase.backend.routes"),Mt=Symbol.for("palbase.backend.params"),Dt=Symbol.for("palbase.backend.injectable"),jt=Symbol.for("palbase.backend.module"),be=Symbol.for("palbase.backend.events"),Oe=Symbol.for("palbase.backend.webhook"),he=Symbol.for("palbase.backend.crons"),fe=Symbol.for("palbase.backend.tasks");function Y(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var Ct=Symbol.for("palbase.backend.declared");function re(){let e=globalThis;return e[Ct]instanceof Set||(e[Ct]=new Set),e[Ct]}var xe=new Set(["webhooks","_palbase"]);function Ka(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&xe.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);Y(n,_e,()=>({basePath:e,options:t})),re().add(n)}}function Ae(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,o)=>{if(typeof s!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);Y(r.constructor,Se,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var Ja=Ae("GET"),Wa=Ae("POST"),Va=Ae("PUT"),Za=Ae("PATCH"),Qa=Ae("DELETE"),Ga=Ae("QUERY");function se(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let o=Y(n.constructor,Mt,()=>new Map);o.has(r)||o.set(r,[]),o.get(r).push({index:s,kind:e,...t})}}function Nt(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var Ya=e=>se("body",{schema:Nt("Body",e)}),Xa=e=>se("query",{schema:Nt("QueryParams",e)}),ei=e=>se("headers",e===void 0?{}:{schema:Nt("Headers",e)}),ti=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return se("param",{name:e})},ni=()=>se("user"),ri=()=>se("optionalUser"),si=()=>se("req"),oi=()=>se("requestId"),ai=()=>se("requestId"),ii=()=>se("client");function di(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return se("resolve",{resolver:e,options:t[0]})}function ci(){return e=>{Y(e,Dt,()=>!0),re().add(e)}}function ui(e){return t=>{Y(t,jt,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Bn=/^[a-z]+(\.[a-z_]+)+$/,ks=/^[a-z][a-z0-9-]{1,62}$/,Ut=e=>e.startsWith("file.");function li(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!ks.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!Ut(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,o)=>{if(typeof s!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@On("${e}") goes on a method`);Y(r.constructor,be,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),re().add(r.constructor)}}var Lt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,vs=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function qn(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!vs.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function fi(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Lt.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=zn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||qn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${qn(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return o=>{if(typeof o.prototype.run!="function")throw new TypeError(`${n} on ${o.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(o,he))throw new TypeError(`${n} on ${o.name}: a class is one cron`);Object.defineProperty(o,he,{value:s,enumerable:!1}),re().add(o)}}var Hn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],$s=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function pi(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!$s.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!Hn.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${Hn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&Ts(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=M(t,be)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let o=new Set;for(let{event:a,bucket:i}of s){if(o.has(a))throw new TypeError(`${n}: @On("${a}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${n}: @On("${a}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);o.add(a)}Y(t,Oe,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:a,fn:i})=>({event:a,fn:i}))})),re().add(t)}}function Ts(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function mi(){return[...re()].filter(e=>M(e,_e)!==void 0)}function hi(e){return(M(e,Se)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var ut=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function ki(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Lt.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,fe))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,fe,{value:r,enumerable:!1}),re().add(s)}}var qt;function Kn(e){qt=e}function It(){if(!qt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return qt}var Es=720*3600;function Rs(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Es))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function _s(e){if(typeof e=="string")return e;let t=e[fe];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var vi=dt("Tasks",{async enqueue(e,t,n={}){return Rs(n),It().enqueue(_s(e),t===void 0?null:t,n)},async cancel(e,t={}){return It().cancel(e,t.machine)},async get(e,t={}){return It().get(e,t.machine)}}),zt=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function Jn(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let o=await le.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return zt(o.data,o.status===200)},async cancel(n,r){return zt((await le.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return zt((await le.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ss=1e4,Os=36e5,Fn=24*36e5,lt=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let c of this.tasks.values())if(c.task===t&&c.key===r.key&&(c.finishedAt===void 0||this.now()-c.finishedAt<Fn))return this.view(c,!0)}let o=this.now(),a=r.delay!==void 0?o+r.delay*1e3:r.runAt?Math.max(o,r.runAt.getTime()):o,i={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:a,createdAt:new Date(o)};return this.tasks.set(i.id,i),this.schedule(i),this.view(i,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),o;try{o=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(o={status:504,message:`it did not end in ${n.timeout} s`})}catch(i){o={status:500,message:i.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let a=`${o.status}${o.message?`: ${o.message}`:""}`;o.status>=200&&o.status<300?this.finish(t,"succeeded"):o.status===422?this.finish(t,"failed",`the app said it can never be done: ${a}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${a}`):(t.state="waiting",t.reason=`the app answered ${a}`,t.runAt=this.now()+Math.min(Ss*2**Math.min(t.attempt-1,16),Os),E.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,o]of this.tasks)o.finishedAt!==void 0&&this.now()-o.finishedAt>=Fn&&this.tasks.delete(s);n==="failed"&&E.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};import{markData as As}from"palgres";var Ht="/_palbase/storage/upload/authorize",Wn="/_palbase/storage/upload/complete",Bt="/_palbase/realtime/rooms";var xs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Pe(e){if(!xs(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function Vn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Zn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function ft(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var pe=Symbol.for("palbase.backend.room"),Me=Symbol.for("palbase.backend.roomHooks"),Jt=6e4,Ce=255,Ps=["roles:","flags:","messaging:","debug:"],Wt=e=>new TextEncoder().encode(e).byteLength,Qn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function";function Vt(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Wt(e)>Ce)return`a channel is ${Ce} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=Ps.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Gn(e){if(typeof e!="string"||e==="")return"is a name";if(Wt(e)>Ce)return`is ${Ce} bytes at most`}function Oi(e,t){if(typeof e!="string"||e==="")throw new TypeError('@Room(pattern, { events }): pattern is the channels it is, like "ai:{sessionId}"');let n=Vt(e);if(n)throw new TypeError(`@Room("${e}"): ${n}`);let r=t??{};if(typeof r.events!="object"||r.events===null||Array.isArray(r.events))throw new TypeError(`@Room("${e}"): events is required \u2014 what the room sends, by name, each its payload's schema ({} for none)`);for(let[a,i]of Object.entries(r.events)){let c=Gn(a);if(c)throw new TypeError(`@Room("${e}"): event "${a}" ${c}`);if(!Qn(i))throw new TypeError(`@Room("${e}"): event "${a}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Room("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);let s={...r.events},o=r.graceMs??Jt;return a=>{let i=Y(a,Me,Zt);Y(a,pe,()=>({pattern:e,events:s,graceMs:o,hooks:{...i.hooks},messages:Object.assign(Object.create(null),i.messages)})),re().add(a)}}var Zt=()=>({hooks:Object.create(null),messages:Object.create(null)});function Je(e){let t=`On${e[0].toUpperCase()}${e.slice(1)}`;return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a room's methods are its instance's`);let o=Y(n.constructor,Me,Zt),a=o.hooks[e];if(a!==void 0&&a!==r)throw new TypeError(`@${t}() is declared twice in one room (${a} and ${r}). A room has one of each hook.`);o.hooks[e]=r,re().add(n.constructor)}}var xi=Je("authorize"),Ai=Je("first"),Pi=Je("join"),Ci=Je("leave"),Mi=Je("empty");function Di(e,t){let n=Gn(e);if(n)throw new TypeError(`@OnMessage(name, schema): name ${n}`);if(!Qn(t))throw new TypeError(`@OnMessage("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return(r,s,o)=>{if(typeof s!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@OnMessage("${e}") goes on a method`);if(typeof r=="function")throw new TypeError(`@OnMessage("${e}") on static ${r.name}.${s}: a room's methods are its instance's`);let a=Y(r.constructor,Me,Zt),i=a.messages[e];if(i!==void 0&&i.fn!==s)throw new TypeError(`@OnMessage("${e}") is declared twice in one room (${i.fn} and ${s}).`);a.messages[e]={fn:s,schema:t},re().add(r.constructor)}}function Qt(e){return M(e,pe)}function Cs(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let o=0;o<n.length;o++){let a=n[o];if(a.length>=2&&a.startsWith("{")&&a.endsWith("}")){if(r[o]==="")return;s.push([a.slice(1,-1),r[o]])}else if(a!==r[o])return}return Object.fromEntries(s)}var Ms=1e4,Ds=1e3,js=100,Gt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ce=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Ns=new Set(["first","join","leave","empty"]);function Yn(e,t){let n=new Map,r=new Map;for(let{cls:h,instance:v}of e){let b=Qt(h),O=b.pattern.split(":").map(F=>F.startsWith("{")?"{}":F).join(":"),z=r.get(O);if(z!==void 0)throw new TypeError(`@Room("${b.pattern}") on ${h.name}: ${n.get(z)?.cls.name}'s "${z}" is the same channels \u2014 one room is told of them; keep one`);r.set(O,b.pattern);for(let[F,D]of[...Object.entries(b.hooks),...Object.entries(b.messages).map(([j,q])=>[`message ${j}`,q.fn])])if(typeof v[D]!="function")throw new TypeError(`@Room("${b.pattern}") on ${h.name}: its ${F} is ${D}, which is no method of it`);n.set(b.pattern,{cls:h,instance:v,room:b})}let s=new Map,o=new Set,a=new Set,i=new Kt(t.broadcast),c=h=>{let v=s.get(h);return v||(v=new AbortController,s.set(h,v)),v},p=(h,v)=>{v?.abort(),s.get(h)===v&&s.delete(h)};function y(h,v,b,O,z,F,D){let j=O?.signal??AbortSignal.abort(),q=`${h.cls.name} (${v})`;return{room:v,params:Object.freeze({...b}),signal:j,count:z,user:F,emit:(H,K)=>i.send({topic:v,event:H,payload:K??{},...D!==void 0?{conn_id:D}:{}},q),owner:{hold(H){ee.exit(async()=>{try{await H(j)}catch(K){j.aborted||E.error(`[palbase] ${q}: a task owner.hold ran failed`,{error:K})}}).catch(()=>{})},release:()=>p(v,O)}}}function k(h){let{room:v,channel:b}=h;if(typeof v!="string"||typeof b!="string")return ce(400,"bad_request","A room's call names its room (the pattern) and its channel");let O=n.get(v);return O?{entry:O,channel:b,params:Cs(v,b)}:ce(404,"not_found",`This app declares no room "${v}"`)}let R=(h,v)=>ce(400,"bad_request",`"${v}" is not a channel of the room "${h}"`);async function U(h,v){let b=k(h);if("status"in b)return b;let{entry:O,channel:z,params:F}=b,D={status:200,body:{subscribe:!1,publish:!1}};if(!F)return E.warn(`[palbase] ${O.cls.name}: realtime asked about "${z}", which is not a channel of the room "${O.room.pattern}"; the join is refused`),D;let j=Pe(h.user),q=j?.id;if(!q)return D;let H=O.room.hooks.authorize;if(!H)return D;let K,de;try{K=await t.run(j,`${O.cls.name}.${H}`,v,async()=>O.instance[H]({user:{id:q},params:Object.freeze({...F})})),de=Us(K)}catch(ne){if(t.isOutage(ne)||v?.aborted)throw ne;return E.error(`[palbase] ${O.cls.name}.${H} (@OnAuthorize of ${z}) failed; the join is refused`,{error:ne}),D}return de==="malformed"?(E.warn(`[palbase] ${O.cls.name}.${H} (@OnAuthorize of ${z}) answered ${Ls(K)}, which is no grant (true, { read, write } or null); the join is refused`),D):{status:200,body:de}}async function I(h,v){let b=k(h);if("status"in b)return b;if(!b.params)return R(b.entry.room.pattern,b.channel);let O=Pe(h.user);if(!O?.id||typeof h.event!="string")return ce(400,"bad_request","A message names its member (user) and its event");let z=Object.hasOwn(b.entry.room.messages,h.event)?b.entry.room.messages[h.event]:void 0;if(!z)return{status:200,body:{ok:!1,reason:Xn(`room "${b.channel}" declares no message "${h.event}"`,Ft)}};let F=await z.schema["~standard"].validate(As(h.payload??{}));if(F.issues)return{status:200,body:{ok:!1,reason:zs(F.issues)}};let D=c(b.channel),j={...y(b.entry,b.channel,b.params,D,0,{id:O.id}),payload:F.value};try{await t.run(O,`${b.entry.cls.name}.${z.fn}`,v,async()=>b.entry.instance[z.fn](j))}catch(q){if(t.isOutage(q))throw q;return v?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${z.fn} (@OnMessage "${h.event}" of ${b.channel}) failed`,{error:q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return{status:200,body:{ok:!0}}}async function L(h,v){let b=k(h);if("status"in b)return b;if(!b.params)return R(b.entry.room.pattern,b.channel);let O=h.event;if(typeof O!="string"||!Ns.has(O))return ce(400,"bad_request","A room's moment is first, join, leave or empty");let z=typeof h.count=="number"&&Number.isInteger(h.count)&&h.count>=0?h.count:void 0;if(z===void 0)return ce(400,"bad_request","A room's moment says its count of members");let F=O==="join"||O==="leave",D=F?Pe(h.user):void 0,j=F?h.connId:void 0;if(F&&(!D?.id||typeof j!="string"||j===""))return ce(400,"bad_request",`A ${O} names its member: user and connId`);let q=`${O}\0${b.channel}\0${typeof j=="string"?j:""}`;if(F&&o.has(q))return{status:204};if(a.has(q))return ce(503,"in_progress","This moment of the room is being handled",5);a.add(q);try{let H=b.entry.room.hooks[O],K;if(O==="empty"?(K=s.get(b.channel),p(b.channel,K)):K=O==="leave"?s.get(b.channel):c(b.channel),H){let de=y(b.entry,b.channel,b.params,K,z,{id:D?.id??""},O==="join"?j:void 0);try{await t.run(D,`${b.entry.cls.name}.${H}`,v,async()=>b.entry.instance[H](de))}catch(ne){if(t.isOutage(ne))throw ne;return v?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${H} (${O} of ${b.channel}) failed; realtime tells it again`,{error:ne}),ce(500,"handler_failed",`The room's ${O} could not be handled`)}}return F&&(o.add(q),o.size>Ms&&o.delete(o.values().next().value)),{status:204}}finally{a.delete(q)}}return{declarations:[...n.values()].map(h=>h.room),async serve(h,v,b){return Gt(v)?h==="authorize"?U(v,b):h==="message"?I(v,b):h==="lifecycle"?L(v,b):ce(404,"not_found",`No room call ${JSON.stringify(h)}`):ce(400,"bad_request","A room's call is a JSON object")},close(){for(let h of s.values())h.abort();s.clear()}}}function Us(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!Gt(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,o=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:o!==!1}}function Ls(e){return Array.isArray(e)?"an array":Gt(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var Is=20,Ft=256;function zs(e){let t="";for(let n of e.slice(0,Is)){let r=(n.path??[]).slice(0,8).map(o=>String(typeof o=="object"&&o!==null&&"key"in o?o.key:o).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Ft)break}return Xn(t,Ft)}function Xn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var Kt=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Wt(t.event)>Ce){E.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Ce} bytes`);return}try{JSON.stringify(t.payload)}catch(o){E.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:o});return}let r=this.queues.get(t.topic);if(r){r.length>=Ds?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ee.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,js);try{await this.broadcast(s)}catch(a){E.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:a})}let o=this.dropped.get(t);o&&(this.dropped.delete(t),E.warn(`[palbase] ${r}: ${o} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};var Yt=Symbol.for("palbase.backend.channels");function Ii(){return{kind:"owner"}}function zi(e={}){return{kind:"public",publish:e.publish??!1,state:e.state}}var qs=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}")).length,pt=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function qi(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("defineChannels({ pattern: entry }): an object of channel patterns");let t=[],n=[],r=new Map;for(let[i,c]of Object.entries(e)){let p=Vt(i);if(p)throw new TypeError(`defineChannels: "${i}": ${p}`);let y=r.get(pt(i));if(y!==void 0)throw new TypeError(`defineChannels: "${i}" and "${y}" are the same channels \u2014 keep one`);if(r.set(pt(i),i),typeof c!="object"||c===null)throw new TypeError(`defineChannels: "${i}": an entry is ownerOnly(), publicChannel() or { authorize }`);if("handler"in c)throw new TypeError(`defineChannels: "${i}": a handler is a room's in v3 \u2014 write @Room("${i}", { events }) with @OnAuthorize and @OnMessage, and leave it out of channels`);if("kind"in c&&c.kind==="owner"){if(qs(i)!==1)throw new TypeError(`defineChannels: ownerOnly() pattern "${i}" must carry exactly one {param} (its value is compared to the signed-in user's id)`);t.push({pattern:i,kind:"owner",publish:!1,state_read:!1,state_write:!1})}else if("kind"in c&&c.kind==="public")t.push({pattern:i,kind:"public",publish:c.publish??!1,state_read:c.state?.read??!1,state_write:c.state?.write??!1});else if("authorize"in c&&typeof c.authorize=="function")n.push({pattern:i,authorize:c.authorize});else throw new TypeError(`defineChannels: "${i}": an entry is ownerOnly(), publicChannel() or { authorize(ctx) }`)}let s={rows:t,custom:n},o=globalThis,a=o[Yt];if(a&&!Hs(a,s))throw new Error(`defineChannels: channels were already declared (${[...a.rows,...a.custom].map(i=>i.pattern).join(", ")}). A project declares its channels once \u2014 a second call would overwrite the first, and channels nobody declared are refused.`);return o[Yt]=s,s}function Hs(e,t){let n=r=>JSON.stringify([r.rows,r.custom.map(s=>[s.pattern,s.authorize.toString()])]);return n(e)===n(t)}function er(){return globalThis[Yt]??{rows:[],custom:[]}}function tr(e){let t=!1;return e.custom.map(({pattern:n,authorize:r})=>{let s={[`channel ${n}`]:class{}}[`channel ${n}`];return Y(s,pe,()=>({pattern:n,events:{},graceMs:Jt,hooks:{authorize:"authorize"},messages:Object.create(null)})),{cls:s,instance:{async authorize(a){let i=await r(a);return i==null||i.subscribe!==!0?null:(i.state&&!t&&(t=!0,E.warn(`[palbase] channel "${n}": its authorize answered state rights; a channel an authorize function decides is a room, which has none \u2014 the user hears${i.publish?" and sends":""}`)),{read:!0,write:i.publish===!0})}}}})}function nr(e,t){let n=new Map(t.map(r=>[pt(r.pattern),r.pattern]));for(let r of[...e.rows,...e.custom]){let s=n.get(pt(r.pattern));if(s!==void 0)return`channel "${r.pattern}" and @Room("${s}") are the same channels \u2014 a channel is declared in defineChannels or by a @Room, not both`}}var Bs=/^[a-z][a-z0-9-]{1,62}$/,rr=1024,Fs=new Set(["userId","uploadId","filename"]);function Ji(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Bs.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let r=Ks(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(a,i,c)=>{if(typeof i!="string"||c===void 0||typeof c.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);Y(a.constructor,Se,()=>[]).push({method:"POST",subpath:e,fn:i,options:o,upload:s})}}function Wi(){return se("uploadedObject")}function Ks(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Fs.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!sr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function sr(e){if(e===""||new TextEncoder().encode(e).byteLength>rr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Js(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ws(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ws(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function or(e,t){let n=Js(e,t);return sr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${rr} bytes)`}}function ar(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(o=>o.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(o=>o.kind==="headers"||o.kind==="req"||o.kind==="client");if(s){let o=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${o}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var Xt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ir(e,t){if(!Xt(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:o}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof o!="string"||o==="")return"uploadId is the upload's id";let a=Pe(t.user);if(!a)return"user is { id?, session?, role }";let i=Vn(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:o,user:a,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let c=Vs(t.uploadedObject);return c?c.uploadId!==o?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:o,user:a,...i?{client:i}:{},filename:"",uploadedObject:c,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Vs(e){if(!Xt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:o,checksum:a,width:i,height:c,thumbhash:p,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof a!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(i!==void 0&&typeof i!="number"||c!==void 0&&typeof c!="number"||p!==void 0&&typeof p!="string")&&!(!Xt(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:o,checksum:a,...i!==void 0?{width:i}:{},...c!==void 0?{height:c}:{},...p!==void 0?{thumbhash:p}:{},variants:{...y}}}import{createHash as en,createHmac as Zs,createPublicKey as lr,timingSafeEqual as Qs,verify as fr}from"node:crypto";function Gi(e){let t=M(e,Oe);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function pr(e,t,n,r={}){let s=new Map,o=[];for(let a of e){let i=M(a,Oe),c=s.get(i.name);if(c)throw new TypeError(`@Webhook "${i.name}" is declared by ${c.cls.name} and by ${a.name}: /webhooks/${i.name} is one endpoint`);let p=`@Webhook "${i.name}" (${a.name})`,y=n[i.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")o.push(`${p} reads its signing secret from ${i.secret.env}, which is not set`);else try{k=Gs(i,y)}catch(I){o.push(`${p}: ${i.secret.env} ${I.message}`)}let R=t(a),U=new Map(i.events.map(({event:I,fn:L})=>[I,{name:`${a.name}.${L}`,call:(h,v)=>R[L](h,v)}]));s.set(i.name,{name:i.name,cls:a,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:k,events:U})}if(o.length>0)throw new Error(`[palbase] the app cannot start:
3
3
  - ${o.join(`
4
4
  - `)}`);return s}function mr(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var De=1024,dr=1024*De;function Gs(e,t){if(e.signature)return ke(void 0,e.signature.header,1/0,co(e.signature,t));switch(e.provider){case"stripe":return ke("stripe","stripe-signature",512*De,eo(t));case"github":return ke("github","x-hub-signature-256",25*dr,to(t));case"slack":return ke("slack","x-slack-signature",64*De,no(t));case"discord":return ke("discord","x-signature-ed25519",64*De,ro(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*De),check:oo(t)};case"sendgrid":return ke("sendgrid","x-twilio-email-event-webhook-signature",dr,ao(t));case"livekit":return ke("livekit","authorization",512*De,io(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function ke(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,o)=>r(s,o)??hr(e,s)}}function hr(e,t){let n=tn(t.body),r;try{r=JSON.parse(n)}catch{if(r=n,e==="slack"){let s=new URLSearchParams(n).get("payload");if(s!==null)try{r=JSON.parse(s)}catch{}}}return{type:gr(e,t.headers,r),event:r,...Ys(e,t,r)}}function gr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=ve(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=br(n)?n.type:void 0;return r===1?"PING":r===2?"INTERACTION_CREATE":Number.isInteger(r)?`type_${String(r)}`:""}case"sendgrid":return"event_batch";case"twilio":return ve(n,"EventType");case"livekit":return ve(n,"event");default:return ve(n,"type")}}function Ys(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(ve(n,"id"));case"slack":return r(ve(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${yr(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>ve(s,"sg_event_id")||void 0)}:{};default:return{}}}var Xs=300;function eo(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,o=[];for(let c of r.split(",")){let p=c.indexOf("=");if(p<=0)continue;let y=c.slice(0,p).trim(),k=c.slice(p+1).trim();if(y==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(y==="v1"){let R=oe(k,"hex");if(!R)return"malformed_signature";o.push(R)}}let a=We(s);if(a===void 0||o.length===0)return"malformed_signature";if(Ve(a,n))return"stale_timestamp";let i=je("sha256",e,`${s}.`,t.body);return o.some(c=>ge(c,i))?void 0:"signature_mismatch"}}function to(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?oe(n.slice(7),"hex"):void 0;return r?ge(r,je("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function no(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),o=We(s),a=r.startsWith("v0=")?oe(r.slice(3),"hex"):void 0;return o===void 0||!a?"malformed_signature":Ve(o,n)?"stale_timestamp":ge(a,je("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function ro(e){let t=oe(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let n=lr({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let o=r.headers.get("x-signature-ed25519");if(!o)return"missing_signature";let a=r.headers.get("x-signature-timestamp")??void 0,i=We(a),c=oe(o,"hex");return i===void 0||!c||c.byteLength!==64?"malformed_signature":Ve(i,s)?"stale_timestamp":fr(null,wr(a,r.body),n,c)?void 0:"signature_mismatch"}}var so=1e3;function oo(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=oe(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let o=s.searchParams.get("bodySHA256"),a="",i;if(o!==null){if(!ge(Buffer.from(o.toLowerCase()),Buffer.from(en("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let U=1;for(let h of t.body)if(h===38&&++U>so)return"malformed_signature";let I=new Map;for(let[h,v]of new URLSearchParams(tn(t.body))){let b=I.get(h);b||I.set(h,b=new Set),b.add(v)}let L=[];for(let h of[...I.keys()].sort()){let v=[...I.get(h)].sort();for(let b of v)a+=h+b;L.push([h,v.length===1?v[0]:v])}i=Object.fromEntries(L)}let c=s.protocol==="https:"?"443":"80",p=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,y=`${s.protocol}//${s.hostname}:${s.port||c}${s.pathname}${s.search}`;if(![p,y].some(U=>ge(r,je("sha1",e,U,a))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),R=k?{id:`${k}:${yr(`${p}
5
5
  ${a}`)}`}:{};return i?{type:gr("twilio",t.headers,i),event:i,...R}:{...hr("twilio",t),...R}}}function ao(e){let t;try{let n=oe(e,"base64");if(!n)throw new Error;t=lr({key:Buffer.from(n),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(n,r)=>{let s=n.headers.get("x-twilio-email-event-webhook-signature");if(!s)return"missing_signature";let o=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),a=We(o),i=oe(s.trim(),"base64");return a===void 0||!i?"malformed_signature":Ve(a,r)?"stale_timestamp":fr("sha256",wr(o,n.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var cr=60;function io(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let o=ur(oe(s[0],"base64url")),a=oe(s[2],"base64url");if(o?.alg!=="HS256"||!a)return"malformed_signature";if(!ge(a,je("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let i=ur(oe(s[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(n>i.exp+cr||typeof i.nbf=="number"&&n<i.nbf-cr)return"stale_timestamp";let c=typeof i.sha256=="string"?oe(i.sha256,"base64"):void 0;return c&&ge(c,en("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function co(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,o)=>{let a=s.headers.get(e.header);if(!a)return"missing_signature";if(e.prefix){if(!a.startsWith(e.prefix))return"malformed_signature";a=a.slice(e.prefix.length)}let i="";if(n.includes("{ts}")){i=s.headers.get(e.timestampHeader)?.trim()??"";let p=We(i);if(p===void 0)return"malformed_signature";if(Ve(p,o))return"stale_timestamp"}let c=oe(a.trim(),e.encoding);return c?ge(c,je(r,t,...n.map(p=>p==="{body}"?s.body:p==="{ts}"?i:p)))?void 0:"signature_mismatch":"malformed_signature"}}var uo=new TextEncoder;function je(e,t,...n){let r=Zs(e,t);for(let s of n)r.update(s);return r.digest()}function yr(e){return en("sha256").update(e).digest("hex")}function wr(e,t){return Buffer.concat([uo.encode(e),t])}function ge(e,t){return e.byteLength===t.byteLength&&Qs(e,t)}var lo={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function oe(e,t){return lo[t].test(e)?Buffer.from(e,t):void 0}function We(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function Ve(e,t){return Math.abs(t-e)>Xs}function tn(e){return new TextDecoder().decode(e)}function ur(e){if(e)try{return JSON.parse(tn(e))}catch{return}}function br(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ve(e,t){let n=br(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var J=class extends Error{kind;path;constructor(t,n,r,s,o){super(`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.5.2 — Palbase SDK License (see LICENSE) */
2
- import{a as k,b as S}from"./TPBWIRHS.js";var T=class extends Error{status;error;data;body;constructor(t,a,l,d){let u=d!==null&&typeof d=="object"?d:{},i=u.error??String(l);super(`${t} ${a} \u2192 ${l} ${i}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=i,this.data=u.data,this.body=u}};function I(n,t){if(!n)throw new Error(`${t} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function R(n){let t=n.split(".")[1];if(!t)return null;try{let a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function x(n){try{return JSON.parse(n)}catch{return n}}function L(n){let t=I(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??t).replace(/\/+$/,""),d=n.fetch??fetch,u=[],i=null;async function c(r,e,s,o,f={},_=!0){let g={...f.headers},m=h=>Object.keys(g).some(O=>O.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),i&&_&&!m("authorization")&&(g.authorization=`Bearer ${i}`),o!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let P=Date.now(),p=await d(`${r}${s}`,{method:e,headers:g,body:o===void 0?void 0:JSON.stringify(o)}),E=await p.text(),A=E?x(E):void 0;if(u.push({method:e,path:s,status:p.status,ms:Date.now()-P}),!p.ok){let h=p.status===401&&i?R(i):null;throw h!==null&&h<=0?new T(e,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new T(e,s,p.status,A)}return A}let y={requests:u,get:(r,e)=>c(t,"GET",r,void 0,e),post:(r,e,s)=>c(t,"POST",r,e,s),patch:(r,e,s)=>c(t,"PATCH",r,e,s),put:(r,e,s)=>c(t,"PUT",r,e,s),delete:(r,e)=>c(t,"DELETE",r,void 0,e),query:(r,e,s)=>c(t,"QUERY",r,e,s),async signInAs(r){let e=n.identities?.[r];if(!e){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return e.accessToken?(i=e.accessToken,{id:e.id??"",email:e.email}):y.signIn(e)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let e=o=>c(l,"POST","/auth/login",r,o?{headers:o}:{},!1),s;try{s=await e()}catch(o){let f=o instanceof T&&o.status===403?k(o.body):null;if(!f)throw o;s=await e(await S(f))}return i=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),i=null},asAnonymous(){i=null}};return y}function b(n){if(!n)return{};let t;try{t=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return t}var $={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(b(process.env.PALBASE_TEST_IDENTITIES),n)}},w,U=new Proxy({},{get(n,t){return w??=L({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:b(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,t,w)}});export{T as a,L as b,$ as c,U as d};
1
+ /*! palbase 0.6.2 — Palbase SDK License (see LICENSE) */
2
+ import{a as k,b as S}from"./KLANM6M6.js";var T=class extends Error{status;error;data;body;constructor(t,a,l,d){let u=d!==null&&typeof d=="object"?d:{},i=u.error??String(l);super(`${t} ${a} \u2192 ${l} ${i}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=i,this.data=u.data,this.body=u}};function I(n,t){if(!n)throw new Error(`${t} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function R(n){let t=n.split(".")[1];if(!t)return null;try{let a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function x(n){try{return JSON.parse(n)}catch{return n}}function L(n){let t=I(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??t).replace(/\/+$/,""),d=n.fetch??fetch,u=[],i=null;async function c(r,e,s,o,f={},_=!0){let g={...f.headers},m=h=>Object.keys(g).some(O=>O.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),i&&_&&!m("authorization")&&(g.authorization=`Bearer ${i}`),o!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let P=Date.now(),p=await d(`${r}${s}`,{method:e,headers:g,body:o===void 0?void 0:JSON.stringify(o)}),E=await p.text(),A=E?x(E):void 0;if(u.push({method:e,path:s,status:p.status,ms:Date.now()-P}),!p.ok){let h=p.status===401&&i?R(i):null;throw h!==null&&h<=0?new T(e,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new T(e,s,p.status,A)}return A}let y={requests:u,get:(r,e)=>c(t,"GET",r,void 0,e),post:(r,e,s)=>c(t,"POST",r,e,s),patch:(r,e,s)=>c(t,"PATCH",r,e,s),put:(r,e,s)=>c(t,"PUT",r,e,s),delete:(r,e)=>c(t,"DELETE",r,void 0,e),query:(r,e,s)=>c(t,"QUERY",r,e,s),async signInAs(r){let e=n.identities?.[r];if(!e){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return e.accessToken?(i=e.accessToken,{id:e.id??"",email:e.email}):y.signIn(e)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let e=o=>c(l,"POST","/auth/login",r,o?{headers:o}:{},!1),s;try{s=await e()}catch(o){let f=o instanceof T&&o.status===403?k(o.body):null;if(!f)throw o;s=await e(await S(f))}return i=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),i=null},asAnonymous(){i=null}};return y}function b(n){if(!n)return{};let t;try{t=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return t}var $={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(b(process.env.PALBASE_TEST_IDENTITIES),n)}},w,U=new Proxy({},{get(n,t){return w??=L({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:b(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,t,w)}});export{T as a,L as b,$ as c,U as d};