palbase 0.14.0 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) 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/{MDKUD5KF.js → 3AENUHVO.js} +2 -2
  8. package/dist/chunks/{VI7VITLG.js → 427AGWP3.js} +2 -2
  9. package/dist/chunks/{VYPEK5RA.js → 44ULNVPP.js} +1 -1
  10. package/dist/chunks/{YX4W5H7Q.js → 4UQ4J7RV.js} +2 -2
  11. package/dist/chunks/{JGUZOLS4.js → 5H7UNNH6.js} +2 -2
  12. package/dist/chunks/{R2FKMKIY.js → 6NC5RYCS.js} +1 -1
  13. package/dist/chunks/{DQ4XHMZN.js → 7DQ76T2V.js} +2 -2
  14. package/dist/chunks/{OIKBZFMC.js → A46IASZE.js} +2 -2
  15. package/dist/chunks/{FGKFL5W3.js → BRHGS5AI.js} +2 -2
  16. package/dist/chunks/{XA7ML545.js → CUL5OL4P.js} +2 -2
  17. package/dist/chunks/{7MGWLEW2.js → DIOZGDFQ.js} +1 -1
  18. package/dist/chunks/{XUX2HR4Z.js → HHZSOYPP.js} +1 -1
  19. package/dist/chunks/{QGGRIABQ.js → JKWWY2LJ.js} +2 -2
  20. package/dist/chunks/LUFWGH2V.js +2 -0
  21. package/dist/chunks/OMK2YEDZ.js +2 -0
  22. package/dist/chunks/{22WJEDHI.js → P67I4TNQ.js} +1 -1
  23. package/dist/chunks/{KOR6BP5M.js → PRJZTG2I.js} +1 -1
  24. package/dist/chunks/{UUS5URWX.js → QZH6GPCR.js} +2 -2
  25. package/dist/chunks/{AGZIRK5O.js → RD5JFDGQ.js} +2 -2
  26. package/dist/chunks/{FQV5NKI4.js → SBUC7GHR.js} +2 -2
  27. package/dist/chunks/{ZSICMUJY.js → W3OCV3QH.js} +2 -2
  28. package/dist/chunks/{OG5U5HFP.js → WXNFMEW7.js} +2 -2
  29. package/dist/chunks/{HQTKK3LU.js → ZZNGA77G.js} +1 -1
  30. package/dist/cli.js +130 -130
  31. package/dist/refuse/ai.js +1 -1
  32. package/dist/refuse/backend.js +1 -1
  33. package/dist/refuse/server.js +1 -1
  34. package/dist/server/index.js +2 -2
  35. package/dist/server/testing.js +2 -2
  36. package/dist/web/index.js +2 -2
  37. package/dist/web/message.js +2 -2
  38. package/dist/web/palbe.js +2 -2
  39. package/dist/web/paywall.js +2 -2
  40. package/dist/web/push-sw.js +1 -1
  41. package/dist/web/ssr.js +2 -2
  42. package/dist/web/vite.js +2 -2
  43. package/package.json +2 -2
  44. package/types/internal/src/modules/ai.d.ts +3 -7
  45. package/types/internal/src/modules/events.d.ts +4 -3
  46. package/types/internal/src/modules/index.d.ts +1 -0
  47. package/types/internal/src/modules/journeys.d.ts +1223 -0
  48. package/types/internal/src/modules/notify.d.ts +8 -0
  49. package/types/internal/src/modules/secrets.d.ts +1 -1
  50. package/types/internal/src/modules/stores.d.ts +777 -0
  51. package/types/server/src/transit.d.ts +8 -1
  52. package/dist/chunks/5LC7GWQ4.js +0 -2
  53. package/dist/chunks/XMJ4WMD2.js +0 -2
@@ -1,4 +1,4 @@
1
- /*! palbase 0.14.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
2
  var Rt=d=>[...new Uint8Array(d)].map(t=>t.toString(16).padStart(2,"0")).join(""),At=d=>`pw-font-${d}`;function ne(d){return(typeof d=="string"?/^asset:([0-9a-f-]{36})$/.exec(d):null)?.[1]}async function an(d,t={}){let a={},l=t.fetch??((c,p)=>globalThis.fetch(c,p));return await Promise.all(d.map(async c=>{try{if(!/^https:\/\//.test(c.url))return;let p=await l(c.url,{signal:t.signal,credentials:"omit"});if(!p.ok)return;let g=await p.arrayBuffer();if(g.byteLength!==c.bytes&&c.bytes>0||Rt(await globalThis.crypto.subtle.digest("SHA-256",g))!==c.sha256.toLowerCase())return;let w=_t(c.kind,new Uint8Array(g));if(w===void 0)return;let y=await Et(c,g,w,t);y&&(a[c.id]=y)}catch{}})),a}var C=(d,t,a=0)=>d.length>=a+t.length&&t.every((l,c)=>d[a+c]===l),W=d=>[...d].map(t=>t.charCodeAt(0));function _t(d,t){switch(d){case"image":return C(t,[137,80,78,71,13,10,26,10])?"image/png":C(t,[255,216,255])?"image/jpeg":C(t,W("RIFF"))&&C(t,W("WEBP"),8)?"image/webp":void 0;case"video":return C(t,W("ftyp"),4)?C(t,W("qt "),8)?"video/quicktime":"video/mp4":C(t,[26,69,223,163])?"video/webm":void 0;case"font":return C(t,W("wOF2"))?"font/woff2":C(t,W("wOFF"))?"font/woff":C(t,W("OTTO"))?"font/otf":C(t,[0,1,0,0])||C(t,W("true"))?"font/ttf":void 0;case"html":return C(t,[80,75,3,4])||C(t,[80,75,5,6])?"application/zip":void 0;default:return}}async function Et(d,t,a,l){switch(d.kind){case"image":case"video":return{kind:d.kind,url:URL.createObjectURL(new Blob([t],{type:a}))};case"font":{let c=At(d.id),p=globalThis.FontFace,g=l.fonts??globalThis.document?.fonts;if(!p||!g)return;let h=new p(c,t,{display:"block"});return await h.load(),g.add(h),{kind:"font",url:"",family:c}}case"html":{let c=await Lt(new Uint8Array(t)),p=Ot(c);return p===void 0?void 0:{kind:"html",url:"",html:p}}}}async function Lt(d){let t=new DataView(d.buffer,d.byteOffset,d.byteLength),a=-1;for(let h=d.length-22;h>=Math.max(0,d.length-22-65535);h--)if(t.getUint32(h,!0)===101010256){a=h;break}if(a<0)throw new Error("not a zip");let l=t.getUint16(a+10,!0),c=t.getUint32(a+16,!0),p=new Map,g=0;for(let h=0;h<l;h++){if(t.getUint32(c,!0)!==33639248)throw new Error("a broken zip");let w=t.getUint16(c+10,!0),y=t.getUint32(c+20,!0),m=t.getUint32(c+24,!0),v=t.getUint16(c+28,!0),_=t.getUint16(c+30,!0),P=t.getUint16(c+32,!0),R=t.getUint32(c+42,!0),x=new TextDecoder().decode(d.subarray(c+46,c+46+v));if(c+=46+v+_+P,x.endsWith("/"))continue;if(x.startsWith("/")||x.split("/").includes(".."))throw new Error("a path leaving the zip");if(g+=m,p.size>=200||g>20971520)throw new Error("a zip too large");let T=R+30+t.getUint16(R+26,!0)+t.getUint16(R+28,!0),O=d.subarray(T,T+y);if(w===0)p.set(x,O);else if(w===8)p.set(x,await Pt(O));else throw new Error("a zip entry compressed another way")}return p}async function Pt(d){let t=new Response(new Uint8Array(d)).body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}var Tt={html:"text/html",css:"text/css",js:"text/javascript",mjs:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};function qe(d,t){let a=Tt[d.split(".").pop()?.toLowerCase()??""]??"application/octet-stream",l="";for(let c=0;c<t.length;c+=32768)l+=String.fromCharCode(...t.subarray(c,c+32768));return`data:${a};base64,${btoa(l)}`}var $t="default-src 'none'; img-src data:; media-src data:; font-src data:; style-src 'unsafe-inline' data:; script-src 'unsafe-inline' data:";function Ot(d){let t=d.get("index.html");if(!t)return;let a=new TextDecoder().decode(t),l=y=>new TextDecoder().decode(d.get(y)),c=y=>{let m=y.replace(/^\.\//,"").split(/[?#]/)[0];return d.has(m)?m:void 0},p=y=>y.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(m,v,_)=>{let P=c(_);return P?`url("${qe(P,d.get(P))}")`:m}),g=globalThis.DOMParser;if(!g)return;let h=new g().parseFromString(a,"text/html");for(let y of[...h.querySelectorAll('link[rel~="stylesheet"][href]')]){let m=c(y.getAttribute("href")),v=h.createElement("style");v.textContent=m?p(l(m)):"",y.replaceWith(v)}for(let y of[...h.querySelectorAll("style")])y.textContent=p(y.textContent??"");for(let y of[...h.querySelectorAll("[src], [href], [poster]")])for(let m of["src","href","poster"]){let v=y.getAttribute(m);if(v===null)continue;let _=c(v);_?y.setAttribute(m,qe(_,d.get(_))):/^(https?:)?\/\//i.test(v)&&y.removeAttribute(m)}for(let y of[...h.querySelectorAll("[style]")])y.setAttribute("style",p(y.getAttribute("style")??""));let w=h.createElement("meta");return w.setAttribute("http-equiv","Content-Security-Policy"),w.setAttribute("content",$t),h.head.prepend(w),`<!doctype html>${h.documentElement.outerHTML}`}var K=(d,t,a)=>`M${d-a} ${t}a${a} ${a} 0 1 0 ${2*a} 0a${a} ${a} 0 1 0 ${-2*a} 0`,de={ad_free:["M3 7h18v10H3z","M4 4l16 16"],bell:["M6 16v-5a6 6 0 0 1 12 0v5l2 2H4z","M10 21a2 2 0 0 0 4 0"],bolt:["M13 2L4 14h7l-1 8 9-12h-7z"],book:["M5 4h11a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3z","M5 17a3 3 0 0 1 3-3h11"],chart:["M3 20h18","M6 20v-8","M11 20V5","M16 20v-6","M21 20V9"],chat:["M4 5h16v11H9l-5 4z"],check:["M5 12l5 5 9-10"],check_circle:[K(12,12,9),"M8 12l3 3 5-6"],clock:[K(12,12,9),"M12 7v5l3 2"],cloud:["M7 18a4 4 0 0 1-.5-7.97A6 6 0 0 1 18 9a4.5 4.5 0 0 1-.5 9z"],crown:["M3 8l4 4 5-7 5 7 4-4-2 11H5z"],download:["M12 4v11","M7 10l5 5 5-5","M4 20h16"],gift:["M3 9h18v4H3z","M5 13v8h14v-8","M12 9v12","M12 9C10 5 6 5 6 7.5S12 9 12 9zm0 0c2-4 6-4 6-1.5S12 9 12 9z"],globe:[K(12,12,9),"M3 12h18","M12 3a14 14 0 0 1 0 18a14 14 0 0 1 0-18z"],heart:["M12 20s-7-4.5-9-9a4.5 4.5 0 0 1 9-3 4.5 4.5 0 0 1 9 3c-2 4.5-9 9-9 9z"],infinity:["M7 9a3 3 0 1 0 0 6c3 0 7-6 10-6a3 3 0 1 1 0 6c-3 0-7-6-10-6z"],lock_open:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 7.5-2"],music:["M9 18V5l11-2v13",K(6,18,3),K(17,16,3)],people:[K(9,8,3.5),"M2 20a7 7 0 0 1 14 0","M16 4.5a3.5 3.5 0 0 1 0 7","M18 14a6 6 0 0 1 4 6"],person:[K(12,8,4),"M4 21a8 8 0 0 1 16 0"],photo:["M3 5h18v14H3z",K(8.5,9.5,1.5),"M3 17l5-5 4 4 3-3 6 6"],shield:["M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"],sparkles:["M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z","M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"],star:["M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3l-5.5 2.9 1-6.2L3 9.6l6.2-.9z"],video:["M3 6h12v12H3z","M15 10l6-3v10l-6-3z"],arrow_right:["M4 12h15","M13 6l6 6-6 6"],calendar:["M4 6h16v15H4z","M4 10h16","M8 3v5","M16 3v5"],close:["M6 6l12 12","M18 6L6 18"],lock:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 8 0v4"],play:["M7 4l13 8-13 8z"],quote:["M5 17c3 0 4-2 4-5V7H4v5h3","M15 17c3 0 4-2 4-5V7h-5v5h3"],trophy:["M7 4h10v5a5 5 0 0 1-10 0z","M7 6H4v2a3 3 0 0 0 3 3","M17 6h3v2a3 3 0 0 1-3 3","M12 14v4","M8 21h8","M9 18h6v3H9z"]};var Be="http://www.w3.org/2000/svg";function pe(d,t,a){let l=d.createElementNS(Be,"svg");l.setAttribute("viewBox","0 0 24 24"),l.setAttribute("width",String(a)),l.setAttribute("height",String(a)),l.setAttribute("fill","none"),l.setAttribute("stroke","currentColor"),l.setAttribute("stroke-width","2"),l.setAttribute("stroke-linecap","round"),l.setAttribute("stroke-linejoin","round"),l.setAttribute("aria-hidden","true"),l.setAttribute("focusable","false");for(let c of t){let p=d.createElementNS(Be,"path");p.setAttribute("d",c),l.append(p)}return l}var dn=2,pn=2,f=(d,t=!1)=>({kind:"value",value:"plain",def:d,required:t}),j=d=>({kind:"value",value:"color",def:d}),We=d=>({kind:"value",value:"spacing",def:d}),zt=d=>({kind:"value",value:"radius",def:d}),X=(d=!1)=>({kind:"text",required:d}),Me=(d,t=!1)=>({kind:"list",item:d,required:t}),se=(d,t=!1)=>({kind:"object",item:d,required:t}),Ke=(d=!1)=>({kind:"component",required:d}),Re={kind:"components"},Ge={stack:{axis:f("vertical"),spacing:We(0),align:f("center"),distribution:f("start"),scroll:f(!1),children:Re},text:{text:X(),spans:Me("span"),font:f(),size:f(),weight:f(),line_height:f(),letter_spacing:f(),color:{kind:"value",value:"textColor",def:"text"},align:f("center"),max_lines:f(),uppercase:f(!1)},image:{src:f(void 0,!0),fit:f("fit"),aspect:f(),mask:se("mask"),overlay:{kind:"value",value:"textColor"},alt:X(),decorative:f(!1)},icon:{name:f(void 0,!0),color:j("accent"),size:f(24)},video:{src:f(void 0,!0),poster:f(),autoplay:f(!0),loop:f(!0),mute:f(!0),controls:f(!1),fit:f("fill"),aspect:f(),alt:X()},button:{action:se("action",!0),content:Ke(!0)},purchase_button:{content:Ke(!0),package:f()},package:{product:f(void 0,!0),plan:f(void 0,!0),selected:f(!1),offer:f(),children:Re},tabs:{},switch:{},carousel:{pages:Re,peek:f(0),spacing:f(8),loop:f(!1),auto_advance_ms:f(),indicator:se("indicator"),height:f("")},countdown:{},timeline:{items:Me("timeline_item",!0),line_color:j("accent"),line_width:f(2),icon_color:j("on_accent"),color:j("text"),spacing:f(16)},features:{items:Me("feature",!0),icon_color:j("accent"),color:j("text"),spacing:f(12)},spacer:{size:We()},divider:{color:j("muted"),thickness:f(1)},custom_html:{src:f(void 0,!0),height:f("",!0)}},Ht={style:{padding:{kind:"edges"},margin:{kind:"edges"},width:f(""),height:f(""),max_width:f(),background:{kind:"fill"},border:se("border"),corners:{kind:"corners"},shadow:se("shadow"),opacity:f(1)},border:{width:f(),color:j("")},shadow:{color:j(""),radius:f(0),x:f(0),y:f(0)},linear:{type:f(""),angle:f(180),stops:f()},radial:{type:f(""),center_x:f(.5),center_y:f(.5),radius:f(.5),stops:f()},image_fill:{type:f(""),src:f(),fit:f("fill")},video_fill:{type:f(""),src:f(),poster:f(),loop:f(!0)},animation:{type:f(""),duration_ms:f(300),delay_ms:f(0),easing:f("ease_out")},action:{type:f(""),url:f(),sheet:f(),package:f()},mask:{shape:f(""),radius:zt(0),depth:f(16)},span:{text:X(!0),bold:f(!1),italic:f(!1),underline:f(!1),strikethrough:f(!1),color:j(""),link:f()},timeline_item:{icon:f(void 0,!0),title:X(!0),text:X(),color:j("")},feature:{icon:f(void 0,!0),text:X(!0)},indicator:{style:f("dots"),color:j("muted"),active_color:j("accent"),size:f(8),spacing:f(6)},typography:{font:f("system"),size:f(),weight:f(400),line_height:f(),letter_spacing:f(0),text_style:f("body")}},Xe=new Set(["package","purchase_button"]),Ct={action:{type:f(""),url:f(),link:f(),sheet:f(),placement:f(),name:f(),value:f(),offer:f(),dismiss:f(!0)},presentation:{type:f(""),position:f("bottom"),auto_dismiss_seconds:f(),dismissible:f(!0),backdrop:j("#00000080")}},jt={modal:["type","dismissible","backdrop"],fullscreen:["type"],banner:["type","position","auto_dismiss_seconds","dismissible"],card:["type"]},Ft={linear:"linear",radial:"radial",image:"image_fill",video:"video_fill"},Nt=["top","bottom","leading","trailing"],Dt=["top_leading","top_trailing","bottom_leading","bottom_trailing"],Jt=Object.keys(Ge),un=Jt.filter(d=>!Xe.has(d)),Ye=/\{\{\s*([^{}]*?)\s*\}\}/g,Q=(d,t)=>typeof d=="object"&&d!==null&&Object.hasOwn(d,t),M=d=>typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{},I=d=>Array.isArray(d)?d:[],G=(d,t)=>d??t;function It(d){let t="";for(let a of new TextEncoder().encode(d)){let l=String.fromCharCode(a);t+=/^[A-Za-z0-9._~-]$/.test(l)?l:`%${a.toString(16).toUpperCase().padStart(2,"0")}`}return t}function Vt(d){let t=Math.floor(d/86400),a=Math.floor(d%86400/3600),l=Math.floor(d%3600/60),c=d%60,p=h=>String(h).padStart(2,"0");return{countdown:t>0?`${t}d ${p(a)}:${p(l)}:${p(c)}`:a>0?`${a}:${p(l)}:${p(c)}`:`${p(l)}:${p(c)}`,days:String(t),hours:p(a),minutes:p(l),seconds:p(c)}}function fn(d){let t=[],a=c=>{if(Array.isArray(c))return c.forEach(a);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.product=="string"&&typeof p.plan=="string"){let g=`${p.product}.${p.plan}`;t.includes(g)||t.push(g)}for(let g of Object.keys(p).sort())a(p[g])},l=d;for(let c of["header","root","footer"])a(l[c]);for(let c of Object.keys(M(l.sheets)).sort())a(M(M(l.sheets)[c]).root);return t}function Ut(d){let t=new Map,a=c=>{if(Array.isArray(c))return c.forEach(a);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.offer=="string"){let g=`${p.product}.${p.plan}`;t.has(g)||t.set(g,p.offer)}for(let g of Object.keys(p).sort())a(p[g])},l=d;for(let c of["header","root","footer","sheets"])a(l[c]);return t}function gn(d,t){return _e(d,t).tree}function _e(d,t){return new ue("paywall",d,t).resolve()}function hn(d,t){return Ee(d,t).tree}function Ee(d,t){let{variables:a,...l}=t;return new ue("message",d,{...l,packages:{"":{...a}}}).resolve()}var ue=class{kind;d;opts;lang;texts={};palette;typography={};radii;spacing;packages;offers;selected="";tab="";paths=new WeakMap;tabsShown={};switchesOn={};countdowns={};constructor(t,a,l){this.kind=t,this.d=a,this.opts=l,this.offers=Ut(a);let c={};for(let[y,m]of Object.entries(l.packages??{})){let v={...m};this.open(y)||(m.price!==void 0?v.offer_price=m.price:delete v.offer_price),c[y]=v}this.packages=c;let p=M(this.d.locales),g=String(this.d.default_locale??""),h=l.locale;Q(p,h)||(h=h.split("-")[0]??"",Q(p,h)||(h=g)),this.lang=h;for(let y of[g,h])for(let[m,v]of Object.entries(M(p[y])))typeof v=="string"&&(this.texts[m]=v);let w=M(this.d.theme);this.palette=M(M(w.colors)[l.appearance]);for(let[y,m]of Object.entries(M(w.typography))){let v={};for(let[_,P]of Object.entries(this.objectFields("typography"))){let R=G(M(m)[_],P.def);R!=null&&(v[_]=R)}this.typography[y]=v}this.radii=M(w.radii),this.spacing=M(w.spacing)}open(t){let a=this.offers.get(t);return a!==void 0&&(this.opts.offers??[]).includes(a)}fields(t){if(!(this.kind==="message"&&Xe.has(t)))return Ge[t]}objectFields(t){return(this.kind==="message"?Ct[t]:void 0)??Ht[t]??{}}resolve(){let[t,a]=this.initialState();this.tab=t,this.selected=this.kind==="paywall"?a:"";let l={theme:{colors:this.palette,typography:this.typography,radii:this.radii,spacing:this.spacing}};this.kind==="paywall"&&(l.selected=a);let c=this.d.presentation;if(typeof c=="object"&&c!==null){let g=this.item("presentation",M(c),void 0)??{},h=jt[String(M(c).type)]??[];for(let w of Object.keys(g))h.includes(w)||delete g[w];l.presentation=g}for(let g of["header","root","footer"]){let h=this.d[g];if(typeof h=="object"&&h!==null){let w=this.component(M(h),g,"",!1);w&&(l[g]=w)}}let p={};if(typeof this.d.sheets=="object"&&this.d.sheets!==null){let g={};for(let[h,w]of Object.entries(M(this.d.sheets))){let y=this.component(M(M(w).root),`sheets.${h}.root`,"",!1);y&&(g[h]=y);let m=this.text(M(w).title,this.packages[this.selected]);m!==null&&(p[h]=m)}l.sheets=g}return{tree:l,pathOf:g=>this.paths.get(g),tabs:this.tabsShown,switches:this.switchesOn,sheetTitles:p,countdowns:this.countdowns,language:this.lang}}switchOn(t,a){return this.opts.switches&&Object.hasOwn(this.opts.switches,a)?this.opts.switches[a]:this.opts.switch?this.opts.switch==="on":t.default===!0}tabShown(t,a){let c=I(t.tabs).map(M).map(g=>String(g.id)),p=this.opts.tabs?.[a];return p!==void 0&&c.includes(p)?p:this.opts.tab?this.opts.tab:typeof t.default=="string"&&t.default!==""?t.default:c[0]??""}initialState(){let t="",a="",l="",c="",p=(h,w)=>{if(Array.isArray(h)){h.forEach((m,v)=>p(m,`${w}[${v}]`));return}if(typeof h!="object"||h===null)return;let y=h;switch(y.type){case"package":{let m=`${y.product}.${y.plan}`;l===""&&(l=m),y.selected===!0&&a===""&&(a=m);break}case"switch":{let m=this.switchOn(y,w),v=m?y.on_package:y.off_package;typeof v=="string"&&c===""&&(c=v),p(m?y.on:y.off,`${w}.${m?"on":"off"}`);return}case"tabs":{let m=this.tabShown(y,w);t===""&&(t=m),I(y.tabs).forEach((v,_)=>{let P=M(v);P.id===m&&(typeof P.package=="string"&&c===""&&(c=P.package),p(P.content,`${w}.tabs[${_}].content`))});return}}for(let m of Object.keys(y).sort())m!=="sheets"&&p(y[m],w===""?m:`${w}.${m}`)};for(let h of["header","root","footer"])p(this.d[h],h);let g=this.opts.selected||c||a||l;return[t,g]}holds(t,a){let l=a||this.selected;for(let[c,p]of Object.entries(t))switch(c){case"selected_package":if(!I(p).includes(this.selected))return!1;break;case"intro_eligible":if((this.opts.eligible??[]).includes(l)!==p)return!1;break;case"offer_open":if(this.open(l)!==p)return!1;break;case"platform":if(!I(p).includes(this.opts.platform))return!1;break;case"locale":if(!I(p).includes(this.opts.locale)&&!I(p).includes(this.lang))return!1;break;case"appearance":if(p!==this.opts.appearance)return!1;break;case"tab":if(p!==this.tab)return!1;break}return!0}component(t,a,l,c){if(typeof t.visible=="object"&&t.visible!==null&&!this.holds(M(t.visible),l))return null;let p=String(t.type),g=l,h=c;p==="package"&&(g=`${t.product}.${t.plan}`,h=g===this.selected);let w={type:p};this.paths.set(w,a),Q(t,"id")&&(w.id=t.id);let y={...M(t.style)};h&&Object.assign(y,M(M(t.states).selected)),Object.keys(y).length>0&&(w.style=this.style(y)),typeof t.animation=="object"&&t.animation!==null&&(w.animation=this.defaults(M(t.animation),this.objectFields("animation")));let m=this.packages[g||this.selected];switch(p){case"tabs":return this.tabs(t,w,a,g);case"switch":return this.switchOf(t,w,a,g,h);case"countdown":return this.countdown(t,w,a,g,h);case"purchase_button":{let v=typeof t.package=="string"?t.package:this.selected;w.package=v,this.open(v)&&(w.offer=this.offers.get(v));let _=this.component(M(t.content),`${a}.content`,v,h);return _?(w.content=_,w):null}case"package":w.product=t.product,w.plan=t.plan,w.selected=h,typeof t.offer=="string"&&(this.opts.offers??[]).includes(t.offer)&&(w.offer=t.offer)}for(let[v,_]of Object.entries(this.fields(p)??{})){if(p==="package"&&(v==="product"||v==="plan"||v==="selected"||v==="offer"))continue;let P=t[v],R=Q(t,v);switch(_.kind){case"component":{if(!R)continue;let x=this.component(M(P),`${a}.${v}`,g,h);if(!x&&_.required)return null;x&&(w[v]=x);break}case"components":{let x=[];I(P).forEach((T,O)=>{let V=this.component(M(T),`${a}.${v}[${O}]`,g,h);V&&x.push(V)}),w[v]=x;break}case"text":{let x=this.text(P,m);if(x!==null)w[v]=x;else if(_.required||p==="text"&&v==="text"&&R)return null;break}case"list":{let x=[];for(let T of I(P)){let O=this.item(_.item,M(T),m);O&&x.push(O)}if(p==="text"&&x.length===0&&R)return null;R&&(w[v]=x);break}case"object":{if(R){let x=this.object(M(P),_.item,m);if(x===null&&_.required)return null;w[v]=x}else v==="indicator"&&(w[v]=this.object({},_.item,m));break}case"value":{let x=this.value(G(P,_.def),_);x!=null&&x!==""&&(w[v]=x);break}}}return p==="text"&&this.typeStyle(w),w}typeStyle(t){if(typeof t.size!="string"){t.size!==void 0&&t.size!==null&&(t.text_style="body");return}let a=this.typography[t.size];for(let l of["font","weight","line_height","letter_spacing","text_style"])!Q(t,l)&&a?.[l]!==void 0&&a?.[l]!==null&&(t[l]=a[l]);t.size=a?.size??null}tabs(t,a,l,c){let p=this.tabShown(t,l);this.tabsShown[l]=p;let g=[];return I(t.tabs).forEach((h,w)=>{let y=M(h),m=y.id===p,v=this.component(M(y.label),`${l}.tabs[${w}].label`,c,m);if(g.push({id:y.id,selected:m,label:v}),m){let _=this.component(M(y.content),`${l}.tabs[${w}].content`,c,!1);_&&(a.content=_)}}),a.tabs=g,typeof t.bar=="object"&&t.bar!==null&&(a.bar=this.style(M(t.bar))),a}switchOf(t,a,l,c,p){let g=this.switchOn(t,l);this.switchesOn[l]=g,a.on=g;let h=this.text(t.label,this.packages[c||this.selected]);h!==null&&(a.label=h),a.tint=this.color(String(G(t.tint,"accent")));let w=g?"on":"off",y=this.component(M(t[w]),`${l}.${w}`,c,p);return y&&(a.content=y),a}countdown(t,a,l,c,p){let g=M(t.target),h=this.opts.now??Date.now(),w;if(typeof g.after_open_seconds=="number"?w=Math.trunc(g.after_open_seconds)-(this.opts.openedSecondsAgo??0):w=Math.trunc((Date.parse(String(g.at))-h)/1e3),w>0){a.state="counting",a.remaining_seconds=w,this.countdowns[l]=w;let y=this.packages,m={};for(let[_,P]of Object.entries(y))m[_]={...P,...Vt(w)};this.packages=m;let v=this.component(M(t.counting),`${l}.counting`,c,p);return v&&(a.content=v),this.packages=y,a}if(a.state="ended",a.remaining_seconds=0,typeof t.ended=="object"&&t.ended!==null){let y=this.component(M(t.ended),`${l}.ended`,c,p);y&&(a.content=y)}return a}item(t,a,l){let c={};for(let[p,g]of Object.entries(this.objectFields(t))){let h=a[p];if(g.kind==="text"){let w=this.text(h,l);if(w!==null)c[p]=w;else if(g.required)return null}else{let w=g.def,y=this.value(G(h,w),g);y!=null&&(Q(a,p)||w!=null&&w!=="")&&(c[p]=y)}}return c}object(t,a,l){if(a==="style")return this.style(t);let c=this.item(a,t,l)??{};if(a==="action")for(let p of["url","link"]){if(typeof c[p]!="string")continue;let g=qt(c[p],l);if(g===null)return null;c[p]=g}return c}defaults(t,a){let l={};for(let[c,p]of Object.entries(a)){let g=G(t[c],p.def);g!=null&&g!==""&&(l[c]=g)}return l}style(t){let a={};for(let[l,c]of Object.entries(t)){let p=this.objectFields("style")[l];if(!p){a[l]=c;continue}switch(p.kind){case"edges":a[l]=this.sides(c,Nt,this.spacing);break;case"corners":a[l]=this.sides(c,Dt,this.radii);break;case"fill":a[l]=this.fill(c);break;case"object":{let g=M(c),h={};for(let[w,y]of Object.entries(this.objectFields(p.item))){let m=G(g[w],y.def);m!=null&&m!==""&&(h[w]=this.value(m,y))}a[l]=h;break}default:a[l]=c}}return a}sides(t,a,l){let c={};for(let p of a){let g=typeof t=="object"&&t!==null?G(M(t)[p],0):t;c[p]=Ae(g,l)}return c}fill(t){if(typeof t=="string")return{type:"color",color:this.color(t)};let a=M(t),l=this.defaults(a,this.objectFields(Ft[String(a.type)]??""));return Array.isArray(a.stops)&&(l.stops=a.stops.map(c=>({color:this.color(String(M(c).color)),at:M(c).at}))),l}value(t,a){if(a.kind!=="value")return t;switch(a.value){case"color":return typeof t=="string"&&t!==""?this.color(t):t;case"textColor":return typeof t=="string"?this.color(t):t==null?t:this.fill(t);case"spacing":return Ae(t,this.spacing);case"radius":return Ae(t,this.radii);default:return t}}color(t){let a=Object.hasOwn(this.palette,t)?this.palette[t]:void 0;return typeof a=="string"?a:t}text(t,a){let l;if(typeof t=="string")l=t;else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let p=t.t;l=typeof p=="string"&&Object.hasOwn(this.texts,p)?this.texts[p]:""}else return null;let c=!1;return l=l.replace(Ye,(p,g)=>{let h=a&&Object.hasOwn(a,g)?a[g]:void 0;return typeof h!="string"||h===""?(c=!0,""):h}),c||l.trim()===""?null:l}};function qt(d,t){let a=!1,l=d.replace(Ye,(c,p)=>{let g=t&&Object.hasOwn(t,p)?t[p]:void 0;return typeof g!="string"||g===""?(a=!0,""):It(g)});return a?null:l}function Ae(d,t){return typeof d=="string"?Object.hasOwn(t,d)?t[d]:null:d}var Bt={packages:"Choose a plan",close:"Close",restore:"Restore purchases",page:(d,t)=>`${d} of ${t}`},ee={system:'-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',rounded:'ui-rounded, "SF Pro Rounded", Nunito, "Varela Round", system-ui, -apple-system, sans-serif',serif:'ui-serif, "New York", "Iowan Old Style", Georgia, "Times New Roman", serif',mono:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace'},Wt=1.35,Ze=20,Kt=new Set(["button","purchase_button","package","text"]),Gt=new Set(["ar","he","fa","ur","ps","yi","dv","ug","ku","sd"]),Qe={ease_out:"cubic-bezier(0.16, 1, 0.3, 1)",ease_in_out:"cubic-bezier(0.65, 0, 0.35, 1)",spring:"cubic-bezier(0.34, 1.56, 0.64, 1)"},Xt={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"},Yt={start:"flex-start",center:"center",end:"flex-end",space_between:"space-between",space_around:"space-around",space_evenly:"space-evenly"},Zt={stack:["children"],package:["children"],button:["content"],purchase_button:["content"],tabs:["tabs","content"],switch:["content"],carousel:["pages"],countdown:["content"]},Qt={package:["selected"],purchase_button:["package"],switch:["on"],countdown:["state","remaining_seconds"]},en=`
3
3
  :host{display:block;height:100%}
4
4
  .pw2{position:relative;box-sizing:border-box;display:flex;flex-direction:column;height:100%;overflow:hidden;font-family:${ee.system};font-size:1rem;line-height:1.3;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;text-rendering:optimizeLegibility}
@@ -1,5 +1,5 @@
1
- /*! palbase 0.14.0 — Palbase SDK License (see LICENSE) */
2
- import{a as xt,c as ne,d as rr,e as sr,f as ye,h as S,i as cr}from"./FQV5NKI4.js";import{c as ar,d as or,e as Yt,f as ir,g as dr}from"./XA7ML545.js";import{a as Qn,e as it,g as Et,h as Xn,i as er,j as St,k as _t,n as tr,t as nr}from"./5LC7GWQ4.js";import{a as $t,b as Zn,n as Yn}from"./HQTKK3LU.js";import{b as oe}from"./QGGRIABQ.js";import"reflect-metadata";var Qt=[{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}],ur="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)",Rt=/^\d+$/;function ra(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 w=s.slice(a+1);if(!Rt.test(w)||Number(w)<1||Number(w)>n)return;d=Number(w)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let w=o.indexOf("-"),k=o.slice(0,w),_=o.slice(w+1);if(!Rt.test(k)||!Rt.test(_)||Number(k)<t||Number(_)>n||Number(k)>Number(_))return;l=Number(k),h=Number(_)}else{if(!Rt.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let w=l;w<=h;w+=d)r.add(w)}return r}function lr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${ur}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let w=ra(t[h],Qt[h].lo,Qt[h].hi);if(!w)return`${ur}; its ${Qt[h].name} "${t[h]}" is not one`;n.push(w)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let w=r.has(l.getUTCDate()),k=a.has(l.getUTCDay());if(o||d?w&&k:w||k)return}return`"${e}" is never due: no date has that day in that month`}var Ue=Symbol.for("palbase.backend.controller"),Le=Symbol.for("palbase.backend.routes"),en=Symbol.for("palbase.backend.params"),tn=Symbol.for("palbase.backend.injectable"),nn=Symbol.for("palbase.backend.module"),Re=Symbol.for("palbase.backend.events"),Ie=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),we=Symbol.for("palbase.backend.tasks"),ke=Symbol.for("palbase.backend.testUserTemplates");function ie(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var Xt=Symbol.for("palbase.backend.declared");function re(){let e=globalThis;return e[Xt]instanceof Set||(e[Xt]=new Set),e[Xt]}var ze=new Set(["webhooks","_palbase"]);function Ki(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&ze.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ie(n,Ue,()=>({basePath:e,options:t})),re().add(n)}}function qe(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`);ie(r.constructor,Le,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var Ji=qe("GET"),Bi=qe("POST"),Wi=qe("PUT"),Vi=qe("PATCH"),Zi=qe("DELETE"),Yi=qe("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=ie(n.constructor,en,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function rn(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 Qi=e=>ue("body",{schema:rn("Body",e)}),Xi=e=>ue("query",{schema:rn("QueryParams",e)}),ed=e=>ue("headers",e===void 0?{}:{schema:rn("Headers",e)}),td=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},nd=()=>ue("user"),rd=()=>ue("optionalUser"),sd=()=>ue("req"),ad=()=>ue("requestId"),od=()=>ue("requestId"),id=()=>ue("client");function dd(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 cd(){return e=>{ie(e,tn,()=>!0),re().add(e)}}function ud(e){return t=>{ie(t,nn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var mr=/^[a-z]+(\.[a-z_]+)+$/,sa=/^[a-z][a-z0-9-]{1,62}$/,sn=e=>e.startsWith("file.");function ld(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"||!sa.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(!sn(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`);ie(r.constructor,Re,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),re().add(r.constructor)}}var an=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,aa=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function fr(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(!aa.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 fd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!an.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=lr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||fr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${fr(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}),re().add(a)}}var pr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],oa=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function pd(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(!oa.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&&!pr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${pr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&ia(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=M(t,Re)??[];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)}ie(t,Ie,()=>({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}))})),re().add(t)}}function ia(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function md(){return[...re()].filter(e=>M(e,Ue)!==void 0)}function hd(e){return(M(e,Le)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var At=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function kd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!an.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,we))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,we,{value:r,enumerable:!1}),re().add(s)}}var cn;function gr(e){cn=e}function on(){if(!cn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return cn}var da=720*3600;function ca(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>da))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 ua(e){if(typeof e=="string")return e;let t=e[we];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var vd=xt("Tasks",{async enqueue(e,t,n={}){return ca(n),on().enqueue(ua(e),t===void 0?null:t,n)},async cancel(e,t={}){return on().cancel(e,t.machine)},async get(e,t={}){return on().get(e,t.machine)}}),dn=(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 yr(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 ye.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 dn(a.data,a.status===200)},async cancel(n,r){return dn((await ye.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return dn((await ye.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var la=1e4,fa=36e5,hr=24*36e5,Ot=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 oe({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 oe({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 oe({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<hr))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new oe({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 oe({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(la*2**Math.min(t.attempt-1,16),fa),S.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>=hr&&this.tasks.delete(s);n==="failed"&&S.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 Pt="/_palbase/test-user-templates",pa=/^[a-z][a-z0-9_-]{0,63}$/;function Sd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!pa.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}),re().add(s)}}function wr(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 br(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof oe&&n.status===404)return!1;throw n}}var ma="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 kr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,ma),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var un="/_palbase/storage/upload/authorize",vr="/_palbase/storage/upload/complete",ln="/_palbase/realtime/rooms";var ha=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function He(e){if(!ha(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 Tr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function $r(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Ct(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var ga=/^[a-z][a-z0-9-]{1,62}$/,Er=1024,ya=new Set(["userId","uploadId","filename"]);function Od(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(!ga.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=wa(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,l)=>{if(typeof d!="string"||l===void 0||typeof l.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ie(o.constructor,Le,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function Pd(){return ue("uploadedObject")}function wa(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!ya.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!Sr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Sr(e){if(e===""||new TextEncoder().encode(e).byteLength>Er)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 ba(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>ka(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function ka(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 _r(e,t){let n=ba(e,t);return Sr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Er} bytes)`}}function xr(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 fn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Rr(e,t){if(!fn(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=He(t.user);if(!o)return"user is { id?, session?, role }";let d=Tr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=va(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function va(e){if(!fn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:w}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!fn(w)||!Object.values(w).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...w}}}import{markData as Ta}from"palgres";var Ae=Symbol.for("palbase.backend.gateway"),Ke=Symbol.for("palbase.backend.gatewayHooks"),Ar={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"]},$a={"~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(Ar),output:()=>structuredClone(Ar)}}},Nr=Symbol.for("palbase.backend.gatewayRefusal"),Or=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,Nr,{value:!0})}},Ea=e=>typeof e=="object"&&e!==null&&e[Nr]===!0&&typeof e.reason=="string",Fe=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Sa=6e4,_a=86400,Pr=604800,Cr=65536,$e=255,xa=["roles:","flags:","messaging:","debug:"],Ra=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(" ")),Ge=e=>new TextEncoder().encode(e).byteLength,pn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",gn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Aa(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(Ge(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=xa.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 Ur(e){if(typeof e!="string"||e==="")return"is a name";if(Ge(e)>$e)return`is ${$e} bytes at most`}function Ud(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Aa(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"&&gn(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=Oa(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)||Ra.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[w,k]of Object.entries(d)){let _=Ur(w);if(_)throw new TypeError(`@Gateway("${e}") on ${o}: event "${w}" ${_}`);if(!pn(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${w}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=ie(a,Ke,yn),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:$a}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Sa,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&Fe(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&&!Fe(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`);ie(a,Ae,()=>h),re().add(a)}}function Oa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return _a;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Pr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Pr} (a week)`);return n}var yn=()=>({hooks:Object.create(null),messages:Object.create(null)}),Pa={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function dt(e){let t=Pa[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=ie(n.constructor,Ke,yn),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,re().add(n.constructor)}}var Ld=dt("authorize"),Id=dt("first"),zd=dt("connect"),qd=dt("disconnect"),Hd=dt("empty");function Fd(e,t,n={}){let r=Ur(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!pn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!pn(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=ie(s.constructor,Ke,yn),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},re().add(s.constructor)}}function Ca(e){return M(e,Ae)}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 Lr(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 Ge(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Ma(e,t,n){let r=gn(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))?Lr(e,t):Da(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 Da(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 Na=1e4,Ua=1e3,La=100,wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),he=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),jr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Mr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Ir(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:E}of e){let m=Ca(b),v=a.get(m.name);if(v!==void 0&&v!==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 C=s.get(Mr(m.pattern));if(C!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: ${n.get(C)?.cls.name}'s "${C}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Mr(m.pattern),m.pattern);for(let[J,B]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([L,N])=>[`message ${L}`,N.fn])])if(typeof E[B]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: its ${J} is ${B}, which is no method of it`);let U={cls:b,instance:E,g:m};n.set(m.pattern,U),r.set(b,U)}let o=new Map,d=new Set,l=new Set,h=new hn(t.broadcast),w=b=>{let E=o.get(b);return E||(E=new AbortController,o.set(b,E)),E},k=(b,E)=>{E?.abort(),o.get(b)===E&&o.delete(b)},_=(b,E,m,v,C,U)=>{if(!Object.hasOwn(b.g.events,m)){S.warn(`[palbase] ${C}: emit("${m}") is not sent \u2014 ${b.cls.name} declares no event "${m}" (static events)`);return}if(b.g.chat&&m==="chat"){S.warn(`[palbase] ${C}: 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:E,event:m,payload:v??{},...U!==void 0?{conn_id:U}:{}},C)},H=async(b,E,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(E)};function I(b,E,m,v,C,U,J){let B=v?.signal??AbortSignal.abort(),L=`${b.cls.name} (${E})`;return{channel:E,params:Object.freeze({...m}),signal:B,count:C,user:U,emit:(N,W)=>_(b,E,N,W,L,J),pipe:N=>H(N,E,L),owner:{hold(N){ne.exit(async()=>{try{await N(B)}catch(W){B.aborted||S.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:W})}}).catch(()=>{})},release:()=>k(E,v)}}}function D(b){let{room:E,channel:m}=b;if(typeof E!="string"||typeof m!="string")return he(400,"bad_request","A gateway's call names its pattern (room) and its channel");let v=n.get(E);return!v||!Fe(v.g)?he(404,"not_found",`This app serves no gateway "${E}"`):{entry:v,channel:m,params:ja(E,m)}}let Y=(b,E)=>he(400,"bad_request",`"${E}" is not a channel of the gateway "${b}"`);async function Q(b,E){let m=D(b);if("status"in m)return m;let{entry:v,channel:C,params:U}=m,J={status:200,body:{subscribe:!1,publish:!1}};if(!U)return S.warn(`[palbase] ${v.cls.name}: realtime asked about "${C}", which is not a channel of the gateway "${v.g.pattern}"; the join is refused`),J;let B=He(b.user),L=B?.id;if(!L)return J;if(v.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(v.g.messages).length>0}};if(v.g.access==="owner")return U[gn(v.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys(v.g.messages).length>0}}:J;let N=v.g.hooks.authorize;if(!N)return J;let W,G;try{W=await t.run(B,`${v.cls.name}.${N}`,E,async()=>v.instance[N]({user:{id:L},params:Object.freeze({...U})})),G=Ia(W)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return S.error(`[palbase] ${v.cls.name}.${N} (@Authorize of ${C}) failed; the join is refused`,{error:te}),J}return G==="malformed"?(S.warn(`[palbase] ${v.cls.name}.${N} (@Authorize of ${C}) answered ${za(W)}, which is no grant (true, { read, write } or null); the join is refused`),J):{status:200,body:G}}async function fe(b,E){let m=D(b);if("status"in m)return m;if(!m.params)return Y(m.entry.g.pattern,m.channel);let v=He(b.user);if(!v?.id||typeof b.event!="string")return he(400,"bad_request","A message names its member (user) and its event");let C=Object.hasOwn(m.entry.g.messages,b.event)?m.entry.g.messages[b.event]:void 0;if(!C)return{status:200,body:{ok:!1,reason:mn(`gateway "${m.channel}" takes no message "${b.event}"`,jt)}};let U=await C.schema["~standard"].validate(Ta(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:Dr(U.issues)}};let J=w(m.channel),B={...I(m.entry,m.channel,m.params,J,0,{id:v.id}),payload:U.value},L=`${m.entry.cls.name}.${C.fn} (@Subscribe "${b.event}" of ${m.channel})`,N;try{N=await t.run(v,`${m.entry.cls.name}.${C.fn}`,E,async()=>m.entry.instance[C.fn](B))}catch(G){if(t.isOutage(G))throw G;return Ea(G)?{status:200,body:{ok:!1,reason:mn(G.reason,jt)}}:(E?.aborted||S.error(`[palbase] ${L} failed`,{error:G}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(C.reply){let G=await C.reply["~standard"].validate(N);if(G.issues)return S.error(`[palbase] ${L} returned an ack its reply schema refuses (${Dr(G.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=G.value}let W;try{W=JSON.stringify(N)}catch(G){return S.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:G}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return W===void 0?{status:200,body:{ok:!0}}:Ge(W)>Cr?(S.error(`[palbase] ${L} returned an ack of ${Ge(W)} bytes, past ${Cr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(W)}}}async function pe(b,E){let m=D(b);if("status"in m)return m;if(!m.params)return Y(m.entry.g.pattern,m.channel);let v=b.event;if(typeof v!="string"||!Object.hasOwn(jr,v))return he(400,"bad_request","A gateway's moment is first, join, leave or empty");let C=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(C===void 0)return he(400,"bad_request","A gateway's moment says its count of members");let U=v==="join"||v==="leave",J=U?He(b.user):void 0,B=U?b.connId:void 0;if(U&&(!J?.id||typeof B!="string"||B===""))return he(400,"bad_request",`A ${v} names its member: user and connId`);let L=`${v}\0${m.channel}\0${typeof B=="string"?B:""}`;if(U&&d.has(L))return{status:204};if(l.has(L))return he(503,"in_progress","This moment of the gateway is being handled",5);l.add(L);try{let N=m.entry.g.hooks[jr[v]],W;if(v==="empty"?(W=o.get(m.channel),k(m.channel,W)):W=v==="leave"?o.get(m.channel):w(m.channel),N){let G=I(m.entry,m.channel,m.params,W,C,{id:J?.id??""},v==="join"?B:void 0);try{await t.run(J,`${m.entry.cls.name}.${N}`,E,async()=>m.entry.instance[N](G))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||S.error(`[palbase] ${m.entry.cls.name}.${N} (${v} of ${m.channel}) failed; realtime tells it again`,{error:te}),he(500,"handler_failed",`The gateway's ${v} could not be handled`)}}return U&&(d.add(L),d.size>Na&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(L)}}function be(b,E){let m=r.get(b),v=`Palbase.gateways.to(${b?.name??String(b)})`;if(!m)throw new TypeError(`${v}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let C=Lr(m.g.pattern,E??{});if(typeof C!="string")throw new TypeError(`${v}: ${C.problem}`);return{entry:m,channel:C,where:v}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,E,m){return wn(E)?b==="authorize"?Q(E,m):b==="message"?fe(E,m):b==="lifecycle"?pe(E,m):he(404,"not_found",`No gateway call ${JSON.stringify(b)}`):he(400,"bad_request","A gateway's call is a JSON object")},emit(b,E,m,v){let{entry:C,channel:U,where:J}=be(b,E);_(C,U,m,v,J)},async pipe(b,E,m){let{channel:v,where:C}=be(b,E);await H(m,v,C)},async revalidate(b,E,m={}){let v=r.get(b),C=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!v)throw new TypeError(`${C}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let U=Ma(v.g.pattern,E??{},m);if("problem"in U)throw new TypeError(`${C}: ${U.problem}`);await t.revalidate(U)},close(){for(let b of o.values())b.abort();o.clear()}}}function Ia(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!wn(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 za(e){return Array.isArray(e)?"an array":wn(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 qa=20,jt=256;function Dr(e){let t="";for(let n of e.slice(0,qa)){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)>=jt)break}return mn(t,jt)}function mn(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 hn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ge(t.event)>$e){S.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){S.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>=Ua?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,La);try{await this.broadcast(s)}catch(o){S.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),S.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as bn,createHmac as Ha,createPublicKey as Fr,timingSafeEqual as Fa,verify as Gr}from"node:crypto";function Bd(e){let t=M(e,Ie);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 Kr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=M(o,Ie),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,w=n[d.secret.env],k;if(r.secrets!==!1)if(w===void 0||w==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=Ga(d,w)}catch(I){a.push(`${h}: ${d.secret.env} ${I.message}`)}let _=t(o),H=new Map(d.events.map(({event:I,fn:D})=>[I,{name:`${o.name}.${D}`,call:(Y,Q)=>_[D](Y,Q)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:H})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
+ import{a as xt,c as ne,d as rr,e as sr,f as ye,h as S,i as cr}from"./SBUC7GHR.js";import{c as ar,d as or,e as Yt,f as ir,g as dr}from"./CUL5OL4P.js";import{a as Qn,e as it,g as Et,h as Xn,i as er,j as St,k as _t,n as tr,t as nr}from"./LUFWGH2V.js";import{a as $t,b as Zn,n as Yn}from"./ZZNGA77G.js";import{b as oe}from"./JKWWY2LJ.js";import"reflect-metadata";var Qt=[{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}],ur="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)",Rt=/^\d+$/;function ra(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 w=s.slice(a+1);if(!Rt.test(w)||Number(w)<1||Number(w)>n)return;d=Number(w)}let l=t,h=n;if(o!=="*")if(o.includes("-")){let w=o.indexOf("-"),k=o.slice(0,w),_=o.slice(w+1);if(!Rt.test(k)||!Rt.test(_)||Number(k)<t||Number(_)>n||Number(k)>Number(_))return;l=Number(k),h=Number(_)}else{if(!Rt.test(o)||Number(o)<t||Number(o)>n)return;l=Number(o),h=a===-1?l:n}for(let w=l;w<=h;w+=d)r.add(w)}return r}function lr(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${ur}; "${e}" is not`;let n=[];for(let h=0;h<5;h++){let w=ra(t[h],Qt[h].lo,Qt[h].hi);if(!w)return`${ur}; its ${Qt[h].name} "${t[h]}" is not one`;n.push(w)}let[,,r,s,a]=n;a.has(7)&&a.add(0);let o=t[2].startsWith("*"),d=t[4].startsWith("*"),l=new Date(Date.UTC(2e3,0,1));for(let h=0;h<366*8+2;h++,l.setUTCDate(l.getUTCDate()+1)){if(!s.has(l.getUTCMonth()+1))continue;let w=r.has(l.getUTCDate()),k=a.has(l.getUTCDay());if(o||d?w&&k:w||k)return}return`"${e}" is never due: no date has that day in that month`}var Ue=Symbol.for("palbase.backend.controller"),Le=Symbol.for("palbase.backend.routes"),en=Symbol.for("palbase.backend.params"),tn=Symbol.for("palbase.backend.injectable"),nn=Symbol.for("palbase.backend.module"),Re=Symbol.for("palbase.backend.events"),Ie=Symbol.for("palbase.backend.webhook"),Te=Symbol.for("palbase.backend.crons"),we=Symbol.for("palbase.backend.tasks"),ke=Symbol.for("palbase.backend.testUserTemplates");function ie(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var Xt=Symbol.for("palbase.backend.declared");function re(){let e=globalThis;return e[Xt]instanceof Set||(e[Xt]=new Set),e[Xt]}var ze=new Set(["webhooks","_palbase"]);function Ki(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&ze.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);ie(n,Ue,()=>({basePath:e,options:t})),re().add(n)}}function qe(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`);ie(r.constructor,Le,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var Ji=qe("GET"),Bi=qe("POST"),Wi=qe("PUT"),Vi=qe("PATCH"),Zi=qe("DELETE"),Yi=qe("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=ie(n.constructor,en,()=>new Map);a.has(r)||a.set(r,[]),a.get(r).push({index:s,kind:e,...t})}}function rn(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 Qi=e=>ue("body",{schema:rn("Body",e)}),Xi=e=>ue("query",{schema:rn("QueryParams",e)}),ed=e=>ue("headers",e===void 0?{}:{schema:rn("Headers",e)}),td=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return ue("param",{name:e})},nd=()=>ue("user"),rd=()=>ue("optionalUser"),sd=()=>ue("req"),ad=()=>ue("requestId"),od=()=>ue("requestId"),id=()=>ue("client");function dd(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 cd(){return e=>{ie(e,tn,()=>!0),re().add(e)}}function ud(e){return t=>{ie(t,nn,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var mr=/^[a-z]+(\.[a-z_]+)+$/,sa=/^[a-z][a-z0-9-]{1,62}$/,sn=e=>e.startsWith("file.");function ld(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"||!sa.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(!sn(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`);ie(r.constructor,Re,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),re().add(r.constructor)}}var an=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,aa=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function fr(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(!aa.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 fd(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!an.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=lr(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||fr(t.timeZone)!==void 0))throw new TypeError(`${n}: ${fr(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}),re().add(a)}}var pr=["stripe","github","twilio","sendgrid","slack","discord","livekit"],oa=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function pd(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(!oa.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&&!pr.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${pr.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&ia(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=M(t,Re)??[];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)}ie(t,Ie,()=>({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}))})),re().add(t)}}function ia(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function md(){return[...re()].filter(e=>M(e,Ue)!==void 0)}function hd(e){return(M(e,Le)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var At=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function kd(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!an.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,we))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,we,{value:r,enumerable:!1}),re().add(s)}}var cn;function gr(e){cn=e}function on(){if(!cn)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return cn}var da=720*3600;function ca(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>da))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 ua(e){if(typeof e=="string")return e;let t=e[we];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var vd=xt("Tasks",{async enqueue(e,t,n={}){return ca(n),on().enqueue(ua(e),t===void 0?null:t,n)},async cancel(e,t={}){return on().cancel(e,t.machine)},async get(e,t={}){return on().get(e,t.machine)}}),dn=(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 yr(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 ye.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 dn(a.data,a.status===200)},async cancel(n,r){return dn((await ye.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return dn((await ye.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var la=1e4,fa=36e5,hr=24*36e5,Ot=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 oe({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 oe({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 oe({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let l of this.tasks.values())if(l.task===t&&l.key===r.key&&(l.finishedAt===void 0||this.now()-l.finishedAt<hr))return this.view(l,!0)}let a=this.now(),o=r.delay!==void 0?a+r.delay*1e3:r.runAt?Math.max(a,r.runAt.getTime()):a,d={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:o,createdAt:new Date(a)};return this.tasks.set(d.id,d),this.schedule(d),this.view(d,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new oe({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 oe({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(la*2**Math.min(t.attempt-1,16),fa),S.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>=hr&&this.tasks.delete(s);n==="failed"&&S.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 Pt="/_palbase/test-user-templates",pa=/^[a-z][a-z0-9_-]{0,63}$/;function Sd(e){let t=e??{},n=`@TestUserTemplate(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!pa.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}),re().add(s)}}function wr(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 br(e,t){try{let{data:n}=await e.auth.adminGetUser({path:{uid:t}});return n.is_test===!0}catch(n){if(n instanceof oe&&n.status===404)return!1;throw n}}var ma="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 kr(e){let t=e?.$query;if(typeof t!="function")return{};let n=await t.call(e,ma),r={};for(let s of n)r[s.schemaname==="public"?s.relname:`${s.schemaname}.${s.relname}`]=Number(s.n);return r}var un="/_palbase/storage/upload/authorize",vr="/_palbase/storage/upload/complete",ln="/_palbase/realtime/rooms";var ha=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function He(e){if(!ha(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 Tr(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function $r(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function Ct(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var ga=/^[a-z][a-z0-9-]{1,62}$/,Er=1024,ya=new Set(["userId","uploadId","filename"]);function Od(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(!ga.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=wa(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,l)=>{if(typeof d!="string"||l===void 0||typeof l.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);ie(o.constructor,Le,()=>[]).push({method:"POST",subpath:e,fn:d,options:a,upload:s})}}function Pd(){return ue("uploadedObject")}function wa(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!ya.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!Sr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function Sr(e){if(e===""||new TextEncoder().encode(e).byteLength>Er)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 ba(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>ka(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function ka(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 _r(e,t){let n=ba(e,t);return Sr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${Er} bytes)`}}function xr(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 fn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Rr(e,t){if(!fn(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=He(t.user);if(!o)return"user is { id?, session?, role }";let d=Tr(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let l=va(t.uploadedObject);return l?l.uploadId!==a?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:a,user:o,...d?{client:d}:{},filename:"",uploadedObject:l,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function va(e){if(!fn(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,width:d,height:l,thumbhash:h,variants:w}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof a!="string"||typeof o!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(d!==void 0&&typeof d!="number"||l!==void 0&&typeof l!="number"||h!==void 0&&typeof h!="string")&&!(!fn(w)||!Object.values(w).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:a,checksum:o,...d!==void 0?{width:d}:{},...l!==void 0?{height:l}:{},...h!==void 0?{thumbhash:h}:{},variants:{...w}}}import{markData as Ta}from"palgres";var Ae=Symbol.for("palbase.backend.gateway"),Ke=Symbol.for("palbase.backend.gatewayHooks"),Ar={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"]},$a={"~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(Ar),output:()=>structuredClone(Ar)}}},Nr=Symbol.for("palbase.backend.gatewayRefusal"),Or=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,Nr,{value:!0})}},Ea=e=>typeof e=="object"&&e!==null&&e[Nr]===!0&&typeof e.reason=="string",Fe=e=>Object.keys(e.hooks).length>0||Object.keys(e.messages).length>0,Sa=6e4,_a=86400,Pr=604800,Cr=65536,$e=255,xa=["roles:","flags:","messaging:","debug:"],Ra=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(" ")),Ge=e=>new TextEncoder().encode(e).byteLength,pn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function",gn=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}"));function Aa(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(Ge(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=xa.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 Ur(e){if(typeof e!="string"||e==="")return"is a name";if(Ge(e)>$e)return`is ${$e} bytes at most`}function Ud(e,t={}){if(typeof e!="string"||e==="")throw new TypeError('@Gateway(pattern, options): pattern is the channels it is, like "chat:{chatId}"');let n=Aa(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"&&gn(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=Oa(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)||Ra.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[w,k]of Object.entries(d)){let _=Ur(w);if(_)throw new TypeError(`@Gateway("${e}") on ${o}: event "${w}" ${_}`);if(!pn(k))throw new TypeError(`@Gateway("${e}") on ${o}: event "${w}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}let l=ie(a,Ke,yn),h={name:o,pattern:e,...r.access!==void 0?{access:r.access}:{},publish:r.publish===!0,logKeepSeconds:s,events:r.chat===!0?{...d,chat:$a}:{...d},chat:r.chat===!0,graceMs:r.graceMs??Sa,hooks:{...l.hooks},messages:Object.assign(Object.create(null),l.messages)};if(h.access===void 0&&h.hooks.authorize===void 0)throw new TypeError(`@Gateway("${e}") on ${o}: who may join is not said \u2014 access: 'owner' | 'public', or an @Authorize method`);if(h.access!==void 0&&h.hooks.authorize!==void 0)throw new TypeError(`@Gateway("${e}") on ${o}: access '${h.access}' and @Authorize both say who may join \u2014 keep one`);if(h.publish&&Fe(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&&!Fe(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`);ie(a,Ae,()=>h),re().add(a)}}function Oa(e,t){if(t===void 0||t===!1)return 0;if(t===!0)return _a;let n=typeof t=="object"&&t!==null?t.keepSeconds:void 0;if(typeof n!="number"||!Number.isSafeInteger(n)||n<1||n>Pr)throw new TypeError(`@Gateway("${e}"): durable is true (a day) or { keepSeconds } \u2014 whole seconds, 1 to ${Pr} (a week)`);return n}var yn=()=>({hooks:Object.create(null),messages:Object.create(null)}),Pa={authorize:"Authorize",first:"OnFirst",connect:"OnConnect",disconnect:"OnDisconnect",empty:"OnEmpty"};function dt(e){let t=Pa[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=ie(n.constructor,Ke,yn),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,re().add(n.constructor)}}var Ld=dt("authorize"),Id=dt("first"),zd=dt("connect"),qd=dt("disconnect"),Hd=dt("empty");function Fd(e,t,n={}){let r=Ur(e);if(r)throw new TypeError(`@Subscribe(name, schema): name ${r}`);if(!pn(t))throw new TypeError(`@Subscribe("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);if(n.reply!==void 0&&!pn(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=ie(s.constructor,Ke,yn),l=d.messages[e];if(l!==void 0&&l.fn!==a)throw new TypeError(`@Subscribe("${e}") is declared twice in one gateway (${l.fn} and ${a}).`);d.messages[e]={fn:a,schema:t,...n.reply?{reply:n.reply}:{}},re().add(s.constructor)}}function Ca(e){return M(e,Ae)}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 Lr(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 Ge(r)>$e?{problem:`a channel is ${$e} bytes at most`}:r}function Ma(e,t,n){let r=gn(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))?Lr(e,t):Da(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 Da(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 Na=1e4,Ua=1e3,La=100,wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),he=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),jr={first:"first",join:"connect",leave:"disconnect",empty:"empty"},Mr=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function Ir(e,t){let n=new Map,r=new Map,s=new Map,a=new Map;for(let{cls:b,instance:E}of e){let m=Ca(b),v=a.get(m.name);if(v!==void 0&&v!==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 C=s.get(Mr(m.pattern));if(C!==void 0)throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: ${n.get(C)?.cls.name}'s "${C}" is the same channels \u2014 one gateway is told of them; keep one`);s.set(Mr(m.pattern),m.pattern);for(let[J,B]of[...Object.entries(m.hooks),...Object.entries(m.messages).map(([L,N])=>[`message ${L}`,N.fn])])if(typeof E[B]!="function")throw new TypeError(`@Gateway("${m.pattern}") on ${b.name}: its ${J} is ${B}, which is no method of it`);let U={cls:b,instance:E,g:m};n.set(m.pattern,U),r.set(b,U)}let o=new Map,d=new Set,l=new Set,h=new hn(t.broadcast),w=b=>{let E=o.get(b);return E||(E=new AbortController,o.set(b,E)),E},k=(b,E)=>{E?.abort(),o.get(b)===E&&o.delete(b)},_=(b,E,m,v,C,U)=>{if(!Object.hasOwn(b.g.events,m)){S.warn(`[palbase] ${C}: emit("${m}") is not sent \u2014 ${b.cls.name} declares no event "${m}" (static events)`);return}if(b.g.chat&&m==="chat"){S.warn(`[palbase] ${C}: 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:E,event:m,payload:v??{},...U!==void 0?{conn_id:U}:{}},C)},H=async(b,E,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(E)};function I(b,E,m,v,C,U,J){let B=v?.signal??AbortSignal.abort(),L=`${b.cls.name} (${E})`;return{channel:E,params:Object.freeze({...m}),signal:B,count:C,user:U,emit:(N,W)=>_(b,E,N,W,L,J),pipe:N=>H(N,E,L),owner:{hold(N){ne.exit(async()=>{try{await N(B)}catch(W){B.aborted||S.error(`[palbase] ${L}: a task owner.hold ran failed`,{error:W})}}).catch(()=>{})},release:()=>k(E,v)}}}function D(b){let{room:E,channel:m}=b;if(typeof E!="string"||typeof m!="string")return he(400,"bad_request","A gateway's call names its pattern (room) and its channel");let v=n.get(E);return!v||!Fe(v.g)?he(404,"not_found",`This app serves no gateway "${E}"`):{entry:v,channel:m,params:ja(E,m)}}let Y=(b,E)=>he(400,"bad_request",`"${E}" is not a channel of the gateway "${b}"`);async function Q(b,E){let m=D(b);if("status"in m)return m;let{entry:v,channel:C,params:U}=m,J={status:200,body:{subscribe:!1,publish:!1}};if(!U)return S.warn(`[palbase] ${v.cls.name}: realtime asked about "${C}", which is not a channel of the gateway "${v.g.pattern}"; the join is refused`),J;let B=He(b.user),L=B?.id;if(!L)return J;if(v.g.access==="public")return{status:200,body:{subscribe:!0,publish:Object.keys(v.g.messages).length>0}};if(v.g.access==="owner")return U[gn(v.g.pattern)[0].slice(1,-1)]===L?{status:200,body:{subscribe:!0,publish:Object.keys(v.g.messages).length>0}}:J;let N=v.g.hooks.authorize;if(!N)return J;let W,G;try{W=await t.run(B,`${v.cls.name}.${N}`,E,async()=>v.instance[N]({user:{id:L},params:Object.freeze({...U})})),G=Ia(W)}catch(te){if(t.isOutage(te)||E?.aborted)throw te;return S.error(`[palbase] ${v.cls.name}.${N} (@Authorize of ${C}) failed; the join is refused`,{error:te}),J}return G==="malformed"?(S.warn(`[palbase] ${v.cls.name}.${N} (@Authorize of ${C}) answered ${za(W)}, which is no grant (true, { read, write } or null); the join is refused`),J):{status:200,body:G}}async function fe(b,E){let m=D(b);if("status"in m)return m;if(!m.params)return Y(m.entry.g.pattern,m.channel);let v=He(b.user);if(!v?.id||typeof b.event!="string")return he(400,"bad_request","A message names its member (user) and its event");let C=Object.hasOwn(m.entry.g.messages,b.event)?m.entry.g.messages[b.event]:void 0;if(!C)return{status:200,body:{ok:!1,reason:mn(`gateway "${m.channel}" takes no message "${b.event}"`,jt)}};let U=await C.schema["~standard"].validate(Ta(b.payload??{}));if(U.issues)return{status:200,body:{ok:!1,reason:Dr(U.issues)}};let J=w(m.channel),B={...I(m.entry,m.channel,m.params,J,0,{id:v.id}),payload:U.value},L=`${m.entry.cls.name}.${C.fn} (@Subscribe "${b.event}" of ${m.channel})`,N;try{N=await t.run(v,`${m.entry.cls.name}.${C.fn}`,E,async()=>m.entry.instance[C.fn](B))}catch(G){if(t.isOutage(G))throw G;return Ea(G)?{status:200,body:{ok:!1,reason:mn(G.reason,jt)}}:(E?.aborted||S.error(`[palbase] ${L} failed`,{error:G}),{status:200,body:{ok:!1,reason:"handler_failed"}})}if(N===void 0)return{status:200,body:{ok:!0}};if(C.reply){let G=await C.reply["~standard"].validate(N);if(G.issues)return S.error(`[palbase] ${L} returned an ack its reply schema refuses (${Dr(G.issues)}); the member is told it failed`),{status:200,body:{ok:!1,reason:"handler_failed"}};N=G.value}let W;try{W=JSON.stringify(N)}catch(G){return S.error(`[palbase] ${L} returned an ack that is not JSON; the member is told it failed`,{error:G}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return W===void 0?{status:200,body:{ok:!0}}:Ge(W)>Cr?(S.error(`[palbase] ${L} returned an ack of ${Ge(W)} bytes, past ${Cr}; the member is told it failed`),{status:200,body:{ok:!1,reason:"reply_too_large"}}):{status:200,body:{ok:!0,reply:JSON.parse(W)}}}async function pe(b,E){let m=D(b);if("status"in m)return m;if(!m.params)return Y(m.entry.g.pattern,m.channel);let v=b.event;if(typeof v!="string"||!Object.hasOwn(jr,v))return he(400,"bad_request","A gateway's moment is first, join, leave or empty");let C=typeof b.count=="number"&&Number.isInteger(b.count)&&b.count>=0?b.count:void 0;if(C===void 0)return he(400,"bad_request","A gateway's moment says its count of members");let U=v==="join"||v==="leave",J=U?He(b.user):void 0,B=U?b.connId:void 0;if(U&&(!J?.id||typeof B!="string"||B===""))return he(400,"bad_request",`A ${v} names its member: user and connId`);let L=`${v}\0${m.channel}\0${typeof B=="string"?B:""}`;if(U&&d.has(L))return{status:204};if(l.has(L))return he(503,"in_progress","This moment of the gateway is being handled",5);l.add(L);try{let N=m.entry.g.hooks[jr[v]],W;if(v==="empty"?(W=o.get(m.channel),k(m.channel,W)):W=v==="leave"?o.get(m.channel):w(m.channel),N){let G=I(m.entry,m.channel,m.params,W,C,{id:J?.id??""},v==="join"?B:void 0);try{await t.run(J,`${m.entry.cls.name}.${N}`,E,async()=>m.entry.instance[N](G))}catch(te){if(t.isOutage(te))throw te;return E?.aborted||S.error(`[palbase] ${m.entry.cls.name}.${N} (${v} of ${m.channel}) failed; realtime tells it again`,{error:te}),he(500,"handler_failed",`The gateway's ${v} could not be handled`)}}return U&&(d.add(L),d.size>Na&&d.delete(d.values().next().value)),{status:204}}finally{l.delete(L)}}function be(b,E){let m=r.get(b),v=`Palbase.gateways.to(${b?.name??String(b)})`;if(!m)throw new TypeError(`${v}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let C=Lr(m.g.pattern,E??{});if(typeof C!="string")throw new TypeError(`${v}: ${C.problem}`);return{entry:m,channel:C,where:v}}return{declarations:[...n.values()].map(b=>b.g),async serve(b,E,m){return wn(E)?b==="authorize"?Q(E,m):b==="message"?fe(E,m):b==="lifecycle"?pe(E,m):he(404,"not_found",`No gateway call ${JSON.stringify(b)}`):he(400,"bad_request","A gateway's call is a JSON object")},emit(b,E,m,v){let{entry:C,channel:U,where:J}=be(b,E);_(C,U,m,v,J)},async pipe(b,E,m){let{channel:v,where:C}=be(b,E);await H(m,v,C)},async revalidate(b,E,m={}){let v=r.get(b),C=`Palbase.gateways.to(${b?.name??String(b)}).revalidate`;if(!v)throw new TypeError(`${C}: ${b?.name??String(b)} is no @Gateway this app serves \u2014 list it in a module's providers`);let U=Ma(v.g.pattern,E??{},m);if("problem"in U)throw new TypeError(`${C}: ${U.problem}`);await t.revalidate(U)},close(){for(let b of o.values())b.abort();o.clear()}}}function Ia(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!wn(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 za(e){return Array.isArray(e)?"an array":wn(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 qa=20,jt=256;function Dr(e){let t="";for(let n of e.slice(0,qa)){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)>=jt)break}return mn(t,jt)}function mn(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 hn=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Ge(t.event)>$e){S.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){S.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>=Ua?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ne.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,La);try{await this.broadcast(s)}catch(o){S.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),S.warn(`[palbase] ${r}: ${a} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};import{createHash as bn,createHmac as Ha,createPublicKey as Fr,timingSafeEqual as Fa,verify as Gr}from"node:crypto";function Bd(e){let t=M(e,Ie);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 Kr(e,t,n,r={}){let s=new Map,a=[];for(let o of e){let d=M(o,Ie),l=s.get(d.name);if(l)throw new TypeError(`@Webhook "${d.name}" is declared by ${l.cls.name} and by ${o.name}: /webhooks/${d.name} is one endpoint`);let h=`@Webhook "${d.name}" (${o.name})`,w=n[d.secret.env],k;if(r.secrets!==!1)if(w===void 0||w==="")a.push(`${h} reads its signing secret from ${d.secret.env}, which is not set`);else try{k=Ga(d,w)}catch(I){a.push(`${h}: ${d.secret.env} ${I.message}`)}let _=t(o),H=new Map(d.events.map(({event:I,fn:D})=>[I,{name:`${o.name}.${D}`,call:(Y,Q)=>_[D](Y,Q)}]));s.set(d.name,{name:d.name,cls:o,provider:d.provider,signatureHeader:d.signature?.header,secretEnv:d.secret.env,scheme:k,events:H})}if(a.length>0)throw new Error(`[palbase] the app cannot start:
3
3
  - ${a.join(`
4
4
  - `)}`);return s}function Jr(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var Je=1024,zr=1024*Je;function Ga(e,t){if(e.signature)return Oe(void 0,e.signature.header,1/0,to(e.signature,t));switch(e.provider){case"stripe":return Oe("stripe","stripe-signature",512*Je,Ba(t));case"github":return Oe("github","x-hub-signature-256",25*zr,Wa(t));case"slack":return Oe("slack","x-slack-signature",64*Je,Va(t));case"discord":return Oe("discord","x-signature-ed25519",64*Je,Za(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*Je),check:Qa(t)};case"sendgrid":return Oe("sendgrid","x-twilio-email-event-webhook-signature",zr,Xa(t));case"livekit":return Oe("livekit","authorization",512*Je,eo(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function Oe(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,a)=>r(s,a)??Br(e,s)}}function Br(e,t){let n=kn(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:Wr(e,t.headers,r),event:r,...Ka(e,t,r)}}function Wr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=Pe(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=Yr(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 Pe(n,"EventType");case"livekit":return Pe(n,"event");default:return Pe(n,"type")}}function Ka(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(Pe(n,"id"));case"slack":return r(Pe(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${Vr(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>Pe(s,"sg_event_id")||void 0)}:{};default:return{}}}var Ja=300;function Ba(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,a=[];for(let l of r.split(",")){let h=l.indexOf("=");if(h<=0)continue;let w=l.slice(0,h).trim(),k=l.slice(h+1).trim();if(w==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(w==="v1"){let _=le(k,"hex");if(!_)return"malformed_signature";a.push(_)}}let o=ct(s);if(o===void 0||a.length===0)return"malformed_signature";if(ut(o,n))return"stale_timestamp";let d=Be("sha256",e,`${s}.`,t.body);return a.some(l=>Ee(l,d))?void 0:"signature_mismatch"}}function Wa(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?le(n.slice(7),"hex"):void 0;return r?Ee(r,Be("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function Va(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=ct(s),o=r.startsWith("v0=")?le(r.slice(3),"hex"):void 0;return a===void 0||!o?"malformed_signature":ut(a,n)?"stale_timestamp":Ee(o,Be("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function Za(e){let t=le(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=Fr({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=ct(o),l=le(a,"hex");return d===void 0||!l||l.byteLength!==64?"malformed_signature":ut(d,s)?"stale_timestamp":Gr(null,Zr(o,r.body),n,l)?void 0:"signature_mismatch"}}var Ya=1e3;function Qa(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=le(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(!Ee(Buffer.from(a.toLowerCase()),Buffer.from(bn("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let H=1;for(let Y of t.body)if(Y===38&&++H>Ya)return"malformed_signature";let I=new Map;for(let[Y,Q]of new URLSearchParams(kn(t.body))){let fe=I.get(Y);fe||I.set(Y,fe=new Set),fe.add(Q)}let D=[];for(let Y of[...I.keys()].sort()){let Q=[...I.get(Y)].sort();for(let fe of Q)o+=Y+fe;D.push([Y,Q.length===1?Q[0]:Q])}d=Object.fromEntries(D)}let l=s.protocol==="https:"?"443":"80",h=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,w=`${s.protocol}//${s.hostname}:${s.port||l}${s.pathname}${s.search}`;if(![h,w].some(H=>Ee(r,Be("sha1",e,H,o))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),_=k?{id:`${k}:${Vr(`${h}
5
5
  ${o}`)}`}:{};return d?{type:Wr("twilio",t.headers,d),event:d,..._}:{...Br("twilio",t),..._}}}function Xa(e){let t;try{let n=le(e,"base64");if(!n)throw new Error;t=Fr({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=ct(a),d=le(s.trim(),"base64");return o===void 0||!d?"malformed_signature":ut(o,r)?"stale_timestamp":Gr("sha256",Zr(a,n.body),{key:t,dsaEncoding:"der"},d)?void 0:"signature_mismatch"}}var qr=60;function eo(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=Hr(le(s[0],"base64url")),o=le(s[2],"base64url");if(a?.alg!=="HS256"||!o)return"malformed_signature";if(!Ee(o,Be("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let d=Hr(le(s[1],"base64url"));if(typeof d?.exp!="number")return"malformed_signature";if(n>d.exp+qr||typeof d.nbf=="number"&&n<d.nbf-qr)return"stale_timestamp";let l=typeof d.sha256=="string"?le(d.sha256,"base64"):void 0;return l&&Ee(l,bn("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function to(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=ct(d);if(h===void 0)return"malformed_signature";if(ut(h,a))return"stale_timestamp"}let l=le(o.trim(),e.encoding);return l?Ee(l,Be(r,t,...n.map(h=>h==="{body}"?s.body:h==="{ts}"?d:h)))?void 0:"signature_mismatch":"malformed_signature"}}var no=new TextEncoder;function Be(e,t,...n){let r=Ha(e,t);for(let s of n)r.update(s);return r.digest()}function Vr(e){return bn("sha256").update(e).digest("hex")}function Zr(e,t){return Buffer.concat([no.encode(e),t])}function Ee(e,t){return e.byteLength===t.byteLength&&Fa(e,t)}var ro={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 le(e,t){return ro[t].test(e)?Buffer.from(e,t):void 0}function ct(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function ut(e,t){return Math.abs(t-e)>Ja}function kn(e){return new TextDecoder().decode(e)}function Hr(e){if(e)try{return JSON.parse(kn(e))}catch{return}}function Yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pe(e,t){let n=Yr(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var K=class extends Error{kind;path;constructor(t,n,r,s,a){super(`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.14.0 — Palbase SDK License (see LICENSE) */
2
- import{b as c,f as u}from"./QGGRIABQ.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
+ import{b as c,f as u}from"./JKWWY2LJ.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
@@ -1,4 +1,4 @@
1
- /*! palbase 0.14.0 — Palbase SDK License (see LICENSE) */
2
- import{f as m}from"./FGKFL5W3.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.14.2 — Palbase SDK License (see LICENSE) */
2
+ import{f as m}from"./BRHGS5AI.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,5 +1,5 @@
1
- /*! palbase 0.14.0 — Palbase SDK License (see LICENSE) */
2
- import{p as R,t as k,u as H}from"./KOR6BP5M.js";var N=40,V=`
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
+ import{p as R,t as k,u as H}from"./PRJZTG2I.js";var N=40,V=`
3
3
  :host{display:contents}
4
4
  .pm-modal,.pm-full{position:fixed;inset:0;width:100%;height:100%;max-width:none;max-height:none;margin:0;border:0;background:transparent;color:inherit;overflow:hidden;display:flex;flex-direction:column}
5
5
  .pm-modal::backdrop,.pm-full::backdrop{background:transparent}
@@ -1,2 +1,2 @@
1
- /*! palbase 0.14.0 — Palbase SDK License (see LICENSE) */
2
- import{b}from"./XUX2HR4Z.js";import{a as k,b as A}from"./22WJEDHI.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.14.2 — Palbase SDK License (see LICENSE) */
2
+ import{b}from"./HHZSOYPP.js";import{a as k,b as A}from"./P67I4TNQ.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,2 +1,2 @@
1
- /*! palbase 0.14.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
2
  var K="pbt1.",E="Palbase-Encryption";var z="x-palbase-encrypted",o=class extends Error{code;constructor(t,n){super(n),this.name="TransitError",this.code=t}},h=new TextEncoder,P=new TextDecoder("utf-8",{fatal:!0}),l=()=>{let e=globalThis.crypto?.subtle;if(!e)throw new Error("encrypted fields need WebCrypto (crypto.subtle): a secure context \u2014 https, or localhost");return e};function y(e){return new Uint8Array(new ArrayBuffer(e))}function f(...e){let t=y(e.reduce((r,i)=>r+i.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function d(e){return f(e)}function m(e,t){let n=y(t);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return n}function x(e){let t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(e){let t=e.replace(/=+$/,"");if(!/^[A-Za-z0-9_-]*$/.test(t)||t.length%4===1)throw new o("malformed","not base64url");let n=atob(t.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-t.length%4)%4)),r=y(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}var S=f(h.encode("KEM"),m(32,2)),g=f(h.encode("HPKE"),m(32,2),m(1,2),m(1,2)),v=h.encode("HPKE-v1"),X=16,H=12,T=32,$=Uint8Array.from([48,46,2,1,0,48,5,6,3,43,101,110,4,34,4,32]);async function N(e,t){let n=await l().importKey("raw",e.length===0?y(32):d(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await l().sign("HMAC",n,d(t)))}async function k(e,t,n,r){return N(t,f(v,e,h.encode(n),r))}async function U(e,t,n,r,i){let a=f(m(i,2),v,e,h.encode(n),r),s=y(i),c=y(0);for(let u=1,p=0;p<i;u++)c=await N(t,f(c,a,Uint8Array.of(u))),s.set(c.subarray(0,Math.min(c.length,i-p)),p),p+=c.length;return s}async function j(e){if(e.length!==32)throw new o("malformed","an X25519 private key is 32 bytes");return l().importKey("pkcs8",f($,e),{name:"X25519"},!1,["deriveBits"])}async function C(e){if(e.length!==32)throw new o("malformed","an X25519 public key is 32 bytes");return l().importKey("raw",d(e),{name:"X25519"},!1,[])}async function O(e,t){return new Uint8Array(await l().deriveBits({name:"X25519",public:t},e,256))}async function R(e,t,n){let r=await k(S,y(0),"eae_prk",e);return U(S,r,"shared_secret",f(t,n),T)}async function _(e,t){let n=await k(g,y(0),"psk_id_hash",y(0)),r=await k(g,y(0),"info_hash",t),i=f(Uint8Array.of(0),n,r),a=await k(g,e,"secret",y(0));return{key:await U(g,a,"key",i,X),nonce:await U(g,a,"base_nonce",i,H)}}async function b(e,t,n,r,i){let a=await l().importKey("raw",d(t),"AES-GCM",!1,[e]);return new Uint8Array(await l()[e]({name:"AES-GCM",iv:d(n),additionalData:d(r)},a,d(i)))}async function V(e,t,n,r=y(0),i){let a,s;if(i)a=await j(i.privateKey),s=d(i.publicKey);else{let B=await l().generateKey({name:"X25519"},!0,["deriveBits"]);a=B.privateKey,s=new Uint8Array(await l().exportKey("raw",B.publicKey))}let c=await R(await O(a,await C(e)),s,e),{key:u,nonce:p}=await _(c,t);return{enc:s,ct:await b("encrypt",u,p,r,n)}}async function q(e,t,n,r,i,a=y(0)){if(n.length!==32)throw new o("malformed","an encapsulated X25519 key is 32 bytes");try{let s=await R(await O(await j(e),await C(n)),n,t),{key:c,nonce:u}=await _(s,r);return await b("decrypt",c,u,a,i)}catch{throw new o("unopenable","the request's key does not open with the project's key it names")}}async function Z(e){let t=await l().importKey("pkcs8",f($,e),{name:"X25519"},!0,["deriveBits"]),n=await l().exportKey("jwk",t);return w(n.x)}function Q(e,t,n,r=[]){if(r.some(i=>i.includes("\0")))throw new o("malformed","a path's value holds no NUL");return h.encode(["palbase-encryption","1",e,t.toUpperCase(),L(n),...r].join("\0"))}function L(e){return e.replace(/\{[^/{}]*\}/g,"{}")}async function Y(e,t,n,r={}){let i=r.key?d(r.key):crypto.getRandomValues(y(32)),{enc:a,ct:s}=await V(t,n,i,y(0),r.ephemeral);return{kid:e,key:i,header:`1.${e}.${x(a)}.${x(s)}`}}function J(e){let t=e.trim().split(".");if(t.length!==4||t[0]!=="1"||!/^t[1-9][0-9]{0,5}$/.test(t[1]))throw new o("malformed",`${E} is 1.<key id>.<enc>.<ct>`);let n=w(t[2]),r=w(t[3]);if(n.length!==32||r.length!==48)throw new o("malformed",`${E} carries a 32-byte encapsulated key and a sealed 32-byte key`);return{kid:t[1],enc:n,ct:r}}async function ee(e,t,n,r){let{enc:i,ct:a}=J(e),s=await q(t,n,i,r,a);if(s.length!==32)throw new o("unopenable","the request's key is not 32 bytes");return s}function I(e){return h.encode(`pbt1\0${e}`)}async function te(e,t,n,r){let i=r?d(r):crypto.getRandomValues(y(12)),a=JSON.stringify(n);if(a===void 0)throw new o("malformed",`${t}: an encrypted field holds a JSON value`);let s=await b("encrypt",e,i,I(t),h.encode(a));return K+x(f(i,s))}function F(e){return typeof e=="string"&&e.startsWith(K)}async function ne(e,t,n){if(!F(n))throw new o("unopenable",`${t} is not an encrypted field`);let r;try{r=w(n.slice(K.length))}catch{throw new o("unopenable",`${t} is not an encrypted field`)}if(r.length<28)throw new o("unopenable",`${t} is too short to be an encrypted field`);let i;try{i=await b("decrypt",e,r.subarray(0,12),I(t),r.subarray(12))}catch{throw new o("unopenable",`${t} does not open: changed, moved from another field, or another request's`)}try{return JSON.parse(P.decode(i))}catch{throw new o("unopenable",`${t} opens to no JSON value`)}}function D(e){return e.replace(/~/g,"~0").replace(/\//g,"~1").replace(/\*/g,"~2")}function G(e){return e.replace(/~2/g,"*").replace(/~1/g,"/").replace(/~0/g,"~")}var M=Symbol("items");function W(e,t){if(!(e!==t&&!e.startsWith(t+"/")))return e===t?[]:e.slice(t.length+1).split("/").map(n=>n==="*"?M:G(n))}async function re(e,t,n,r){let i=e;for(let a of n){let s=W(a,t);s!==void 0&&(i=await A(i,s,t,r))}return i}async function A(e,t,n,r){if(t.length===0)return e===void 0?void 0:r(n,e);let[i,...a]=t;if(i===M){if(!Array.isArray(e))return e;let c=[];for(let[u,p]of e.entries())c.push(await A(p,a,`${n}/${u}`,r));return c}if(Array.isArray(e)){if(!/^(0|[1-9][0-9]*)$/.test(i)||Number(i)>=e.length)return e;let c=[...e];return c[Number(i)]=await A(c[Number(i)],a,`${n}/${i}`,r),c}if(typeof e!="object"||e===null||Array.isArray(e)||!Object.hasOwn(e,i))return e;let s={...e};return s[i]=await A(s[i],a,`${n}/${D(i)}`,r),s}function ie(){return x(crypto.getRandomValues(y(16)))}async function se(e,t,n,r){let i,a=!1;try{i=w(e.payload);let u=await l().importKey("raw",w(t),{name:"Ed25519"},!1,["verify"]);a=await l().verify({name:"Ed25519"},u,w(e.signature),i)}catch{throw new o("unverified","the project's key list does not verify")}if(!a)throw new o("unverified","the project's key list is not signed with the project's key");let s;try{s=JSON.parse(P.decode(i))}catch{throw new o("unverified","the project's key list is no JSON")}if(s.v!==1||s.project!==n||typeof s.issued_at!="string"||!Array.isArray(s.keys)||s.keys.length===0)throw new o("unverified","the key list is not this project's, or holds no key");if(s.nonce!==r)throw new o("unverified","the key list was not asked for just now: its nonce is not the one sent");let c=s.keys.map(u=>{if(typeof u.kid!="string"||!/^t[1-9][0-9]{0,5}$/.test(u.kid)||typeof u.key!="string")throw new o("unverified","a key of the list is malformed");let p=w(u.key);if(p.length!==32)throw new o("unverified","a key of the list is not an X25519 public key");return{kid:u.kid,key:p}});return{project:s.project,issuedAt:s.issued_at,keys:c}}export{E as a,z as b,o as c,w as d,Z as e,Q as f,Y as g,J as h,ee as i,te as j,F as k,ne as l,D as m,G as n,re as o,ie as p,se as q};