palbase 0.40.2 → 0.41.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +3 -3
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{Z7RZBBBS.js → 2L2UBNP2.js} +2 -2
  8. package/dist/chunks/{KR3XSIAZ.js → 4LZMYSZA.js} +2 -2
  9. package/dist/chunks/{FDAOVX6B.js → 4YIEZ7GQ.js} +1 -1
  10. package/dist/chunks/{LO6DFZ7L.js → 5CV5NIXC.js} +2 -2
  11. package/dist/chunks/{OHNIWLO3.js → 5FC4ZZTY.js} +2 -2
  12. package/dist/chunks/{Q4VZ2BNE.js → BWWL27VF.js} +1 -1
  13. package/dist/chunks/{HDBPJPTI.js → DUBT7TA5.js} +2 -2
  14. package/dist/chunks/{D4KYGGQC.js → FXF4QMOQ.js} +2 -2
  15. package/dist/chunks/{CHQGN5YD.js → GFDEHWHB.js} +2 -2
  16. package/dist/chunks/{EJR46234.js → HAHKHE2Q.js} +2 -2
  17. package/dist/chunks/{4ONQGDDE.js → IRDLGXAB.js} +1 -1
  18. package/dist/chunks/{DFVKNPW7.js → JVDN7EOQ.js} +2 -2
  19. package/dist/chunks/{DN2MAZHA.js → K2BXR423.js} +2 -2
  20. package/dist/chunks/{LVX42GRN.js → KDQME6JZ.js} +2 -2
  21. package/dist/chunks/{7QY7ZMHT.js → LZSBQVXB.js} +2 -2
  22. package/dist/chunks/{HEHSHDUM.js → S7VKVW6I.js} +2 -2
  23. package/dist/chunks/{WH3G2H3E.js → ULKE62TM.js} +1 -1
  24. package/dist/chunks/{37C5IJBG.js → VEGFZICN.js} +2 -2
  25. package/dist/chunks/{ZTGSTF3B.js → X7T5ZRUE.js} +1 -1
  26. package/dist/chunks/{RCUVA3QW.js → XGLNNBME.js} +1 -1
  27. package/dist/chunks/{4ZMAF4YF.js → YGQVQEVB.js} +2 -2
  28. package/dist/chunks/{5QE5KFNR.js → YNE6YXJM.js} +2 -2
  29. package/dist/chunks/{Z5QBR46U.js → ZW4OIDTK.js} +1 -1
  30. package/dist/cli.js +139 -139
  31. package/dist/cloud/index.js +2 -2
  32. package/dist/refuse/ai.js +1 -1
  33. package/dist/refuse/backend.js +1 -1
  34. package/dist/refuse/cloud.js +1 -1
  35. package/dist/refuse/server.js +1 -1
  36. package/dist/server/index.js +2 -2
  37. package/dist/server/testing.js +2 -2
  38. package/dist/web/index.js +2 -2
  39. package/dist/web/message.js +2 -2
  40. package/dist/web/palbe.js +2 -2
  41. package/dist/web/paywall.js +2 -2
  42. package/dist/web/push-sw.js +1 -1
  43. package/dist/web/ssr.js +2 -2
  44. package/dist/web/vite.js +2 -2
  45. package/package.json +2 -2
package/dist/ai/index.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{a,b,c,d,e,f}from"../chunks/OHNIWLO3.js";import"../chunks/LO6DFZ7L.js";import"../chunks/RCUVA3QW.js";import"../chunks/4ZMAF4YF.js";import"../chunks/HEHSHDUM.js";import"../chunks/5QE5KFNR.js";import"../chunks/Q4VZ2BNE.js";import"../chunks/FDAOVX6B.js";export{e as AIResponseError,b as AISchemaError,d as ToolError,f as createAI,a as partial,c as prepare};
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
2
+ import{a,b,c,d,e,f}from"../chunks/5FC4ZZTY.js";import"../chunks/5CV5NIXC.js";import"../chunks/XGLNNBME.js";import"../chunks/YGQVQEVB.js";import"../chunks/S7VKVW6I.js";import"../chunks/YNE6YXJM.js";import"../chunks/BWWL27VF.js";import"../chunks/4YIEZ7GQ.js";export{e as AIResponseError,b as AISchemaError,d as ToolError,f as createAI,a as partial,c as prepare};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{ia as w,ma as h}from"../chunks/DN2MAZHA.js";import"../chunks/37C5IJBG.js";import"../chunks/D4KYGGQC.js";import"../chunks/OHNIWLO3.js";import"../chunks/LO6DFZ7L.js";import"../chunks/LVX42GRN.js";import"../chunks/Z5QBR46U.js";import"../chunks/4ONQGDDE.js";import"../chunks/RCUVA3QW.js";import"../chunks/4ZMAF4YF.js";import"../chunks/HEHSHDUM.js";import"../chunks/5QE5KFNR.js";import"../chunks/Q4VZ2BNE.js";import"../chunks/FDAOVX6B.js";import{binding as R,createDatabase as v}from"palgres";var y=new WeakMap;function q(p,e,a){if(!a?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=a.schemas,n=y.get(p);n||y.set(p,n=new Map);let r=n.get(u);r||n.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",g=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},f=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(f);i||(i=v({sql:p,schemas:u,binding:R(0,!0),roles:g,...a.fields!==void 0?{fields:a.fields}:{}}),r.set(f,i));let b=JSON.parse(e.claimsJson),m=i.then(s=>s.request({role:o,claims:b},{diagnostics:a.diagnostics,signal:a.signal})),d=s=>new Proxy(()=>{},{apply:async(t,D,c)=>{let l=(await m).client;return s(l).apply(l,c)}});return{client:new Proxy({},{get(s,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:d(l=>l.asService()[c])}):d(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async s=>(await m).rollback(s)}}export{w as createApp,q as createRequestDatabase,h as makeMemoryCache};
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
2
+ import{ia as w,ma as h}from"../chunks/K2BXR423.js";import"../chunks/VEGFZICN.js";import"../chunks/FXF4QMOQ.js";import"../chunks/5FC4ZZTY.js";import"../chunks/5CV5NIXC.js";import"../chunks/KDQME6JZ.js";import"../chunks/ZW4OIDTK.js";import"../chunks/IRDLGXAB.js";import"../chunks/XGLNNBME.js";import"../chunks/YGQVQEVB.js";import"../chunks/S7VKVW6I.js";import"../chunks/YNE6YXJM.js";import"../chunks/BWWL27VF.js";import"../chunks/4YIEZ7GQ.js";import{binding as R,createDatabase as v}from"palgres";var y=new WeakMap;function q(p,e,a){if(!a?.schemas?.length)throw new TypeError("createRequestDatabase(sql, identity, { schemas }): the engine compiles each call against the app's schemas \u2014 pass the schema files' default exports");let u=a.schemas,n=y.get(p);n||y.set(p,n=new Map);let r=n.get(u);r||n.set(u,r=new Map);let o=e.role===e.serviceRole?"service":e.role==="anon"?"anon":"authenticated",g=o==="service"?{service:e.serviceRole}:{[o]:e.role,service:e.serviceRole},f=`${o}\0${e.role}\0${e.serviceRole}`,i=r.get(f);i||(i=v({sql:p,schemas:u,binding:R(0,!0),roles:g,...a.fields!==void 0?{fields:a.fields}:{}}),r.set(f,i));let b=JSON.parse(e.claimsJson),m=i.then(s=>s.request({role:o,claims:b},{diagnostics:a.diagnostics,signal:a.signal})),d=s=>new Proxy(()=>{},{apply:async(t,D,c)=>{let l=(await m).client;return s(l).apply(l,c)}});return{client:new Proxy({},{get(s,t){if(t!=="then")return t==="diagnostics"?()=>null:t==="asService"?()=>new Proxy({},{get:(D,c)=>c==="then"?void 0:d(l=>l.asService()[c])}):d(D=>D[t])}}),commit:async()=>(await m).commit(),rollback:async s=>(await m).rollback(s)}}export{w as createApp,q as createRequestDatabase,h as makeMemoryCache};
@@ -1 +1 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
@@ -1,5 +1,5 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{$ as $t,A as ut,B as F,C as pt,D as ht,E as ft,F as mt,G as gt,H as bt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as Tt,R as xt,S as Rt,T as _t,U as Ot,V as Ct,W as Bt,X as Ft,Y as se,Z as Mt,_ as It,a as X,aa as Lt,b as Z,ba as Dt,c as ee,ca as Ut,d as qe,da as jt,e as We,ea as Nt,f as Ke,fa as qt,g as Ve,ga as M,h as Ge,ha as Gt,i as ze,ia as I,j as He,ja as G,k as Ye,ka as zt,l as Je,la as Ht,m as Qe,n as Xe,o as Ze,p as et,q as tt,r as rt,s as st,t as nt,u as at,v as ot,w as it,x as lt,y as ct,z as dt}from"../chunks/DN2MAZHA.js";import{a as Wt,b as Kt}from"../chunks/37C5IJBG.js";import{a as ae}from"../chunks/ZTGSTF3B.js";import{a as _,b as te,c as re,f as g,g as V,h as d,j as ne,k as Vt}from"../chunks/D4KYGGQC.js";import"../chunks/OHNIWLO3.js";import"../chunks/LO6DFZ7L.js";import{d as R,j as je,k as Ne,l as Y,m as B,t as J,u as Q}from"../chunks/LVX42GRN.js";import"../chunks/Z5QBR46U.js";import"../chunks/4ONQGDDE.js";import"../chunks/RCUVA3QW.js";import{p as Ue}from"../chunks/4ZMAF4YF.js";import"../chunks/HEHSHDUM.js";import{b as E,c as K}from"../chunks/5QE5KFNR.js";import"../chunks/Q4VZ2BNE.js";import"../chunks/FDAOVX6B.js";import"reflect-metadata";import{existsSync as z,writeFileSync as Rr,writeSync as _r}from"node:fs";import{createServer as Or}from"node:http";import{dirname as T,join as H,resolve as _e}from"node:path";import{Readable as Cr}from"node:stream";var Yt=2e3,Jt=1e4,Qt=/^[A-Za-z0-9_-]{1,64}$/,Xt=512,$=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,r={}){this.sink=e,this.linesPerSecond=r.linesPerSecond??10,this.batchSize=Math.min(100,r.batchSize??100),this.flushMs=r.flushMs??2e3,this.maxPending=r.maxPending??2e3,this.sendMs=r.sendMs??Jt,this.shutdownMs=r.shutdownMs??Yt,this.now=r.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,r,s=new Promise(a=>r=a),n=setTimeout(()=>{e=!0,r()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),s]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,r=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),r>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${r} dropped`)}log(e){let r=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(r-this.refilled)/1e3*this.linesPerSecond),this.refilled=r,this.unlogged>0&&r-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=r),this.tokens<1){this.unlogged===0&&(this.unloggedSince=r),this.unlogged++;return}this.tokens-=1;let s=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[s](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Qt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Xt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let i=a.status,o=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Zt}from"node:crypto";import{bind as er,bunDriver as tr,createDatabase as rr,envBlock as sr,createSearchWorker as nr,cutOff as ar,forgetUserIn as or,MigrationOpen as ir,MigrationRefused as lr,Migrator as de,renewingBunPool as oe,VersionNotMigrated as cr}from"palgres";import{toModel as ue}from"palgres/dsl";var dr=["start","complete","rollback","plan","status","types"],ur=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function pe(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!dr.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function he(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function D(t){return ue(he(t))}function pr(t){return t.tables.some(e=>e.search!==void 0)}function U(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function fe(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let r=Number(e);if(!Number.isSafeInteger(r)||r<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return r}function hr(t){if(!Number.isSafeInteger(t)||t<3)throw new Error(`[palbase] db.driver: a pool of ${t} connection(s) \u2014 the engine needs at least 3: one request's transaction and the two further ones it may hold`);let e=Math.floor(t/3);return{concurrency:e,nestedConcurrency:e*2}}var ie=5;function me(t,e){if(t.driver)return t.driver;let r=globalThis.Bun;if(!r)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let s=e-1;return n=>{let a=oe(()=>new r.SQL({url:n,prepare:!1,max:s})),i=oe(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:tr(a,i),poolSize:s,close:async()=>{await a.close({timeout:ie}),await i.close({timeout:ie})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await O(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await O("types",sr(r,{module:"palbase/backend/env"}),e),0}async function ye(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!ur.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=me(t,fe(e)),i=a(s),o,c=l=>d.error(`[palbase] migrate ${r}: ${l}`);try{let l=D(t),u=new de(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let m=new URL(s);m.pathname=`/${f}`;let y=a(m.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>fr(e)});if(r==="plan"){let f=await u.plan(l);return await O(r,f),f.refusals.length>0?1:0}if(r==="status")return await O(r,await u.status()),0;let h=r==="start"?await mr(u,l,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:h}),await O(r,h),0}catch(l){return l instanceof lr?(d.error(`[palbase] migrate ${r}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):ar(l)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??le(l)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:l}),c(`failed \u2014 ${le(l)}`),1)}finally{await i.close().catch(()=>{})}}async function fr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let s=R({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function mr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof ir)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var gr=(t,e)=>{process.stdout.write(t,()=>e())};function O(t,e,r=gr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
2
+ import{$ as $t,A as ut,B as F,C as pt,D as ht,E as ft,F as mt,G as gt,H as bt,I as yt,J as wt,K as Pt,L as St,M as vt,N as At,O as kt,P as Et,Q as Tt,R as xt,S as Rt,T as _t,U as Ot,V as Ct,W as Bt,X as Ft,Y as se,Z as Mt,_ as It,a as X,aa as Lt,b as Z,ba as Dt,c as ee,ca as Ut,d as qe,da as jt,e as We,ea as Nt,f as Ke,fa as qt,g as Ve,ga as M,h as Ge,ha as Gt,i as ze,ia as I,j as He,ja as G,k as Ye,ka as zt,l as Je,la as Ht,m as Qe,n as Xe,o as Ze,p as et,q as tt,r as rt,s as st,t as nt,u as at,v as ot,w as it,x as lt,y as ct,z as dt}from"../chunks/K2BXR423.js";import{a as Wt,b as Kt}from"../chunks/VEGFZICN.js";import{a as ae}from"../chunks/X7T5ZRUE.js";import{a as _,b as te,c as re,f as g,g as V,h as d,j as ne,k as Vt}from"../chunks/FXF4QMOQ.js";import"../chunks/5FC4ZZTY.js";import"../chunks/5CV5NIXC.js";import{d as R,j as je,k as Ne,l as Y,m as B,t as J,u as Q}from"../chunks/KDQME6JZ.js";import"../chunks/ZW4OIDTK.js";import"../chunks/IRDLGXAB.js";import"../chunks/XGLNNBME.js";import{p as Ue}from"../chunks/YGQVQEVB.js";import"../chunks/S7VKVW6I.js";import{b as E,c as K}from"../chunks/YNE6YXJM.js";import"../chunks/BWWL27VF.js";import"../chunks/4YIEZ7GQ.js";import"reflect-metadata";import{existsSync as z,writeFileSync as Rr,writeSync as _r}from"node:fs";import{createServer as Or}from"node:http";import{dirname as T,join as H,resolve as _e}from"node:path";import{Readable as Cr}from"node:stream";var Yt=2e3,Jt=1e4,Qt=/^[A-Za-z0-9_-]{1,64}$/,Xt=512,$=class{linesPerSecond;batchSize;flushMs;maxPending;sendMs;shutdownMs;now;tokens;refilled;unlogged=0;unloggedSince;pending=[];timer;sending;inFlight;pausedUntil=0;lastSendWarning=0;sink;constructor(e,r={}){this.sink=e,this.linesPerSecond=r.linesPerSecond??10,this.batchSize=Math.min(100,r.batchSize??100),this.flushMs=r.flushMs??2e3,this.maxPending=r.maxPending??2e3,this.sendMs=r.sendMs??Jt,this.shutdownMs=r.shutdownMs??Yt,this.now=r.now??Date.now,this.tokens=this.linesPerSecond,this.refilled=this.now(),this.unloggedSince=this.refilled}record(e){this.log(e),this.sink&&this.trace(e)}async flush(){this.timer&&clearTimeout(this.timer),this.timer=void 0;let e=!1,r,s=new Promise(a=>r=a),n=setTimeout(()=>{e=!0,r()},this.shutdownMs);try{for(;!e&&(this.pending.length>0||this.sending)&&(await Promise.race([this.sending??this.send(),s]),!(this.now()<this.pausedUntil)););}finally{clearTimeout(n)}e&&this.letGo()}letGo(){let e=this.inFlight,r=(e?.traces??0)+this.pending.length;this.pending=[],e&&(e.letGo=!0,e.call.abort(new Error(`analytics did not answer within the ${this.shutdownMs} ms a flush waits`))),r>0&&d.warn(`[palbase] request traces were not sent to analytics within the ${this.shutdownMs} ms a flush waits; ${r} dropped`)}log(e){let r=this.now();if(this.tokens=Math.min(this.linesPerSecond,this.tokens+(r-this.refilled)/1e3*this.linesPerSecond),this.refilled=r,this.unlogged>0&&r-this.unloggedSince>=6e4&&(d.info(`[palbase] ${this.unlogged} more requests answered in the last minute than the log keeps a line for (Analytics \u203A Network has every one)`),this.unlogged=0,this.unloggedSince=r),this.tokens<1){this.unlogged===0&&(this.unloggedSince=r),this.unlogged++;return}this.tokens-=1;let s=e.status>=500?"error":e.status>=400&&e.status!==499?"warn":"info",n=Math.round(e.durationMs*10)/10;d[s](`${e.method} ${e.path} ${e.status} ${n}ms`,{route:e.endpoint,status:e.status,duration_ms:n,...e.userId?{user_id:e.userId}:{}})}trace(e){this.pending.length>=this.maxPending&&this.pending.shift(),this.pending.push({request_id:Qt.test(e.requestId)?e.requestId:e.requestId.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,64)||"unnamed",source:"backend",endpoint:e.endpoint.slice(0,Xt),method:e.method,status:e.status,duration_ms:Math.max(0,Math.round(e.durationMs)),timestamp:this.now(),...e.userId?{distinct_id:e.userId}:{}}),this.pending.length>=this.batchSize&&!this.sending?this.send():!this.timer&&!this.sending&&this.schedule(this.flushMs)}schedule(e){this.timer=setTimeout(()=>{this.send()},e),this.timer.unref?.()}send(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,this.sending||this.pending.length===0||this.now()<this.pausedUntil||!this.sink)return this.sending??Promise.resolve();let e=this.pending.splice(0,this.batchSize),r=this.sink,s={call:new AbortController,traces:e.length,letGo:!1};this.inFlight=s;let n=setTimeout(()=>s.call.abort(new Error(`analytics did not answer in ${this.sendMs} ms`)),this.sendMs);return n.unref?.(),this.sending=(async()=>{try{await r.sendTraceBatch({body:{traces:e},signal:s.call.signal})}catch(a){if(s.letGo)return;let i=a.status,o=i??(s.call.signal.aborted?`no answer in ${this.sendMs} ms`:"unreachable"),c=a.retryAfter;this.pausedUntil=this.now()+(typeof c=="number"&&c>0?c*1e3:i===429?1e3:5e3),this.now()-this.lastSendWarning>6e4&&(this.lastSendWarning=this.now(),d.warn(`[palbase] request traces were not sent to analytics (${o}); ${e.length} dropped`,{error:a}))}finally{if(clearTimeout(n),this.sending=void 0,this.inFlight=void 0,this.pending.length>0){let a=Math.max(0,this.pausedUntil-this.now());this.schedule(this.pending.length>=this.batchSize?a:Math.max(a,this.flushMs))}}})(),this.sending}};import{createHmac as Zt}from"node:crypto";import{bind as er,bunDriver as tr,createDatabase as rr,envBlock as sr,createSearchWorker as nr,cutOff as ar,forgetUserIn as or,MigrationOpen as ir,MigrationRefused as lr,Migrator as de,renewingBunPool as oe,VersionNotMigrated as cr}from"palgres";import{toModel as ue}from"palgres/dsl";var dr=["start","complete","rollback","plan","status","types"],ur=/^(deploy|cli:[^\u0000-\u001f\u007f]{1,200})$/u;function pe(t){let e=t.PALBASE_DB_MIGRATE;if(!(e===void 0||e==="")){if(!dr.includes(e))throw new Error(`[palbase] PALBASE_DB_MIGRATE is start, complete, rollback, plan, status or types, not ${e}`);return e}}function he(t){let e=Array.isArray(t.schemas)?t.schemas:[t.schemas];for(let r of e)if(r.name===M.name)throw new Error(`[palbase] db.schemas: the ${M.name} schema is the framework's own (its tables are migrated with the app's) \u2014 name the app's schema otherwise`);return[...e,M]}function D(t){return ue(he(t))}function pr(t){return t.tables.some(e=>e.search!==void 0)}function U(t){return t.tables.some(e=>!e.ignored&&e.columns.some(r=>r.user!==void 0&&!r.ignored))}function fe(t){let e=t.PALBASE_DB_CONNECTIONS;if(e===void 0||e==="")return 31;let r=Number(e);if(!Number.isSafeInteger(r)||r<4)throw new Error(`[palbase] PALBASE_DB_CONNECTIONS is how many connections the app may hold to its database, 4 at least (a request's transaction, the two further ones it may hold, one to cancel with) \u2014 not ${e}`);return r}function hr(t){if(!Number.isSafeInteger(t)||t<3)throw new Error(`[palbase] db.driver: a pool of ${t} connection(s) \u2014 the engine needs at least 3: one request's transaction and the two further ones it may hold`);let e=Math.floor(t/3);return{concurrency:e,nestedConcurrency:e*2}}var ie=5;function me(t,e){if(t.driver)return t.driver;let r=globalThis.Bun;if(!r)throw new Error("[palbase] db.driver: off Bun there is no SQL client built in \u2014 give one: postgres.js with { types: POSTGRES_JS_TYPES }, its engine postgresJsDriver(pool, control)");let s=e-1;return n=>{let a=oe(()=>new r.SQL({url:n,prepare:!1,max:s})),i=oe(()=>new r.SQL({url:n,prepare:!1,max:1}));return{pool:{reserve:()=>a.reserve(),unsafe:(o,c)=>a.unsafe(o,c),begin:o=>a.current.begin(o)},engine:tr(a,i),poolSize:s,close:async()=>{await a.close({timeout:ie}),await i.close({timeout:ie})}}}}async function ge(t){return t==="rollback"?(d.info("[palbase] migrate rollback: this app declares no database; nothing of it to take back"),await O(t,{state:"none"}),0):(d.error(`[palbase] migrate ${t}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`),1)}async function be(t,e){if(!t)return d.error("[palbase] db types: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })"),1;let r=Array.isArray(t.schemas)?t.schemas:[t.schemas];return await O("types",sr(r,{module:"palbase/backend/env"}),e),0}async function ye(t,e,r){let s=e.PALBASE_DB_OWNER_URL;if(!s)return d.error("[palbase] PALBASE_DB_MIGRATE without PALBASE_DB_OWNER_URL: a migration runs as the tables' owner"),1;let n=e.PALBASE_DB_MIGRATION_BY||"deploy";if(!ur.test(n))return d.error("[palbase] PALBASE_DB_MIGRATION_BY is deploy, or cli:<who>"),1;let a=me(t,fe(e)),i=a(s),o,c=l=>d.error(`[palbase] migrate ${r}: ${l}`);try{let l=D(t),u=new de(i.pool,{log:f=>{/ is held by others | held by writers/.test(f)&&(o=f.trim()),d.info(f)},shadow:f=>{let m=new URL(s);m.pathname=`/${f}`;let y=a(m.toString());return{reserve:()=>y.pool.reserve(),end:()=>y.close()}},openedBy:n,fields:()=>fr(e)});if(r==="plan"){let f=await u.plan(l);return await O(r,f),f.refusals.length>0?1:0}if(r==="status")return await O(r,await u.status()),0;let h=r==="start"?await mr(u,l,n):r==="complete"?await u.complete():await u.rollback();return d.info(`[palbase] migrate ${r}: done`,{result:h}),await O(r,h),0}catch(l){return l instanceof lr?(d.error(`[palbase] migrate ${r}: refused`,{refusals:l.refusals}),c(`refused \u2014 ${l.refusals.join("; ")}`),1):ar(l)?(d.error(`[palbase] migrate ${r}: cut off; run again, it goes on from where it stopped`,{error:l}),c(`cut off \u2014 ${o??le(l)}`),75):(d.error(`[palbase] migrate ${r}: failed`,{error:l}),c(`failed \u2014 ${le(l)}`),1)}finally{await i.close().catch(()=>{})}}async function fr(t){let e=t.PALBASE_URL,r=t.PALBASE_SECRET_KEY;if(!e||!r)throw new Error("[palbase] this migration seals or opens an encrypted column's rows: it reads the project's field keys with PALBASE_URL and PALBASE_SECRET_KEY");let s=R({url:e,secretKey:r}).fields;return await s.load(),s.close(),s}async function mr(t,e,r){try{return await t.start(e)}catch(s){if(!(s instanceof ir)||r!=="deploy"||!s.openedBy?.startsWith("cli:"))throw s;return d.warn(`[palbase] migrate start: the migration ${s.openedBy} opened (version ${s.to}) gives way to this release \u2014 rolled back first`),await t.rollback(),await t.start(e)}}var gr=(t,e)=>{process.stdout.write(t,()=>e())};function O(t,e,r=gr){return new Promise(s=>r(`${JSON.stringify({palbase_migrate:t,result:e})}
3
3
  `,s))}function le(t){return(t instanceof Error?t.message:String(t)).split(`
4
4
  `)[0].slice(0,300)||(t instanceof Error?t.name:"unknown")}async function br(t,e){try{return await new de(t).plan(e)}catch{return}}var ce="palbase.idempotency_keys.response_body";function yr(t,e){let r=null,s=!1,n=async()=>{let o=e.currentKey();if(!(s||o===r)){s=!0;try{let c=await t.reseal();r=o;let l=c.reduce((u,h)=>u+h.resealed,0);l>0&&d.info(`[palbase] fields: ${l} value(s) sealed again with key ${o}`,{report:c})}catch(c){d.warn(`[palbase] fields: sealing again with key ${o} stopped; tried again in a minute`,{error:c})}finally{s=!1}}},a=setTimeout(n,1e4),i=setInterval(n,6e4);for(let o of[a,i])o.unref?.();return()=>{clearTimeout(a),clearInterval(i)}}var L=class extends Error{digest;plan;constructor(e,r){super([`[palbase] this schema (${e}) has no version in the database yet: palbase db:push tries it there (a database of your own: palbase db:push --url <its address>)`,...r?wr(r):[" palbase db:plan says what it would change"]].join(`
5
5
  `)),this.name="SchemaNotPushed",this.digest=e,this.plan=r}};function wr(t){let e=[t.adoption?` takes the database over as version 1${t.to>1?`, then version 1 \u2192 ${t.to}`:""}`:` version ${t.from??"none"} \u2192 ${t.to}`];t.changes.length===0&&t.refusals.length===0&&e.push(" nothing to change");for(let r of t.changes)e.push(` + ${r}`);for(let r of t.refusals)e.push(` \u2717 ${r}`);return e}var Pr=8e4;async function we(t,e,r,s){let n=t.url??e.PALBASE_DB_URL;if(!n)throw new Error("[palbase] db.url / PALBASE_DB_URL is the database the app connects to");let a=he(t),i=ue(a),o=me(t,fe(e))(n);try{let c=!1,l=p=>{c||(c=!0,d.warn(`[palbase] database: not answering yet (${p instanceof Error?p.message:String(p)}) \u2014 waiting for it, as one waking does`))},u=await er(o.engine,i,{waitMs:s.onPlatform?Pr:0,onUnreachable:l}).catch(async p=>{throw s.onPlatform||!(p instanceof cr)?p:new L(p.digest,await br(o.pool,i))}),h=Zt("sha256",r).update("palgres page cursor").digest("hex"),f=t.embed??s.embed,m=s.fields,y=await rr({sql:o.engine,schemas:a,binding:u,cursorSecret:h,admission:hr(o.poolSize),embed:f,log:p=>d.warn(`[palbase] ${p}`),fields:async()=>(await m.load(),m)}),S=m.loaded?yr(y,m):()=>{},b=pr(i)?nr({sql:o.engine,embed:f,log:p=>d.info(`[palbase] ${p}`)}):void 0;return{model:i,binding:u,app:y,requests:t.requests??"caller",forget:(p,k)=>or({attempt:v=>k.$attempt(v)},u,i,p),...b?{search:b}:{},keptAnswers:{seal:p=>m.loaded?m.encrypt(ce,p):p,open:async p=>m.isEncrypted(p)?(m.loaded||await m.load(),m.decrypt(ce,p)):p},close:async()=>{S(),m.close(),await o.close()}}}catch(c){throw await o.close(),c}}function Sr(t){let e=Buffer.from(t,"base64"),r=new Array(e.byteLength/4);for(let s=0;s<r.length;s++)r[s]=e.readFloatLE(s*4);return r}function Pe(t){return async({texts:e,model:r,dimensions:s})=>{let{data:n}=await t.ai.createEmbeddings({body:{input:e,model:r,dimensions:s}});return{model:n.model,vectors:n.vectors.map(Sr)}}}var vr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Se(t,e,r){let s=[],n=t.url??e.PALBASE_URL??"",a="";try{let u=new URL(n);a=u.origin,u.protocol!=="https:"&&u.hostname!=="localhost"&&u.hostname!=="127.0.0.1"&&s.push("palbase.url / PALBASE_URL is https://<ref>.<domain>"),(u.pathname!=="/"||u.search||u.hash)&&s.push("palbase.url / PALBASE_URL is the project origin alone")}catch{s.push("palbase.url / PALBASE_URL is the project address, https://<ref>.<domain>")}let i=t.projectId??e.PALBASE_PROJECT_ID??"";vr.test(i)||s.push("palbase.projectId / PALBASE_PROJECT_ID is the project id (a UUID)");let o=t.secretKey??e.PALBASE_SECRET_KEY??"";/^pb_[a-z0-9]+_s/.test(o)||s.push("palbase.secretKey / PALBASE_SECRET_KEY is the project secret key (pb_<ref>_s\u2026), kept in the project's Secrets");let c=(t.platformSecret??e.PALBASE_PLATFORM_SECRET)||void 0;c!==void 0&&!/^[0-9a-f]{64}$/.test(c)&&s.push("palbase.platformSecret / PALBASE_PLATFORM_SECRET is the key the platform signs its calls to this machine with (64 hex characters): the platform sets it, unset off the platform");let l=(t.webhookSecret??e.PALBASE_WEBHOOK_SECRET)||void 0;if(r.needsWebhookSecret&&(c!==void 0||l!==void 0)&&!/^whsec_[0-9a-f]{64}$/.test(l??"")&&s.push("palbase.webhookSecret / PALBASE_WEBHOOK_SECRET is the project's webhook endpoint secret (whsec_\u2026): the platform delivers this app events \u2014 its @On handlers', or user.deleted for the users its tables keep"),s.length>0)throw new Error(`[palbase] the app cannot start:
@@ -9,4 +9,4 @@ ${s.join(`
9
9
  `)}
10
10
  `}function ke(t,e,r=kr){let s=Buffer.from(e,"utf8"),n=new Int32Array(new SharedArrayBuffer(4));for(let a=0;a<s.length;)try{a+=r(t,s,a,s.length-a)}catch(i){if(i.code!=="EAGAIN")throw i;Atomics.wait(n,0,0,5)}}var Ee=2e4,Te=5e3,Br=15e3,Fr="/_palbase/health";function Mr(t){let e=new Set,r=s=>{if(e.has(s))return!1;e.add(s);let n=F(s,X);return n?n.providers.some(a=>F(a,Z)!==void 0&&F(a,ee)===void 0)||n.imports.some(r):!1};return t.some(r)}var Ir={async create(t,e={}){let r=Array.isArray(t)?t:[t],s=e.env??process.env,n=pe(s);if(n!==void 0){let w=n==="types"?await be(e.db):e.db?await ye(e.db,s,n):await ge(n);throw process.exit(w),new j(w)}let a=s.PALBASE_CONTRACT_OUT;if(a){let w;try{await Re(xe(s)),w=await $r(r,e,s)}catch(A){throw _r(2,`[palbase] the contract: ${A instanceof Error?A.message:String(A)}
11
11
  `),process.exit(1),new C}throw a==="/dev/stdout"?ke(1,Ae(w)):Rr(a,`${w}
12
- `),process.exit(0),new C}let i=xe(s),o=await Re(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),ne(o?void 0:i);let c=e.db?D(e.db):void 0,l=await Q({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Mr(r)||c!==void 0&&U(c),h=Se(e.palbase??{},s,{needsWebhookSecret:u});u&&h.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=R({url:h.url,secretKey:h.secretKey}),m=e.port??Number(s.PORT??"8080");if(!Number.isInteger(m)||m<0||m>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let y=e.db?await we(e.db,s,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:Pe(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&U(y.model)?{"user.deleted":[w=>Lr(y,w)]}:void 0,b=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new $(f.analytics),k=()=>I({modules:r,verifier:new B({issuer:h.url,projectId:h.projectId,standing:Y({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:s,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:jr(e.cors,s.PALBASE_WEB_ORIGINS),platform:b,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),v=k(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await v.start();break}catch(A){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:A}),A;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:A}),await new Promise(De=>setTimeout(De,W)),W*=2,v=k()}return Dr(v,f,m,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function xe(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=T(_e(e));for(;!z(H(r,"package.json"))&&T(r)!==r;)r=T(r);return z(H(r,"package.json"))?r:process.cwd()}async function Re(t){try{return await ae(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function $r(t,e,r){let s=_e(r.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(s))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${s||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=T(s);for(;!z(H(n,"package.json"))&&T(n)!==n;)n=T(n);let{analyzeProject:a}=await import("../chunks/KR3XSIAZ.js"),{routeContracts:i}=await import("../chunks/EJR46234.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=I({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:R({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:se()},events:e.db&&U(D(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var C=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Lr(t,e){let r=e.data?.user_id;if(typeof r!="string"||r==="")throw new Error("[palbase] user.deleted without a user_id");let s=await t.forget(r,V.$asService());d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Dr(t,e,r,s,n,a){let i,o={on:!1},c=(b,p)=>new URL(b.url).pathname===Fr&&b.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(b,p),l=Or((b,p)=>{Ur(c,b,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((b,p)=>{l.once("error",p),l.listen(r,s,()=>b())})}catch(b){throw await t.stop(),await a?.close(),b}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=b=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(v=>l.close(()=>v()));l.closeIdleConnections();let k=setTimeout(()=>l.closeAllConnections(),b);await p,clearTimeout(k),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(Ee),m=!1,y=()=>{if(m){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}m=!0;let b=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ee+Br);b.unref(),f().then(()=>{clearTimeout(b),process.exit(0)},p=>{clearTimeout(b),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=b=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:b});let p=setTimeout(()=>process.exit(1),Te+1e3);h(Te).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Ur(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let m of f)i.append(h,m);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?Cr.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress,target:n});if(r.statusCode=u.status,u.headers.forEach((h,f)=>r.setHeader(f,h)),s.on&&r.setHeader("connection","close"),u.body)for await(let h of u.body)r.write(h);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function jr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(o=>G(o)),a=s.filter(o=>!G(o));a.length>0&&r(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as Js,boolean as Qs,check as Xs,date as Zs,defineSchema as en,defineTable as tn,enumType as rn,foreignKey as sn,index as nn,integer as an,jsonb as on,numeric as ln,ownedByUser as cn,policy as dn,raw as un,sqlType as pn,text as hn,timestamp as fn,userRef as mn,uuid as gn}from"palgres/dsl";import{increment as yn,now as wn}from"palgres";function x(t){if(t instanceof E)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return x(r)}}var Nr=_("Secrets",{async get(t){if(J(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),qr=100,Wr=1e3,Kr=168*3600,Vr={s:1,m:60,h:3600,d:86400};function Gr(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let r=0;for(let[,s,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))r+=Math.round(Number(s)*Vr[n]*1e3);return Math.ceil(r/1e3)}function $e(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(s,"path",i)).join("%2F")}catch(i){throw i instanceof E&&i.code==="invalid_path_parameter"?new E({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${g.url}/storage/public/${K(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function Oe(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function zr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await g.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Oe(a.data),error:null,status:a.status}}catch(a){return a instanceof E&&a.status===412&&a.code==="object_exists"?{data:null,error:{code:"already_exists",message:"An object already exists at that path: upload with { upsert: true } to replace it"},status:409}:x(a)}},async download(e){try{let r=await g.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return x(r)}},getPublicUrl(e,r){return $e(t,e,r?.variant)},async createSignedUrl(e,r){let s=Gr(r?.expiresIn);return s===void 0||s<1||s>Kr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:P(()=>g.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??qr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(Wr,n+s-a.length)),l=await g.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(Oe(u));if(i=l.data.next_cursor,!i)break}}catch(c){return x(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await g.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return x(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return P(()=>g.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>g.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var Hr={bucket:zr},Ce=t=>te("Storage",t,Hr),Yr={bucket:t=>Ce("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Ce("buckets").bucket(e):void 0})},Jr=_("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>g.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return P(()=>g.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await g.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return x(c)}return{data:{message_ids:a},error:null,status:i}}}}),Be=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Fe=t=>typeof t=="string"?{name:t}:null,Me=t=>t==="override"?"user":t,Qr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Le(){return re.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Le();return P(()=>e?g.flags.getUserValues({path:{user_id:e}}):g.flags.getValues(),r=>r.values??{})}var Ie={setOverrideForUser:(t,e,r)=>P(()=>g.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Me(s.source)})),setOverridesForUser:(t,e)=>P(()=>g.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>g.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Me(r.source)})),clearAllOverridesForUser:t=>P(()=>g.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>g.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Xr=_("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await N(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Be(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await N(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Fe(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Fe(s);return{name:r,enabled:Be(s),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,r){let s,n=!1,a;r!==void 0?(s=e,n=!0,a=r):Qr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await N(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?s??null:o,error:null,status:i.status}},async setOverride(t,e){let r=Le();return r?Ie.setOverrideForUser(r,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Ie}}),Zr=_("Realtime",{broadcast(t,e,r){return P(()=>g.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as xn}from"zod";export{at as AttestedDevice,Ne as AuthUnavailable,At as Authorize,It as BadRequest,Ye as Body,zt as CACHE_MAX_TTL,Ht as Cache,Pt as ChatPart,nt as Client,$t as Conflict,C as ContractRunEnded,qe as Controller,dt as Cron,V as Database,Lt as DeadlockDetected,ze as Delete,Ot as DiError,Ue as EVENT_TYPES,Xr as Flags,Ft as Forbidden,vt as Gateway,St as GatewayRefusal,We as Get,Qe as Headers,Dt as HttpError,it as Injectable,d as Log,Gt as MAX_BODY_BYTES,j as MigrationRunEnded,lt as Module,Ut as NotFound,Jr as Notifications,ct as On,Et as OnConnect,Tt as OnDisconnect,xt as OnEmpty,kt as OnFirst,et as OptionalUser,Ct as PalError,g as Palbase,E as PalbaseError,Ir as PalbaseFactory,Xe as Param,Ge as Patch,Ke as Post,Ve as Put,He as Query,Je as QueryParams,Zr as Realtime,tt as Req,rt as RequestId,ot as Resolve,L as SchemaNotPushed,Nr as Secrets,jt as SerializationFailure,Yr as Storage,Rt as Subscribe,mt as Task,ft as TaskFailure,gt as Tasks,bt as TestUserTemplate,je as TokenError,B as TokenVerifier,Nt as TooManyRequests,st as TraceId,Bt as Unauthorized,qt as UniqueViolation,yt as Upload,wt as UploadedObject,Ze as User,ut as Webhook,Js as bigint,Qs as boolean,Xs as check,I as createApp,Zs as date,Mt as defineError,en as defineSchema,tn as defineTable,Kt as encrypt,Wt as encrypted,rn as enumType,sn as foreignKey,pt as getRegisteredControllers,ht as getRoutes,_t as getWebhookManifest,yn as increment,nn as index,an as integer,on as jsonb,wn as now,ln as numeric,cn as ownedByUser,dn as policy,un as raw,pn as sqlType,Vt as t,hn as text,fn as timestamp,mn as userRef,gn as uuid,xn as z};
12
+ `),process.exit(0),new C}let i=xe(s),o=await Re(i);o&&d.info(`[palbase] strings: ${o.source} and ${o.locales.length-1} other language(s), ${Object.keys(o.strings).length} sentence(s), from ${i}/palbase/strings`),ne(o?void 0:i);let c=e.db?D(e.db):void 0,l=await Q({env:s,url:e.palbase?.url,secretKey:e.palbase?.secretKey});l&&d.info(`[palbase] secrets: ${l.loaded.length} from the project's ${l.set} set${l.kept.length>0?`; ${l.kept.join(", ")} kept as the environment gives them`:""}`),l&&l.refused.length>0&&d.warn(`[palbase] secrets not set \u2014 names a process reads as its own, not the app's: ${l.refused.map(w=>JSON.stringify(w)).join(", ")}`);let u=Mr(r)||c!==void 0&&U(c),h=Se(e.palbase??{},s,{needsWebhookSecret:u});u&&h.webhookSecret===void 0&&d.warn("[palbase] events: none is delivered here \u2014 the platform delivers them to the app's machine, not to this computer; its @On handlers (and forgetting a deleted user's rows) run there. Set PALBASE_WEBHOOK_SECRET to take a delivery forwarded here");let f=R({url:h.url,secretKey:h.secretKey}),m=e.port??Number(s.PORT??"8080");if(!Number.isInteger(m)||m<0||m>65535)throw new Error(`[palbase] PORT is a port number, not ${String(e.port??s.PORT)}`);let y=e.db?await we(e.db,s,h.secretKey,{onPlatform:h.platformSecret!==void 0,embed:Pe(f),fields:f.fields}):void 0;y&&d.info(`[palbase] database: version ${y.binding.version}`);let S=y&&U(y.model)?{"user.deleted":[w=>Lr(y,w)]}:void 0,b=h.platformSecret===void 0?void 0:{secret:h.platformSecret},p=e.requestTelemetry===!1?void 0:new $(f.analytics),k=()=>I({modules:r,verifier:new B({issuer:h.url,projectId:h.projectId,standing:Y({url:h.url,secretKey:h.secretKey})}),server:f,webhookSecret:h.webhookSecret,env:s,projectId:h.projectId,telemetry:p,auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:jr(e.cors,s.PALBASE_WEB_ORIGINS),platform:b,events:S,database:y&&{app:y.app,requests:y.requests,keptAnswers:y.keptAnswers},strings:o}),v=k(),q=e.boot?.attempts??5,W=e.boot?.backoffMs??1e3;for(let w=1;;w++)try{await v.start();break}catch(A){if(w>=q)throw d.error(`[palbase] the app did not start after ${q} attempts`,{error:A}),A;d.warn(`[palbase] the app did not start (attempt ${w} of ${q}); trying again in ${W} ms`,{error:A}),await new Promise(De=>setTimeout(De,W)),W*=2,v=k()}return Dr(v,f,m,e.host??"0.0.0.0",e.exitOnFatal??!0,y)}};function xe(t){let e=t.PALBASE_CONTRACT_ENTRY??process.argv[1];if(!e)return process.cwd();let r=T(_e(e));for(;!z(H(r,"package.json"))&&T(r)!==r;)r=T(r);return z(H(r,"package.json"))?r:process.cwd()}async function Re(t){try{return await ae(t)}catch(e){throw new Error(`[palbase] the app's strings: ${e instanceof Error?e.message:String(e)}`)}}async function $r(t,e,r){let s=_e(r.PALBASE_CONTRACT_ENTRY??process.argv[1]??"");if(!/\.[cm]?tsx?$/.test(s))throw new Error(`the contract is read from the app's TypeScript source, and this run's entry is ${s||"none"}: start it from its source (bun run src/main.ts), or name the source's entry in PALBASE_CONTRACT_ENTRY`);let n=T(s);for(;!z(H(n,"package.json"))&&T(n)!==n;)n=T(n);let{analyzeProject:a}=await import("../chunks/4LZMYSZA.js"),{routeContracts:i}=await import("../chunks/HAHKHE2Q.js"),o=a(n,s);for(let u of o.warnings)d.warn(`[palbase] the contract: ${u}`);let c="https://contract.palbase.invalid",l=I({modules:t,verifier:new B({issuer:c,projectId:"contract",standing:()=>Promise.reject(new Error("the contract run serves nothing"))}),server:R({url:c,secretKey:"pb_contract_s"}),env:r,projectId:"contract",auth:e.auth,tokens:e.tokens,rateLimit:e.rateLimit,maxBodyBytes:e.bodyLimit,cors:e.cors,contractOnly:{database:e.db!==void 0,routes:await i(o.routes),errors:se()},events:e.db&&U(D(e.db))?{"user.deleted":[]}:void 0});return JSON.stringify(l.contract())}var C=class extends Error{constructor(){super("[palbase] the contract run ended"),this.name="ContractRunEnded"}},j=class extends Error{code;constructor(e){super(`[palbase] the migration run ended with ${e}`),this.name="MigrationRunEnded",this.code=e}};async function Lr(t,e){let r=e.data?.user_id;if(typeof r!="string"||r==="")throw new Error("[palbase] user.deleted without a user_id");let s=await t.forget(r,V.$asService());d.info(`[palbase] user ${r} deleted: ${s.deleted} row(s) gone, ${s.detached} forgot them`)}async function Dr(t,e,r,s,n,a){let i,o={on:!1},c=(b,p)=>new URL(b.url).pathname===Fr&&b.method==="GET"?Promise.resolve(o.on?Response.json({ok:!1,stopping:!0},{status:503}):Response.json({ok:!0})):t.handle(b,p),l=Or((b,p)=>{Ur(c,b,p,o).finally(()=>{o.on&&l.closeIdleConnections()})});l.keepAliveTimeout=29e4,l.headersTimeout=3e5;try{await new Promise((b,p)=>{l.once("error",p),l.listen(r,s,()=>b())})}catch(b){throw await t.stop(),await a?.close(),b}let u=l.address().port;d.info(`[palbase] serving ${t.routes.length} route(s) on :${u}`,{routes:t.routes}),a?.search?.start();let h=b=>i??=(async()=>{d.info("[palbase] stopping: finishing the requests in flight"),o.on=!0;let p=new Promise(v=>l.close(()=>v()));l.closeIdleConnections();let k=setTimeout(()=>l.closeAllConnections(),b);await p,clearTimeout(k),process.off("SIGINT",y),process.off("uncaughtException",S),process.off("unhandledRejection",S);try{await t.stop(),await a?.search?.stop(),await a?.close()}finally{process.off("SIGTERM",y)}})(),f=()=>h(Ee),m=!1,y=()=>{if(m){d.info("[palbase] stopping: told to stop again; the requests in flight are still being finished");return}m=!0;let b=setTimeout(()=>{d.error("[palbase] stopping took longer than it is given; the process ends"),process.exit(1)},Ee+Br);b.unref(),f().then(()=>{clearTimeout(b),process.exit(0)},p=>{clearTimeout(b),d.error("[palbase] stopping failed; the process ends",{error:p}),process.exit(1)})},S=b=>{d.error("[palbase] the app crashed; stopping so the machine starts it again",{error:b});let p=setTimeout(()=>process.exit(1),Te+1e3);h(Te).finally(()=>{clearTimeout(p),process.exit(1)})};return process.on("SIGTERM",y),process.once("SIGINT",y),n&&(process.on("uncaughtException",S),process.on("unhandledRejection",S)),{routes:t.routes,palbase:e,port:u,handle:c,close:f}}async function Ur(t,e,r,s){try{let n=e.url??"/",a;try{if(!n.startsWith("/"))throw new TypeError("the request target is not a path");a=new URL(`http://localhost${n}`)}catch{r.statusCode=400,r.end();return}let i=new Headers;for(let[h,f]of Object.entries(e.headers))if(f!==void 0)if(Array.isArray(f))for(let m of f)i.append(h,m);else i.set(h,f);let o=e.method!=="GET"&&e.method!=="HEAD",c=new AbortController;r.on("close",()=>{r.writableFinished||c.abort(new Error("the client closed the connection"))});let l=new Request(a,{method:e.method,headers:i,body:o?Cr.toWeb(e):void 0,duplex:"half",signal:c.signal}),u=await t(l,{remoteAddress:e.socket.remoteAddress,target:n});if(r.statusCode=u.status,u.headers.forEach((h,f)=>r.setHeader(f,h)),s.on&&r.setHeader("connection","close"),u.body)for await(let h of u.body)r.write(h);r.end()}catch(n){d.error("[palbase] the request could not be answered",{error:n}),r.headersSent||(r.statusCode=500),r.end()}}function jr(t,e,r=s=>console.warn(s)){let s=(e??"").split(",").map(o=>o.trim()).filter(o=>o!=="");if(s.length===0||t?.origins==="*")return t;let n=s.filter(o=>G(o)),a=s.filter(o=>!G(o));a.length>0&&r(`[palbase] the project's web origins ${a.map(o=>JSON.stringify(o)).join(", ")} are not CORS origins (https://host[:port], http only for localhost): browsers there are not let in`);let i=[...new Set([...t?.origins??[],...n])];return i.length===0?t:{...t,origins:i}}import{bigint as Js,boolean as Qs,check as Xs,date as Zs,defineSchema as en,defineTable as tn,enumType as rn,foreignKey as sn,index as nn,integer as an,jsonb as on,numeric as ln,ownedByUser as cn,policy as dn,raw as un,sqlType as pn,text as hn,timestamp as fn,userRef as mn,uuid as gn}from"palgres/dsl";import{increment as yn,now as wn}from"palgres";function x(t){if(t instanceof E)return{data:null,error:{code:t.code,message:t.message},status:t.status};throw t}async function P(t,e){try{let r=await t();return{data:await e(r.data),error:null,status:r.status}}catch(r){return x(r)}}var Nr=_("Secrets",{async get(t){if(J(t))return null;let e=process.env[t];return typeof e=="string"&&e!==""?e:null}}),qr=100,Wr=1e3,Kr=168*3600,Vr={s:1,m:60,h:3600,d:86400};function Gr(t){let e=String(t).trim();if(!/^(\d+(\.\d+)?[dhms])+$/.test(e))return;let r=0;for(let[,s,,n]of e.matchAll(/(\d+(\.\d+)?)([dhms])/g))r+=Math.round(Number(s)*Vr[n]*1e3);return Math.ceil(r/1e3)}function $e(t,e,r){let s="getPublicUrl",n;try{n=String(e).split("/").map(i=>K(s,"path",i)).join("%2F")}catch(i){throw i instanceof E&&i.code==="invalid_path_parameter"?new E({op:s,status:0,code:"invalid_path_parameter",message:`${s}: the object path ${JSON.stringify(e)} has an empty, "." or ".." segment: storage keeps no such object`}):i}let a=`${g.url}/storage/public/${K(s,"bucket",t)}/${n}`;return r?`${a}?variant=${encodeURIComponent(r)}`:a}function Oe(t){return{path:t.path,name:t.path,bucket:t.bucket,size:t.size,contentType:t.content_type,checksum:t.checksum_sha256,...t.width!==void 0?{width:t.width}:{},...t.height!==void 0?{height:t.height}:{},...t.thumbhash!==void 0?{thumbhash:t.thumbhash}:{},variants:Object.fromEntries(Object.keys(t.variants??{}).map(e=>[e,$e(t.bucket,t.path,e)]))}}function zr(t){return{async upload(e,r,s){let n=s?.contentType??(r instanceof Blob&&r.type!==""?r.type:void 0);try{let a=await g.storage.putObject({path:{bucket:t,path:e},headers:s?.upsert?void 0:{"If-None-Match":"*"},body:r,contentType:n});return{data:Oe(a.data),error:null,status:a.status}}catch(a){return a instanceof E&&a.status===412&&a.code==="object_exists"?{data:null,error:{code:"already_exists",message:"An object already exists at that path: upload with { upsert: true } to replace it"},status:409}:x(a)}},async download(e){try{let r=await g.storage.getObject({path:{bucket:t,path:e}});if(r.status===304)throw new Error("storage answered 304 to a read that sent no entity tag");let s=r.data;try{return{data:await s.blob(),error:null,status:r.status}}catch(n){return{data:null,error:{code:"network_error",message:`the object's bytes stopped arriving: ${n instanceof Error?n.message:String(n)}`},status:0}}}catch(r){return x(r)}},getPublicUrl(e,r){return $e(t,e,r?.variant)},async createSignedUrl(e,r){let s=Gr(r?.expiresIn);return s===void 0||s<1||s>Kr?{data:null,error:{code:"bad_request",message:`expiresIn is a duration from 1s to 7d, like "15m", "1h" or "7d" (got ${JSON.stringify(r?.expiresIn)})`},status:400}:P(()=>g.storage.createSignedUrl({path:{bucket:t},body:{path:e,expires_in:s}}),n=>({signedUrl:n.url,expiresAt:n.expires_at}))},async list(e,r){let s=r?.limit??qr,n=r?.offset??0;if(!Number.isInteger(s)||s<0||!Number.isInteger(n)||n<0)return{data:null,error:{code:"bad_request",message:"limit and offset are whole numbers, 0 or more"},status:400};let a=[],i,o=200;try{for(;a.length<s;){let c=Math.max(1,Math.min(Wr,n+s-a.length)),l=await g.storage.listObjects({path:{bucket:t},query:{...e?{prefix:e}:{},limit:c,...i?{cursor:i}:{}}});o=l.status;for(let u of l.data.objects)n>0?n--:a.length<s&&a.push(Oe(u));if(i=l.data.next_cursor,!i)break}}catch(c){return x(c)}return{data:a,error:null,status:o}},async remove(e){let r=[];for(let s of e){try{await g.storage.deleteObject({path:{bucket:t,path:s}})}catch(n){return x(n)}r.push({path:s,name:s,bucket:t,size:0,contentType:"",checksum:"",variants:{}})}return{data:r,error:null,status:200}},move(e,r){return P(()=>g.storage.moveObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})},copy(e,r){return P(()=>g.storage.copyObject({path:{bucket:t},body:{from:e,to:r}}),()=>{})}}}var Hr={bucket:zr},Ce=t=>te("Storage",t,Hr),Yr={bucket:t=>Ce("bucket").bucket(t),buckets:new Proxy({},{get:(t,e)=>typeof e=="string"?Ce("buckets").bucket(e):void 0})},Jr=_("Notifications",{push:{send(t){let{to:e,...r}=t,s=typeof e=="string"?{user_ids:[e]}:Array.isArray(e)?{user_ids:e}:{topic:e.topic};return P(()=>g.notify.sendPush({body:{...r,to:s}}),n=>({message_ids:n.message_ids,recipients:n.message_ids.length,skipped_user_ids:n.skipped_user_ids}))}},email:{async send(t){let{to:e,templateSlug:r,...s}=t,n={...s,...r!==void 0?{template:r}:{}};if(!Array.isArray(e))return P(()=>g.notify.sendEmail({body:{...n,to:e}}),o=>({...o.message_id!==void 0?{message_id:o.message_id}:{},...o.skipped?{skipped:!0}:{}}));let a=[],i=202;for(let o of e)try{let c=await g.notify.sendEmail({body:{...n,to:o}});i=c.status,a.push(c.data.message_id??null)}catch(c){return x(c)}return{data:{message_ids:a},error:null,status:i}}}}),Be=t=>typeof t=="boolean"?t:t!=null&&t!==0&&t!=="",Fe=t=>typeof t=="string"?{name:t}:null,Me=t=>t==="override"?"user":t,Qr=t=>t!==null&&typeof t=="object"&&!Array.isArray(t)&&"userId"in t;function Le(){return re.getStore()?.userId}function N(t){let e=t&&"userId"in t?t.userId??void 0:Le();return P(()=>e?g.flags.getUserValues({path:{user_id:e}}):g.flags.getValues(),r=>r.values??{})}var Ie={setOverrideForUser:(t,e,r)=>P(()=>g.flags.putUserValue({path:{user_id:t,key:e},body:{value:r}}),s=>({key:s.key,value:s.value,source:Me(s.source)})),setOverridesForUser:(t,e)=>P(()=>g.flags.putUserValues({path:{user_id:t},body:{values:e}}),r=>({values:r.values??{}})),clearOverrideForUser:(t,e)=>P(()=>g.flags.deleteUserValue({path:{user_id:t,key:e}}),r=>({key:r.key,value:r.value,source:Me(r.source)})),clearAllOverridesForUser:t=>P(()=>g.flags.deleteUserValues({path:{user_id:t}}),e=>({deleted:e.deleted})),batchSetOverrides:t=>P(()=>g.flags.batchUserValues({body:{operations:t.map(e=>({user_id:e.userId,values:e.values}))}}),e=>({applied:e.applied}))},Xr=_("Flags",{async isEnabled(t,e){let r=s=>(d.warn(`[palbase] flag "${t}" could not be read (${s}): treating it as off`),!1);try{let s=await N(e);return s.error?r(`${s.error.code}: ${s.error.message}`):Be(s.data[t])}catch(s){return r(s instanceof Error?s.message:String(s))}},async getVariant(t,e){let r=await N(e);return r.error?{data:null,error:r.error,status:r.status}:{data:Fe(r.data[t]),error:null,status:r.status}},async getAll(t){let e=await N(t);return e.error?{data:null,error:e.error,status:e.status}:{data:Object.entries(e.data).map(([r,s])=>{let n=Fe(s);return{name:r,enabled:Be(s),...n?{variant:n}:{}}}),error:null,status:e.status}},async get(t,e,r){let s,n=!1,a;r!==void 0?(s=e,n=!0,a=r):Qr(e)?a=e:e!==void 0&&(s=e,n=!0);let i=await N(a);if(i.error)return n?{data:s??null,error:null,status:i.status}:{data:null,error:i.error,status:i.status};let o=i.data[t];return{data:o===void 0?s??null:o,error:null,status:i.status}},async setOverride(t,e){let r=Le();return r?Ie.setOverrideForUser(r,t,e):{data:null,error:{code:"no_user",message:"Flags.setOverride writes the signed-in user's value: this request has none \u2014 Flags.$asService().setOverrideForUser(userId, key, value) writes anyone's"},status:400}},$asService(){return Ie}}),Zr=_("Realtime",{broadcast(t,e,r){return P(()=>g.realtime.broadcast({body:{messages:[{topic:t,event:e,payload:r??{}}]}}),()=>{})},state:{set(t,e,r){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,value:r}]}}),()=>{})},clear(t,e){return P(()=>g.realtime.writeState({body:{ops:[{topic:t,key:e,delete:!0}]}}),()=>{})}}});import{z as xn}from"zod";export{at as AttestedDevice,Ne as AuthUnavailable,At as Authorize,It as BadRequest,Ye as Body,zt as CACHE_MAX_TTL,Ht as Cache,Pt as ChatPart,nt as Client,$t as Conflict,C as ContractRunEnded,qe as Controller,dt as Cron,V as Database,Lt as DeadlockDetected,ze as Delete,Ot as DiError,Ue as EVENT_TYPES,Xr as Flags,Ft as Forbidden,vt as Gateway,St as GatewayRefusal,We as Get,Qe as Headers,Dt as HttpError,it as Injectable,d as Log,Gt as MAX_BODY_BYTES,j as MigrationRunEnded,lt as Module,Ut as NotFound,Jr as Notifications,ct as On,Et as OnConnect,Tt as OnDisconnect,xt as OnEmpty,kt as OnFirst,et as OptionalUser,Ct as PalError,g as Palbase,E as PalbaseError,Ir as PalbaseFactory,Xe as Param,Ge as Patch,Ke as Post,Ve as Put,He as Query,Je as QueryParams,Zr as Realtime,tt as Req,rt as RequestId,ot as Resolve,L as SchemaNotPushed,Nr as Secrets,jt as SerializationFailure,Yr as Storage,Rt as Subscribe,mt as Task,ft as TaskFailure,gt as Tasks,bt as TestUserTemplate,je as TokenError,B as TokenVerifier,Nt as TooManyRequests,st as TraceId,Bt as Unauthorized,qt as UniqueViolation,yt as Upload,wt as UploadedObject,Ze as User,ut as Webhook,Js as bigint,Qs as boolean,Xs as check,I as createApp,Zs as date,Mt as defineError,en as defineSchema,tn as defineTable,Kt as encrypt,Wt as encrypted,rn as enumType,sn as foreignKey,pt as getRegisteredControllers,ht as getRoutes,_t as getWebhookManifest,yn as increment,nn as index,an as integer,on as jsonb,wn as now,ln as numeric,cn as ownedByUser,dn as policy,un as raw,pn as sqlType,Vt as t,hn as text,fn as timestamp,mn as userRef,gn as uuid,xn as z};
@@ -1 +1 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
@@ -1,2 +1,2 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{a as u}from"../chunks/ZTGSTF3B.js";import{c as p,i as c}from"../chunks/D4KYGGQC.js";import"../chunks/OHNIWLO3.js";import{b as l,c as g,d as f,e as y}from"../chunks/Z7RZBBBS.js";import"../chunks/LO6DFZ7L.js";import"../chunks/Z5QBR46U.js";import"../chunks/RCUVA3QW.js";import"../chunks/4ZMAF4YF.js";import"../chunks/HEHSHDUM.js";import"../chunks/5QE5KFNR.js";import"../chunks/Q4VZ2BNE.js";import"../chunks/FDAOVX6B.js";import"reflect-metadata";import{randomUUID as m}from"node:crypto";import{createFakeClient as w,typedDatabase as d}from"palgres/testing";function T(t,n,a){if(a?.acceptLanguage!==void 0&&a.strings===void 0)throw new TypeError("withServices: acceptLanguage chooses among the languages of a strings table, and none was given \u2014 { strings: await loadStringsTable(appRoot), acceptLanguage }");let{Database:r,...o}=t,e=a?.strings;return p.run({requestId:`test_${m()}`,database:r===void 0?void 0:d(r),services:o,...e!==void 0?{strings:e,locales:c(a?.acceptLanguage??null,e.source),usedLocales:[]}:{}},n)}function b(){let t=new Map,n=new Map,a=[],r=e=>{if(t.has(e))return t.get(e);if(n.has(e))return n.get(e);if(a.includes(e)){let s=[...a.slice(a.indexOf(e)),e].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${s.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}a.push(e);try{let s=Reflect.getMetadata("design:paramtypes",e)??[],i=new e(...s.map(r));return n.set(e,i),i}finally{a.pop()}},o={with(e,s){return t.set(e,s),o},get:e=>r(e)};return o}function h(){let t=w();return{db:d(t),raw:t,queries:t.queries,seed:(n,a)=>t.seed(n,a),inserted:n=>t.inserted(n),updated:n=>t.updated(n),deleted:n=>t.deleted(n)}}export{l as TestApiError,y as api,g as createTestApi,h as fakeDatabase,b as isolated,u as loadStringsTable,f as testRun,T as withServices};
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as u}from"../chunks/X7T5ZRUE.js";import{c as p,i as c}from"../chunks/FXF4QMOQ.js";import"../chunks/5FC4ZZTY.js";import{b as l,c as g,d as f,e as y}from"../chunks/2L2UBNP2.js";import"../chunks/5CV5NIXC.js";import"../chunks/ZW4OIDTK.js";import"../chunks/XGLNNBME.js";import"../chunks/YGQVQEVB.js";import"../chunks/S7VKVW6I.js";import"../chunks/YNE6YXJM.js";import"../chunks/BWWL27VF.js";import"../chunks/4YIEZ7GQ.js";import"reflect-metadata";import{randomUUID as m}from"node:crypto";import{createFakeClient as w,typedDatabase as d}from"palgres/testing";function T(t,n,a){if(a?.acceptLanguage!==void 0&&a.strings===void 0)throw new TypeError("withServices: acceptLanguage chooses among the languages of a strings table, and none was given \u2014 { strings: await loadStringsTable(appRoot), acceptLanguage }");let{Database:r,...o}=t,e=a?.strings;return p.run({requestId:`test_${m()}`,database:r===void 0?void 0:d(r),services:o,...e!==void 0?{strings:e,locales:c(a?.acceptLanguage??null,e.source),usedLocales:[]}:{}},n)}function b(){let t=new Map,n=new Map,a=[],r=e=>{if(t.has(e))return t.get(e);if(n.has(e))return n.get(e);if(a.includes(e)){let s=[...a.slice(a.indexOf(e)),e].map(i=>i.name??String(i));throw new TypeError(`isolated(): ${s.join(" \u2192 ")} needs itself to be built \u2014 give one of them with .with(Token, value)`)}a.push(e);try{let s=Reflect.getMetadata("design:paramtypes",e)??[],i=new e(...s.map(r));return n.set(e,i),i}finally{a.pop()}},o={with(e,s){return t.set(e,s),o},get:e=>r(e)};return o}function h(){let t=w();return{db:d(t),raw:t,queries:t.queries,seed:(n,a)=>t.seed(n,a),inserted:n=>t.inserted(n),updated:n=>t.updated(n),deleted:n=>t.deleted(n)}}export{l as TestApiError,y as api,g as createTestApi,h as fakeDatabase,b as isolated,u as loadStringsTable,f as testRun,T as withServices};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{b}from"./Z5QBR46U.js";import{a as k,b as A}from"./Q4VZ2BNE.js";import{randomBytes as _}from"node:crypto";async function N(){let n={keys:[{id:"k1",key:_(32).toString("base64url"),activates_at:new Date(0).toISOString()}],lookup:_(32).toString("base64url")},e=new b({fetch:async()=>n});return await e.load(),e.close(),e}var f=class extends Error{status;error;data;body;constructor(e,a,l,d){let u=d!==null&&typeof d=="object"?d:{},o=u.error??String(l);super(`${e} ${a} \u2192 ${l} ${o}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=o,this.data=u.data,this.body=u}};function x(n,e){if(!n)throw new Error(`${e} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function B(n){let e=n.split(".")[1];if(!e)return null;try{let a=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function L(n){try{return JSON.parse(n)}catch{return n}}function $(n){let e=x(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??e).replace(/\/+$/,""),d=n.fetch??fetch,u=[],o=null;async function c(r,t,s,i,T={},O=!0){let g={...T.headers},m=h=>Object.keys(g).some(R=>R.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),o&&O&&!m("authorization")&&(g.authorization=`Bearer ${o}`),i!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let I=Date.now(),p=await d(`${r}${s}`,{method:t,headers:g,body:i===void 0?void 0:JSON.stringify(i)}),E=await p.text(),S=E?L(E):void 0;if(u.push({method:t,path:s,status:p.status,ms:Date.now()-I}),!p.ok){let h=p.status===401&&o?B(o):null;throw h!==null&&h<=0?new f(t,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new f(t,s,p.status,S)}return S}let y={requests:u,get:(r,t)=>c(e,"GET",r,void 0,t),post:(r,t,s)=>c(e,"POST",r,t,s),patch:(r,t,s)=>c(e,"PATCH",r,t,s),put:(r,t,s)=>c(e,"PUT",r,t,s),delete:(r,t)=>c(e,"DELETE",r,void 0,t),query:(r,t,s)=>c(e,"QUERY",r,t,s),async signInAs(r){let t=n.identities?.[r];if(!t){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return t.accessToken?(o=t.accessToken,{id:t.id??"",email:t.email}):y.signIn(t)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let t=i=>c(l,"POST","/auth/login",r,i?{headers:i}:{},!1),s;try{s=await t()}catch(i){let T=i instanceof f&&i.status===403?k(i.body):null;if(!T)throw i;s=await t(await A(T))}return o=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),o=null},asAnonymous(){o=null}};return y}function P(n){if(!n)return{};let e;try{e=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return e}var j={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(P(process.env.PALBASE_TEST_IDENTITIES),n)}},w,q=new Proxy({},{get(n,e){return w??=$({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:P(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,e,w)}});export{N as a,f as b,$ as c,j as d,q as e};
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
2
+ import{b}from"./ZW4OIDTK.js";import{a as k,b as A}from"./BWWL27VF.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,5 +1,5 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import"./FDAOVX6B.js";import{realpathSync as Je}from"node:fs";import{resolve as ge}from"node:path";import vt from"typescript";import{existsSync as he,readFileSync as be}from"node:fs";import{createRequire as Qe}from"node:module";import{dirname as re,join as G,relative as We,resolve as xe,sep as ne}from"node:path";var b=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},Z=new Set(["palbase/backend","@palbase/backend","palgres"]),Ge=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function we(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new b(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var Ze={bun:"bun-types",node:"@types/node"},He=Qe(import.meta.url);function Xe(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=Ze[i],a=e.resolveTypeReferenceDirective(i,G(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=He.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(be(c,"utf8"));s.push(G(re(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function ke(e,t){we(e);let n=G(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(he(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new b(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
2
+ import"./4YIEZ7GQ.js";import{realpathSync as Je}from"node:fs";import{resolve as ge}from"node:path";import vt from"typescript";import{existsSync as he,readFileSync as be}from"node:fs";import{createRequire as Qe}from"node:module";import{dirname as re,join as G,relative as We,resolve as xe,sep as ne}from"node:path";var b=class extends Error{constructor(t){super(t),this.name="ContractAnalysisError"}},Z=new Set(["palbase/backend","@palbase/backend","palgres"]),Ge=new Set(["Get","Post","Put","Patch","Delete","Query","Upload"]);function we(e){if(typeof e.createProgram!="function"||typeof e.getDecorators!="function"||typeof e.readConfigFile!="function")throw new b(`the contract is read with TypeScript's compiler API, and the TypeScript given (v${e.version??"unknown"}) has none \u2014 TypeScript 7 is the Go-native compiler, whose package exposes version metadata only`)}var Ze={bun:"bun-types",node:"@types/node"},He=Qe(import.meta.url);function Xe(e,t,n){if(!n.types)return{types:void 0,files:[]};let r=[],s=[];for(let i of n.types){let o=Ze[i],a=e.resolveTypeReferenceDirective(i,G(t,"tsconfig.json"),n,e.sys).resolvedTypeReferenceDirective,c;if(!a&&o)try{c=He.resolve(`${o}/package.json`)}catch{c=void 0}if(!c){r.push(i);continue}let l=JSON.parse(be(c,"utf8"));s.push(G(re(c),l.types??l.typings??"index.d.ts"))}return{types:r,files:s}}function ke(e,t){we(e);let n=G(t,"tsconfig.json"),r={target:e.ScriptTarget.ES2022,module:e.ModuleKind.ESNext,moduleResolution:e.ModuleResolutionKind.Bundler,experimentalDecorators:!0,allowImportingTsExtensions:!0},s=[];if(he(n)){let i=e.readConfigFile(n,e.sys.readFile);if(i.error)throw new b(`${n}: ${e.flattenDiagnosticMessageText(i.error.messageText,`
3
3
  `)}`);let o=e.parseJsonConfigFileContent(i.config,e.sys,t);r=o.options,s=o.fileNames.filter(c=>/\.d\.[cm]?ts$/.test(c));let a=Xe(e,t,r);r={...r,types:a.types},s=[...s,...a.files]}return{options:{...r,strictNullChecks:!0,noEmit:!0,skipLibCheck:!0},ambient:s}}function Ee(e,t,n,r,s){we(e);let i=e.createProgram([...new Set(n)],r,s);return{ts:e,root:t,program:i,checker:i.getTypeChecker(),packages:new Map}}function $(e,t){let n=xe(t);return!n.includes(`${ne}node_modules${ne}`)&&!/\.d\.[cm]?ts$/.test(n)&&(n===e.root||n.startsWith(e.root+ne))}function v(e,t){return!!t&&$(e,t.getSourceFile().fileName)}function Ce(e,t){let n=[],r=re(xe(t)),s=null;for(;;){let i=e.packages.get(r);if(i!==void 0){s=i;break}n.push(r);let o=G(r,"package.json");if(he(o)){try{let c=JSON.parse(be(o,"utf8")).name;s=typeof c=="string"?c:null}catch{s=null}break}let a=re(r);if(a===r)break;r=a}for(let i of n)e.packages.set(i,s);return s}function se(e,t){if($(e,t))return!1;let n=Ce(e,t)??"";return n==="palbase"?/[\\/]types[\\/]backend[\\/]/.test(t):Z.has(n)}function ie(e,t){if($(e,t))return!1;let n=Ce(e,t)??"";return Z.has(n)||n==="palbase"||n.startsWith("@palbase/")}function O(e,t){let n=t.getSourceFile(),{line:r}=n.getLineAndCharacterOfPosition(t.getStart(n));return`${We(e.root,n.fileName)}:${r+1}`}function T(e,t){for(;t;){if(e.isParenthesizedExpression(t)||e.isAsExpression(t)||e.isNonNullExpression(t)||e.isAwaitExpression(t)||e.isTypeAssertionExpression(t)||e.isSatisfiesExpression(t)){t=t.expression;continue}return t}return t}function H(e,t){if(t&&t.flags&e.ts.SymbolFlags.Alias){let n=e.checker.getAliasedSymbol(t);if(n&&n.declarations)return n}return t}function L(e,t){let n=H(e,e.checker.getSymbolAtLocation(t));return n&&(n.valueDeclaration||n.declarations&&n.declarations[0])||null}function ye(e,t){let n=t;for(;n&&!e.isImportDeclaration(n)&&!e.isExportDeclaration(n);)n=n.parent;return n&&(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier&&e.isStringLiteral(n.moduleSpecifier)?n.moduleSpecifier.text:null}function I(e,t){let n=e.ts;if(t=T(n,t),!t)return null;if(n.isPropertyAccessExpression(t)){let i=e.checker.getSymbolAtLocation(t.expression);return i&&(i.declarations||[]).some(a=>n.isNamespaceImport(a)&&Z.has(ye(n,a)??""))?t.name.text:null}if(!n.isIdentifier(t))return null;let r=e.checker.getSymbolAtLocation(t),s=new Set;for(;r&&!s.has(r);){s.add(r);for(let i of r.declarations||[]){if((n.isImportSpecifier(i)||n.isExportSpecifier(i))&&Z.has(ye(n,i)??""))return(i.propertyName||i.name).text;if(se(e,i.getSourceFile().fileName))return r.name}if(!(r.flags&n.SymbolFlags.Alias))return null;r=e.checker.getImmediateAliasedSymbol(r)}return null}function Te(e,t){let n=t.expression;return I(e,e.ts.isCallExpression(n)?n.expression:n)}function P(e,t){return t&&(e.isIdentifier(t)||e.isPrivateIdentifier(t)||e.isStringLiteral(t)||e.isNumericLiteral(t))?t.text:null}function X(e,t){let n=e.ts,r=[];for(let s of t.statements){if(!n.isClassDeclaration(s)||!(n.getDecorators(s)||[]).some(o=>Te(e,o)==="Controller"))continue;if(!s.name)throw new b(`${O(e,s)} \u2014 a @Controller class needs a name \u2014 its routes' errors are bound to it by name`);let i=[];for(let o of s.members)if(!(!n.isMethodDeclaration(o)||!o.body)&&(n.getDecorators(o)||[]).some(a=>Ge.has(Te(e,a)??""))){if(P(n,o.name)===null)throw new b(`${O(e,o)} \u2014 a route method needs a plain name; the contract reaches it by name`);i.push(o)}r.push({cls:s,routes:i})}return r}var Ye=new Set([2307,2580,2582,2583,2584,2591,2592,2593,2688,2867,2868,7016]);function et(e){let t=e.getSymbol();return t?.getName()==="Response"&&(t.declarations??[]).length>0&&(t.declarations??[]).every(n=>n.getSourceFile().isDeclarationFile)}function Ne(e){let{ts:t,program:n,checker:r}=e,s=!1;return function(o,a){let c=o.getSourceFile().fileName,l=o.name.getText(o.getSourceFile()),u=d=>{throw new b(`${c} \u2014 ${a}.${l}: cannot infer a safe response contract (${d}). Use a named Zod return schema for this response; any/unknown is never emitted as a successful contract.`)};if(!s){let d=[];for(let p of n.getSourceFiles()){if(d.length>=5)break;p.isDeclarationFile||n.isSourceFileFromExternalLibrary(p)||/[\\/]node_modules[\\/]/.test(p.fileName)||ie(e,p.fileName)||d.push(...n.getSemanticDiagnostics(p).filter(x=>x.category===t.DiagnosticCategory.Error&&!Ye.has(x.code)))}d.length&&u(t.formatDiagnostics(d.slice(0,5),{getCanonicalFileName:p=>p,getCurrentDirectory:()=>e.root,getNewLine:()=>`
4
4
  `})),s=!0}let m=r.getSignatureFromDeclaration(o),g=m&&r.getAwaitedType(r.getReturnTypeOfSignature(m));if(!g)return u("unresolved return type");if(g.flags&(t.TypeFlags.Void|t.TypeFlags.Undefined))return{kind:"void"};if(et(g))return{kind:"raw"};function y(d){let p=d.getSymbol();if(p?.getName()!=="Encrypted"||!(p.declarations??[]).some(S=>ie(e,S.getSourceFile().fileName)))return;let x=r.getTypeArguments(d);return x.length===1?x[0]:void 0}let f=new Set,V=0;function h(d,p){if(++V>2e3||f.size>24)return u(`${p}: contract is too large; name its schema`);let x=d.flags,S=t.TypeFlags;if(x&(S.Any|S.Unknown|S.Never|S.TypeParameter))return u(`${p}: ${r.typeToString(d)}`);let pe=y(d);if(pe)return`encrypted(${h(pe,p)})`;let Se=w=>{let k=r.getPropertiesOfType(w);if(!(w.flags&S.Object)||k.length!==1||k[0].name!=="__pg"||!(k[0].flags&t.SymbolFlags.Optional)||r.getIndexInfosOfType(w).length)return!1;let N=r.getTypeOfSymbolAtLocation(k[0],o);return(N.isUnion()?N.types:[N]).every(E=>E.flags&(S.StringLiteral|S.Undefined))};if(d.isIntersection()){let w=d.types.filter(k=>!Se(k));if(w.length===1&&w.length<d.types.length)return h(w[0],p)}if(Se(d))return u(`${p}: unknown PostgreSQL payload; name its response schema`);if(x&S.StringLiteral)return`z.literal(${JSON.stringify(d.value)})`;if(x&S.NumberLiteral)return`z.literal(${JSON.stringify(d.value)})`;if(x&S.BooleanLiteral)return`z.literal(${r.typeToString(d)==="true"})`;if(x&S.String)return"z.string()";if(x&S.TemplateLiteral){let w=d;if(w.types.length>8||!w.types.every(E=>E.flags&S.String))return u(`${p}: template literal requires an explicit schema`);let k=E=>E.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N="^"+k(w.texts[0]);for(let E of w.texts.slice(1,-1))if(E){let te=k(E);N+=`(?:(?!${te})[\\s\\S])*${te}`}return N+="[\\s\\S]*"+k(w.texts.at(-1))+"$(?![\\s\\S])",N.length>4096?u(`${p}: template pattern is too large`):`z.string().regex(new RegExp(${JSON.stringify(N)}))`}if(x&S.Number)return"z.number().finite()";if(x&S.Boolean)return"z.boolean()";if(x&S.Null)return"z.null()";if(x&S.Undefined)return"z.undefined()";if(f.has(d))return u(`${p}: recursive response`);f.add(d);try{if(d.isUnion()){if(d.types.length>32)return u(`${p}: union has more than 32 alternatives`);let A=d.types.some(M=>M.flags&S.Null),W=d.types.some(M=>M.flags&S.Undefined),j=d.types.filter(M=>!(M.flags&(S.Null|S.Undefined)));return(j.length===0?A?"z.null()":"z.undefined()":j.length===1?h(j[0],p):`z.union([${j.map(M=>h(M,p)).join(",")}])`)+(A&&j.length?".nullable()":"")+(W?".optional()":"")}if(r.isTupleType(d))return u(`${p}: tuple requires an explicit schema`);if(r.isArrayType(d)){let A=r.getTypeArguments(d)[0];return A.flags&S.Never?"z.array(z.string()).length(0)":`z.array(${h(A,`${p}[]`)})`}let w=d.isIntersection()&&d.types.every(A=>A.flags&S.Object);if(!(x&S.Object)&&!w||d.getCallSignatures().length||d.getConstructSignatures().length)return u(`${p}: non-JSON type ${r.typeToString(d)}`);let k=d.symbol?.declarations?.[0];if(k&&(t.isClassDeclaration(k)||t.isClassExpression(k)))return u(`${p}: class instance ${r.typeToString(d)}`);let N=r.getPropertiesOfType(d),E=r.getIndexInfosOfType(d);return E.length?E.length!==1||!(E[0].keyType.flags&S.String)||N.length?u(`${p}: mixed or non-string index signature`):`z.record(z.string(), ${h(E[0].type,`${p}.*`)})`:N.length?`z.object({${N.map(A=>{if(A.escapedName.toString().startsWith("__@"))return u(`${p}: symbol property`);let W=A.getName(),j=h(r.getTypeOfSymbolAtLocation(A,o),`${p}.${W}`);return`${JSON.stringify(W)}:${j}${A.flags&t.SymbolFlags.Optional?".optional()":""}`}).join(",")}}).strict()`:u(`${p}: empty structural type`)}finally{f.delete(d)}}return{kind:"expression",expression:h(g,"return")}}}import{resolve as tt}from"node:path";var oe=Symbol("not a named schema");function Ae(e,t,n,r){let{ts:s}=e,i=r.getSourceFile(),o=r.name.getText(i),a=f=>new b(`${i.fileName} \u2014 ${n}.${o}: ${f}`);function c(f){if(s.isTypeReferenceNode(f)&&f.typeName.getText(i)==="Promise"&&f.typeArguments&&f.typeArguments.length===1)return c(f.typeArguments[0]);if(f.kind===s.SyntaxKind.VoidKeyword||f.kind===s.SyntaxKind.UndefinedKeyword)return null;let V=s.isArrayTypeNode(f)?f.elementType:s.isTypeReferenceNode(f)&&f.typeName.getText(i)==="Array"&&f.typeArguments&&f.typeArguments.length===1?f.typeArguments[0]:void 0,h=l(V??f);return h===oe?h:{...h,isArray:V!==void 0}}function l(f){if(s.isTypeReferenceNode(f)&&!f.typeArguments)return{typeName:f.typeName.getText(i),node:f.typeName};if(s.isTypeReferenceNode(f)&&f.typeArguments&&f.typeArguments.length===1){let V=f.typeName.getText(i);if(/^(z\.)?(infer|output|input)$/.test(V)){let h=f.typeArguments[0];if(s.isTypeQueryNode(h))return{typeName:h.exprName.getText(i),node:h.exprName};if(s.isTypeReferenceNode(h)&&!h.typeArguments)return{typeName:h.typeName.getText(i),node:h.typeName}}}if(f.kind===s.SyntaxKind.VoidKeyword)throw a("void cannot appear inside an array/Promise here");return oe}let u=()=>t(r,n);if(!r.type)return u();let m=c(r.type);if(m===null)return{kind:"void"};if(m===oe)return u();let g=nt(e,m.node);if(!g)return u();let y=rt(e,g.symbol);return y?{kind:"schema",...y,array:m.isArray}:u()}function nt(e,t){let{ts:n,checker:r}=e,s=r.getSymbolAtLocation(n.isQualifiedName(t)?t.right:t),i=H(e,s);if(!i||!(i.flags&n.SymbolFlags.Variable))return null;let o=i.valueDeclaration;return!o||!n.isVariableDeclaration(o)||!r.getTypeOfSymbolAtLocation(i,o).getProperty("~standard")?null:{symbol:i}}function rt(e,t){let n=t.valueDeclaration?.getSourceFile();if(!n||n.isDeclarationFile)return null;let r=e.checker.getSymbolAtLocation(n);if(!r)return null;let s=e.checker.getExportsOfModule(r).filter(i=>H(e,i)===t).map(i=>i.name);return s.length===0?null:{file:tt(n.fileName),exportName:s.includes(t.name)?t.name:s[0]}}var ue={BadRequest:{code:"bad_request",status:400,codeArg:null},Unauthorized:{code:"unauthorized",status:401,codeArg:1},Forbidden:{code:"forbidden",status:403,codeArg:1},NotFound:{code:"not_found",status:404,codeArg:1},Conflict:{code:"conflict",status:409,codeArg:1},UniqueViolation:{code:"unique_violation",status:409,codeArg:2},SerializationFailure:{code:"serialization_failure",status:409,codeArg:null},DeadlockDetected:{code:"deadlock_detected",status:409,codeArg:null},TooManyRequests:{code:"too_many_requests",status:429,codeArg:null}},st=new Set(["HttpError","PalError"]),it=[{member:"page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"$page",container:null,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"NotFound",code:"not_found",status:404}},{member:"update",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}},{member:"updateScoped",container:/^RepositoryOf(\$\d+)?$/,error:{name:"BadRequest",code:"bad_request",status:400}}],ot=new Map([["expectOne",0],["expectNone",0],["expectAtLeast",1],["expectAtMost",1]]);function $e(e){let t={...e,ids:new WeakMap,nextId:1,providerSet:null,concrete:null,summaries:new Map,warnings:new Map,statusOf:null,round:0,cyclic:!1,grew:!1};return{analyze(n){let r;for(;t.round+=1,t.cyclic=!1,t.grew=!1,r=At(t,n),!(!t.cyclic||!t.grew););for(let s of t.summaries.values())s.final=!0;return r},warnings(){return[...t.warnings.values()]}}}function at(e,t,n){throw new b(`${O(e,t)} \u2014 ${n}`)}function q(e,t){let n=e.ids.get(t);return n||(n=e.nextId++,e.ids.set(t,n)),n}function de(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Static)!==0}function Fe(e,t){return(e.getCombinedModifierFlags(t)&e.ModifierFlags.Abstract)!==0}function F(e,t){return!!t&&(e.isClassDeclaration(t)||e.isClassExpression(t))}function Oe(e,t){if(!t)return null;if(F(e,t))return t;if((e.isVariableDeclaration(t)||e.isPropertyDeclaration(t)||e.isPropertyAssignment(t))&&t.initializer){let n=T(e,t.initializer);if(e.isClassExpression(n))return n}return null}function ct(e,t){if(t.name)return t.name.text;let n=t.parent;if(n&&(e.isVariableDeclaration(n)||e.isPropertyDeclaration(n)||e.isPropertyAssignment(n))&&n.name&&P(e,n.name))return P(e,n.name)??void 0}function _(e,t){let n=e.ts,r=T(n,t);if(!r)return null;let s=Oe(n,L(e,n.isPropertyAccessExpression(r)?r.name:r));return s&&v(e,s)?s:null}function J(e,t){let n=e.ts,r=(t.heritageClauses||[]).find(i=>i.token===n.SyntaxKind.ExtendsKeyword),s=r&&r.types[0]&&r.types[0].expression;return s?_(e,s):null}function Re(e,t,n){for(let r=J(e,t);r;r=J(e,r))if(r===n)return!0;return!1}function U(e,t,n,r){let s=e.ts;for(let i=t;i;i=J(e,i))for(let o of i.members)if(!(P(s,o.name)!==n||de(s,o)!==r)){if((s.isMethodDeclaration(o)||s.isGetAccessorDeclaration(o))&&o.body)return{fn:o,owner:i};if(s.isPropertyDeclaration(o)&&o.initializer){let a=T(s,o.initializer);if(s.isArrowFunction(a)||s.isFunctionExpression(a))return{fn:a,owner:i}}}return null}function lt(e){let t=e.ts;if(e.providerSet)return e.providerSet;let n=new Set;for(let r of e.program.getSourceFiles())if($(e,r.fileName)){for(let s of r.statements)if(t.isClassDeclaration(s))for(let i of t.getDecorators(s)||[]){let o=i.expression;if(!t.isCallExpression(o)||I(e,o.expression)!=="Module")continue;let a=T(t,o.arguments[0]);if(!(!a||!t.isObjectLiteralExpression(a)))for(let c of a.properties){if(!t.isPropertyAssignment(c)||P(t,c.name)!=="providers")continue;let l=T(t,c.initializer);if(t.isArrayLiteralExpression(l))for(let u of l.elements){let m=_(e,u);m&&n.add(m)}}}}return e.providerSet=n,n}function ve(e){let t=e.ts;if(e.concrete)return e.concrete;let n=[],r=s=>{F(t,s)&&!Fe(t,s)&&n.push(s),t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.concrete=n,n}function ze(e,t){let n=t.name?e.checker.getSymbolAtLocation(t.name):t.symbol;return n?e.checker.getDeclaredTypeOfSymbol(n):null}function ut(e,t){let n=t&&(t.getSymbol()||t.aliasSymbol),r=n&&(n.declarations||[]).find(s=>F(e.ts,s));return r&&F(e.ts,r)&&v(e,r)?r:null}function ae(e,t){return t.type?e.checker.getTypeFromTypeNode(t.type):e.checker.getTypeAtLocation(t.name||t)}function Q(e,t,n){let r=e.ts;if(!t)return;if(t.isUnion()){for(let l of t.types)Q(e,l,n);return}let s=r.TypeFlags,i=s.StringLike|s.NumberLike|s.BigIntLike|s.BooleanLike|s.EnumLike|s.ESSymbolLike|s.VoidLike|s.Null;if(t.flags&(s.Any|s.Unknown|i))return;let o=t.getSymbol();if(!o)return;let a=(o.declarations||[]).find(l=>F(r,l));if(a&&F(r,a)){if(!v(e,a))return;Fe(r,a)||n.add(a);for(let l of ve(e))Re(e,l,a)&&n.add(l);return}if((o.declarations||[]).some(l=>v(e,l)))for(let l of ve(e)){let u=ze(e,l);u&&e.checker.isTypeAssignableTo(u,t)&&n.add(l)}}function fe(e,t,n){let r=ut(e,t);if(r){let s=lt(e);if(s.has(r)){n.add(r);return}let i=[...s].filter(o=>o!==r&&Re(e,o,r));if(i.length===1){n.add(i[0]);return}}Q(e,t,n)}function ft(e,t){for(let n=e;n;n=n.parent)if(n===t)return!0;return!1}function je(e,t){return t.fn&&ft(e,t.fn)?t:{receiver:null,owner:null,fn:null}}function C(e,t,n,r=new Set){let s=e.ts,i=new Set;if(t=T(s,t),!t)return i;let o=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`;if(r.has(o))return i;r.add(o);let a=c=>{for(let l of c)i.add(l)};if(s.isNewExpression(t)){let c=_(e,t.expression);return c&&i.add(c),i}if(t.kind===s.SyntaxKind.ThisKeyword)return n.receiver&&i.add(n.receiver),i;if(s.isConditionalExpression(t))return a(C(e,t.whenTrue,n,r)),a(C(e,t.whenFalse,n,r)),i;if(s.isBinaryExpression(t)){let c=t.operatorToken.kind,l=s.SyntaxKind;if(c===l.QuestionQuestionToken||c===l.BarBarToken||c===l.AmpersandAmpersandToken)return a(C(e,t.left,n,r)),a(C(e,t.right,n,r)),i;if(c===l.CommaToken||c===l.EqualsToken)return a(C(e,t.right,n,r)),i}if(s.isCallExpression(t)){for(let c of ee(e,t,n))for(let l of Y(s,c.fn))a(C(e,l,c.ctx,r));if(i.size>0)return i}else if(s.isIdentifier(t)||s.isPropertyAccessExpression(t)){let c=L(e,s.isPropertyAccessExpression(t)?t.name:t);if(c&&s.isVariableDeclaration(c))return c.initializer&&a(C(e,c.initializer,je(c,n),r)),(!((s.getCombinedNodeFlags(c)&s.NodeFlags.Const)!==0)||!c.initializer)&&Q(e,ae(e,c),i),i;if(c&&s.isParameter(c)){let l=ae(e,c);return c.parent&&s.isConstructorDeclaration(c.parent)?fe(e,l,i):Q(e,l,i),i}if(c&&s.isPropertyDeclaration(c))return c.initializer?a(C(e,c.initializer,{receiver:c.parent,owner:c.parent,fn:null},r)):fe(e,ae(e,c),i),i;if(c&&s.isGetAccessorDeclaration(c)&&c.body){for(let l of Y(s,c))a(C(e,l,{receiver:c.parent,owner:c.parent,fn:c},r));if(i.size>0)return i}if(c&&s.isPropertyAssignment(c)&&(a(C(e,c.initializer,{receiver:null,owner:null,fn:null},r)),i.size>0))return i}return Q(e,e.checker.getTypeAtLocation(t),i),i}function Y(e,t){if(e.isArrowFunction(t)&&!e.isBlock(t.body))return[t.body];let n=e.isFunctionLike(t)?t.body:void 0;if(!n)return[];let r=[],s=i=>{if(e.isReturnStatement(i)){i.expression&&r.push(i.expression);return}e.isFunctionLike(i)||F(e,i)||e.forEachChild(i,s)};return e.forEachChild(n,s),r}function Me(e,t){return e.isPropertyAccessExpression(t)?t.name.text:e.isElementAccessExpression(t)&&e.isStringLiteralLike(t.argumentExpression)?t.argumentExpression.text:null}function Ie(e,t){return e.isPropertyAccessExpression(t)?t.name:t.argumentExpression}function dt(e,t){let n=e.ts,r=Me(n,t);if(r===null)return[];let s=e.checker.getSymbolAtLocation(Ie(n,t)),i=new Map;for(let o of s&&s.declarations||[]){if(!se(e,o.getSourceFile().fileName))continue;let a=o.parent,c=a&&a.name&&n.isIdentifier(a.name)?a.name.text:"";for(let l of it)l.member===r&&(!l.container||l.container.test(c))&&i.set(l.error.code,l.error)}return[...i.values()]}function mt(e,t){let n=e.checker.getSymbolAtLocation(Ie(e.ts,t));return n?(n.declarations||[]).some(r=>v(e,r)):!0}function Be(e,t,n){let r=e.ts,s=[];for(let i=t;i;i=J(e,i)){for(let a of i.members){if(!r.isPropertyDeclaration(a)||!a.initializer||de(r,a))continue;let c=T(r,a.initializer);r.isArrowFunction(c)||r.isFunctionExpression(c)||s.push({fn:a.initializer,ctx:{receiver:n,owner:i,fn:null}})}let o=i.members.find(a=>r.isConstructorDeclaration(a)&&!!a.body);if(o){s.push({fn:o,ctx:{receiver:n,owner:i,fn:o}});break}}return s}function ee(e,t,n){let r=e.ts,s=T(r,t.expression);if(s.kind===r.SyntaxKind.SuperKeyword){let c=n.owner&&J(e,n.owner);return c?Be(e,c,n.receiver):[]}let i=Me(r,s);if(i!==null){let c=s,l=T(r,c.expression);if(l.kind===r.SyntaxKind.SuperKeyword){let g=n.owner&&J(e,n.owner),y=g&&U(e,g,i,!1);return y?[{fn:y.fn,ctx:{receiver:n.receiver,owner:y.owner,fn:y.fn}}]:[]}let u=r.isIdentifier(l)||r.isPropertyAccessExpression(l)?_(e,l):null;if(u){let g=U(e,u,i,!0);return g?[{fn:g.fn,ctx:{receiver:null,owner:g.owner,fn:g.fn}}]:[]}if(!mt(e,c))return[];let m=[];for(let g of C(e,l,n)){let y=U(e,g,i,!1);y&&m.push({fn:y.fn,ctx:{receiver:g,owner:y.owner,fn:y.fn}})}if(m.length>0)return m}let o=e.checker.getResolvedSignature(t),a=o&&o.declaration;if(a&&!r.isJSDocSignature(a)&&a.body&&v(e,a)){let c=a,l=c.parent&&F(r,c.parent)?c.parent:null,u=l&&!de(r,c)?l:null;return[{fn:c,ctx:{receiver:u,owner:l,fn:c}}]}return[]}function De(e,t,n){let r=e.ts,s=T(r,t);if(!s)return[];if(r.isPropertyAccessExpression(s)){let i=L(e,s.name);if(!(i&&v(e,i)&&(r.isMethodDeclaration(i)||r.isPropertyDeclaration(i))))return[];let a=[];for(let c of C(e,s.expression,n)){let l=U(e,c,s.name.text,!1);l&&a.push({fn:l.fn,ctx:{receiver:c,owner:l.owner,fn:l.fn}})}return a}if(r.isIdentifier(s)){let i=L(e,s);if(!i||!v(e,i))return[];if(r.isFunctionDeclaration(i)&&i.body)return[{fn:i,ctx:{receiver:null,owner:null,fn:i}}];if(r.isVariableDeclaration(i)&&i.initializer){let o=T(r,i.initializer);if(r.isArrowFunction(o)||r.isFunctionExpression(o))return[{fn:o,ctx:{receiver:null,owner:null,fn:o}}]}}return[]}function K(e,t,n){let r=e.ts,s=T(r,t);if(!s)return null;if(n==="string"&&(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return[s.text];if(n==="number"&&r.isNumericLiteral(s))return[Number(s.text)];let i=e.checker.getTypeAtLocation(s),o=[];for(let a of i.isUnion()?i.types:[i])if(n==="string"&&a.isStringLiteral())o.push(a.value);else if(n==="number"&&a.isNumberLiteral())o.push(a.value);else return null;return o.length>0?[...new Set(o)]:null}function Le(e,t,n){let r=O(e,t);e.warnings.has(r)||e.warnings.set(r,`${r} \u2014 ${n}`)}function gt(e,t){let n=T(e,t);return!n||e.isIdentifier(n)&&n.text==="undefined"||n.kind===e.SyntaxKind.VoidExpression}function Pe(e){let t=e.split(/[^A-Za-z0-9]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join("");return/^[A-Za-z]/.test(t)?t:`E${t}`}function Ke(e,t,n,r,s){if(st.has(t)){let c=K(e,n[0],"number"),l=K(e,n[1],"string");return!l||!c||c.length!==1?(Le(e,r,`new ${t}(status, code, \u2026) with a code or status decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code and status literal types (or declare it with defineError)`),[]):l.map(u=>({name:s&&l.length===1?s:Pe(u),code:u,status:c[0]}))}let i=Object.prototype.hasOwnProperty.call(ue,t)?ue[t]:null;if(!i)return[];let o=[i.code];if(i.codeArg!==null&&n.length>i.codeArg&&!gt(e.ts,n[i.codeArg])&&(o=K(e,n[i.codeArg],"string"),!o))return Le(e,r,`new ${t}(\u2026) with a code decided at runtime cannot be typed; clients receive it as their untyped case. To type it, give the code a literal type (or declare it with defineError)`),[];let a=o;return a.map(c=>({name:s&&a.length===1?s:c===i.code?t:Pe(c),code:c,status:i.status}))}function me(e,t){let n=e.ts,r=t.initializer&&T(n,t.initializer);return r&&n.isCallExpression(r)&&I(e,r.expression)==="defineError"?r:null}function _e(e,t,n){let r=K(e,n.arguments[0],"string"),s=K(e,n.arguments[1],"number"),i=r&&r.length===1?r[0]:null,o=s&&s.length===1?s[0]:null;return(i===null||o===null)&&at(e,n,`defineError(...) for "${t.name.getText()}" declares a typed error, so its code and status must be known when the project is built (a literal, or a constant of literal type)`),{name:t.name.getText(),code:i,status:o}}function pt(e,t){let n=null,r=s=>{if(!(n||e.isFunctionLike(s))){if(e.isCallExpression(s)&&s.expression.kind===e.SyntaxKind.SuperKeyword){n=s;return}e.forEachChild(s,r)}};return t.body&&e.forEachChild(t.body,r),n}function Ve(e,t,n,r){let s=e.ts,i=(t.heritageClauses||[]).find(f=>f.token===s.SyntaxKind.ExtendsKeyword),o=i&&i.types[0]&&i.types[0].expression;if(!o)return[];let a=t.members.find(f=>s.isConstructorDeclaration(f)&&!!f.body),c=n,l=r;if(a){let f=pt(s,a);if(!f)return[];c=f.arguments,l=f}let u=ct(s,t),m=I(e,o);if(m)return Ke(e,m,c,l,u);let g=L(e,o);if(g&&s.isVariableDeclaration(g)){let f=me(e,g);return f?[{..._e(e,g,f),name:u||g.name.getText()}]:[]}let y=_(e,o);if(y){let f=Ve(e,y,c,l);return f.length===1&&u?[{...f[0],name:u}]:f}return[]}function St(e,t){let n=e.ts,r=t.arguments||[],s=I(e,t.expression);if(s)return Ke(e,s,r,t);let i=T(n,t.expression),o=L(e,n.isPropertyAccessExpression(i)?i.name:i);if(!o)return[];if(n.isVariableDeclaration(o)){let c=me(e,o);if(c)return[_e(e,o,c)]}let a=Oe(n,o);return a&&v(e,a)?Ve(e,a,r,t):[]}function z(e,t,n,r,s,i,o=new Set){let a=e.ts;if(t=T(a,t),!t)return;let c=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`;if(!o.has(c)){if(o.add(c),a.isNewExpression(t)){let l=O(e,t);R(e,r,s,i,St(e,t).map(u=>({...u,site:l})));return}if(a.isConditionalExpression(t)){z(e,t.whenTrue,n,r,s,i,o),z(e,t.whenFalse,n,r,s,i,o);return}if(a.isBinaryExpression(t)){let l=a.SyntaxKind,u=t.operatorToken.kind;(u===l.QuestionQuestionToken||u===l.BarBarToken)&&z(e,t.left,n,r,s,i,o),z(e,t.right,n,r,s,i,o);return}if(a.isCallExpression(t)){for(let l of ee(e,t,n))for(let u of Y(a,l.fn))z(e,u,l.ctx,r,s,i,o);return}if(a.isIdentifier(t)||a.isPropertyAccessExpression(t)){let l=L(e,a.isPropertyAccessExpression(t)?t.name:t);if(l&&(a.isVariableDeclaration(l)||a.isPropertyDeclaration(l))&&l.initializer){let u=a.isVariableDeclaration(l)?je(l,n):n;z(e,l.initializer,u,r,s,i,o)}}}}function ce(e,t){let n=e.ts;if(!n.isFunctionLike(t))return!1;if((n.getCombinedModifierFlags(t)&n.ModifierFlags.Async)!==0)return!0;let r=e.checker.getSignatureFromDeclaration(t);if(!r)return!1;let s=e.checker.getReturnTypeOfSignature(r),i=e.checker.getPromisedTypeOfPromise;return i?i.call(e.checker,s)!==void 0:e.checker.getAwaitedType(s)!==s}function yt(e,t,n){let r=null;for(let s=t.parent;s&&s!==n;s=s.parent)e.isFunctionLike(s)&&(e.getCombinedModifierFlags(s)&e.ModifierFlags.Async)!==0&&(r=s);return r}function Tt(e,t,n){for(let r=t.parent;r&&r!==n;r=r.parent)if(e.isAwaitExpression(r)||e.isForOfStatement(r)&&r.awaitModifier)return!0;return!1}function ht(e,t,n,r){for(let s=t.scopes.length-1;s>=0;s--){let i=t.scopes[s],o=yt(e.ts,n,i.node),a=r||o!==null;if(i.kind==="try"){if(!a||Tt(e.ts,o||n,i.node))return i.sink}else if(i.kind==="settle"){if(a)return null}else if(i.kind==="catch"&&a&&!i.rethrows)return null}return t.root}function bt(e){let t=e.ts;if(e.statusOf)return e.statusOf;let n=new Map;for(let[s,i]of Object.entries(ue))n.set(i.code,{status:i.status,site:`palbase/backend ${s}`});let r=s=>{if(t.isVariableDeclaration(s)&&t.isIdentifier(s.name)){let i=me(e,s),o=i&&K(e,i.arguments[0],"string"),a=i&&K(e,i.arguments[1],"number");o&&a&&o.length===1&&a.length===1&&!n.has(o[0])&&n.set(o[0],{status:a[0],site:O(e,s)})}t.forEachChild(s,r)};for(let s of e.program.getSourceFiles())$(e,s.fileName)&&r(s);return e.statusOf=n,n}function xt(e,t){let n=bt(e),r=n.get(t.code);if(!r){n.set(t.code,{status:t.status,site:t.site});return}if(r.status!==t.status)throw new b(`"${t.code}" is thrown with status ${t.status} (${t.site}) but the code carries status ${r.status} (${r.site}) \u2014 a client matches an error by its code, so one code carries one status. Throw the code's own class, or give the error its own code`)}function R(e,t,n,r,s){for(let o of s)xt(e,o);let i=ht(e,t,n,r);if(i)for(let o of s)i.has(o.code)||i.set(o.code,o)}function Ue(e,t,n){if(!n)return!1;let r=!1,s=o=>{let a=!1,c=l=>{a||(e.isIdentifier(l)&&l.text===n?a=!0:e.forEachChild(l,c))};return c(o),a},i=o=>{r||e.isFunctionLike(o)&&o!==t||(e.isThrowStatement(o)&&o.expression&&s(o.expression)?r=!0:e.forEachChild(o,i))};return i(t),r}function wt(e,t){let n=T(e,t);if(n&&(e.isArrowFunction(n)||e.isFunctionExpression(n))){let r=n.parameters[0];return r?e.isIdentifier(r.name)?e.isBlock(n.body)?Ue(e,n.body,r.name.text):!1:!0:!1}return!0}function kt(e,t,n){let r=e.ts;if(!r.isPropertyAccessExpression(t)||t.name.text!==n)return!1;let s=T(r,t.expression);if(!r.isIdentifier(s)||s.text!=="Promise")return!1;let i=L(e,s);return!i||!v(e,i)}function B(e,t,n){let r=e.ts,s=`${q(e,t)}@${n.receiver?q(e,n.receiver):0}`,i=e.summaries.get(s);if(i&&(i.final||i.round===e.round))return i.busy&&(e.cyclic=!0),i.errors;i={errors:i?new Map(i.errors):new Map,busy:!0,round:e.round,final:!1},e.summaries.set(s,i);let o=i.errors.size,a={root:i.errors,scopes:[]};if(r.isFunctionLike(t)){let c=t;for(let l of c.parameters||[])l.initializer&&D(e,l.initializer,n,a);c.body&&D(e,c.body,n,a)}else D(e,t,n,a);return i.busy=!1,i.errors.size!==o&&(e.grew=!0),i.errors}function le(e,t){return{root:e.root,scopes:[...e.scopes,t]}}function D(e,t,n,r){let s=e.ts;if(s.isTryStatement(t)){let o=new Map;D(e,t.tryBlock,n,le(r,{kind:"try",node:t.tryBlock,sink:o}));let a=t.catchClause;(!a||(a.variableDeclaration&&s.isIdentifier(a.variableDeclaration.name)?Ue(s,a.block,a.variableDeclaration.name.text):a.variableDeclaration))&&R(e,r,t,!1,[...o.values()]),a&&D(e,a.block,n,r),t.finallyBlock&&D(e,t.finallyBlock,n,r);return}if(s.isThrowStatement(t))t.expression&&z(e,t.expression,n,r,t,!1);else if(s.isCallExpression(t)){let o=T(s,t.expression);if(kt(e,o,"allSettled")){D(e,t.expression,n,r);let u=le(r,{kind:"settle",node:t});for(let m of t.arguments)D(e,m,n,u);return}let a=s.isPropertyAccessExpression(o)?o.name.text==="catch"?0:o.name.text==="then"&&t.arguments.length>1?1:-1:-1;if(a>=0){let u=o,m=wt(s,t.arguments[a]);D(e,u.expression,n,le(r,{kind:"catch",node:u.expression,rethrows:m}));for(let g of t.arguments)D(e,g,n,r);return}let c=s.isPropertyAccessExpression(o)?ot.get(o.name.text):void 0;c!==void 0&&t.arguments[c]&&z(e,t.arguments[c],n,r,t,!0);let l=dt(e,o);if(l.length>0){let u=O(e,t);R(e,r,t,!0,l.map(m=>({...m,site:u})))}for(let u of ee(e,t,n))R(e,r,t,ce(e,u.fn),[...B(e,u.fn,u.ctx).values()]);for(let u of t.arguments)for(let m of De(e,u,n))R(e,r,u,ce(e,m.fn),[...B(e,m.fn,m.ctx).values()])}else if(s.isNewExpression(t)){let o=_(e,t.expression);if(o)for(let a of Be(e,o,o))R(e,r,t,!1,[...B(e,a.fn,a.ctx).values()]);for(let a of t.arguments||[])for(let c of De(e,a,n))R(e,r,a,ce(e,c.fn),[...B(e,c.fn,c.ctx).values()])}else if(s.isPropertyAccessExpression(t)&&!(t.parent&&s.isCallExpression(t.parent)&&t.parent.expression===t)){let o=L(e,t.name);if(o&&s.isGetAccessorDeclaration(o)&&o.body&&v(e,o))for(let a of C(e,t.expression,n)){let c=U(e,a,t.name.text,!1);c&&R(e,r,t,!1,[...B(e,c.fn,{receiver:a,owner:c.owner,fn:c.fn}).values()])}}if(F(s,t))return;let i=s.isFunctionExpression(t)||s.isFunctionDeclaration(t)?{receiver:null,owner:null,fn:t}:n;s.forEachChild(t,o=>D(e,o,i,r))}function qe(e,t,n){let r=e.ts;if(n.has(t))return[];if(n.add(t),I(e,t.expression)==="Resolve")return[t];let s=[];for(let i of ee(e,t,{receiver:null,owner:null,fn:null}))for(let o of Y(r,i.fn)){let a=T(r,o);r.isCallExpression(a)&&s.push(...qe(e,a,n))}return s}function Et(e,t){let n=e.ts,r=[];for(let s of t.parameters)for(let i of n.getDecorators(s)||[]){let o=T(n,i.expression);if(n.isCallExpression(o))for(let a of qe(e,o,new Set)){let c=_(e,a.arguments[0]);if(!c)continue;let l=new Set;fe(e,ze(e,c),l);for(let u of l){let m=U(e,u,"resolve",!1);m&&r.push({fn:m.fn,ctx:{receiver:u,owner:m.owner,fn:m.fn}})}}}return r}function Ct(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Nt(e,t,n){let r=new Map;for(let i of Et(e,n))for(let o of B(e,i.fn,i.ctx).values())r.has(o.code)||r.set(o.code,o);for(let i of B(e,n,{receiver:t,owner:t,fn:n}).values())r.has(i.code)||r.set(i.code,i);let s=new Map;for(let i of r.values()){let o=Ct(i.name),a=s.get(o);if(a)throw new b(`${t.name.text}.${P(e.ts,n.name)} can throw two errors named "${i.name}" \u2014 "${a.code}" (${a.site}) and "${i.code}" (${i.site}). Every client names an error case after it; give one of them its own defineError`);s.set(o,i)}return[...r.values()].map(({name:i,code:o,status:a})=>({name:i,code:o,status:a}))}function At(e,t){let n=[];for(let{cls:r,routes:s}of X(e,t)){let i={};for(let o of s)i[P(e.ts,o.name)]=Nt(e,r,o);n.push({className:r.name.text,ops:i})}return n}function Gt(e,t,n={}){let r=n.typescript??vt,s=Je(ge(e)),{options:i,ambient:o}=ke(r,s);return Dt(Ee(r,s,[Je(ge(t)),...o],i))}function Dt(e){let t=e.ts,n=Ne(e),r=$e(e),s=[],i=e.program.getSourceFiles().filter(a=>$(e,a.fileName)).sort((a,c)=>a.fileName<c.fileName?-1:a.fileName>c.fileName?1:0),o=[];for(let a of i){let c=X(e,a);if(c.length===0)continue;let l=new Map;for(let{cls:u,routes:m}of c)for(let g of m)try{l.set(`${u.name.text}.${P(t,g.name)}`,Ae(e,n,u.name.text,g))}catch(y){if(!(y instanceof b))throw y;o.push(y.message)}if(!(o.length>0))for(let{className:u,ops:m}of r.analyze(a))for(let[g,y]of Object.entries(m))s.push({file:ge(a.fileName),className:u,method:g,returns:l.get(`${u}.${g}`),throws:y})}if(o.length===1)throw new b(o[0]);if(o.length>1)throw new b(`${o.length} routes have no contract:
5
5
  ${o.map(a=>`- ${a}`).join(`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
2
2
  var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{a as u,b as d}from"./5QE5KFNR.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it",ai_budget_reached:()=>"the project's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or an owner or admin raises the budget (Studio \u203A AI \u203A Settings, or palbase ai:settings:set --monthly-budget) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",ai_payment_required:()=>"the month's free AI dollar is spent and the project has no paid rights now to pay for Palbase's models (it is on Free, at its month's limit, or its payment account has an unpaid charge): move it to Pay as you go (Studio \u203A Billing) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",billing_unavailable:t=>`Palbase's billing did not say whether its models serve the project${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`},g=new WeakSet;function c(t){if(!(t instanceof d)||g.has(t))return t;let r=p[t.code];if(!r)return t;let s=new d({op:t.op,status:t.status,code:t.code,message:`${r(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(s),s}function m(t){return t.catch(r=>{throw c(r)})}function _(t){if(typeof t!="object"||t===null)return;let r=t,s=r.data;if(typeof r.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let e=u(s),i=typeof r.id=="number"&&Number.isSafeInteger(r.id)?r.id:0;switch(r.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:i,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:i};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:i,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:i}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:i,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:i,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...o}=e;return{...o,type:"goal",seq:i,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(a=>typeof a=="object"&&a!==null&&(a.role==="user"||a.role==="assistant")&&typeof a.text=="string"),o=e.forked_from;return{type:"history",forked_from:o&&typeof o.chat_id=="string"?o:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:i,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:i,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};default:return}}function b(t){let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r+=1:e<2048?r+=2:e>=55296&&e<=56319&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(r+=4,s++):r+=3}return r}function l(t,r){if(r<=0)return 0;let s=0;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e),n=3,o=1;if(i<128?n=1:i<2048?n=2:i>=55296&&i<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(n=4,o=2),s+=n,s>=r)return e+o;e+=o-1}return t.length}function v(t,r){return t.slice(l(t,r))}export{m as a,_ as b,b as c,l as d,v as e};
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as u,b as d}from"./YNE6YXJM.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it",ai_budget_reached:()=>"the project's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or an owner or admin raises the budget (Studio \u203A AI \u203A Settings, or palbase ai:settings:set --monthly-budget) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",ai_payment_required:()=>"the month's free AI dollar is spent and the project has no paid rights now to pay for Palbase's models (it is on Free, at its month's limit, or its payment account has an unpaid charge): move it to Pay as you go (Studio \u203A Billing) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",billing_unavailable:t=>`Palbase's billing did not say whether its models serve the project${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`},g=new WeakSet;function c(t){if(!(t instanceof d)||g.has(t))return t;let r=p[t.code];if(!r)return t;let s=new d({op:t.op,status:t.status,code:t.code,message:`${r(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(s),s}function m(t){return t.catch(r=>{throw c(r)})}function _(t){if(typeof t!="object"||t===null)return;let r=t,s=r.data;if(typeof r.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let e=u(s),i=typeof r.id=="number"&&Number.isSafeInteger(r.id)?r.id:0;switch(r.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:i,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:i};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:i,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:i}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:i,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:i,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...o}=e;return{...o,type:"goal",seq:i,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(a=>typeof a=="object"&&a!==null&&(a.role==="user"||a.role==="assistant")&&typeof a.text=="string"),o=e.forked_from;return{type:"history",forked_from:o&&typeof o.chat_id=="string"?o:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:i,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:i,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};default:return}}function b(t){let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r+=1:e<2048?r+=2:e>=55296&&e<=56319&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(r+=4,s++):r+=3}return r}function l(t,r){if(r<=0)return 0;let s=0;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e),n=3,o=1;if(i<128?n=1:i<2048?n=2:i>=55296&&i<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(n=4,o=2),s+=n,s>=r)return e+o;e+=o-1}return t.length}function v(t,r){return t.slice(l(t,r))}export{m as a,_ as b,b as c,l as d,v as e};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{a as M,c as ye,d as be,e as we}from"./LO6DFZ7L.js";import{a as ke}from"./RCUVA3QW.js";import{a as ge}from"./4ZMAF4YF.js";import{a as fe,b as me,c as he}from"./HEHSHDUM.js";import{b as $,d as pe}from"./5QE5KFNR.js";async function*Te(e,t={}){let a=e.getReader(),o=new TextDecoder,i="",l="",u=[],h,r=()=>{a.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:s}=await a.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=o.decode(s,{stream:!0});for(let d=i.indexOf(`
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as M,c as ye,d as be,e as we}from"./5CV5NIXC.js";import{a as ke}from"./XGLNNBME.js";import{a as ge}from"./YGQVQEVB.js";import{a as fe,b as me,c as he}from"./S7VKVW6I.js";import{b as $,d as pe}from"./YNE6YXJM.js";async function*Te(e,t={}){let a=e.getReader(),o=new TextDecoder,i="",l="",u=[],h,r=()=>{a.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:s}=await a.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=o.decode(s,{stream:!0});for(let d=i.indexOf(`
3
3
  `);d>=0;d=i.indexOf(`
4
4
  `)){let p=i.slice(0,i[d-1]==="\r"?d-1:d);i=i.slice(d+1),p===""?(l!==""&&(yield h===void 0?{event:l,data:u.join(`
5
5
  `)}:{event:l,data:u.join(`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
2
2
  var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{p as R,t as k,u as H}from"./WH3G2H3E.js";var N=40,V=`
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
2
+ import{p as R,t as k,u as H}from"./ULKE62TM.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,4 +1,4 @@
1
- /*! palbase 0.40.2 — Palbase SDK License (see LICENSE) */
2
- import{f as m}from"./OHNIWLO3.js";import{AsyncLocalStorage as O}from"node:async_hooks";function h(n,e){return new Proxy(e,{get(s,t,i){if(c.getStore()?.services===void 0)return Reflect.get(s,t,i);let o=R(n,t,s),r=o[t];return typeof r=="function"?r.bind(o):r}})}function R(n,e,s){let t=c.getStore()?.services;if(t===void 0)return s;let i=t[n];if(i!==void 0)return i;if(n==="Log"||typeof e=="symbol"||e==="then")return s;throw new Error(`${n}.${String(e)} was read, but this test did not provide ${n}. Pass it: withServices({ ${n}: \u2026 }, () => \u2026)`)}var P=Symbol.for("palbase.backend.requestScope"),c=globalThis[P]??=new O,d,w,E,G={get ai(){if(!d)throw new Error("Palbase.ai is called before the app is served (serve() binds it)");return d.ai}};function H(n){d=n}function F(n){w=n}var T=h("Gateways",{to(n,e){if(!w)throw new Error("Palbase.gateways is reached before the app is served (createApp() binds it)");return w.to(n,e)}}),Z=new Proxy({},{get(n,e){if(e==="gateways")return T;if(e==="ai")return E??=m({server:G});if(!d)throw new Error(`Palbase.${String(e)} is reached before the app is served (serve() binds it)`);return d[e]}}),B=new Proxy({},{get(n,e){let s=c.getStore(),t=s?.database;if(!t)throw new Error(s?.services?`Database.${String(e)} was read, and this test gave no Database: withServices({ Database: fake.raw }, \u2026)`:s?`Database.${String(e)}: this app declares no database \u2014 PalbaseFactory.create(\u2026, { db: { schemas } })`:`Database.${String(e)} is reached outside a request: it is the request's transaction, reached from a handler, a service it calls or an @On`);let i=t[e];return typeof i=="function"?i.bind(t):i}});function l(n,e,s){let t={time:new Date().toISOString(),level:n,msg:e},i=c.getStore();if(i&&(t.request_id=i.requestId),s)for(let[r,a]of Object.entries(s))t[r]=a instanceof Error?{name:a.name,message:a.message,stack:a.stack}:a;let o=k(t);n==="error"||n==="warn"?process.stderr.write(`${o}
1
+ /*! palbase 0.41.1 — Palbase SDK License (see LICENSE) */
2
+ import{f as m}from"./5FC4ZZTY.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};