palbase 0.40.2 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) 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 +3 -3
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{RCUVA3QW.js → 2YSSZFTA.js} +1 -1
  8. package/dist/chunks/{4ZMAF4YF.js → 44P5SNHL.js} +2 -2
  9. package/dist/chunks/{CHQGN5YD.js → 45OZMCTY.js} +2 -2
  10. package/dist/chunks/{KR3XSIAZ.js → 4CCH7DIT.js} +2 -2
  11. package/dist/chunks/{7QY7ZMHT.js → 4J5ENCJ7.js} +2 -2
  12. package/dist/chunks/{4ONQGDDE.js → 4Y6CJKXK.js} +1 -1
  13. package/dist/chunks/{HDBPJPTI.js → 6KKJ6RVV.js} +2 -2
  14. package/dist/chunks/{EJR46234.js → AJKLKBCU.js} +2 -2
  15. package/dist/chunks/{ZTGSTF3B.js → B5MHKAMX.js} +1 -1
  16. package/dist/chunks/{LVX42GRN.js → E267BI6B.js} +2 -2
  17. package/dist/chunks/{HEHSHDUM.js → GUS7UMLA.js} +2 -2
  18. package/dist/chunks/{D4KYGGQC.js → H3RARUDI.js} +2 -2
  19. package/dist/chunks/{5QE5KFNR.js → HR6L4MUD.js} +2 -2
  20. package/dist/chunks/{Z5QBR46U.js → ITREUT6F.js} +1 -1
  21. package/dist/chunks/{DFVKNPW7.js → L6ZYGBVU.js} +2 -2
  22. package/dist/chunks/{37C5IJBG.js → OCFHMHBP.js} +2 -2
  23. package/dist/chunks/{DN2MAZHA.js → OVXIALPD.js} +2 -2
  24. package/dist/chunks/{Q4VZ2BNE.js → QWFHHS3E.js} +1 -1
  25. package/dist/chunks/{Z7RZBBBS.js → VXPH5UY7.js} +2 -2
  26. package/dist/chunks/{WH3G2H3E.js → WFGAHBSJ.js} +1 -1
  27. package/dist/chunks/{FDAOVX6B.js → XHIEWIHW.js} +1 -1
  28. package/dist/chunks/{OHNIWLO3.js → ZJUVHFOW.js} +2 -2
  29. package/dist/chunks/{LO6DFZ7L.js → ZZ5WS5AO.js} +2 -2
  30. package/dist/cli.js +139 -139
  31. package/dist/cloud/index.js +2 -2
  32. package/dist/refuse/ai.js +1 -1
  33. package/dist/refuse/backend.js +1 -1
  34. package/dist/refuse/cloud.js +1 -1
  35. package/dist/refuse/server.js +1 -1
  36. package/dist/server/index.js +2 -2
  37. package/dist/server/testing.js +2 -2
  38. package/dist/web/index.js +2 -2
  39. package/dist/web/message.js +2 -2
  40. package/dist/web/palbe.js +2 -2
  41. package/dist/web/paywall.js +2 -2
  42. package/dist/web/push-sw.js +1 -1
  43. package/dist/web/ssr.js +2 -2
  44. package/dist/web/vite.js +2 -2
  45. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{f as m}from"./OHNIWLO3.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(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 P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=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 l(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=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
1
+ /*! palbase 0.41.0 — Palbase SDK License (see LICENSE) */
2
+ import{f as m}from"./ZJUVHFOW.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(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 P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=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 l(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=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
3
3
  `):process.stdout.write(`${o}
4
4
  `)}function k(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 v=h("Log",{debug:(n,e)=>l("debug",n,e),info:(n,e)=>l("info",n,e),warn:(n,e)=>l("warn",n,e),error:(n,e)=>l("error",n,e)});var L=512,_=8,q=64,D=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/,S={"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 $(n){let e=n.indexOf("-");return e>0?n.slice(0,e):n}function j(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 I(n){let e=n.trim().replaceAll("_","-");if(e===""||e==="*"||e.length>q)return;let s=e.toLowerCase(),t=Object.hasOwn(S,s)?S[s]:void 0;if(t===void 0){try{t=Intl.getCanonicalLocales(j(e))[0]}catch{return}if(t===void 0)return}let i=$(t);if(!(i===""||i==="und"||i==="mul"))return t}function z(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 Y(n,e){let s=[],t=i=>{i!==""&&!s.includes(i)&&s.push(i)};if(n!==null&&n.length<=L){let i=[];for(let o of n.split(",")){let r=o.trim();if(r==="")continue;let a=1,f=r.indexOf(";");if(f>=0){let A=r.slice(f+1);r=r.slice(0,f).trim();for(let p of A.split(";")){let b=p.indexOf("=");if(b<0||p.slice(0,b).trim().toLowerCase()!=="q")continue;let y=p.slice(b+1).trim(),g=D.test(y)?Number(y):Number.NaN;a=Number.isFinite(g)&&g>=0&&g<=1?g: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,_)){let r=I(o);if(r!==void 0)for(let a of z(r))t(a)}}return e!==void 0&&e!==""&&t(e),s}function N(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 C=/\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;function x(n,e){return n.replace(C,(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 W(n){u=n===void 0?void 0:{root:n,said:!1}}function Q(n,e){let s=c.getStore(),t=s?.strings;if(t===void 0)return u&&!u.said&&s?.services===void 0&&(u.said=!0,v.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`)),x(n,e);let{text:i,locale:o}=N(t,n,s?.locales??[t.source]),r=s?.usedLocales;return r!==void 0&&!r.includes(o)&&r.push(o),x(i,e)}export{h as a,R as b,c,H as d,F as e,Z as f,B as g,v as h,Y as i,W as j,Q as k};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{a as g,b}from"./Q4VZ2BNE.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=E(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=v(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await $(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status]??(r.ownResponse&&i.status>=200&&i.status<300?"raw":void 0);if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await O(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function $(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:U(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function U(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function E(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function v(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+P(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(e.secretKey??e.token);case"PalbaseBearer":return!!e.token;case"userJWT":return!!a&&!e.token;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):(o==="SecretKeyAuth"||o==="AdminAuth"||o==="PalbaseBearer")&&e.token?n.set("authorization",`Bearer ${e.token}`):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function P(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function O(t,e){let n=await B(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=_(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function B(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function _(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,E as e,R as f};
1
+ /*! palbase 0.41.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as g,b}from"./QWFHHS3E.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=E(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=v(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await $(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status]??(r.ownResponse&&i.status>=200&&i.status<300?"raw":void 0);if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await O(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function $(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:U(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function U(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function E(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function v(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+P(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!(e.secretKey??e.token);case"PalbaseBearer":return!!e.token;case"userJWT":return!!a&&!e.token;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):(o==="SecretKeyAuth"||o==="AdminAuth"||o==="PalbaseBearer")&&e.token?n.set("authorization",`Bearer ${e.token}`):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function P(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function O(t,e){let n=await B(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=_(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function B(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function _(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,E as e,R as f};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.41.0 — Palbase SDK License (see LICENSE) */
2
2
  var s=class extends Error{code;constructor(t,e){super(e),this.name="FieldError",this.code=t}},f="pbe1.",g="pbl1.",k=6e4,p="[A-Za-z_][A-Za-z0-9_$]{0,62}",w=new RegExp(`^${p}\\.${p}(\\.${p})?$`);function v(o){return w.test(o)}var h=class{crypto;keys=new Map;lookupKey;timer;opts;now;constructor(t){this.opts=t,this.now=t.now??Date.now}get loaded(){return this.lookupKey!==void 0}async load(t){this.crypto??=await import("node:crypto"),this.take(await this.opts.fetch(t)),this.timer===void 0&&(this.timer=setInterval(()=>{this.opts.fetch().then(e=>this.take(e),()=>{})},k),this.timer.unref?.())}close(){clearInterval(this.timer),this.timer=void 0}take(t){let e=new Map;for(let r of t.keys)e.set(r.id,{id:r.id,key:Buffer.from(r.key,"base64url"),activatesAt:Date.parse(r.activates_at)});this.keys=e,this.lookupKey=Buffer.from(t.lookup,"base64url")}ready(){if(this.crypto===void 0||this.lookupKey===void 0)throw new s("not_loaded","the project's field keys are not loaded: await palbase.fields.load() at startup");return this.crypto}currentKey(){this.ready();let t;for(let e of this.keys.values())e.activatesAt<=this.now()&&(t===void 0||e.activatesAt>=t.activatesAt)&&(t=e);if(t===void 0)throw new s("unknown_key","the project has no field key in force");return t.id}encrypt(t,e){let r=this.ready();l(t);let n=this.currentKey(),i=r.randomBytes(12);return b(r,this.keys.get(n).key,i,n,t,e)}decrypt(t,e){let r=this.ready();if(l(t),!e.startsWith(f))throw new s("not_encrypted",`${t} holds a value that is not encrypted`);let n=e.slice(f.length),i=n.indexOf("."),a=i<0?n:n.slice(0,i),u=this.keys.get(a);if(u===void 0)throw new s("unknown_key",`${t} was sealed with field key ${a}, which this project does not hold`);let c=Buffer.from(n.slice(i+1),"base64url");if(i<0||c.length<28||c.toString("base64url")!==n.slice(i+1))throw new s("unopenable",`${t} holds a value that does not open here`);try{let d=r.createDecipheriv("aes-256-gcm",u.key,c.subarray(0,12));return d.setAAD(y(t)),d.setAuthTag(c.subarray(c.length-16)),Buffer.concat([d.update(c.subarray(12,c.length-16)),d.final()]).toString("utf8")}catch{throw new s("unopenable",`${t} holds a value that does not open here: tampered, or another column's`)}}isEncrypted(t){return t.startsWith(f)}lookup(t,e){let r=this.ready();return l(t),m(r,this.lookupKey,t,e)}};function l(o){if(!v(o))throw new TypeError(`a field's address is table.column, or schema.table.column, not ${JSON.stringify(o)}`)}function y(o){return Buffer.from(`pbe1\0${o}`,"utf8")}function b(o,t,e,r,n,i){let a=o.createCipheriv("aes-256-gcm",t,e);a.setAAD(y(n));let u=Buffer.concat([e,a.update(i,"utf8"),a.final(),a.getAuthTag()]);return`${f}${r}.${u.toString("base64url")}`}function m(o,t,e,r){let n=o.createHmac("sha256",t);return n.update(`pbl1\0${e}\0`,"utf8"),n.update(r,"utf8"),`${g}${n.digest("base64url")}`}export{s as a,h as b};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{b as M,c as N,d as T}from"./LO6DFZ7L.js";import{a as z,f as Q,g as Y,j as Z,k as X,l as ee,o as G,p as te,q as ne}from"./4ONQGDDE.js";import{d as A}from"./HEHSHDUM.js";import{a as b,b as V,c as _,e as j}from"./5QE5KFNR.js";var l=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function oe(t){return t instanceof l||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function q(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??qe(e,"request_id"),data:E(e,"data"),cause:t};if(t.code==="network_error")return new l("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new l("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new l("attestationRequired",n);if(t.status===401)return new l("unauthorized",n);if(t.status===429)return new l("rateLimited",{...n,retryAfter:Ne(e)??t.retryAfter});let s=Me(e);return t.status===400&&s?new l("validation",{...n,fields:s}):new l("server",n)}function R(t){return t instanceof V||t instanceof Error&&t.name==="PalbaseError"}function se(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Me(t){let e=E(E(t,"data"),"fields");if(se(e))return e;let n=E(t,"fields");return se(n)?n:void 0}function Ne(t){return re(t,"retry_after")??re(E(t,"data"),"retryAfter")}function E(t,e){if(typeof t=="object"&&t!==null)return t[e]}function re(t,e){let n=E(t,e);return typeof n=="number"?n:void 0}function qe(t,e){let n=E(t,e);return typeof n=="string"?n:void 0}var De=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ke=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Be=new Set(Ke),Le=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function P(t){return t==="then"||t==="toJSON"||Le.has(t)}function ae(t){return t==="call"||t==="join"||P(t)}function ie(t){return typeof t=="string"&&De.test(t)&&!Be.has(t)&&!P(t)}function de(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function le(t){j(t)}function ce(t){return j(t).origin}var I=class{me;reader;messages=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;taken=[];older=[];oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;told=!1;ended=!1;constructor(e=()=>{},n,s){this.me=e,this.reader=n,this.chatId=s}get hasOlder(){return this.olderLeft}loadOlder(e={}){return this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading}async readOlder(e){if(!this.olderLeft)return!1;let s={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.signal?{signal:e.signal}:{}},r;if(e.load)r=await e.load(s);else{let a=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");r=await this.reader.parts(a,s)}if(this.ended)return!1;let o=(r?.parts??[]).map(a=>M(a)).filter(a=>a!==void 0);return this.older=[...o,...this.older],this.olderCursor=r?.nextCursor,this.olderLeft=typeof r?.nextCursor=="string"&&r.nextCursor!=="",this.refold(),this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}refold(){this.messages.clear(),this.responses.clear(),this.order.length=0,this.turn=null,this.goal=null,this.goalWords.clear(),this.voiceWords.clear(),this.voice=null,this.history.clear(),this.forkedFrom=null,this.calls.clear();for(let e of this.older)this.fold(e);for(let e of this.taken)this.fold(e);this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(a=>e=a)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0;for(let e of[...this.enders])e()}}takePayload(e){let n=M(e);n&&this.take(n)}take(e){if(this.ended)return;this.taken.push(e);let n=e.seq;typeof n=="number"&&n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.fold(e)&&this.changed()}fold(e){switch(e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(n.thought.has(e.seq))return!1;n.thought.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:N(n.text),thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:N(n.text),thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e});break;case"voice":{let n=`${e.voice_id}\0${e.status}`;if(this.voiceWords.has(n))return!1;this.voiceWords.add(n),(e.status==="closed"?this.voice===null||this.voice.voice_id===e.voice_id:!this.voiceWords.has(`${e.voice_id}\0closed`))&&(this.voice=e),this.order.push({type:"voice",event:e});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,e.offset))+e.text;break}case"reset":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,e.offset));break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let n=this.response(e.response_id);if(n.runId=e.run_id,n.agent=e.name,n.parentId===null){n.parentId=e.parent_response_id;let s=this.order.findIndex(r=>r.type==="response"&&r.key===e.response_id);s>=0&&this.order.splice(s,1)}break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let n=Fe(e),s=this.messages.get(n),r=e.status==="delivered"||e.status==="failed"?e.status:"pending";this.messages.set(n,{clientId:e.client_id,id:e.id??s?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:s?.status==="delivered"?"delivered":r,error:e.error??null,responseId:e.response_id??s?.responseId??null,createdAt:e.created_at??s?.createdAt??"",mine:!1,metadata:e.metadata??s?.metadata??{},history:!1,truncated:!1,kind:e.kind??s?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:s?.voice??null,attachments:e.attachments?ue(e.attachments):s?.attachments??[]}),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n}),this.changed()}place(e,n){let s=e.response_id??null,o=s!==null&&![...this.messages.entries()].some(([a,i])=>a!==n&&i.responseId===s)?this.order.findIndex(a=>a.type==="response"&&a.key===s):-1;o>=0?this.order.splice(o,0,{type:"message",key:n}):this.order.push({type:"message",key:n})}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",marks:new Map,thought:new Set,runId:null,agent:null,parentId:null,startedBy:void 0,goal:null},this.responses.set(e,n),this.order.push({type:"response",key:e})),n}changed(){this.snapshot=void 0,!this.told&&(this.told=!0,queueMicrotask(()=>{this.told=!1;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=d=>e!==void 0&&d.startedBy===e,s=new Map;for(let d of this.responses.values()){let u=d.parentId!==null?this.responses.get(d.parentId)??d:d;s.set(d.id,We(d,u.startedBy??null,n(u),d.goal??u.goal))}let r=new Map([...this.messages].map(([d,u])=>[d,e!==void 0&&u.author===e?{...u,mine:!0}:u])),o=[...this.history.entries()].sort(([d],[u])=>d-u).flatMap(([d,u])=>u.map((f,m)=>He(f,`${d}:${m}`,e))),a=[...o];for(let d of this.order)d.type==="goal"?a.push({type:"goal",goal:d.event}):d.type==="voice"?a.push({type:"voice",voice:d.event}):d.type==="message"?a.push({type:"message",message:r.get(d.key)}):this.responses.get(d.key).parentId===null&&a.push({type:"response",response:s.get(d.key)});let i=o.flatMap(d=>d.type==="message"?[d.message]:[]),c=o.flatMap(d=>d.type==="response"?[d.response]:[]),p=[...this.calls.values()].filter(d=>s.get(d.response_id)?.mine===!0);return{items:a,messages:[...i,...r.values()],responses:[...c,...s.values()],turn:this.turn,waiting:{approvals:p.filter(d=>d.status==="awaiting_approval"),outputs:p.filter(d=>d.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Je(this.voice,e):null}}};function Je(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function ue(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Fe(t){return`${t.author??""}\0${t.client_id}`}function We(t,e,n,s){let r=[...t.marks.values()].map((c,p)=>({m:c,i:p,at:T(t.text,Math.max(0,Number(c.text_offset)||0))}));r.sort((c,p)=>c.at-p.at||c.i-p.i);let o=[],a=[],i=0;for(let{m:c,at:p}of r)p>i&&o.push({type:"text",text:t.text.slice(i,p)}),i=Math.max(i,p),c.type==="thinking"?(o.push({type:"thinking",thinking:c.thinking}),a.push(c.thinking)):o.push(c.type==="tool"?{type:"tool",tool:c}:{type:"agent",agent:c});return i<t.text.length&&o.push({type:"text",text:t.text.slice(i)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:o,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:a,goal:s,history:!1,truncated:!1}}function He(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:ue(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var D=[["ApiKeyAuth","userJWT"]];function pe(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:D,answers:{200:"json"},query:s,signal:n.signal})).data;return r.next_cursor===void 0?{parts:r.parts}:{parts:r.parts,nextCursor:r.next_cursor}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:D,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:D,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var $=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},he=new WeakMap;async function fe(t,e,n,s={},r=()=>{},o){let{pattern:a,events:i,messages:c,durable:p,chat:d}=Ue(e),u=Ve(a,n),f=he.get(t);f||he.set(t,f=new Map);let m=f,g=m.get(u)??{count:0};m.set(u,g),g.count++;let y=t.channel(u,p&&s.history!==!1?{after:0}:{});if(d&&!g.chat){let h=n.chatId,k=new I(r,o,typeof h=="string"&&h!==""?h:void 0);g.chat=k,g.unchat=y.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let x=()=>{--g.count>0||(m.delete(u),g.unchat?.(),g.chat?.end(),y.leave())};try{await y.join()}catch{let h=y.state==="refused"?ge(y.refusal,"unavailable"):"socket closed";throw x(),new $(`gateway ${JSON.stringify(u)} was not joined: ${h}`,h)}let C=!1,S=new Set,W=()=>{if(!C){C=!0,Ge();for(let h of[...S])h();x()}},Ge=y.onClosed(W),H=h=>{if(C)return()=>{};let k=y.on("broadcast",v=>{typeof v.event=="string"&&i.has(v.event)&&h(v.event,b(v.payload))}),w=()=>{S.delete(w),k()};return S.add(w),w},U={topic:u,get seq(){return y.logSeq},on(h,k){if(typeof h=="function")return H((w,v)=>h({event:w,payload:v}));if(!i.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no event ${JSON.stringify(String(h))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(a)}: on(${JSON.stringify(h)}, \u2026) takes the function the event is handed to`);return H((w,v)=>{w===h&&k(v)})},off(h){S.has(h)&&h()},async send(h,k){if(!c.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no message ${JSON.stringify(String(h))}`);let w=C?{status:"error",response:{reason:"not joined"}}:await y.push("broadcast",{type:"broadcast",event:h,payload:k});if(w.status==="ok")return b(w.response.reply);let v=ge(w.response,"unavailable");throw new $(`gateway ${JSON.stringify(u)} did not take ${JSON.stringify(h)}: ${v}`,v)},leave:W};return d&&Object.defineProperty(U,"chat",{value:g.chat,enumerable:!0}),U}function Ue(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function Ve(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(n,r)?n[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function ge(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ze=3600*1e3,O=new Map;function Qe(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=O.get(s);if(!n&&r&&Date.now()-r.at<ze)return r.list;let o=(async()=>{let a=te(),i;try{i=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:a},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(c){throw new l("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:c})}try{return await ne(i,e.signer,e.projectId,a)}catch(c){throw new l("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:c})}})();return O.set(s,{list:o,at:Date.now()}),o.catch(()=>{O.get(s)?.list===o&&O.delete(s)}),o}async function ye(t,e,n,s,r,o){let i=(await Qe(t,e,o)).keys[0];return Y(i.kid,i.key,Q(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,n,s,(r,o)=>Z(t.key,r,o))}function me(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):G(e,"/response",n,async(r,o)=>{if(!X(o))throw new l("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ee(t.key,r,o)}catch(a){throw new l("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:a})}})}function we(t){return t instanceof l&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
1
+ /*! palbase 0.41.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as M,c as N,d as T}from"./ZZ5WS5AO.js";import{a as z,f as Q,g as Y,j as Z,k as X,l as ee,o as G,p as te,q as ne}from"./4Y6CJKXK.js";import{d as A}from"./GUS7UMLA.js";import{a as b,b as V,c as _,e as j}from"./HR6L4MUD.js";var l=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function oe(t){return t instanceof l||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function q(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??qe(e,"request_id"),data:E(e,"data"),cause:t};if(t.code==="network_error")return new l("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new l("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new l("attestationRequired",n);if(t.status===401)return new l("unauthorized",n);if(t.status===429)return new l("rateLimited",{...n,retryAfter:Ne(e)??t.retryAfter});let s=Me(e);return t.status===400&&s?new l("validation",{...n,fields:s}):new l("server",n)}function R(t){return t instanceof V||t instanceof Error&&t.name==="PalbaseError"}function se(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Me(t){let e=E(E(t,"data"),"fields");if(se(e))return e;let n=E(t,"fields");return se(n)?n:void 0}function Ne(t){return re(t,"retry_after")??re(E(t,"data"),"retryAfter")}function E(t,e){if(typeof t=="object"&&t!==null)return t[e]}function re(t,e){let n=E(t,e);return typeof n=="number"?n:void 0}function qe(t,e){let n=E(t,e);return typeof n=="string"?n:void 0}var De=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ke=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Be=new Set(Ke),Le=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function P(t){return t==="then"||t==="toJSON"||Le.has(t)}function ae(t){return t==="call"||t==="join"||P(t)}function ie(t){return typeof t=="string"&&De.test(t)&&!Be.has(t)&&!P(t)}function de(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function le(t){j(t)}function ce(t){return j(t).origin}var I=class{me;reader;messages=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;taken=[];older=[];oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;told=!1;ended=!1;constructor(e=()=>{},n,s){this.me=e,this.reader=n,this.chatId=s}get hasOlder(){return this.olderLeft}loadOlder(e={}){return this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading}async readOlder(e){if(!this.olderLeft)return!1;let s={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.signal?{signal:e.signal}:{}},r;if(e.load)r=await e.load(s);else{let a=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");r=await this.reader.parts(a,s)}if(this.ended)return!1;let o=(r?.parts??[]).map(a=>M(a)).filter(a=>a!==void 0);return this.older=[...o,...this.older],this.olderCursor=r?.nextCursor,this.olderLeft=typeof r?.nextCursor=="string"&&r.nextCursor!=="",this.refold(),this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}refold(){this.messages.clear(),this.responses.clear(),this.order.length=0,this.turn=null,this.goal=null,this.goalWords.clear(),this.voiceWords.clear(),this.voice=null,this.history.clear(),this.forkedFrom=null,this.calls.clear();for(let e of this.older)this.fold(e);for(let e of this.taken)this.fold(e);this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(a=>e=a)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0;for(let e of[...this.enders])e()}}takePayload(e){let n=M(e);n&&this.take(n)}take(e){if(this.ended)return;this.taken.push(e);let n=e.seq;typeof n=="number"&&n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.fold(e)&&this.changed()}fold(e){switch(e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(n.thought.has(e.seq))return!1;n.thought.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:N(n.text),thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:N(n.text),thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e});break;case"voice":{let n=`${e.voice_id}\0${e.status}`;if(this.voiceWords.has(n))return!1;this.voiceWords.add(n),(e.status==="closed"?this.voice===null||this.voice.voice_id===e.voice_id:!this.voiceWords.has(`${e.voice_id}\0closed`))&&(this.voice=e),this.order.push({type:"voice",event:e});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,e.offset))+e.text;break}case"reset":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,e.offset));break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let n=this.response(e.response_id);if(n.runId=e.run_id,n.agent=e.name,n.parentId===null){n.parentId=e.parent_response_id;let s=this.order.findIndex(r=>r.type==="response"&&r.key===e.response_id);s>=0&&this.order.splice(s,1)}break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let n=Fe(e),s=this.messages.get(n),r=e.status==="delivered"||e.status==="failed"?e.status:"pending";this.messages.set(n,{clientId:e.client_id,id:e.id??s?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:s?.status==="delivered"?"delivered":r,error:e.error??null,responseId:e.response_id??s?.responseId??null,createdAt:e.created_at??s?.createdAt??"",mine:!1,metadata:e.metadata??s?.metadata??{},history:!1,truncated:!1,kind:e.kind??s?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:s?.voice??null,attachments:e.attachments?ue(e.attachments):s?.attachments??[]}),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n}),this.changed()}place(e,n){let s=e.response_id??null,o=s!==null&&![...this.messages.entries()].some(([a,i])=>a!==n&&i.responseId===s)?this.order.findIndex(a=>a.type==="response"&&a.key===s):-1;o>=0?this.order.splice(o,0,{type:"message",key:n}):this.order.push({type:"message",key:n})}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",marks:new Map,thought:new Set,runId:null,agent:null,parentId:null,startedBy:void 0,goal:null},this.responses.set(e,n),this.order.push({type:"response",key:e})),n}changed(){this.snapshot=void 0,!this.told&&(this.told=!0,queueMicrotask(()=>{this.told=!1;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=d=>e!==void 0&&d.startedBy===e,s=new Map;for(let d of this.responses.values()){let u=d.parentId!==null?this.responses.get(d.parentId)??d:d;s.set(d.id,We(d,u.startedBy??null,n(u),d.goal??u.goal))}let r=new Map([...this.messages].map(([d,u])=>[d,e!==void 0&&u.author===e?{...u,mine:!0}:u])),o=[...this.history.entries()].sort(([d],[u])=>d-u).flatMap(([d,u])=>u.map((f,m)=>He(f,`${d}:${m}`,e))),a=[...o];for(let d of this.order)d.type==="goal"?a.push({type:"goal",goal:d.event}):d.type==="voice"?a.push({type:"voice",voice:d.event}):d.type==="message"?a.push({type:"message",message:r.get(d.key)}):this.responses.get(d.key).parentId===null&&a.push({type:"response",response:s.get(d.key)});let i=o.flatMap(d=>d.type==="message"?[d.message]:[]),c=o.flatMap(d=>d.type==="response"?[d.response]:[]),p=[...this.calls.values()].filter(d=>s.get(d.response_id)?.mine===!0);return{items:a,messages:[...i,...r.values()],responses:[...c,...s.values()],turn:this.turn,waiting:{approvals:p.filter(d=>d.status==="awaiting_approval"),outputs:p.filter(d=>d.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Je(this.voice,e):null}}};function Je(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function ue(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Fe(t){return`${t.author??""}\0${t.client_id}`}function We(t,e,n,s){let r=[...t.marks.values()].map((c,p)=>({m:c,i:p,at:T(t.text,Math.max(0,Number(c.text_offset)||0))}));r.sort((c,p)=>c.at-p.at||c.i-p.i);let o=[],a=[],i=0;for(let{m:c,at:p}of r)p>i&&o.push({type:"text",text:t.text.slice(i,p)}),i=Math.max(i,p),c.type==="thinking"?(o.push({type:"thinking",thinking:c.thinking}),a.push(c.thinking)):o.push(c.type==="tool"?{type:"tool",tool:c}:{type:"agent",agent:c});return i<t.text.length&&o.push({type:"text",text:t.text.slice(i)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:o,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:a,goal:s,history:!1,truncated:!1}}function He(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:ue(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var D=[["ApiKeyAuth","userJWT"]];function pe(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:D,answers:{200:"json"},query:s,signal:n.signal})).data;return r.next_cursor===void 0?{parts:r.parts}:{parts:r.parts,nextCursor:r.next_cursor}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:D,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:D,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var $=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},he=new WeakMap;async function fe(t,e,n,s={},r=()=>{},o){let{pattern:a,events:i,messages:c,durable:p,chat:d}=Ue(e),u=Ve(a,n),f=he.get(t);f||he.set(t,f=new Map);let m=f,g=m.get(u)??{count:0};m.set(u,g),g.count++;let y=t.channel(u,p&&s.history!==!1?{after:0}:{});if(d&&!g.chat){let h=n.chatId,k=new I(r,o,typeof h=="string"&&h!==""?h:void 0);g.chat=k,g.unchat=y.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let x=()=>{--g.count>0||(m.delete(u),g.unchat?.(),g.chat?.end(),y.leave())};try{await y.join()}catch{let h=y.state==="refused"?ge(y.refusal,"unavailable"):"socket closed";throw x(),new $(`gateway ${JSON.stringify(u)} was not joined: ${h}`,h)}let C=!1,S=new Set,W=()=>{if(!C){C=!0,Ge();for(let h of[...S])h();x()}},Ge=y.onClosed(W),H=h=>{if(C)return()=>{};let k=y.on("broadcast",v=>{typeof v.event=="string"&&i.has(v.event)&&h(v.event,b(v.payload))}),w=()=>{S.delete(w),k()};return S.add(w),w},U={topic:u,get seq(){return y.logSeq},on(h,k){if(typeof h=="function")return H((w,v)=>h({event:w,payload:v}));if(!i.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no event ${JSON.stringify(String(h))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(a)}: on(${JSON.stringify(h)}, \u2026) takes the function the event is handed to`);return H((w,v)=>{w===h&&k(v)})},off(h){S.has(h)&&h()},async send(h,k){if(!c.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no message ${JSON.stringify(String(h))}`);let w=C?{status:"error",response:{reason:"not joined"}}:await y.push("broadcast",{type:"broadcast",event:h,payload:k});if(w.status==="ok")return b(w.response.reply);let v=ge(w.response,"unavailable");throw new $(`gateway ${JSON.stringify(u)} did not take ${JSON.stringify(h)}: ${v}`,v)},leave:W};return d&&Object.defineProperty(U,"chat",{value:g.chat,enumerable:!0}),U}function Ue(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function Ve(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(n,r)?n[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function ge(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ze=3600*1e3,O=new Map;function Qe(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=O.get(s);if(!n&&r&&Date.now()-r.at<ze)return r.list;let o=(async()=>{let a=te(),i;try{i=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:a},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(c){throw new l("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:c})}try{return await ne(i,e.signer,e.projectId,a)}catch(c){throw new l("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:c})}})();return O.set(s,{list:o,at:Date.now()}),o.catch(()=>{O.get(s)?.list===o&&O.delete(s)}),o}async function ye(t,e,n,s,r,o){let i=(await Qe(t,e,o)).keys[0];return Y(i.kid,i.key,Q(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,n,s,(r,o)=>Z(t.key,r,o))}function me(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):G(e,"/response",n,async(r,o)=>{if(!X(o))throw new l("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ee(t.key,r,o)}catch(a){throw new l("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:a})}})}function we(t){return t instanceof l&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
3
3
  `);let n=[],s=this.pending.indexOf(`
4
4
  `);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&n.push({event:this.eventName,payload:this.dataLines.join(`
5
5
  `)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let a=o.slice(5);this.dataLines.push(a.startsWith(" ")?a.slice(1):a)}else if(o.startsWith("event:")){let a=o.slice(6);this.eventName=a.startsWith(" ")?a.slice(1):a}}s=this.pending.indexOf(`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{b as d,m as k}from"./4ONQGDDE.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
1
+ /*! palbase 0.41.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as d,m as k}from"./4Y6CJKXK.js";function S(n){let o=n.meta;if(typeof o!="function")throw new TypeError("encrypted() takes a zod schema: z.string(), z.number(), z.object(\u2026)");return o.call(n,{[d]:!0})}var p=class{value;constructor(o){this.value=o}toJSON(){throw new TypeError("an encrypt() value is sealed by the engine, in a route's answer: it is never JSON of its own")}},m=0;function $(n){if(n===void 0)throw new TypeError("encrypt() takes a JSON value: undefined is none");if(n instanceof p)throw new TypeError("encrypt() of an encrypt() value: one is enough");return m++,new p(n)}function j(){return m}function O(n){let o=[],s=new Set,f=(t,a)=>{if(t instanceof p){if(o.push(a),g(t.value,new Set))throw new TypeError(`${a}: an encrypt() value holds another \u2014 encrypt the whole, or its parts`);return t.value}if(typeof t!="object"||t===null||s.has(t))return t;if(Array.isArray(t)){s.add(t);let r=t.map((c,e)=>f(c,`${a}/${e}`));return s.delete(t),r}let y=Object.getPrototypeOf(t);if(y!==Object.prototype&&y!==null)return t;s.add(t);let i={};for(let[r,c]of Object.entries(t))i[r]=f(c,`${a}/${k(r)}`);return s.delete(t),i};return{value:f(n,"/response"),pointers:o}}function g(n,o){return n instanceof p?!0:typeof n!="object"||n===null||o.has(n)?!1:(o.add(n),Object.values(n).some(s=>g(s,o)))}function v(n,o,s){let f=new Set,l=n,t=l?.$defs??{},a=(i,r,c)=>{if(typeof i!="object"||i===null)return;let e=i;if(typeof e.$ref=="string"){if(c.has(e.$ref))return;let u=new Set(c).add(e.$ref);e.$ref==="#"?a(l,r,u):e.$ref.startsWith("#/$defs/")&&a(t[e.$ref.slice(8)],r,u)}if(e[d]===!0){f.add(r);return}for(let u of["anyOf","oneOf","allOf"])if(Array.isArray(e[u]))for(let w of e[u])a(w,r,c);if(typeof e.properties=="object"&&e.properties!==null)for(let[u,w]of Object.entries(e.properties))a(w,`${r}/${k(u)}`,c);typeof e.items=="object"&&e.items!==null&&a(e.items,`${r}/*`,c);for(let u of["additionalProperties","patternProperties","prefixItems"])if(e[u]!==void 0&&y(e[u]))throw new TypeError(`${s}: an encrypted field is a named property \u2014 not every key of a record, nor a tuple's place`)},y=i=>{if(h(i))return!0;let r=typeof i=="object"&&i!==null?i.$ref:void 0;return typeof r=="string"&&h(r==="#"?l:t[r.slice(8)])};return a(n,o,new Set),[...f]}function T(n){let s=n["~standard"].jsonSchema?.input;if(typeof s!="function")return{};try{return s({target:"draft-2020-12",libraryOptions:{unrepresentable:"any"}})}catch{return{}}}function h(n){return JSON.stringify(n??null).includes(`"${d}":true`)}export{S as a,$ as b,j as c,O as d,v as e,T as f,h as g};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{c as pr,d as mr,e as rn,f as hr,g as gr}from"./37C5IJBG.js";import{a as Pt,c as re,d as lr,e as fr,f as we,h as _,i as yr}from"./D4KYGGQC.js";import{a as or,e as dt,g as xt,h as ir,i as dr,j as Rt,k as Ot,n as cr,t as ur}from"./LVX42GRN.js";import{a as At,b as sr,n as ar}from"./4ONQGDDE.js";import{b as de}from"./5QE5KFNR.js";import"reflect-metadata";var sn=[{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}],wr="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 ya(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let y=s.slice(a+1);if(!Ct.test(y)||Number(y)<1||Number(y)>n)return;d=Number(y)}let f=t,h=n;if(o!=="*")if(o.includes("-")){let y=o.indexOf("-"),k=o.slice(0,y),T=o.slice(y+1);if(!Ct.test(k)||!Ct.test(T)||Number(k)<t||Number(T)>n||Number(k)>Number(T))return;f=Number(k),h=Number(T)}else{if(!Ct.test(o)||Number(o)<t||Number(o)>n)return;f=Number(o),h=a===-1?f:n}for(let y=f;y<=h;y+=d)r.add(y)}return r}function br(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${wr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let y=ya(t[h],sn[h].lo,sn[h].hi);if(!y)return`${wr}; its ${sn[h].name} "${t[h]}" is not one`;n.push(y)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),f=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,f.setUTCDate(f.getUTCDate()+1)){if(!s.has(f.getUTCMonth()+1))continue;let y=r.has(f.getUTCDate()),k=a.has(f.getUTCDay());if(o||d?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var He=Symbol.for("palbase.backend.controller"),qe=Symbol.for("palbase.backend.routes"),on=Symbol.for("palbase.backend.params"),dn=Symbol.for("palbase.backend.injectable"),cn=Symbol.for("palbase.backend.module"),Ce=Symbol.for("palbase.backend.events"),ze=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),be=Symbol.for("palbase.backend.tasks"),ke=Symbol.for("palbase.backend.testUserTemplates");function ce(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var an=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[an]instanceof Set||(e[an]=new Set),e[an]}var Ge=new Set(["webhooks","_palbase"]);function md(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&&Ge.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ce(n,He,()=>({basePath:e,options:t})),se().add(n)}}function Fe(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);ce(r.constructor,qe,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var hd=Fe("GET"),gd=Fe("POST"),yd=Fe("PUT"),wd=Fe("PATCH"),bd=Fe("DELETE"),kd=Fe("QUERY");function ue(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=ce(n.constructor,on,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function un(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 vd=e=>ue("body",{schema:un("Body",e)}),Td=e=>ue("query",{schema:un("QueryParams",e)}),$d=e=>ue("headers",e===void 0?{}:{schema:un("Headers",e)}),_d=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},Ed=()=>ue("user"),Sd=()=>ue("optionalUser"),Ad=()=>ue("req"),xd=()=>ue("requestId"),Rd=()=>ue("requestId"),Od=()=>ue("client"),Pd=()=>ue("attestedDevice");function Cd(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return ue("resolve",{resolver:e,options:t[0]})}function Md(){return e=>{ce(e,dn,()=>!0),se().add(e)}}function jd(e){return t=>{ce(t,cn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Tr=/^[a-z]+(\.[a-z_]+)+$/,wa=/^[a-z][a-z0-9-]{1,62}$/,ln=e=>e.startsWith("file.");function Dd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!wa.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(!ln(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);ce(r.constructor,Ce,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var fn=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ba=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function kr(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(!ba.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Nd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.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=br(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||kr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${kr(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Te))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Te,{value:s,enumerable:!1}),se().add(a)}}var vr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],ka=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ud(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!ka.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&&!vr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${vr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&va(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Ce)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}ce(t,ze,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function va(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ld(){return[...se()].filter(e=>D(e,He)!==void 0)}function Id(e){return(D(e,qe)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Mt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Fd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.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,be))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,be,{value:r,enumerable:!1}),se().add(s)}}var hn;function _r(e){hn=e}function pn(){if(!hn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return hn}var Ta=720*3600;function $a(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Ta))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 _a(e){if(typeof e=="string")return e;let t=e[be];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Bd=Pt("Tasks",{async enqueue(e,t,n={}){return $a(n),pn().enqueue(_a(e),t===void 0?null:t,n)},async cancel(e,t={}){return pn().cancel(e,t.machine)},async get(e,t={}){return pn().get(e,t.machine)}}),mn=(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 Er(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await we.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 mn(a.data,a.status===200)},async cancel(n,r){return mn((await we.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return mn((await we.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ea=1e4,Sa=36e5,$r=24*36e5,jt=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 de({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 de({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 de({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 f of this.tasks.values())if(f.task===t&&f.key===r.key&&(f.finishedAt===void 0||this.now()-f.finishedAt<$r))return this.view(f,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new de({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 de({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(Ea*2**Math.min(t.attempt-1,16),Sa),_.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=$r&&this.tasks.delete(s);n==="failed"&&_.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Dt="/_palbase/test-user-templates",Aa=/^[a-z][a-z0-9_-]{0,63}$/;function Vd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Aa.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}function Sr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Ar(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof de&&n.status===404)return!1;throw n}}var xa="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function xr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,xa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var gn="/_palbase/storage/upload/authorize",Rr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Ra=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Be(e){if(!Ra(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 Or(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Pr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Nt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Oa=/^[a-z][a-z0-9-]{1,62}$/,Cr=1024,Pa=new Set(["userId","uploadId","filename"]);function ec(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);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(!Oa.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=Ca(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,d,f)=>{if(typeof d!="string"||f===void 0||typeof f.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ce(o.constructor,qe,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function tc(){return ue("uploadedObject")}function Ca(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Pa.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(!Mr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Mr(e){if(e===""||new TextEncoder().encode(e).byteLength>Cr)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 Ma(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>ja(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function ja(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 jr(e,t){let n=Ma(e,t);return Mr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Cr} bytes)`}}function Dr(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Nr(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Be(t.user);if(!o)return"user is { id?, session?, role }";let d=Or(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let f=Da(t.uploadedObject);return f?f.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:f,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Da(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:f,thumbhash:h,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||f!==void 0&&typeof f!="number"||h!==void 0&&typeof h!="string")&&!(!wn(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...f!==void 0?{height:f}:{},...h!==void 0?{thumbhash:h}:{},variants:{...y}}}import{markData as Na}from"palgres";var Me=Symbol.for("palbase.backend.gateway"),We=Symbol.for("palbase.backend.gatewayHooks"),Ur={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},Ua={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(Ur),output:()=>structuredClone(Ur)}}},Fr=Symbol.for("palbase.backend.gatewayRefusal"),Lr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Fr,{value:!0})}},La=e=>typeof e=="object"&&e!==null&&e[Fr]===!0&&typeof e.reason=="string",Ke=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Ia=6e4,Ha=86400,Ir=604800,Hr=65536,$e=255,qa=["roles:","flags:","messaging:","calls:","debug:"],za=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Je=e=>new TextEncoder().encode(e).byteLength,bn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",Tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Ga(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(Je(e)>$e)return`a channel is ${$e} 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=qa.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 Br(e){if(typeof e!="string"||e==="")return"is a name";if(Je(e)>$e)return`is ${$e} bytes at most`}function ic(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Ga(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&Tn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Fa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||za.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[y,k]of Object.entries(d)){let T=Br(y);if(T)throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" ${T}`);if(!bn(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let f=ce(a,We,$n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Ua}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ia,hooks:{...f.hooks},messages:Object.assign(Object.create(null),f.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);ce(a,Me,()=>h),se().add(a)}}function Fa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ha;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Ir)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Ir} (a week)`);return n}var $n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ba={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ba[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=ce(n.constructor,We,$n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var dc=ct("authorize"),cc=ct("first"),uc=ct("connect"),lc=ct("disconnect"),fc=ct("empty");function pc(e,t,n={}){let r=Br(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!bn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!bn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=ce(s.constructor,We,$n),f=d.messages[e];if(f!==void 0&&f.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${f.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ka(e){return D(e,Me)}function Ja(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Kr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Je(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Wa(e,t,n){let r=Tn(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Kr(e,t):Va(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Va(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Za=1e4,Ya=1e3,Qa=100,_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ye=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),qr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},zr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Jr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:S}of e){let m=Ka(b),$=a.get(m.name);if($!==void 0&&$!==b)throw new TypeError(`@Gateway("${m.pattern}"): two gateways are named ${m.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(m.name,b);let M=s.get(zr(m.pattern));if(M!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: ${n.get(M)?.cls.name}'s "${M}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(zr(m.pattern),m.pattern);for(let[Z,Y]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([L,I])=>[`message ${L}`,I.fn])])if(typeof S[Y]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: its ${Z} is ${Y}, which is no method of it`);let U={cls:b,instance:S,g:m};n.set(m.pattern,U),r.set(b,U)}let o=new Map,d=new Set,f=new Set,h=new vn(t.broadcast),y=b=>{let S=o.get(b);return S||(S=new AbortController,o.set(b,S)),S},k=(b,S)=>{S?.abort(),o.get(b)===S&&o.delete(b)},T=(b,S,m,$,M,U)=>{if(!Object.hasOwn(b.g.events,m)){_.warn(`[palbase] ${M}: emit("${m}") is not sent \u2014 ${b.cls.name} declares no event "${m}" (static events)`);return}if(b.g.chat&&m==="chat"){_.warn(`[palbase] ${M}: emit("chat") is not sent \u2014 ${b.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:S,event:m,payload:$??{},...U!==void 0?{conn_id:U}:{}},M)},F=async(b,S,m)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${m}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(S)};function N(b,S,m,$,M,U,Z){let Y=$?.signal??AbortSignal.abort(),L=`${b.cls.name} (${S})`;return{channel:S,params:Object.freeze({...m}),signal:Y,count:M,user:U,emit:(I,G)=>T(b,S,I,G,L,Z),pipe:I=>F(I,S,L),owner:{hold(I){re.exit(async()=>{try{await I(Y)}catch(G){Y.aborted||_.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(S,$)}}}function H(b){let{room:S,channel:m}=b;if(typeof S!="string"||typeof m!="string")return ye(400,"bad_request","A gateway's call names its pattern (room) and its channel");let $=n.get(S);return!$||!Ke($.g)?ye(404,"not_found",`This app serves no gateway "${S}"`):{entry:$,channel:m,params:Ja(S,m)}}let W=(b,S)=>ye(400,"bad_request",`"${S}" is not a channel of the gateway "${b}"`);async function z(b,S){let m=H(b);if("status"in m)return m;let{entry:$,channel:M,params:U}=m,Z={status:200,body:{subscribe:!1,publish:!1}};if(!U)return _.warn(`[palbase] ${$.cls.name}: realtime asked about "${M}", which is not a channel of the gateway "${$.g.pattern}"; the join is refused`),Z;let Y=Be(b.user),L=Y?.id;if(!L)return Z;if($.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}};if($.g.access==="owner")return U[Tn($.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}}:Z;let I=$.g.hooks.authorize;if(!I)return Z;let G,B;try{G=await t.run(Y,`${$.cls.name}.${I}`,S,async()=>$.instance[I]({user:{id:L},params:Object.freeze({...U})})),B=Xa(G)}catch(ne){if(t.isOutage(ne)||S?.aborted)throw ne;return _.error(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) failed; the join is refused`,{error:ne}),Z}return B==="malformed"?(_.warn(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) answered ${eo(G)}, which is no grant (true, { read, write } or null); the join is refused`),Z):{status:200,body:B}}async function ie(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=Be(b.user);if(!$?.id||typeof b.event!="string")return ye(400,"bad_request","A message names its member (user) and its event");let M=Object.hasOwn(m.entry.g.messages,b.event)?m.entry.g.messages[b.event]:void 0;if(!M)return{status:200,body:{ok:!1,reason:kn(`gateway "${m.channel}" takes no message "${b.event}"`,Ut)}};let U=await M.schema["~standard"].validate(Na(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:Gr(U.issues)}};let Z=y(m.channel),Y={...N(m.entry,m.channel,m.params,Z,0,{id:$.id}),payload:U.value},L=`${m.entry.cls.name}.${M.fn} (@Subscribe "${b.event}" of ${m.channel})`,I;try{I=await t.run($,`${m.entry.cls.name}.${M.fn}`,S,async()=>m.entry.instance[M.fn](Y))}catch(B){if(t.isOutage(B))throw B;return La(B)?{status:200,body:{ok:!1,reason:kn(B.reason,Ut)}}:(S?.aborted||_.error(`[palbase] ${L} failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(I===void 0)return{status:200,body:{ok:!0}};if(M.reply){let B=await M.reply["~standard"].validate(I);if(B.issues)return _.error(`[palbase] ${L} returned an ack its reply schema refuses (${Gr(B.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};I=B.value}let G;try{G=JSON.stringify(I)}catch(B){return _.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Je(G)>Hr?(_.error(`[palbase] ${L} returned an ack of ${Je(G)} bytes, past ${Hr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(G)}}}async function ge(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=b.event;if(typeof $!="string"||!Object.hasOwn(qr,$))return ye(400,"bad_request","A gateway's moment is first, join, leave or empty");let M=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(M===void 0)return ye(400,"bad_request","A gateway's moment says its count of members");let U=$==="join"||$==="leave",Z=U?Be(b.user):void 0,Y=U?b.connId:void 0;if(U&&(!Z?.id||typeof Y!="string"||Y===""))return ye(400,"bad_request",`A ${$} names its member: user and connId`);let L=`${$}\0${m.channel}\0${typeof Y=="string"?Y:""}`;if(U&&d.has(L))return{status:204};if(f.has(L))return ye(503,"in_progress","This moment of the gateway is being handled",5);f.add(L);try{let I=m.entry.g.hooks[qr[$]],G;if($==="empty"?(G=o.get(m.channel),k(m.channel,G)):G=$==="leave"?o.get(m.channel):y(m.channel),I){let B=N(m.entry,m.channel,m.params,G,M,{id:Z?.id??""},$==="join"?Y:void 0);try{await t.run(Z,`${m.entry.cls.name}.${I}`,S,async()=>m.entry.instance[I](B))}catch(ne){if(t.isOutage(ne))throw ne;return S?.aborted||_.error(`[palbase] ${m.entry.cls.name}.${I} (${$} of ${m.channel}) failed; realtime tells it again`,{error:ne}),ye(500,"handler_failed",`The gateway's ${$} could not be handled`)}}return U&&(d.add(L),d.size>Za&&d.delete(d.values().next().value)),{status:204}}finally{f.delete(L)}}function Se(b,S){let m=r.get(b),$=`Palbase.gateways.to(${b?.name??String(b)})`;if(!m)throw new TypeError(`${$}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let M=Kr(m.g.pattern,S??{});if(typeof M!="string")throw new TypeError(`${$}: ${M.problem}`);return{entry:m,channel:M,where:$}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,S,m){return _n(S)?b==="authorize"?z(S,m):b==="message"?ie(S,m):b==="lifecycle"?ge(S,m):ye(404,"not_found",`No gateway call ${JSON.stringify(b)}`):ye(400,"bad_request","A gateway's call is a JSON object")},emit(b,S,m,$){let{entry:M,channel:U,where:Z}=Se(b,S);T(M,U,m,$,Z)},async pipe(b,S,m){let{channel:$,where:M}=Se(b,S);await F(m,$,M)},async revalidate(b,S,m={}){let $=r.get(b),M=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!$)throw new TypeError(`${M}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let U=Wa($.g.pattern,S??{},m);if("problem"in U)throw new TypeError(`${M}: ${U.problem}`);await t.revalidate(U)},close(){for(let b of o.values())b.abort();o.clear()}}}function Xa(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!_n(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function eo(e){return Array.isArray(e)?"an array":_n(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var to=20,Ut=256;function Gr(e){let t="";for(let n of e.slice(0,to)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Ut)break}return kn(t,Ut)}function kn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var vn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Je(t.event)>$e){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${$e} bytes`);return}try{JSON.stringify(t.payload)}catch(a){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=Ya?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),re.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,Qa);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as En,createHmac as no,createPublicKey as Yr,timingSafeEqual as ro,verify as Qr}from"node:crypto";function yc(e){let t=D(e,ze);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 Xr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,ze),f=s.get(d.name);if(f)throw new TypeError(`@Webhook "${d.name}" is declared by ${f.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,y=n[d.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=so(d,y)}catch(N){a.push(`${h}: ${d.secret.env} ${N.message}`)}let T=t(o),F=new Map(d.events.map(({event:N,fn:H})=>[N,{name:`${o.name}.${H}`,call:(W,z)=>T[H](W,z)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:F})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
1
+ /*! palbase 0.41.0 — Palbase SDK License (see LICENSE) */
2
+ import{c as pr,d as mr,e as rn,f as hr,g as gr}from"./OCFHMHBP.js";import{a as Pt,c as re,d as lr,e as fr,f as we,h as _,i as yr}from"./H3RARUDI.js";import{a as or,e as dt,g as xt,h as ir,i as dr,j as Rt,k as Ot,n as cr,t as ur}from"./E267BI6B.js";import{a as At,b as sr,n as ar}from"./4Y6CJKXK.js";import{b as de}from"./HR6L4MUD.js";import"reflect-metadata";var sn=[{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}],wr="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 ya(e,t,n){let r=new Set;for(let s of e.split(",")){let a=s.indexOf("/"),o=a===-1?s:s.slice(0,a),d=1;if(a!==-1){let y=s.slice(a+1);if(!Ct.test(y)||Number(y)<1||Number(y)>n)return;d=Number(y)}let f=t,h=n;if(o!=="*")if(o.includes("-")){let y=o.indexOf("-"),k=o.slice(0,y),T=o.slice(y+1);if(!Ct.test(k)||!Ct.test(T)||Number(k)<t||Number(T)>n||Number(k)>Number(T))return;f=Number(k),h=Number(T)}else{if(!Ct.test(o)||Number(o)<t||Number(o)>n)return;f=Number(o),h=a===-1?f:n}for(let y=f;y<=h;y+=d)r.add(y)}return r}function br(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${wr}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let y=ya(t[h],sn[h].lo,sn[h].hi);if(!y)return`${wr}; its ${sn[h].name} "${t[h]}" is not one`;n.push(y)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),f=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,f.setUTCDate(f.getUTCDate()+1)){if(!s.has(f.getUTCMonth()+1))continue;let y=r.has(f.getUTCDate()),k=a.has(f.getUTCDay());if(o||d?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var He=Symbol.for("palbase.backend.controller"),qe=Symbol.for("palbase.backend.routes"),on=Symbol.for("palbase.backend.params"),dn=Symbol.for("palbase.backend.injectable"),cn=Symbol.for("palbase.backend.module"),Ce=Symbol.for("palbase.backend.events"),ze=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),be=Symbol.for("palbase.backend.tasks"),ke=Symbol.for("palbase.backend.testUserTemplates");function ce(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var an=Symbol.for("palbase.backend.declared");function se(){let e=globalThis;return e[an]instanceof Set||(e[an]=new Set),e[an]}var Ge=new Set(["webhooks","_palbase"]);function md(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&&Ge.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ce(n,He,()=>({basePath:e,options:t})),se().add(n)}}function Fe(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);ce(r.constructor,qe,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var hd=Fe("GET"),gd=Fe("POST"),yd=Fe("PUT"),wd=Fe("PATCH"),bd=Fe("DELETE"),kd=Fe("QUERY");function ue(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let a=ce(n.constructor,on,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function un(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 vd=e=>ue("body",{schema:un("Body",e)}),Td=e=>ue("query",{schema:un("QueryParams",e)}),$d=e=>ue("headers",e===void 0?{}:{schema:un("Headers",e)}),_d=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},Ed=()=>ue("user"),Sd=()=>ue("optionalUser"),Ad=()=>ue("req"),xd=()=>ue("requestId"),Rd=()=>ue("requestId"),Od=()=>ue("client"),Pd=()=>ue("attestedDevice");function Cd(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return ue("resolve",{resolver:e,options:t[0]})}function Md(){return e=>{ce(e,dn,()=>!0),se().add(e)}}function jd(e){return t=>{ce(t,cn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Tr=/^[a-z]+(\.[a-z_]+)+$/,wa=/^[a-z][a-z0-9-]{1,62}$/,ln=e=>e.startsWith("file.");function Dd(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!wa.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(!ln(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,a)=>{if(typeof s!="string"||a===void 0||typeof a.value!="function")throw new TypeError(`@On("${e}") goes on a method`);ce(r.constructor,Ce,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),se().add(r.constructor)}}var fn=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ba=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function kr(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(!ba.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function Nd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.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=br(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||kr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${kr(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return a=>{if(typeof a.prototype.run!="function")throw new TypeError(`${n} on ${a.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(a,Te))throw new TypeError(`${n} on ${a.name}: a class is one cron`);Object.defineProperty(a,Te,{value:s,enumerable:!1}),se().add(a)}}var vr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],ka=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function Ud(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!ka.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&&!vr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${vr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&va(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=D(t,Ce)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let a=new Set;for(let{event:o,bucket:d}of s){if(a.has(o))throw new TypeError(`${n}: @On("${o}") is declared twice; one method takes an event`);if(d!==void 0)throw new TypeError(`${n}: @On("${o}", { bucket: "${d}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);a.add(o)}ce(t,ze,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:o,fn:d})=>({event:o,fn:d}))})),se().add(t)}}function va(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function D(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function Ld(){return[...se()].filter(e=>D(e,He)!==void 0)}function Id(e){return(D(e,qe)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var Mt=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function Fd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!fn.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,be))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,be,{value:r,enumerable:!1}),se().add(s)}}var hn;function _r(e){hn=e}function pn(){if(!hn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return hn}var Ta=720*3600;function $a(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Ta))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 _a(e){if(typeof e=="string")return e;let t=e[be];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var Bd=Pt("Tasks",{async enqueue(e,t,n={}){return $a(n),pn().enqueue(_a(e),t===void 0?null:t,n)},async cancel(e,t={}){return pn().cancel(e,t.machine)},async get(e,t={}){return pn().get(e,t.machine)}}),mn=(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 Er(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let a=await we.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 mn(a.data,a.status===200)},async cancel(n,r){return mn((await we.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return mn((await we.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ea=1e4,Sa=36e5,$r=24*36e5,jt=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 de({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 de({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 de({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 f of this.tasks.values())if(f.task===t&&f.key===r.key&&(f.finishedAt===void 0||this.now()-f.finishedAt<$r))return this.view(f,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new de({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 de({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),a;try{a=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(a={status:504,message:`it did not end in ${n.timeout} s`})}catch(d){a={status:500,message:d.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let o=`${a.status}${a.message?`: ${a.message}`:""}`;a.status>=200&&a.status<300?this.finish(t,"succeeded"):a.status===422?this.finish(t,"failed",`the app said it can never be done: ${o}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${o}`):(t.state="waiting",t.reason=`the app answered ${o}`,t.runAt=this.now()+Math.min(Ea*2**Math.min(t.attempt-1,16),Sa),_.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,a]of this.tasks)a.finishedAt!==void 0&&this.now()-a.finishedAt>=$r&&this.tasks.delete(s);n==="failed"&&_.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};var Dt="/_palbase/test-user-templates",Aa=/^[a-z][a-z0-9_-]{0,63}$/;function Vd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Aa.test(t.name))throw new TypeError(`${n}: name is lowercase letters, digits, '_' and '-', at most 64, starting with a letter`);let r={name:t.name};return s=>{let a=s.prototype;if(typeof a.seed!="function")throw new TypeError(`${n} on ${s.name}: a template is a class with a seed(user, meta) method`);if(a.undo!==void 0&&typeof a.undo!="function")throw new TypeError(`${n} on ${s.name}: undo, when it is there, is a method: undo(user, meta)`);if(Object.prototype.hasOwnProperty.call(s,ke))throw new TypeError(`${n} on ${s.name}: a class is one template`);Object.defineProperty(s,ke,{value:r,enumerable:!1}),se().add(s)}}function Sr(e,t){let n=t??{},r=n.user??{};return n.template!==e?`the call names the template ${JSON.stringify(n.template??null)}, its address ${JSON.stringify(e)}`:typeof r.id!="string"||r.id===""||r.id.length>128?"user.id is the test user's id":typeof r.email!="string"||r.email.length>320?"user.email is the test user's address":{user:{id:r.id,email:r.email}}}async function Ar(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof de&&n.status===404)return!1;throw n}}var xa="SELECT schemaname, relname, (n_tup_ins + n_tup_upd)::int AS n FROM pg_stat_xact_user_tables WHERE n_tup_ins + n_tup_upd > 0 AND schemaname NOT IN ('palbase', 'palgres') ORDER BY schemaname, relname";async function xr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,xa),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var gn="/_palbase/storage/upload/authorize",Rr="/_palbase/storage/upload/complete",yn="/_palbase/realtime/rooms";var Ra=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Be(e){if(!Ra(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 Or(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Pr(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Nt(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var Oa=/^[a-z][a-z0-9-]{1,62}$/,Cr=1024,Pa=new Set(["userId","uploadId","filename"]);function ec(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);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(!Oa.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=Ca(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},a={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(o,d,f)=>{if(typeof d!="string"||f===void 0||typeof f.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ce(o.constructor,qe,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function tc(){return ue("uploadedObject")}function Ca(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Pa.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(!Mr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Mr(e){if(e===""||new TextEncoder().encode(e).byteLength>Cr)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 Ma(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>ja(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function ja(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 jr(e,t){let n=Ma(e,t);return Mr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Cr} bytes)`}}function Dr(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(a=>a.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(a=>a.kind==="headers"||a.kind==="req"||a.kind==="client");if(s){let a=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${a}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Nr(e,t){if(!wn(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:a}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof a!="string"||a==="")return"uploadId is the upload's id";let o=Be(t.user);if(!o)return"user is { id?, session?, role }";let d=Or(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let f=Da(t.uploadedObject);return f?f.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:f,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Da(e){if(!wn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:f,thumbhash:h,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||f!==void 0&&typeof f!="number"||h!==void 0&&typeof h!="string")&&!(!wn(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...f!==void 0?{height:f}:{},...h!==void 0?{thumbhash:h}:{},variants:{...y}}}import{markData as Na}from"palgres";var Me=Symbol.for("palbase.backend.gateway"),We=Symbol.for("palbase.backend.gatewayHooks"),Ur={type:"object",description:"One part of the chat the platform writes into the channel: a member's message, a turn, the answer's text at its byte offset, a reset, a tool call or a subagent.",properties:{type:{type:"string",description:"message, turn, text, reset, tool or agent (a newer module may add others: a client lets them be)."},id:{type:"integer",description:"The chat journal's number of a message, turn, tool or agent part."},data:{type:"object",additionalProperties:{},description:"The part's fields."}},required:["type","data"]},Ua={"~standard":{version:1,vendor:"palbase",validate:e=>typeof e=="object"&&e!==null&&typeof e.type=="string"&&typeof e.data=="object"?{value:e}:{issues:[{message:"a chat part is {type, id?, data}"}]},jsonSchema:{input:()=>structuredClone(Ur),output:()=>structuredClone(Ur)}}},Fr=Symbol.for("palbase.backend.gatewayRefusal"),Lr=class extends Error{reason;constructor(t){if(typeof t!="string"||t==="")throw new TypeError("a GatewayRefusal says its reason: the word the member's app acts on");super(t),this.name="GatewayRefusal",this.reason=t,Object.defineProperty(this,Fr,{value:!0})}},La=e=>typeof e=="object"&&e!==null&&e[Fr]===!0&&typeof e.reason=="string",Ke=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Ia=6e4,Ha=86400,Ir=604800,Hr=65536,$e=255,qa=["roles:","flags:","messaging:","calls:","debug:"],za=new Set("await break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield implements interface let package private protected public static arguments eval undefined NaN Infinity globalThis Error TypeError Object Array Promise String Number Boolean Symbol BigInt Date Map Set JSON Math Reflect Proxy RegExp Record Partial Readonly".split(" ")),Je=e=>new TextEncoder().encode(e).byteLength,bn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",Tn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Ga(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(Je(e)>$e)return`a channel is ${$e} 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=qa.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 Br(e){if(typeof e!="string"||e==="")return"is a name";if(Je(e)>$e)return`is ${$e} bytes at most`}function ic(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Ga(e);if(n)throw new TypeError(`@Gateway("${e}"): ${n}`);let r=t??{};if(r.access!==void 0&&r.access!=="owner"&&r.access!=="public")throw new TypeError(`@Gateway("${e}"): access is 'owner' or 'public' (or left out for an @Authorize method)`);if(r.access==="owner"&&Tn(e).length!==1)throw new TypeError(`@Gateway("${e}"): access 'owner' needs exactly one {param} \u2014 the joining user's id is compared with it`);if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Gateway("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);if(r.chat!==void 0&&typeof r.chat!="boolean")throw new TypeError(`@Gateway("${e}"): chat is true for a gateway that carries a chat, or left out`);let s=Fa(e,r.durable===void 0&&r.chat===!0?!0:r.durable);return a=>{let o=a.name;if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(o)||za.has(o))throw new TypeError(`@Gateway("${e}"): the class is named ${JSON.stringify(o)} \u2014 a gateway's class has a name of its own (export class ChatGateway), its client's in every generated module`);let d=a.events??{};if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError(`@Gateway("${e}") on ${o}: static events is what it sends, by name, each its payload's schema`);if(r.chat===!0&&Object.hasOwn(d,"chat"))throw new TypeError(`@Gateway("${e}") on ${o}: chat: true makes its event "chat" the platform's \u2014 its static events declare none of that name`);for(let[y,k]of Object.entries(d)){let T=Br(y);if(T)throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" ${T}`);if(!bn(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${y}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let f=ce(a,We,$n),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:Ua}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Ia,hooks:{...f.hooks},messages:Object.assign(Object.create(null),f.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: publish is for a gateway of no method \u2014 one with methods takes its members' messages itself (@Subscribe)`);if(h.publish&&h.chat)throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway's channel is written by the platform and its server alone \u2014 publish would let its members write chat parts`);if(h.chat&&!Ke(h))throw new TypeError(`@Gateway("${e}") on ${o}: a chat gateway is served by the app \u2014 give it its members' messages (@Subscribe) or an @Authorize, so no member writes on its channel`);ce(a,Me,()=>h),se().add(a)}}function Fa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return Ha;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Ir)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Ir} (a week)`);return n}var $n=()=>({hooks:Object.create(null),messages:Object.create(null)}),Ba={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function ct(e){let t=Ba[e];return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a gateway's methods are its instance's`);let a=ce(n.constructor,We,$n),o=a.hooks[e];if(o!==void 0&&o!==r)throw new TypeError(`@${t}() is declared twice in one gateway (${o} and ${r}). A gateway has one of each.`);a.hooks[e]=r,se().add(n.constructor)}}var dc=ct("authorize"),cc=ct("first"),uc=ct("connect"),lc=ct("disconnect"),fc=ct("empty");function pc(e,t,n={}){let r=Br(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!bn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!bn(n.reply))throw new TypeError(`@Subscribe("${e}", schema, { reply }): reply is a Standard Schema \u2014 its ack's`);return(s,a,o)=>{if(typeof a!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@Subscribe("${e}") goes on a method`);if(typeof s=="function")throw new TypeError(`@Subscribe("${e}") on static ${s.name}.${a}: a gateway's methods are its instance's`);let d=ce(s.constructor,We,$n),f=d.messages[e];if(f!==void 0&&f.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${f.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},se().add(s.constructor)}}function Ka(e){return D(e,Me)}function Ja(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let a=0;a<n.length;a++){let o=n[a];if(o.length>=2&&o.startsWith("{")&&o.endsWith("}")){if(r[a]==="")return;s.push([o.slice(1,-1),r[a]])}else if(o!==r[a])return}return Object.fromEntries(s)}function Kr(e,t){let n=[];for(let s of e.split(":")){if(!(s.length>=2&&s.startsWith("{")&&s.endsWith("}"))){n.push(s);continue}let a=s.slice(1,-1),o=Object.hasOwn(t,a)?t[a]:void 0;if(typeof o!="string"||o===""||o.includes(":")||/[\x00-\x1F\x7F]/.test(o))return{problem:`{${a}} is a non-empty string with no ':' (got ${o===void 0?"nothing":typeof o})`};n.push(o)}let r=n.join(":");return Je(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Wa(e,t,n){let r=Tn(e).map(d=>d.slice(1,-1));for(let d of Object.keys(t))if(!r.includes(d))return{problem:`{${d}} is no capture of "${e}"`};let s=n.user;if(s!==void 0&&(typeof s!="string"||s===""||s.length>128))return{problem:"user is a user's id"};let a=r.every(d=>Object.hasOwn(t,d))?Kr(e,t):Va(e,t,r);if(typeof a!="string"&&"problem"in a)return a;let o=typeof a=="string"?{topic:a}:a;if(s!==void 0&&(o.user=s),n.end===!0){if(o.topic===void 0)return{problem:`end is one channel's: give every capture of "${e}" (${r.map(d=>`{${d}}`).join(", ")})`};if(s!==void 0)return{problem:"end is the whole channel's: a user's membership is decided again without it"};o.end=!0}return o}function Va(e,t,n){let r={};for(let s of n){if(!Object.hasOwn(t,s))continue;let a=t[s];if(typeof a!="string"||a===""||a.includes(":")||/[\x00-\x1F\x7F]/.test(a))return{problem:`{${s}} is a non-empty string with no ':' (got ${typeof a})`};r[s]=a}return{pattern:e,params:r}}var Za=1e4,Ya=1e3,Qa=100,_n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ye=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),qr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},zr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Jr(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:S}of e){let m=Ka(b),$=a.get(m.name);if($!==void 0&&$!==b)throw new TypeError(`@Gateway("${m.pattern}"): two gateways are named ${m.name} \u2014 each is a client by its name in every generated module; rename one`);a.set(m.name,b);let M=s.get(zr(m.pattern));if(M!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: ${n.get(M)?.cls.name}'s "${M}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(zr(m.pattern),m.pattern);for(let[Z,Y]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([L,I])=>[`message ${L}`,I.fn])])if(typeof S[Y]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: its ${Z} is ${Y}, which is no method of it`);let U={cls:b,instance:S,g:m};n.set(m.pattern,U),r.set(b,U)}let o=new Map,d=new Set,f=new Set,h=new vn(t.broadcast),y=b=>{let S=o.get(b);return S||(S=new AbortController,o.set(b,S)),S},k=(b,S)=>{S?.abort(),o.get(b)===S&&o.delete(b)},T=(b,S,m,$,M,U)=>{if(!Object.hasOwn(b.g.events,m)){_.warn(`[palbase] ${M}: emit("${m}") is not sent \u2014 ${b.cls.name} declares no event "${m}" (static events)`);return}if(b.g.chat&&m==="chat"){_.warn(`[palbase] ${M}: emit("chat") is not sent \u2014 ${b.cls.name}'s chat parts are written by the platform (ctx.pipe(Palbase.ai.chats.events(id)))`);return}h.send({topic:S,event:m,payload:$??{},...U!==void 0?{conn_id:U}:{}},M)},F=async(b,S,m)=>{if(typeof b!="object"||b===null||typeof b.pipe!="function")throw new TypeError(`${m}: pipe(source) takes what the platform writes into a channel \u2014 Palbase.ai.chats.events(chatId)`);await b.pipe(S)};function N(b,S,m,$,M,U,Z){let Y=$?.signal??AbortSignal.abort(),L=`${b.cls.name} (${S})`;return{channel:S,params:Object.freeze({...m}),signal:Y,count:M,user:U,emit:(I,G)=>T(b,S,I,G,L,Z),pipe:I=>F(I,S,L),owner:{hold(I){re.exit(async()=>{try{await I(Y)}catch(G){Y.aborted||_.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:G})}}).catch(()=>{})},release:()=>k(S,$)}}}function H(b){let{room:S,channel:m}=b;if(typeof S!="string"||typeof m!="string")return ye(400,"bad_request","A gateway's call names its pattern (room) and its channel");let $=n.get(S);return!$||!Ke($.g)?ye(404,"not_found",`This app serves no gateway "${S}"`):{entry:$,channel:m,params:Ja(S,m)}}let W=(b,S)=>ye(400,"bad_request",`"${S}" is not a channel of the gateway "${b}"`);async function z(b,S){let m=H(b);if("status"in m)return m;let{entry:$,channel:M,params:U}=m,Z={status:200,body:{subscribe:!1,publish:!1}};if(!U)return _.warn(`[palbase] ${$.cls.name}: realtime asked about "${M}", which is not a channel of the gateway "${$.g.pattern}"; the join is refused`),Z;let Y=Be(b.user),L=Y?.id;if(!L)return Z;if($.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}};if($.g.access==="owner")return U[Tn($.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys($.g.messages).length>0}}:Z;let I=$.g.hooks.authorize;if(!I)return Z;let G,B;try{G=await t.run(Y,`${$.cls.name}.${I}`,S,async()=>$.instance[I]({user:{id:L},params:Object.freeze({...U})})),B=Xa(G)}catch(ne){if(t.isOutage(ne)||S?.aborted)throw ne;return _.error(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) failed; the join is refused`,{error:ne}),Z}return B==="malformed"?(_.warn(`[palbase] ${$.cls.name}.${I} (@Authorize of ${M}) answered ${eo(G)}, which is no grant (true, { read, write } or null); the join is refused`),Z):{status:200,body:B}}async function ie(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=Be(b.user);if(!$?.id||typeof b.event!="string")return ye(400,"bad_request","A message names its member (user) and its event");let M=Object.hasOwn(m.entry.g.messages,b.event)?m.entry.g.messages[b.event]:void 0;if(!M)return{status:200,body:{ok:!1,reason:kn(`gateway "${m.channel}" takes no message "${b.event}"`,Ut)}};let U=await M.schema["~standard"].validate(Na(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:Gr(U.issues)}};let Z=y(m.channel),Y={...N(m.entry,m.channel,m.params,Z,0,{id:$.id}),payload:U.value},L=`${m.entry.cls.name}.${M.fn} (@Subscribe "${b.event}" of ${m.channel})`,I;try{I=await t.run($,`${m.entry.cls.name}.${M.fn}`,S,async()=>m.entry.instance[M.fn](Y))}catch(B){if(t.isOutage(B))throw B;return La(B)?{status:200,body:{ok:!1,reason:kn(B.reason,Ut)}}:(S?.aborted||_.error(`[palbase] ${L} failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(I===void 0)return{status:200,body:{ok:!0}};if(M.reply){let B=await M.reply["~standard"].validate(I);if(B.issues)return _.error(`[palbase] ${L} returned an ack its reply schema refuses (${Gr(B.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};I=B.value}let G;try{G=JSON.stringify(I)}catch(B){return _.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:B}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return G===void 0?{status:200,body:{ok:!0}}:Je(G)>Hr?(_.error(`[palbase] ${L} returned an ack of ${Je(G)} bytes, past ${Hr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(G)}}}async function ge(b,S){let m=H(b);if("status"in m)return m;if(!m.params)return W(m.entry.g.pattern,m.channel);let $=b.event;if(typeof $!="string"||!Object.hasOwn(qr,$))return ye(400,"bad_request","A gateway's moment is first, join, leave or empty");let M=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(M===void 0)return ye(400,"bad_request","A gateway's moment says its count of members");let U=$==="join"||$==="leave",Z=U?Be(b.user):void 0,Y=U?b.connId:void 0;if(U&&(!Z?.id||typeof Y!="string"||Y===""))return ye(400,"bad_request",`A ${$} names its member: user and connId`);let L=`${$}\0${m.channel}\0${typeof Y=="string"?Y:""}`;if(U&&d.has(L))return{status:204};if(f.has(L))return ye(503,"in_progress","This moment of the gateway is being handled",5);f.add(L);try{let I=m.entry.g.hooks[qr[$]],G;if($==="empty"?(G=o.get(m.channel),k(m.channel,G)):G=$==="leave"?o.get(m.channel):y(m.channel),I){let B=N(m.entry,m.channel,m.params,G,M,{id:Z?.id??""},$==="join"?Y:void 0);try{await t.run(Z,`${m.entry.cls.name}.${I}`,S,async()=>m.entry.instance[I](B))}catch(ne){if(t.isOutage(ne))throw ne;return S?.aborted||_.error(`[palbase] ${m.entry.cls.name}.${I} (${$} of ${m.channel}) failed; realtime tells it again`,{error:ne}),ye(500,"handler_failed",`The gateway's ${$} could not be handled`)}}return U&&(d.add(L),d.size>Za&&d.delete(d.values().next().value)),{status:204}}finally{f.delete(L)}}function Se(b,S){let m=r.get(b),$=`Palbase.gateways.to(${b?.name??String(b)})`;if(!m)throw new TypeError(`${$}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let M=Kr(m.g.pattern,S??{});if(typeof M!="string")throw new TypeError(`${$}: ${M.problem}`);return{entry:m,channel:M,where:$}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,S,m){return _n(S)?b==="authorize"?z(S,m):b==="message"?ie(S,m):b==="lifecycle"?ge(S,m):ye(404,"not_found",`No gateway call ${JSON.stringify(b)}`):ye(400,"bad_request","A gateway's call is a JSON object")},emit(b,S,m,$){let{entry:M,channel:U,where:Z}=Se(b,S);T(M,U,m,$,Z)},async pipe(b,S,m){let{channel:$,where:M}=Se(b,S);await F(m,$,M)},async revalidate(b,S,m={}){let $=r.get(b),M=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!$)throw new TypeError(`${M}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let U=Wa($.g.pattern,S??{},m);if("problem"in U)throw new TypeError(`${M}: ${U.problem}`);await t.revalidate(U)},close(){for(let b of o.values())b.abort();o.clear()}}}function Xa(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!_n(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,a=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:a!==!1}}function eo(e){return Array.isArray(e)?"an array":_n(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var to=20,Ut=256;function Gr(e){let t="";for(let n of e.slice(0,to)){let r=(n.path??[]).slice(0,8).map(a=>String(typeof a=="object"&&a!==null&&"key"in a?a.key:a).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Ut)break}return kn(t,Ut)}function kn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var vn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Je(t.event)>$e){_.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${$e} bytes`);return}try{JSON.stringify(t.payload)}catch(a){_.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:a});return}let r=this.queues.get(t.topic);if(r){r.length>=Ya?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),re.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,Qa);try{await this.broadcast(s)}catch(o){_.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:o})}let a=this.dropped.get(t);a&&(this.dropped.delete(t),_.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as En,createHmac as no,createPublicKey as Yr,timingSafeEqual as ro,verify as Qr}from"node:crypto";function yc(e){let t=D(e,ze);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 Xr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=D(o,ze),f=s.get(d.name);if(f)throw new TypeError(`@Webhook "${d.name}" is declared by ${f.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,y=n[d.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=so(d,y)}catch(N){a.push(`${h}: ${d.secret.env} ${N.message}`)}let T=t(o),F=new Map(d.events.map(({event:N,fn:H})=>[N,{name:`${o.name}.${H}`,call:(W,z)=>T[H](W,z)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:F})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
3
3
  - ${a.join(`
4
4
  - `)}`);return s}function es(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Ve=1024,Wr=1024*Ve;function so(e,t){if(e.signature)return je(void 0,e.signature.header,1/0,go(e.signature,t));switch(e.provider){case"stripe":return je("stripe","stripe-signature",512*Ve,io(t));case"github":return je("github","x-hub-signature-256",25*Wr,co(t));case"slack":return je("slack","x-slack-signature",64*Ve,uo(t));case"discord":return je("discord","x-signature-ed25519",64*Ve,lo(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Ve),check:po(t)};case"sendgrid":return je("sendgrid","x-twilio-email-event-webhook-signature",Wr,mo(t));case"livekit":return je("livekit","authorization",512*Ve,ho(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function je(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??ts(e,s)}}function ts(e,t){let n=Sn(t.body),r;try{r=JSON.parse(n)}catch{if(r=n,e==="slack"){let s=new URLSearchParams(n).get("payload");if(s!==null)try{r=JSON.parse(s)}catch{}}}return{type:ns(e,t.headers,r),event:r,...ao(e,t,r)}}function ns(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=De(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=as(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 De(n,"EventType");case"livekit":return De(n,"event");default:return De(n,"type")}}function ao(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(De(n,"id"));case"slack":return r(De(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${rs(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>De(s,"sg_event_id")||void 0)}:{};default:return{}}}var oo=300;function io(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let f of r.split(",")){let h=f.indexOf("=");if(h<=0)continue;let y=f.slice(0,h).trim(),k=f.slice(h+1).trim();if(y==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(y==="v1"){let T=me(k,"hex");if(!T)return"malformed_signature";a.push(T)}}let o=ut(s);if(o===void 0||a.length===0)return"malformed_signature";if(lt(o,n))return"stale_timestamp";let d=Ze("sha256",e,`${s}.`,t.body);return a.some(f=>_e(f,d))?void 0:"signature_mismatch"}}function co(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?me(n.slice(7),"hex"):void 0;return r?_e(r,Ze("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function uo(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),a=ut(s),o=r.startsWith("v0=")?me(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":lt(a,n)?"stale_timestamp":_e(o,Ze("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function lo(e){let t=me(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let n=Yr({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let a=r.headers.get("x-signature-ed25519");if(!a)return"missing_signature";let o=r.headers.get("x-signature-timestamp")??void 0,d=ut(o),f=me(a,"hex");return d===void 0||!f||f.byteLength!==64?"malformed_signature":lt(d,s)?"stale_timestamp":Qr(null,ss(o,r.body),n,f)?void 0:"signature_mismatch"}}var fo=1e3;function po(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=me(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let a=s.searchParams.get("bodySHA256"),o="",d;if(a!==null){if(!_e(Buffer.from(a.toLowerCase()),Buffer.from(En("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let F=1;for(let W of t.body)if(W===38&&++F>fo)return"malformed_signature";let N=new Map;for(let[W,z]of new URLSearchParams(Sn(t.body))){let ie=N.get(W);ie||N.set(W,ie=new Set),ie.add(z)}let H=[];for(let W of[...N.keys()].sort()){let z=[...N.get(W)].sort();for(let ie of z)o+=W+ie;H.push([W,z.length===1?z[0]:z])}d=Object.fromEntries(H)}let f=s.protocol==="https:"?"443":"80",h=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,y=`${s.protocol}//${s.hostname}:${s.port||f}${s.pathname}${s.search}`;if(![h,y].some(F=>_e(r,Ze("sha1",e,F,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),T=k?{id:`${k}:${rs(`${h}
5
5
  ${o}`)}`}:{};return d?{type:ns("twilio",t.headers,d),event:d,...T}:{...ts("twilio",t),...T}}}function mo(e){let t;try{let n=me(e,"base64");if(!n)throw new Error;t=Yr({key:Buffer.from(n),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(n,r)=>{let s=n.headers.get("x-twilio-email-event-webhook-signature");if(!s)return"missing_signature";let a=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),o=ut(a),d=me(s.trim(),"base64");return o===void 0||!d?"malformed_signature":lt(o,r)?"stale_timestamp":Qr("sha256",ss(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var Vr=60;function ho(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let a=Zr(me(s[0],"base64url")),o=me(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!_e(o,Ze("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=Zr(me(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+Vr||typeof d.nbf=="number"&&n<d.nbf-Vr)return"stale_timestamp";let f=typeof d.sha256=="string"?me(d.sha256,"base64"):void 0;return f&&_e(f,En("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function go(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,a)=>{let o=s.headers.get(e.header);if(!o)return"missing_signature";if(e.prefix){if(!o.startsWith(e.prefix))return"malformed_signature";o=o.slice(e.prefix.length)}let d="";if(n.includes("{ts}")){d=s.headers.get(e.timestampHeader)?.trim()??"";let h=ut(d);if(h===void 0)return"malformed_signature";if(lt(h,a))return"stale_timestamp"}let f=me(o.trim(),e.encoding);return f?_e(f,Ze(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var yo=new TextEncoder;function Ze(e,t,...n){let r=no(e,t);for(let s of n)r.update(s);return r.digest()}function rs(e){return En("sha256").update(e).digest("hex")}function ss(e,t){return Buffer.concat([yo.encode(e),t])}function _e(e,t){return e.byteLength===t.byteLength&&ro(e,t)}var wo={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function me(e,t){return wo[t].test(e)?Buffer.from(e,t):void 0}function ut(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function lt(e,t){return Math.abs(t-e)>oo}function Sn(e){return new TextDecoder().decode(e)}function Zr(e){if(e)try{return JSON.parse(Sn(e))}catch{return}}function as(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function De(e,t){let n=as(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var V=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.41.0 — Palbase SDK License (see LICENSE) */
2
2
  var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{b}from"./Z5QBR46U.js";import{a as k,b as A}from"./Q4VZ2BNE.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} 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 B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,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 f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){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 t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},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 t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=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(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
1
+ /*! palbase 0.41.0 — Palbase SDK License (see LICENSE) */
2
+ import{b}from"./ITREUT6F.js";import{a as k,b as A}from"./QWFHHS3E.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} 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 B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,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 f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){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 t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},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 t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=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(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};