palbase 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/ai/index.js +2 -14
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +9 -9
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/5VTGMNPL.js +20 -0
  8. package/dist/chunks/{SXH5AIQX.js → BO5KR2EQ.js} +2 -2
  9. package/dist/chunks/{AYY4J3B2.js → BRBCWPR3.js} +1 -1
  10. package/dist/chunks/DB3SIBKB.js +2 -0
  11. package/dist/chunks/EGNEXFTZ.js +2 -0
  12. package/dist/chunks/{VP7V7YRH.js → FZ3MQOVA.js} +2 -2
  13. package/dist/chunks/{A3CDCPXX.js → JSJVV43D.js} +1 -1
  14. package/dist/chunks/K6RRNI23.js +4 -0
  15. package/dist/chunks/{SUX2BJG4.js → KDWDPSL2.js} +1 -1
  16. package/dist/chunks/P4Z5E6ZI.js +2 -0
  17. package/dist/chunks/PDOHT46N.js +2 -0
  18. package/dist/chunks/PGPQGKH2.js +18 -0
  19. package/dist/chunks/{DRTZ33XF.js → RBA6V3UO.js} +2 -2
  20. package/dist/chunks/{KLANM6M6.js → RO5Y5YU4.js} +1 -1
  21. package/dist/chunks/{53FS342F.js → TUGRIOFX.js} +2 -2
  22. package/dist/chunks/WEI32SAJ.js +13 -0
  23. package/dist/chunks/{GVFZM4BI.js → WINBISC2.js} +3 -3
  24. package/dist/chunks/Z5JVQNAZ.js +2 -0
  25. package/dist/cli.js +140 -139
  26. package/dist/refuse/ai.js +1 -1
  27. package/dist/refuse/backend.js +1 -1
  28. package/dist/refuse/server.js +1 -1
  29. package/dist/server/index.js +2 -2
  30. package/dist/server/testing.js +2 -2
  31. package/dist/web/index.js +2 -2
  32. package/dist/web/palbe.js +2 -2
  33. package/dist/web/paywall.js +2 -2
  34. package/dist/web/ssr.js +2 -2
  35. package/dist/web/vite.js +2 -2
  36. package/package.json +2 -2
  37. package/types/ai/src/ai.d.ts +46 -19
  38. package/types/ai/src/chats.d.ts +478 -18
  39. package/types/ai/src/index.d.ts +4 -4
  40. package/types/ai/src/tools.d.ts +161 -29
  41. package/types/backend/src/bootstrap.d.ts +8 -0
  42. package/types/backend/src/container.d.ts +11 -2
  43. package/types/backend/src/database.d.ts +17 -2
  44. package/types/backend/src/engine.d.ts +3 -4
  45. package/types/backend/src/gateways.d.ts +269 -0
  46. package/types/backend/src/index.d.ts +3 -2
  47. package/types/backend/src/openapi.d.ts +3 -6
  48. package/types/backend/src/runtime.d.ts +51 -2
  49. package/types/backend/src/testing/unit.d.ts +3 -1
  50. package/types/internal/src/chat.d.ts +168 -35
  51. package/types/internal/src/modules/ai.d.ts +1826 -545
  52. package/types/internal/src/modules/auth.d.ts +14 -2
  53. package/types/internal/src/modules/events.d.ts +2 -2
  54. package/types/internal/src/modules/machines.d.ts +57 -1
  55. package/types/internal/src/modules/notify.d.ts +6 -6
  56. package/types/internal/src/modules/purchases.d.ts +357 -13
  57. package/types/internal/src/modules/realtime.d.ts +45 -1
  58. package/types/internal/src/modules/stores.d.ts +259 -22
  59. package/types/internal/src/transport.d.ts +5 -0
  60. package/types/server/src/auth/jwt.d.ts +1 -6
  61. package/types/web/src/auth.d.ts +15 -4
  62. package/types/web/src/backends.d.ts +20 -13
  63. package/types/web/src/chat.d.ts +329 -0
  64. package/types/web/src/client.d.ts +28 -3
  65. package/types/web/src/gateways.d.ts +90 -0
  66. package/types/web/src/index.d.ts +5 -4
  67. package/types/web/src/session.d.ts +11 -1
  68. package/types/web/src/socket.d.ts +18 -2
  69. package/types/web/src/voice.d.ts +36 -0
  70. package/dist/chunks/2RG3I7LX.js +0 -6
  71. package/dist/chunks/A76UZBAF.js +0 -2
  72. package/dist/chunks/AD5LBZAB.js +0 -4
  73. package/dist/chunks/DRGYTL6T.js +0 -20
  74. package/dist/chunks/IVEAUFGE.js +0 -13
  75. package/dist/chunks/IYCW6PWG.js +0 -2
  76. package/dist/chunks/KL7FIRII.js +0 -2
  77. package/dist/chunks/U4OZ4HOF.js +0 -2
  78. package/types/backend/src/channels.d.ts +0 -81
  79. package/types/backend/src/rooms.d.ts +0 -178
  80. package/types/web/src/ai.d.ts +0 -224
  81. package/types/web/src/rooms.d.ts +0 -61
@@ -1,20 +0,0 @@
1
- /*! palbase 0.6.2 — Palbase SDK License (see LICENSE) */
2
- import{a as dt,c as ee,d as Un,e as le,g as E,h as Ln}from"./AD5LBZAB.js";import{b as Ke,d as ot,e as Mn,f as Dn,g as at,h as it,k as jn,q as Nn}from"./U4OZ4HOF.js";import{b as ie}from"./IYCW6PWG.js";import"reflect-metadata";var Pt=[{name:"minute",lo:0,hi:59},{name:"hour",lo:0,hi:23},{name:"day of the month",lo:1,hi:31},{name:"month",lo:1,hi:12},{name:"day of the week",lo:0,hi:7}],In="a schedule is five fields \u2014 minute hour day-of-month month day-of-week \u2014 of numbers, *, lists (1,15), ranges (1-5) and steps (*/10)",ct=/^\d+$/;function bs(e,t,n){let r=new Set;for(let s of e.split(",")){let o=s.indexOf("/"),a=o===-1?s:s.slice(0,o),i=1;if(o!==-1){let y=s.slice(o+1);if(!ct.test(y)||Number(y)<1||Number(y)>n)return;i=Number(y)}let c=t,p=n;if(a!=="*")if(a.includes("-")){let y=a.indexOf("-"),k=a.slice(0,y),R=a.slice(y+1);if(!ct.test(k)||!ct.test(R)||Number(k)<t||Number(R)>n||Number(k)>Number(R))return;c=Number(k),p=Number(R)}else{if(!ct.test(a)||Number(a)<t||Number(a)>n)return;c=Number(a),p=o===-1?c:n}for(let y=c;y<=p;y+=i)r.add(y)}return r}function zn(e){let t=e.trim().split(/\s+/);if(t.length!==5||t[0]==="")return`${In}; "${e}" is not`;let n=[];for(let p=0;p<5;p++){let y=bs(t[p],Pt[p].lo,Pt[p].hi);if(!y)return`${In}; its ${Pt[p].name} "${t[p]}" is not one`;n.push(y)}let[,,r,s,o]=n;o.has(7)&&o.add(0);let a=t[2].startsWith("*"),i=t[4].startsWith("*"),c=new Date(Date.UTC(2e3,0,1));for(let p=0;p<366*8+2;p++,c.setUTCDate(c.getUTCDate()+1)){if(!s.has(c.getUTCMonth()+1))continue;let y=r.has(c.getUTCDate()),k=o.has(c.getUTCDay());if(a||i?y&&k:y||k)return}return`"${e}" is never due: no date has that day in that month`}var _e=Symbol.for("palbase.backend.controller"),Se=Symbol.for("palbase.backend.routes"),Mt=Symbol.for("palbase.backend.params"),Dt=Symbol.for("palbase.backend.injectable"),jt=Symbol.for("palbase.backend.module"),be=Symbol.for("palbase.backend.events"),Oe=Symbol.for("palbase.backend.webhook"),he=Symbol.for("palbase.backend.crons"),fe=Symbol.for("palbase.backend.tasks");function Y(e,t,n){let r=e;return Object.prototype.hasOwnProperty.call(r,t)||Object.defineProperty(r,t,{value:n(),enumerable:!1}),r[t]}var Ct=Symbol.for("palbase.backend.declared");function re(){let e=globalThis;return e[Ct]instanceof Set||(e[Ct]=new Set),e[Ct]}var xe=new Set(["webhooks","_palbase"]);function Ka(e,t={}){if(typeof e!="string")throw new TypeError("@Controller(path, options): path is a string");return n=>{let r=e.split("/").filter(Boolean)[0];if(r!==void 0&&xe.has(r))throw new TypeError(`@Controller("${e}") on ${n.name}: /${r} is the platform's; a controller is served elsewhere`);Y(n,_e,()=>({basePath:e,options:t})),re().add(n)}}function Ae(e){return(t,n={})=>{if(typeof t!="string")throw new TypeError(`@${e[0]}${e.slice(1).toLowerCase()}(path, options): path is a string \u2014 the query string is read with @QueryParams(schema)`);return(r,s,o)=>{if(typeof s!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@${e}("${t}") goes on a method`);Y(r.constructor,Se,()=>[]).push({method:e,subpath:t,fn:s,options:n})}}}var Ja=Ae("GET"),Wa=Ae("POST"),Va=Ae("PUT"),Za=Ae("PATCH"),Qa=Ae("DELETE"),Ga=Ae("QUERY");function se(e,t={}){return(n,r,s)=>{if(typeof r!="string")throw new TypeError(`@${e} goes on a route method's parameter`);let o=Y(n.constructor,Mt,()=>new Map);o.has(r)||o.set(r,[]),o.get(r).push({index:s,kind:e,...t})}}function Nt(e,t){if(typeof t!="object"||t===null||typeof t["~standard"]?.validate!="function")throw new TypeError(`@${e}(schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return t}var Ya=e=>se("body",{schema:Nt("Body",e)}),Xa=e=>se("query",{schema:Nt("QueryParams",e)}),ei=e=>se("headers",e===void 0?{}:{schema:Nt("Headers",e)}),ti=e=>{if(typeof e!="string"||e==="")throw new TypeError("@Param(name): name is the path parameter");return se("param",{name:e})},ni=()=>se("user"),ri=()=>se("optionalUser"),si=()=>se("req"),oi=()=>se("requestId"),ai=()=>se("requestId"),ii=()=>se("client");function di(e,...t){if(typeof e!="function"||typeof e.prototype?.resolve!="function")throw new TypeError(`@Resolve(resolver): resolver is a class with a resolve(context, options) method${typeof e=="function"?` \u2014 ${e.name} has none`:""}`);return se("resolve",{resolver:e,options:t[0]})}function ci(){return e=>{Y(e,Dt,()=>!0),re().add(e)}}function ui(e){return t=>{Y(t,jt,()=>({imports:[],controllers:[],providers:[],exports:[],...e}))}}var Bn=/^[a-z]+(\.[a-z_]+)+$/,ks=/^[a-z][a-z0-9-]{1,62}$/,Ut=e=>e.startsWith("file.");function li(e,t={}){if(typeof e!="string")throw new TypeError("@On(event): event is the type its handler takes, like user.deleted");let n=t?.bucket;if(n!==void 0){if(typeof n!="string"||!ks.test(n))throw new TypeError(`@On("${e}", { bucket }): ${JSON.stringify(n)} is not a bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 of them`);if(!Ut(e))throw new TypeError(`@On("${e}", { bucket: "${n}" }): only a storage event (file.uploaded, file.deleted, file.moved) is of a bucket`)}return(r,s,o)=>{if(typeof s!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@On("${e}") goes on a method`);Y(r.constructor,be,()=>[]).push(n===void 0?{event:e,fn:s}:{event:e,fn:s,bucket:n}),re().add(r.constructor)}}var Lt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,vs=/^(UTC|[A-Z][A-Za-z_]*(\/[A-Z][A-Za-z0-9_+-]*)+)$/;function qn(e){let t=`timeZone is a time zone's IANA name, written as the database writes it, like "Europe/Istanbul" or "UTC" (got ${JSON.stringify(e)})`;if(!vs.test(e))return t;try{let n=new Intl.DateTimeFormat("en-US",{timeZone:e}).resolvedOptions().timeZone;return n!==e&&n.toLowerCase()===e.toLowerCase()?t:void 0}catch{return t}}function fi(e){let t=e??{},n=`@Cron(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Lt.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(typeof t.schedule!="string")throw new TypeError(`${n}: schedule is five fields of cron's, like "0 3 * * *"`);let r=zn(t.schedule);if(r)throw new TypeError(`${n}: ${r}`);if(t.timeZone!==void 0&&(typeof t.timeZone!="string"||qn(t.timeZone)!==void 0))throw new TypeError(`${n}: ${qn(String(t.timeZone))}`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>10))throw new TypeError(`${n}: retry is a whole number, 0 to 10 (got ${String(t.retry)})`);let s={name:t.name,schedule:t.schedule.trim().split(/\s+/).join(" "),timeZone:t.timeZone??"UTC",timeout:t.timeout??30,retries:t.retry??5};return o=>{if(typeof o.prototype.run!="function")throw new TypeError(`${n} on ${o.name}: a cron is a class with a run(meta) method`);if(Object.prototype.hasOwnProperty.call(o,he))throw new TypeError(`${n} on ${o.name}: a class is one cron`);Object.defineProperty(o,he,{value:s,enumerable:!1}),re().add(o)}}var Hn=["stripe","github","twilio","sendgrid","slack","discord","livekit"],$s=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;function pi(e){return t=>{let n=`@Webhook on ${t.name}`,r=e??{};if(typeof r.name!="string"||r.name==="")throw new TypeError(`${n}: name is required \u2014 the last segment of its URL, /webhooks/<name>, which the sender is configured with`);if(!$s.test(r.name))throw new TypeError(`${n}: name "${r.name}" is the last segment of its URL: lowercase letters, digits and dashes, starting and ending with one of those`);if(r.name==="palbase")throw new TypeError(`${n}: /webhooks/palbase is the platform's own deliveries (an @On outside a @Webhook class takes them); this webhook is served under another name`);if(r.provider===void 0&&r.signature===void 0)throw new TypeError(`${n}: a provider or a signature is required \u2014 an endpoint that verifies nothing takes forged deliveries`);if(r.provider!==void 0&&r.signature!==void 0)throw new TypeError(`${n}: a provider and a signature are alternatives \u2014 keep the one that describes the sender`);if(r.provider!==void 0&&!Hn.includes(r.provider))throw new TypeError(`${n}: provider "${String(r.provider)}" is not one of ${Hn.join(", ")} \u2014 another sender's scheme is spelled out as signature`);if(r.signature!==void 0&&Ts(r.signature,n),typeof r.secret?.env!="string"||r.secret.env==="")throw new TypeError(`${n}: secret: { env: "VAR_NAME" } is required \u2014 the env var holding the signing secret`);let s=M(t,be)??[];if(s.length===0)throw new TypeError(`${n}: at least one @On is required \u2014 a webhook that runs nothing for every delivery is a mistake`);let o=new Set;for(let{event:a,bucket:i}of s){if(o.has(a))throw new TypeError(`${n}: @On("${a}") is declared twice; one method takes an event`);if(i!==void 0)throw new TypeError(`${n}: @On("${a}", { bucket: "${i}" }) \u2014 a bucket keeps a handler to the project's storage events, and ${r.name}'s are a third party's`);o.add(a)}Y(t,Oe,()=>({name:r.name,provider:r.provider,signature:r.signature&&{...r.signature},secret:{env:r.secret.env},events:s.map(({event:a,fn:i})=>({event:a,fn:i}))})),re().add(t)}}function Ts(e,t){if(typeof e.header!="string"||e.header==="")throw new TypeError(`${t}: signature.header is required \u2014 the header the signature arrives in`);if(e.prefix!==void 0&&typeof e.prefix!="string")throw new TypeError(`${t}: signature.prefix is the text before the signature, like "sha256="`);if(e.algo!=="hmac-sha256"&&e.algo!=="hmac-sha1")throw new TypeError(`${t}: signature.algo "${String(e.algo)}" is not hmac-sha256 or hmac-sha1`);if(e.encoding!=="hex"&&e.encoding!=="base64")throw new TypeError(`${t}: signature.encoding "${String(e.encoding)}" is not hex or base64`);if(typeof e.signs!="string"||!e.signs.includes("{body}"))throw new TypeError(`${t}: signature.signs must contain {body} \u2014 a signature of a constant signs nothing`);if(e.signs.includes("{ts}")&&(typeof e.timestampHeader!="string"||e.timestampHeader===""))throw new TypeError(`${t}: signature.signs uses {ts} but no timestampHeader says where to read it`)}function M(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function mi(){return[...re()].filter(e=>M(e,_e)!==void 0)}function hi(e){return(M(e,Se)??[]).map(t=>({method:t.method,path:t.subpath,fnName:t.fn,options:{...t.options,...t.upload!==void 0?{uploadConfig:t.upload}:{}}}))}var ut=class extends Error{constructor(t,n){super(t,n),this.name="TaskFailure"}};function ki(e){let t=e??{},n=`@Task(${JSON.stringify(t.name??null)})`;if(typeof t.name!="string"||!Lt.test(t.name))throw new TypeError(`${n}: name is letters, digits, '.', '_' and '-', at most 64, starting with a letter or digit`);if(t.timeout!==void 0&&(!Number.isInteger(t.timeout)||t.timeout<1||t.timeout>900))throw new TypeError(`${n}: timeout is whole seconds, 1 to 900 (got ${String(t.timeout)})`);if(t.retry!==void 0&&(!Number.isInteger(t.retry)||t.retry<0||t.retry>20))throw new TypeError(`${n}: retry is a whole number, 0 to 20 (got ${String(t.retry)})`);if(t.concurrency!==void 0&&(!Number.isInteger(t.concurrency)||t.concurrency<1||t.concurrency>50))throw new TypeError(`${n}: concurrency is a whole number, 1 to 50 (got ${String(t.concurrency)})`);if(t.payload!==void 0&&typeof t.payload?.["~standard"]?.validate!="function")throw new TypeError(`${n}: payload is a schema (zod, valibot, arktype \u2014 any Standard Schema)`);let r={name:t.name,timeout:t.timeout??60,retries:t.retry??5,concurrency:t.concurrency??5,...t.payload?{payload:t.payload}:{}};return s=>{if(typeof s.prototype.run!="function")throw new TypeError(`${n} on ${s.name}: a task is a class with a run(payload, meta) method`);if(Object.prototype.hasOwnProperty.call(s,fe))throw new TypeError(`${n} on ${s.name}: a class is one task type`);Object.defineProperty(s,fe,{value:r,enumerable:!1}),re().add(s)}}var qt;function Kn(e){qt=e}function It(){if(!qt)throw new Error("Tasks are put on the queue once the app is served (serve() binds the queue)");return qt}var Es=720*3600;function Rs(e){if(e.delay!==void 0&&(!Number.isInteger(e.delay)||e.delay<0||e.delay>Es))throw new TypeError(`Tasks.enqueue: delay is whole seconds, 0 to 30 days (got ${String(e.delay)})`);if(e.runAt!==void 0&&!(e.runAt instanceof Date&&!Number.isNaN(e.runAt.getTime())))throw new TypeError("Tasks.enqueue: runAt is a Date");if(e.delay!==void 0&&e.runAt!==void 0)throw new TypeError("Tasks.enqueue: a task is due after a delay or at a time \u2014 give one of the two");if(e.key!==void 0&&(typeof e.key!="string"||e.key===""||new TextEncoder().encode(e.key).length>200))throw new TypeError("Tasks.enqueue: key is text of 1 to 200 bytes")}function _s(e){if(typeof e=="string")return e;let t=e[fe];if(!t)throw new TypeError(`Tasks.enqueue: ${e.name} is not a @Task class`);return t.name}var vi=dt("Tasks",{async enqueue(e,t,n={}){return Rs(n),It().enqueue(_s(e),t===void 0?null:t,n)},async cancel(e,t={}){return It().cancel(e,t.machine)},async get(e,t={}){return It().get(e,t.machine)}}),zt=(e,t)=>({id:e.id,task:e.task,state:e.state,attempt:e.attempt,runAt:new Date(e.run_at).toISOString(),...e.key?{key:e.key}:{},...e.reason?{reason:e.reason}:{},duplicate:t});function Jn(e){let t=n=>{let r=n??e;if(!r)throw new Error("[palbase] this machine was started without PALBASE_MACHINE, its own name: deploy it again, and the platform gives it");return r};return{async enqueue(n,r,s){let o=await le.machines.enqueueTask({path:{name:t(s.machine)},body:{task:n,payload:r,...s.delay!==void 0?{delay:s.delay}:{},...s.runAt?{run_at:s.runAt.toISOString()}:{},...s.key!==void 0?{key:s.key}:{}}});return zt(o.data,o.status===200)},async cancel(n,r){return zt((await le.machines.cancelTask({path:{name:t(r),task:n}})).data,!1)},async get(n,r){return zt((await le.machines.getTask({path:{name:t(r),task:n}})).data,!1)}}}var Ss=1e4,Os=36e5,Fn=24*36e5,lt=class{constructor(t,n,r=Date.now){this.types=t;this.run=n;this.now=r}types;run;now;tasks=new Map;running=new Map;idle=new Set;async enqueue(t,n,r){if(r.machine!==void 0)throw new ie({op:"enqueueTask",status:404,code:"machine_not_found",message:`off the platform the app runs its own tasks only: ${r.machine}'s are its own machine's`});if(!this.types.has(t))throw new ie({op:"enqueueTask",status:404,code:"task_type_not_found",message:`this app has no @Task ${JSON.stringify(t)}`});let s=JSON.stringify(n??null);if(new TextEncoder().encode(s).length>65536)throw new ie({op:"enqueueTask",status:413,code:"payload_too_large",message:"a task carries 64 KiB at most: name what it works on (an id), and read it where it runs"});if(r.key!==void 0){for(let c of this.tasks.values())if(c.task===t&&c.key===r.key&&(c.finishedAt===void 0||this.now()-c.finishedAt<Fn))return this.view(c,!0)}let o=this.now(),a=r.delay!==void 0?o+r.delay*1e3:r.runAt?Math.max(o,r.runAt.getTime()):o,i={id:crypto.randomUUID(),task:t,payload:JSON.parse(s),key:r.key,state:"waiting",attempt:0,runAt:a,createdAt:new Date(o)};return this.tasks.set(i.id,i),this.schedule(i),this.view(i,!1)}async cancel(t){let n=this.known(t);if(n.state!=="waiting")throw new ie({op:"cancelTask",status:409,code:"task_not_waiting",message:`only a task waiting is cancelled (it is ${n.state})`});return clearTimeout(n.timer),this.finish(n,"cancelled","cancelled before it ran"),this.view(n,!1)}async get(t){return this.view(this.known(t),!1)}settled(){return this.quiet()?Promise.resolve():new Promise(t=>this.idle.add(t))}quiet(){for(let t of this.tasks.values())if(t.state==="running"||t.state==="waiting"&&t.runAt<=this.now())return!1;return!0}known(t){let n=this.tasks.get(t);if(!n)throw new ie({op:"getTask",status:404,code:"task_not_found",message:"the machine has no task of this id"});return n}view(t,n){return{id:t.id,task:t.task,state:t.state,attempt:t.attempt,runAt:new Date(t.runAt).toISOString(),...t.key?{key:t.key}:{},...t.reason?{reason:t.reason}:{},duplicate:n}}schedule(t){clearTimeout(t.timer),t.timer=setTimeout(()=>this.pump(),Math.max(0,t.runAt-this.now())),t.timer.unref?.()}pump(){let t=this.now();for(let n of[...this.tasks.values()].sort((r,s)=>r.runAt-s.runAt)){if(n.state!=="waiting"||n.runAt>t)continue;let r=this.types.get(n.task);(this.running.get(n.task)??0)>=r.concurrency||this.attempt(n,r)}this.wake()}async attempt(t,n){t.state="running",t.attempt++,this.running.set(t.task,(this.running.get(t.task)??0)+1);let r=new AbortController,s=setTimeout(()=>r.abort(),n.timeout*1e3),o;try{o=await this.run({task:t.task,id:t.id,attempt:t.attempt,payload:t.payload,createdAt:t.createdAt},r.signal),r.signal.aborted&&(o={status:504,message:`it did not end in ${n.timeout} s`})}catch(i){o={status:500,message:i.message}}finally{clearTimeout(s),this.running.set(t.task,(this.running.get(t.task)??1)-1)}let a=`${o.status}${o.message?`: ${o.message}`:""}`;o.status>=200&&o.status<300?this.finish(t,"succeeded"):o.status===422?this.finish(t,"failed",`the app said it can never be done: ${a}`):t.attempt>n.retries?this.finish(t,"failed",`the app answered ${a}`):(t.state="waiting",t.reason=`the app answered ${a}`,t.runAt=this.now()+Math.min(Ss*2**Math.min(t.attempt-1,16),Os),E.warn(`[palbase] task ${t.task} ${t.id}: attempt ${t.attempt} failed; made again in ${Math.round((t.runAt-this.now())/1e3)} s`,{reason:t.reason}),this.schedule(t)),this.pump()}finish(t,n,r){t.state=n,t.finishedAt=this.now(),r&&(t.reason=r);for(let[s,o]of this.tasks)o.finishedAt!==void 0&&this.now()-o.finishedAt>=Fn&&this.tasks.delete(s);n==="failed"&&E.error(`[palbase] task ${t.task} ${t.id} failed: ${r}`),this.wake()}wake(){if(!(this.idle.size===0||!this.quiet())){for(let t of this.idle)t();this.idle.clear()}}};import{markData as As}from"palgres";var Ht="/_palbase/storage/upload/authorize",Wn="/_palbase/storage/upload/complete",Bt="/_palbase/realtime/rooms";var xs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Pe(e){if(!xs(e)||typeof e.role!="string"||e.role===""||e.id!==void 0&&typeof e.id!="string"||e.session!==void 0&&typeof e.session!="string")return;let t={role:e.role};return typeof e.id=="string"&&e.id!==""&&(t.id=e.id),typeof e.session=="string"&&e.session!==""&&(t.session=e.session),t.id&&typeof e.email=="string"&&e.email!==""&&(t.email=e.email),t.id&&typeof e.emailVerified=="boolean"&&(t.emailVerified=e.emailVerified),t}function Vn(e){return typeof e=="string"&&e!==""&&e.length<=64?e:void 0}function Zn(e,t){return e.id?`u:${e.id}`:e.session?`s:${e.session}`:t?`a:${t}`:`r:${e.role}`}function ft(e){return e?.id?{sub:e.id,role:e.role,...e.session?{session_id:e.session}:{}}:null}var pe=Symbol.for("palbase.backend.room"),Me=Symbol.for("palbase.backend.roomHooks"),Jt=6e4,Ce=255,Ps=["roles:","flags:","messaging:","debug:"],Wt=e=>new TextEncoder().encode(e).byteLength,Qn=e=>typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function";function Vt(e){if(e.includes("/"))return`channel patterns are colon-separated, not slash-separated. Write "${e.replace(/\//g,":")}" \u2014 a slash matches no live topic.`;if(Wt(e)>Ce)return`a channel is ${Ce} bytes at most`;if(/[\x00-\x1F\x7F]/.test(e))return"a channel has no control character";if(e==="phoenix")return"phoenix is the socket's own";let t=Ps.find(r=>e.startsWith(r));if(t)return`${t} channels are the platform's`;let n=new Set;for(let r of e.split(":")){if(r==="")return"empty segment \u2014 every segment must be non-empty.";if(/[{}]/.test(r)){if(r==="{}")return'"{}" names no parameter.';if(!/^\{[^{}]+\}$/.test(r))return`"${r}" \u2014 a parameter is a whole segment, {name}`;if(n.has(r))return`parameter "${r}" appears twice.`;n.add(r)}}}function Gn(e){if(typeof e!="string"||e==="")return"is a name";if(Wt(e)>Ce)return`is ${Ce} bytes at most`}function Oi(e,t){if(typeof e!="string"||e==="")throw new TypeError('@Room(pattern, { events }): pattern is the channels it is, like "ai:{sessionId}"');let n=Vt(e);if(n)throw new TypeError(`@Room("${e}"): ${n}`);let r=t??{};if(typeof r.events!="object"||r.events===null||Array.isArray(r.events))throw new TypeError(`@Room("${e}"): events is required \u2014 what the room sends, by name, each its payload's schema ({} for none)`);for(let[a,i]of Object.entries(r.events)){let c=Gn(a);if(c)throw new TypeError(`@Room("${e}"): event "${a}" ${c}`);if(!Qn(i))throw new TypeError(`@Room("${e}"): event "${a}" is a Standard Schema (a zod, valibot or arktype schema) \u2014 its payload's`)}if(r.graceMs!==void 0&&(!Number.isSafeInteger(r.graceMs)||r.graceMs<=0))throw new TypeError(`@Room("${e}"): graceMs is whole milliseconds, more than 0 (got ${String(r.graceMs)})`);let s={...r.events},o=r.graceMs??Jt;return a=>{let i=Y(a,Me,Zt);Y(a,pe,()=>({pattern:e,events:s,graceMs:o,hooks:{...i.hooks},messages:Object.assign(Object.create(null),i.messages)})),re().add(a)}}var Zt=()=>({hooks:Object.create(null),messages:Object.create(null)});function Je(e){let t=`On${e[0].toUpperCase()}${e.slice(1)}`;return()=>(n,r,s)=>{if(typeof r!="string"||s===void 0||typeof s.value!="function")throw new TypeError(`@${t}() goes on a method`);if(typeof n=="function")throw new TypeError(`@${t}() on static ${n.name}.${r}: a room's methods are its instance's`);let o=Y(n.constructor,Me,Zt),a=o.hooks[e];if(a!==void 0&&a!==r)throw new TypeError(`@${t}() is declared twice in one room (${a} and ${r}). A room has one of each hook.`);o.hooks[e]=r,re().add(n.constructor)}}var xi=Je("authorize"),Ai=Je("first"),Pi=Je("join"),Ci=Je("leave"),Mi=Je("empty");function Di(e,t){let n=Gn(e);if(n)throw new TypeError(`@OnMessage(name, schema): name ${n}`);if(!Qn(t))throw new TypeError(`@OnMessage("${e}", schema): schema is a Standard Schema (a zod, valibot or arktype schema)`);return(r,s,o)=>{if(typeof s!="string"||o===void 0||typeof o.value!="function")throw new TypeError(`@OnMessage("${e}") goes on a method`);if(typeof r=="function")throw new TypeError(`@OnMessage("${e}") on static ${r.name}.${s}: a room's methods are its instance's`);let a=Y(r.constructor,Me,Zt),i=a.messages[e];if(i!==void 0&&i.fn!==s)throw new TypeError(`@OnMessage("${e}") is declared twice in one room (${i.fn} and ${s}).`);a.messages[e]={fn:s,schema:t},re().add(r.constructor)}}function Qt(e){return M(e,pe)}function Cs(e,t){let n=e.split(":"),r=t.split(":");if(n.length!==r.length)return;let s=[];for(let o=0;o<n.length;o++){let a=n[o];if(a.length>=2&&a.startsWith("{")&&a.endsWith("}")){if(r[o]==="")return;s.push([a.slice(1,-1),r[o]])}else if(a!==r[o])return}return Object.fromEntries(s)}var Ms=1e4,Ds=1e3,js=100,Gt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ce=(e,t,n,r)=>({status:e,code:t,message:n,...r!==void 0?{retryAfter:r}:{}}),Ns=new Set(["first","join","leave","empty"]);function Yn(e,t){let n=new Map,r=new Map;for(let{cls:h,instance:v}of e){let b=Qt(h),O=b.pattern.split(":").map(F=>F.startsWith("{")?"{}":F).join(":"),z=r.get(O);if(z!==void 0)throw new TypeError(`@Room("${b.pattern}") on ${h.name}: ${n.get(z)?.cls.name}'s "${z}" is the same channels \u2014 one room is told of them; keep one`);r.set(O,b.pattern);for(let[F,D]of[...Object.entries(b.hooks),...Object.entries(b.messages).map(([j,q])=>[`message ${j}`,q.fn])])if(typeof v[D]!="function")throw new TypeError(`@Room("${b.pattern}") on ${h.name}: its ${F} is ${D}, which is no method of it`);n.set(b.pattern,{cls:h,instance:v,room:b})}let s=new Map,o=new Set,a=new Set,i=new Kt(t.broadcast),c=h=>{let v=s.get(h);return v||(v=new AbortController,s.set(h,v)),v},p=(h,v)=>{v?.abort(),s.get(h)===v&&s.delete(h)};function y(h,v,b,O,z,F,D){let j=O?.signal??AbortSignal.abort(),q=`${h.cls.name} (${v})`;return{room:v,params:Object.freeze({...b}),signal:j,count:z,user:F,emit:(H,K)=>i.send({topic:v,event:H,payload:K??{},...D!==void 0?{conn_id:D}:{}},q),owner:{hold(H){ee.exit(async()=>{try{await H(j)}catch(K){j.aborted||E.error(`[palbase] ${q}: a task owner.hold ran failed`,{error:K})}}).catch(()=>{})},release:()=>p(v,O)}}}function k(h){let{room:v,channel:b}=h;if(typeof v!="string"||typeof b!="string")return ce(400,"bad_request","A room's call names its room (the pattern) and its channel");let O=n.get(v);return O?{entry:O,channel:b,params:Cs(v,b)}:ce(404,"not_found",`This app declares no room "${v}"`)}let R=(h,v)=>ce(400,"bad_request",`"${v}" is not a channel of the room "${h}"`);async function U(h,v){let b=k(h);if("status"in b)return b;let{entry:O,channel:z,params:F}=b,D={status:200,body:{subscribe:!1,publish:!1}};if(!F)return E.warn(`[palbase] ${O.cls.name}: realtime asked about "${z}", which is not a channel of the room "${O.room.pattern}"; the join is refused`),D;let j=Pe(h.user),q=j?.id;if(!q)return D;let H=O.room.hooks.authorize;if(!H)return D;let K,de;try{K=await t.run(j,`${O.cls.name}.${H}`,v,async()=>O.instance[H]({user:{id:q},params:Object.freeze({...F})})),de=Us(K)}catch(ne){if(t.isOutage(ne)||v?.aborted)throw ne;return E.error(`[palbase] ${O.cls.name}.${H} (@OnAuthorize of ${z}) failed; the join is refused`,{error:ne}),D}return de==="malformed"?(E.warn(`[palbase] ${O.cls.name}.${H} (@OnAuthorize of ${z}) answered ${Ls(K)}, which is no grant (true, { read, write } or null); the join is refused`),D):{status:200,body:de}}async function I(h,v){let b=k(h);if("status"in b)return b;if(!b.params)return R(b.entry.room.pattern,b.channel);let O=Pe(h.user);if(!O?.id||typeof h.event!="string")return ce(400,"bad_request","A message names its member (user) and its event");let z=Object.hasOwn(b.entry.room.messages,h.event)?b.entry.room.messages[h.event]:void 0;if(!z)return{status:200,body:{ok:!1,reason:Xn(`room "${b.channel}" declares no message "${h.event}"`,Ft)}};let F=await z.schema["~standard"].validate(As(h.payload??{}));if(F.issues)return{status:200,body:{ok:!1,reason:zs(F.issues)}};let D=c(b.channel),j={...y(b.entry,b.channel,b.params,D,0,{id:O.id}),payload:F.value};try{await t.run(O,`${b.entry.cls.name}.${z.fn}`,v,async()=>b.entry.instance[z.fn](j))}catch(q){if(t.isOutage(q))throw q;return v?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${z.fn} (@OnMessage "${h.event}" of ${b.channel}) failed`,{error:q}),{status:200,body:{ok:!1,reason:"handler_failed"}}}return{status:200,body:{ok:!0}}}async function L(h,v){let b=k(h);if("status"in b)return b;if(!b.params)return R(b.entry.room.pattern,b.channel);let O=h.event;if(typeof O!="string"||!Ns.has(O))return ce(400,"bad_request","A room's moment is first, join, leave or empty");let z=typeof h.count=="number"&&Number.isInteger(h.count)&&h.count>=0?h.count:void 0;if(z===void 0)return ce(400,"bad_request","A room's moment says its count of members");let F=O==="join"||O==="leave",D=F?Pe(h.user):void 0,j=F?h.connId:void 0;if(F&&(!D?.id||typeof j!="string"||j===""))return ce(400,"bad_request",`A ${O} names its member: user and connId`);let q=`${O}\0${b.channel}\0${typeof j=="string"?j:""}`;if(F&&o.has(q))return{status:204};if(a.has(q))return ce(503,"in_progress","This moment of the room is being handled",5);a.add(q);try{let H=b.entry.room.hooks[O],K;if(O==="empty"?(K=s.get(b.channel),p(b.channel,K)):K=O==="leave"?s.get(b.channel):c(b.channel),H){let de=y(b.entry,b.channel,b.params,K,z,{id:D?.id??""},O==="join"?j:void 0);try{await t.run(D,`${b.entry.cls.name}.${H}`,v,async()=>b.entry.instance[H](de))}catch(ne){if(t.isOutage(ne))throw ne;return v?.aborted||E.error(`[palbase] ${b.entry.cls.name}.${H} (${O} of ${b.channel}) failed; realtime tells it again`,{error:ne}),ce(500,"handler_failed",`The room's ${O} could not be handled`)}}return F&&(o.add(q),o.size>Ms&&o.delete(o.values().next().value)),{status:204}}finally{a.delete(q)}}return{declarations:[...n.values()].map(h=>h.room),async serve(h,v,b){return Gt(v)?h==="authorize"?U(v,b):h==="message"?I(v,b):h==="lifecycle"?L(v,b):ce(404,"not_found",`No room call ${JSON.stringify(h)}`):ce(400,"bad_request","A room's call is a JSON object")},close(){for(let h of s.values())h.abort();s.clear()}}}function Us(e){let t={subscribe:!1,publish:!1};if(e==null||e===!1)return t;if(e===!0)return{subscribe:!0,publish:!0};if(!Gt(e))return"malformed";let n=Object.hasOwn(e,"read"),r=Object.hasOwn(e,"write");if(n&&typeof e.read!="boolean"||r&&typeof e.write!="boolean"||!n&&!r)return"malformed";let s=n?e.read:void 0,o=r?e.write:void 0;return s===!1?t:{subscribe:!0,publish:o!==!1}}function Ls(e){return Array.isArray(e)?"an array":Gt(e)?Object.hasOwn(e,"read")||Object.hasOwn(e,"write")?"an object whose read or write is not true or false":"an object that says neither read nor write":typeof e=="function"?"a function":typeof e=="string"?"a string":`${typeof e} ${String(e)}`}var Is=20,Ft=256;function zs(e){let t="";for(let n of e.slice(0,Is)){let r=(n.path??[]).slice(0,8).map(o=>String(typeof o=="object"&&o!==null&&"key"in o?o.key:o).slice(0,64)).join("."),s=r===""?n.message:`${r}: ${n.message}`;if(t=t===""?s:`${t}; ${s}`,Buffer.byteLength(t)>=Ft)break}return Xn(t,Ft)}function Xn(e,t){if(Buffer.byteLength(e)<=t)return e;let n="";for(let r of e){if(Buffer.byteLength(n+r)>t-3)break;n+=r}return`${n}\u2026`}var Kt=class{constructor(t){this.broadcast=t}broadcast;queues=new Map;dropped=new Map;send(t,n){if(typeof t.event!="string"||t.event===""||Wt(t.event)>Ce){E.warn(`[palbase] ${n}: emit(${JSON.stringify(t.event)}) is not sent \u2014 an event's name is 1 to ${Ce} bytes`);return}try{JSON.stringify(t.payload)}catch(o){E.warn(`[palbase] ${n}: emit("${t.event}") is not sent \u2014 its payload is not JSON`,{error:o});return}let r=this.queues.get(t.topic);if(r){r.length>=Ds?this.dropped.set(t.topic,(this.dropped.get(t.topic)??0)+1):r.push(t);return}let s=[t];this.queues.set(t.topic,s),ee.exit(()=>this.drain(t.topic,s,n))}async drain(t,n,r){for(;;){if(n.length===0){this.queues.delete(t);return}let s=n.splice(0,js);try{await this.broadcast(s)}catch(a){E.warn(`[palbase] ${r}: ${s.length} event(s) to ${t} were not sent`,{error:a})}let o=this.dropped.get(t);o&&(this.dropped.delete(t),E.warn(`[palbase] ${r}: ${o} event(s) to ${t} dropped \u2014 realtime took them slower than they were emitted`))}}};var Yt=Symbol.for("palbase.backend.channels");function Ii(){return{kind:"owner"}}function zi(e={}){return{kind:"public",publish:e.publish??!1,state:e.state}}var qs=e=>e.split(":").filter(t=>t.startsWith("{")&&t.endsWith("}")).length,pt=e=>e.split(":").map(t=>t.startsWith("{")?"{}":t).join(":");function qi(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("defineChannels({ pattern: entry }): an object of channel patterns");let t=[],n=[],r=new Map;for(let[i,c]of Object.entries(e)){let p=Vt(i);if(p)throw new TypeError(`defineChannels: "${i}": ${p}`);let y=r.get(pt(i));if(y!==void 0)throw new TypeError(`defineChannels: "${i}" and "${y}" are the same channels \u2014 keep one`);if(r.set(pt(i),i),typeof c!="object"||c===null)throw new TypeError(`defineChannels: "${i}": an entry is ownerOnly(), publicChannel() or { authorize }`);if("handler"in c)throw new TypeError(`defineChannels: "${i}": a handler is a room's in v3 \u2014 write @Room("${i}", { events }) with @OnAuthorize and @OnMessage, and leave it out of channels`);if("kind"in c&&c.kind==="owner"){if(qs(i)!==1)throw new TypeError(`defineChannels: ownerOnly() pattern "${i}" must carry exactly one {param} (its value is compared to the signed-in user's id)`);t.push({pattern:i,kind:"owner",publish:!1,state_read:!1,state_write:!1})}else if("kind"in c&&c.kind==="public")t.push({pattern:i,kind:"public",publish:c.publish??!1,state_read:c.state?.read??!1,state_write:c.state?.write??!1});else if("authorize"in c&&typeof c.authorize=="function")n.push({pattern:i,authorize:c.authorize});else throw new TypeError(`defineChannels: "${i}": an entry is ownerOnly(), publicChannel() or { authorize(ctx) }`)}let s={rows:t,custom:n},o=globalThis,a=o[Yt];if(a&&!Hs(a,s))throw new Error(`defineChannels: channels were already declared (${[...a.rows,...a.custom].map(i=>i.pattern).join(", ")}). A project declares its channels once \u2014 a second call would overwrite the first, and channels nobody declared are refused.`);return o[Yt]=s,s}function Hs(e,t){let n=r=>JSON.stringify([r.rows,r.custom.map(s=>[s.pattern,s.authorize.toString()])]);return n(e)===n(t)}function er(){return globalThis[Yt]??{rows:[],custom:[]}}function tr(e){let t=!1;return e.custom.map(({pattern:n,authorize:r})=>{let s={[`channel ${n}`]:class{}}[`channel ${n}`];return Y(s,pe,()=>({pattern:n,events:{},graceMs:Jt,hooks:{authorize:"authorize"},messages:Object.create(null)})),{cls:s,instance:{async authorize(a){let i=await r(a);return i==null||i.subscribe!==!0?null:(i.state&&!t&&(t=!0,E.warn(`[palbase] channel "${n}": its authorize answered state rights; a channel an authorize function decides is a room, which has none \u2014 the user hears${i.publish?" and sends":""}`)),{read:!0,write:i.publish===!0})}}}})}function nr(e,t){let n=new Map(t.map(r=>[pt(r.pattern),r.pattern]));for(let r of[...e.rows,...e.custom]){let s=n.get(pt(r.pattern));if(s!==void 0)return`channel "${r.pattern}" and @Room("${s}") are the same channels \u2014 a channel is declared in defineChannels or by a @Room, not both`}}var Bs=/^[a-z][a-z0-9-]{1,62}$/,rr=1024,Fs=new Set(["userId","uploadId","filename"]);function Ji(e,t){if(typeof e!="string")throw new TypeError("@Upload(path, { bucket, pathTemplate }): path is a string");let n=t??{};if(typeof t!="object"||t===null)throw new TypeError(`@Upload("${e}"): the second argument is { bucket, pathTemplate } \u2014 where its files go`);if(typeof n.bucket!="string"||n.bucket==="")throw new TypeError(`@Upload("${e}"): bucket is required \u2014 the name of the bucket its files go to`);if(!Bs.test(n.bucket))throw new TypeError(`@Upload("${e}"): bucket "${n.bucket}" is no bucket's name \u2014 lowercase letters, digits and dashes, starting with a letter, 2 to 63 long`);if(typeof n.pathTemplate!="string"||n.pathTemplate==="")throw new TypeError(`@Upload("${e}"): pathTemplate is required \u2014 the path each file is stored under, like "{userId}/{uploadId}-{filename}"`);let r=Ks(n.pathTemplate);if(r)throw new TypeError(`@Upload("${e}"): pathTemplate "${n.pathTemplate}" ${r}`);let s={bucket:n.bucket,pathTemplate:n.pathTemplate},o={...n.auth!==void 0?{auth:n.auth}:{},...n.rateLimit!==void 0?{rateLimit:n.rateLimit}:{}};return(a,i,c)=>{if(typeof i!="string"||c===void 0||typeof c.value!="function")throw new TypeError(`@Upload("${e}") goes on a method`);Y(a.constructor,Se,()=>[]).push({method:"POST",subpath:e,fn:i,options:o,upload:s})}}function Wi(){return se("uploadedObject")}function Ks(e){for(let n of e.matchAll(/\{([^{}]*)\}/g))if(!Fs.has(n[1]))return`names {${n[1]}}: its tokens are {userId}, {uploadId} and {filename}`;if(/[{}]/.test(e.replace(/\{(userId|uploadId|filename)\}/g,"")))return"has a brace of no token: its tokens are {userId}, {uploadId} and {filename}";let t=e.replace(/\{(userId|uploadId|filename)\}/g,"x");if(!sr(t))return"is no path storage keeps: segments separated by /, none empty, . or .., no control character, at most 1024 bytes"}function sr(e){if(e===""||new TextEncoder().encode(e).byteLength>rr)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n===127)return!1}return e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function Js(e,t){return e.replace(/\{(userId|uploadId|filename)\}/g,(n,r)=>Ws(r==="userId"?t.userId??"anonymous":r==="uploadId"?t.uploadId:t.filename??"file"))}function Ws(e){let t=e.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200F\u2028-\u202E\u2060-\u2069\uFEFF]/g,"").replace(/[/\\]/g,"-").replace(/\.{2,}/g,".").replace(/^[\s.]+/,"").trimEnd();return t===""?"file":Array.from(t).slice(0,200).join("")}function or(e,t){let n=Js(e,t);return sr(n)?{path:n}:{problem:`the file's name makes its path longer than storage keeps (${rr} bytes)`}}function ar(e){let t=new Map;for(let n of e)n.meta.upload&&t.set(n.controller,(t.get(n.controller)??new Set).add(n.fn));for(let n of e){let r=`${n.controller.name}.${n.fn}`;if(!n.meta.upload){if(t.get(n.controller)?.has(n.fn))throw new TypeError(`${r}: @Upload and @${n.method[0]}${n.method.slice(1).toLowerCase()} on one method \u2014 an upload's handler runs with the stored object, which an ordinary route has none of; give each its own method`);if(n.params.some(o=>o.kind==="uploadedObject"))throw new TypeError(`${r}: @UploadedObject() on ${n.id}, which is no @Upload route \u2014 only an upload has a stored object`);continue}let s=n.params.find(o=>o.kind==="headers"||o.kind==="req"||o.kind==="client");if(s){let o=s.kind==="headers"?"Headers":s.kind==="req"?"Req":"Client";throw new TypeError(`${r}: @${o}() on an @Upload route \u2014 the client's request reaches storage, which forwards none of its headers; the handler is given the caller (@User), the body (@Body) and the stored object`)}}}var Xt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ir(e,t){if(!Xt(t))return"a call is a JSON object";let{route:n,method:r,query:s,uploadId:o}=t;if(typeof n!="string"||!n.startsWith("/"))return"route is the upload route's path";if(typeof r!="string"||r==="")return"method is the route's";if(typeof s!="string")return'query is the query string, "" for none';if(typeof o!="string"||o==="")return"uploadId is the upload's id";let a=Pe(t.user);if(!a)return"user is { id?, session?, role }";let i=Vn(t.client);if(e==="authorize")return t.filename!==void 0&&typeof t.filename!="string"?"filename is the file's name":{route:n,method:r,query:s,uploadId:o,user:a,...i?{client:i}:{},filename:t.filename??"",...Object.hasOwn(t,"body")?{body:t.body??null}:{}};let c=Vs(t.uploadedObject);return c?c.uploadId!==o?"uploadedObject is another upload's":{route:n,method:r,query:s,uploadId:o,user:a,...i?{client:i}:{},filename:"",uploadedObject:c,body:t.body??null}:"uploadedObject is the stored object: { uploadId, path, bucket, size, contentType, checksum, width?, height?, thumbhash?, variants }"}function Vs(e){if(!Xt(e))return;let{uploadId:t,path:n,bucket:r,size:s,contentType:o,checksum:a,width:i,height:c,thumbhash:p,variants:y}=e;if(!(typeof t!="string"||typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof a!="string")&&!(typeof s!="number"||!Number.isInteger(s)||s<0)&&!(i!==void 0&&typeof i!="number"||c!==void 0&&typeof c!="number"||p!==void 0&&typeof p!="string")&&!(!Xt(y)||!Object.values(y).every(k=>typeof k=="string")))return{uploadId:t,path:n,bucket:r,size:s,contentType:o,checksum:a,...i!==void 0?{width:i}:{},...c!==void 0?{height:c}:{},...p!==void 0?{thumbhash:p}:{},variants:{...y}}}import{createHash as en,createHmac as Zs,createPublicKey as lr,timingSafeEqual as Qs,verify as fr}from"node:crypto";function Gi(e){let t=M(e,Oe);if(!t)throw new TypeError(`${e.name} is not a @Webhook`);return{name:t.name,provider:t.provider,secretEnv:t.secret.env,events:t.events.map(n=>n.event)}}function pr(e,t,n,r={}){let s=new Map,o=[];for(let a of e){let i=M(a,Oe),c=s.get(i.name);if(c)throw new TypeError(`@Webhook "${i.name}" is declared by ${c.cls.name} and by ${a.name}: /webhooks/${i.name} is one endpoint`);let p=`@Webhook "${i.name}" (${a.name})`,y=n[i.secret.env],k;if(r.secrets!==!1)if(y===void 0||y==="")o.push(`${p} reads its signing secret from ${i.secret.env}, which is not set`);else try{k=Gs(i,y)}catch(I){o.push(`${p}: ${i.secret.env} ${I.message}`)}let R=t(a),U=new Map(i.events.map(({event:I,fn:L})=>[I,{name:`${a.name}.${L}`,call:(h,v)=>R[L](h,v)}]));s.set(i.name,{name:i.name,cls:a,provider:i.provider,signatureHeader:i.signature?.header,secretEnv:i.secret.env,scheme:k,events:U})}if(o.length>0)throw new Error(`[palbase] the app cannot start:
3
- - ${o.join(`
4
- - `)}`);return s}function mr(e,t){return`https://${(e.headers.get("host")??t.host).toLowerCase()}${t.pathname}${t.search}`}var De=1024,dr=1024*De;function Gs(e,t){if(e.signature)return ke(void 0,e.signature.header,1/0,co(e.signature,t));switch(e.provider){case"stripe":return ke("stripe","stripe-signature",512*De,eo(t));case"github":return ke("github","x-hub-signature-256",25*dr,to(t));case"slack":return ke("slack","x-slack-signature",64*De,no(t));case"discord":return ke("discord","x-signature-ed25519",64*De,ro(t));case"twilio":return{header:"x-twilio-signature",maxBytes:n=>Math.min(n,64*De),check:oo(t)};case"sendgrid":return ke("sendgrid","x-twilio-email-event-webhook-signature",dr,ao(t));case"livekit":return ke("livekit","authorization",512*De,io(t));default:throw new TypeError(`names no scheme: provider ${String(e.provider)}`)}}function ke(e,t,n,r){return{header:t,maxBytes:s=>Math.min(s,n),check:(s,o)=>r(s,o)??hr(e,s)}}function hr(e,t){let n=tn(t.body),r;try{r=JSON.parse(n)}catch{if(r=n,e==="slack"){let s=new URLSearchParams(n).get("payload");if(s!==null)try{r=JSON.parse(s)}catch{}}}return{type:gr(e,t.headers,r),event:r,...Ys(e,t,r)}}function gr(e,t,n){switch(e){case"github":{let r=t.get("x-github-event")??"",s=ve(n,"action");return r!==""&&s!==""?`${r}.${s}`:r}case"discord":{let r=br(n)?n.type:void 0;return r===1?"PING":r===2?"INTERACTION_CREATE":Number.isInteger(r)?`type_${String(r)}`:""}case"sendgrid":return"event_batch";case"twilio":return ve(n,"EventType");case"livekit":return ve(n,"event");default:return ve(n,"type")}}function Ys(e,t,n){let r=s=>s?{id:s}:{};switch(e){case"stripe":case"discord":case"livekit":return r(ve(n,"id"));case"slack":return r(ve(n,"event_id"));case"github":{let s=t.headers.get("x-github-delivery");return s?{id:`${s}:${yr(t.body)}`}:{}}case"sendgrid":return Array.isArray(n)?{ids:n.map(s=>ve(s,"sg_event_id")||void 0)}:{};default:return{}}}var Xs=300;function eo(e){return(t,n)=>{let r=t.headers.get("stripe-signature");if(!r)return"missing_signature";let s,o=[];for(let c of r.split(",")){let p=c.indexOf("=");if(p<=0)continue;let y=c.slice(0,p).trim(),k=c.slice(p+1).trim();if(y==="t"){if(s!==void 0)return"malformed_signature";s=k}else if(y==="v1"){let R=oe(k,"hex");if(!R)return"malformed_signature";o.push(R)}}let a=We(s);if(a===void 0||o.length===0)return"malformed_signature";if(Ve(a,n))return"stale_timestamp";let i=je("sha256",e,`${s}.`,t.body);return o.some(c=>ge(c,i))?void 0:"signature_mismatch"}}function to(e){return t=>{let n=t.headers.get("x-hub-signature-256");if(!n)return"missing_signature";let r=n.startsWith("sha256=")?oe(n.slice(7),"hex"):void 0;return r?ge(r,je("sha256",e,t.body))?void 0:"signature_mismatch":"malformed_signature"}}function no(e){return(t,n)=>{let r=t.headers.get("x-slack-signature");if(!r)return"missing_signature";let s=t.headers.get("x-slack-request-timestamp")?.trim(),o=We(s),a=r.startsWith("v0=")?oe(r.slice(3),"hex"):void 0;return o===void 0||!a?"malformed_signature":Ve(o,n)?"stale_timestamp":ge(a,je("sha256",e,`v0:${s}:`,t.body))?void 0:"signature_mismatch"}}function ro(e){let t=oe(e,"hex");if(!t||t.byteLength!==32)throw new TypeError("is not an Ed25519 public key: the application's PUBLIC KEY, 64 hex characters");let n=lr({key:{kty:"OKP",crv:"Ed25519",x:Buffer.from(t).toString("base64url")},format:"jwk"});return(r,s)=>{let o=r.headers.get("x-signature-ed25519");if(!o)return"missing_signature";let a=r.headers.get("x-signature-timestamp")??void 0,i=We(a),c=oe(o,"hex");return i===void 0||!c||c.byteLength!==64?"malformed_signature":Ve(i,s)?"stale_timestamp":fr(null,wr(a,r.body),n,c)?void 0:"signature_mismatch"}}var so=1e3;function oo(e){return t=>{let n=t.headers.get("x-twilio-signature");if(!n)return"missing_signature";let r=oe(n.trim(),"base64");if(!r||r.byteLength!==20)return"malformed_signature";let s;try{s=new URL(t.url)}catch{return"signature_mismatch"}let o=s.searchParams.get("bodySHA256"),a="",i;if(o!==null){if(!ge(Buffer.from(o.toLowerCase()),Buffer.from(en("sha256").update(t.body).digest("hex"))))return"signature_mismatch"}else{let U=1;for(let h of t.body)if(h===38&&++U>so)return"malformed_signature";let I=new Map;for(let[h,v]of new URLSearchParams(tn(t.body))){let b=I.get(h);b||I.set(h,b=new Set),b.add(v)}let L=[];for(let h of[...I.keys()].sort()){let v=[...I.get(h)].sort();for(let b of v)a+=h+b;L.push([h,v.length===1?v[0]:v])}i=Object.fromEntries(L)}let c=s.protocol==="https:"?"443":"80",p=`${s.protocol}//${s.hostname}${s.pathname}${s.search}`,y=`${s.protocol}//${s.hostname}:${s.port||c}${s.pathname}${s.search}`;if(![p,y].some(U=>ge(r,je("sha1",e,U,a))))return"signature_mismatch";let k=t.headers.get("i-twilio-idempotency-token"),R=k?{id:`${k}:${yr(`${p}
5
- ${a}`)}`}:{};return i?{type:gr("twilio",t.headers,i),event:i,...R}:{...hr("twilio",t),...R}}}function ao(e){let t;try{let n=oe(e,"base64");if(!n)throw new Error;t=lr({key:Buffer.from(n),format:"der",type:"spki"})}catch{throw new TypeError("is not the Event Webhook's verification key: the base64 public key SendGrid shows")}if(t.asymmetricKeyType!=="ec"||t.asymmetricKeyDetails?.namedCurve!=="prime256v1")throw new TypeError("is not the Event Webhook's verification key: an ECDSA P-256 public key");return(n,r)=>{let s=n.headers.get("x-twilio-email-event-webhook-signature");if(!s)return"missing_signature";let o=n.headers.get("x-twilio-email-event-webhook-timestamp")?.trim(),a=We(o),i=oe(s.trim(),"base64");return a===void 0||!i?"malformed_signature":Ve(a,r)?"stale_timestamp":fr("sha256",wr(o,n.body),{key:t,dsaEncoding:"der"},i)?void 0:"signature_mismatch"}}var cr=60;function io(e){return(t,n)=>{let r=t.headers.get("authorization");if(!r)return"missing_signature";let s=r.split(".");if(s.length!==3)return"malformed_signature";let o=ur(oe(s[0],"base64url")),a=oe(s[2],"base64url");if(o?.alg!=="HS256"||!a)return"malformed_signature";if(!ge(a,je("sha256",e,`${s[0]}.${s[1]}`)))return"signature_mismatch";let i=ur(oe(s[1],"base64url"));if(typeof i?.exp!="number")return"malformed_signature";if(n>i.exp+cr||typeof i.nbf=="number"&&n<i.nbf-cr)return"stale_timestamp";let c=typeof i.sha256=="string"?oe(i.sha256,"base64"):void 0;return c&&ge(c,en("sha256").update(t.body).digest())?void 0:"signature_mismatch"}}function co(e,t){let n=e.signs.split(/(\{body\}|\{ts\})/),r=e.algo==="hmac-sha1"?"sha1":"sha256";return(s,o)=>{let a=s.headers.get(e.header);if(!a)return"missing_signature";if(e.prefix){if(!a.startsWith(e.prefix))return"malformed_signature";a=a.slice(e.prefix.length)}let i="";if(n.includes("{ts}")){i=s.headers.get(e.timestampHeader)?.trim()??"";let p=We(i);if(p===void 0)return"malformed_signature";if(Ve(p,o))return"stale_timestamp"}let c=oe(a.trim(),e.encoding);return c?ge(c,je(r,t,...n.map(p=>p==="{body}"?s.body:p==="{ts}"?i:p)))?void 0:"signature_mismatch":"malformed_signature"}}var uo=new TextEncoder;function je(e,t,...n){let r=Zs(e,t);for(let s of n)r.update(s);return r.digest()}function yr(e){return en("sha256").update(e).digest("hex")}function wr(e,t){return Buffer.concat([uo.encode(e),t])}function ge(e,t){return e.byteLength===t.byteLength&&Qs(e,t)}var lo={hex:/^(?:[0-9a-fA-F]{2})+$/,base64:/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$/,base64url:/^[A-Za-z0-9_-]+$/};function oe(e,t){return lo[t].test(e)?Buffer.from(e,t):void 0}function We(e){return e!==void 0&&/^[0-9]{1,12}$/.test(e)?Number(e):void 0}function Ve(e,t){return Math.abs(t-e)>Xs}function tn(e){return new TextDecoder().decode(e)}function ur(e){if(e)try{return JSON.parse(tn(e))}catch{return}}function br(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ve(e,t){let n=br(e)?e[t]:void 0;return typeof n=="string"?n:""}import"reflect-metadata";var J=class extends Error{kind;path;constructor(t,n,r,s,o){super(`
6
- Kind: ${t}
7
- Path: ${n.join(" -> ")}
8
- At: ${r}
9
- ${s}
10
-
11
- Potential solutions:
12
- ${o.map(a=>` - ${a}`).join(`
13
- `)}`),this.name="DiError",this.kind=t,this.path=n}},fo=["onModuleInit","onApplicationBootstrap","onModuleDestroy","beforeApplicationShutdown","onApplicationShutdown"],po=new Set([Object,String,Number,Boolean,Symbol,BigInt,Array,Function,Promise,void 0]),mt=class{owner=new Map;defs=new Map;instances=new Map;order=[];controllers=[];eventProviders=[];webhooks=[];cronProviders=[];taskProviders=[];rooms=[];constructor(t){this.collect(t),this.validate()}collect(t){let n=(r,s)=>{if(this.defs.has(r))return;let o=M(r,jt);if(!o)throw new J("unknown import",[...s,r.name],r.name,`${r.name} is not a @Module`,["decorate it with @Module({ \u2026 })","or list the module itself, not one of its classes"]);this.defs.set(r,o);for(let a of o.imports){if(a===r)throw new J("unknown import",[r.name],r.name,`${r.name} imports itself`,["remove it from its own imports"]);n(a,[...s,r.name])}};for(let r of t)n(r,[]);for(let[r,s]of this.defs){for(let o of[...s.controllers,...s.providers]){let a=this.owner.get(o);if(a&&a!==r)throw new J("duplicate ownership",[a.name,o.name,r.name],o.name,`${o.name} is listed by ${a.name} and by ${r.name}; a class has one owner`,["keep it in one module and export it from there"]);this.owner.set(o,r)}for(let o of s.controllers){if(!M(o,_e))throw new J("undeclared provider",[r.name,o.name],o.name,`${o.name} is in ${r.name}'s controllers but is not a @Controller`,["decorate it with @Controller(path)"]);if(M(o,he))throw new J("undeclared provider",[r.name,o.name],o.name,`${o.name} is a controller and a @Cron: a cron is a provider's`,["give the cron a class of its own \u2014 @Cron({ name, schedule }) with run(meta) \u2014 listed in the module's providers"]);if(M(o,fe))throw new J("undeclared provider",[r.name,o.name],o.name,`${o.name} is a controller and a @Task: a task is a provider's`,["give the task a class of its own \u2014 @Task({ name }) with run(payload, meta) \u2014 listed in the module's providers"]);if(M(o,pe)||M(o,Me))throw new J("undeclared provider",[r.name,o.name],o.name,`${o.name} is a controller and a @Room: a room is a provider's`,["give the room a class of its own, listed in the module's providers"]);this.controllers.push({cls:o,module:r})}}}validate(){for(let t of re())if(!this.owner.has(t))throw new J("unowned class",[t.name],t.name,`${t.name} is declared but no module lists it: it would never be built`,["list it in a module's controllers or providers","or delete it"]);for(let[t,n]of this.defs){for(let r of n.exports)if(this.owner.get(r)!==t)throw new J("unknown export",[t.name,r.name],t.name,`${t.name} exports ${r.name}, which it does not own`,[`list ${r.name} in ${t.name}'s providers`,"or export it from the module that owns it"]);for(let r of n.providers){if(M(r,Me)&&!M(r,pe))throw new J("undeclared provider",[t.name,r.name],r.name,`${r.name} has a room's methods (@OnAuthorize, @OnFirst, @OnMessage\u2026) but is no @Room`,["decorate it with @Room(pattern, { events })"]);if(!M(r,Dt)&&!M(r,be)&&!M(r,pe)&&!M(r,he)&&!M(r,fe)){let s=Reflect.getMetadata("design:paramtypes",r);throw r.length>0&&!s?new J("metadata missing",[t.name,r.name],r.name,`${r.name} has constructor parameters but no emitted types`,["decorate it with @Injectable()","enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json"]):new J("undeclared provider",[t.name,r.name],r.name,`${r.name} is in ${t.name}'s providers but is not @Injectable() (nor an @On handler, a @Room, a @Cron or a @Task)`,["decorate it with @Injectable()"])}M(r,pe)&&this.rooms.push(r),M(r,Oe)?this.webhooks.push(r):M(r,be)&&this.eventProviders.push(r),M(r,he)&&this.cronProviders.push(r),M(r,fe)&&this.taskProviders.push(r)}}for(let t of this.owner.keys())for(let n of fo)if(typeof t.prototype[n]=="function")throw new J("nest lifecycle name",[t.name],`${t.name}.${n}`,`${n} is NestJS's; it is never called here`,["use onStart() and onShutdown()"]);for(let t of this.owner.keys())this.resolve(t,[])}get(t){let n=this.instances.get(t);if(!n)throw new Error(`${t.name} is not built by this app`);return n}resolve(t,n){let r=this.instances.get(t);if(r)return r;if(n.includes(t.name))throw new J("dependency cycle",[...n,t.name],t.name,`${[...n,t.name].join(" -> ")} goes round`,["move the shared part into a third class both depend on"]);let s=[...n,t.name],o=t.length,a=Reflect.getMetadata("design:paramtypes",t)??[];if(o>0&&a.length===0)throw new J("metadata missing",s,t.name,`${t.name} takes ${o} constructor parameter(s) but no types were emitted`,["enable experimentalDecorators and emitDecoratorMetadata in tsconfig.json","build with tsc, Bun or SWC (esbuild does not emit them)"]);let i=[];a.slice(0,o).forEach((p,y)=>{if(po.has(p)||typeof p!="function")throw new J("unresolvable dependency",s,`${t.name} constructor parameter ${y}`,`parameter ${y} of ${t.name} is typed as ${p===void 0?"something with no runtime class":p.name} \u2014 an interface, union or primitive has no class to build`,["type it with the class itself"]);i.push(this.resolve(this.reachable(t,p,s),s))});let c=new t(...i);return this.instances.set(t,c),this.order.push(c),c}dependencyOf(t,n,r){let s=t;return this.resolve(this.reachable(s,n,[s.name,r]),[s.name,r])}reachable(t,n,r){let s=this.owner.get(t),o=this.target(n,r),a=this.owner.get(o);if(a!==s){if(!this.defs.get(s).imports.includes(a))throw new J("missing import",[...r,o.name],`${s.name}`,`${t.name} (in ${s.name}) needs ${o.name}, owned by ${a.name}, which ${s.name} does not import`,[`add ${a.name} to ${s.name}'s imports (imports are not transitive)`]);if(!this.defs.get(a).exports.includes(o))throw new J("private dependency",[...r,o.name],`${a.name}`,`${o.name} is ${a.name}'s own: it is not in its exports`,[`add ${o.name} to ${a.name}'s exports`])}return o}target(t,n){if(this.owner.has(t))return t;let r=[...this.owner.keys()].filter(s=>s.prototype instanceof t);if(r.length===1)return r[0];throw r.length>1?new J("duplicate ownership",[...n,t.name],t.name,`${t.name} has ${r.length} owned subclasses (${r.map(s=>s.name).join(", ")}): which one is meant cannot be told`,["ask for the subclass itself"]):new J("unowned class",[...n,t.name],t.name,`${t.name} is needed but no module lists it`,[`list ${t.name} in a module's providers (and export it if another module needs it)`])}async start(){let t=[];for(let n of this.order){let r=n.onStart;if(typeof r=="function")try{await r.call(n)}catch(s){throw await this.shutdown(t),new Error(`[palbase] ${n.constructor.name}.onStart() failed: ${s instanceof Error?s.message:String(s)}`,{cause:s})}t.push(n)}}async shutdown(t=this.order){for(let n of[...t].reverse()){let r=n.onShutdown;if(typeof r=="function")try{await r.call(n)}catch(s){console.error(`[palbase] ${n.constructor.name}.onShutdown() failed`,s)}}}};import{HTTP_ERROR_BRAND as mo,HttpError as Ze}from"palgres";import{z as ye}from"zod";import{BadRequest as dd,Conflict as cd,DeadlockDetected as ud,HttpError as ld,NotFound as fd,SerializationFailure as pd,TooManyRequests as md,UniqueViolation as hd}from"palgres";function Qe(e){if(typeof e!="object"||e===null||e[mo]!==!0)return!1;let t=e;return Number.isInteger(t.status)&&t.status>=400&&t.status<=599&&typeof t.error=="string"&&typeof t.errorDescription=="string"}var kr=class extends Ze{constructor(t,n,r,s){super(t,n,r,s),this.name=new.target.name}},vr=class extends Ze{constructor(t="Unauthorized",n="unauthorized",r){super(401,n,t,r),this.name="Unauthorized"}},$r=class extends Ze{constructor(t="Forbidden",n="forbidden",r){super(403,n,t,r),this.name="Forbidden"}};function Er(e,t){let n={error:e.error,error_description:e.errorDescription,status:e.status,request_id:t};return e.data!==void 0&&(n.data=e.data),n}var ho=Symbol.for("palbase.backend.errorRegistry"),go={bad_request:ye.object({fields:ye.array(ye.object({field:ye.string(),message:ye.string()})),more:ye.number().int().optional()}),too_many_requests:ye.object({retryAfter:ye.number().int()})},yo=new Set(["auth_unavailable","check_failed","client_closed_request","database_unavailable","duplicate_upload","email_not_verified","handler_failed","idempotency_key_in_use","idempotency_key_reused","in_progress","internal_error","invalid_idempotency_key","invalid_signature","invalid_token","job_failed","job_not_found","method_not_allowed","missing_signature","payload_too_large","service_unavailable","signature_mismatch","temporarily_unavailable","unknown_token","upload_required","webhook_secret_missing"]);function wo(){let e=new Map;for(let[t,n,r]of[["bad_request",400,"BadRequest"],["unauthorized",401,"Unauthorized"],["forbidden",403,"Forbidden"],["not_found",404,"NotFound"],["conflict",409,"Conflict"],["unique_violation",409,"UniqueViolation"],["too_many_requests",429,"TooManyRequests"]]){let s=go[t];e.set(t,{code:t,status:n,className:r,builtin:!0,...s?{data:s}:{}})}return e}function bo(){let e=globalThis;return e[ho]??=wo()}function od(e,t,n){if(typeof e!="string"||!/^[a-z][a-z0-9_]*$/.test(e))throw new TypeError(`defineError(code, status): code is a lowercase wire code like room_locked, not ${JSON.stringify(e)}`);if(!Number.isInteger(t)||t<400||t>599)throw new TypeError(`defineError("${e}", status): status is a 4xx or 5xx integer, not ${String(t)} \u2014 an error is never a success`);if(n!==void 0&&typeof n?.["~standard"]?.validate!="function")throw new TypeError(`defineError("${e}", ${t}, data): data is a Standard Schema (a zod, valibot or arktype schema)`);if(yo.has(e))throw new TypeError(`defineError("${e}", ${t}): "${e}" is the framework's own answer \u2014 a client would read the framework's refusal as the project's error; give the project's its own code`);let r=bo(),s=r.get(e);if(s&&(s.builtin||s.status!==t||s.data===void 0!=(n===void 0)||n!==void 0&&s.data!==n&&Tr(s.data)!==Tr(n)))throw new TypeError(`defineError("${e}", ${t}): "${e}" is already ${s.builtin?`the built-in ${s.className}`:`defined with status ${s.status}${s.status===t?" and other data":""}`} \u2014 a code is one error of the project's`);let o=e.split("_").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(""),a=e.replace(/_/g," "),i=a.charAt(0).toUpperCase()+a.slice(1),y=n?(k=>class extends Ze{static code=e;static status=t;constructor(R,U){let I=ko(e,k,R);super(t,e,U??(typeof I=="string"?I:i),I),this.name=o}})(n):class extends Ze{static code=e;static status=t;constructor(k){super(t,e,k??i),this.name=o}};return Object.defineProperty(y,"name",{value:o}),r.set(e,{code:e,status:t,className:o,builtin:!1,...n?{data:n}:{}}),y}function ko(e,t,n){let r=t["~standard"].validate(n);if(r instanceof Promise)throw new TypeError(`${e}: its data schema validates asynchronously; an error is made at once`);if(r.issues)throw new TypeError(`${e}: its data does not fit its schema \u2014 ${r.issues.map(s=>s.message).join("; ")}`);return r.value}function Tr(e){let t=e?.["~standard"]?.jsonSchema?.input;try{return JSON.stringify(t?t({target:"draft-2020-12"}):null)}catch{return"unconvertible"}}var Rr="/_palbase/ai/tools",_r="/_palbase/ai/agents",Sr="/_palbase/ai/repos";var vo=Symbol.for("palbase.ai.tool_error");function Or(e){return e instanceof Error&&e[vo]===!0}var $o=Symbol.for("palbase.ai.declared");function xr(){let e=globalThis[$o];if(!e)return{tools:new Map,agents:new Map,repos:new Map};if(e.twice.size>0){let t=[...e.twice].map(n=>n.replace(":"," "));throw new TypeError(`[palbase] ${t.join(", ")}: declared twice with different values \u2014 an ai.tool's and an ai.agent's name is its own; make each once, at a module's top level`)}return{tools:new Map(e.tools),agents:new Map(e.agents),repos:new Map(e.repos??[])}}var nn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function rn(e){if(!nn(e))return"context is {chat_id, agent, user, metadata}";if(typeof e.chat_id!="string")return"context.chat_id is the chat (empty for a one-shot answer's call)";if(typeof e.agent!="string")return"context.agent is the agent's name";let t=null;if(e.user!==null&&e.user!==void 0){if(!nn(e.user)||typeof e.user.id!="string"||e.user.id===""||e.user.name!==void 0&&typeof e.user.name!="string")return"context.user is {id, name}, or null";t={id:e.user.id,name:typeof e.user.name=="string"?e.user.name:""}}let n={};if(e.metadata!==void 0&&e.metadata!==null){if(!nn(e.metadata))return"context.metadata is an object of strings";for(let[r,s]of Object.entries(e.metadata)){if(typeof s!="string")return"context.metadata is an object of strings";Object.defineProperty(n,r,{value:s,enumerable:!0,writable:!0,configurable:!0})}}return{chatId:e.chat_id,agent:e.agent,user:t,metadata:n}}var To=1e4,Eo=10*6e4,ht=class{constructor(t=Date.now){this.now=t}now;seen=new Map;take(t){let n=this.now();for(let[r,s]of this.seen){if(n-s<=Eo&&this.seen.size<=To)break;this.seen.delete(r)}return this.seen.has(t)?!1:(this.seen.set(t,n),!0)}},Ro=1e3,_o=256*1024,gt=class{answers=new Map;running=new Set;answered(t){return this.answers.get(t)}isRunning(t){return this.running.has(t)}start(t){this.running.add(t)}end(t,n){this.running.delete(t),!(n===void 0||n.answer.length>_o)&&(this.answers.set(t,n),this.answers.size>Ro&&this.answers.delete(this.answers.keys().next().value))}};import{connectionFailure as ns,isEngineRaised as bn,markData as ae}from"palgres";import{createHash as rs}from"node:crypto";import{createHash as So,randomInt as Oo}from"node:crypto";import{ago as sn,isRetryable as xo,now as Ar}from"palgres";import{defineSchema as Ao,defineTable as Po,index as Co,integer as Mo,jsonb as Do,raw as jo,text as on,timestamp as Pr}from"palgres/dsl";var Ur=new Set(["POST","PUT","PATCH","DELETE"]),Cr=255,Mr=35,Dr=24,No=65536,jr=1e3,Uo=64,dn={description:"Makes the write safe to send again (at most 255 characters). A retry with the same key and the same request gets the first answer back, marked `Idempotent-Replayed: true`, and changes nothing; the same key with a different request is refused with 422, and while the first request still runs a retry gets 409 with Retry-After. Answers are kept for 24 hours.",in:"header",name:"Idempotency-Key",required:!1,schema:{maxLength:255,type:"string"}},Lo=Po("idempotency_keys",{columns:{key:on().primaryKey(),fingerprint:on(),started_at:Pr().defaultNow(),completed_at:Pr().nullable(),status_code:Mo().nullable(),response_headers:Do().nullable(),response_body:on().nullable()},indexes:e=>[Co("idempotency_keys_started").on(e.col("started_at"))]}),Td=Ao("palbase",{tables:[Lo],raw:[jo("idempotency_answer",`CREATE OR REPLACE FUNCTION palbase.idempotency_answer(record_key text, claimed_at timestamptz, answer_status integer, answer_headers jsonb, answer_body text) RETURNS boolean
14
- LANGUAGE sql VOLATILE SECURITY DEFINER SET search_path = pg_catalog, pg_temp
15
- AS $answer$
16
- UPDATE palbase.idempotency_keys
17
- SET completed_at = now(), status_code = answer_status, response_headers = answer_headers, response_body = answer_body
18
- WHERE key = record_key AND started_at = claimed_at AND completed_at IS NULL
19
- RETURNING true
20
- $answer$`,{drop:"DROP FUNCTION IF EXISTS palbase.idempotency_answer(text, timestamptz, integer, jsonb, text)"})]}),Io={status:422,code:"idempotency_key_reused",message:"This Idempotency-Key was sent with a different request"},zo={status:409,code:"idempotency_key_in_use",message:"A request with this Idempotency-Key is still running; retry after Retry-After seconds",retryAfter:1},qo={status:409,code:"idempotency_key_in_use",message:"This request's Idempotency-Key was taken over by a retry; what it did is not kept",retryAfter:1},Ho={status:503,code:"temporarily_unavailable",message:"The request could not be recorded; retry after Retry-After seconds",retryAfter:2},wt=class extends Error{};function Ge(e){return Ur.has(e.method)&&e.meta.upload===void 0}function Lr(e,t){if(!Ur.has(e))return;let n=t.get("idempotency-key");return n===null||n===""?void 0:n}function Bo(e,t){return Ir([e.role,e.uid,t]).digest("hex")}function Fo(e){return Ir([e.method,e.uri,e.caller.role,e.caller.uid]).update(e.body).digest("hex")}function Ir(e){let t=So("sha256");for(let n of e)t.update(n).update("\0");return t}function Ko(e,t){return e.fingerprint!==t?"reused":e.completed_at!==null?"replay":"running"}function an(e){return e<500&&e!==429&&e!==499}function Jo(e,t){return t&&an(e)}function zr(e){let t=e["~standard"].jsonSchema?.input,n;try{n=t?.({target:"draft-2020-12"})}catch{return!1}let r=n?.properties;return typeof r=="object"&&r!==null&&Object.keys(r).some(s=>s.toLowerCase()==="idempotency-key")}var Wo={role:"service",claims:{}},bt=class{constructor(t){this.db=t}db;async serve(t,n,r){if(t.key.length>Cr)return r.refusal({status:400,code:"invalid_idempotency_key",message:`Idempotency-Key is at most ${Cr} characters`});let s;try{s=await this.begin(Bo(t.caller,t.key),Fo(t))}catch(i){return E.warn("[palbase] an Idempotency-Key could not be recorded; the write is not run",{error:i}),r.refusal(Ho)}if("kept"in s)return Vo(s.kept,r.requestId);if("refused"in s)return r.refusal(s.refused==="reused"?Io:zo);let o=s.claim,a;try{a=await n(i=>this.record(o,i))}catch(i){if(i instanceof wt)return r.refusal(qo);let c=r.failure(i);return Jo(c.status,r.ran())&&!xo(i)?this.keep(o,c):(await this.release(o),c)}return an(a.status)||await this.release(o),a}async sweep(){return this.asService(t=>t.deleteMany({where:{started_at:{lt:sn({hours:Dr})}}}))}async begin(t,n){return Oo(Uo)===0&&await this.sweep().catch(r=>E.warn("[palbase] the expired Idempotency-Keys could not be taken away; the next sweep tries again",{error:r})),this.asService(async r=>{for(let s=0;s<3;s++){let[o]=await r.insertMany([{key:t,fingerprint:n}],{onConflict:["key"],action:"ignore"});if(o)return{claim:{key:t,started:o.started_at}};if(await r.deleteMany({where:{key:t,started_at:{lt:sn({hours:Dr})}}})>0)continue;let a=await r.findUnique({where:{key:t}});if(a===null)continue;let i=Ko(a,n);if(i==="reused")return{refused:"reused"};if(i==="replay")return{kept:{status:a.status_code,headers:a.response_headers??[],body:a.response_body}};let[c]=await r.updateMany({where:{key:t,completed_at:null,started_at:{lt:sn({seconds:Mr})}},set:{started_at:Ar()}});return c?{claim:{key:t,started:c.started_at}}:{refused:"in_use"}}return{refused:"in_use"}})}async record(t,n){if(!an(n.status))return n;let{response:r,kept:s}=await Nr(n),o=ee.getStore()?.database;if(!o)throw new Error("[palbase] an Idempotency-Key is recorded inside the request, in its transaction");let[a]=await o.$query("SELECT palbase.idempotency_answer($1, $2, $3, $4, $5) AS answered",[t.key,t.started,s.status,JSON.stringify(s.headers),s.body]);if(a?.answered!==!0)throw new wt;return r}async keep(t,n){let{response:r,kept:s}=await Nr(n);try{await this.asService(o=>o.updateMany({where:{key:t.key,started_at:t.started,completed_at:null},set:{completed_at:Ar(),status_code:s.status,response_headers:s.headers,response_body:s.body}}))}catch(o){E.warn("[palbase] a refusal could not be kept against its Idempotency-Key; a retry runs it again once the key is stale",{error:o})}return r}async release(t){if(await this.releaseOnce(t))return;let n=Date.now()+Mr*1e3,r=()=>{Date.now()+jr>=n||setTimeout(()=>{this.releaseOnce(t).then(s=>s||r())},jr).unref()};r()}async releaseOnce(t){try{return await this.asService(n=>n.deleteMany({where:{key:t.key,started_at:t.started,completed_at:null}})),!0}catch{return!1}}async asService(t){let n=this.db.request(Wo),r;try{r=await t(n.database.palbase.idempotency_keys)}catch(s){throw await n.rollback(s).catch(()=>{}),s}try{await n.commit()}catch(s){throw await n.rollback(s).catch(()=>{}),s}return r}};function Vo(e,t){let n=new Headers(e.headers);return n.set("x-request-id",t),n.set("idempotent-replayed","true"),new Response(e.body===null?null:Buffer.from(e.body,"base64"),{status:e.status,headers:n})}var yt=Symbol("waits");function Zo(e){return new Promise((t,n)=>{let r=setImmediate(()=>t(yt));e.then(s=>{clearImmediate(r),t(s)},s=>{clearImmediate(r),n(s)})})}async function Nr(e){let t=[];e.headers.forEach((i,c)=>{c!=="x-request-id"&&t.push([c,i])});let n=i=>new Response(i,{status:e.status,statusText:e.statusText,headers:e.headers});if(e.body===null)return{response:n(null),kept:{status:e.status,headers:t,body:null}};let r=e.body.getReader(),s=[],o=0;for(;;){let i=r.read(),c=await Zo(i);if(c!==yt&&c.done)break;if(c!==yt&&(s.push(c.value),o+=c.value.byteLength,o<=No))continue;let p=c===yt?i:void 0,y=new ReadableStream({start(k){for(let R of s)k.enqueue(R)},async pull(k){let R=await(p??r.read());p=void 0,R.done?k.close():k.enqueue(R.value)},cancel:k=>r.cancel(k)});return{response:n(y),kept:{status:e.status,headers:t.filter(([k])=>k!=="content-length"&&k!=="content-encoding"),body:null}}}let a=Buffer.concat(s);return{response:n(a),kept:{status:e.status,headers:t,body:a.byteLength===0?null:a.toString("base64")}}}import{createHash as Qo}from"node:crypto";var cn="/webhooks/palbase",Jr="PalbaseErrorEnvelope",qr="PalbaseBearer",Go={$ref:`#/components/schemas/${Jr}`},Yo={type:"object",description:"Every refusal: the framework's, a handler's HttpError, the database's.",properties:{error:{type:"string",description:"A stable code, like bad_request"},error_description:{type:"string",description:"What went wrong, for a person"},status:{type:"integer",description:"The HTTP status"},request_id:{type:"string",description:"The request's id, as the app's log has it"},data:{description:"Details, when the refusal has them: a validation's fields, a token's reason, a limit's retryAfter"}},required:["error","error_description","status","request_id"]},Hr={stripe:"Stripe",github:"GitHub",twilio:"Twilio",sendgrid:"SendGrid",slack:"Slack",discord:"Discord",livekit:"LiveKit"},Ne={"Retry-After":{description:"Seconds to wait before trying again",schema:{type:"integer",minimum:1}}};function Wr(e,t,n){let r={[Jr]:Yo},s={},o=[],a=[],i=new Set,c=new Map;for(let h of e){let v=a.find(V=>ta(V,h));if(v){o.push({route:h.id,handler:Br(h),answeredBy:v.id});continue}a.push(h);let b=h.segments.map(V=>typeof V=="string"?V:"{}").join("/");c.has(b)||c.set(b,ra(h.segments.flatMap(V=>typeof V=="string"?[]:[V.param])));let O=c.get(b),z=0,F=`/${h.segments.map(V=>typeof V=="string"?V:`{${O[z++]}}`).join("/")}`,D=t(h),j=kt(na(h),i),q=h.method!=="GET"&&h.method!=="HEAD",H=V=>{let Te=h.params.filter(me=>me.kind===V&&me.schema).map((me,He)=>Tt(me.schema,`${j}.${V}${He===0?"":`.${He+1}`}`,r));return Te.length===0?void 0:Te.length===1?Te[0]:{allOf:Te}},K=O.map(V=>({name:V,in:"path",required:!0,schema:{type:"string"}})),de=H("query");de&&K.push(...Kr(de,"query")??[{name:"query",in:"query",style:"form",explode:!0,schema:de}]);let ne=H("headers");ne&&K.push(...Kr(ne,"header")??[]);let st=n.idempotency===!0&&Ge(h);st&&K.push({...dn,schema:{...dn.schema}});let ze=q?H("body"):void 0,W={operationId:j};h.controller.name!==""&&(W.tags=[h.controller.name]),K.length>0&&(W.parameters=K),ze&&(W.requestBody={required:!da(ze),content:{"application/json":{schema:ze}}});let we=h.params.some(V=>V.schema!==void 0),$e=n.routes?.(h),qe=ua(j,$e?.throws??[],n.errors);W.responses={...ca($e,j,r),...pa(D,{validates:we,hasPathParams:O.length>0,readsBody:q,keyed:st}),...fa(qe,j,r)},qe.length>0&&(W["x-palbase-errors"]=la(j,qe)),D.auth.required&&(W.security=[{[qr]:[]}]),W["x-palbase-handler"]=Br(h);let xt=h.params.some(V=>V.kind==="optionalUser")||n.databaseSeesCaller;W["x-palbase-auth"]=D.auth.required?"required":xt?"optional":"public",W["x-palbase-verified-email"]=D.auth.verifiedEmail,W["x-palbase-rate-limit"]=D.limit===!1?!1:{max:D.limit.max,window:D.limit.window},h.meta.upload&&(W["x-palbase-upload"]={bucket:h.meta.upload.bucket,pathTemplate:h.meta.upload.pathTemplate}),(s[F]??={})[h.method.toLowerCase()]=W}for(let h of n.webhooks??[]){let v={operationId:kt(`webhooks.${h.name}`,i)};h.cls!==""&&(v.tags=[h.cls]),v.description=h.provider?`${Hr[h.provider]??h.provider}'s deliveries: verified with ${Hr[h.provider]??h.provider}'s signature scheme under the secret in ${h.secretEnv}, then handed to the @On of their event type.`:`Deliveries signed in the ${h.signatureHeader} header: verified under the secret in ${h.secretEnv}, then handed to the @On of their event type.`,v.responses={200:{description:"Taken: { ok: true, handled } \u2014 handled is false when no @On takes the event's type, and duplicate is true for a delivery already run; or the handler's answer: a Response as it is, text as text, anything else as JSON",content:{"application/json":{},[h.provider==="twilio"?"text/xml":"text/plain"]:{}}},401:G("invalid_signature: the delivery is not signed with the secret \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:G("in_progress: the same delivery is being handled; the sender delivers it again",Ne),413:G("payload_too_large: the body is over what this sender sends"),500:G("handler_failed: the handler failed \u2014 the sender delivers it again; the app's log has it under the request id"),503:G("service_unavailable, auth_unavailable or database_unavailable: what the handler needs of the platform did not answer \u2014 the sender delivers it again after Retry-After",Ne)},v["x-palbase-webhook"]=h.provider?{provider:h.provider,secretEnv:h.secretEnv,events:h.events}:{signatureHeader:h.signatureHeader,secretEnv:h.secretEnv,events:h.events},s[`/webhooks/${h.name}`]={post:v}}let p=[...new Set(n.platformEvents??[])].sort();if(p.length>0){let h={operationId:kt("webhooks.palbase",i)};h.description="The project's events, delivered by the platform to the app's machine: verified under the secret in PALBASE_WEBHOOK_SECRET, then handed to the @On of their type \u2014 user.deleted first to forgetting the rows the app keeps of that user.",h.responses={204:{description:"Taken: handled, or a delivery already run"},401:G("invalid_signature: the delivery is not the platform's \u2014 error_description says which of missing_signature, malformed_signature, stale_timestamp or signature_mismatch"),409:G("in_progress: the same event is being handled; the platform delivers it again",Ne),500:G("handler_failed: a handler failed \u2014 the platform delivers it again; the app's log has it under the request id"),503:G("webhook_secret_missing: the app was started without PALBASE_WEBHOOK_SECRET and takes no delivery")};let v=[...new Set(n.platformEventBuckets??[])].sort();h["x-palbase-webhook"]={provider:"palbase",secretEnv:"PALBASE_WEBHOOK_SECRET",events:p,...v.length>0?{buckets:v}:{}},s[cn]={post:h}}let y=Xo(n.rooms??[],r),k=Object.keys(y).length>0,R=n.channels??[],U=R.length>0,I={schemas:r,securitySchemes:{[qr]:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"A user's access token, from the project's auth"}}},L={openapi:"3.2.0",info:{title:"Palbase backend",version:Qo("sha256").update(JSON.stringify({paths:s,components:I,unreachable:o,...k?{rooms:y}:{},...U?{channels:R}:{}})).digest("hex").slice(0,12),description:"The routes this app serves, as its decorators declare them, and \u2014 when its source was read as the contract was written \u2014 what each answers and the errors it throws (x-palbase-errors). Every refusal is the PalbaseErrorEnvelope; a declared error's carries its code and its data."},paths:s,components:I};return o.length>0&&(L["x-palbase-unreachable"]=o),k&&(L["x-palbase-room"]=y),U&&(L["x-palbase-channels"]=R.map(h=>({...h}))),L}function Xo(e,t){let n=[];for(let r of e){let s=r.pattern.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_|_$/g,""),o=(c,p,y,k)=>{let R=$t(`Room_${s}_${p}`),U={},I=Tt(y,R,U,k);I.$ref===void 0&&(U[R]=I),ea(r.pattern,c,p,U[R]);for(let[L,h]of Object.entries(U)){if(Object.hasOwn(t,L)&&JSON.stringify(t[L])!==JSON.stringify(h))throw new Error(`@Room("${r.pattern}") ${c} "${p}": its schema is the component ${L}, which another room's event or message names with another schema \u2014 rename one of them`);t[L]=h}return{$ref:`#/components/schemas/${R}`}},a=Object.fromEntries(Object.entries(r.events).map(([c,p])=>[c,o("event",c,p,"answered")])),i=Object.fromEntries(Object.entries(r.messages).map(([c,p])=>[c,o("message",c,p.schema,"sent")]));n.push([r.pattern,{events:a,messages:i,graceMs:r.graceMs}])}return Object.fromEntries(n)}function ea(e,t,n,r){if(!(!te(r)||!te(r.properties))){for(let[s,o]of Object.entries(r.properties))if(o===!0||te(o)&&Object.keys(o).length===0)throw new Error(t==="event"?`@Room("${e}") event "${n}" has an untyped field "${s}". An untyped payload makes every generated client opaque \u2014 declare its shape.`:`@Room("${e}") message "${n}" has an untyped field "${s}". Inbound payloads reach the server \u2014 declare the shape so it can be validated.`)}}function ta(e,t){return e.method===t.method&&e.segments.length===t.segments.length&&e.segments.every((n,r)=>typeof n!="string"||n===t.segments[r])}function Br(e){return`${e.controller.name}.${e.fn}`}function na(e){let t=e.controller.name;if(t.endsWith("Controller")&&(t=t.slice(0,-10)),t!=="")return`${t[0].toLowerCase()}${t.slice(1)}.${e.fn}`;let n=r=>r.charAt(0).toUpperCase()+r.slice(1);return e.method.toLowerCase()+e.segments.map(r=>typeof r=="string"?n(r):`By${n(r.param)}`).join("")}function kt(e,t){let n=e;for(let r=2;t.has(n);r++)n=`${e}_${r}`;return t.add(n),n}function ra(e){let t=new Set;return e.map(n=>kt(n,t))}function Tt(e,t,n,r="sent"){let s=e["~standard"],o=s.jsonSchema?.input;if(typeof o!="function")return{};let a;try{a=o({target:"draft-2020-12",libraryOptions:{unrepresentable:"any",...s.vendor==="zod"?{override:sa}:{}}})}catch{return{}}let i=$t(t);for(;Object.keys(n).some(c=>c===i||c.startsWith(`${i}.`));)i=`${i}_`;return oa(a,i,n,r)}function sa(e){e.zodSchema?._zod?.def?.type==="date"&&(e.jsonSchema.type="string")}function oa(e,t,n,r){let s=typeof e.$defs=="object"&&e.$defs!==null?e.$defs:{},o=!1,a=p=>p==="#"?(o=!0,`#/components/schemas/${t}`):p.startsWith("#/$defs/")?`#/components/schemas/${t}.${$t(ia(p.slice(8)))}`:p,i="all";if(r==="sent"){let p=new Set;for(let y of[e,...Object.values(s)])vt(y,p);i=p}for(let[p,y]of Object.entries(s))n[`${t}.${$t(p)}`]=Xe(Ye(y,a,i));let c=Xe(Ye(e,a,i));return o?(n[t]=c,{$ref:`#/components/schemas/${t}`}):c}var aa=new Set(["type","enum","required","dependentRequired","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","pattern","format","contentEncoding","contentMediaType","minItems","maxItems","uniqueItems","minContains","maxContains","minProperties","maxProperties","readOnly","writeOnly","deprecated"]),un=new Set(["items","additionalProperties","propertyNames","contains","not","if","then","else","unevaluatedProperties","unevaluatedItems"]),ln=new Set(["anyOf","oneOf","allOf","prefixItems"]),fn=new Set(["properties","patternProperties","dependentSchemas"]),te=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ye(e,t,n){if(!te(e))return typeof e=="boolean"?e:{};let r={};for(let[s,o]of Object.entries(e))s==="$ref"&&typeof o=="string"?r.$ref=t(o):s==="const"?(n==="all"||n.has(e))&&(r.const=o):aa.has(s)?r[s]=o:un.has(s)?r[s]=Ye(o,t,n):ln.has(s)&&Array.isArray(o)?r[s]=o.map(a=>Ye(a,t,n)):fn.has(s)&&te(o)&&(r[s]=Object.fromEntries(Object.entries(o).map(([a,i])=>[a,Ye(i,t,n)])));return r}var Fr=Number.MAX_SAFE_INTEGER;function Xe(e){if(!te(e))return e;let t={};for(let[r,s]of Object.entries(e))un.has(r)?t[r]=Xe(s):ln.has(r)&&Array.isArray(s)?t[r]=s.map(Xe):fn.has(r)&&te(s)?t[r]=Object.fromEntries(Object.entries(s).map(([o,a])=>[o,Xe(a)])):t[r]=s;if("const"in t){let{const:r,...s}=t;t={...s,enum:[r]}}if(t.type==="integer"&&(t.minimum===-Fr&&delete t.minimum,t.maximum===Fr&&delete t.maximum),typeof t.minItems=="number"&&t.minItems===t.maxItems&&(delete t.minItems,delete t.maxItems),typeof t.format=="string"&&delete t.pattern,te(t.propertyNames)&&Object.keys(t.propertyNames).length===1&&t.propertyNames.type==="string"&&delete t.propertyNames,Array.isArray(t.type)&&t.type.filter(r=>r!=="null").length>1&&Object.keys(t).length===1)return{anyOf:t.type.map(r=>({type:r}))};let n=t.anyOf;if(Array.isArray(n)&&n.length===2&&Object.keys(t).length===1){let r=n.findIndex(o=>te(o)&&Object.keys(o).length===1&&o.type==="null"),s=n[1-r];if(r!==-1&&te(s)&&typeof s.type=="string")return{...s,type:[s.type,"null"]}}return t}function vt(e,t){if(te(e)){for(let n of["anyOf","oneOf"]){let r=e[n];if(!Array.isArray(r)||r.length<2||!r.every(te))continue;if(r.every(o=>"const"in o||Array.isArray(o.enum)))for(let o of r)t.add(o);let s=r.map(o=>te(o.properties)?o.properties:{});for(let o of Object.keys(s[0]))if(s.every(a=>te(a[o])&&"const"in a[o]))for(let a of s)t.add(a[o])}for(let[n,r]of Object.entries(e))if(un.has(n))vt(r,t);else if(ln.has(n)&&Array.isArray(r))for(let s of r)vt(s,t);else if(fn.has(n)&&te(r))for(let s of Object.values(r))vt(s,t)}}function ia(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}function $t(e){return e.replace(/^__/,"").replace(/[^A-Za-z0-9._-]/g,"_")}function Kr(e,t){if(e.type!=="object"||typeof e.properties!="object"||e.properties===null)return;let n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([r,s])=>({name:r,in:t,required:n.has(r),schema:s}))}function da(e){return e.type==="object"&&!(Array.isArray(e.required)&&e.required.length>0)}function G(e,t){return{description:e,...t?{headers:t}:{},content:{"application/json":{schema:Go}}}}function ca(e,t,n){if(!e)return{200:{description:"The handler's answer, as JSON",content:{"application/json":{}}},204:{description:"The handler answered nothing (undefined or null)"}};if(e.returns.kind==="void")return{204:{description:"No Content"}};if(e.returns.kind==="raw")return{default:{description:"The handler's own Response, as it built it"}};let r=Tt(e.returns.schema,`${t}.response`,n,"answered");return{200:{description:"Success",content:{"application/json":{schema:e.returns.array?{type:"array",items:r}:r}}}}}function ua(e,t,n){let r=new Set,s=[];for(let o of t){if(r.has(o.code))continue;r.add(o.code);let a=n?.get(o.code);if(a&&o.status!==a.status)throw new Error(`${e} throws "${o.code}" with status ${o.status}, but the code is defined with status ${a.status} \u2014 a client matches an error by its code, so one code carries one status`);s.push({...o,...a?.data?{data:a.data}:{}})}return s}function la(e,t){let n=Object.create(null);for(let r of t){let s=r.name.charAt(0).toLowerCase()+r.name.slice(1),o=Object.hasOwn(n,s)?n[s]:void 0;if(o)throw new Error(`${e} throws "${o.code}" and "${r.code}" under one name, "${r.name}" \u2014 every client names an error case after it; give one of them its own defineError`);n[s]={status:r.status,code:r.code,hasData:r.data!==void 0,description:""}}return n}function fa(e,t,n){let r=new Map;for(let o of e)r.set(o.status,[...r.get(o.status)??[],o]);let s={};for(let o of[...r.keys()].sort((a,i)=>a-i)){let a=r.get(o),i=a.map(c=>{let p={error:{type:"string",const:c.code},error_description:{type:"string"},status:{type:"integer"},request_id:{type:"string"}},y=["error","error_description","status","request_id"];return c.data&&(p.data=Tt(c.data,`${t}.${c.code}.data`,n,"answered"),y.push("data")),{type:"object",properties:p,required:y}});s[String(o)]={description:a.map(c=>c.code).join(" | "),content:{"application/json":{schema:i.length===1?i[0]:{oneOf:i}}}}}return s}function pa(e,t){let n={},r=[t.validates&&"a parameter failed its schema (data.fields names each field, data.more how many more)",t.hasPathParams&&"the path is not valid percent-encoding"].filter(Boolean),s=[r.length>0&&`bad_request: ${r.join("; or ")}`,t.keyed&&"invalid_idempotency_key: the Idempotency-Key is over 255 characters"].filter(Boolean);return s.length>0&&(n[400]=G(s.join("; "))),e.auth.required&&(n[401]=G("unauthorized: no access token was sent; invalid_token: the token is not valid (data.reason says why), or the Authorization header is not a Bearer token")),e.auth.verifiedEmail&&(n[403]=G("email_not_verified: the user's email address is not verified")),t.keyed&&(n[409]=G("idempotency_key_in_use: a request with this Idempotency-Key is still running",Ne)),t.readsBody&&(n[413]=G("payload_too_large: the body is over the app's body limit")),t.keyed&&(n[422]=G("idempotency_key_reused: the Idempotency-Key was sent with a different request")),e.limit!==!1&&(n[429]=G("too_many_requests: over the route's limit for this caller (x-palbase-rate-limit; data.retryAfter)",Ne)),n[500]=G("internal_error: the handler failed; the app's log has it under the request id"),n[503]=G(`${e.auth.required?"auth_unavailable: sign-ins cannot be checked right now; ":""}service_unavailable: a platform service the request needs did not answer${t.keyed?"; temporarily_unavailable: the Idempotency-Key could not be recorded":""}`,Ne),n}var Et=class{windows=new Map;now;maxKeys;constructor(t=Date.now,n=1e5){this.now=t,this.maxKeys=n}take(t,n){let r=this.now(),s=this.windows.get(t);if((!s||r>=s.resetAt)&&(s={count:0,resetAt:r+n.window*1e3}),this.windows.delete(t),this.windows.set(t,s),this.windows.size>this.maxKeys&&this.windows.delete(this.windows.keys().next().value),s.count++,s.count>n.max)return Math.max(1,Math.ceil((s.resetAt-r)/1e3))}reserve(t,n){let r=this.take(t,n);return r!==void 0?{wait:r}:{window:this.windows.get(t).resetAt}}give(t,n){let r=this.windows.get(t);r&&r.resetAt===n&&r.count>0&&r.count--}};function Rt(e,t){let r=e.get("x-forwarded-for")?.split(",").map(s=>s.trim()).filter(Boolean).at(-1);return ma(r??t??"unknown")}function ma(e){let t=e.replace(/^\[|\]$/g,"").replace(/%.*$/,"");if(!t.includes(":"))return e;let n=/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i.exec(t);if(n)return n[1];let[r,s=""]=t.split("::"),o=r?r.split(":"):[],a=s?s.split(":"):[],i=t.includes("::")?[...o,...Array(8-o.length-a.length).fill("0"),...a]:o;return i.length!==8||i.some(c=>!/^[0-9a-f]{1,4}$/i.test(c))?t:`${i.slice(0,4).map(c=>parseInt(c,16).toString(16)).join(":")}::/64`}function Vr(e){let t=[];for(let n of e){let r=M(n,_e),s=M(n,Se)??[];if(s.length===0)throw new TypeError(`@Controller ${n.name} has no routes: a controller with nothing to serve is a mistake`);let o=M(n,Mt)??new Map;for(let a of s){let i=`${r.basePath}${a.subpath}`||"/",c=i.split("/").filter(Boolean).map(y=>{let k=/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(y)??/^:([A-Za-z_][A-Za-z0-9_]*)$/.exec(y);return k?{param:k[1]}:y});if(typeof c[0]=="string"&&xe.has(c[0]))throw new TypeError(`${n.name}.${a.fn}: ${a.method} ${i} \u2014 /${c[0]} is the platform's; a route is served elsewhere`);let p=[...o.get(a.fn)??[]].sort((y,k)=>y.index-k.index);for(let y of p)if(y.kind==="param"&&!c.some(k=>typeof k!="string"&&k.param===y.name))throw new TypeError(`${n.name}.${a.fn}: @Param("${y.name}") names no {${y.name}} in ${a.method} ${i}`);t.push({id:`${a.method} ${i}`,method:a.method,segments:c,controller:n,fn:a.fn,params:p,meta:a,controllerAuth:r.options.auth})}}return ar(t),t}function pn(e,t,n){let r=n.split("/").filter(Boolean);for(let s of e){if(s.method!==t||s.segments.length!==r.length)continue;let o={},a=!0;for(let i=0;i<r.length&&a;i++){let c=s.segments[i];if(typeof c=="string")a=c===r[i];else try{o[c.param]=decodeURIComponent(r[i])}catch{return{malformed:!0}}}if(a)return{route:s,params:o}}return null}function gn(e,t){return e==="service"?{role:"service",claims:{...t??{}}}:t?{role:"authenticated",claims:{...t}}:{role:"anon",claims:{}}}async function Ue(e,t,n,r,s){return _t(e,e?gn(e.requests,t):void 0,n,r,s)}var mn={role:"service",claims:{}};async function _t(e,t,n,r,s){if(!e||!t)return s();let o=p=>E.warn(`[palbase] ${r}: a transaction of the request could not be given back \u2014 it wrote, locked, is an $atomic or an $attempt, ran SQL of its own, or the database keeps one snapshot for it \u2014 and sat ${p} ms with no statement running: the handler waited on something else, and a database connection waited with it. Make the outside call before the first write, or outside $atomic.`,{waitedMs:p}),a=e.app.request(t,{signal:n,heldIdle:o}),i=ee.getStore();i&&(i.database=a.database);let c;try{c=await s()}catch(p){throw await a.rollback(p).catch(y=>E.error("[palbase] the request's transaction could not be rolled back",{error:y})),p}try{await a.commit()}catch(p){throw await a.rollback(p).catch(y=>E.error("[palbase] the request's transaction could not be rolled back",{error:y})),p}return c}var ga=1024*1024,ya=20,wa={max:300,window:60},Le="/_palbase/crons",Ie="/_palbase/tasks",Zr=50,Qr=50,ba=4096,ka=69632,Gr=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/,tt=1e4,va=6e4;function $a(e,t){let n=e.meta.options.auth??e.controllerAuth??t??!0;if(typeof n=="boolean")return{required:n,verifiedEmail:!1};if((n.role??"").trim()!==""||(n.permission??"").trim()!=="")throw new TypeError(`${e.id}: auth { role, permission } were checked against v2's database; v3 has none yet \u2014 check the role in the service`);return{required:n.required!==!1,verifiedEmail:n.verifiedEmail===!0}}var X=class extends Error{constructor(n,r,s,o,a,i){super(s);this.status=n;this.code=r;this.data=o;this.retryAfter=a;this.challenge=i}status;code;data;retryAfter;challenge};function Ta(e){if(e==="proof")return'DPoP error="invalid_dpop_proof", algs="ES256"';if(e==="bound"||e==="not_bound")return'DPoP error="invalid_token", algs="ES256"'}var Ea=["connection","keep-alive","proxy-connection","transfer-encoding","te","trailer","upgrade"];function Ra(e,t){let n=new Headers(e.headers);for(let r of Ea)n.delete(r);return e.url!==""&&(n.delete("content-encoding"),n.delete("content-length")),n.set("x-request-id",t),new Response(e.body,{status:e.status,statusText:e.statusText,headers:n})}function Yr(e,t){return t===void 0||t.length===0||(e.headers.has("content-language")||e.headers.set("content-language",t.join(", ")),St(e.headers,"Accept-Language")),e}function St(e,t){let n=(e.get("vary")??"").split(",").map(r=>r.trim()).filter(Boolean);n.includes("*")||n.some(r=>r.toLowerCase()===t.toLowerCase())||e.set("vary",[...n,t].join(", "))}function ue(e,t,n,r={}){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json","x-request-id":n,...r}})}function $(e,t){let n={error:e.code,error_description:e.message,status:e.status,request_id:t};e.data!==void 0&&(n.data=e.data);let r={};return e.retryAfter!==void 0&&(r["retry-after"]=String(e.retryAfter)),e.challenge!==void 0&&(r["www-authenticate"]=e.challenge),ue(e.status,n,t,r)}var ss=new Set([0,429,502,503,504]);function Xr(e,t,n,r){if(r?.aborted)return E.info(`[palbase] ${n}: the client left before its answer`),$({status:499,code:"client_closed_request",message:"The client closed the connection before its answer"},t);if(e instanceof X)return $({status:e.status,code:e.code,message:e.message,data:e.data,retryAfter:e.retryAfter,challenge:e.challenge},t);if(Qe(e)){let o=e;return o.status>=500&&E.error(`[palbase] ${n} answered ${o.status} ${o.error}`,{error:e}),ue(o.status,Er(o,t),t,o.retryAfter!==void 0?{"retry-after":String(o.retryAfter)}:{})}let s=Ot(e,n);return s?$(s,t):(e instanceof ie?E.error(`[palbase] ${n}: a platform service refused the app's call (${e.op}: ${e.status} ${e.code})`,{error:e}):E.error(`[palbase] unhandled error in ${n}`,{error:e}),$({status:500,code:"internal_error",message:"The request could not be completed"},t))}function Ot(e,t){if(e instanceof it)return E.warn(`[palbase] ${t}: sign-ins cannot be checked (${e.message})`,{error:e}),{status:503,code:"auth_unavailable",message:"Sign-ins cannot be checked right now; try again shortly",retryAfter:1};if(e instanceof ie&&ss.has(e.status))return E.warn(`[palbase] ${t}: a platform service did not answer (${e.op}: ${e.status} ${e.code})`,{error:e}),{status:503,code:"service_unavailable",message:"A service this request needs did not answer; try again shortly",retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))};let n=ns(e);if(n!==void 0)return E.warn(`[palbase] ${t}: the database connection ${n==="lost"?"was lost":"could not be opened"}`,{error:e}),{status:503,code:"database_unavailable",message:"The database is temporarily unavailable",data:{retrySafe:n==="never"},retryAfter:1}}function _a(e){let t=n=>(n.length>1e3?`${n.slice(0,1e3)}\u2026`:n)||"The tool failed";return Or(e)?t(e.message):Qe(e)&&!bn(e)&&!yn(e)?t(e.errorDescription):yn(e)?"The tool could not reach a service it needs right now; try again shortly":"The tool failed"}function yn(e){return e instanceof it||e instanceof ie&&ss.has(e.status)||ns(e)!==void 0||Qe(e)&&e.status===503&&bn(e)}async function hn(e,t,n){let r=await e["~standard"].validate(t);if(r.issues){let s=r.issues.slice(0,ya).map(a=>({field:(a.path??[]).map(i=>String(typeof i=="object"&&i!==null&&"key"in i?i.key:i)).join("."),message:a.message})),o=r.issues.length-s.length;throw new X(400,"bad_request",`${n} failed validation`,o>0?{fields:s,more:o}:{fields:s})}return r.value}async function nt(e,t){let n=Number(e.headers.get("content-length")??"NaN");if(Number.isFinite(n)&&n>t)throw new X(413,"payload_too_large",`Request body exceeds ${t} bytes`);if(!e.body)return new Uint8Array(0);let r=e.body.getReader(),s=[],o=0;for(;;){let{done:c,value:p}=await r.read();if(c)break;if(o+=p.byteLength,o>t)throw await r.cancel().catch(()=>{}),new X(413,"payload_too_large",`Request body exceeds ${t} bytes`);s.push(p)}let a=new Uint8Array(o),i=0;for(let c of s)a.set(c,i),i+=c.byteLength;return a}function Sa(e){if(e.byteLength===0)return{};let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return{}}return ae(t)}function Oa(e){let t=e.claims.custom_claims;return{id:e.id,email:e.email,role:e.role,emailVerified:e.emailVerified,metadata:typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{},sessionId:e.sessionId,test:e.claims.test===!0}}function xa(e){return e.id?{id:e.id,email:e.email??null,role:e.role,emailVerified:e.emailVerified??!1,metadata:{},sessionId:e.session??null,test:!1}:null}var Aa=/^[A-Za-z0-9._:-]{8,128}$/,Pa=/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,Ca={max:20,window:60},Ma=10*6e4,Da=1e4,rt=class extends Error{constructor(n){super("too many unknown tokens from this address");this.wait=n}wait},wn=class{constructor(t,n){this.limiter=t;this.now=n}limiter;now;known=new Map;async ask(t,n,r){let s=rs("sha256").update(t).digest("hex"),o=(this.known.get(s)??0)>this.now(),a=`token-misses\0a:${n}`,i;if(!o){let p=this.limiter.reserve(a,Ca);if("wait"in p)throw new rt(p.wait);i=p}let c=await r();if(!c)throw this.known.delete(s),new at("unknown_token","The token is not one of the app's");return i&&this.limiter.give(a,i.window),this.known.delete(s),this.known.set(s,this.now()+Ma),this.known.size>Da&&this.known.delete(this.known.keys().next().value),c}};function Yd(e){let t=new mt(e.modules),n=Vr(t.controllers.map(d=>d.cls)),r=new Map(n.map(d=>[d,$a(d,e.auth)]));for(let[d,u]of r){if(!u.required&&d.params.some(f=>f.kind==="user"))throw new TypeError(`${d.id}: @User() on a route that does not need a signed-in user \u2014 use @OptionalUser() (null when nobody is)`);if(d.meta.upload&&u.verifiedEmail)throw new TypeError(`${d.id}: an @Upload route cannot ask for a verified email \u2014 storage names its caller by id and session, not by its token; read the user (Palbase.auth) in the handler to check it`)}let s=new Map;for(let d of n)for(let u of d.params)u.kind==="resolve"&&s.set(u,t.dependencyOf(d.controller,u.resolver,`${d.id} @Resolve(${u.resolver?.name})`));let o=new Map;for(let d of t.cronProviders){let u=t.get(d),f=M(d,he),l=o.get(f.name);if(l)throw new TypeError(`@Cron "${f.name}" is ${l.owner} and ${d.name}: a cron's name is its own \u2014 name one of them`);o.set(f.name,{declaration:f,owner:d.name,run:g=>u.run(g)})}let a=new Map;for(let d of t.taskProviders){let u=t.get(d),f=M(d,fe),l=a.get(f.name);if(l)throw new TypeError(`@Task "${f.name}" is ${l.owner} and ${d.name}: a task type's name is its own \u2014 name one of them`);a.set(f.name,{declaration:f,owner:d.name,run:(g,m)=>u.run(g,m)})}let i=new Set,c=new Set;if(e.platform&&!e.platform.secret)throw new Error("[palbase] platform.secret is the key the platform signs its calls with (PALBASE_PLATFORM_SECRET)");if(o.size>Zr)throw new TypeError(`${o.size} @Cron classes: a machine runs ${Zr} crons at most`);if(a.size>Qr)throw new TypeError(`${a.size} @Task classes: a machine runs ${Qr} task types at most`);o.size>0&&!e.platform&&E.info(`[palbase] ${o.size} @Cron(s): the platform runs them on a machine; nothing calls them here`);let p=e.channels??er(),y=nr(p,t.rooms.map(d=>Qt(d)));if(y)throw new TypeError(y);let k=Yn([...t.rooms.map(d=>({cls:d,instance:t.get(d)})),...tr(p)],{run:(d,u,f,l)=>ee.run({requestId:ee.getStore()?.requestId??"",...d?.id?{userId:d.id}:{}},()=>_t(e.database,e.database?d?.id?gn(e.database.requests,ft(d)):mn:void 0,f,u,async()=>{let g=await l();if(f?.aborted)throw new Error(`realtime gave up on ${u} before it ended`);return g})),broadcast:d=>e.server.realtime.broadcast({body:{messages:d}}),isOutage:yn});k.declarations.length>0&&!e.platform&&E.info(`[palbase] ${k.declarations.length} @Room(s): realtime tells a machine of them; nothing does here`);let R=xr();(R.tools.size>0||R.agents.size>0)&&!e.platform&&E.info(`[palbase] ${R.tools.size} ai.tool(s) and ${R.agents.size} ai.agent(s): the platform's chats call a machine for them; nothing does here`);let U=new gt,I=new ht(e.now??Date.now),L=new Set,h=e.database!==void 0||e.contractOnly?.database===!0;if(h){for(let d of n)if(Ge(d)&&d.params.some(u=>u.kind==="headers"&&u.schema!==void 0&&zr(u.schema)))throw new TypeError(`${d.id}: its @Headers schema declares Idempotency-Key \u2014 the framework takes that header on every write of an app with a database and answers a retry from it; a handler reads it with @Headers() (no schema)`)}let v=e.database?new bt(e.database.app):void 0,b=qa(e.cors),O=e.now??Date.now,z=new Et(e.now),F=new wn(z,e.now??Date.now),D=e.maxBodyBytes??ga,j=d=>{let u=d.meta.options.rateLimit??e.rateLimit??wa;return u!==!1&&u.max>0&&u.window>0?u:!1},q=e.env??process.env,H=pr(t.webhooks,d=>t.get(d),q,{secrets:e.contractOnly===void 0}),K=H.size===0&&o.size===0&&a.size===0?{}:Object.freeze(Object.fromEntries(Object.entries(q).filter(d=>typeof d[1]=="string"&&!Nn(d[0])))),de=new Map([...H.keys()].map(d=>[d,{seen:new Set,inflight:new Set}])),ne=new Map([...H.keys()].map(d=>[d,{counts:new Map,at:void 0}])),st,ze=()=>st??=Wr(n,d=>({auth:r.get(d),limit:j(d)}),{databaseSeesCaller:h,idempotency:h,webhooks:[...H.values()].map(d=>({name:d.name,cls:d.cls.name,provider:d.provider,signatureHeader:d.signatureHeader,secretEnv:d.secretEnv,events:[...d.events.keys()]})),platformEvents:[...W.keys()],rooms:k.declarations,channels:p.rows,platformEventBuckets:Na(W),routes:e.contractOnly?.routes,errors:e.contractOnly?.errors}),W=new Map;for(let[d,u]of Object.entries(e.events??{}))W.set(d,u.map(f=>({name:`palbase(${d})`,call:l=>f(l)})));for(let d of t.eventProviders){let u=t.get(d);for(let{event:f,fn:l,bucket:g}of M(d,be)??[]){if(!Bn.test(f))throw new TypeError(`@On("${f}") on ${d.name}.${l}: a platform event's type is dotted lowercase words, like user.deleted \u2014 a third party's event is taken by an @On in its @Webhook class`);W.has(f)||W.set(f,[]),W.get(f).push({name:`${d.name}.${l}`,bucket:g,call:async(m,w)=>u[l](m,w)})}}let we=new Set,$e=new Set;Un(e.server),Kn(e.platform?Jn(q.PALBASE_MACHINE):new lt(new Map([...a].map(([d,u])=>[d,u.declaration])),(d,u)=>Tn(d,u),e.now));async function qe(d,u){let f;try{f=await Dn(d,e.webhookSecret,{now:e.now})}catch(l){if(l instanceof Ke)return $({status:401,code:"invalid_signature",message:`The delivery is not the platform's: ${l.code}`},u);throw l}if(ae(f.data),we.has(f.id))return new Response(null,{status:204,headers:{"x-request-id":u}});if($e.has(f.id))return $({status:409,code:"in_progress",message:"This event is being handled",retryAfter:5},u);$e.add(f.id);try{let l;try{await Ue(e.database,null,void 0,`event ${f.type}`,async()=>{for(let g of W.get(f.type)??[])if(!(g.bucket!==void 0&&ja(f)!==g.bucket))try{await g.call(f,{requestId:u})}catch(m){throw l=g.name,m}})}catch(g){return E.error(`[palbase] ${l??"the delivery"} failed on ${f.type} ${f.id}; the platform delivers it again`,{error:g}),$({status:500,code:"handler_failed",message:"The event could not be handled"},u)}return we.add(f.id),we.size>tt&&we.delete(we.values().next().value),new Response(null,{status:204,headers:{"x-request-id":u}})}finally{$e.delete(f.id)}}async function xt(d,u={}){let f=d.headers.get("origin");if(b&&f!==null){let l=b.allows(f);if(d.method==="OPTIONS"&&d.headers.has("access-control-request-method"))return l?new Response(null,{status:204,headers:b.preflight(f,d.headers.get("access-control-request-headers"))}):new Response(null,{status:403,headers:{vary:"Origin"}});let g=await Sn(d,u);if(l)for(let[m,w]of Object.entries(b.headers(f)))m==="vary"?St(g.headers,w):g.headers.set(m,w);else St(g.headers,"Origin");return g}return Sn(d,u)}async function V(d,u,f,l){if(!d.headers.get(f.scheme.header))return me(f,"missing_signature",l);let g={headers:d.headers,body:await nt(d,f.scheme.maxBytes(D)),url:mr(d,u)},m;try{m=f.scheme.check(g,O()/1e3)}catch{return me(f,"signature_mismatch",l,"check_failed")}if(typeof m=="string")return me(f,m,l);let w=f.events.get(m.type);if(!w)return E.info(`[palbase] webhook ${f.name}: no @On takes "${m.type}"; acknowledged`),ue(200,{ok:!0,handled:!1},l);let T=de.get(f.name),_=m.event,C=[];if(m.id!==void 0){if(T.seen.has(m.id))return ue(200,{ok:!0,handled:!1,duplicate:!0},l);C=[m.id]}else if(m.ids&&Array.isArray(_)){let S=m.ids,x=_.map((P,Q)=>[P,S[Q]]).filter(([,P])=>P===void 0||!T.seen.has(P));if(x.length===0)return ue(200,{ok:!0,handled:!1,duplicate:!0},l);_=x.map(([P])=>P),C=x.flatMap(([,P])=>P===void 0?[]:[P])}if(C.some(S=>T.inflight.has(S)))return $({status:409,code:"in_progress",message:"This delivery is being handled",retryAfter:5},l);ae(_);for(let S of C)T.inflight.add(S);let A;try{A=await Ue(e.database,null,void 0,`webhook ${f.name}`,()=>w.call(_,{env:K,requestId:l,environmentId:e.projectId??""}))}catch(S){let x=Ot(S,`webhook ${f.name}`)??Ua(S,f.name);return x?$(x,l):(E.error(`[palbase] ${w.name} failed on ${f.name} "${m.type}"; the sender delivers it again`,{error:S}),$({status:500,code:"handler_failed",message:"The event could not be handled"},l))}finally{for(let S of C)T.inflight.delete(S)}for(let S of C)T.seen.add(S),T.seen.size>tt&&T.seen.delete(T.seen.values().next().value);return Te(A,f,l)}function Te(d,u,f){if(d instanceof Response)return d;if(typeof d=="string"){let l=u.provider==="twilio"?"text/xml; charset=utf-8":"text/plain; charset=utf-8";return new Response(d,{status:200,headers:{"content-type":l,"x-request-id":f}})}return ue(200,d??{ok:!0,handled:!0},f)}function me(d,u,f,l=u){let g=ne.get(d.name);g.counts.set(l,(g.counts.get(l)??0)+1);let m=O();return(g.at===void 0||m-g.at>=va)&&(He(d.name),g.at=m),$({status:401,code:"invalid_signature",message:`The delivery is not signed with this webhook's secret: ${u}`},f)}function He(d){let u=ne.get(d).counts;if(u.size===0)return;let f=[...u.values()].reduce((l,g)=>l+g,0);E.warn(`[palbase] webhook ${d}: ${f} deliveries refused since the last report (one a minute at most)`,{refused:Object.fromEntries(u)}),u.clear()}function is(d){let u=d.split("/").filter(Boolean);return u.length===2&&u[0]==="webhooks"?H.get(u[1]):void 0}async function ds(d,u,f,l){let g=u.pathname===Le;if(d.method!==(g?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:g?"The crons are listed with GET":"A cron is run with POST"},l);let m=g?new Uint8Array(0):await nt(d,ba);try{await ot({secret:f,signature:d.headers.get("palbase-signature"),body:m,now:e.now})}catch(Z){if(Z instanceof Ke)return $({status:401,code:"invalid_signature",message:`The crons are the platform's to call: ${Z.code}`},l);throw Z}if(g){let Z=[...o.values()].map(({declaration:B})=>({name:B.name,schedule:B.schedule,time_zone:B.timeZone,timeout:B.timeout,retry:B.retries}));return ue(200,{crons:Z},l,{"cache-control":"no-store"})}let w=u.pathname.slice(Le.length+1),T=o.get(w);if(!T)return $({status:404,code:"cron_not_found",message:`This version has no cron ${JSON.stringify(w)}`},l);let _;try{_=JSON.parse(new TextDecoder().decode(m))}catch{return $({status:400,code:"bad_request",message:"A run is the JSON {cron, run_id, scheduled_at, attempt}"},l)}let{cron:C,run_id:A,scheduled_at:S,attempt:x}=_??{};if(C!==w||typeof A!="string"||A===""||typeof S!="string"||!Gr.test(S)||Number.isNaN(Date.parse(S))||!Number.isInteger(x)||x<1)return $({status:400,code:"bad_request",message:`A run of ${w} is the JSON {cron: "${w}", run_id, scheduled_at (RFC 3339), attempt (1 or more)}`},l);let P=`${A}#${String(x)}`;if(i.has(P))return new Response(null,{status:204,headers:{"x-request-id":l}});if(c.has(P))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},l);c.add(P);let Q={env:K,environmentId:e.projectId??"",cron:w,runId:A,scheduledAt:new Date(S),attempt:x};try{await _t(e.database,e.database?mn:void 0,d.signal,`cron ${w}`,async()=>{if(await T.run(Q),d.signal.aborted)throw new Error(`the platform gave up on this attempt of ${w} before it ended`)})}catch(Z){return d.signal.aborted||E.error(`[palbase] cron ${w} failed (run ${A}, attempt ${String(x)})`,{error:Z}),$({status:500,code:"cron_failed",message:`The cron ${w} failed; the platform tries it again`},l)}finally{c.delete(P)}return i.add(P),i.size>tt&&i.delete(i.values().next().value),new Response(null,{status:204,headers:{"x-request-id":l}})}let Tn=async({task:d,id:u,attempt:f,payload:l,createdAt:g},m)=>{let w=a.get(d);if(!w)return{status:404,message:`this version has no task ${JSON.stringify(d)}`};let T=ae(l??null),_=w.declaration.payload;if(_){let A=await _["~standard"].validate(T);if(A.issues){let S=A.issues.slice(0,5).map(x=>`${(x.path??[]).map(P=>String(typeof P=="object"&&P!==null&&"key"in P?P.key:P)).join(".")||"(payload)"}: ${x.message}`).join("; ");return E.error(`[palbase] task ${d} ${u}: what it carries is not what it takes \u2014 it fails, not to be tried again: ${S}`),{status:422,message:`what it carries is not what @Task "${d}" takes: ${S}`}}T=A.value}let C={env:K,environmentId:e.projectId??"",task:d,id:u,attempt:f,createdAt:g};try{await _t(e.database,e.database?mn:void 0,m,`task ${d}`,async()=>{if(await w.run(T,C),m.aborted)throw new Error(`the platform gave up on this attempt of ${d} before it ended`)})}catch(A){return A instanceof ut?(E.error(`[palbase] task ${d} ${u} can never be done: ${A.message}`),{status:422,message:A.message}):(m.aborted||E.error(`[palbase] task ${d} failed (task ${u}, attempt ${String(f)})`,{error:A}),{status:500,message:`the task ${d} failed; it is tried again`})}return{status:204}};async function cs(d,u,f,l){let g=u.pathname===Ie;if(d.method!==(g?"GET":"POST"))return $({status:405,code:"method_not_allowed",message:g?"The task types are listed with GET":"A task is run with POST"},l);let m=g?new Uint8Array(0):await nt(d,ka);try{await ot({secret:f,signature:d.headers.get("palbase-signature"),body:m,now:e.now})}catch(Z){if(Z instanceof Ke)return $({status:401,code:"invalid_signature",message:`The tasks are the platform's to call: ${Z.code}`},l);throw Z}if(g){let Z=[...a.values()].map(({declaration:B})=>({name:B.name,timeout:B.timeout,retry:B.retries,concurrency:B.concurrency}));return ue(200,{tasks:Z},l,{"cache-control":"no-store"})}let w=u.pathname.slice(Ie.length+1),T;try{T=JSON.parse(new TextDecoder().decode(m))}catch{return $({status:400,code:"bad_request",message:"A task is the JSON {task, id, attempt, payload, created_at}"},l)}let{task:_,id:C,attempt:A,payload:S,created_at:x}=T??{};if(_!==w||typeof C!="string"||C===""||typeof x!="string"||!Gr.test(x)||Number.isNaN(Date.parse(x))||!Number.isInteger(A)||A<1)return $({status:400,code:"bad_request",message:`A task of ${w} is the JSON {task: "${w}", id, attempt (1 or more), payload, created_at (RFC 3339)}`},l);let P=`task:${C}#${String(A)}`;if(i.has(P))return new Response(null,{status:204,headers:{"x-request-id":l}});if(c.has(P))return $({status:409,code:"in_progress",message:"This attempt is running",retryAfter:5},l);c.add(P);let Q;try{Q=await Tn({task:w,id:C,attempt:A,payload:S,createdAt:new Date(x)},d.signal)}finally{c.delete(P)}return Q.status===404?$({status:404,code:"task_not_found",message:Q.message??""},l):Q.status===422?$({status:422,code:"task_failure",message:Q.message??""},l):Q.status>=300?$({status:Q.status,code:"task_failed",message:Q.message??""},l):(i.add(P),i.size>tt&&i.delete(i.values().next().value),new Response(null,{status:204,headers:{"x-request-id":l}}))}async function Be(d,u,f,l){if(d.method!=="POST")return $({status:405,code:"method_not_allowed",message:`${l} is POSTed`},f);let g;try{Mn({signature:d.headers.get("palbase-signature"),now:e.now}),g=await nt(d,1048576),await ot({secret:u,signature:d.headers.get("palbase-signature"),body:g,now:e.now})}catch(w){if(w instanceof Ke)return $({status:401,code:"invalid_signature",message:`${l} is the platform's to call: ${w.code}`},f);throw w}let m;try{m=JSON.parse(new TextDecoder().decode(g))}catch{return $({status:400,code:"bad_request",message:`${l} is JSON`},f)}return typeof m!="object"||m===null||!Object.hasOwn(m,"call")||m.call!==new URL(d.url).pathname?$({status:401,code:"invalid_signature",message:`${l} is the platform's to call: signed_for_another_call`},f):{body:m}}async function us(d,u,f,l,g){let m=await Be(u,f,l,`An upload's ${d}`);if(m instanceof Response)return m;let w=ir(d,m.body);if(typeof w=="string")return $({status:400,code:"bad_request",message:`An upload's ${d}: ${w}`},l);if(d==="complete"){if(L.has(w.uploadId))return $({status:409,code:"duplicate_upload",message:"This upload was completed here already: storage completes each once"},l);L.add(w.uploadId),L.size>tt&&L.delete(L.values().next().value)}let T=pn(n,w.method,w.route);if(!T||"malformed"in T||!T.route.meta.upload)return $({status:404,code:"not_found",message:`No upload route for ${w.method} ${w.route}`},l);let{route:_,params:C}=T,A=T.route.meta.upload,S=xa(w.user);if(S&&On(g,S.id),r.get(_).required&&!S)throw new X(401,"unauthorized","This route needs a signed-in user");if(d==="authorize"){let Q=j(_);if(Q!==!1){let B=z.take(`${_.id}\0${Zn(w.user,w.client)}`,Q);if(B!==void 0)throw new X(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:B},B)}let Z=or(A.pathTemplate,{userId:S?.id??null,uploadId:w.uploadId,filename:w.filename});if("problem"in Z)throw new X(400,"bad_request",Z.problem);return await Ue(e.database,ft(w.user),u.signal,_.id,async()=>{let B={request:u,query:new URLSearchParams(w.query),params:C,user:S,body:w.body===void 0||w.body===null?{}:ae(w.body),requestId:l};await _n(_,B);for(let Ee of _.params)(Ee.kind==="query"||Ee.kind==="body"&&w.body!==void 0)&&await ts(Ee,B)}),ue(200,{bucket:A.bucket,path:Z.path},l)}g.endpoint=_.id.slice(_.id.indexOf(" ")+1);let x=new URLSearchParams(w.query),P=w.body===null||w.body===void 0?{}:ae(w.body);return At(_,{request:u,query:x,params:C,user:S,body:P,requestId:l,uploadedObject:ae(w.uploadedObject)},ft(w.user))}function En(d,u,f,l){let g=d?{sub:d.id,role:"authenticated"}:null;return ee.run({requestId:ee.getStore()?.requestId??"",...d?{userId:d.id}:{}},()=>Ue(e.database,g,f,u,async()=>{let m=await l();if(f.aborted)throw new Error(`the platform gave up on ${u} before it ended`);return m}))}let Rn=(d,u)=>new Response(d,{status:200,headers:{"content-type":"application/json","x-request-id":u}});async function ls(d,u,f){let l=await Be(d,u,f,"A tool call");if(l instanceof Response)return l;let g=l.body,m=g.tool;if(typeof m!="string"||m==="")return $({status:400,code:"bad_request",message:"A tool call is {tool, call_id, input, context}: tool names it"},f);let w=R.tools.get(m);if(!w)return $({status:404,code:"tool_not_found",message:`This version has no ai.tool ${JSON.stringify(m.slice(0,64))}`},f);let T=g.call_id,_=rn(g.context);if(typeof T!="string"||T===""||T.length>256||typeof _=="string")return $({status:400,code:"bad_request",message:`A call of ${m} is {tool, call_id, input, context}${typeof _=="string"?`: ${_}`:""}`},f);let C=rs("sha256").update(JSON.stringify(g)).digest("hex"),A=U.answered(T);if(A!==void 0)return A.digest!==C?$({status:409,code:"call_id_reused",message:"This call id was answered here for another call"},f):Rn(A.answer,f);if(U.isRunning(T))return $({status:409,code:"in_progress",message:"This call is running",retryAfter:2},f);U.start(T);let S;try{let x=await En(_.user,`ai.tool ${m}`,d.signal,()=>w.call(ae(g.input??{}),{..._,callId:T,signal:d.signal}));S=JSON.stringify({output:x.output,is_error:x.is_error});let P=new TextEncoder().encode(S).byteLength;P>4194304&&(E.error(`[palbase] ai.tool ${m} answered ${P} bytes (call ${T}): a machine's answer is ${4194304} at most; the agent is told it failed`),S=JSON.stringify({output:[{type:"text",text:`The tool's answer was larger than the ${4194304/(1<<20)} MiB it may be`}],is_error:!0}))}catch(x){if(d.signal.aborted)return U.end(T,void 0),$({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);E.error(`[palbase] ai.tool ${m} failed (call ${T}, chat ${_.chatId}); the agent is told`,{error:x}),S=JSON.stringify({output:[{type:"text",text:_a(x)}],is_error:!0})}return U.end(T,{digest:C,answer:S}),Rn(S,f)}async function fs(d,u,f){let l=await Be(d,u,f,"An agent's turn");if(l instanceof Response)return l;let g=rn(l.body);if(typeof g=="string"||g.agent==="")return $({status:400,code:"bad_request",message:`A turn is {chat_id, agent, user, metadata}${typeof g=="string"?`: ${g}`:": agent names it"}`},f);let m=g.agent,w=R.agents.get(m);if(!w)return $({status:404,code:"agent_not_found",message:`This version has no ai.agent ${JSON.stringify(m.slice(0,64))}`},f);let T;try{T=await En(g.user,`ai.agent ${m}`,d.signal,()=>w.resolve({...g,signal:d.signal}))}catch(A){if(d.signal.aborted)return $({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let S=Ot(A,`ai.agent ${m}`);return S?$(S,f):(E.error(`[palbase] ai.agent ${m} failed for chat ${g.chatId}; the turn is not started`,{error:A}),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},f))}let _=T.tools.find(A=>R.tools.get(A.name)!==A);if(_)return E.error(`[palbase] ai.agent ${m} handed out ai.tool ${JSON.stringify(_.name)}, which this app did not declare when it was made \u2014 make each ai.tool once, at a module's top level, and hand that one out`),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},f);let C=JSON.stringify(T.definition);return new TextEncoder().encode(C).byteLength>4194304?(E.error(`[palbase] ai.agent ${m}'s definition is larger than the ${4194304} bytes a machine's answer may be`),$({status:500,code:"agent_failed",message:`The agent ${m} could not be defined for this turn`},f)):new Response(C,{status:200,headers:{"content-type":"application/json","x-request-id":f,"cache-control":"no-store"}})}async function ps(d,u,f){let l=await Be(d,u,f,"A repository's token");if(l instanceof Response)return l;let g=l.body;if(typeof g.repo!="string"||g.repo===""||typeof g.repository!="string"||typeof g.call_id!="string"||g.call_id===""||g.call_id.length>256)return $({status:400,code:"bad_request",message:"A repository's token is asked as {call_id, repo, repository}"},f);if(!I.take(g.call_id))return $({status:409,code:"call_id_reused",message:"This token ask was answered already"},f);let m=R.repos.get(g.repo);if(!m)return $({status:404,code:"repo_not_found",message:`This version has no ai.repo ${JSON.stringify(g.repo.slice(0,64))}`},f);let w;try{w=await m.token({repo:g.repo,repository:g.repository,signal:d.signal})}catch(T){if(d.signal.aborted)return $({status:499,code:"client_closed_request",message:"The platform closed the call before its answer"},f);let _=Ot(T,`ai.repo ${g.repo}`);return _?$(_,f):(E.error(`[palbase] ai.repo ${g.repo} gave no token; the workspace's clone or push is refused`,{error:T}),$({status:500,code:"token_failed",message:`The repository ${g.repo} gave no token`},f))}return typeof w!="string"||w.trim()===""?(E.error(`[palbase] ai.repo ${g.repo}'s token function answered no token`),$({status:500,code:"token_failed",message:`The repository ${g.repo} gave no token`},f)):new Response(JSON.stringify({token:w}),{status:200,headers:{"content-type":"application/json","x-request-id":f,"cache-control":"no-store"}})}async function ms(d,u,f,l){let g=await Be(u,f,l,`A room's ${d}`);if(g instanceof Response)return g;let m=await k.serve(d,g.body,u.signal);return"code"in m?$({status:m.status,code:m.code,message:m.message,retryAfter:m.retryAfter},l):"body"in m?ue(200,m.body,l):new Response(null,{status:204,headers:{"x-request-id":l}})}async function _n(d,u){let f=[],l={params:Object.freeze({...u.params}),user:ae(u.user),headers:d.meta.upload?new Headers:u.request.headers,requestId:u.requestId};for(let g of d.params)g.kind==="resolve"&&(f[g.index]=await s.get(g).resolve(l,g.options));return f}async function At(d,u,f,l){let g=t.get(d.controller),m=await Ue(e.database,f,u.request.signal,d.id,async()=>{let w=await _n(d,u);for(let _ of d.params)_.kind!=="resolve"&&(w[_.index]=await ts(_,u));l?.ran();let T=await g[d.fn](...w);if(u.uploadedObject&&u.request.signal.aborted)throw new Error(`storage gave up on ${d.id}'s upload before it was answered`);return l?l.record(Yr(es(T,u.requestId),ee.getStore()?.usedLocales)):T});return l?m:Yr(es(m,u.requestId),ee.getStore()?.usedLocales)}async function Sn(d,u){let f=d.headers.get("x-request-id")??"",l=Aa.test(f)?f:`req_${crypto.randomUUID()}`,g=performance.now(),m=new URL(d.url).pathname,w={endpoint:m},T=await hs(d,u,l,w);return e.telemetry?.record({requestId:l,method:d.method,endpoint:w.endpoint,path:m,status:T.status,durationMs:performance.now()-g,userId:w.userId}),T}function On(d,u){d.userId=u;let f=ee.getStore();f&&(f.userId=u)}async function hs(d,u,f,l){let g=e.strings,m=g?{requestId:f,strings:g,locales:Ln(d.headers.get("accept-language"),g.source),usedLocales:[]}:{requestId:f},w=await gs(m,d,u,f,l);return g&&St(w.headers,"Accept-Language"),w}async function gs(d,u,f,l,g){return ee.run(d,async()=>{let m=new URL(u.url),w=`${u.method} ${m.pathname}`;try{if(m.pathname===cn&&W.size>0)return u.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},l):e.webhookSecret?await qe(u,l):$({status:503,code:"webhook_secret_missing",message:"This app was started without PALBASE_WEBHOOK_SECRET and takes no delivery"},l);let T=is(m.pathname);if(T)return w=`webhook ${T.name}`,u.method!=="POST"?$({status:405,code:"method_not_allowed",message:"Deliveries are POSTed"},l):await V(u,m,T,l);if(e.platform&&(m.pathname===Le||m.pathname.startsWith(`${Le}/`)))return w=m.pathname===Le?"crons":`cron ${m.pathname.slice(Le.length+1)}`,await ds(u,m,e.platform.secret,l);if(e.platform&&(m.pathname===Ie||m.pathname.startsWith(`${Ie}/`)))return w=m.pathname===Ie?"tasks":`task ${m.pathname.slice(Ie.length+1)}`,await cs(u,m,e.platform.secret,l);if(e.platform&&(m.pathname===Ht||m.pathname===Wn)){let N=m.pathname===Ht?"authorize":"complete";return w=`upload ${N}`,await us(N,u,e.platform.secret,l,g)}if(e.platform&&m.pathname.startsWith(`${Bt}/`)){let N=m.pathname.slice(Bt.length+1);return w=`room ${N}`,await ms(N,u,e.platform.secret,l)}if(e.platform&&m.pathname===Rr)return w="ai tool call",await ls(u,e.platform.secret,l);if(e.platform&&m.pathname===_r)return w="ai agent's turn",await fs(u,e.platform.secret,l);if(e.platform&&m.pathname===Sr)return w="ai repository's token",await ps(u,e.platform.secret,l);if(La(m.pathname))return $({status:404,code:"not_found",message:`No route for ${u.method} ${m.pathname}`},l);let _=pn(n,u.method,m.pathname);if(_&&"malformed"in _)return $({status:400,code:"bad_request",message:"The path is not valid percent-encoding"},l);if(!_)return $({status:404,code:"not_found",message:`No route for ${u.method} ${m.pathname}`},l);let{route:C,params:A}=_;if(w=C.id,g.endpoint=C.id.slice(C.id.indexOf(" ")+1),C.meta.upload)throw new X(400,"upload_required",`${C.id} is an upload: its file and body are sent through storage (POST /storage/upload/<machine>/<route>), which calls it`);let S=r.get(C),x=null,P=null,Q=u.headers.get("authorization")??"",Z=/^(bearer|dpop)\s+(\S+)$/i.exec(Q),B=Z?.[2],Ee=Z?.[1].toLowerCase()==="dpop";if(B)try{let N=!Ee&&e.tokens&&!Pa.test(B)&&e.tokens.accepts(B)?e.tokens:void 0,Re=N?await F.ask(B,Rt(u.headers,f.remoteAddress),()=>Ue(e.database,null,u.signal,"token",()=>N.resolve(B))):await e.verifier.verify(B,Ee?{proof:u.headers.get("dpop"),method:u.method,url:jn(u.headers,m)}:void 0);x=Oa(Re),P=Re.claims}catch(N){if(!S.required&&(N instanceof at||N instanceof it||N instanceof rt))x=null;else throw N instanceof rt?new X(429,"too_many_requests","Too many unknown tokens from this address",{retryAfter:N.wait},N.wait):N instanceof at?new X(401,"invalid_token","The access token is not valid",{reason:N.reason},void 0,Ta(N.reason)):N}else if(Q!==""&&S.required)throw new X(401,"invalid_token","The Authorization header is not a Bearer or DPoP token");if(x&&On(g,x.id),S.required&&!x)throw new X(401,"unauthorized","This route needs a signed-in user");if(S.verifiedEmail&&!x?.emailVerified)throw new X(403,"email_not_verified","This route needs a verified email address");let xn=j(C);if(xn!==!1){let N=x?`u:${x.id}`:`a:${Rt(u.headers,f.remoteAddress)}`,Re=z.take(`${C.id}\0${N}`,xn);if(Re!==void 0)throw new X(429,"too_many_requests","Rate limit exceeded for this endpoint",{retryAfter:Re},Re)}let Fe=u.method==="GET"||u.method==="HEAD"?void 0:await nt(u,D),ys=Fe===void 0?void 0:Sa(Fe),An={request:u,query:m.searchParams,params:A,user:x,body:ys,raw:Fe,requestId:l},Pn=v&&Fe!==void 0&&Ge(C)?Lr(u.method,u.headers):void 0;if(!v||Pn===void 0)return await At(C,An,P);let ws={role:gn(e.database.requests,P).role,uid:x?.id??`a:${Rt(u.headers,f.remoteAddress)}`},Cn=!1;return await v.serve({key:Pn,caller:ws,method:u.method,uri:`${m.pathname}${m.search}`,body:Fe},N=>At(C,An,P,{record:N,ran:()=>{Cn=!0}}),{requestId:l,refusal:N=>$(N,l),failure:N=>Xr(N,l,w,u.signal),ran:()=>Cn})}catch(T){return Xr(T,l,w,u.signal)}})}return{handle:xt,routes:n.map(d=>d.id),contract:ze,start:()=>t.start(),stop:async()=>{k.close();for(let d of ne.keys())He(d);await t.shutdown(),await e.telemetry?.flush()}}}function ja(e){let t=e.data;return typeof t=="object"&&t!==null?t.bucket:void 0}function Na(e){let t=new Set;for(let[n,r]of e)if(Ut(n))for(let s of r){if(s.bucket===void 0)return;t.add(s.bucket)}return t.size===0?void 0:[...t].sort()}function es(e,t){return e instanceof Response?Ra(e,t):e==null?new Response(null,{status:204,headers:{"x-request-id":t}}):ue(200,e,t)}function Ua(e,t){if(!(!Qe(e)||e.status!==503||!bn(e)))return E.warn(`[palbase] webhook ${t}: the database did not answer (${e.error})`,{error:e}),{status:503,code:e.error,message:e.errorDescription,data:e.data,retryAfter:Math.max(1,Math.ceil(e.retryAfter??1))}}function La(e){let t=e.split("/").find(Boolean);if(t===void 0)return!1;try{return xe.has(decodeURIComponent(t))}catch{return xe.has(t)}}var Ia="GET, POST, PUT, PATCH, DELETE, QUERY",za=/^https?:\/\/[a-z0-9.-]+(:\d{1,5})?$/;function qa(e){if(!e)return;if(e.origins!=="*"){for(let r of e.origins)if(!za.test(r)||r.startsWith("http://")&&!/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(r))throw new TypeError(`cors origin ${JSON.stringify(r)} is https://host[:port] (http only for localhost), with no path`)}let t=e.origins==="*"?null:new Set(e.origins),n=String(e.maxAge??600);return{allows:r=>t===null||t.has(r),headers:r=>({"access-control-allow-origin":t===null?"*":r,"access-control-expose-headers":"idempotent-replayed, retry-after, x-request-id",vary:"Origin"}),preflight:(r,s)=>({"access-control-allow-origin":t===null?"*":r,"access-control-allow-methods":Ia,"access-control-allow-headers":s&&/^[A-Za-z0-9-]+(\s*,\s*[A-Za-z0-9-]+)*$/.test(s)?s:"authorization, content-type","access-control-max-age":n,vary:"Origin"})}}async function ts(e,t){switch(e.kind){case"body":return hn(e.schema,t.body??{},"Request body");case"query":return hn(e.schema,ae(Object.fromEntries(t.query)),"Query parameters");case"headers":{let n={};return t.request.headers.forEach((r,s)=>n[s.toLowerCase()]=r),ae(n),e.schema?hn(e.schema,n,"Request headers"):n}case"param":return t.params[e.name];case"user":case"optionalUser":return ae(t.user);case"req":return t.raw===void 0?t.request:new Request(t.request.url,{method:t.request.method,headers:t.request.headers,body:t.raw,signal:t.request.signal});case"requestId":return t.requestId;case"resolve":throw new Error("@Resolve parameters are made by their resolver, before the others");case"uploadedObject":return t.uploadedObject;case"client":{let n=t.request.headers;return ae({sdkVersion:n.get("x-palbase-sdk-version"),appVersion:n.get("x-palbase-client-version"),platform:n.get("x-platform"),osVersion:n.get("x-os-version")})}}}var vn=720*3600;function kn(e){return e instanceof ie&&(e.status===0||e.status===429||e.status>=500||e.code==="network_error")}function os(e){if(!(e===void 0||!Number.isFinite(e)||e<=0))return Math.min(Math.ceil(e),vn)}function as(e){return e===void 0?null:JSON.parse(JSON.stringify(e)??"null")}var $n=class{filling=new Map;async get(t){try{let n=await le.cache.getCacheEntry({query:{key:t}});return n.data.found?n.data.value??null:null}catch(n){if(!kn(n))throw n;return E.warn("cache: a read could not reach the cache; it is a miss",{key:t,status:n.status}),null}}async set(t,n,r){try{await le.cache.putCacheEntry({query:{key:t},body:{value:as(n),ttl:os(r)}})}catch(s){if(!kn(s))throw s;E.warn("cache: a write could not reach the cache; it is let go",{key:t,status:s.status})}}async del(t){await le.cache.deleteCacheEntry({query:{key:t}})}async incr(t){return(await le.cache.incrementCacheEntry({query:{key:t}})).data.value}getOrSet(t,n,r){let s=this.filling.get(t);if(s)return s;let o=(async()=>{try{let a;try{a=(await le.cache.getCacheEntry({query:{key:t}})).data}catch(c){if(!kn(c))throw c;E.warn("cache: a read could not reach the cache; the value is computed",{key:t,status:c.status})}if(a?.found)return a.value??null;let i=await r();return await this.set(t,i,n),i}finally{this.filling.delete(t)}})();return this.filling.set(t,o),o}},nc=dt("Cache",new $n);function rc(e={}){let t=e.maxEntries??5e4,n=e.now??(()=>Date.now()),r=new Map,s=new Map,o=p=>{let y=r.get(p);if(y&&y.expiresAt<=n()){r.delete(p);return}return y},a=()=>{let p=n();for(let[k,R]of r)R.expiresAt<=p&&r.delete(k);if(r.size<t)return;let y=[...r.entries()].sort((k,R)=>k[1].expiresAt-R[1].expiresAt);for(let[k]of y.slice(0,Math.ceil(y.length/4)))r.delete(k)},i=async(p,y,k)=>{r.size>=t&&!r.has(p)&&a(),r.set(p,{value:as(y),expiresAt:n()+(os(k)??vn)*1e3})};return{get:async p=>{let y=o(p);return y?structuredClone(y.value):null},set:i,async del(p){r.delete(p)},async incr(p){let y=o(p),k=(typeof y?.value=="number"&&Number.isInteger(y.value)?y.value:0)+1;return r.set(p,{value:k,expiresAt:y?.expiresAt??n()+vn*1e3}),k},getOrSet(p,y,k){let R=o(p);if(R)return Promise.resolve(structuredClone(R.value));let U=s.get(p);if(U)return U;let I=(async()=>{try{let L=await k();return await i(p,L,y),L}finally{s.delete(p)}})();return s.set(p,I),I}}}export{jt as a,be as b,Oe as c,Ka as d,Ja as e,Wa as f,Va as g,Za as h,Qa as i,Ga as j,Ya as k,Xa as l,ei as m,ti as n,ni as o,ri as p,si as q,oi as r,ai as s,ii as t,di as u,ci as v,ui as w,li as x,fi as y,pi as z,M as A,mi as B,hi as C,ut as D,ki as E,vi as F,Oi as G,xi as H,Ai as I,Pi as J,Ci as K,Mi as L,Di as M,Ii as N,zi as O,qi as P,Ji as Q,Wi as R,Gi as S,J as T,kr as U,vr as V,$r as W,bo as X,od as Y,dd as Z,cd as _,ud as $,ld as aa,fd as ba,pd as ca,md as da,hd as ea,Td as fa,ga,Yd as ha,vn as ia,nc as ja,rc as ka};
@@ -1,13 +0,0 @@
1
- /*! palbase 0.6.2 — Palbase SDK License (see LICENSE) */
2
- import{d as O}from"./SXH5AIQX.js";import{a as E,b as T,e as _}from"./IYCW6PWG.js";var a=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(n,t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="BackendError",this.kind=n,this.code=t.code,this.status=t.status??0,this.requestId=t.requestId,this.fields=t.fields,this.retryAfter=t.retryAfter,this.data=t.data}};function D(e){return e instanceof a||typeof e=="object"&&e!==null&&e.name==="BackendError"&&typeof e.kind=="string"}function $(e){let n=e.body,t={code:e.code,message:e.message,status:e.status,requestId:e.requestId??se(n,"request_id"),data:b(n,"data"),cause:e};if(e.code==="network_error")return new a("network",t);if(e.status===401)return new a("unauthorized",t);if(e.status===429)return new a("rateLimited",{...t,retryAfter:oe(n)??e.retryAfter});let r=re(n);return e.status===400&&r?new a("validation",{...t,fields:r}):new a("server",t)}function P(e){return e instanceof T||e instanceof Error&&e.name==="PalbaseError"}function j(e){return Array.isArray(e)&&e.length>0&&e.every(n=>typeof n=="object"&&n!==null&&typeof n.field=="string"&&typeof n.message=="string")}function re(e){let n=b(b(e,"data"),"fields");if(j(n))return n;let t=b(e,"fields");return j(t)?t:void 0}function oe(e){return N(e,"retry_after")??N(b(e,"data"),"retryAfter")}function b(e,n){if(typeof e=="object"&&e!==null)return e[n]}function N(e,n){let t=b(e,n);return typeof t=="number"?t:void 0}function se(e,n){let t=b(e,n);return typeof t=="string"?t:void 0}var ie=/^[A-Za-z_$][A-Za-z0-9_$]*$/,ae=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),ce=new Set(ae),de=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function S(e){return e==="then"||e==="toJSON"||de.has(e)}function A(e){return e==="call"||e==="join"||S(e)}function C(e){return typeof e=="string"&&ie.test(e)&&!ce.has(e)&&!S(e)}function B(e){return typeof e=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(e)}function I(e){_(e)}function J(e){return _(e).origin}var R=class extends Error{reason;constructor(n,t){super(n),this.name="RoomError",this.reason=t}},q=new WeakMap;async function U(e,n,t){let{pattern:r,events:o,messages:s}=pe(n),i=ue(r,t),c=q.get(e);c||q.set(e,c=new Map);let p=c;p.set(i,(p.get(i)??0)+1);let u=e.channel(i),l=()=>{let d=(p.get(i)??1)-1;d>0?p.set(i,d):(p.delete(i),u.leave())};try{await u.join()}catch{let d=u.state==="refused"?K(u.refusal,"unavailable"):"socket closed";throw l(),new R(`room ${JSON.stringify(i)} was not joined: ${d}`,d)}let m=!1,w=new Set,k=()=>{if(!m){m=!0,h();for(let d of[...w])d();l()}},h=u.onClosed(k),y=d=>{if(m)return()=>{};let v=u.on("broadcast",f=>{typeof f.event=="string"&&o.has(f.event)&&d(f.event,E(f.payload))}),g=()=>{w.delete(g),v()};return w.add(g),g};return{topic:i,on(d,v){if(typeof d=="function")return y((g,f)=>d({event:g,payload:f}));if(!o.has(d))throw new TypeError(`room ${JSON.stringify(r)} declares no event ${JSON.stringify(String(d))}`);if(typeof v!="function")throw new TypeError(`room ${JSON.stringify(r)}: on(${JSON.stringify(d)}, \u2026) takes the function the event is handed to`);return y((g,f)=>{g===d&&v(f)})},off(d){w.has(d)&&d()},async send(d,v){if(!s.has(d))throw new TypeError(`room ${JSON.stringify(r)} declares no message ${JSON.stringify(String(d))}`);let g=m?{status:"error",response:{reason:"not joined"}}:await u.push("broadcast",{type:"broadcast",event:d,payload:v});if(g.status==="ok")return;let f=K(g.response,"unavailable");throw new R(`room ${JSON.stringify(i)} did not take ${JSON.stringify(d)}: ${f}`,f)},leave:k}}function pe(e){let n=typeof e=="object"&&e!==null?e:{},t=r=>Array.isArray(r)&&r.every(o=>typeof o=="string");if(typeof n.pattern!="string"||n.pattern===""||!t(n.events)||!t(n.messages))throw new TypeError("join takes a room of the backend's generated module: its pattern, its events and its messages");return{pattern:n.pattern,events:new Set(n.events),messages:new Set(n.messages)}}function ue(e,n){let t=typeof n=="object"&&n!==null?n:{};return e.split(":").map(r=>{if(!(r.startsWith("{")&&r.endsWith("}")&&r.length>2))return r;let o=r.slice(1,-1),s=Object.hasOwn(t,o)?t[o]:void 0;if(typeof s!="string"||s==="")throw new TypeError(`room ${JSON.stringify(e)} needs a value for ${JSON.stringify(o)}`);if(s.includes(":"))throw new TypeError(`room ${JSON.stringify(e)}: the value of ${JSON.stringify(o)} is one segment of the channel's name and cannot hold ":"`);return s}).join(":")}function K(e,n){let t=e?.reason;return typeof t=="string"&&t!==""?t:n}var x=class{pending="";dataLines=[];eventName;consume(n){this.pending+=n.replace(/\r\n/g,`
3
- `);let t=[],r=this.pending.indexOf(`
4
- `);for(;r!==-1;){let o=this.pending.slice(0,r);this.pending=this.pending.slice(r+1);let s=o.endsWith("\r")?o.slice(0,-1):o;if(s==="")this.dataLines.length>0&&t.push({event:this.eventName,payload:this.dataLines.join(`
5
- `)}),this.dataLines=[],this.eventName=void 0;else if(!s.startsWith(":")){if(s.startsWith("data:")){let i=s.slice(5);this.dataLines.push(i.startsWith(" ")?i.slice(1):i)}else if(s.startsWith("event:")){let i=s.slice(6);this.eventName=i.startsWith(" ")?i.slice(1):i}}r=this.pending.indexOf(`
6
- `)}return t}};async function*M(e,n){let t=e.getReader(),r=new TextDecoder,o=new x;try{for(;;){let{done:s,value:i}=await t.read();if(s)break;for(let c of o.consume(r.decode(i,{stream:!0}))){if(c.event==="error")throw new a("network",{code:"stream_failed",message:`stream failed: ${c.payload}`});let p;try{p=JSON.parse(c.payload)}catch{throw new a("decode",{code:"invalid_frame",message:`stream frame is not valid JSON: ${c.payload.slice(0,120)}`})}yield E(p)}}}finally{n.abort();try{await t.cancel()}catch{}}}var le={},W=new WeakMap;function Ke(e,n,t,r,o){W.set(e,{project:n,machine:t,storage:r,socket:o})}var L=new Map,F=new WeakMap;function Ue(e,n,t,r,o){if(!C(n))throw new a("validation",{code:"reserved_namespace",message:`Cannot register backend ${JSON.stringify(String(n))}: a backend's name is an identifier the client does not keep.`});let s=J(e);if(!B(t))throw new TypeError(`${JSON.stringify(String(t))} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);I(r),H(o);for(let i of Object.keys(o))if(A(i))throw z(i);(L.get(n)??fe(n)).set(s,{machine:t,url:r,tree:o})}function fe(e){let n=new Map;return L.set(e,n),Object.defineProperty(le,e,{configurable:!0,get(){return me(this,e,n)}}),n}function me(e,n,t){let r=W.get(e);if(!r)return;let o=t.get(r.project);if(!o)throw new TypeError(`pb.${n} is the backend of ${[...t.keys()].join(" and ")}: this client is ${r.project}'s, and its user's session never goes to another project's machine`);let s=F.get(e);s||F.set(e,s=new Map);let i=s.get(n);if(i?.registration===o)return i.ns;let c={machine:()=>r.machine(o.url),storage:r.storage,name:o.machine},p=Object.assign({call:(u,l,m)=>ve(c.machine,u,l,m),join:(u,l)=>U(r.socket,u,l)},V(o.tree,c));return s.set(n,{registration:o,ns:p}),p}function z(e){return new a("validation",{code:"reserved_namespace",message:`Cannot register endpoint namespace ${JSON.stringify(e)}: the name is reserved.`})}function G(e){return typeof e.path=="string"&&typeof e.method=="string"}function ge(e,n){if(e.pathParams!==void 0){if(!Array.isArray(e.pathParams)||!e.pathParams.every(t=>typeof t=="string"))throw new a("validation",{code:"invalid_namespace_tree",message:`Descriptor '${n}': pathParams must be an array of strings.`});for(let t of e.pathParams)if(!e.path.includes(`{${t}}`))throw new a("validation",{code:"invalid_namespace_tree",message:`Descriptor '${n}': pathParams entry '${t}' has no '{${t}}' placeholder in the path.`})}if(e.sse!==void 0&&typeof e.sse!="boolean")throw new a("validation",{code:"invalid_namespace_tree",message:`Descriptor '${n}': sse must be a boolean.`});if(e.idempotent!==void 0&&typeof e.idempotent!="boolean")throw new a("validation",{code:"invalid_namespace_tree",message:`Descriptor '${n}': idempotent must be a boolean.`});if(e.upload!==void 0&&typeof e.upload!="boolean")throw new a("validation",{code:"invalid_namespace_tree",message:`Descriptor '${n}': upload must be a boolean.`});if(e.upload===!0&&(e.method!=="POST"||e.sse===!0))throw new a("validation",{code:"invalid_namespace_tree",message:`Descriptor '${n}': an upload endpoint is a POST, and no stream.`});if(e.sse===!0&&e.input==="query")throw new a("validation",{code:"invalid_namespace_tree",message:`Descriptor '${n}': an sse endpoint cannot take query input.`});if(e.input!==void 0&&e.input!=="body"&&e.input!=="query"&&e.input!=="none")throw new a("validation",{code:"invalid_namespace_tree",message:`Descriptor '${n}': input must be 'body', 'query' or 'none'.`});if(e.errors!==void 0){for(let[t,r]of Object.entries(e.errors))if(typeof r!="function")throw new a("validation",{code:"invalid_namespace_tree",message:`Descriptor '${n}': errors['${t}'] must be a function.`})}}function H(e){if(typeof e!="object"||e===null)throw new a("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new a("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});for(let[t,r]of Object.entries(e)){if(S(t))throw z(t);typeof r=="object"&&r!==null&&G(r)?(r.method=r.method.toUpperCase(),ge(r,r.path)):H(r)}}function V(e,n){if(G(e))return e.upload===!0?async(...r)=>be(n,e,r):async(...r)=>Z(n.machine(),e,r);let t={};for(let[r,o]of Object.entries(e))t[r]=V(o,n);return t}function Q(e){if(e==null)return"";let n=Object.entries(e).filter(([,r])=>r!=null).sort(([r],[o])=>r<o?-1:r>o?1:0);return n.length===0?"":`?${n.map(([r,o])=>{if(typeof o!="string"&&typeof o!="number"&&typeof o!="boolean")throw new a("validation",{code:"invalid_query_value",message:`Query parameter '${r}' must be a string, number, or boolean.`});return`${encodeURIComponent(r)}=${encodeURIComponent(String(o))}`}).join("&")}`}function he(e,n,t){let r=String(t);if(r===""||r==="."||r==="..")throw new a("validation",{code:"invalid_path_parameter",message:`${e.path}: path parameter '${n}' cannot be ${r===""?"empty":JSON.stringify(r)}`});return encodeURIComponent(r)}function Y(e,n){let t=e.pathParams??[],r=e.path;for(let o=0;o<t.length;o++){let s=n[o];if(typeof s!="string"&&typeof s!="number")throw new a("validation",{code:"missing_path_param",message:`${e.path}: path parameter '${t[o]}' must be a string or number`});r=r.replace(`{${t[o]}}`,he(e,t[o],s))}return r}var ye=new Set(["POST","PUT","PATCH","DELETE"]);async function Z(e,n,t){let r=n.pathParams??[],o=Y(n,t);if(n.input==="none"&&t.length>r.length+1)throw new a("validation",{code:"unexpected_argument",message:`${n.path}: endpoint takes no input \u2014 pass only path params and options`});let s=n.input==="none"?void 0:t[r.length],i=n.input==="none"?r.length:r.length+1,c=t[i],p;if(n.input==="query")o+=Q(s);else if(n.input!=="none")if(n.method==="GET"){if(s!==void 0)throw new a("validation",{code:"unsupported_get_input",message:`${n.path}: GET endpoints take no body input`})}else p=s;let u={...c?.headers};ye.has(n.method)&&!Object.keys(u).some(l=>l.toLowerCase()==="idempotency-key")&&(u["Idempotency-Key"]=O());try{return n.sse===!0?await Re(e,n,o,p,u,c?.signal):await Se(e,n,o,p,u,c?.signal)}catch(l){throw X(n,l)}}function X(e,n){return e.errors&&D(n)&&Object.hasOwn(e.errors,n.code)?e.errors[n.code](n):n}var we=[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]];async function be(e,n,t){let r=n.pathParams??[],o=Y(n,t),s=n.input==="none"?r.length:r.length+1;if(t.length>s+2)throw new a("validation",{code:"unexpected_argument",message:`${n.path}: an upload takes its path params, ${n.input==="none"?"":"its input, "}the file and options`});let i=n.input==="none"?void 0:t[r.length],c=t[s],p=t[s+1];if(!(c instanceof Blob))throw new a("validation",{code:"invalid_file",message:`${n.path}: the file is a Blob (a File is one)`});let u=`/storage/upload/${e.name}/${encodeURIComponent(o.slice(1))}`;n.input==="query"&&(u+=Q(i));let l=ke(n.input==="query"?void 0:i,c),m=l.body.size,w=0,k=h=>{w=h;try{p?.onProgress?.({loaded:h,total:m})}catch{}};p?.onProgress&&k(0);try{let h;try{let y={op:`Upload ${n.path}`,method:"POST",path:u,auth:we,answers:ee,body:{kind:"raw",contentType:l.type,value:l.body},signal:p?.signal,...p?.onProgress?{onUploadProgress:d=>k(d)}:{}};h=(await e.storage.send(y)).data}catch(y){throw P(y)?$(y):y}return p?.onProgress&&w<m&&k(m),await te(n,h,p?.signal)}catch(h){throw X(n,h)}}function ke(e,n){let t=`Palbase-${O()}`,r=c=>c.replaceAll('"',"_").replace(/[\r\n]/g,""),o=typeof n.name=="string"?n.name:"blob",s=(c,p)=>`--${t}\r
7
- Content-Disposition: form-data; ${c}\r
8
- Content-Type: ${p}\r
9
- \r
10
- `,i=[];return e!==void 0&&i.push(s('name="body"',"application/json"),JSON.stringify(e),`\r
11
- `),i.push(s(`name="file"; filename="${r(o)}"`,r(n.type)||"application/octet-stream"),n,`\r
12
- --${t}--\r
13
- `),{body:new Blob(i),type:`multipart/form-data; boundary=${t}`}}async function ve(e,n,t,r){if(typeof n!="string"||n===""||n==="/")throw new a("validation",{code:"invalid_endpoint_name",message:'Endpoint name must be a non-empty path like "todos/create"'});let o=n.startsWith("/")?n:`/${n}`;return Z(e(),{method:"POST",path:o},[t,r])}var ee=Object.fromEntries(Array.from({length:100},(e,n)=>[200+n,"raw"])),Ee=[["userJWT"],[]];async function ne(e,n,t,r,o,s){let i={op:`${n.method} ${n.path}`,method:n.method,path:t,auth:Ee,answers:ee,headers:o,...r===void 0?{}:{body:{kind:"json",contentType:"application/json",value:r}},idempotent:n.idempotent===!0,signal:s};try{return(await e.send(i)).data}catch(c){throw P(c)?$(c):c}}async function Se(e,n,t,r,o,s){return te(n,await ne(e,n,t,r,o,s),s)}async function te(e,n,t){let r=n.headers.get("x-request-id")??void 0,o;try{o=await n.text()}catch(s){throw t?.aborted?s:new a("network",{code:"network_error",message:`${e.method} ${e.path}: the answer did not arrive whole`,status:n.status,requestId:r,cause:s})}if(o!=="")try{return E(JSON.parse(o))}catch(s){throw new a("decode",{code:"invalid_json",message:`${e.method} ${e.path}: the answer is not JSON`,status:n.status,requestId:r,cause:s})}}async function Re(e,n,t,r,o,s){let i=new AbortController;s&&(s.aborted?i.abort():s.addEventListener("abort",()=>i.abort(),{once:!0}));let c=await ne(e,n,t,r,{accept:"text/event-stream",...o},i.signal);if(!c.body)throw new a("network",{code:"empty_stream",message:"the server answered a streaming route with no body",status:c.status});return M(c.body,i)}export{a,D as b,ae as c,C as d,R as e,le as f,Ke as g,Ue as h};
@@ -1,2 +0,0 @@
1
- /*! palbase 0.6.2 — Palbase SDK License (see LICENSE) */
2
- import{a as g,b}from"./KLANM6M6.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=v(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=E(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await U(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status];if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await P(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function U(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:$(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function $(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function v(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function E(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+O(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!e.secretKey;case"userJWT":return!!a;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function O(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function P(t,e){let n=await _(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=B(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function _(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function B(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,v as e,R as f};
@@ -1,2 +0,0 @@
1
- /*! palbase 0.6.2 — Palbase SDK License (see LICENSE) */
2
- import{f as W,g as X}from"./IVEAUFGE.js";import{u as Y}from"./GVFZM4BI.js";import{c as k,e as j,f as p,g as z,h as D}from"./2RG3I7LX.js";import{a as B,b as U,c as m,h as H}from"./A76UZBAF.js";import{a as G,b as S,c as J}from"./SXH5AIQX.js";import{b as f,d as b}from"./IYCW6PWG.js";var y=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function Q(){let i=null;return{load:()=>i,save:e=>{i=e},clear:()=>{i=null},shared:!1}}function Z(i){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let n=s()?.getItem(i);return n==null?t?null:e:JSON.parse(n)}catch{return e}},save(n){e=n;try{let r=s();if(!r)throw new Error("no storage");r.setItem(i,JSON.stringify(n)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(i)}catch{}},watch(n){let r=globalThis;if(typeof r.addEventListener!="function")return()=>{};let o=a=>{(a.key===i||a.key===null)&&n()};return r.addEventListener("storage",o),()=>r.removeEventListener?.("storage",o)}}}function he(i){try{let e=i.split(".")[1]??"",t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),s=JSON.parse(t).sub;return typeof s=="string"?s:""}catch{return""}}var de=6e4,ue=15e3;function pe(i,e,t){let s=i?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var T=class{current=null;loaded;inflight=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,n={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=n.now??Date.now,this.lockName=n.lockName??"palbase.session.refresh",this.refreshTimeoutMs=n.refreshTimeoutMs??ue,this.mode=n.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(r=>{this.current=r}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let n=t==="TOKEN_REFRESHED"?this.current:null,r={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??n?.userId??he(e.access_token),user:s??n?.user};return this.current=r,await this.store.save(r),this.emit(t,r),r}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e){await this.loaded;let t=this.current;this.current=null,this.inflight=null;let s=await this.store.load();(!s||!t||s.userId===t.userId)&&await this.store.clear(),t&&this.emit(e,null)}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>de)return e.accessToken;if(this.mode==="never")return t>0?e.accessToken:void 0;if(t>0&&this.mode==="behind")return this.refresh().catch(()=>{}),e.accessToken;if(t>0)try{return(await this.refresh()).accessToken}catch(s){if(this.current===e)return e.accessToken;throw s}return(await this.refresh()).accessToken}refresh(){if(this.mode==="never")return Promise.reject(new Error("this client does not renew its session (refresh: 'never'): where the session cannot be written back, the request's middleware renews it"));if(this.inflight)return this.inflight;let e=pe(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new y("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let n=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new y("the session changed while it was refreshed");return await this.set(n,"TOKEN_REFRESHED")}catch(n){throw this.isRejected(n)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED"),n}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new y("signed out in another tab");if(t.userId!==e.userId)throw this.current=t,this.emit("SIGNED_OUT",null),this.emit("SIGNED_IN",t),new y("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((n,r)=>{t=setTimeout(()=>r(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){for(let s of this.listeners)try{s(e,t)}catch{}}};var q=class{state="closed";refusal;joinRef=null;listeners=new Map;closers=new Set;joinWaiters=[];name;socket;constructor(e,t){this.name=e,this.socket=t}get topic(){return`realtime:${this.name}`}join(){if(this.state==="joined")return Promise.resolve();let e=new Promise((t,s)=>this.joinWaiters.push({resolve:t,reject:s}));return this.state!=="joining"&&this.socket.join(this),e}leave(){this.socket.leave(this)}push(e,t){return this.socket.request(this,e,t)}on(e,t){let s=this.listeners.get(e);return s||this.listeners.set(e,s=new Set),s.add(t),()=>s.delete(t)}onClosed(e){return this.closers.add(e),()=>this.closers.delete(e)}deliver(e,t){for(let s of this.listeners.get(e)??[])try{s(t)}catch{}}settled(e,t){this.state=e?"joined":"refused",this.refusal=e?void 0:t;let s=this.joinWaiters.splice(0);for(let n of s)e?n.resolve():n.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`))}closed(e){this.state="closed",this.joinRef=null;let t=this.joinWaiters.splice(0);for(let s of t)s.reject(new Error(`join ${this.name}: ${e}`));for(let s of[...this.closers])try{s()}catch{}}},P=class{ws=null;opening=null;ref=0;channels=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;reconnects=0;opts;constructor(e){this.opts=e}channel(e){let t=this.channels.get(e);return t||this.channels.set(e,t=new q(e,this)),t}disconnect(){this.closedByUs=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.closed("the socket was closed")}async tokenChanged(){if(!this.ws||this.ws.readyState!==1)return;let e=await this.opts.accessToken();if(e)for(let t of this.channels.values())t.state==="joined"&&this.push(t.joinRef,t.topic,"access_token",{access_token:e})}join(e){e.state="joining",this.open().then(()=>this.sendJoin(e)).catch(t=>e.settled(!1,{reason:t instanceof Error?t.message:String(t)}))}leave(e){e.state==="joined"&&this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let n=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||n?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let r=this.nextRef(),o=JSON.stringify([e.joinRef,r,e.topic,t,s]),a=this.awaitReply(r);return n.send(o),a}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1;let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((n,r)=>{let o=new e(t);this.ws=o,o.onopen=()=>{this.attempts=0,this.startHeartbeat(),n()},o.onmessage=a=>this.receive(String(a.data)),o.onerror=()=>r(new Error("the realtime socket could not be opened")),o.onclose=()=>this.dropped(o)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,this.stopHeartbeat();for(let[,n]of this.replies)n("error",{reason:"socket closed"});this.replies.clear();for(let n of this.channels.values())n.state==="joined"&&(n.state="joining");if(this.closedByUs||![...this.channels.values()].some(n=>n.state==="joining"))return;let t=this.opts.backoff??[500,1e3,2e3,5e3,1e4,3e4],s=t[Math.min(this.attempts,t.length-1)]*(.8+Math.random()*.4);this.attempts++,this.reconnectTimer=_(setTimeout(()=>{this.reconnectTimer=null,this.reconnects++;let n=[...this.channels.values()].filter(r=>r.state==="joining");this.open().then(()=>Promise.all(n.map(r=>this.sendJoin(r)))).catch(()=>{})},s))}async sendJoin(e){let t=await this.opts.accessToken(),s=this.nextRef();e.joinRef=s;let n=this.awaitReply(s);this.push(s,e.topic,"phx_join",{access_token:t,config:{broadcast:{self:!1}}},s);let{status:r,response:o}=await n;if(this.channels.get(e.name)!==e||e.state!=="joining"){r==="ok"&&this.ws?.readyState===1&&this.push(s,e.topic,"phx_leave",{});return}e.settled(r==="ok",o)}awaitReply(e){return new Promise(t=>{let s=_(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(n,r)=>{clearTimeout(s),this.replies.delete(e),t({status:n,response:r})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[,s,n,r,o]=t,a=typeof o=="object"&&o!==null?o:{};if(r==="phx_reply"&&typeof s=="string"){if(s===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(s)?.(String(a.status),a.response??{});return}let l=[...this.channels.values()].find(c=>c.topic===n);if(l){if(r==="phx_close"){l.state="closed";return}if(r==="phx_error"){l.state="joining",_(setTimeout(()=>this.channels.get(l.name)===l&&l.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(l),1e3));return}l.deliver(r,a)}}push(e,t,s,n,r=this.nextRef()){this.ws?.send(JSON.stringify([e,r,t,s,n]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=_(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null,this.ws?.close(4e3);return}this.heartbeatRef=this.nextRef(),this.push(null,"phoenix","heartbeat",{},this.heartbeatRef)},this.opts.heartbeatMs??25e3))}stopHeartbeat(){this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.heartbeatRef=null}};function _(i){return i.unref?.(),i}var ge=30*6e4,ee=1e3,ye=100,me=60*1024,I=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function R(){try{return globalThis.localStorage}catch{return}}var C=class{api;closingApi;flushMs;flushAt;now;anonKey;sessionKey;events=[];samples=[];timer;memoryAnon;memorySession;appVersion;stopAuto;session;identifyPending=!1;constructor(e,t,s,n={}){this.session=t,this.api=U.client(e),this.closingApi=U.client({send:r=>e.send({...r,keepalive:!0})}),this.flushMs=n.flushMs??5e3,this.flushAt=n.flushAt??20,this.now=n.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${s}`,this.sessionKey=`palbase.analytics.session.${s}`,t.onChange(r=>{r==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):r==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())})}capture(e,t){let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}page(e={}){let t=globalThis.location,s=globalThis.document,n=e.url??(t?`${t.origin}${t.pathname}`:"");if(!n)return;let r=e.referrer??ke(s?.referrer);this.capture("$pageview",{...e.properties,url:n,...e.title??s?.title?{title:e.title??s?.title}:{},...r?{referrer:r}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;t&&(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0;try{R()?.removeItem(this.anonKey),R()?.removeItem(this.sessionKey)}catch{}}async flush(e=!1){this.timer&&clearTimeout(this.timer),this.timer=void 0;let t=e?this.closingApi:this.api,s=this.now(),n=this.session.snapshot()?.userId;for(this.identifyPending&&n&&(this.identifyPending=!1,await this.sendIdentify(t,n));this.events.length>0;){let r=this.take(this.events,e);try{await t.batch({body:{events:r.map(o=>({...o,sent_at:s}))}})}catch{}}for(;this.samples.length>0;){let r=this.take(this.samples,e);try{await t.sendPerf({body:{items:r}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push(be((o,a)=>this.sample("web_vital",o,a))),e.network!==!1&&s.push(this.watchFetch(t));let n=()=>{document.visibilityState==="hidden"&&this.flush(!0)},r=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",n),t.addEventListener("pagehide",r),s.push(()=>{document.removeEventListener("visibilitychange",n),t.removeEventListener("pagehide",r)}),this.stopAuto=()=>{for(let o of s.splice(0))o();this.stopAuto=void 0},this.stopAuto}hold(e){this.events.length>=ee&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,n={}){this.samples.length>=ee&&this.samples.shift(),this.samples.push({row_id:I(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),distinct_id:this.distinctId(),...n}),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,ye);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>me;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=R();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${I()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${I()}`,this.memoryAnon}sessionId(e){let t=R(),s=this.memorySession;try{let r=t?.getItem(this.sessionKey);r&&(s=JSON.parse(r))}catch{}let n=s&&e-s.last<ge?{id:s.id,last:e}:{id:`ses_${I()}`,last:e};this.memorySession=n;try{t?.setItem(this.sessionKey,JSON.stringify(n))}catch{}return n.id}watchPages(e){let t="",s=()=>{let a=`${e.location.origin}${e.location.pathname}`;a!==t&&(t=a,setTimeout(()=>this.page({url:a}),0))},n=e.history,r=n.pushState.bind(n),o=n.replaceState.bind(n);return n.pushState=(...a)=>{r(...a),s()},n.replaceState=(...a)=>{o(...a),s()},e.addEventListener("popstate",s),s(),()=>{n.pushState=r,n.replaceState=o,e.removeEventListener("popstate",s)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(n,r)=>{let o=performance.now(),a=n instanceof Request?n:void 0,l=(r?.method??a?.method??"GET").toUpperCase(),c;try{c=new URL(a?.url??String(n),e.location.href)}catch{c=void 0}let h=!!c&&c.pathname.startsWith("/analytics/")||Se(r?.headers??a?.headers);try{let u=await t(n,r);return c&&!h&&this.sample("network",`${l} ${c.origin}${c.pathname}`,performance.now()-o,{attrs:{status:String(u.status)},...u.headers.get("x-request-id")?{request_id:u.headers.get("x-request-id")}:{}}),u}catch(u){throw c&&!h&&this.sample("network",`${l} ${c.origin}${c.pathname}`,performance.now()-o,{attrs:{status:"0"}}),u}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}},ve=i=>i.entryType==="layout-shift"&&"value"in i&&"hadRecentInput"in i,we=i=>i.entryType==="event"||i.entryType==="first-input";function E(i,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:i,buffered:!0}),t}catch{return}}function be(i){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,n=[E("largest-contentful-paint",c=>{for(let h of c)e=Math.max(e,h.startTime)}),E("layout-shift",c=>{for(let h of c)ve(h)&&!h.hadRecentInput&&(t+=h.value)}),E("event",c=>{for(let h of c)we(h)&&(s=Math.max(s,h.duration))}),E("paint",c=>{for(let h of c)h.name==="first-contentful-paint"&&i("FCP",h.startTime)})],r=performance.getEntriesByType("navigation")[0];r&&r.responseStart>0&&i("TTFB",r.responseStart);let o=!1,a=()=>{o||(o=!0,e>0&&i("LCP",e),i("CLS",t),s>0&&i("INP",s))},l=()=>{document.visibilityState==="hidden"&&a()};return document.addEventListener("visibilitychange",l),()=>{a(),document.removeEventListener("visibilitychange",l);for(let c of n)c?.disconnect()}}function Se(i){if(!i)return!1;try{return new Headers(i).has("next-router-prefetch")}catch{return!1}}function ke(i){if(!i)return"";try{let e=new URL(i);return`${e.origin}${e.pathname}`}catch{return i.split(/[?#]/,1)[0]??""}}var x=class{api;session;socket;ref;fetch;appVersion;app;listeners=new Set;watch;following;last;constructor(e,t,s,n,r,o,a){this.api=H.client(e),this.session=t,this.socket=s,this.ref=n,this.fetch=r,this.appVersion=o,this.app=a}async me(){let e=this.session.snapshot()?.userId,t=(await this.api.getMyCustomerInfo()).data;return this.watch&&this.watch.userId===e&&this.offer(this.watch,t),t}async offerings(e="web"){return(await this.api.getOfferings({query:{channel:e}})).data}async paywall(e,t={}){return Y(this.api,this.ref,e,s=>this.checkout(s),{signal:t.signal,fetch:this.fetch,attributes:t.attributes,locale:t.locale,appVersion:this.appVersion,app:this.app})}async checkout(e){let t={product:e.product,plan:e.plan,success_url:e.successUrl,cancel_url:e.cancelUrl};return(await this.api.createCheckout({body:t})).data.url}async portal(e){return(await this.api.createPortalSession({body:{return_url:e}})).data.url}async mergeGrant(){return(await this.api.createMergeGrant()).data}async merge(e){let t=this.session.snapshot()?.userId,s=(await this.api.mergeGuest({body:{grant:typeof e=="string"?e:e.grant}})).data;return this.watch&&this.watch.userId===t&&this.offer(this.watch,s),s}onCustomerInfo(e){if(this.listeners.add(e),this.listeners.size===1)this.start();else if(this.last!==void 0){let t=this.last;queueMicrotask(()=>this.listeners.has(e)&&te(e,t))}return()=>{this.listeners.delete(e)&&this.listeners.size===0&&this.stop()}}start(){this.following=this.session.onChange((e,t)=>{(e==="SIGNED_IN"||e==="SIGNED_OUT"||e==="SESSION_EXPIRED")&&this.follow(t)}),this.session.session().then(e=>{this.following&&!this.watch&&this.last===void 0&&this.follow(e)})}stop(){this.following?.(),this.following=void 0,this.unfollow(),this.last=void 0}follow(e){if(this.unfollow(),!e){this.tell(null);return}let t=this.socket.channel(`purchases:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},revision:-1,reading:!1,wanted:Number.NEGATIVE_INFINITY},n=[t.on("broadcast",r=>{r.event==="changed"&&this.changed(s,K(r.payload))}),t.on("state_snapshot",r=>this.held(s,K(se(r.entries)))),t.on("state_diff",r=>this.held(s,K(se(r.set))))];s.off=()=>n.forEach(r=>r()),this.watch=s,t.join().catch(()=>{}),this.read(s)}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}changed(e,t){this.watch!==e||t!==void 0&&t<=e.revision||(e.reading?e.wanted=Math.max(e.wanted,t??Number.POSITIVE_INFINITY):this.read(e))}held(e,t){t!==void 0&&this.changed(e,t)}async read(e){e.reading=!0;try{for(;;){e.wanted=Number.NEGATIVE_INFINITY;try{let t=(await this.api.getMyCustomerInfo()).data;if(this.watch!==e)return;this.offer(e,t)}catch{}if(this.watch!==e||e.wanted<=e.revision)return}}finally{e.reading=!1}}offer(e,t){this.watch!==e||t.revision<=e.revision||(e.revision=t.revision,this.tell(t))}tell(e){if(!(this.last===null&&e===null)){this.last=e;for(let t of[...this.listeners])te(t,e)}}};function te(i,e){try{i(e)}catch{}}function se(i){let e=typeof i=="object"&&i!==null?i.revision:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function K(i){let e=typeof i=="object"&&i!==null?i.revision:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}function ne(){return"cm_"+crypto.randomUUID()}async function M(i,e=4){for(let t=1;;t++)try{return await i()}catch(s){if(t>=e||!(s instanceof f)||s.status===429)throw j(s);let n=J(s,t,30);if(n===void 0)throw j(s);await new Promise(r=>setTimeout(r,n*1e3))}}var V=class{id;api;session;options;status="idle";error=null;messages=new Map;responses=new Map;order=[];turn=null;calls=new Map;voiceParts=[];handlers=new Map;answering=new Set;listeners=new Set;following;position;snapshot;told=!1;constructor(e,t,s={},n){this.api=e,this.id=t,this.options=s,this.session=n,this.position={after:s.after??0}}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),this.follow(),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,t,s=this.subscribe(()=>e?.());try{for(;;){let n=this.state;if(n!==t){t=n,yield n;continue}if(this.status==="closed"||this.status==="failed")return;await new Promise(r=>e=r)}}finally{s()}}async send(e,t={}){let s=t.clientId??ne(),n=this.messages.get(s),r=n?{...n,status:"pending",error:null}:{clientId:s,id:null,text:e,author:this.session?.snapshot()?.userId??null,authorName:"",delivery:t.delivery??"next",status:"pending",error:null,responseId:null,createdAt:new Date().toISOString(),mine:!0};this.messages.set(s,r),n||this.order.push({type:"message",key:s}),this.changed(),this.follow();let o={client_id:s,text:r.text};t.delivery!==void 0&&(o.delivery=t.delivery);try{let a=await M(async()=>(await this.api.sendChatMessage({path:{chat_id:this.id},body:o})).data);this.heard(a,!0)}catch(a){let l=this.messages.get(s);throw l.status==="pending"&&(this.messages.set(s,{...l,status:"failed",error:a instanceof f?a.code:"send_failed"}),this.changed()),a}return this.messages.get(s)}tools(e){for(let[t,s]of Object.entries(e))this.handlers.set(t,s);this.follow();for(let t of this.calls.values())this.autoAnswer(t);return()=>{for(let[t,s]of Object.entries(e))this.handlers.get(t)===s&&this.handlers.delete(t)}}async answer(e,t,s={}){let n={output:D(t),is_error:s.isError===!0};this.answering.add(e);try{return await M(()=>this.api.answerChatToolCall({path:{chat_id:this.id,call_id:e},body:n})),!0}catch(r){if(r instanceof f&&r.status===409)return!1;throw this.answering.delete(e),r}}async approve(e,t){await p(this.api.decideChatApproval({path:{chat_id:this.id,approval_id:e},body:t===void 0?{approve:!0}:{approve:!0,reason:t}}))}async deny(e,t){await p(this.api.decideChatApproval({path:{chat_id:this.id,approval_id:e},body:t===void 0?{approve:!1}:{approve:!1,reason:t}}))}async stop(){return(await p(this.api.stopChat({path:{chat_id:this.id}}))).data.stopped}async startVoice(e){let t=new RTCPeerConnection,s=e.audio??(typeof Audio=="function"?new Audio:void 0);s&&(s.autoplay=!0),t.ontrack=n=>{s&&(s.srcObject=n.streams[0]??new MediaStream([n.track]))};for(let n of e.stream.getAudioTracks())t.addTrack(n,e.stream);try{let n=await t.createOffer();await t.setLocalDescription(n);let r=e.voice===void 0?{sdp:n.sdp??""}:{sdp:n.sdp??"",voice:e.voice},o=(await p(this.api.startChatVoice({path:{chat_id:this.id},body:r}))).data;await t.setRemoteDescription({type:"answer",sdp:o.sdp??""}),this.follow();let a=o.id;return{id:a,peer:t,stop:async()=>(t.close(),(await p(this.api.closeChatVoice({path:{chat_id:this.id,voice_id:a}}))).data.seconds)}}catch(n){throw t.close(),n}}async sendToSubagent(e,t){let s={client_id:ne(),text:t};await M(()=>this.api.sendSubagentMessage({path:{chat_id:this.id,run_id:e},body:s}))}close(){this.following?.abort(),this.following=void 0,this.status="closed",this.changed()}follow(){if(this.following||this.status==="closed")return;let e=new AbortController;this.following=e,this.status="connecting",this.error=null,this.changed();let t=z(async(s,n)=>{this.status!=="connecting"&&(this.status="connecting",this.changed());let r=(await this.api.followChat({path:{chat_id:this.id},query:s,signal:n})).data;return this.status="live",this.changed(),r},{...this.position,resumeFor:this.options.resumeFor,signal:e.signal});(async()=>{try{for await(let s of t)this.take(s)}catch(s){if(this.position=t.position,e.signal.aborted)return;this.status="failed",this.error=s,this.following=void 0,this.changed()}})()}take(e){switch(e.type){case"message":this.heard(e.message,!1);return;case"turn":{let t=this.response(e.response_id);t.status=e.status,t.waiting=e.waiting,t.error=e.error,e.user_id!==void 0&&(t.startedBy=e.user_id),typeof e.solo=="boolean"&&(t.solo=e.solo),this.turn=e;for(let s of this.calls.values())s.response_id===e.response_id&&this.autoAnswer(s);break}case"text":{let t=this.response(e.response_id);t.text=t.text.slice(0,k(t.text,e.offset))+e.text;break}case"reset":{let t=this.response(e.response_id);t.text=t.text.slice(0,k(t.text,e.offset));break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e),this.autoAnswer(e);break}case"voice":this.voiceParts.push(e);break;case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let t=this.response(e.response_id);if(t.runId=e.run_id,t.agent=e.name,t.parentId===null){t.parentId=e.parent_response_id;let s=this.order.findIndex(n=>n.type==="response"&&n.key===e.response_id);s>=0&&this.order.splice(s,1)}break}}this.changed()}heard(e,t){let s=this.messages.get(e.client_id),n=e.status==="delivered"||e.status==="failed"?e.status:"pending",r={clientId:e.client_id,id:e.id,text:e.text,author:e.author,authorName:e.author_name,delivery:e.delivery,status:s&&s.status==="delivered"&&t?"delivered":n,error:e.error,responseId:e.response_id??s?.responseId??null,createdAt:e.created_at,mine:s?.mine??!1};this.messages.set(e.client_id,r),s||this.order.push({type:"message",key:e.client_id}),this.changed()}response(e){let t=this.responses.get(e);return t||(t={id:e,status:null,waiting:null,error:null,text:"",marks:new Map,runId:null,agent:null,parentId:null,startedBy:void 0,solo:void 0},this.responses.set(e,t),this.order.push({type:"response",key:e})),t}autoAnswer(e){if(e.status!=="awaiting_output"||this.answering.has(e.call_id)||!this.mine(e.response_id)||this.responses.get(e.response_id)?.solo!==!0)return;let t=this.handlers.get(e.name);t&&(this.answering.add(e.call_id),(async()=>{let s;try{s={output:D(await t(e.input,e)),is_error:!1}}catch(n){s={output:[{type:"text",text:n instanceof Error?n.message||n.name:String(n)}],is_error:!0}}try{await M(()=>this.api.answerChatToolCall({path:{chat_id:this.id,call_id:e.call_id},body:s}))}catch(n){n instanceof f&&(n.status===409||n.status===403)||this.answering.delete(e.call_id)}})())}mine(e){let t=this.session?.snapshot()?.userId;return t!==void 0&&this.responses.get(e)?.startedBy===t}changed(){this.snapshot=void 0,!this.told&&(this.told=!0,queueMicrotask(()=>{this.told=!1;let e=this.state;for(let t of[...this.listeners])try{t(e)}catch{}}))}build(){let e=new Map;for(let n of this.responses.values()){let r=n.parentId!==null?this.responses.get(n.parentId)??n:n;e.set(n.id,Te(n,r.startedBy??null,this.mine(r.id),r.solo??null))}let t=[];for(let n of this.order)n.type==="message"?t.push({type:"message",message:this.messages.get(n.key)}):this.responses.get(n.key).parentId===null&&t.push({type:"response",response:e.get(n.key)});let s=[...this.calls.values()].filter(n=>this.mine(n.response_id));return{status:this.status,error:this.error,items:t,messages:[...this.messages.values()],responses:[...e.values()],turn:this.turn,waiting:{approvals:s.filter(n=>n.status==="awaiting_approval"),outputs:s.filter(n=>n.status==="awaiting_output")},voice:[...this.voiceParts]}}};function Te(i,e,t,s){let n=[...i.marks.values()].map((a,l)=>({m:a,i:l,at:k(i.text,Math.max(0,Number(a.text_offset)||0))}));n.sort((a,l)=>a.at-l.at||a.i-l.i);let r=[],o=0;for(let{m:a,at:l}of n)l>o&&r.push({type:"text",text:i.text.slice(o,l)}),o=Math.max(o,l),r.push(a.type==="tool"?{type:"tool",tool:a}:{type:"agent",agent:a});return o<i.text.length&&r.push({type:"text",text:i.text.slice(o)}),{id:i.id,status:i.status,waiting:i.waiting,error:i.error,text:i.text,parts:r,runId:i.runId,agent:i.agent,parentId:i.parentId,startedBy:e,mine:t,solo:s}}var A=class{api;session;chats;constructor(e,t){let s=B.client(e);this.api=s,this.session=t,this.chats={async create(n){let r={agent:n.agent};return n.name!==void 0&&(r.name=n.name),n.title!==void 0&&(r.title=n.title),(await p(s.createChat({body:r}))).data},async list(){return(await p(s.listChats({}))).data.chats},async get(n){return(await p(s.getChat({path:{chat_id:n}}))).data},async delete(n){await p(s.deleteChat({path:{chat_id:n}}))}}}chat(e,t={}){if(typeof e!="string"||e==="")throw new TypeError("pb.ai.chat(id): id is the chat's");return new V(this.api,e,t,this.session)}};var O=class{api;open;session;credentials;mfa;passkey;magicLink;phone;password;email;sessions;constructor(e,t,s,n){this.api=m.client(e),this.open=m.client(t),this.session=s,this.credentials=n;let r=this.api,o=this.open;this.mfa={challenge:async(a,l,c)=>this.signedIn((await o.mfaChallenge({body:{mfa_token:a,type:l,code:c}})).data),recovery:async(a,l)=>this.signedIn((await o.mfaRecovery({body:{mfa_token:a,code:l}})).data),sendSmsCode:async a=>{await o.mfaSmsChallenge({body:{mfa_token:a}})},sendEmailCode:async a=>{await o.mfaEmailChallenge({body:{mfa_token:a}})},enrollTotp:async()=>{let a=(await r.mfaEnroll({body:{type:"totp"}})).data;return{enrollmentId:a.enrollment_id,secret:a.secret,otpUrl:a.otp_url,qrCode:a.qr_code,recoveryCodes:a.recovery_codes}},verifyTotp:async a=>{await r.mfaVerifyEnrollment({body:{code:a}})},enrollSms:async a=>(await r.mfaSmsEnroll({body:{phone:a}})).data,verifySms:async a=>{await r.mfaSmsVerifyEnrollment({body:{code:a}})},enrollEmail:async()=>{await r.mfaEmailEnroll()},factors:async()=>(await r.mfaListFactors()).data,removeFactor:async(a,l)=>{await r.mfaRemoveFactor({path:{id:a},body:{current_password:l}})},regenerateRecoveryCodes:async()=>(await r.mfaRegenerateRecoveryCodes()).data},this.passkey={register:async a=>{let l=(await r.webauthnRegisterBegin({body:{name:a}})).data,c=await this.authenticator().create({publicKey:ie(l.options.publicKey)});return(await r.webauthnRegisterFinish({body:ae(c)})).data},signIn:async(a={})=>{let l=(await o.webauthnLoginBegin({body:a.userId?{user_id:a.userId}:{}})).data,c=await this.authenticator().get({publicKey:re(l.options.publicKey)}),h=await o.webauthnLoginFinish({query:a.userId?{user_id:a.userId}:void 0,body:oe(c)});return this.signedIn(h.data)},signUp:async(a,l)=>{let c=(await o.webauthnSignupBegin({body:{identifier:a,user_name:l}})).data,h=await this.authenticator().create({publicKey:ie(c.options.publicKey)});await o.webauthnSignupFinish({query:{user_id:c.user_id},body:ae(h)});let u=(await o.webauthnLoginBegin({body:{user_id:c.user_id}})).data,v=await this.authenticator().get({publicKey:re(u.options.publicKey)});return this.signedIn((await o.webauthnLoginFinish({query:{user_id:c.user_id},body:oe(v)})).data)},list:async()=>(await r.webauthnListCredentials()).data,remove:async a=>{await r.webauthnDeleteCredential({path:{id:a}})}},this.magicLink={send:async a=>{await o.magicLinkRequest({body:{email:a}})},verify:async a=>this.signedIn((await o.magicLinkVerify({body:{token:a}})).data)},this.phone={sendCode:async a=>(await o.requestPhoneOtp({body:{phone:a,channel:"sms"}})).data,verifyCode:async(a,l)=>this.signInResult((await o.verifyPhoneOtp({body:{phone:a,token:l}})).data)},this.password={requestReset:async a=>{await o.passwordResetRequest({body:{email:a}})},confirmReset:async(a,l)=>{await o.passwordResetConfirm({body:{token:a,new_password:l}})},change:async a=>(await r.passwordChange({body:a})).data,set:async a=>(await r.setPassword({body:a})).data},this.email={verify:async a=>{await o.verifyEmail({body:a})},resendVerification:async a=>(await o.resendVerification({body:{email:a}})).data},this.sessions={list:async()=>(await r.listSessions()).data,revoke:async a=>{await r.revokeSession({path:{id:a}})},revokeAll:async()=>{await r.revokeAllSessions()}}}onAuthStateChange(e){return this.session.onChange(e)}currentSession(){return this.session.session()}async signUp(e){let t=(await this.open.signup({body:e})).data;return t.access_token&&t.refresh_token&&t.expires_in!==void 0&&await this.session.set({access_token:t.access_token,refresh_token:t.refresh_token,expires_in:t.expires_in},"SIGNED_IN",t.user),t}async signIn(e,t){return this.signInResult((await this.open.login({body:{email:e,password:t}})).data)}async signOut(){try{await this.session.session()&&await this.api.logout()}finally{await this.session.clear("SIGNED_OUT")}}async getUser(){let e=this.session.snapshot(),t=(await this.api.getMe()).data;return await this.session.setUser(t,e),t}async refreshSession(){return this.session.refresh()}async deleteAccount(e){await this.api.deleteAccount(e===void 0?void 0:{body:{password:e}}),await this.session.clear("SIGNED_OUT")}async signInResult(e){return"mfa_required"in e&&e.mfa_required?{mfaRequired:{mfaToken:e.mfa_token,factors:e.factors}}:{user:await this.signedIn(e)}}async setSession(e){return this.signedIn(e)}async signedIn(e){let t=await this.session.set({access_token:e.access_token,refresh_token:e.refresh_token,expires_in:e.expires_in},"SIGNED_IN",e.user);if(e.user)return e.user;let s=(await this.api.verifyTokenUser()).data;return await this.session.setUser(s,t),s}authenticator(){if(!this.credentials)throw new Error("passkeys need navigator.credentials (or createClient({ webauthn }))");return this.credentials}},N=i=>{let e=atob(i.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(i.length/4)*4,"=")),t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t.buffer},g=i=>{if(!i)return;let e=i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength),t="";for(let s of e)t+=String.fromCharCode(s);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")},le=i=>Array.isArray(i)?i.map(e=>({...e,id:N(String(e.id))})):void 0;function ie(i){let e=i.user;return{...i,challenge:N(String(i.challenge)),user:{...e,id:N(String(e.id))},excludeCredentials:le(i.excludeCredentials)}}function re(i){return{...i,challenge:N(String(i.challenge)),allowCredentials:le(i.allowCredentials)}}function ae(i){let e=i,t=e.response;return{id:e.id,rawId:g(e.rawId),type:"public-key",authenticatorAttachment:e.authenticatorAttachment??void 0,clientExtensionResults:e.getClientExtensionResults?.()??{},response:{clientDataJSON:g(t.clientDataJSON),attestationObject:g(t.attestationObject),transports:t.getTransports?.()}}}function oe(i){let e=i,t=e.response;return{id:e.id,rawId:g(e.rawId),type:"public-key",authenticatorAttachment:e.authenticatorAttachment??void 0,clientExtensionResults:e.getClientExtensionResults?.()??{},response:{clientDataJSON:g(t.clientDataJSON),authenticatorData:g(t.authenticatorData),signature:g(t.signature),userHandle:g(t.userHandle)}}}var _e=/^pb_[a-z0-9]+_s/,Pe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ie=new Set(["invalid_token","token_expired","session_expired","session_revoked","missing_token"]),Re=new Set(["invalid_token","token_reuse","token_expired","session_revoked","session_expired","session_device_changed"]);function Ee(i){return i.status===400&&i.code==="invalid_request"}function et(i){if(_e.test(i.publishableKey)||"secretKey"in i)throw new TypeError("a secret key never goes into a client app: palbase/web takes the publishable key (pb_<ref>_c\u2026); servers use palbase/server");let e=/^pb_([a-z0-9]+)_c/.exec(i.publishableKey)?.[1];if(e===void 0)throw new TypeError("publishableKey is the project publishable key (pb_<ref>_c\u2026)");if(i.appId!==void 0&&!Pe.test(i.appId))throw new TypeError("appId is the registered app's id, a UUID (settings.appId of palbase apps:sync), not its slug");let t=new URL(i.url).origin,s=i.storage??(Ce()?Z(`palbase.session.${t}`):Q()),n=i.retry??G,r=S(b({baseUrl:i.url,credentials:{publishableKey:i.publishableKey},fetch:i.fetch}),n),o=m.client(r),a=new T(s,async d=>(await o.refreshToken({body:{refresh_token:d}})).data,d=>d instanceof f&&(d.status===401&&Re.has(d.code)||Ee(d)),{lockName:`palbase.session.refresh.${t}`,refresh:i.refresh}),l=b({baseUrl:i.url,credentials:{publishableKey:i.publishableKey,accessToken:()=>a.accessToken()},fetch:i.fetch,xmlHttpRequest:i.xmlHttpRequest??(i.fetch===void 0?globalThis.XMLHttpRequest:void 0)}),c=S(F(l,a),n),h=new P({baseUrl:i.url,publishableKey:i.publishableKey,accessToken:()=>a.accessToken(),webSocket:i.webSocket});a.onChange(d=>{d==="SIGNED_OUT"||d==="SESSION_EXPIRED"||d==="SIGNED_IN"?h.disconnect():d==="TOKEN_REFRESHED"&&h.tokenChanged()});let u=new C(F(l,a),a,t);i.analytics&&u.start(i.analytics===!0?{}:i.analytics);let v=new Map,ce=d=>{let L=new URL(d).origin,w=v.get(L);return w||(w=S(F(b({baseUrl:L,credentials:{accessToken:()=>a.accessToken()},fetch:i.fetch}),a),n),v.set(L,w)),w},$=Object.assign(Object.create(W),{auth:new O(c,r,a,i.webauthn??globalThis.navigator?.credentials),socket:h,transport:c,analytics:u,purchases:new x(c,a,h,e,i.fetch,i.appVersion,i.appId),ai:new A(c,a)});return X($,t,ce,c,h),$}function Ce(){try{return typeof globalThis.localStorage<"u"}catch{return!1}}function F(i,e){return{async send(t){let s=await e.session();try{return await i.send(t)}catch(n){let r=t.auth.some(o=>o.includes("userJWT"));if(!(n instanceof f)||n.status!==401||!Ie.has(n.code)||!r||!s)throw n;try{e.snapshot()?.refreshToken===s.refreshToken&&await e.refresh()}catch{throw n}if(e.snapshot()?.userId!==s.userId)throw n;return i.send(t)}}}}export{y as a,Q as b,Z as c,q as d,P as e,C as f,x as g,V as h,A as i,et as j};
@@ -1,2 +0,0 @@
1
- /*! palbase 0.6.2 — Palbase SDK License (see LICENSE) */
2
- import{a as D}from"./SUX2BJG4.js";import{a as P,b as R,c as b,d as x,e as O,f as j,g as M,h as C,i as U,j as L,k as K,l as N}from"./A76UZBAF.js";import{a as $,b as I}from"./SXH5AIQX.js";import{b as v,d as w}from"./IYCW6PWG.js";var ae=/^pb_[a-z0-9]+_s/;function E(n){if(D())throw new TypeError("palbase/server runs on a server: its secret key never goes into a browser or a mobile app \u2014 apps use palbase/web (or the native SDKs) with the publishable key");if(typeof n.secretKey!="string"||!ae.test(n.secretKey))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026); a publishable key belongs in palbase/web");let e=I(w({baseUrl:n.url,credentials:{secretKey:n.secretKey},fetch:n.fetch,solveProofOfWork:n.solveProofOfWork??!1}),n.retry??$);return{ai:P.client(e),analytics:R.client(e),auth:b.client(e),cache:x.client(e),flags:O.client(e),machines:j.client(e),notify:M.client(e),purchases:C.client(e),realtime:U.client(e),secrets:L.client(e),storage:K.client(e),stores:N.client(e),transport:e,url:new URL(n.url).origin}}var f=class extends Error{code;constructor(e,t){super(t),this.name="WebhookSignatureError",this.code=e}},ue=300,de=/^[0-9]{1,12}$/,le=/^[0-9a-f]{64}$/,W=8,fe=/^whsec_[0-9A-Za-z]{32,}$/,he=1024*1024;async function B(n){if(typeof n.secret!="string"||!fe.test(n.secret))throw new TypeError("secret is the webhook endpoint secret (whsec_\u2026), not an API key");await F(n);let e;try{e=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(z(n.body)))}catch{throw new f("invalid_body","the signed body is not JSON")}if(!be(e))throw new f("invalid_body","the signed body is not a Palbase event (id, type, project_id, created_at, data)");return e}async function F(n){if(typeof n.secret!="string"||n.secret==="")throw new TypeError("secret is the key the request was signed with");let e=z(n.body),{t,v1:r}=H(n),s=await crypto.subtle.importKey("raw",new TextEncoder().encode(n.secret),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),o=new Uint8Array(await crypto.subtle.sign("HMAC",s,we(new TextEncoder().encode(`${t}.`),e))),a=!1;for(let u of r)me(o,ge(u))&&(a=!0);if(!a)throw new f("signature_mismatch","no v1 in Palbase-Signature is this body signed with this secret")}function H(n){let e=n.toleranceSeconds??ue;if(!Number.isFinite(e)||e<0)throw new TypeError(`toleranceSeconds is a number of seconds, 0 or more (got ${String(n.toleranceSeconds)})`);let t=(n.now??Date.now)();if(!Number.isFinite(t))throw new TypeError(`now() returns epoch milliseconds (got ${String(t)})`);let r=n.signature;if(typeof r!="string"||r.trim()==="")throw new f("missing_signature","the request carries no Palbase-Signature header");let s,o=[];for(let a of r.split(",")){let u=a.indexOf("=");if(u<=0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");let c=a.slice(0,u).trim(),i=a.slice(u+1).trim();if(c==="t"){if(s!==void 0||!de.test(i))throw new f("malformed_signature","Palbase-Signature carries one t, in unix seconds");s=i}else if(c==="v1"){if(!le.test(i))throw new f("malformed_signature","a v1 is 64 lowercase hex characters");if(o.length===W)throw new f("malformed_signature",`Palbase-Signature carries at most ${W} v1`);o.push(i)}}if(s===void 0||o.length===0)throw new f("malformed_signature","Palbase-Signature is t=<seconds>,v1=<hex>");if(Math.abs(t/1e3-Number(s))>e)throw new f("stale_timestamp",`the signature's time is more than ${e} s from now: an old delivery sent again is not taken`);return{t:s,v1:o}}async function pe(n,e,t={}){let r=await ye(n,t.maxBytes??he);return B({toleranceSeconds:t.toleranceSeconds,now:t.now,secret:e,signature:n.headers.get("palbase-signature"),body:r})}async function ye(n,e){let t=()=>new f("body_too_large",`the body is larger than ${e} bytes`),r=Number(n.headers.get("content-length")??"NaN");if(Number.isFinite(r)&&r>e)throw t();if(!n.body)return new Uint8Array(0);let s=n.body.getReader(),o=[],a=0;for(;;){let{done:i,value:l}=await s.read();if(i)break;if(a+=l.byteLength,a>e)throw await s.cancel().catch(()=>{}),t();o.push(l)}let u=new Uint8Array(a),c=0;for(let i of o)u.set(i,c),c+=i.byteLength;return u}function z(n){if(typeof n=="string")return new TextEncoder().encode(n);if(n instanceof Uint8Array)return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);throw new TypeError("body is the raw request body (string or bytes): a parsed object is not what was signed \u2014 read the body before any JSON middleware")}function ge(n){let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function me(n,e){if(n.byteLength!==e.byteLength)return!1;let t=0;for(let r=0;r<n.byteLength;r++)t|=n[r]^e[r];return t===0}function we(n,e){let t=new Uint8Array(n.byteLength+e.byteLength);return t.set(n,0),t.set(e,n.byteLength),t}function be(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.id=="string"&&typeof e.type=="string"&&typeof e.project_id=="string"&&typeof e.created_at=="string"&&"data"in e}var V=60,ke=60,Se=8*1024,ve=1e5;function _(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Y(n){let e=n.replace(/[\s=]+/g,"");if(!/^[A-Za-z0-9+/_-]*$/.test(e)||e.length%4===1)return;let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}function J(n){let e=Y(n);if(e)try{let t=JSON.parse(new TextDecoder().decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}var k=class{byKey=new Map;held=0;sweptAt=Number.NEGATIVE_INFINITY;max;constructor(e=ve){this.max=e}spend(e,t){if(t>=e.until)throw new d("proof","the DPoP proof is not taken: it was checked too long ago");let r=this.byKey.get(e.jkt);if(r){this.forgetOld(e.jkt,r,t);let s=r.get(e.jti);if(s!==void 0&&s>t)throw new d("proof","the DPoP proof is not taken: it was used before");s!==void 0&&r.delete(e.jti)&&this.held--}this.held>=this.max&&this.makeRoom(t),r=this.byKey.get(e.jkt),r||(r=new Map,this.byKey.set(e.jkt,r)),r.set(e.jti,e.until),this.held++}forgetOld(e,t,r){for(let[s,o]of t){if(o>r)break;t.delete(s),this.held--}t.size===0&&this.byKey.delete(e)}makeRoom(e){if(e-this.sweptAt>=1e3){this.sweptAt=e;for(let[r,s]of this.byKey){for(let[o,a]of s)a>e||(s.delete(o),this.held--);s.size===0&&this.byKey.delete(r)}this.held=0;for(let r of this.byKey.values())this.held+=r.size}if(this.held<this.max)return;let t=[...this.byKey].sort((r,s)=>s[1].size-r[1].size);for(let[r,s]of t){if(this.held<=this.max*.9)break;this.byKey.delete(r),this.held-=s.size}}};async function Ee(n,e){let t=`{"crv":"P-256","kty":"EC","x":"${n}","y":"${e}"}`;return _(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))}function q(n){try{let e=new URL(n);return e.username!==""||e.password!==""?void 0:`${e.protocol}//${e.host}${e.pathname}`}catch{return}}async function G(n,e,t,r){let s=ie=>{throw new d("proof",`the DPoP proof is not taken: ${ie}`)},o=t.proof;if(!o)return s("there is none (a DPoP-bound token comes with a DPoP header)");if(o.length>Se)return s("it is too long");let a=o.split(".");if(a.length!==3)return s("it is not a JWS of three parts");let u=J(a[0]),c=J(a[1]);if(!u||!c)return s("its header or claims are not base64url JSON");if(u.typ!=="dpop+jwt")return s("its typ is not dpop+jwt");if(u.alg!=="ES256")return s(`it is signed with ${String(u.alg)}; only ES256 is taken`);let i=u.jwk;if(!i||typeof i!="object"||i.kty!=="EC"||i.crv!=="P-256"||typeof i.x!="string"||typeof i.y!="string")return s("its header carries no P-256 public key");if("d"in i)return s("its header carries a private key");if(await Ee(i.x,i.y)!==e)return s("it is signed by a key the token does not name");let l;try{l=await crypto.subtle.importKey("jwk",{kty:"EC",crv:"P-256",x:i.x,y:i.y,ext:!0},{name:"ECDSA",namedCurve:"P-256"},!1,["verify"])}catch{return s("its key is not a P-256 point")}let p=Y(a[2]);if(!p||!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},l,p,new TextEncoder().encode(`${a[0]}.${a[1]}`)).catch(()=>!1))return s("its signature does not verify");if(typeof c.htm!="string"||c.htm.toUpperCase()!==t.method.toUpperCase())return s(`it is for ${String(c.htm)}, not ${t.method}`);let h=typeof c.htu=="string"?q(c.htu):void 0,y=q(t.url);if(!h||!y||h!==y)return s(`it is for ${String(c.htu)}, not ${y??t.url}`);let re=r/1e3;if(typeof c.iat!="number"||Math.abs(c.iat-re)>V)return s("it was not made within a minute of now");let se=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n)));if(c.ath!==se)return s("it is not for this token (ath)");if(typeof c.jti!="string"||c.jti===""||c.jti.length>256)return s("it has no jti (or one longer than 256)");let oe=_(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c.jti)));return{jkt:e,jti:oe,until:(c.iat+V+ke)*1e3+1}}var d=class extends Error{reason;constructor(e,t){super(t),this.name="TokenError",this.reason=e}},g=class extends Error{constructor(e,t){super(e,t),this.name="AuthUnavailable"}};function _e(n){return async e=>{let t=b.client(w({baseUrl:n.url,credentials:{secretKey:n.secretKey,accessToken:()=>e},fetch:n.fetch}));try{return await t.verifyTokenUser(),!0}catch(r){if(r instanceof v&&r.status===401)return!1;throw r}}}var T={ES256:{kty:"EC",import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}},PS256:{kty:"RSA",import:{name:"RSA-PSS",hash:"SHA-256"},verify:{name:"RSA-PSS",saltLength:32}}},X=60,Te=16*1024,Ae=10*6e4,Pe=5e4,Z=n=>typeof n=="string"&&Object.hasOwn(T,n),A=class{issuer;projectId;fetchImpl;now;maxKeyAgeMs;refetchIntervalMs;fetchTimeoutMs;standing;standingTtlMs;standingStaleMs;standings=new Map;asking=new Map;keys=new Map;keysUntil=0;lastFetch=Number.NEGATIVE_INFINITY;lastFailure=void 0;inflight=null;seenProofs=new k;constructor(e){let t=new URL(e.issuer);if(t.origin!==e.issuer.replace(/\/$/,""))throw new TypeError(`issuer is the project's origin (https://<ref>.<domain>), not ${e.issuer}`);if(typeof e.projectId!="string"||e.projectId==="")throw new TypeError("projectId is the project id the tokens carry");if(this.issuer=t.origin,this.projectId=e.projectId,this.fetchImpl=e.fetch??globalThis.fetch,this.now=e.now??Date.now,this.maxKeyAgeMs=e.maxKeyAgeMs??60*6e4,this.refetchIntervalMs=e.refetchIntervalMs??3e4,this.fetchTimeoutMs=e.fetchTimeoutMs??5e3,typeof e.standing!="function")throw new TypeError("standing is how the verifier asks whether a token's session stands");this.standing=e.standing,this.standingTtlMs=e.standingTtlMs??1e3,this.standingStaleMs=e.standingStaleMs??15e3}async verify(e,t){if(typeof e!="string"||e.length===0||e.length>Te)throw new d("malformed","the token is not a JWT");let r=e.split(".");if(r.length!==3)throw new d("malformed","the token is not a JWS of three parts");let s=Q(r[0]),o=Q(r[1]);if(!s||!o)throw new d("malformed","the token header or claims are not base64url JSON");let a=s.alg;if(!Z(a))throw new d("algorithm",`the token is signed with ${String(a)}; only ES256 and PS256 are taken`);let u=s.kid;if(typeof u!="string"||u==="")throw new d("malformed","the token header names no kid");let c=await this.key(u);if(!c)throw new d("unknown_key",`no key ${u} in the project's key set`);if(c.alg!==a)throw new d("algorithm",`key ${u} is ${c.alg}, the token says ${a}`);let i=te(r[2]);if(!i)throw new d("malformed","the signature is not base64url");let l=new TextEncoder().encode(`${r[0]}.${r[1]}`);if(!await crypto.subtle.verify(T[c.alg].verify,c.key,i,l).catch(()=>!1))throw new d("signature","the signature does not verify");let m=this.check(o),h=o.cnf,y;if(h!==void 0){if(!t)throw new d("bound","the token is bound to a key (DPoP): it comes with the DPoP scheme and a proof, not as a Bearer");if(typeof h!="object"||h===null||typeof h.jkt!="string"||h.jkt==="")throw new d("bound","the token is bound to a key it does not name (cnf.jkt)");y=await G(e,h.jkt,t,this.now())}else if(t)throw new d("not_bound","the DPoP scheme came with a token bound to no key");if(!await this.stands(e,m.sessionId))throw new d("session_ended","the token's session has ended (signed out, revoked, or its user banned)");return y&&this.seenProofs.spend(y,this.now()),m}async verifyRequest(e){let t=e.headers instanceof Headers?e.headers:xe(e.headers),r=t.get("authorization")??"";if(r==="")return null;let s=/^(bearer|dpop)\s+(\S+)$/i.exec(r);if(!s)throw new d("malformed","the Authorization header is not a Bearer or DPoP token");let o=s[1].toLowerCase()==="dpop",a=new URL(e.url,`http://${t.get("host")??"localhost"}`);return this.verify(s[2],o?{proof:t.get("dpop"),method:e.method,url:ee(t,a)}:void 0)}async stands(e,t){let r=this.now(),s=this.standings.get(t);if(s&&r<s.until)return s.live;let o=this.asking.get(t);o||(o=this.standing(e,t).finally(()=>this.asking.delete(t)),this.asking.set(t,o));let a;try{a=await o}catch(c){let i=this.standings.get(t),l=this.now();if(i&&l<i.at+this.standingStaleMs)return i.until=Math.min(l+this.standingTtlMs,i.at+this.standingStaleMs),i.live;throw new g("a session's standing cannot be read now",{cause:c})}let u=this.now();return this.standings.delete(t),this.standings.set(t,{live:a,at:u,until:u+this.standingTtlMs}),this.standings.size>Pe&&this.standings.delete(this.standings.keys().next().value),a}check(e){if(e.iss!==this.issuer)throw new d("issuer",`the token was issued by ${String(e.iss)}, not this project`);if(!(Array.isArray(e.aud)?e.aud:[e.aud]).includes(this.issuer))throw new d("audience","the token is not meant for this project");if(e.project_id!==this.projectId)throw new d("project","the token names another project");let r=this.now()/1e3;if(typeof e.exp!="number"||e.exp+X<=r)throw new d("expired","the token has expired");if(e.nbf!==void 0&&(typeof e.nbf!="number"||e.nbf-X>r))throw new d("not_yet_valid","the token is not valid yet");if(typeof e.sub!="string"||e.sub===""||typeof e.auth_time!="number")throw new d("not_a_user","the token is not a user's");if(typeof e.session_id!="string"||e.session_id==="")throw new d("not_a_session","the token is no session's");let s=e.custom_claims;if(s!==void 0&&(typeof s!="object"||s===null||s.type!==void 0))throw new d("not_a_session","the token is a custom one (an exchange or an approval), not a session's");return{id:e.sub,email:typeof e.email=="string"?e.email:null,emailVerified:e.email_verified===!0,role:typeof e.role=="string"?e.role:null,sessionId:typeof e.session_id=="string"?e.session_id:null,claims:Object.freeze({...e})}}async key(e){let t=this.now();if(t>=this.keysUntil){let s=this.keys.size>0&&t<this.keysUntil+Ae;if(this.lastFailure!==void 0&&t-this.lastFetch<this.refetchIntervalMs){if(!s)throw new g("the project's key set cannot be read now",{cause:this.lastFailure})}else try{await this.refresh()}catch(o){if(!s)throw o}}let r=this.keys.get(e);return!r&&t-this.lastFetch>=this.refetchIntervalMs&&(await this.refresh(),r=this.keys.get(e)),r}refresh(){if(this.inflight)return this.inflight;let e=this.load().finally(()=>{this.inflight=null});return this.inflight=e,e}async load(){this.lastFetch=this.now();let e,t;try{if(t=await this.fetchImpl(`${this.issuer}/.well-known/jwks.json`,{redirect:"error",headers:{accept:"application/json"},signal:AbortSignal.timeout(this.fetchTimeoutMs)}),!t.ok)throw new Error(`the project's key set answered ${t.status}`);e=await t.json()}catch(o){throw this.lastFailure=o,new g("the project's key set cannot be read now",{cause:o})}this.lastFailure=void 0;let r=new Map;for(let o of Array.isArray(e.keys)?e.keys:[]){let a=o.alg;if(typeof o.kid!="string"||!Z(a))continue;let u=T[a];if(o.kty!==u.kty||o.use!==void 0&&o.use!=="sig")continue;let{d:c,...i}=o;try{r.set(o.kid,{alg:a,key:await crypto.subtle.importKey("jwk",i,u.import,!1,["verify"])})}catch{}}this.keys=r;let s=Oe(t.headers.get("cache-control"))??this.maxKeyAgeMs;this.keysUntil=this.now()+Math.min(Math.max(s,this.refetchIntervalMs),this.maxKeyAgeMs)}};function ee(n,e){let t=n.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase(),r=t==="https"||t==="http"?t:e.protocol.slice(0,-1),s=n.get("host")??e.host;return Re.test(s)?`${r}://${s}${e.pathname}`:""}var Re=/^(?:[a-z0-9-]+(?:\.[a-z0-9-]+)*|\[[0-9a-f:.]+\])(?::[0-9]{1,5})?$/i;function xe(n){let e=new Headers;for(let[t,r]of Object.entries(n))if(r!==void 0)for(let s of Array.isArray(r)?r:[r])e.append(t,s);return e}function Oe(n){let e=/(?:^|,)\s*max-age=(\d+)/i.exec(n??"");return e?Number(e[1])*1e3:void 0}function te(n){if(!/^[A-Za-z0-9_-]*$/.test(n)||n.length%4===1)return null;let e=atob(n.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(n.length/4)*4,"=")),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Q(n){let e=te(n);if(!e)return null;try{let t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function je(n,e,t=Date.now()){let r=Object.hasOwn(n.entitlements,e)?n.entitlements[e]:void 0;return r?.active?r.expires_at===null?!0:Date.parse(r.expires_at)>(typeof t=="number"?t:t.getTime()):!1}var S=class extends Error{receipt;constructor(e){super(`the reservation ${JSON.stringify(e.idempotency_key)} is ${e.status} already: its job is not run again (a new one is a new Idempotency-Key)`),this.name="ReservationSettled",this.receipt=e}};async function Me(n,e,t,r){let{idempotencyKey:s,amount:o,ttlSeconds:a,metadata:u}=t;if(typeof s!="string"||s==="")throw new TypeError("idempotencyKey names the reservation for good: a retry with it is the same hold, never a second");let c={amount:o,...t.credits!==void 0?{credits:t.credits}:{limit:t.limit},...a!==void 0?{ttl_seconds:a}:{},...u!==void 0?{metadata:u}:{}},i=(await n.purchases.holdSpend({path:{customer_id:e},headers:{"Idempotency-Key":s},body:c})).data;if(i.status!=="held")throw new S(i);let l={customer_id:i.customer,spend_id:i.id},p;try{p=await r(i)}catch(m){throw await n.purchases.releaseSpend({path:l}).catch(()=>{}),m}return await n.purchases.commitSpend({path:l}),p}async function*Ce(n){let e,t=new Set;do{let r=(await n(e)).data;yield r;let s=r.next_cursor??void 0;if(s!==void 0&&t.has(s))throw new Error(`the listing answered a cursor it had answered before (${s})`);s!==void 0&&t.add(s),e=s}while(e)}var Ue=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/,Le=/^(PALBASE_|NODE_|BUN_|NPM_|LD_|DYLD_|GIT_|SSH_)|^(PATH|HOME|SHELL|USER|TMPDIR|TMP|TEMP|PWD|IFS|ENV|BASH_ENV|SSL_CERT_FILE|SSL_CERT_DIR|CURL_CA_BUNDLE|REQUESTS_CA_BUNDLE|NO_PROXY|ALL_PROXY|HTTP_PROXY|HTTPS_PROXY|PG\w*)$/i;function ne(n){return!Ue.test(n)||Le.test(n)||/_PROXY$/i.test(n)}var Ke=/^(PORT|PALBASE_(URL|PROJECT_ID|MACHINE|REPLICAS|SECRET_KEY|WEBHOOK_SECRET|PLATFORM_SECRET|CONTRACT_OUT|SECRETS|DB_[A-Z0-9_]+))$/;function Ne(n){return Ke.test(n)}async function $e(n={}){let e=n.env??process.env,t=e.PALBASE_SECRETS;if(t===void 0||t==="")return;if(t!=="development"&&t!=="production")throw new TypeError(`PALBASE_SECRETS is development or production, not ${t}`);let r=n.url??e.PALBASE_URL??"",s=n.secretKey??e.PALBASE_SECRET_KEY??"";if(r===""||s==="")throw new TypeError("PALBASE_SECRETS reads the project's Secrets with PALBASE_URL and PALBASE_SECRET_KEY: give both (palbase env:pull writes them)");let o=E({url:new URL(r).origin,secretKey:s,fetch:n.fetch}),{data:a}=await o.secrets.getEnvironmentValues({path:{environment:t}}),u=[],c=[],i=[];for(let[l,p]of Object.entries(a.values)){if(ne(l)){i.push(l);continue}if(e[l]!==void 0&&e[l]!==""){c.push(l);continue}e[l]=p,u.push(l)}return{set:t,loaded:u.sort(),kept:c.sort(),refused:i.sort()}}export{E as a,f as b,B as c,F as d,H as e,pe as f,d as g,g as h,_e as i,A as j,ee as k,je as l,S as m,Me as n,Ce as o,ne as p,Ne as q,$e as r};